| 1 | // Package gitrepo legt bare repositories op schijf en praat met de git-binary. |
| 2 | package gitrepo |
| 3 | |
| 4 | import ( |
| 5 | "bufio" |
| 6 | "bytes" |
| 7 | "context" |
| 8 | "fmt" |
| 9 | "io" |
| 10 | "os" |
| 11 | "os/exec" |
| 12 | "path/filepath" |
| 13 | "strings" |
| 14 | |
| 15 | "gitlab.com/Timfa/bluegit/internal/access" |
| 16 | ) |
| 17 | |
| 18 | // Dir is de bare repository op de datadisk. |
| 19 | func Dir(storage, owner, name string) string { |
| 20 | return filepath.Join(storage, "repos", owner, name+".git") |
| 21 | } |
| 22 | |
| 23 | // Init maakt een lege bare repository en zet de pre-receive-hook. |
| 24 | func Init(gitBin, dir, defaultBranch, hookBinary string) error { |
| 25 | if err := os.MkdirAll(filepath.Dir(dir), 0o755); err != nil { |
| 26 | return err |
| 27 | } |
| 28 | if _, err := run(context.Background(), gitBin, nil, "init", "--bare", "--initial-branch", defaultBranch, dir); err != nil { |
| 29 | return err |
| 30 | } |
| 31 | for _, kv := range [][2]string{ |
| 32 | {"http.receivepack", "true"}, |
| 33 | {"http.uploadpack", "true"}, |
| 34 | {"receive.denyCurrentBranch", "ignore"}, |
| 35 | } { |
| 36 | if _, err := run(context.Background(), gitBin, nil, "-C", dir, "config", kv[0], kv[1]); err != nil { |
| 37 | return err |
| 38 | } |
| 39 | } |
| 40 | return InstallHook(dir, hookBinary) |
| 41 | } |
| 42 | |
| 43 | // InstallHook schrijft hooks/pre-receive. Die roept deze binary aan. |
| 44 | func InstallHook(dir, hookBinary string) error { |
| 45 | if hookBinary == "" { |
| 46 | return fmt.Errorf("hook-binary ontbreekt") |
| 47 | } |
| 48 | path := filepath.Join(dir, "hooks", "pre-receive") |
| 49 | body := "#!/bin/sh\nset -eu\nexec " + shellQuote(hookBinary) + " hook pre-receive\n" |
| 50 | if err := os.WriteFile(path, []byte(body), 0o755); err != nil { |
| 51 | return err |
| 52 | } |
| 53 | return nil |
| 54 | } |
| 55 | |
| 56 | func shellQuote(s string) string { |
| 57 | return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" |
| 58 | } |
| 59 | |
| 60 | // PushEnv zijn de variabelen die de hook leest. Zonder deze variabelen |
| 61 | // weigert de hook, zodat een push buiten BlueGit om niet slaagt. |
| 62 | func PushEnv(role access.Role, patterns []string) []string { |
| 63 | return []string{ |
| 64 | "BLUEGIT_ROLE=" + string(role), |
| 65 | "BLUEGIT_PROTECTED=" + strings.Join(patterns, "\n"), |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | // ReadUpdates leest de regels van een pre-receive-hook. |
| 70 | func ReadUpdates(r io.Reader) ([]access.RefUpdate, error) { |
| 71 | sc := bufio.NewScanner(r) |
| 72 | var out []access.RefUpdate |
| 73 | for sc.Scan() { |
| 74 | line := strings.TrimSpace(sc.Text()) |
| 75 | if line == "" { |
| 76 | continue |
| 77 | } |
| 78 | parts := strings.Fields(line) |
| 79 | if len(parts) != 3 { |
| 80 | return nil, fmt.Errorf("onverwachte hookregel %q", line) |
| 81 | } |
| 82 | out = append(out, access.RefUpdate{Old: parts[0], New: parts[1], Ref: parts[2]}) |
| 83 | } |
| 84 | return out, sc.Err() |
| 85 | } |
| 86 | |
| 87 | // EvaluatePush is wat `bluegit hook pre-receive` doet. |
| 88 | func EvaluatePush(role access.Role, patterns []string, r io.Reader) error { |
| 89 | if role == "" { |
| 90 | return fmt.Errorf("push geweigerd: geen BlueGit-rol") |
| 91 | } |
| 92 | ups, err := ReadUpdates(r) |
| 93 | if err != nil { |
| 94 | return err |
| 95 | } |
| 96 | return access.AuthorizeUpdates(role, patterns, ups) |
| 97 | } |
| 98 | |
| 99 | // Commit is één commit voor de webinterface. |
| 100 | type Commit struct { |
| 101 | SHA string |
| 102 | Short string |
| 103 | Author string |
| 104 | Date string |
| 105 | Subject string |
| 106 | Body string |
| 107 | } |
| 108 | |
| 109 | // Entry is een bestand of map in een tree. |
| 110 | type Entry struct { |
| 111 | Mode string |
| 112 | Type string |
| 113 | SHA string |
| 114 | Name string |
| 115 | } |
| 116 | |
| 117 | // Log geeft de nieuwste commits. |
| 118 | func Log(ctx context.Context, gitBin, dir, rev string, limit int) ([]Commit, error) { |
| 119 | if rev == "" { |
| 120 | rev = "HEAD" |
| 121 | } |
| 122 | out, err := run(ctx, gitBin, nil, "-C", dir, "log", "--format=%H%x1f%an%x1f%ad%x1f%s%x1f%b%x1e", "--date=short", fmt.Sprintf("-n%d", limit), rev) |
| 123 | if err != nil { |
| 124 | if strings.Contains(err.Error(), "does not have any commits") || strings.Contains(err.Error(), "bad default revision") || strings.Contains(err.Error(), "ambiguous argument") { |
| 125 | return nil, nil |
| 126 | } |
| 127 | return nil, err |
| 128 | } |
| 129 | return parseLog(out), nil |
| 130 | } |
| 131 | |
| 132 | func parseLog(out string) []Commit { |
| 133 | var commits []Commit |
| 134 | for _, rec := range strings.Split(out, "\x1e") { |
| 135 | rec = strings.TrimSpace(rec) |
| 136 | if rec == "" { |
| 137 | continue |
| 138 | } |
| 139 | parts := strings.Split(rec, "\x1f") |
| 140 | if len(parts) < 4 { |
| 141 | continue |
| 142 | } |
| 143 | c := Commit{SHA: parts[0], Author: parts[1], Date: parts[2], Subject: parts[3]} |
| 144 | if len(c.SHA) >= 10 { |
| 145 | c.Short = c.SHA[:10] |
| 146 | } |
| 147 | if len(parts) > 4 { |
| 148 | c.Body = strings.TrimSpace(parts[4]) |
| 149 | } |
| 150 | commits = append(commits, c) |
| 151 | } |
| 152 | return commits |
| 153 | } |
| 154 | |
| 155 | // Show leest één commit. |
| 156 | func Show(ctx context.Context, gitBin, dir, sha string) (Commit, error) { |
| 157 | list, err := Log(ctx, gitBin, dir, sha, 1) |
| 158 | if err != nil { |
| 159 | return Commit{}, err |
| 160 | } |
| 161 | if len(list) == 0 { |
| 162 | return Commit{}, fmt.Errorf("commit niet gevonden") |
| 163 | } |
| 164 | return list[0], nil |
| 165 | } |
| 166 | |
| 167 | // Tree leest een map. path is relatief en mag leeg zijn. |
| 168 | func Tree(ctx context.Context, gitBin, dir, rev, rel string) ([]Entry, error) { |
| 169 | spec := rev |
| 170 | if rel != "" { |
| 171 | spec = rev + ":" + rel |
| 172 | } |
| 173 | out, err := run(ctx, gitBin, nil, "-C", dir, "ls-tree", spec) |
| 174 | if err != nil { |
| 175 | return nil, err |
| 176 | } |
| 177 | var entries []Entry |
| 178 | for _, line := range strings.Split(strings.TrimSpace(out), "\n") { |
| 179 | if line == "" { |
| 180 | continue |
| 181 | } |
| 182 | // mode type sha\tname |
| 183 | tab := strings.SplitN(line, "\t", 2) |
| 184 | if len(tab) != 2 { |
| 185 | continue |
| 186 | } |
| 187 | head := strings.Fields(tab[0]) |
| 188 | if len(head) != 3 { |
| 189 | continue |
| 190 | } |
| 191 | entries = append(entries, Entry{Mode: head[0], Type: head[1], SHA: head[2], Name: tab[1]}) |
| 192 | } |
| 193 | return entries, nil |
| 194 | } |
| 195 | |
| 196 | // Blob leest een tekstbestand, afgekapt op max bytes. binary is waar als |
| 197 | // het bestand een NUL bevat. |
| 198 | func Blob(ctx context.Context, gitBin, dir, rev, rel string, max int) (text string, binary bool, err error) { |
| 199 | out, err := run(ctx, gitBin, nil, "-C", dir, "show", rev+":"+rel) |
| 200 | if err != nil { |
| 201 | return "", false, err |
| 202 | } |
| 203 | if strings.Contains(out, "\x00") { |
| 204 | return "", true, nil |
| 205 | } |
| 206 | if len(out) > max { |
| 207 | out = out[:max] + "\n… afgekapt" |
| 208 | } |
| 209 | return out, false, nil |
| 210 | } |
| 211 | |
| 212 | // Branches geeft lokale branchnamen. |
| 213 | func Branches(ctx context.Context, gitBin, dir string) ([]string, error) { |
| 214 | out, err := run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--format=%(refname:short)", "refs/heads") |
| 215 | if err != nil { |
| 216 | return nil, err |
| 217 | } |
| 218 | var names []string |
| 219 | for _, line := range strings.Split(strings.TrimSpace(out), "\n") { |
| 220 | if line != "" { |
| 221 | names = append(names, line) |
| 222 | } |
| 223 | } |
| 224 | return names, nil |
| 225 | } |
| 226 | |
| 227 | // HasCommit meldt of sha een commit in deze repository is. |
| 228 | func HasCommit(ctx context.Context, gitBin, dir, sha string) bool { |
| 229 | out, err := run(ctx, gitBin, nil, "-C", dir, "cat-file", "-t", sha) |
| 230 | return err == nil && strings.TrimSpace(out) == "commit" |
| 231 | } |
| 232 | |
| 233 | // Refs geeft refnaam → sha. |
| 234 | func Refs(ctx context.Context, gitBin, dir string) (map[string]string, error) { |
| 235 | out, err := run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--format=%(objectname) %(refname)") |
| 236 | if err != nil { |
| 237 | return nil, err |
| 238 | } |
| 239 | m := map[string]string{} |
| 240 | for _, line := range strings.Split(strings.TrimSpace(out), "\n") { |
| 241 | if line == "" { |
| 242 | continue |
| 243 | } |
| 244 | parts := strings.SplitN(line, " ", 2) |
| 245 | if len(parts) == 2 { |
| 246 | m[parts[1]] = parts[0] |
| 247 | } |
| 248 | } |
| 249 | return m, nil |
| 250 | } |
| 251 | |
| 252 | // BranchOfRef haalt de branch uit refs/heads/… . |
| 253 | func BranchOfRef(ref string) (string, bool) { |
| 254 | const p = "refs/heads/" |
| 255 | if strings.HasPrefix(ref, p) && len(ref) > len(p) { |
| 256 | return ref[len(p):], true |
| 257 | } |
| 258 | return "", false |
| 259 | } |
| 260 | |
| 261 | // Merge voegt source samen in target en pusht het resultaat. |
| 262 | // De push gaat door de hook, dus role en patterns moeten kloppen. |
| 263 | func Merge(ctx context.Context, gitBin, bare, work, source, target, author, email, message string, role access.Role, patterns []string) error { |
| 264 | if err := os.RemoveAll(work); err != nil { |
| 265 | return err |
| 266 | } |
| 267 | if err := os.MkdirAll(filepath.Dir(work), 0o755); err != nil { |
| 268 | return err |
| 269 | } |
| 270 | if _, err := run(ctx, gitBin, nil, "clone", bare, work); err != nil { |
| 271 | return err |
| 272 | } |
| 273 | env := append(os.Environ(), |
| 274 | "GIT_AUTHOR_NAME="+author, |
| 275 | "GIT_AUTHOR_EMAIL="+email, |
| 276 | "GIT_COMMITTER_NAME="+author, |
| 277 | "GIT_COMMITTER_EMAIL="+email, |
| 278 | ) |
| 279 | if _, err := run(ctx, gitBin, env, "-C", work, "checkout", target); err != nil { |
| 280 | return fmt.Errorf("doelbranch %s: %w", target, err) |
| 281 | } |
| 282 | if _, err := run(ctx, gitBin, env, "-C", work, "merge", "--no-ff", "--no-edit", "-m", message, source); err != nil { |
| 283 | return fmt.Errorf("samenvoegen lukt niet, er is een conflict of de branch ontbreekt") |
| 284 | } |
| 285 | pushEnv := append(env, PushEnv(role, patterns)...) |
| 286 | if _, err := run(ctx, gitBin, pushEnv, "-C", work, "push", "origin", target); err != nil { |
| 287 | return err |
| 288 | } |
| 289 | return nil |
| 290 | } |
| 291 | |
| 292 | // Tag zet een annotated tag op sha. |
| 293 | func Tag(ctx context.Context, gitBin, dir, tag, sha, message string) error { |
| 294 | _, err := run(ctx, gitBin, nil, "-C", dir, "tag", "-a", tag, sha, "-m", message) |
| 295 | return err |
| 296 | } |
| 297 | |
| 298 | // DiffStat is een korte vergelijking tussen twee branches. |
| 299 | func DiffStat(ctx context.Context, gitBin, dir, target, source string) (string, error) { |
| 300 | out, err := run(ctx, gitBin, nil, "-C", dir, "log", "--oneline", target+".."+source) |
| 301 | if err != nil { |
| 302 | return "", err |
| 303 | } |
| 304 | return strings.TrimSpace(out), nil |
| 305 | } |
| 306 | |
| 307 | func run(ctx context.Context, bin string, env []string, args ...string) (string, error) { |
| 308 | if bin == "" { |
| 309 | bin = "git" |
| 310 | } |
| 311 | cmd := exec.CommandContext(ctx, bin, args...) |
| 312 | if env != nil { |
| 313 | cmd.Env = env |
| 314 | } |
| 315 | var stdout, stderr bytes.Buffer |
| 316 | cmd.Stdout = &stdout |
| 317 | cmd.Stderr = &stderr |
| 318 | if err := cmd.Run(); err != nil { |
| 319 | msg := strings.TrimSpace(stderr.String()) |
| 320 | if msg == "" { |
| 321 | msg = err.Error() |
| 322 | } |
| 323 | return "", fmt.Errorf("%s", msg) |
| 324 | } |
| 325 | return stdout.String(), nil |
| 326 | } |