BlueGit

timfa bluegit

Files

bluegit / internal / gitrepo / repo.go

repo.go

feat: activiteitsheatmap op dashboard, groep en repository
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 4 weeks ago
Failed d5433bc7 History
repo.go 14.6 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 Date string
106 Unix int64
107 Subject string
108 Body string
109}
110
111// Entry is een bestand of map in een tree.
112type Entry struct {
113 Mode string
114 Type string
115 SHA string
116 Name string
117}
118
119// Log geeft de nieuwste commits.
120func Log(ctx context.Context, gitBin, dir, rev string, limit int) ([]Commit, error) {
121 if rev == "" {
122 rev = "HEAD"
123 }
124 out, err := run(ctx, gitBin, nil, "-C", dir, "log", "--format=%H%x1f%an%x1f%ad%x1f%at%x1f%s%x1f%b%x1e", "--date=short", fmt.Sprintf("-n%d", limit), rev)
125 if err != nil {
126 if strings.Contains(err.Error(), "does not have any commits") || strings.Contains(err.Error(), "bad default revision") || strings.Contains(err.Error(), "ambiguous argument") {
127 return nil, nil
128 }
129 return nil, err
130 }
131 return parseLog(out), nil
132}
133
134func parseLog(out string) []Commit {
135 var commits []Commit
136 for _, rec := range strings.Split(out, "\x1e") {
137 rec = strings.TrimSpace(rec)
138 if rec == "" {
139 continue
140 }
141 parts := strings.Split(rec, "\x1f")
142 if len(parts) < 5 {
143 continue
144 }
145 c := Commit{SHA: parts[0], Author: parts[1], Date: parts[2], Subject: parts[4]}
146 c.Unix, _ = strconv.ParseInt(parts[3], 10, 64)
147 if len(c.SHA) >= 10 {
148 c.Short = c.SHA[:10]
149 }
150 if len(parts) > 5 {
151 c.Body = strings.TrimSpace(parts[5])
152 }
153 commits = append(commits, c)
154 }
155 return commits
156}
157
158// Show leest één commit.
159func Show(ctx context.Context, gitBin, dir, sha string) (Commit, error) {
160 list, err := Log(ctx, gitBin, dir, sha, 1)
161 if err != nil {
162 return Commit{}, err
163 }
164 if len(list) == 0 {
165 return Commit{}, fmt.Errorf("commit niet gevonden")
166 }
167 return list[0], nil
168}
169
170// Tree leest een map. path is relatief en mag leeg zijn.
171func Tree(ctx context.Context, gitBin, dir, rev, rel string) ([]Entry, error) {
172 spec := rev
173 if rel != "" {
174 spec = rev + ":" + rel
175 }
176 out, err := run(ctx, gitBin, nil, "-C", dir, "ls-tree", spec)
177 if err != nil {
178 return nil, err
179 }
180 var entries []Entry
181 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
182 if line == "" {
183 continue
184 }
185 // mode type sha\tname
186 tab := strings.SplitN(line, "\t", 2)
187 if len(tab) != 2 {
188 continue
189 }
190 head := strings.Fields(tab[0])
191 if len(head) != 3 {
192 continue
193 }
194 entries = append(entries, Entry{Mode: head[0], Type: head[1], SHA: head[2], Name: tab[1]})
195 }
196 return entries, nil
197}
198
199// Blob leest een tekstbestand, afgekapt op max bytes. binary is waar als
200// het bestand een NUL bevat.
201func Blob(ctx context.Context, gitBin, dir, rev, rel string, max int) (text string, binary bool, err error) {
202 out, err := run(ctx, gitBin, nil, "-C", dir, "show", rev+":"+rel)
203 if err != nil {
204 return "", false, err
205 }
206 if strings.Contains(out, "\x00") {
207 return "", true, nil
208 }
209 if len(out) > max {
210 out = out[:max] + "\n… afgekapt"
211 }
212 return out, false, nil
213}
214
215// Branches geeft lokale branchnamen.
216func Branches(ctx context.Context, gitBin, dir string) ([]string, error) {
217 out, err := run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--format=%(refname:short)", "refs/heads")
218 if err != nil {
219 return nil, err
220 }
221 var names []string
222 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
223 if line != "" {
224 names = append(names, line)
225 }
226 }
227 return names, nil
228}
229
230// HasCommit meldt of sha een commit in deze repository is.
231func HasCommit(ctx context.Context, gitBin, dir, sha string) bool {
232 out, err := run(ctx, gitBin, nil, "-C", dir, "cat-file", "-t", sha)
233 return err == nil && strings.TrimSpace(out) == "commit"
234}
235
236// Refs geeft refnaam → sha.
237func Refs(ctx context.Context, gitBin, dir string) (map[string]string, error) {
238 out, err := run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--format=%(objectname) %(refname)")
239 if err != nil {
240 return nil, err
241 }
242 m := map[string]string{}
243 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
244 if line == "" {
245 continue
246 }
247 parts := strings.SplitN(line, " ", 2)
248 if len(parts) == 2 {
249 m[parts[1]] = parts[0]
250 }
251 }
252 return m, nil
253}
254
255// Touch geeft per pad de nieuwste commit uit de recente geschiedenis.
256// Mappen erven de nieuwste commit van een bestand erin.
257func Touch(ctx context.Context, gitBin, dir, rev string) (map[string]Commit, error) {
258 if rev == "" {
259 rev = "HEAD"
260 }
261 out, err := run(ctx, gitBin, nil, "-C", dir, "log", "--format=%H%x1f%an%x1f%at%x1f%s", "--name-only", "-n", "400", rev)
262 if err != nil {
263 if emptyHistory(err) {
264 return map[string]Commit{}, nil
265 }
266 return nil, err
267 }
268 m := map[string]Commit{}
269 var cur Commit
270 have := false
271 for _, line := range strings.Split(out, "\n") {
272 if strings.Contains(line, "\x1f") {
273 parts := strings.Split(line, "\x1f")
274 if len(parts) < 4 {
275 continue
276 }
277 cur = Commit{SHA: parts[0], Author: parts[1], Subject: parts[3]}
278 cur.Unix, _ = strconv.ParseInt(parts[2], 10, 64)
279 if len(cur.SHA) >= 10 {
280 cur.Short = cur.SHA[:10]
281 }
282 have = true
283 continue
284 }
285 line = strings.TrimSpace(line)
286 if line == "" || !have {
287 continue
288 }
289 notePath(m, line, cur)
290 }
291 return m, nil
292}
293
294func notePath(m map[string]Commit, path string, c Commit) {
295 for path != "" && path != "." {
296 if _, ok := m[path]; !ok {
297 m[path] = c
298 }
299 i := strings.LastIndex(path, "/")
300 if i < 0 {
301 return
302 }
303 path = path[:i]
304 }
305}
306
307func emptyHistory(err error) bool {
308 msg := err.Error()
309 return strings.Contains(msg, "does not have any commits") || strings.Contains(msg, "bad default revision") || strings.Contains(msg, "ambiguous argument")
310}
311
312// Stats telt commits op rev, lokale branches en tags.
313func Stats(ctx context.Context, gitBin, dir, rev string) (commits, branches, tags int, err error) {
314 if rev == "" {
315 rev = "HEAD"
316 }
317 out, err := run(ctx, gitBin, nil, "-C", dir, "rev-list", "--count", rev)
318 if err != nil {
319 if emptyHistory(err) {
320 return 0, 0, 0, nil
321 }
322 return 0, 0, 0, err
323 }
324 commits, _ = strconv.Atoi(strings.TrimSpace(out))
325 names, err := Branches(ctx, gitBin, dir)
326 if err != nil {
327 return commits, 0, 0, err
328 }
329 branches = len(names)
330 out, err = run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--format=%(refname:short)", "refs/tags")
331 if err != nil {
332 return commits, branches, 0, err
333 }
334 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
335 if line != "" {
336 tags++
337 }
338 }
339 return commits, branches, tags, nil
340}
341
342// Tags geeft tagnamen.
343func Tags(ctx context.Context, gitBin, dir string) ([]string, error) {
344 out, err := run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--format=%(refname:short)", "refs/tags")
345 if err != nil {
346 return nil, err
347 }
348 var names []string
349 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
350 if line != "" {
351 names = append(names, line)
352 }
353 }
354 return names, nil
355}
356
357// TreeAll leest de hele boom. Name is het pad vanaf de root.
358func TreeAll(ctx context.Context, gitBin, dir, rev string) ([]Entry, error) {
359 if rev == "" {
360 rev = "HEAD"
361 }
362 out, err := run(ctx, gitBin, nil, "-C", dir, "ls-tree", "-r", "-t", rev)
363 if err != nil {
364 if emptyHistory(err) {
365 return nil, nil
366 }
367 return nil, err
368 }
369 return parseTree(out), nil
370}
371
372func parseTree(out string) []Entry {
373 var entries []Entry
374 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
375 if line == "" {
376 continue
377 }
378 tab := strings.SplitN(line, "\t", 2)
379 if len(tab) != 2 {
380 continue
381 }
382 head := strings.Fields(tab[0])
383 if len(head) != 3 {
384 continue
385 }
386 entries = append(entries, Entry{Mode: head[0], Type: head[1], SHA: head[2], Name: tab[1]})
387 }
388 return entries
389}
390
391// LastCommit is de nieuwste commit die path heeft geraakt. Leeg pad is de tip.
392func LastCommit(ctx context.Context, gitBin, dir, rev, path string) (Commit, error) {
393 if rev == "" {
394 rev = "HEAD"
395 }
396 args := []string{"-C", dir, "log", "-1", "--format=%H%x1f%an%x1f%at%x1f%s", rev}
397 if path != "" {
398 args = append(args, "--", path)
399 }
400 out, err := run(ctx, gitBin, nil, args...)
401 if err != nil {
402 if emptyHistory(err) {
403 return Commit{}, nil
404 }
405 return Commit{}, err
406 }
407 line := strings.TrimSpace(out)
408 parts := strings.Split(line, "\x1f")
409 if len(parts) < 4 {
410 return Commit{}, nil
411 }
412 c := Commit{SHA: parts[0], Author: parts[1], Subject: parts[3]}
413 c.Unix, _ = strconv.ParseInt(parts[2], 10, 64)
414 if len(c.SHA) >= 10 {
415 c.Short = c.SHA[:10]
416 }
417 return c, nil
418}
419
420// BlobSize is de grootte in bytes.
421func BlobSize(ctx context.Context, gitBin, dir, rev, rel string) (int64, error) {
422 out, err := run(ctx, gitBin, nil, "-C", dir, "cat-file", "-s", rev+":"+rel)
423 if err != nil {
424 return 0, err
425 }
426 return strconv.ParseInt(strings.TrimSpace(out), 10, 64)
427}
428
429// PushedCommit is een commit die met een push nieuw bereikbaar werd.
430type PushedCommit struct {
431 SHA string
432 Email string
433 Name string
434 Unix int64
435}
436
437// CommitsSince geeft commits die newSHA bereikt en old niet.
438// Een lege of nul-old is de hele geschiedenis van newSHA.
439func CommitsSince(ctx context.Context, gitBin, dir, old, newSHA string) ([]PushedCommit, error) {
440 if newSHA == "" || allZero(newSHA) {
441 return nil, nil
442 }
443 args := []string{"-C", dir, "log", "--format=%H%x1f%ae%x1f%an%x1f%at", newSHA}
444 if old != "" && !allZero(old) {
445 args = append(args, "--not", old)
446 }
447 out, err := run(ctx, gitBin, nil, args...)
448 if err != nil {
449 if emptyHistory(err) {
450 return nil, nil
451 }
452 return nil, err
453 }
454 var commits []PushedCommit
455 for _, line := range strings.Split(out, "\n") {
456 line = strings.TrimSpace(line)
457 if line == "" || !strings.Contains(line, "\x1f") {
458 continue
459 }
460 parts := strings.Split(line, "\x1f")
461 if len(parts) < 4 {
462 continue
463 }
464 c := PushedCommit{SHA: parts[0], Email: parts[1], Name: parts[2]}
465 c.Unix, _ = strconv.ParseInt(parts[3], 10, 64)
466 commits = append(commits, c)
467 }
468 return commits, nil
469}
470
471func allZero(sha string) bool {
472 return strings.Trim(sha, "0") == ""
473}
474
475// BranchOfRef haalt de branch uit refs/heads/… .
476func BranchOfRef(ref string) (string, bool) {
477 const p = "refs/heads/"
478 if strings.HasPrefix(ref, p) && len(ref) > len(p) {
479 return ref[len(p):], true
480 }
481 return "", false
482}
483
484// Merge voegt source samen in target en pusht het resultaat.
485// De push gaat door de hook, dus role en patterns moeten kloppen.
486func Merge(ctx context.Context, gitBin, bare, work, source, target, author, email, message string, role access.Role, patterns []string) error {
487 if err := os.RemoveAll(work); err != nil {
488 return err
489 }
490 if err := os.MkdirAll(filepath.Dir(work), 0o755); err != nil {
491 return err
492 }
493 if _, err := run(ctx, gitBin, nil, "clone", bare, work); err != nil {
494 return err
495 }
496 env := append(os.Environ(),
497 "GIT_AUTHOR_NAME="+author,
498 "GIT_AUTHOR_EMAIL="+email,
499 "GIT_COMMITTER_NAME="+author,
500 "GIT_COMMITTER_EMAIL="+email,
501 )
502 if _, err := run(ctx, gitBin, env, "-C", work, "checkout", target); err != nil {
503 return fmt.Errorf("doelbranch %s: %w", target, err)
504 }
505 if _, err := run(ctx, gitBin, env, "-C", work, "merge", "--no-ff", "--no-edit", "-m", message, source); err != nil {
506 return fmt.Errorf("samenvoegen lukt niet, er is een conflict of de branch ontbreekt")
507 }
508 pushEnv := append(env, PushEnv(role, patterns)...)
509 if _, err := run(ctx, gitBin, pushEnv, "-C", work, "push", "origin", target); err != nil {
510 return err
511 }
512 return nil
513}
514
515// Tag zet een annotated tag op sha.
516func Tag(ctx context.Context, gitBin, dir, tag, sha, message string) error {
517 _, err := run(ctx, gitBin, nil, "-C", dir, "tag", "-a", tag, sha, "-m", message)
518 return err
519}
520
521// DiffStat is een korte vergelijking tussen twee branches.
522func DiffStat(ctx context.Context, gitBin, dir, target, source string) (string, error) {
523 out, err := run(ctx, gitBin, nil, "-C", dir, "log", "--oneline", target+".."+source)
524 if err != nil {
525 return "", err
526 }
527 return strings.TrimSpace(out), nil
528}
529
530func run(ctx context.Context, bin string, env []string, args ...string) (string, error) {
531 if bin == "" {
532 bin = "git"
533 }
534 cmd := exec.CommandContext(ctx, bin, args...)
535 if env != nil {
536 cmd.Env = env
537 }
538 var stdout, stderr bytes.Buffer
539 cmd.Stdout = &stdout
540 cmd.Stderr = &stderr
541 if err := cmd.Run(); err != nil {
542 msg := strings.TrimSpace(stderr.String())
543 if msg == "" {
544 msg = err.Error()
545 }
546 return "", fmt.Errorf("%s", msg)
547 }
548 return stdout.String(), nil
549}