| 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 | return LogPage(ctx, gitBin, dir, rev, 0, limit) |
| 127 | } |
| 128 | |
| 129 | // LogPage slaat de nieuwste skip commits over en leest daarna hooguit limit commits. |
| 130 | func LogPage(ctx context.Context, gitBin, dir, rev string, skip, limit int) ([]Commit, error) { |
| 131 | if rev == "" { |
| 132 | rev = "HEAD" |
| 133 | } |
| 134 | if limit < 1 { |
| 135 | limit = 1 |
| 136 | } |
| 137 | if skip < 0 { |
| 138 | skip = 0 |
| 139 | } |
| 140 | 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)} |
| 141 | if skip > 0 { |
| 142 | args = append(args, fmt.Sprintf("--skip=%d", skip)) |
| 143 | } |
| 144 | args = append(args, rev) |
| 145 | out, err := run(ctx, gitBin, nil, args...) |
| 146 | if err != nil { |
| 147 | if strings.Contains(err.Error(), "does not have any commits") || strings.Contains(err.Error(), "bad default revision") || strings.Contains(err.Error(), "ambiguous argument") { |
| 148 | return nil, nil |
| 149 | } |
| 150 | return nil, err |
| 151 | } |
| 152 | return parseLog(out), nil |
| 153 | } |
| 154 | |
| 155 | func parseLog(out string) []Commit { |
| 156 | var commits []Commit |
| 157 | for _, rec := range strings.Split(out, "\x1e") { |
| 158 | rec = strings.TrimSpace(rec) |
| 159 | if rec == "" { |
| 160 | continue |
| 161 | } |
| 162 | parts := strings.Split(rec, "\x1f") |
| 163 | if len(parts) < 6 { |
| 164 | continue |
| 165 | } |
| 166 | c := Commit{SHA: parts[0], Author: parts[1], Email: parts[2], Date: parts[3], Subject: parts[5]} |
| 167 | c.Unix, _ = strconv.ParseInt(parts[4], 10, 64) |
| 168 | if len(c.SHA) >= 10 { |
| 169 | c.Short = c.SHA[:10] |
| 170 | } |
| 171 | if len(parts) > 6 { |
| 172 | c.Body = strings.TrimSpace(parts[6]) |
| 173 | } |
| 174 | commits = append(commits, c) |
| 175 | } |
| 176 | return commits |
| 177 | } |
| 178 | |
| 179 | // Message is een commitbericht. Merge is waar bij twee of meer ouders. |
| 180 | type Message struct { |
| 181 | Subject string |
| 182 | Body string |
| 183 | Author string |
| 184 | Email string |
| 185 | Merge bool |
| 186 | } |
| 187 | |
| 188 | // Messages leest hooguit limit berichten, oudste eerst. |
| 189 | func Messages(ctx context.Context, gitBin, dir, rev string, limit int) ([]Message, error) { |
| 190 | if rev == "" { |
| 191 | rev = "HEAD" |
| 192 | } |
| 193 | if limit < 1 { |
| 194 | limit = 1 |
| 195 | } |
| 196 | if limit > 100 { |
| 197 | limit = 100 |
| 198 | } |
| 199 | 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) |
| 200 | if err != nil { |
| 201 | if strings.Contains(err.Error(), "does not have any commits") || strings.Contains(err.Error(), "bad default revision") || strings.Contains(err.Error(), "ambiguous argument") { |
| 202 | return nil, nil |
| 203 | } |
| 204 | return nil, err |
| 205 | } |
| 206 | return parseMessages(out), nil |
| 207 | } |
| 208 | |
| 209 | func parseMessages(out string) []Message { |
| 210 | var msgs []Message |
| 211 | for _, rec := range strings.Split(out, "\x1e") { |
| 212 | rec = strings.TrimSpace(rec) |
| 213 | if rec == "" { |
| 214 | continue |
| 215 | } |
| 216 | parts := strings.Split(rec, "\x1f") |
| 217 | if len(parts) < 4 { |
| 218 | continue |
| 219 | } |
| 220 | m := Message{Author: parts[0], Email: parts[1], Subject: parts[3]} |
| 221 | m.Merge = len(strings.Fields(parts[2])) > 1 |
| 222 | if len(parts) > 4 { |
| 223 | m.Body = strings.TrimSpace(parts[4]) |
| 224 | } |
| 225 | msgs = append(msgs, m) |
| 226 | } |
| 227 | return msgs |
| 228 | } |
| 229 | |
| 230 | // Show leest één commit. |
| 231 | func Show(ctx context.Context, gitBin, dir, sha string) (Commit, error) { |
| 232 | list, err := Log(ctx, gitBin, dir, sha, 1) |
| 233 | if err != nil { |
| 234 | return Commit{}, err |
| 235 | } |
| 236 | if len(list) == 0 { |
| 237 | return Commit{}, fmt.Errorf("commit niet gevonden") |
| 238 | } |
| 239 | return list[0], nil |
| 240 | } |
| 241 | |
| 242 | // Tree leest een map. path is relatief en mag leeg zijn. |
| 243 | func Tree(ctx context.Context, gitBin, dir, rev, rel string) ([]Entry, error) { |
| 244 | spec := rev |
| 245 | if rel != "" { |
| 246 | spec = rev + ":" + rel |
| 247 | } |
| 248 | out, err := run(ctx, gitBin, nil, "-C", dir, "ls-tree", spec) |
| 249 | if err != nil { |
| 250 | return nil, err |
| 251 | } |
| 252 | var entries []Entry |
| 253 | for _, line := range strings.Split(strings.TrimSpace(out), "\n") { |
| 254 | if line == "" { |
| 255 | continue |
| 256 | } |
| 257 | // mode type sha\tname |
| 258 | tab := strings.SplitN(line, "\t", 2) |
| 259 | if len(tab) != 2 { |
| 260 | continue |
| 261 | } |
| 262 | head := strings.Fields(tab[0]) |
| 263 | if len(head) != 3 { |
| 264 | continue |
| 265 | } |
| 266 | entries = append(entries, Entry{Mode: head[0], Type: head[1], SHA: head[2], Name: tab[1]}) |
| 267 | } |
| 268 | return entries, nil |
| 269 | } |
| 270 | |
| 271 | // Blob leest een tekstbestand, afgekapt op max bytes. binary is waar als |
| 272 | // het bestand een NUL bevat. |
| 273 | func Blob(ctx context.Context, gitBin, dir, rev, rel string, max int) (text string, binary bool, err error) { |
| 274 | out, err := run(ctx, gitBin, nil, "-C", dir, "show", rev+":"+rel) |
| 275 | if err != nil { |
| 276 | return "", false, err |
| 277 | } |
| 278 | if strings.Contains(out, "\x00") { |
| 279 | return "", true, nil |
| 280 | } |
| 281 | if len(out) > max { |
| 282 | out = out[:max] + "\n… afgekapt" |
| 283 | } |
| 284 | return out, false, nil |
| 285 | } |
| 286 | |
| 287 | // Branches geeft lokale branchnamen. |
| 288 | func Branches(ctx context.Context, gitBin, dir string) ([]string, error) { |
| 289 | out, err := run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--format=%(refname:short)", "refs/heads") |
| 290 | if err != nil { |
| 291 | return nil, err |
| 292 | } |
| 293 | var names []string |
| 294 | for _, line := range strings.Split(strings.TrimSpace(out), "\n") { |
| 295 | if line != "" { |
| 296 | names = append(names, line) |
| 297 | } |
| 298 | } |
| 299 | return names, nil |
| 300 | } |
| 301 | |
| 302 | // HasCommit meldt of sha een commit in deze repository is. |
| 303 | func HasCommit(ctx context.Context, gitBin, dir, sha string) bool { |
| 304 | out, err := run(ctx, gitBin, nil, "-C", dir, "cat-file", "-t", sha) |
| 305 | return err == nil && strings.TrimSpace(out) == "commit" |
| 306 | } |
| 307 | |
| 308 | // Refs geeft refnaam → sha. |
| 309 | func Refs(ctx context.Context, gitBin, dir string) (map[string]string, error) { |
| 310 | out, err := run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--format=%(objectname) %(refname)") |
| 311 | if err != nil { |
| 312 | return nil, err |
| 313 | } |
| 314 | m := map[string]string{} |
| 315 | for _, line := range strings.Split(strings.TrimSpace(out), "\n") { |
| 316 | if line == "" { |
| 317 | continue |
| 318 | } |
| 319 | parts := strings.SplitN(line, " ", 2) |
| 320 | if len(parts) == 2 { |
| 321 | m[parts[1]] = parts[0] |
| 322 | } |
| 323 | } |
| 324 | return m, nil |
| 325 | } |
| 326 | |
| 327 | // Touch geeft per pad de nieuwste commit uit de recente geschiedenis. |
| 328 | // Mappen erven de nieuwste commit van een bestand erin. |
| 329 | func Touch(ctx context.Context, gitBin, dir, rev string) (map[string]Commit, error) { |
| 330 | if rev == "" { |
| 331 | rev = "HEAD" |
| 332 | } |
| 333 | out, err := run(ctx, gitBin, nil, "-C", dir, "log", "--format=%H%x1f%an%x1f%at%x1f%s", "--name-only", "-n", "400", rev) |
| 334 | if err != nil { |
| 335 | if emptyHistory(err) { |
| 336 | return map[string]Commit{}, nil |
| 337 | } |
| 338 | return nil, err |
| 339 | } |
| 340 | m := map[string]Commit{} |
| 341 | var cur Commit |
| 342 | have := false |
| 343 | for _, line := range strings.Split(out, "\n") { |
| 344 | if strings.Contains(line, "\x1f") { |
| 345 | parts := strings.Split(line, "\x1f") |
| 346 | if len(parts) < 4 { |
| 347 | continue |
| 348 | } |
| 349 | cur = Commit{SHA: parts[0], Author: parts[1], Subject: parts[3]} |
| 350 | cur.Unix, _ = strconv.ParseInt(parts[2], 10, 64) |
| 351 | if len(cur.SHA) >= 10 { |
| 352 | cur.Short = cur.SHA[:10] |
| 353 | } |
| 354 | have = true |
| 355 | continue |
| 356 | } |
| 357 | line = strings.TrimSpace(line) |
| 358 | if line == "" || !have { |
| 359 | continue |
| 360 | } |
| 361 | notePath(m, line, cur) |
| 362 | } |
| 363 | return m, nil |
| 364 | } |
| 365 | |
| 366 | func notePath(m map[string]Commit, path string, c Commit) { |
| 367 | for path != "" && path != "." { |
| 368 | if _, ok := m[path]; !ok { |
| 369 | m[path] = c |
| 370 | } |
| 371 | i := strings.LastIndex(path, "/") |
| 372 | if i < 0 { |
| 373 | return |
| 374 | } |
| 375 | path = path[:i] |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | func emptyHistory(err error) bool { |
| 380 | msg := err.Error() |
| 381 | return strings.Contains(msg, "does not have any commits") || strings.Contains(msg, "bad default revision") || strings.Contains(msg, "ambiguous argument") |
| 382 | } |
| 383 | |
| 384 | // Stats telt commits op rev, lokale branches en tags. |
| 385 | func Stats(ctx context.Context, gitBin, dir, rev string) (commits, branches, tags int, err error) { |
| 386 | if rev == "" { |
| 387 | rev = "HEAD" |
| 388 | } |
| 389 | out, err := run(ctx, gitBin, nil, "-C", dir, "rev-list", "--count", rev) |
| 390 | if err != nil { |
| 391 | if emptyHistory(err) { |
| 392 | return 0, 0, 0, nil |
| 393 | } |
| 394 | return 0, 0, 0, err |
| 395 | } |
| 396 | commits, _ = strconv.Atoi(strings.TrimSpace(out)) |
| 397 | names, err := Branches(ctx, gitBin, dir) |
| 398 | if err != nil { |
| 399 | return commits, 0, 0, err |
| 400 | } |
| 401 | branches = len(names) |
| 402 | out, err = run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--format=%(refname:short)", "refs/tags") |
| 403 | if err != nil { |
| 404 | return commits, branches, 0, err |
| 405 | } |
| 406 | for _, line := range strings.Split(strings.TrimSpace(out), "\n") { |
| 407 | if line != "" { |
| 408 | tags++ |
| 409 | } |
| 410 | } |
| 411 | return commits, branches, tags, nil |
| 412 | } |
| 413 | |
| 414 | // Tags geeft tagnamen. |
| 415 | func Tags(ctx context.Context, gitBin, dir string) ([]string, error) { |
| 416 | out, err := run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--format=%(refname:short)", "refs/tags") |
| 417 | if err != nil { |
| 418 | return nil, err |
| 419 | } |
| 420 | var names []string |
| 421 | for _, line := range strings.Split(strings.TrimSpace(out), "\n") { |
| 422 | if line != "" { |
| 423 | names = append(names, line) |
| 424 | } |
| 425 | } |
| 426 | return names, nil |
| 427 | } |
| 428 | |
| 429 | // TagInfo is één git-tag voor de webinterface. |
| 430 | type TagInfo struct { |
| 431 | Name string |
| 432 | Annotated bool |
| 433 | Message string |
| 434 | CommitSHA string |
| 435 | CommitSubject string |
| 436 | Unix int64 |
| 437 | } |
| 438 | |
| 439 | // ListTags geeft alle tags, nieuwste eerst. |
| 440 | func ListTags(ctx context.Context, gitBin, dir string) ([]TagInfo, error) { |
| 441 | const format = "%(refname:short)\n%(objecttype)\n%(objectname)\n%(*objectname)\n%(creatordate:unix)\n%(subject)\n%(*subject)\nBLUEGIT-END" |
| 442 | out, err := run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--sort=-creatordate", "--format="+format, "refs/tags") |
| 443 | if err != nil { |
| 444 | return nil, err |
| 445 | } |
| 446 | lines := strings.Split(out, "\n") |
| 447 | if len(lines) > 0 && lines[len(lines)-1] == "" { |
| 448 | lines = lines[:len(lines)-1] |
| 449 | } |
| 450 | var tags []TagInfo |
| 451 | for i := 0; i+7 < len(lines); i += 8 { |
| 452 | if lines[i+7] != "BLUEGIT-END" { |
| 453 | continue |
| 454 | } |
| 455 | unix, _ := strconv.ParseInt(strings.TrimSpace(lines[i+4]), 10, 64) |
| 456 | tag := TagInfo{Name: lines[i], Unix: unix} |
| 457 | if lines[i+1] == "tag" { |
| 458 | tag.Annotated = true |
| 459 | tag.CommitSHA = lines[i+3] |
| 460 | tag.CommitSubject = lines[i+6] |
| 461 | if tag.CommitSHA == "" { |
| 462 | tag.CommitSHA = lines[i+2] |
| 463 | } |
| 464 | if tag.CommitSubject == "" { |
| 465 | tag.CommitSubject = lines[i+5] |
| 466 | } |
| 467 | msg, err := run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--format=%(contents)", "refs/tags/"+tag.Name) |
| 468 | if err != nil { |
| 469 | return nil, err |
| 470 | } |
| 471 | tag.Message = strings.TrimSpace(msg) |
| 472 | } else { |
| 473 | tag.CommitSHA = lines[i+2] |
| 474 | tag.CommitSubject = lines[i+5] |
| 475 | } |
| 476 | if tag.Name != "" { |
| 477 | tags = append(tags, tag) |
| 478 | } |
| 479 | } |
| 480 | sort.SliceStable(tags, func(i, j int) bool { |
| 481 | if tags[i].Unix != tags[j].Unix { |
| 482 | return tags[i].Unix > tags[j].Unix |
| 483 | } |
| 484 | return tags[i].Name < tags[j].Name |
| 485 | }) |
| 486 | return tags, nil |
| 487 | } |
| 488 | |
| 489 | // CreateTag zet een tag op een branch of commit. Een leeg bericht blijft licht. |
| 490 | func CreateTag(ctx context.Context, gitBin, dir, name, rev, message, author, email string) error { |
| 491 | if err := names.ValidTag(name); err != nil { |
| 492 | return err |
| 493 | } |
| 494 | sha, err := resolveCommit(ctx, gitBin, dir, rev) |
| 495 | if err != nil { |
| 496 | return err |
| 497 | } |
| 498 | if HasTag(ctx, gitBin, dir, name) { |
| 499 | return i18n.E("err.tagExists", name) |
| 500 | } |
| 501 | message = strings.TrimSpace(message) |
| 502 | if len(message) > 5000 { |
| 503 | return i18n.E("err.tagLong") |
| 504 | } |
| 505 | home, err := os.MkdirTemp(dir, "home-") |
| 506 | if err != nil { |
| 507 | return classifyGit(err) |
| 508 | } |
| 509 | defer os.RemoveAll(home) |
| 510 | env := CommandEnv(author, email, home, home) |
| 511 | if message == "" { |
| 512 | _, err = run(ctx, gitBin, env, "-C", dir, "tag", name, sha) |
| 513 | return err |
| 514 | } |
| 515 | _, err = run(ctx, gitBin, env, "-C", dir, "tag", "-a", name, sha, "-m", message) |
| 516 | return err |
| 517 | } |
| 518 | |
| 519 | // DeleteTag verwijdert een bestaande tag. |
| 520 | func DeleteTag(ctx context.Context, gitBin, dir, name string) error { |
| 521 | if err := usableTag(name); err != nil { |
| 522 | return err |
| 523 | } |
| 524 | if !HasTag(ctx, gitBin, dir, name) { |
| 525 | return i18n.E("err.tagMissing", name) |
| 526 | } |
| 527 | _, err := run(ctx, gitBin, nil, "-C", dir, "tag", "-d", "--", name) |
| 528 | return err |
| 529 | } |
| 530 | |
| 531 | // HasTag meldt of refs/tags/name bestaat. |
| 532 | func HasTag(ctx context.Context, gitBin, dir, name string) bool { |
| 533 | if err := usableTag(name); err != nil { |
| 534 | return false |
| 535 | } |
| 536 | _, err := run(ctx, gitBin, nil, "-C", dir, "rev-parse", "-q", "--verify", "--end-of-options", "refs/tags/"+name) |
| 537 | return err == nil |
| 538 | } |
| 539 | |
| 540 | // Archive schrijft een zip of tar.gz van de tag naar w. |
| 541 | func Archive(ctx context.Context, w io.Writer, gitBin, dir, prefix, name, format string) error { |
| 542 | if err := usableTag(name); err != nil { |
| 543 | return err |
| 544 | } |
| 545 | if !HasTag(ctx, gitBin, dir, name) { |
| 546 | return i18n.E("err.tagMissing", name) |
| 547 | } |
| 548 | return ArchiveAt(ctx, w, gitBin, dir, prefix, name, format) |
| 549 | } |
| 550 | |
| 551 | // ArchiveAt schrijft een zip of tar.gz van een bestaande revisie. |
| 552 | // rev is een tagnaam of refs/heads/…. |
| 553 | func ArchiveAt(ctx context.Context, w io.Writer, gitBin, dir, prefix, rev, format string) error { |
| 554 | if format != "zip" && format != "tar.gz" { |
| 555 | return i18n.E("err.notFound") |
| 556 | } |
| 557 | if rev == "" || strings.HasPrefix(rev, "-") || strings.Contains(rev, "..") || strings.ContainsAny(rev, " \t\r\n\\") { |
| 558 | return i18n.E("err.notFound") |
| 559 | } |
| 560 | if gitBin == "" { |
| 561 | gitBin = "git" |
| 562 | } |
| 563 | if prefix != "" && !strings.HasSuffix(prefix, "/") { |
| 564 | prefix += "/" |
| 565 | } |
| 566 | cmd := exec.CommandContext(ctx, gitBin, "-C", dir, "archive", "--format="+format, "--prefix="+prefix, rev) |
| 567 | cmd.Stdout = w |
| 568 | var stderr bytes.Buffer |
| 569 | cmd.Stderr = &stderr |
| 570 | if err := cmd.Run(); err != nil { |
| 571 | msg := strings.TrimSpace(stderr.String()) |
| 572 | if msg == "" { |
| 573 | msg = err.Error() |
| 574 | } |
| 575 | return fmt.Errorf("%s", msg) |
| 576 | } |
| 577 | return nil |
| 578 | } |
| 579 | |
| 580 | func resolveCommit(ctx context.Context, gitBin, dir, rev string) (string, error) { |
| 581 | rev = strings.TrimSpace(rev) |
| 582 | if rev == "" || strings.HasPrefix(rev, "-") || strings.Contains(rev, "..") || strings.ContainsAny(rev, " \t\r\n\\") { |
| 583 | return "", i18n.E("err.tagRef", rev) |
| 584 | } |
| 585 | out, err := run(ctx, gitBin, nil, "-C", dir, "rev-parse", "--verify", "--end-of-options", rev+"^{commit}") |
| 586 | if err != nil { |
| 587 | return "", i18n.E("err.tagRef", rev) |
| 588 | } |
| 589 | return strings.TrimSpace(out), nil |
| 590 | } |
| 591 | |
| 592 | func usableTag(name string) error { |
| 593 | 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\\~^:?*[") { |
| 594 | return i18n.E("err.tag", name) |
| 595 | } |
| 596 | return nil |
| 597 | } |
| 598 | |
| 599 | // TreeAll leest de hele boom. Name is het pad vanaf de root. |
| 600 | func TreeAll(ctx context.Context, gitBin, dir, rev string) ([]Entry, error) { |
| 601 | if rev == "" { |
| 602 | rev = "HEAD" |
| 603 | } |
| 604 | out, err := run(ctx, gitBin, nil, "-C", dir, "ls-tree", "-r", "-t", rev) |
| 605 | if err != nil { |
| 606 | if emptyHistory(err) { |
| 607 | return nil, nil |
| 608 | } |
| 609 | return nil, err |
| 610 | } |
| 611 | return parseTree(out), nil |
| 612 | } |
| 613 | |
| 614 | func parseTree(out string) []Entry { |
| 615 | var entries []Entry |
| 616 | for _, line := range strings.Split(strings.TrimSpace(out), "\n") { |
| 617 | if line == "" { |
| 618 | continue |
| 619 | } |
| 620 | tab := strings.SplitN(line, "\t", 2) |
| 621 | if len(tab) != 2 { |
| 622 | continue |
| 623 | } |
| 624 | head := strings.Fields(tab[0]) |
| 625 | if len(head) != 3 { |
| 626 | continue |
| 627 | } |
| 628 | entries = append(entries, Entry{Mode: head[0], Type: head[1], SHA: head[2], Name: tab[1]}) |
| 629 | } |
| 630 | return entries |
| 631 | } |
| 632 | |
| 633 | // LastCommit is de nieuwste commit die path heeft geraakt. Leeg pad is de tip. |
| 634 | func LastCommit(ctx context.Context, gitBin, dir, rev, path string) (Commit, error) { |
| 635 | if rev == "" { |
| 636 | rev = "HEAD" |
| 637 | } |
| 638 | args := []string{"-C", dir, "log", "-1", "--format=%H%x1f%an%x1f%ae%x1f%at%x1f%s", rev} |
| 639 | if path != "" { |
| 640 | args = append(args, "--", path) |
| 641 | } |
| 642 | out, err := run(ctx, gitBin, nil, args...) |
| 643 | if err != nil { |
| 644 | if emptyHistory(err) { |
| 645 | return Commit{}, nil |
| 646 | } |
| 647 | return Commit{}, err |
| 648 | } |
| 649 | line := strings.TrimSpace(out) |
| 650 | parts := strings.Split(line, "\x1f") |
| 651 | if len(parts) < 5 { |
| 652 | return Commit{}, nil |
| 653 | } |
| 654 | c := Commit{SHA: parts[0], Author: parts[1], Email: parts[2], Subject: parts[4]} |
| 655 | c.Unix, _ = strconv.ParseInt(parts[3], 10, 64) |
| 656 | if len(c.SHA) >= 10 { |
| 657 | c.Short = c.SHA[:10] |
| 658 | } |
| 659 | return c, nil |
| 660 | } |
| 661 | |
| 662 | // BlobSize is de grootte in bytes. |
| 663 | func BlobSize(ctx context.Context, gitBin, dir, rev, rel string) (int64, error) { |
| 664 | out, err := run(ctx, gitBin, nil, "-C", dir, "cat-file", "-s", rev+":"+rel) |
| 665 | if err != nil { |
| 666 | return 0, err |
| 667 | } |
| 668 | return strconv.ParseInt(strings.TrimSpace(out), 10, 64) |
| 669 | } |
| 670 | |
| 671 | // PushedCommit is een commit die met een push nieuw bereikbaar werd. |
| 672 | type PushedCommit struct { |
| 673 | SHA string |
| 674 | Email string |
| 675 | Name string |
| 676 | Unix int64 |
| 677 | } |
| 678 | |
| 679 | // CommitsSince geeft commits die newSHA bereikt en old niet. |
| 680 | // Een lege of nul-old is de hele geschiedenis van newSHA. |
| 681 | func CommitsSince(ctx context.Context, gitBin, dir, old, newSHA string) ([]PushedCommit, error) { |
| 682 | if newSHA == "" || allZero(newSHA) { |
| 683 | return nil, nil |
| 684 | } |
| 685 | args := []string{"-C", dir, "log", "--format=%H%x1f%ae%x1f%an%x1f%at", newSHA} |
| 686 | if old != "" && !allZero(old) { |
| 687 | args = append(args, "--not", old) |
| 688 | } |
| 689 | out, err := run(ctx, gitBin, nil, args...) |
| 690 | if err != nil { |
| 691 | if emptyHistory(err) { |
| 692 | return nil, nil |
| 693 | } |
| 694 | return nil, err |
| 695 | } |
| 696 | var commits []PushedCommit |
| 697 | for _, line := range strings.Split(out, "\n") { |
| 698 | line = strings.TrimSpace(line) |
| 699 | if line == "" || !strings.Contains(line, "\x1f") { |
| 700 | continue |
| 701 | } |
| 702 | parts := strings.Split(line, "\x1f") |
| 703 | if len(parts) < 4 { |
| 704 | continue |
| 705 | } |
| 706 | c := PushedCommit{SHA: parts[0], Email: parts[1], Name: parts[2]} |
| 707 | c.Unix, _ = strconv.ParseInt(parts[3], 10, 64) |
| 708 | commits = append(commits, c) |
| 709 | } |
| 710 | return commits, nil |
| 711 | } |
| 712 | |
| 713 | func allZero(sha string) bool { |
| 714 | return strings.Trim(sha, "0") == "" |
| 715 | } |
| 716 | |
| 717 | // RangeLog geeft de commits die newSHA bereikt en old niet, nieuwste eerst. |
| 718 | // Een lege of nul-old is de geschiedenis van newSHA. |
| 719 | func RangeLog(ctx context.Context, gitBin, dir, old, newSHA string) ([]Commit, error) { |
| 720 | if newSHA == "" || allZero(newSHA) { |
| 721 | return nil, nil |
| 722 | } |
| 723 | args := []string{"-C", dir, "log", "--format=%H%x1f%an%x1f%ae%x1f%ad%x1f%at%x1f%s%x1f%b%x1e", "--date=short", newSHA} |
| 724 | if old != "" && !allZero(old) { |
| 725 | args = append(args, "--not", old) |
| 726 | } |
| 727 | out, err := run(ctx, gitBin, nil, args...) |
| 728 | if err != nil { |
| 729 | if emptyHistory(err) { |
| 730 | return nil, nil |
| 731 | } |
| 732 | return nil, err |
| 733 | } |
| 734 | return parseLog(out), nil |
| 735 | } |
| 736 | |
| 737 | // BranchOfRef haalt de branch uit refs/heads/… . |
| 738 | func BranchOfRef(ref string) (string, bool) { |
| 739 | const p = "refs/heads/" |
| 740 | if strings.HasPrefix(ref, p) && len(ref) > len(p) { |
| 741 | return ref[len(p):], true |
| 742 | } |
| 743 | return "", false |
| 744 | } |
| 745 | |
| 746 | // Merge voegt source samen in target en pusht het resultaat. |
| 747 | // squash maakt één gewone commit met message in plaats van een merge-commit. |
| 748 | // De push gaat door de hook, dus role en patterns moeten kloppen. |
| 749 | func Merge(ctx context.Context, gitBin, bare, work, source, target, author, email, message string, squash bool, role access.Role, patterns []string) error { |
| 750 | repo, env, err := prepareWork(work, author, email) |
| 751 | if err != nil { |
| 752 | return classifyGit(err) |
| 753 | } |
| 754 | if _, err := run(ctx, gitBin, env, "clone", bare, repo); err != nil { |
| 755 | return classifyGit(err) |
| 756 | } |
| 757 | if _, err := run(ctx, gitBin, env, "-C", repo, "checkout", target); err != nil { |
| 758 | return classifyGit(fmt.Errorf("doelbranch %s: %w", target, err)) |
| 759 | } |
| 760 | // De kloon heeft de bron alleen als origin/<branch>, niet als lokale branch. |
| 761 | if squash { |
| 762 | if _, err := run(ctx, gitBin, env, "-C", repo, "merge", "--squash", "origin/"+source); err != nil { |
| 763 | return i18n.E("err.mergeConflict") |
| 764 | } |
| 765 | if _, err := run(ctx, gitBin, env, "-C", repo, "commit", "-m", message); err != nil { |
| 766 | return classifyGit(err) |
| 767 | } |
| 768 | } else if _, err := run(ctx, gitBin, env, "-C", repo, "merge", "--no-ff", "--no-edit", "-m", message, "origin/"+source); err != nil { |
| 769 | return i18n.E("err.mergeConflict") |
| 770 | } |
| 771 | pushEnv := append(append([]string{}, env...), PushEnv(role, patterns, nil)...) |
| 772 | if _, err := run(ctx, gitBin, pushEnv, "-C", repo, "push", "origin", target); err != nil { |
| 773 | return classifyGit(err) |
| 774 | } |
| 775 | return nil |
| 776 | } |
| 777 | |
| 778 | // Tag zet een annotated tag op sha. |
| 779 | // Tag maakt een geannoteerde tag. Een annotated tag heeft een tagger |
| 780 | // nodig; de serviceaccount heeft geen git-identiteit, dus die komt mee. |
| 781 | // Leeg valt terug op BlueGit <noreply@git.timfalken.com>. |
| 782 | func Tag(ctx context.Context, gitBin, dir, tag, sha, message, author, email string) error { |
| 783 | if strings.TrimSpace(author) == "" || strings.TrimSpace(email) == "" { |
| 784 | author, email = FallbackName, FallbackEmail |
| 785 | } |
| 786 | home, err := os.MkdirTemp("", "bluegit-tag-") |
| 787 | if err != nil { |
| 788 | return err |
| 789 | } |
| 790 | defer os.RemoveAll(home) |
| 791 | _, err = run(ctx, gitBin, CommandEnv(author, email, home, home), "-C", dir, "tag", "-a", tag, sha, "-m", message) |
| 792 | return err |
| 793 | } |
| 794 | |
| 795 | // FallbackName en FallbackEmail zijn de identiteit van BlueGit zelf. |
| 796 | const ( |
| 797 | FallbackName = "BlueGit" |
| 798 | FallbackEmail = "noreply@git.timfalken.com" |
| 799 | ) |
| 800 | |
| 801 | // DiffStat is een korte vergelijking tussen twee branches. |
| 802 | func DiffStat(ctx context.Context, gitBin, dir, target, source string) (string, error) { |
| 803 | out, err := run(ctx, gitBin, nil, "-C", dir, "log", "--oneline", target+".."+source) |
| 804 | if err != nil { |
| 805 | return "", err |
| 806 | } |
| 807 | return strings.TrimSpace(out), nil |
| 808 | } |
| 809 | |
| 810 | func run(ctx context.Context, bin string, env []string, args ...string) (string, error) { |
| 811 | if bin == "" { |
| 812 | bin = "git" |
| 813 | } |
| 814 | cmd := exec.CommandContext(ctx, bin, args...) |
| 815 | if env != nil { |
| 816 | cmd.Env = env |
| 817 | } |
| 818 | var stdout, stderr bytes.Buffer |
| 819 | cmd.Stdout = &stdout |
| 820 | cmd.Stderr = &stderr |
| 821 | if err := cmd.Run(); err != nil { |
| 822 | msg := strings.TrimSpace(stderr.String()) |
| 823 | if msg == "" { |
| 824 | msg = err.Error() |
| 825 | } |
| 826 | return "", fmt.Errorf("%s", msg) |
| 827 | } |
| 828 | return stdout.String(), nil |
| 829 | } |