| 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 | "errors" |
| 9 | "fmt" |
| 10 | "io" |
| 11 | "os" |
| 12 | "os/exec" |
| 13 | "path/filepath" |
| 14 | "sort" |
| 15 | "strconv" |
| 16 | "strings" |
| 17 | |
| 18 | "gitlab.com/Timfa/bluegit/internal/access" |
| 19 | "gitlab.com/Timfa/bluegit/internal/i18n" |
| 20 | "gitlab.com/Timfa/bluegit/internal/names" |
| 21 | ) |
| 22 | |
| 23 | // Dir is de bare repository op de datadisk. |
| 24 | func Dir(storage, owner, name string) string { |
| 25 | return filepath.Join(storage, "repos", owner, name+".git") |
| 26 | } |
| 27 | |
| 28 | // Init maakt een lege bare repository en zet de pre-receive-hook. |
| 29 | func Init(gitBin, dir, defaultBranch, hookBinary string) error { |
| 30 | if err := os.MkdirAll(filepath.Dir(dir), 0o755); err != nil { |
| 31 | return err |
| 32 | } |
| 33 | if _, err := run(context.Background(), gitBin, nil, "init", "--bare", "--initial-branch", defaultBranch, dir); err != nil { |
| 34 | return err |
| 35 | } |
| 36 | for _, kv := range [][2]string{ |
| 37 | {"http.receivepack", "true"}, |
| 38 | {"http.uploadpack", "true"}, |
| 39 | {"receive.denyCurrentBranch", "ignore"}, |
| 40 | } { |
| 41 | if _, err := run(context.Background(), gitBin, nil, "-C", dir, "config", kv[0], kv[1]); err != nil { |
| 42 | return err |
| 43 | } |
| 44 | } |
| 45 | return InstallHook(dir, hookBinary) |
| 46 | } |
| 47 | |
| 48 | // InstallHook schrijft hooks/pre-receive. Die roept deze binary aan. |
| 49 | func InstallHook(dir, hookBinary string) error { |
| 50 | if hookBinary == "" { |
| 51 | return fmt.Errorf("hook-binary ontbreekt") |
| 52 | } |
| 53 | path := filepath.Join(dir, "hooks", "pre-receive") |
| 54 | body := "#!/bin/sh\nset -eu\nexec " + shellQuote(hookBinary) + " hook pre-receive\n" |
| 55 | if err := os.WriteFile(path, []byte(body), 0o755); err != nil { |
| 56 | return err |
| 57 | } |
| 58 | return nil |
| 59 | } |
| 60 | |
| 61 | func shellQuote(s string) string { |
| 62 | return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" |
| 63 | } |
| 64 | |
| 65 | // PushEnv zijn de variabelen die de hook leest. Zonder deze variabelen |
| 66 | // weigert de hook, zodat een push buiten BlueGit om niet slaagt. |
| 67 | func PushEnv(role access.Role, patterns, tagPatterns []string) []string { |
| 68 | return []string{ |
| 69 | "BLUEGIT_ROLE=" + string(role), |
| 70 | "BLUEGIT_PROTECTED=" + strings.Join(patterns, "\n"), |
| 71 | "BLUEGIT_PROTECTED_TAGS=" + strings.Join(tagPatterns, "\n"), |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | // ReadUpdates leest de regels van een pre-receive-hook. |
| 76 | func ReadUpdates(r io.Reader) ([]access.RefUpdate, error) { |
| 77 | sc := bufio.NewScanner(r) |
| 78 | var out []access.RefUpdate |
| 79 | for sc.Scan() { |
| 80 | line := strings.TrimSpace(sc.Text()) |
| 81 | if line == "" { |
| 82 | continue |
| 83 | } |
| 84 | parts := strings.Fields(line) |
| 85 | if len(parts) != 3 { |
| 86 | return nil, fmt.Errorf("onverwachte hookregel %q", line) |
| 87 | } |
| 88 | out = append(out, access.RefUpdate{Old: parts[0], New: parts[1], Ref: parts[2]}) |
| 89 | } |
| 90 | return out, sc.Err() |
| 91 | } |
| 92 | |
| 93 | // EvaluatePush is wat `bluegit hook pre-receive` doet. |
| 94 | func EvaluatePush(role access.Role, patterns, tagPatterns []string, r io.Reader) error { |
| 95 | if role == "" { |
| 96 | return fmt.Errorf("push geweigerd: geen BlueGit-rol") |
| 97 | } |
| 98 | ups, err := ReadUpdates(r) |
| 99 | if err != nil { |
| 100 | return err |
| 101 | } |
| 102 | return access.AuthorizeUpdates(role, patterns, tagPatterns, ups) |
| 103 | } |
| 104 | |
| 105 | // Commit is één commit voor de webinterface. |
| 106 | type Commit struct { |
| 107 | SHA string |
| 108 | Short string |
| 109 | Author string |
| 110 | Email string |
| 111 | Date string |
| 112 | Unix int64 |
| 113 | Subject string |
| 114 | Body string |
| 115 | } |
| 116 | |
| 117 | // Entry is een bestand of map in een tree. |
| 118 | type Entry struct { |
| 119 | Mode string |
| 120 | Type string |
| 121 | SHA string |
| 122 | Name string |
| 123 | } |
| 124 | |
| 125 | // Log geeft de nieuwste commits. |
| 126 | func Log(ctx context.Context, gitBin, dir, rev string, limit int) ([]Commit, error) { |
| 127 | return LogPage(ctx, gitBin, dir, rev, 0, limit) |
| 128 | } |
| 129 | |
| 130 | // LogPage slaat de nieuwste skip commits over en leest daarna hooguit limit commits. |
| 131 | func LogPage(ctx context.Context, gitBin, dir, rev string, skip, limit int) ([]Commit, error) { |
| 132 | if rev == "" { |
| 133 | rev = "HEAD" |
| 134 | } |
| 135 | if limit < 1 { |
| 136 | limit = 1 |
| 137 | } |
| 138 | if skip < 0 { |
| 139 | skip = 0 |
| 140 | } |
| 141 | args := []string{"-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)} |
| 142 | if skip > 0 { |
| 143 | args = append(args, fmt.Sprintf("--skip=%d", skip)) |
| 144 | } |
| 145 | args = append(args, rev) |
| 146 | out, err := run(ctx, gitBin, nil, args...) |
| 147 | if err != nil { |
| 148 | if strings.Contains(err.Error(), "does not have any commits") || strings.Contains(err.Error(), "bad default revision") || strings.Contains(err.Error(), "ambiguous argument") { |
| 149 | return nil, nil |
| 150 | } |
| 151 | return nil, err |
| 152 | } |
| 153 | return parseLog(out), nil |
| 154 | } |
| 155 | |
| 156 | func parseLog(out string) []Commit { |
| 157 | var commits []Commit |
| 158 | for _, rec := range strings.Split(out, "\x1e") { |
| 159 | rec = strings.TrimSpace(rec) |
| 160 | if rec == "" { |
| 161 | continue |
| 162 | } |
| 163 | parts := strings.Split(rec, "\x1f") |
| 164 | if len(parts) < 6 { |
| 165 | continue |
| 166 | } |
| 167 | c := Commit{SHA: parts[0], Author: parts[1], Email: parts[2], Date: parts[3], Subject: parts[5]} |
| 168 | c.Unix, _ = strconv.ParseInt(parts[4], 10, 64) |
| 169 | if len(c.SHA) >= 10 { |
| 170 | c.Short = c.SHA[:10] |
| 171 | } |
| 172 | if len(parts) > 6 { |
| 173 | c.Body = strings.TrimSpace(parts[6]) |
| 174 | } |
| 175 | commits = append(commits, c) |
| 176 | } |
| 177 | return commits |
| 178 | } |
| 179 | |
| 180 | // Message is een commitbericht. Merge is waar bij twee of meer ouders. |
| 181 | type Message struct { |
| 182 | Subject string |
| 183 | Body string |
| 184 | Author string |
| 185 | Email string |
| 186 | Merge bool |
| 187 | } |
| 188 | |
| 189 | // Messages leest hooguit limit berichten, oudste eerst. |
| 190 | func Messages(ctx context.Context, gitBin, dir, rev string, limit int) ([]Message, error) { |
| 191 | if rev == "" { |
| 192 | rev = "HEAD" |
| 193 | } |
| 194 | if limit < 1 { |
| 195 | limit = 1 |
| 196 | } |
| 197 | if limit > 100 { |
| 198 | limit = 100 |
| 199 | } |
| 200 | out, err := run(ctx, gitBin, nil, "-C", dir, "log", "--reverse", "--format=%an%x1f%ae%x1f%P%x1f%s%x1f%b%x1e", "--date=short", fmt.Sprintf("-n%d", limit), rev) |
| 201 | if err != nil { |
| 202 | if strings.Contains(err.Error(), "does not have any commits") || strings.Contains(err.Error(), "bad default revision") || strings.Contains(err.Error(), "ambiguous argument") { |
| 203 | return nil, nil |
| 204 | } |
| 205 | return nil, err |
| 206 | } |
| 207 | return parseMessages(out), nil |
| 208 | } |
| 209 | |
| 210 | func parseMessages(out string) []Message { |
| 211 | var msgs []Message |
| 212 | for _, rec := range strings.Split(out, "\x1e") { |
| 213 | rec = strings.TrimSpace(rec) |
| 214 | if rec == "" { |
| 215 | continue |
| 216 | } |
| 217 | parts := strings.Split(rec, "\x1f") |
| 218 | if len(parts) < 4 { |
| 219 | continue |
| 220 | } |
| 221 | m := Message{Author: parts[0], Email: parts[1], Subject: parts[3]} |
| 222 | m.Merge = len(strings.Fields(parts[2])) > 1 |
| 223 | if len(parts) > 4 { |
| 224 | m.Body = strings.TrimSpace(parts[4]) |
| 225 | } |
| 226 | msgs = append(msgs, m) |
| 227 | } |
| 228 | return msgs |
| 229 | } |
| 230 | |
| 231 | // Show leest één commit. |
| 232 | func Show(ctx context.Context, gitBin, dir, sha string) (Commit, error) { |
| 233 | list, err := Log(ctx, gitBin, dir, sha, 1) |
| 234 | if err != nil { |
| 235 | return Commit{}, err |
| 236 | } |
| 237 | if len(list) == 0 { |
| 238 | return Commit{}, fmt.Errorf("commit niet gevonden") |
| 239 | } |
| 240 | return list[0], nil |
| 241 | } |
| 242 | |
| 243 | // Tree leest een map. path is relatief en mag leeg zijn. |
| 244 | func Tree(ctx context.Context, gitBin, dir, rev, rel string) ([]Entry, error) { |
| 245 | spec := rev |
| 246 | if rel != "" { |
| 247 | spec = rev + ":" + rel |
| 248 | } |
| 249 | out, err := run(ctx, gitBin, nil, "-C", dir, "ls-tree", spec) |
| 250 | if err != nil { |
| 251 | return nil, err |
| 252 | } |
| 253 | var entries []Entry |
| 254 | for _, line := range strings.Split(strings.TrimSpace(out), "\n") { |
| 255 | if line == "" { |
| 256 | continue |
| 257 | } |
| 258 | // mode type sha\tname |
| 259 | tab := strings.SplitN(line, "\t", 2) |
| 260 | if len(tab) != 2 { |
| 261 | continue |
| 262 | } |
| 263 | head := strings.Fields(tab[0]) |
| 264 | if len(head) != 3 { |
| 265 | continue |
| 266 | } |
| 267 | entries = append(entries, Entry{Mode: head[0], Type: head[1], SHA: head[2], Name: tab[1]}) |
| 268 | } |
| 269 | return entries, nil |
| 270 | } |
| 271 | |
| 272 | // Blob leest een tekstbestand, afgekapt op max bytes. binary is waar als |
| 273 | // het bestand een NUL bevat. |
| 274 | func Blob(ctx context.Context, gitBin, dir, rev, rel string, max int) (text string, binary bool, err error) { |
| 275 | out, err := run(ctx, gitBin, nil, "-C", dir, "show", rev+":"+rel) |
| 276 | if err != nil { |
| 277 | return "", false, err |
| 278 | } |
| 279 | if strings.Contains(out, "\x00") { |
| 280 | return "", true, nil |
| 281 | } |
| 282 | if len(out) > max { |
| 283 | out = out[:max] + "\n… afgekapt" |
| 284 | } |
| 285 | return out, false, nil |
| 286 | } |
| 287 | |
| 288 | // Branches geeft lokale branchnamen. |
| 289 | func Branches(ctx context.Context, gitBin, dir string) ([]string, error) { |
| 290 | out, err := run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--format=%(refname:short)", "refs/heads") |
| 291 | if err != nil { |
| 292 | return nil, err |
| 293 | } |
| 294 | var names []string |
| 295 | for _, line := range strings.Split(strings.TrimSpace(out), "\n") { |
| 296 | if line != "" { |
| 297 | names = append(names, line) |
| 298 | } |
| 299 | } |
| 300 | return names, nil |
| 301 | } |
| 302 | |
| 303 | // SetHEAD zet de symbolische HEAD van een bare repository naar een bestaande branch. |
| 304 | // Het verwijdert geen refs of objecten. |
| 305 | func SetHEAD(ctx context.Context, gitBin, dir, branch string) error { |
| 306 | if branch == "" { |
| 307 | return fmt.Errorf("leeg branch") |
| 308 | } |
| 309 | _, err := run(ctx, gitBin, nil, "-C", dir, "symbolic-ref", "HEAD", "refs/heads/"+branch) |
| 310 | return err |
| 311 | } |
| 312 | |
| 313 | // HasBranch meldt of de named branch bestaat. |
| 314 | func HasBranch(ctx context.Context, gitBin, dir, branch string) bool { |
| 315 | if branch == "" { |
| 316 | return false |
| 317 | } |
| 318 | _, err := run(ctx, gitBin, nil, "-C", dir, "show-ref", "--verify", "--quiet", "refs/heads/"+branch) |
| 319 | return err == nil |
| 320 | } |
| 321 | |
| 322 | // HasCommit meldt of sha een commit in deze repository is. |
| 323 | func HasCommit(ctx context.Context, gitBin, dir, sha string) bool { |
| 324 | out, err := run(ctx, gitBin, nil, "-C", dir, "cat-file", "-t", sha) |
| 325 | return err == nil && strings.TrimSpace(out) == "commit" |
| 326 | } |
| 327 | |
| 328 | // Refs geeft refnaam → sha. |
| 329 | func Refs(ctx context.Context, gitBin, dir string) (map[string]string, error) { |
| 330 | out, err := run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--format=%(objectname) %(refname)") |
| 331 | if err != nil { |
| 332 | return nil, err |
| 333 | } |
| 334 | m := map[string]string{} |
| 335 | for _, line := range strings.Split(strings.TrimSpace(out), "\n") { |
| 336 | if line == "" { |
| 337 | continue |
| 338 | } |
| 339 | parts := strings.SplitN(line, " ", 2) |
| 340 | if len(parts) == 2 { |
| 341 | m[parts[1]] = parts[0] |
| 342 | } |
| 343 | } |
| 344 | return m, nil |
| 345 | } |
| 346 | |
| 347 | // Touch geeft per pad de nieuwste commit uit de recente geschiedenis. |
| 348 | // Mappen erven de nieuwste commit van een bestand erin. |
| 349 | func Touch(ctx context.Context, gitBin, dir, rev string) (map[string]Commit, error) { |
| 350 | if rev == "" { |
| 351 | rev = "HEAD" |
| 352 | } |
| 353 | out, err := run(ctx, gitBin, nil, "-C", dir, "log", "--format=%H%x1f%an%x1f%at%x1f%s", "--name-only", "-n", "400", rev) |
| 354 | if err != nil { |
| 355 | if emptyHistory(err) { |
| 356 | return map[string]Commit{}, nil |
| 357 | } |
| 358 | return nil, err |
| 359 | } |
| 360 | m := map[string]Commit{} |
| 361 | var cur Commit |
| 362 | have := false |
| 363 | for _, line := range strings.Split(out, "\n") { |
| 364 | if strings.Contains(line, "\x1f") { |
| 365 | parts := strings.Split(line, "\x1f") |
| 366 | if len(parts) < 4 { |
| 367 | continue |
| 368 | } |
| 369 | cur = Commit{SHA: parts[0], Author: parts[1], Subject: parts[3]} |
| 370 | cur.Unix, _ = strconv.ParseInt(parts[2], 10, 64) |
| 371 | if len(cur.SHA) >= 10 { |
| 372 | cur.Short = cur.SHA[:10] |
| 373 | } |
| 374 | have = true |
| 375 | continue |
| 376 | } |
| 377 | line = strings.TrimSpace(line) |
| 378 | if line == "" || !have { |
| 379 | continue |
| 380 | } |
| 381 | notePath(m, line, cur) |
| 382 | } |
| 383 | return m, nil |
| 384 | } |
| 385 | |
| 386 | func notePath(m map[string]Commit, path string, c Commit) { |
| 387 | for path != "" && path != "." { |
| 388 | if _, ok := m[path]; !ok { |
| 389 | m[path] = c |
| 390 | } |
| 391 | i := strings.LastIndex(path, "/") |
| 392 | if i < 0 { |
| 393 | return |
| 394 | } |
| 395 | path = path[:i] |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | func emptyHistory(err error) bool { |
| 400 | msg := err.Error() |
| 401 | return strings.Contains(msg, "does not have any commits") || strings.Contains(msg, "bad default revision") || strings.Contains(msg, "ambiguous argument") |
| 402 | } |
| 403 | |
| 404 | // Stats telt commits op rev, lokale branches en tags. |
| 405 | func Stats(ctx context.Context, gitBin, dir, rev string) (commits, branches, tags int, err error) { |
| 406 | if rev == "" { |
| 407 | rev = "HEAD" |
| 408 | } |
| 409 | out, err := run(ctx, gitBin, nil, "-C", dir, "rev-list", "--count", rev) |
| 410 | if err != nil { |
| 411 | if emptyHistory(err) { |
| 412 | return 0, 0, 0, nil |
| 413 | } |
| 414 | return 0, 0, 0, err |
| 415 | } |
| 416 | commits, _ = strconv.Atoi(strings.TrimSpace(out)) |
| 417 | names, err := Branches(ctx, gitBin, dir) |
| 418 | if err != nil { |
| 419 | return commits, 0, 0, err |
| 420 | } |
| 421 | branches = len(names) |
| 422 | out, err = run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--format=%(refname:short)", "refs/tags") |
| 423 | if err != nil { |
| 424 | return commits, branches, 0, err |
| 425 | } |
| 426 | for _, line := range strings.Split(strings.TrimSpace(out), "\n") { |
| 427 | if line != "" { |
| 428 | tags++ |
| 429 | } |
| 430 | } |
| 431 | return commits, branches, tags, nil |
| 432 | } |
| 433 | |
| 434 | // Tags geeft tagnamen. |
| 435 | func Tags(ctx context.Context, gitBin, dir string) ([]string, error) { |
| 436 | out, err := run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--format=%(refname:short)", "refs/tags") |
| 437 | if err != nil { |
| 438 | return nil, err |
| 439 | } |
| 440 | var names []string |
| 441 | for _, line := range strings.Split(strings.TrimSpace(out), "\n") { |
| 442 | if line != "" { |
| 443 | names = append(names, line) |
| 444 | } |
| 445 | } |
| 446 | return names, nil |
| 447 | } |
| 448 | |
| 449 | // TagInfo is één git-tag voor de webinterface. |
| 450 | type TagInfo struct { |
| 451 | Name string |
| 452 | Annotated bool |
| 453 | Message string |
| 454 | CommitSHA string |
| 455 | CommitSubject string |
| 456 | Unix int64 |
| 457 | } |
| 458 | |
| 459 | // ListTags geeft alle tags, nieuwste eerst. |
| 460 | func ListTags(ctx context.Context, gitBin, dir string) ([]TagInfo, error) { |
| 461 | const format = "%(refname:short)\n%(objecttype)\n%(objectname)\n%(*objectname)\n%(creatordate:unix)\n%(subject)\n%(*subject)\nBLUEGIT-END" |
| 462 | out, err := run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--sort=-creatordate", "--format="+format, "refs/tags") |
| 463 | if err != nil { |
| 464 | return nil, err |
| 465 | } |
| 466 | lines := strings.Split(out, "\n") |
| 467 | if len(lines) > 0 && lines[len(lines)-1] == "" { |
| 468 | lines = lines[:len(lines)-1] |
| 469 | } |
| 470 | var tags []TagInfo |
| 471 | for i := 0; i+7 < len(lines); i += 8 { |
| 472 | if lines[i+7] != "BLUEGIT-END" { |
| 473 | continue |
| 474 | } |
| 475 | unix, _ := strconv.ParseInt(strings.TrimSpace(lines[i+4]), 10, 64) |
| 476 | tag := TagInfo{Name: lines[i], Unix: unix} |
| 477 | if lines[i+1] == "tag" { |
| 478 | tag.Annotated = true |
| 479 | tag.CommitSHA = lines[i+3] |
| 480 | tag.CommitSubject = lines[i+6] |
| 481 | if tag.CommitSHA == "" { |
| 482 | tag.CommitSHA = lines[i+2] |
| 483 | } |
| 484 | if tag.CommitSubject == "" { |
| 485 | tag.CommitSubject = lines[i+5] |
| 486 | } |
| 487 | msg, err := run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--format=%(contents)", "refs/tags/"+tag.Name) |
| 488 | if err != nil { |
| 489 | return nil, err |
| 490 | } |
| 491 | tag.Message = strings.TrimSpace(msg) |
| 492 | } else { |
| 493 | tag.CommitSHA = lines[i+2] |
| 494 | tag.CommitSubject = lines[i+5] |
| 495 | } |
| 496 | if tag.Name != "" { |
| 497 | tags = append(tags, tag) |
| 498 | } |
| 499 | } |
| 500 | sort.SliceStable(tags, func(i, j int) bool { |
| 501 | if tags[i].Unix != tags[j].Unix { |
| 502 | return tags[i].Unix > tags[j].Unix |
| 503 | } |
| 504 | return tags[i].Name < tags[j].Name |
| 505 | }) |
| 506 | return tags, nil |
| 507 | } |
| 508 | |
| 509 | // CreateTag zet een tag op een branch of commit. Een leeg bericht blijft licht. |
| 510 | func CreateTag(ctx context.Context, gitBin, dir, name, rev, message, author, email string) error { |
| 511 | if err := names.ValidTag(name); err != nil { |
| 512 | return err |
| 513 | } |
| 514 | sha, err := resolveCommit(ctx, gitBin, dir, rev) |
| 515 | if err != nil { |
| 516 | return err |
| 517 | } |
| 518 | if HasTag(ctx, gitBin, dir, name) { |
| 519 | return i18n.E("err.tagExists", name) |
| 520 | } |
| 521 | message = strings.TrimSpace(message) |
| 522 | if len(message) > 5000 { |
| 523 | return i18n.E("err.tagLong") |
| 524 | } |
| 525 | home, err := os.MkdirTemp(dir, "home-") |
| 526 | if err != nil { |
| 527 | return classifyGit(err) |
| 528 | } |
| 529 | defer os.RemoveAll(home) |
| 530 | env := CommandEnv(author, email, home, home) |
| 531 | if message == "" { |
| 532 | _, err = run(ctx, gitBin, env, "-C", dir, "tag", name, sha) |
| 533 | return err |
| 534 | } |
| 535 | _, err = run(ctx, gitBin, env, "-C", dir, "tag", "-a", name, sha, "-m", message) |
| 536 | return err |
| 537 | } |
| 538 | |
| 539 | // DeleteTag verwijdert een bestaande tag. |
| 540 | func DeleteTag(ctx context.Context, gitBin, dir, name string) error { |
| 541 | if err := usableTag(name); err != nil { |
| 542 | return err |
| 543 | } |
| 544 | if !HasTag(ctx, gitBin, dir, name) { |
| 545 | return i18n.E("err.tagMissing", name) |
| 546 | } |
| 547 | _, err := run(ctx, gitBin, nil, "-C", dir, "tag", "-d", "--", name) |
| 548 | return err |
| 549 | } |
| 550 | |
| 551 | // HasTag meldt of refs/tags/name bestaat. |
| 552 | func HasTag(ctx context.Context, gitBin, dir, name string) bool { |
| 553 | if err := usableTag(name); err != nil { |
| 554 | return false |
| 555 | } |
| 556 | _, err := run(ctx, gitBin, nil, "-C", dir, "rev-parse", "-q", "--verify", "--end-of-options", "refs/tags/"+name) |
| 557 | return err == nil |
| 558 | } |
| 559 | |
| 560 | // Archive schrijft een zip of tar.gz van de tag naar w. |
| 561 | func Archive(ctx context.Context, w io.Writer, gitBin, dir, prefix, name, format string) error { |
| 562 | if err := usableTag(name); err != nil { |
| 563 | return err |
| 564 | } |
| 565 | if !HasTag(ctx, gitBin, dir, name) { |
| 566 | return i18n.E("err.tagMissing", name) |
| 567 | } |
| 568 | return ArchiveAt(ctx, w, gitBin, dir, prefix, name, format) |
| 569 | } |
| 570 | |
| 571 | // ArchiveAt schrijft een zip of tar.gz van een bestaande revisie. |
| 572 | // rev is een tagnaam of refs/heads/…. |
| 573 | func ArchiveAt(ctx context.Context, w io.Writer, gitBin, dir, prefix, rev, format string) error { |
| 574 | if format != "zip" && format != "tar.gz" { |
| 575 | return i18n.E("err.notFound") |
| 576 | } |
| 577 | if rev == "" || strings.HasPrefix(rev, "-") || strings.Contains(rev, "..") || strings.ContainsAny(rev, " \t\r\n\\") { |
| 578 | return i18n.E("err.notFound") |
| 579 | } |
| 580 | if gitBin == "" { |
| 581 | gitBin = "git" |
| 582 | } |
| 583 | if prefix != "" && !strings.HasSuffix(prefix, "/") { |
| 584 | prefix += "/" |
| 585 | } |
| 586 | cmd := exec.CommandContext(ctx, gitBin, "-C", dir, "archive", "--format="+format, "--prefix="+prefix, rev) |
| 587 | cmd.Stdout = w |
| 588 | var stderr bytes.Buffer |
| 589 | cmd.Stderr = &stderr |
| 590 | if err := cmd.Run(); err != nil { |
| 591 | msg := strings.TrimSpace(stderr.String()) |
| 592 | if msg == "" { |
| 593 | msg = err.Error() |
| 594 | } |
| 595 | return fmt.Errorf("%s", msg) |
| 596 | } |
| 597 | return nil |
| 598 | } |
| 599 | |
| 600 | func resolveCommit(ctx context.Context, gitBin, dir, rev string) (string, error) { |
| 601 | rev = strings.TrimSpace(rev) |
| 602 | if rev == "" || strings.HasPrefix(rev, "-") || strings.Contains(rev, "..") || strings.ContainsAny(rev, " \t\r\n\\") { |
| 603 | return "", i18n.E("err.tagRef", rev) |
| 604 | } |
| 605 | out, err := run(ctx, gitBin, nil, "-C", dir, "rev-parse", "--verify", "--end-of-options", rev+"^{commit}") |
| 606 | if err != nil { |
| 607 | return "", i18n.E("err.tagRef", rev) |
| 608 | } |
| 609 | return strings.TrimSpace(out), nil |
| 610 | } |
| 611 | |
| 612 | func usableTag(name string) error { |
| 613 | 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\\~^:?*[") { |
| 614 | return i18n.E("err.tag", name) |
| 615 | } |
| 616 | return nil |
| 617 | } |
| 618 | |
| 619 | // TreeAll leest de hele boom. Name is het pad vanaf de root. |
| 620 | func TreeAll(ctx context.Context, gitBin, dir, rev string) ([]Entry, error) { |
| 621 | if rev == "" { |
| 622 | rev = "HEAD" |
| 623 | } |
| 624 | out, err := run(ctx, gitBin, nil, "-C", dir, "ls-tree", "-r", "-t", rev) |
| 625 | if err != nil { |
| 626 | if emptyHistory(err) { |
| 627 | return nil, nil |
| 628 | } |
| 629 | return nil, err |
| 630 | } |
| 631 | return parseTree(out), nil |
| 632 | } |
| 633 | |
| 634 | func parseTree(out string) []Entry { |
| 635 | var entries []Entry |
| 636 | for _, line := range strings.Split(strings.TrimSpace(out), "\n") { |
| 637 | if line == "" { |
| 638 | continue |
| 639 | } |
| 640 | tab := strings.SplitN(line, "\t", 2) |
| 641 | if len(tab) != 2 { |
| 642 | continue |
| 643 | } |
| 644 | head := strings.Fields(tab[0]) |
| 645 | if len(head) != 3 { |
| 646 | continue |
| 647 | } |
| 648 | entries = append(entries, Entry{Mode: head[0], Type: head[1], SHA: head[2], Name: tab[1]}) |
| 649 | } |
| 650 | return entries |
| 651 | } |
| 652 | |
| 653 | // LastCommit is de nieuwste commit die path heeft geraakt. Leeg pad is de tip. |
| 654 | func LastCommit(ctx context.Context, gitBin, dir, rev, path string) (Commit, error) { |
| 655 | if rev == "" { |
| 656 | rev = "HEAD" |
| 657 | } |
| 658 | args := []string{"-C", dir, "log", "-1", "--format=%H%x1f%an%x1f%ae%x1f%at%x1f%s", rev} |
| 659 | if path != "" { |
| 660 | args = append(args, "--", path) |
| 661 | } |
| 662 | out, err := run(ctx, gitBin, nil, args...) |
| 663 | if err != nil { |
| 664 | if emptyHistory(err) { |
| 665 | return Commit{}, nil |
| 666 | } |
| 667 | return Commit{}, err |
| 668 | } |
| 669 | line := strings.TrimSpace(out) |
| 670 | parts := strings.Split(line, "\x1f") |
| 671 | if len(parts) < 5 { |
| 672 | return Commit{}, nil |
| 673 | } |
| 674 | c := Commit{SHA: parts[0], Author: parts[1], Email: parts[2], Subject: parts[4]} |
| 675 | c.Unix, _ = strconv.ParseInt(parts[3], 10, 64) |
| 676 | if len(c.SHA) >= 10 { |
| 677 | c.Short = c.SHA[:10] |
| 678 | } |
| 679 | return c, nil |
| 680 | } |
| 681 | |
| 682 | // BlobSize is de grootte in bytes. |
| 683 | func BlobSize(ctx context.Context, gitBin, dir, rev, rel string) (int64, error) { |
| 684 | out, err := run(ctx, gitBin, nil, "-C", dir, "cat-file", "-s", rev+":"+rel) |
| 685 | if err != nil { |
| 686 | return 0, err |
| 687 | } |
| 688 | return strconv.ParseInt(strings.TrimSpace(out), 10, 64) |
| 689 | } |
| 690 | |
| 691 | // PushedCommit is een commit die met een push nieuw bereikbaar werd. |
| 692 | type PushedCommit struct { |
| 693 | SHA string |
| 694 | Email string |
| 695 | Name string |
| 696 | Unix int64 |
| 697 | } |
| 698 | |
| 699 | // CommitsSince geeft commits die newSHA bereikt en old niet. |
| 700 | // Een lege of nul-old is de hele geschiedenis van newSHA. |
| 701 | func CommitsSince(ctx context.Context, gitBin, dir, old, newSHA string) ([]PushedCommit, error) { |
| 702 | if newSHA == "" || allZero(newSHA) { |
| 703 | return nil, nil |
| 704 | } |
| 705 | args := []string{"-C", dir, "log", "--format=%H%x1f%ae%x1f%an%x1f%at", newSHA} |
| 706 | if old != "" && !allZero(old) { |
| 707 | args = append(args, "--not", old) |
| 708 | } |
| 709 | out, err := run(ctx, gitBin, nil, args...) |
| 710 | if err != nil { |
| 711 | if emptyHistory(err) { |
| 712 | return nil, nil |
| 713 | } |
| 714 | return nil, err |
| 715 | } |
| 716 | var commits []PushedCommit |
| 717 | for _, line := range strings.Split(out, "\n") { |
| 718 | line = strings.TrimSpace(line) |
| 719 | if line == "" || !strings.Contains(line, "\x1f") { |
| 720 | continue |
| 721 | } |
| 722 | parts := strings.Split(line, "\x1f") |
| 723 | if len(parts) < 4 { |
| 724 | continue |
| 725 | } |
| 726 | c := PushedCommit{SHA: parts[0], Email: parts[1], Name: parts[2]} |
| 727 | c.Unix, _ = strconv.ParseInt(parts[3], 10, 64) |
| 728 | commits = append(commits, c) |
| 729 | } |
| 730 | return commits, nil |
| 731 | } |
| 732 | |
| 733 | func allZero(sha string) bool { |
| 734 | return strings.Trim(sha, "0") == "" |
| 735 | } |
| 736 | |
| 737 | // RangeLog geeft de commits die newSHA bereikt en old niet, nieuwste eerst. |
| 738 | // Een lege of nul-old is de geschiedenis van newSHA. |
| 739 | func RangeLog(ctx context.Context, gitBin, dir, old, newSHA string) ([]Commit, error) { |
| 740 | if newSHA == "" || allZero(newSHA) { |
| 741 | return nil, nil |
| 742 | } |
| 743 | args := []string{"-C", dir, "log", "--format=%H%x1f%an%x1f%ae%x1f%ad%x1f%at%x1f%s%x1f%b%x1e", "--date=short", newSHA} |
| 744 | if old != "" && !allZero(old) { |
| 745 | args = append(args, "--not", old) |
| 746 | } |
| 747 | out, err := run(ctx, gitBin, nil, args...) |
| 748 | if err != nil { |
| 749 | if emptyHistory(err) { |
| 750 | return nil, nil |
| 751 | } |
| 752 | return nil, err |
| 753 | } |
| 754 | return parseLog(out), nil |
| 755 | } |
| 756 | |
| 757 | // BranchOfRef haalt de branch uit refs/heads/… . |
| 758 | func BranchOfRef(ref string) (string, bool) { |
| 759 | const p = "refs/heads/" |
| 760 | if strings.HasPrefix(ref, p) && len(ref) > len(p) { |
| 761 | return ref[len(p):], true |
| 762 | } |
| 763 | return "", false |
| 764 | } |
| 765 | |
| 766 | // Merge voegt source samen in target en pusht het resultaat. |
| 767 | // squash maakt één gewone commit met message in plaats van een merge-commit. |
| 768 | // De push gaat door de hook, dus role en patterns moeten kloppen. |
| 769 | func Merge(ctx context.Context, gitBin, bare, work, source, target, author, email, message string, squash bool, role access.Role, patterns []string) error { |
| 770 | repo, env, err := prepareWork(work, author, email) |
| 771 | if err != nil { |
| 772 | return classifyGit(err) |
| 773 | } |
| 774 | if _, err := run(ctx, gitBin, env, "clone", bare, repo); err != nil { |
| 775 | return classifyGit(err) |
| 776 | } |
| 777 | if _, err := run(ctx, gitBin, env, "-C", repo, "checkout", target); err != nil { |
| 778 | return classifyGit(fmt.Errorf("doelbranch %s: %w", target, err)) |
| 779 | } |
| 780 | // De kloon heeft de bron alleen als origin/<branch>, niet als lokale branch. |
| 781 | if squash { |
| 782 | if _, err := run(ctx, gitBin, env, "-C", repo, "merge", "--squash", "origin/"+source); err != nil { |
| 783 | return i18n.E("err.mergeConflict") |
| 784 | } |
| 785 | if _, err := run(ctx, gitBin, env, "-C", repo, "commit", "-m", message); err != nil { |
| 786 | return classifyGit(err) |
| 787 | } |
| 788 | } else if _, err := run(ctx, gitBin, env, "-C", repo, "merge", "--no-ff", "--no-edit", "-m", message, "origin/"+source); err != nil { |
| 789 | return i18n.E("err.mergeConflict") |
| 790 | } |
| 791 | pushEnv := append(append([]string{}, env...), PushEnv(role, patterns, nil)...) |
| 792 | if _, err := run(ctx, gitBin, pushEnv, "-C", repo, "push", "origin", target); err != nil { |
| 793 | return classifyGit(err) |
| 794 | } |
| 795 | return nil |
| 796 | } |
| 797 | |
| 798 | // Tag zet een annotated tag op sha. |
| 799 | // Tag maakt een geannoteerde tag. Een annotated tag heeft een tagger |
| 800 | // nodig; de serviceaccount heeft geen git-identiteit, dus die komt mee. |
| 801 | // Leeg valt terug op BlueGit <noreply@git.timfalken.com>. |
| 802 | func Tag(ctx context.Context, gitBin, dir, tag, sha, message, author, email string) error { |
| 803 | if strings.TrimSpace(author) == "" || strings.TrimSpace(email) == "" { |
| 804 | author, email = FallbackName, FallbackEmail |
| 805 | } |
| 806 | home, err := os.MkdirTemp("", "bluegit-tag-") |
| 807 | if err != nil { |
| 808 | return err |
| 809 | } |
| 810 | defer os.RemoveAll(home) |
| 811 | _, err = run(ctx, gitBin, CommandEnv(author, email, home, home), "-C", dir, "tag", "-a", tag, sha, "-m", message) |
| 812 | return err |
| 813 | } |
| 814 | |
| 815 | // FallbackName en FallbackEmail zijn de identiteit van BlueGit zelf. |
| 816 | const ( |
| 817 | FallbackName = "BlueGit" |
| 818 | FallbackEmail = "noreply@git.timfalken.com" |
| 819 | ) |
| 820 | |
| 821 | // DiffStat is een korte vergelijking tussen twee branches. |
| 822 | func DiffStat(ctx context.Context, gitBin, dir, target, source string) (string, error) { |
| 823 | out, err := run(ctx, gitBin, nil, "-C", dir, "log", "--oneline", target+".."+source) |
| 824 | if err != nil { |
| 825 | return "", err |
| 826 | } |
| 827 | return strings.TrimSpace(out), nil |
| 828 | } |
| 829 | |
| 830 | func run(ctx context.Context, bin string, env []string, args ...string) (string, error) { |
| 831 | if bin == "" { |
| 832 | bin = "git" |
| 833 | } |
| 834 | cmd := exec.CommandContext(ctx, bin, args...) |
| 835 | if env != nil { |
| 836 | cmd.Env = env |
| 837 | } |
| 838 | var stdout, stderr bytes.Buffer |
| 839 | cmd.Stdout = &stdout |
| 840 | cmd.Stderr = &stderr |
| 841 | if err := cmd.Run(); err != nil { |
| 842 | msg := strings.TrimSpace(stderr.String()) |
| 843 | if msg == "" { |
| 844 | msg = err.Error() |
| 845 | } |
| 846 | return "", fmt.Errorf("%s", msg) |
| 847 | } |
| 848 | return stdout.String(), nil |
| 849 | } |
| 850 | |
| 851 | // Fork maakt dir als bare kloon van src met alle branches en tags. Objecten |
| 852 | // worden lokaal gehardlinkt (geen extra schijfruimte voor bestaande objecten). |
| 853 | // Daarna dezelfde instellingen en hook als Init; de remote naar src gaat weg. |
| 854 | func Fork(gitBin, src, dir, hookBinary string) error { |
| 855 | if err := os.MkdirAll(filepath.Dir(dir), 0o755); err != nil { |
| 856 | return err |
| 857 | } |
| 858 | if _, err := run(context.Background(), gitBin, nil, "clone", "--bare", "--quiet", src, dir); err != nil { |
| 859 | return err |
| 860 | } |
| 861 | _, _ = run(context.Background(), gitBin, nil, "-C", dir, "remote", "remove", "origin") |
| 862 | for _, kv := range [][2]string{ |
| 863 | {"http.receivepack", "true"}, |
| 864 | {"http.uploadpack", "true"}, |
| 865 | {"receive.denyCurrentBranch", "ignore"}, |
| 866 | } { |
| 867 | if _, err := run(context.Background(), gitBin, nil, "-C", dir, "config", kv[0], kv[1]); err != nil { |
| 868 | return err |
| 869 | } |
| 870 | } |
| 871 | return InstallHook(dir, hookBinary) |
| 872 | } |
| 873 | |
| 874 | // ErrNotFastForward: de branch in de fork is afgeweken van upstream. |
| 875 | var ErrNotFastForward = errors.New("not fast-forward") |
| 876 | |
| 877 | // PushBranch zet branch uit src door naar dst, alleen fast-forward (geen |
| 878 | // force). De pre-receive-hook van dst controleert rechten en bescherming. |
| 879 | func PushBranch(ctx context.Context, gitBin, src, dst, branch string, env []string) error { |
| 880 | out, err := run(ctx, gitBin, env, "-C", src, "push", dst, "refs/heads/"+branch+":refs/heads/"+branch) |
| 881 | if err != nil { |
| 882 | msg := out + " " + err.Error() |
| 883 | if strings.Contains(msg, "non-fast-forward") || strings.Contains(msg, "fetch first") { |
| 884 | return ErrNotFastForward |
| 885 | } |
| 886 | return classifyGit(err) |
| 887 | } |
| 888 | return nil |
| 889 | } |
| 890 | |
| 891 | // FetchBranch haalt branch uit src op in dst als refs/heads/as (geforceerd: |
| 892 | // de spiegel volgt de bron). Een fetch draait geen hooks in dst. |
| 893 | func FetchBranch(ctx context.Context, gitBin, src, dst, branch, as string) error { |
| 894 | _, err := run(ctx, gitBin, nil, "-C", dst, "fetch", "--quiet", "--no-tags", src, "+refs/heads/"+branch+":refs/heads/"+as) |
| 895 | return err |
| 896 | } |