BlueGit

timfa bluegit

Files

bluegit / internal / gitrepo / repo.go

repo.go

feat: koppel commits aan wie ze pushte
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 3 weeks ago
Failed 6c3f521b History
repo.go 14.7 KiB Download Raw
1// Package gitrepo legt bare repositories op schijf en praat met de git-binary.
2package gitrepo
3
4import (
5 "bufio"
6 "bytes"
7 "context"
8 "fmt"
9 "io"
10 "os"
11 "os/exec"
12 "path/filepath"
13 "strconv"
14 "strings"
15
16 "gitlab.com/Timfa/bluegit/internal/access"
17)
18
19// Dir is de bare repository op de datadisk.
20func Dir(storage, owner, name string) string {
21 return filepath.Join(storage, "repos", owner, name+".git")
22}
23
24// Init maakt een lege bare repository en zet de pre-receive-hook.
25func Init(gitBin, dir, defaultBranch, hookBinary string) error {
26 if err := os.MkdirAll(filepath.Dir(dir), 0o755); err != nil {
27 return err
28 }
29 if _, err := run(context.Background(), gitBin, nil, "init", "--bare", "--initial-branch", defaultBranch, dir); err != nil {
30 return err
31 }
32 for _, kv := range [][2]string{
33 {"http.receivepack", "true"},
34 {"http.uploadpack", "true"},
35 {"receive.denyCurrentBranch", "ignore"},
36 } {
37 if _, err := run(context.Background(), gitBin, nil, "-C", dir, "config", kv[0], kv[1]); err != nil {
38 return err
39 }
40 }
41 return InstallHook(dir, hookBinary)
42}
43
44// InstallHook schrijft hooks/pre-receive. Die roept deze binary aan.
45func InstallHook(dir, hookBinary string) error {
46 if hookBinary == "" {
47 return fmt.Errorf("hook-binary ontbreekt")
48 }
49 path := filepath.Join(dir, "hooks", "pre-receive")
50 body := "#!/bin/sh\nset -eu\nexec " + shellQuote(hookBinary) + " hook pre-receive\n"
51 if err := os.WriteFile(path, []byte(body), 0o755); err != nil {
52 return err
53 }
54 return nil
55}
56
57func shellQuote(s string) string {
58 return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
59}
60
61// PushEnv zijn de variabelen die de hook leest. Zonder deze variabelen
62// weigert de hook, zodat een push buiten BlueGit om niet slaagt.
63func PushEnv(role access.Role, patterns []string) []string {
64 return []string{
65 "BLUEGIT_ROLE=" + string(role),
66 "BLUEGIT_PROTECTED=" + strings.Join(patterns, "\n"),
67 }
68}
69
70// ReadUpdates leest de regels van een pre-receive-hook.
71func ReadUpdates(r io.Reader) ([]access.RefUpdate, error) {
72 sc := bufio.NewScanner(r)
73 var out []access.RefUpdate
74 for sc.Scan() {
75 line := strings.TrimSpace(sc.Text())
76 if line == "" {
77 continue
78 }
79 parts := strings.Fields(line)
80 if len(parts) != 3 {
81 return nil, fmt.Errorf("onverwachte hookregel %q", line)
82 }
83 out = append(out, access.RefUpdate{Old: parts[0], New: parts[1], Ref: parts[2]})
84 }
85 return out, sc.Err()
86}
87
88// EvaluatePush is wat `bluegit hook pre-receive` doet.
89func EvaluatePush(role access.Role, patterns []string, r io.Reader) error {
90 if role == "" {
91 return fmt.Errorf("push geweigerd: geen BlueGit-rol")
92 }
93 ups, err := ReadUpdates(r)
94 if err != nil {
95 return err
96 }
97 return access.AuthorizeUpdates(role, patterns, ups)
98}
99
100// Commit is één commit voor de webinterface.
101type Commit struct {
102 SHA string
103 Short string
104 Author string
105 Email string
106 Date string
107 Unix int64
108 Subject string
109 Body string
110}
111
112// Entry is een bestand of map in een tree.
113type Entry struct {
114 Mode string
115 Type string
116 SHA string
117 Name string
118}
119
120// Log geeft de nieuwste commits.
121func Log(ctx context.Context, gitBin, dir, rev string, limit int) ([]Commit, error) {
122 if rev == "" {
123 rev = "HEAD"
124 }
125 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)
126 if err != nil {
127 if strings.Contains(err.Error(), "does not have any commits") || strings.Contains(err.Error(), "bad default revision") || strings.Contains(err.Error(), "ambiguous argument") {
128 return nil, nil
129 }
130 return nil, err
131 }
132 return parseLog(out), nil
133}
134
135func parseLog(out string) []Commit {
136 var commits []Commit
137 for _, rec := range strings.Split(out, "\x1e") {
138 rec = strings.TrimSpace(rec)
139 if rec == "" {
140 continue
141 }
142 parts := strings.Split(rec, "\x1f")
143 if len(parts) < 6 {
144 continue
145 }
146 c := Commit{SHA: parts[0], Author: parts[1], Email: parts[2], Date: parts[3], Subject: parts[5]}
147 c.Unix, _ = strconv.ParseInt(parts[4], 10, 64)
148 if len(c.SHA) >= 10 {
149 c.Short = c.SHA[:10]
150 }
151 if len(parts) > 6 {
152 c.Body = strings.TrimSpace(parts[6])
153 }
154 commits = append(commits, c)
155 }
156 return commits
157}
158
159// Show leest één commit.
160func Show(ctx context.Context, gitBin, dir, sha string) (Commit, error) {
161 list, err := Log(ctx, gitBin, dir, sha, 1)
162 if err != nil {
163 return Commit{}, err
164 }
165 if len(list) == 0 {
166 return Commit{}, fmt.Errorf("commit niet gevonden")
167 }
168 return list[0], nil
169}
170
171// Tree leest een map. path is relatief en mag leeg zijn.
172func Tree(ctx context.Context, gitBin, dir, rev, rel string) ([]Entry, error) {
173 spec := rev
174 if rel != "" {
175 spec = rev + ":" + rel
176 }
177 out, err := run(ctx, gitBin, nil, "-C", dir, "ls-tree", spec)
178 if err != nil {
179 return nil, err
180 }
181 var entries []Entry
182 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
183 if line == "" {
184 continue
185 }
186 // mode type sha\tname
187 tab := strings.SplitN(line, "\t", 2)
188 if len(tab) != 2 {
189 continue
190 }
191 head := strings.Fields(tab[0])
192 if len(head) != 3 {
193 continue
194 }
195 entries = append(entries, Entry{Mode: head[0], Type: head[1], SHA: head[2], Name: tab[1]})
196 }
197 return entries, nil
198}
199
200// Blob leest een tekstbestand, afgekapt op max bytes. binary is waar als
201// het bestand een NUL bevat.
202func Blob(ctx context.Context, gitBin, dir, rev, rel string, max int) (text string, binary bool, err error) {
203 out, err := run(ctx, gitBin, nil, "-C", dir, "show", rev+":"+rel)
204 if err != nil {
205 return "", false, err
206 }
207 if strings.Contains(out, "\x00") {
208 return "", true, nil
209 }
210 if len(out) > max {
211 out = out[:max] + "\n… afgekapt"
212 }
213 return out, false, nil
214}
215
216// Branches geeft lokale branchnamen.
217func Branches(ctx context.Context, gitBin, dir string) ([]string, error) {
218 out, err := run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--format=%(refname:short)", "refs/heads")
219 if err != nil {
220 return nil, err
221 }
222 var names []string
223 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
224 if line != "" {
225 names = append(names, line)
226 }
227 }
228 return names, nil
229}
230
231// HasCommit meldt of sha een commit in deze repository is.
232func HasCommit(ctx context.Context, gitBin, dir, sha string) bool {
233 out, err := run(ctx, gitBin, nil, "-C", dir, "cat-file", "-t", sha)
234 return err == nil && strings.TrimSpace(out) == "commit"
235}
236
237// Refs geeft refnaam → sha.
238func Refs(ctx context.Context, gitBin, dir string) (map[string]string, error) {
239 out, err := run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--format=%(objectname) %(refname)")
240 if err != nil {
241 return nil, err
242 }
243 m := map[string]string{}
244 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
245 if line == "" {
246 continue
247 }
248 parts := strings.SplitN(line, " ", 2)
249 if len(parts) == 2 {
250 m[parts[1]] = parts[0]
251 }
252 }
253 return m, nil
254}
255
256// Touch geeft per pad de nieuwste commit uit de recente geschiedenis.
257// Mappen erven de nieuwste commit van een bestand erin.
258func Touch(ctx context.Context, gitBin, dir, rev string) (map[string]Commit, error) {
259 if rev == "" {
260 rev = "HEAD"
261 }
262 out, err := run(ctx, gitBin, nil, "-C", dir, "log", "--format=%H%x1f%an%x1f%at%x1f%s", "--name-only", "-n", "400", rev)
263 if err != nil {
264 if emptyHistory(err) {
265 return map[string]Commit{}, nil
266 }
267 return nil, err
268 }
269 m := map[string]Commit{}
270 var cur Commit
271 have := false
272 for _, line := range strings.Split(out, "\n") {
273 if strings.Contains(line, "\x1f") {
274 parts := strings.Split(line, "\x1f")
275 if len(parts) < 4 {
276 continue
277 }
278 cur = Commit{SHA: parts[0], Author: parts[1], Subject: parts[3]}
279 cur.Unix, _ = strconv.ParseInt(parts[2], 10, 64)
280 if len(cur.SHA) >= 10 {
281 cur.Short = cur.SHA[:10]
282 }
283 have = true
284 continue
285 }
286 line = strings.TrimSpace(line)
287 if line == "" || !have {
288 continue
289 }
290 notePath(m, line, cur)
291 }
292 return m, nil
293}
294
295func notePath(m map[string]Commit, path string, c Commit) {
296 for path != "" && path != "." {
297 if _, ok := m[path]; !ok {
298 m[path] = c
299 }
300 i := strings.LastIndex(path, "/")
301 if i < 0 {
302 return
303 }
304 path = path[:i]
305 }
306}
307
308func emptyHistory(err error) bool {
309 msg := err.Error()
310 return strings.Contains(msg, "does not have any commits") || strings.Contains(msg, "bad default revision") || strings.Contains(msg, "ambiguous argument")
311}
312
313// Stats telt commits op rev, lokale branches en tags.
314func Stats(ctx context.Context, gitBin, dir, rev string) (commits, branches, tags int, err error) {
315 if rev == "" {
316 rev = "HEAD"
317 }
318 out, err := run(ctx, gitBin, nil, "-C", dir, "rev-list", "--count", rev)
319 if err != nil {
320 if emptyHistory(err) {
321 return 0, 0, 0, nil
322 }
323 return 0, 0, 0, err
324 }
325 commits, _ = strconv.Atoi(strings.TrimSpace(out))
326 names, err := Branches(ctx, gitBin, dir)
327 if err != nil {
328 return commits, 0, 0, err
329 }
330 branches = len(names)
331 out, err = run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--format=%(refname:short)", "refs/tags")
332 if err != nil {
333 return commits, branches, 0, err
334 }
335 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
336 if line != "" {
337 tags++
338 }
339 }
340 return commits, branches, tags, nil
341}
342
343// Tags geeft tagnamen.
344func Tags(ctx context.Context, gitBin, dir string) ([]string, error) {
345 out, err := run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--format=%(refname:short)", "refs/tags")
346 if err != nil {
347 return nil, err
348 }
349 var names []string
350 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
351 if line != "" {
352 names = append(names, line)
353 }
354 }
355 return names, nil
356}
357
358// TreeAll leest de hele boom. Name is het pad vanaf de root.
359func TreeAll(ctx context.Context, gitBin, dir, rev string) ([]Entry, error) {
360 if rev == "" {
361 rev = "HEAD"
362 }
363 out, err := run(ctx, gitBin, nil, "-C", dir, "ls-tree", "-r", "-t", rev)
364 if err != nil {
365 if emptyHistory(err) {
366 return nil, nil
367 }
368 return nil, err
369 }
370 return parseTree(out), nil
371}
372
373func parseTree(out string) []Entry {
374 var entries []Entry
375 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
376 if line == "" {
377 continue
378 }
379 tab := strings.SplitN(line, "\t", 2)
380 if len(tab) != 2 {
381 continue
382 }
383 head := strings.Fields(tab[0])
384 if len(head) != 3 {
385 continue
386 }
387 entries = append(entries, Entry{Mode: head[0], Type: head[1], SHA: head[2], Name: tab[1]})
388 }
389 return entries
390}
391
392// LastCommit is de nieuwste commit die path heeft geraakt. Leeg pad is de tip.
393func LastCommit(ctx context.Context, gitBin, dir, rev, path string) (Commit, error) {
394 if rev == "" {
395 rev = "HEAD"
396 }
397 args := []string{"-C", dir, "log", "-1", "--format=%H%x1f%an%x1f%ae%x1f%at%x1f%s", rev}
398 if path != "" {
399 args = append(args, "--", path)
400 }
401 out, err := run(ctx, gitBin, nil, args...)
402 if err != nil {
403 if emptyHistory(err) {
404 return Commit{}, nil
405 }
406 return Commit{}, err
407 }
408 line := strings.TrimSpace(out)
409 parts := strings.Split(line, "\x1f")
410 if len(parts) < 5 {
411 return Commit{}, nil
412 }
413 c := Commit{SHA: parts[0], Author: parts[1], Email: parts[2], Subject: parts[4]}
414 c.Unix, _ = strconv.ParseInt(parts[3], 10, 64)
415 if len(c.SHA) >= 10 {
416 c.Short = c.SHA[:10]
417 }
418 return c, nil
419}
420
421// BlobSize is de grootte in bytes.
422func BlobSize(ctx context.Context, gitBin, dir, rev, rel string) (int64, error) {
423 out, err := run(ctx, gitBin, nil, "-C", dir, "cat-file", "-s", rev+":"+rel)
424 if err != nil {
425 return 0, err
426 }
427 return strconv.ParseInt(strings.TrimSpace(out), 10, 64)
428}
429
430// PushedCommit is een commit die met een push nieuw bereikbaar werd.
431type PushedCommit struct {
432 SHA string
433 Email string
434 Name string
435 Unix int64
436}
437
438// CommitsSince geeft commits die newSHA bereikt en old niet.
439// Een lege of nul-old is de hele geschiedenis van newSHA.
440func CommitsSince(ctx context.Context, gitBin, dir, old, newSHA string) ([]PushedCommit, error) {
441 if newSHA == "" || allZero(newSHA) {
442 return nil, nil
443 }
444 args := []string{"-C", dir, "log", "--format=%H%x1f%ae%x1f%an%x1f%at", newSHA}
445 if old != "" && !allZero(old) {
446 args = append(args, "--not", old)
447 }
448 out, err := run(ctx, gitBin, nil, args...)
449 if err != nil {
450 if emptyHistory(err) {
451 return nil, nil
452 }
453 return nil, err
454 }
455 var commits []PushedCommit
456 for _, line := range strings.Split(out, "\n") {
457 line = strings.TrimSpace(line)
458 if line == "" || !strings.Contains(line, "\x1f") {
459 continue
460 }
461 parts := strings.Split(line, "\x1f")
462 if len(parts) < 4 {
463 continue
464 }
465 c := PushedCommit{SHA: parts[0], Email: parts[1], Name: parts[2]}
466 c.Unix, _ = strconv.ParseInt(parts[3], 10, 64)
467 commits = append(commits, c)
468 }
469 return commits, nil
470}
471
472func allZero(sha string) bool {
473 return strings.Trim(sha, "0") == ""
474}
475
476// BranchOfRef haalt de branch uit refs/heads/… .
477func BranchOfRef(ref string) (string, bool) {
478 const p = "refs/heads/"
479 if strings.HasPrefix(ref, p) && len(ref) > len(p) {
480 return ref[len(p):], true
481 }
482 return "", false
483}
484
485// Merge voegt source samen in target en pusht het resultaat.
486// De push gaat door de hook, dus role en patterns moeten kloppen.
487func Merge(ctx context.Context, gitBin, bare, work, source, target, author, email, message string, role access.Role, patterns []string) error {
488 if err := os.RemoveAll(work); err != nil {
489 return err
490 }
491 if err := os.MkdirAll(filepath.Dir(work), 0o755); err != nil {
492 return err
493 }
494 if _, err := run(ctx, gitBin, nil, "clone", bare, work); err != nil {
495 return err
496 }
497 env := append(os.Environ(),
498 "GIT_AUTHOR_NAME="+author,
499 "GIT_AUTHOR_EMAIL="+email,
500 "GIT_COMMITTER_NAME="+author,
501 "GIT_COMMITTER_EMAIL="+email,
502 )
503 if _, err := run(ctx, gitBin, env, "-C", work, "checkout", target); err != nil {
504 return fmt.Errorf("doelbranch %s: %w", target, err)
505 }
506 if _, err := run(ctx, gitBin, env, "-C", work, "merge", "--no-ff", "--no-edit", "-m", message, source); err != nil {
507 return fmt.Errorf("samenvoegen lukt niet, er is een conflict of de branch ontbreekt")
508 }
509 pushEnv := append(env, PushEnv(role, patterns)...)
510 if _, err := run(ctx, gitBin, pushEnv, "-C", work, "push", "origin", target); err != nil {
511 return err
512 }
513 return nil
514}
515
516// Tag zet een annotated tag op sha.
517func Tag(ctx context.Context, gitBin, dir, tag, sha, message string) error {
518 _, err := run(ctx, gitBin, nil, "-C", dir, "tag", "-a", tag, sha, "-m", message)
519 return err
520}
521
522// DiffStat is een korte vergelijking tussen twee branches.
523func DiffStat(ctx context.Context, gitBin, dir, target, source string) (string, error) {
524 out, err := run(ctx, gitBin, nil, "-C", dir, "log", "--oneline", target+".."+source)
525 if err != nil {
526 return "", err
527 }
528 return strings.TrimSpace(out), nil
529}
530
531func run(ctx context.Context, bin string, env []string, args ...string) (string, error) {
532 if bin == "" {
533 bin = "git"
534 }
535 cmd := exec.CommandContext(ctx, bin, args...)
536 if env != nil {
537 cmd.Env = env
538 }
539 var stdout, stderr bytes.Buffer
540 cmd.Stdout = &stdout
541 cmd.Stderr = &stderr
542 if err := cmd.Run(); err != nil {
543 msg := strings.TrimSpace(stderr.String())
544 if msg == "" {
545 msg = err.Error()
546 }
547 return "", fmt.Errorf("%s", msg)
548 }
549 return stdout.String(), nil
550}