| 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 | "sort" |
| 14 | "strconv" |
| 15 | "strings" |
| 16 | |
| 17 | "gitlab.com/Timfa/bluegit/internal/access" |
| 18 | "gitlab.com/Timfa/bluegit/internal/i18n" |
| 19 | "gitlab.com/Timfa/bluegit/internal/names" |
| 20 | ) |
| 21 | |
| 22 | // Dir is de bare repository op de datadisk. |
| 23 | func Dir(storage, owner, name string) string { |
| 24 | return filepath.Join(storage, "repos", owner, name+".git") |
| 25 | } |
| 26 | |
| 27 | // Init maakt een lege bare repository en zet de pre-receive-hook. |
| 28 | func Init(gitBin, dir, defaultBranch, hookBinary string) error { |
| 29 | if err := os.MkdirAll(filepath.Dir(dir), 0o755); err != nil { |
| 30 | return err |
| 31 | } |
| 32 | if _, err := run(context.Background(), gitBin, nil, "init", "--bare", "--initial-branch", defaultBranch, dir); err != nil { |
| 33 | return err |
| 34 | } |
| 35 | for _, kv := range [][2]string{ |
| 36 | {"http.receivepack", "true"}, |
| 37 | {"http.uploadpack", "true"}, |
| 38 | {"receive.denyCurrentBranch", "ignore"}, |
| 39 | } { |
| 40 | if _, err := run(context.Background(), gitBin, nil, "-C", dir, "config", kv[0], kv[1]); err != nil { |
| 41 | return err |
| 42 | } |
| 43 | } |
| 44 | return InstallHook(dir, hookBinary) |
| 45 | } |
| 46 | |
| 47 | // InstallHook schrijft hooks/pre-receive. Die roept deze binary aan. |
| 48 | func InstallHook(dir, hookBinary string) error { |
| 49 | if hookBinary == "" { |
| 50 | return fmt.Errorf("hook-binary ontbreekt") |
| 51 | } |
| 52 | path := filepath.Join(dir, "hooks", "pre-receive") |
| 53 | body := "#!/bin/sh\nset -eu\nexec " + shellQuote(hookBinary) + " hook pre-receive\n" |
| 54 | if err := os.WriteFile(path, []byte(body), 0o755); err != nil { |
| 55 | return err |
| 56 | } |
| 57 | return nil |
| 58 | } |
| 59 | |
| 60 | func shellQuote(s string) string { |
| 61 | return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" |
| 62 | } |
| 63 | |
| 64 | // PushEnv zijn de variabelen die de hook leest. Zonder deze variabelen |
| 65 | // weigert de hook, zodat een push buiten BlueGit om niet slaagt. |
| 66 | func PushEnv(role access.Role, patterns, tagPatterns []string) []string { |
| 67 | return []string{ |
| 68 | "BLUEGIT_ROLE=" + string(role), |
| 69 | "BLUEGIT_PROTECTED=" + strings.Join(patterns, "\n"), |
| 70 | "BLUEGIT_PROTECTED_TAGS=" + strings.Join(tagPatterns, "\n"), |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | // ReadUpdates leest de regels van een pre-receive-hook. |
| 75 | func ReadUpdates(r io.Reader) ([]access.RefUpdate, error) { |
| 76 | sc := bufio.NewScanner(r) |
| 77 | var out []access.RefUpdate |
| 78 | for sc.Scan() { |
| 79 | line := strings.TrimSpace(sc.Text()) |
| 80 | if line == "" { |
| 81 | continue |
| 82 | } |
| 83 | parts := strings.Fields(line) |
| 84 | if len(parts) != 3 { |
| 85 | return nil, fmt.Errorf("onverwachte hookregel %q", line) |
| 86 | } |
| 87 | out = append(out, access.RefUpdate{Old: parts[0], New: parts[1], Ref: parts[2]}) |
| 88 | } |
| 89 | return out, sc.Err() |
| 90 | } |
| 91 | |
| 92 | // EvaluatePush is wat `bluegit hook pre-receive` doet. |
| 93 | func EvaluatePush(role access.Role, patterns, tagPatterns []string, r io.Reader) error { |
| 94 | if role == "" { |
| 95 | return fmt.Errorf("push geweigerd: geen BlueGit-rol") |
| 96 | } |
| 97 | ups, err := ReadUpdates(r) |
| 98 | if err != nil { |
| 99 | return err |
| 100 | } |
| 101 | return access.AuthorizeUpdates(role, patterns, tagPatterns, ups) |
| 102 | } |
| 103 | |
| 104 | // Commit is één commit voor de webinterface. |
| 105 | type Commit struct { |
| 106 | SHA string |
| 107 | Short string |
| 108 | Author string |
| 109 | Email string |
| 110 | Date string |
| 111 | Unix int64 |
| 112 | Subject string |
| 113 | Body string |
| 114 | } |
| 115 | |
| 116 | // Entry is een bestand of map in een tree. |
| 117 | type Entry struct { |
| 118 | Mode string |
| 119 | Type string |
| 120 | SHA string |
| 121 | Name string |
| 122 | } |
| 123 | |
| 124 | // Log geeft de nieuwste commits. |
| 125 | func Log(ctx context.Context, gitBin, dir, rev string, limit int) ([]Commit, error) { |
| 126 | if rev == "" { |
| 127 | rev = "HEAD" |
| 128 | } |
| 129 | out, err := run(ctx, gitBin, nil, "-C", dir, "log", "--format=%H%x1f%an%x1f%ae%x1f%ad%x1f%at%x1f%s%x1f%b%x1e", "--date=short", fmt.Sprintf("-n%d", limit), rev) |
| 130 | if err != nil { |
| 131 | if strings.Contains(err.Error(), "does not have any commits") || strings.Contains(err.Error(), "bad default revision") || strings.Contains(err.Error(), "ambiguous argument") { |
| 132 | return nil, nil |
| 133 | } |
| 134 | return nil, err |
| 135 | } |
| 136 | return parseLog(out), nil |
| 137 | } |
| 138 | |
| 139 | func parseLog(out string) []Commit { |
| 140 | var commits []Commit |
| 141 | for _, rec := range strings.Split(out, "\x1e") { |
| 142 | rec = strings.TrimSpace(rec) |
| 143 | if rec == "" { |
| 144 | continue |
| 145 | } |
| 146 | parts := strings.Split(rec, "\x1f") |
| 147 | if len(parts) < 6 { |
| 148 | continue |
| 149 | } |
| 150 | c := Commit{SHA: parts[0], Author: parts[1], Email: parts[2], Date: parts[3], Subject: parts[5]} |
| 151 | c.Unix, _ = strconv.ParseInt(parts[4], 10, 64) |
| 152 | if len(c.SHA) >= 10 { |
| 153 | c.Short = c.SHA[:10] |
| 154 | } |
| 155 | if len(parts) > 6 { |
| 156 | c.Body = strings.TrimSpace(parts[6]) |
| 157 | } |
| 158 | commits = append(commits, c) |
| 159 | } |
| 160 | return commits |
| 161 | } |
| 162 | |
| 163 | // Show leest één commit. |
| 164 | func Show(ctx context.Context, gitBin, dir, sha string) (Commit, error) { |
| 165 | list, err := Log(ctx, gitBin, dir, sha, 1) |
| 166 | if err != nil { |
| 167 | return Commit{}, err |
| 168 | } |
| 169 | if len(list) == 0 { |
| 170 | return Commit{}, fmt.Errorf("commit niet gevonden") |
| 171 | } |
| 172 | return list[0], nil |
| 173 | } |
| 174 | |
| 175 | // Tree leest een map. path is relatief en mag leeg zijn. |
| 176 | func Tree(ctx context.Context, gitBin, dir, rev, rel string) ([]Entry, error) { |
| 177 | spec := rev |
| 178 | if rel != "" { |
| 179 | spec = rev + ":" + rel |
| 180 | } |
| 181 | out, err := run(ctx, gitBin, nil, "-C", dir, "ls-tree", spec) |
| 182 | if err != nil { |
| 183 | return nil, err |
| 184 | } |
| 185 | var entries []Entry |
| 186 | for _, line := range strings.Split(strings.TrimSpace(out), "\n") { |
| 187 | if line == "" { |
| 188 | continue |
| 189 | } |
| 190 | // mode type sha\tname |
| 191 | tab := strings.SplitN(line, "\t", 2) |
| 192 | if len(tab) != 2 { |
| 193 | continue |
| 194 | } |
| 195 | head := strings.Fields(tab[0]) |
| 196 | if len(head) != 3 { |
| 197 | continue |
| 198 | } |
| 199 | entries = append(entries, Entry{Mode: head[0], Type: head[1], SHA: head[2], Name: tab[1]}) |
| 200 | } |
| 201 | return entries, nil |
| 202 | } |
| 203 | |
| 204 | // Blob leest een tekstbestand, afgekapt op max bytes. binary is waar als |
| 205 | // het bestand een NUL bevat. |
| 206 | func Blob(ctx context.Context, gitBin, dir, rev, rel string, max int) (text string, binary bool, err error) { |
| 207 | out, err := run(ctx, gitBin, nil, "-C", dir, "show", rev+":"+rel) |
| 208 | if err != nil { |
| 209 | return "", false, err |
| 210 | } |
| 211 | if strings.Contains(out, "\x00") { |
| 212 | return "", true, nil |
| 213 | } |
| 214 | if len(out) > max { |
| 215 | out = out[:max] + "\n… afgekapt" |
| 216 | } |
| 217 | return out, false, nil |
| 218 | } |
| 219 | |
| 220 | // Branches geeft lokale branchnamen. |
| 221 | func Branches(ctx context.Context, gitBin, dir string) ([]string, error) { |
| 222 | out, err := run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--format=%(refname:short)", "refs/heads") |
| 223 | if err != nil { |
| 224 | return nil, err |
| 225 | } |
| 226 | var names []string |
| 227 | for _, line := range strings.Split(strings.TrimSpace(out), "\n") { |
| 228 | if line != "" { |
| 229 | names = append(names, line) |
| 230 | } |
| 231 | } |
| 232 | return names, nil |
| 233 | } |
| 234 | |
| 235 | // HasCommit meldt of sha een commit in deze repository is. |
| 236 | func HasCommit(ctx context.Context, gitBin, dir, sha string) bool { |
| 237 | out, err := run(ctx, gitBin, nil, "-C", dir, "cat-file", "-t", sha) |
| 238 | return err == nil && strings.TrimSpace(out) == "commit" |
| 239 | } |
| 240 | |
| 241 | // Refs geeft refnaam → sha. |
| 242 | func Refs(ctx context.Context, gitBin, dir string) (map[string]string, error) { |
| 243 | out, err := run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--format=%(objectname) %(refname)") |
| 244 | if err != nil { |
| 245 | return nil, err |
| 246 | } |
| 247 | m := map[string]string{} |
| 248 | for _, line := range strings.Split(strings.TrimSpace(out), "\n") { |
| 249 | if line == "" { |
| 250 | continue |
| 251 | } |
| 252 | parts := strings.SplitN(line, " ", 2) |
| 253 | if len(parts) == 2 { |
| 254 | m[parts[1]] = parts[0] |
| 255 | } |
| 256 | } |
| 257 | return m, nil |
| 258 | } |
| 259 | |
| 260 | // Touch geeft per pad de nieuwste commit uit de recente geschiedenis. |
| 261 | // Mappen erven de nieuwste commit van een bestand erin. |
| 262 | func Touch(ctx context.Context, gitBin, dir, rev string) (map[string]Commit, error) { |
| 263 | if rev == "" { |
| 264 | rev = "HEAD" |
| 265 | } |
| 266 | out, err := run(ctx, gitBin, nil, "-C", dir, "log", "--format=%H%x1f%an%x1f%at%x1f%s", "--name-only", "-n", "400", rev) |
| 267 | if err != nil { |
| 268 | if emptyHistory(err) { |
| 269 | return map[string]Commit{}, nil |
| 270 | } |
| 271 | return nil, err |
| 272 | } |
| 273 | m := map[string]Commit{} |
| 274 | var cur Commit |
| 275 | have := false |
| 276 | for _, line := range strings.Split(out, "\n") { |
| 277 | if strings.Contains(line, "\x1f") { |
| 278 | parts := strings.Split(line, "\x1f") |
| 279 | if len(parts) < 4 { |
| 280 | continue |
| 281 | } |
| 282 | cur = Commit{SHA: parts[0], Author: parts[1], Subject: parts[3]} |
| 283 | cur.Unix, _ = strconv.ParseInt(parts[2], 10, 64) |
| 284 | if len(cur.SHA) >= 10 { |
| 285 | cur.Short = cur.SHA[:10] |
| 286 | } |
| 287 | have = true |
| 288 | continue |
| 289 | } |
| 290 | line = strings.TrimSpace(line) |
| 291 | if line == "" || !have { |
| 292 | continue |
| 293 | } |
| 294 | notePath(m, line, cur) |
| 295 | } |
| 296 | return m, nil |
| 297 | } |
| 298 | |
| 299 | func notePath(m map[string]Commit, path string, c Commit) { |
| 300 | for path != "" && path != "." { |
| 301 | if _, ok := m[path]; !ok { |
| 302 | m[path] = c |
| 303 | } |
| 304 | i := strings.LastIndex(path, "/") |
| 305 | if i < 0 { |
| 306 | return |
| 307 | } |
| 308 | path = path[:i] |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | func emptyHistory(err error) bool { |
| 313 | msg := err.Error() |
| 314 | return strings.Contains(msg, "does not have any commits") || strings.Contains(msg, "bad default revision") || strings.Contains(msg, "ambiguous argument") |
| 315 | } |
| 316 | |
| 317 | // Stats telt commits op rev, lokale branches en tags. |
| 318 | func Stats(ctx context.Context, gitBin, dir, rev string) (commits, branches, tags int, err error) { |
| 319 | if rev == "" { |
| 320 | rev = "HEAD" |
| 321 | } |
| 322 | out, err := run(ctx, gitBin, nil, "-C", dir, "rev-list", "--count", rev) |
| 323 | if err != nil { |
| 324 | if emptyHistory(err) { |
| 325 | return 0, 0, 0, nil |
| 326 | } |
| 327 | return 0, 0, 0, err |
| 328 | } |
| 329 | commits, _ = strconv.Atoi(strings.TrimSpace(out)) |
| 330 | names, err := Branches(ctx, gitBin, dir) |
| 331 | if err != nil { |
| 332 | return commits, 0, 0, err |
| 333 | } |
| 334 | branches = len(names) |
| 335 | out, err = run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--format=%(refname:short)", "refs/tags") |
| 336 | if err != nil { |
| 337 | return commits, branches, 0, err |
| 338 | } |
| 339 | for _, line := range strings.Split(strings.TrimSpace(out), "\n") { |
| 340 | if line != "" { |
| 341 | tags++ |
| 342 | } |
| 343 | } |
| 344 | return commits, branches, tags, nil |
| 345 | } |
| 346 | |
| 347 | // Tags geeft tagnamen. |
| 348 | func Tags(ctx context.Context, gitBin, dir string) ([]string, error) { |
| 349 | out, err := run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--format=%(refname:short)", "refs/tags") |
| 350 | if err != nil { |
| 351 | return nil, err |
| 352 | } |
| 353 | var names []string |
| 354 | for _, line := range strings.Split(strings.TrimSpace(out), "\n") { |
| 355 | if line != "" { |
| 356 | names = append(names, line) |
| 357 | } |
| 358 | } |
| 359 | return names, nil |
| 360 | } |
| 361 | |
| 362 | // TagInfo is één git-tag voor de webinterface. |
| 363 | type TagInfo struct { |
| 364 | Name string |
| 365 | Annotated bool |
| 366 | Message string |
| 367 | CommitSHA string |
| 368 | CommitSubject string |
| 369 | Unix int64 |
| 370 | } |
| 371 | |
| 372 | // ListTags geeft alle tags, nieuwste eerst. |
| 373 | func ListTags(ctx context.Context, gitBin, dir string) ([]TagInfo, error) { |
| 374 | const format = "%(refname:short)\n%(objecttype)\n%(objectname)\n%(*objectname)\n%(creatordate:unix)\n%(subject)\n%(*subject)\nBLUEGIT-END" |
| 375 | out, err := run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--sort=-creatordate", "--format="+format, "refs/tags") |
| 376 | if err != nil { |
| 377 | return nil, err |
| 378 | } |
| 379 | lines := strings.Split(out, "\n") |
| 380 | if len(lines) > 0 && lines[len(lines)-1] == "" { |
| 381 | lines = lines[:len(lines)-1] |
| 382 | } |
| 383 | var tags []TagInfo |
| 384 | for i := 0; i+7 < len(lines); i += 8 { |
| 385 | if lines[i+7] != "BLUEGIT-END" { |
| 386 | continue |
| 387 | } |
| 388 | unix, _ := strconv.ParseInt(strings.TrimSpace(lines[i+4]), 10, 64) |
| 389 | tag := TagInfo{Name: lines[i], Unix: unix} |
| 390 | if lines[i+1] == "tag" { |
| 391 | tag.Annotated = true |
| 392 | tag.CommitSHA = lines[i+3] |
| 393 | tag.CommitSubject = lines[i+6] |
| 394 | if tag.CommitSHA == "" { |
| 395 | tag.CommitSHA = lines[i+2] |
| 396 | } |
| 397 | if tag.CommitSubject == "" { |
| 398 | tag.CommitSubject = lines[i+5] |
| 399 | } |
| 400 | msg, err := run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--format=%(contents)", "refs/tags/"+tag.Name) |
| 401 | if err != nil { |
| 402 | return nil, err |
| 403 | } |
| 404 | tag.Message = strings.TrimSpace(msg) |
| 405 | } else { |
| 406 | tag.CommitSHA = lines[i+2] |
| 407 | tag.CommitSubject = lines[i+5] |
| 408 | } |
| 409 | if tag.Name != "" { |
| 410 | tags = append(tags, tag) |
| 411 | } |
| 412 | } |
| 413 | sort.SliceStable(tags, func(i, j int) bool { |
| 414 | if tags[i].Unix != tags[j].Unix { |
| 415 | return tags[i].Unix > tags[j].Unix |
| 416 | } |
| 417 | return tags[i].Name < tags[j].Name |
| 418 | }) |
| 419 | return tags, nil |
| 420 | } |
| 421 | |
| 422 | // CreateTag zet een tag op een branch of commit. Een leeg bericht blijft licht. |
| 423 | func CreateTag(ctx context.Context, gitBin, dir, name, rev, message, author, email string) error { |
| 424 | if err := names.ValidTag(name); err != nil { |
| 425 | return err |
| 426 | } |
| 427 | sha, err := resolveCommit(ctx, gitBin, dir, rev) |
| 428 | if err != nil { |
| 429 | return err |
| 430 | } |
| 431 | if HasTag(ctx, gitBin, dir, name) { |
| 432 | return i18n.E("err.tagExists", name) |
| 433 | } |
| 434 | message = strings.TrimSpace(message) |
| 435 | if len(message) > 5000 { |
| 436 | return i18n.E("err.tagLong") |
| 437 | } |
| 438 | env := identityEnv(author, email) |
| 439 | if message == "" { |
| 440 | _, err = run(ctx, gitBin, env, "-C", dir, "tag", name, sha) |
| 441 | return err |
| 442 | } |
| 443 | _, err = run(ctx, gitBin, env, "-C", dir, "tag", "-a", name, sha, "-m", message) |
| 444 | return err |
| 445 | } |
| 446 | |
| 447 | // DeleteTag verwijdert een bestaande tag. |
| 448 | func DeleteTag(ctx context.Context, gitBin, dir, name string) error { |
| 449 | if err := usableTag(name); err != nil { |
| 450 | return err |
| 451 | } |
| 452 | if !HasTag(ctx, gitBin, dir, name) { |
| 453 | return i18n.E("err.tagMissing", name) |
| 454 | } |
| 455 | _, err := run(ctx, gitBin, nil, "-C", dir, "tag", "-d", "--", name) |
| 456 | return err |
| 457 | } |
| 458 | |
| 459 | // HasTag meldt of refs/tags/name bestaat. |
| 460 | func HasTag(ctx context.Context, gitBin, dir, name string) bool { |
| 461 | if err := usableTag(name); err != nil { |
| 462 | return false |
| 463 | } |
| 464 | _, err := run(ctx, gitBin, nil, "-C", dir, "rev-parse", "-q", "--verify", "--end-of-options", "refs/tags/"+name) |
| 465 | return err == nil |
| 466 | } |
| 467 | |
| 468 | // Archive schrijft een zip of tar.gz van de tag naar w. |
| 469 | func Archive(ctx context.Context, w io.Writer, gitBin, dir, prefix, name, format string) error { |
| 470 | if err := usableTag(name); err != nil { |
| 471 | return err |
| 472 | } |
| 473 | if !HasTag(ctx, gitBin, dir, name) { |
| 474 | return i18n.E("err.tagMissing", name) |
| 475 | } |
| 476 | kind := format |
| 477 | if format != "zip" && format != "tar.gz" { |
| 478 | return i18n.E("err.notFound") |
| 479 | } |
| 480 | if gitBin == "" { |
| 481 | gitBin = "git" |
| 482 | } |
| 483 | if prefix != "" && !strings.HasSuffix(prefix, "/") { |
| 484 | prefix += "/" |
| 485 | } |
| 486 | cmd := exec.CommandContext(ctx, gitBin, "-C", dir, "archive", "--format="+kind, "--prefix="+prefix, name) |
| 487 | cmd.Stdout = w |
| 488 | var stderr bytes.Buffer |
| 489 | cmd.Stderr = &stderr |
| 490 | if err := cmd.Run(); err != nil { |
| 491 | msg := strings.TrimSpace(stderr.String()) |
| 492 | if msg == "" { |
| 493 | msg = err.Error() |
| 494 | } |
| 495 | return fmt.Errorf("%s", msg) |
| 496 | } |
| 497 | return nil |
| 498 | } |
| 499 | |
| 500 | func resolveCommit(ctx context.Context, gitBin, dir, rev string) (string, error) { |
| 501 | rev = strings.TrimSpace(rev) |
| 502 | if rev == "" || strings.HasPrefix(rev, "-") || strings.Contains(rev, "..") || strings.ContainsAny(rev, " \t\r\n\\") { |
| 503 | return "", i18n.E("err.tagRef", rev) |
| 504 | } |
| 505 | out, err := run(ctx, gitBin, nil, "-C", dir, "rev-parse", "--verify", "--end-of-options", rev+"^{commit}") |
| 506 | if err != nil { |
| 507 | return "", i18n.E("err.tagRef", rev) |
| 508 | } |
| 509 | return strings.TrimSpace(out), nil |
| 510 | } |
| 511 | |
| 512 | func usableTag(name string) error { |
| 513 | if name == "" || len(name) > 200 || strings.HasPrefix(name, "-") || strings.HasPrefix(name, "/") || strings.HasSuffix(name, "/") || strings.Contains(name, "..") || strings.Contains(name, "//") || strings.Contains(name, "@{") || strings.ContainsAny(name, " \t\r\n\\~^:?*[") { |
| 514 | return i18n.E("err.tag", name) |
| 515 | } |
| 516 | return nil |
| 517 | } |
| 518 | |
| 519 | // TreeAll leest de hele boom. Name is het pad vanaf de root. |
| 520 | func TreeAll(ctx context.Context, gitBin, dir, rev string) ([]Entry, error) { |
| 521 | if rev == "" { |
| 522 | rev = "HEAD" |
| 523 | } |
| 524 | out, err := run(ctx, gitBin, nil, "-C", dir, "ls-tree", "-r", "-t", rev) |
| 525 | if err != nil { |
| 526 | if emptyHistory(err) { |
| 527 | return nil, nil |
| 528 | } |
| 529 | return nil, err |
| 530 | } |
| 531 | return parseTree(out), nil |
| 532 | } |
| 533 | |
| 534 | func parseTree(out string) []Entry { |
| 535 | var entries []Entry |
| 536 | for _, line := range strings.Split(strings.TrimSpace(out), "\n") { |
| 537 | if line == "" { |
| 538 | continue |
| 539 | } |
| 540 | tab := strings.SplitN(line, "\t", 2) |
| 541 | if len(tab) != 2 { |
| 542 | continue |
| 543 | } |
| 544 | head := strings.Fields(tab[0]) |
| 545 | if len(head) != 3 { |
| 546 | continue |
| 547 | } |
| 548 | entries = append(entries, Entry{Mode: head[0], Type: head[1], SHA: head[2], Name: tab[1]}) |
| 549 | } |
| 550 | return entries |
| 551 | } |
| 552 | |
| 553 | // LastCommit is de nieuwste commit die path heeft geraakt. Leeg pad is de tip. |
| 554 | func LastCommit(ctx context.Context, gitBin, dir, rev, path string) (Commit, error) { |
| 555 | if rev == "" { |
| 556 | rev = "HEAD" |
| 557 | } |
| 558 | args := []string{"-C", dir, "log", "-1", "--format=%H%x1f%an%x1f%ae%x1f%at%x1f%s", rev} |
| 559 | if path != "" { |
| 560 | args = append(args, "--", path) |
| 561 | } |
| 562 | out, err := run(ctx, gitBin, nil, args...) |
| 563 | if err != nil { |
| 564 | if emptyHistory(err) { |
| 565 | return Commit{}, nil |
| 566 | } |
| 567 | return Commit{}, err |
| 568 | } |
| 569 | line := strings.TrimSpace(out) |
| 570 | parts := strings.Split(line, "\x1f") |
| 571 | if len(parts) < 5 { |
| 572 | return Commit{}, nil |
| 573 | } |
| 574 | c := Commit{SHA: parts[0], Author: parts[1], Email: parts[2], Subject: parts[4]} |
| 575 | c.Unix, _ = strconv.ParseInt(parts[3], 10, 64) |
| 576 | if len(c.SHA) >= 10 { |
| 577 | c.Short = c.SHA[:10] |
| 578 | } |
| 579 | return c, nil |
| 580 | } |
| 581 | |
| 582 | // BlobSize is de grootte in bytes. |
| 583 | func BlobSize(ctx context.Context, gitBin, dir, rev, rel string) (int64, error) { |
| 584 | out, err := run(ctx, gitBin, nil, "-C", dir, "cat-file", "-s", rev+":"+rel) |
| 585 | if err != nil { |
| 586 | return 0, err |
| 587 | } |
| 588 | return strconv.ParseInt(strings.TrimSpace(out), 10, 64) |
| 589 | } |
| 590 | |
| 591 | // PushedCommit is een commit die met een push nieuw bereikbaar werd. |
| 592 | type PushedCommit struct { |
| 593 | SHA string |
| 594 | Email string |
| 595 | Name string |
| 596 | Unix int64 |
| 597 | } |
| 598 | |
| 599 | // CommitsSince geeft commits die newSHA bereikt en old niet. |
| 600 | // Een lege of nul-old is de hele geschiedenis van newSHA. |
| 601 | func CommitsSince(ctx context.Context, gitBin, dir, old, newSHA string) ([]PushedCommit, error) { |
| 602 | if newSHA == "" || allZero(newSHA) { |
| 603 | return nil, nil |
| 604 | } |
| 605 | args := []string{"-C", dir, "log", "--format=%H%x1f%ae%x1f%an%x1f%at", newSHA} |
| 606 | if old != "" && !allZero(old) { |
| 607 | args = append(args, "--not", old) |
| 608 | } |
| 609 | out, err := run(ctx, gitBin, nil, args...) |
| 610 | if err != nil { |
| 611 | if emptyHistory(err) { |
| 612 | return nil, nil |
| 613 | } |
| 614 | return nil, err |
| 615 | } |
| 616 | var commits []PushedCommit |
| 617 | for _, line := range strings.Split(out, "\n") { |
| 618 | line = strings.TrimSpace(line) |
| 619 | if line == "" || !strings.Contains(line, "\x1f") { |
| 620 | continue |
| 621 | } |
| 622 | parts := strings.Split(line, "\x1f") |
| 623 | if len(parts) < 4 { |
| 624 | continue |
| 625 | } |
| 626 | c := PushedCommit{SHA: parts[0], Email: parts[1], Name: parts[2]} |
| 627 | c.Unix, _ = strconv.ParseInt(parts[3], 10, 64) |
| 628 | commits = append(commits, c) |
| 629 | } |
| 630 | return commits, nil |
| 631 | } |
| 632 | |
| 633 | func allZero(sha string) bool { |
| 634 | return strings.Trim(sha, "0") == "" |
| 635 | } |
| 636 | |
| 637 | // BranchOfRef haalt de branch uit refs/heads/… . |
| 638 | func BranchOfRef(ref string) (string, bool) { |
| 639 | const p = "refs/heads/" |
| 640 | if strings.HasPrefix(ref, p) && len(ref) > len(p) { |
| 641 | return ref[len(p):], true |
| 642 | } |
| 643 | return "", false |
| 644 | } |
| 645 | |
| 646 | // Merge voegt source samen in target en pusht het resultaat. |
| 647 | // De push gaat door de hook, dus role en patterns moeten kloppen. |
| 648 | func Merge(ctx context.Context, gitBin, bare, work, source, target, author, email, message string, role access.Role, patterns []string) error { |
| 649 | if err := os.RemoveAll(work); err != nil { |
| 650 | return err |
| 651 | } |
| 652 | if err := os.MkdirAll(filepath.Dir(work), 0o755); err != nil { |
| 653 | return err |
| 654 | } |
| 655 | if _, err := run(ctx, gitBin, nil, "clone", bare, work); err != nil { |
| 656 | return err |
| 657 | } |
| 658 | env := append(os.Environ(), |
| 659 | "GIT_AUTHOR_NAME="+author, |
| 660 | "GIT_AUTHOR_EMAIL="+email, |
| 661 | "GIT_COMMITTER_NAME="+author, |
| 662 | "GIT_COMMITTER_EMAIL="+email, |
| 663 | ) |
| 664 | if _, err := run(ctx, gitBin, env, "-C", work, "checkout", target); err != nil { |
| 665 | return fmt.Errorf("doelbranch %s: %w", target, err) |
| 666 | } |
| 667 | if _, err := run(ctx, gitBin, env, "-C", work, "merge", "--no-ff", "--no-edit", "-m", message, source); err != nil { |
| 668 | return fmt.Errorf("samenvoegen lukt niet, er is een conflict of de branch ontbreekt") |
| 669 | } |
| 670 | pushEnv := append(env, PushEnv(role, patterns, nil)...) |
| 671 | if _, err := run(ctx, gitBin, pushEnv, "-C", work, "push", "origin", target); err != nil { |
| 672 | return err |
| 673 | } |
| 674 | return nil |
| 675 | } |
| 676 | |
| 677 | // Tag zet een annotated tag op sha. |
| 678 | func Tag(ctx context.Context, gitBin, dir, tag, sha, message string) error { |
| 679 | _, err := run(ctx, gitBin, nil, "-C", dir, "tag", "-a", tag, sha, "-m", message) |
| 680 | return err |
| 681 | } |
| 682 | |
| 683 | // DiffStat is een korte vergelijking tussen twee branches. |
| 684 | func DiffStat(ctx context.Context, gitBin, dir, target, source string) (string, error) { |
| 685 | out, err := run(ctx, gitBin, nil, "-C", dir, "log", "--oneline", target+".."+source) |
| 686 | if err != nil { |
| 687 | return "", err |
| 688 | } |
| 689 | return strings.TrimSpace(out), nil |
| 690 | } |
| 691 | |
| 692 | func run(ctx context.Context, bin string, env []string, args ...string) (string, error) { |
| 693 | if bin == "" { |
| 694 | bin = "git" |
| 695 | } |
| 696 | cmd := exec.CommandContext(ctx, bin, args...) |
| 697 | if env != nil { |
| 698 | cmd.Env = env |
| 699 | } |
| 700 | var stdout, stderr bytes.Buffer |
| 701 | cmd.Stdout = &stdout |
| 702 | cmd.Stderr = &stderr |
| 703 | if err := cmd.Run(); err != nil { |
| 704 | msg := strings.TrimSpace(stderr.String()) |
| 705 | if msg == "" { |
| 706 | msg = err.Error() |
| 707 | } |
| 708 | return "", fmt.Errorf("%s", msg) |
| 709 | } |
| 710 | return stdout.String(), nil |
| 711 | } |