BlueGit

timfa bluegit

feat: toon een commit zoals GitLab

De commitpagina toont auteur, hash, parents en pipeline, plus een
bestandsboom en inklapbare diffs met regelnummers en twee weergaven.

Co-authored-by: tim <tim@timfalken.com>

timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa

Authored 2026-10-22 · 3 weeks ago

Hash
dc9d9b261e54860544dfe214e4c270d817df5597
Parent
a6677fb6
13 files changed +1299 −20
internal/gitrepo/patch.go added +198 −0
@@ -0,0 +1,198 @@
1 package gitrepo
2
3 import (
4 "context"
5 "strconv"
6 "strings"
7 )
8
9 // PatchFile is één bestand in de diff van een commit tegen zijn eerste parent.
10 // Een root-commit wordt vergeleken met de lege boom.
11 type PatchFile struct {
12 Status string
13 Path string
14 OldPath string
15 Added int
16 Deleted int
17 Binary bool
18 Lines []DiffLine
19 }
20
21 // CommitPatch leest de parents en de diff van sha.
22 // Een mergecommit wordt tegen de eerste parent gezet.
23 func CommitPatch(ctx context.Context, gitBin, dir, sha string) (parents []string, files []PatchFile, err error) {
24 out, err := run(ctx, gitBin, nil, "-C", dir, "rev-list", "--parents", "-n", "1", sha)
25 if err != nil {
26 return nil, nil, err
27 }
28 fields := strings.Fields(out)
29 if len(fields) == 0 {
30 return nil, nil, err
31 }
32 if len(fields) > 1 {
33 parents = append([]string(nil), fields[1:]...)
34 }
35 base := ""
36 if len(parents) > 0 {
37 base = parents[0]
38 } else {
39 empty, err := run(ctx, gitBin, nil, "hash-object", "-t", "tree", "--stdin")
40 if err != nil {
41 return nil, nil, err
42 }
43 base = strings.TrimSpace(empty)
44 }
45 raw, err := runAllow(ctx, gitBin, nil, 1, "-c", "core.quotepath=false", "-C", dir, "diff", "--no-color", "--find-renames", "--unified=3", base, sha)
46 if err != nil {
47 return nil, nil, err
48 }
49 return parents, ParsePatch(raw), nil
50 }
51
52 // ParsePatch leest de tekst van git diff, inclusief hernoemen en binaire bestanden.
53 func ParsePatch(raw string) []PatchFile {
54 var files []PatchFile
55 var cur *PatchFile
56 var oldGuess, newGuess string
57 var oldLine, newLine int
58 inHunk := false
59 skipBinary := false
60 for _, line := range strings.Split(raw, "\n") {
61 switch {
62 case strings.HasPrefix(line, "diff --git "):
63 files = append(files, PatchFile{Status: "modified"})
64 cur = &files[len(files)-1]
65 oldGuess, newGuess = splitDiffPaths(line)
66 cur.Path = newGuess
67 oldLine, newLine = 0, 0
68 inHunk = false
69 skipBinary = false
70 case cur == nil || skipBinary:
71 continue
72 case strings.HasPrefix(line, "new file mode "):
73 cur.Status = "added"
74 case strings.HasPrefix(line, "deleted file mode "):
75 cur.Status = "deleted"
76 if oldGuess != "" {
77 cur.Path = oldGuess
78 }
79 case strings.HasPrefix(line, "rename from ") || strings.HasPrefix(line, "copy from "):
80 cur.Status = "renamed"
81 cur.OldPath = metaPath(line)
82 case strings.HasPrefix(line, "rename to ") || strings.HasPrefix(line, "copy to "):
83 cur.Status = "renamed"
84 if p := metaPath(line); p != "" {
85 cur.Path = p
86 }
87 case strings.HasPrefix(line, "Binary files ") || strings.HasPrefix(line, "GIT binary patch"):
88 cur.Binary = true
89 cur.Lines = nil
90 cur.Added, cur.Deleted = 0, 0
91 skipBinary = true
92 inHunk = false
93 case strings.HasPrefix(line, "@@"):
94 oldLine, newLine = hunkStart(line)
95 oldLine--
96 newLine--
97 inHunk = true
98 cur.Lines = append(cur.Lines, DiffLine{Kind: "hunk", Text: line})
99 case !inHunk:
100 continue
101 case strings.HasPrefix(line, `\`):
102 continue
103 case strings.HasPrefix(line, "+"):
104 newLine++
105 cur.Added++
106 cur.Lines = append(cur.Lines, DiffLine{Kind: "add", New: newLine, Text: line[1:]})
107 case strings.HasPrefix(line, "-"):
108 oldLine++
109 cur.Deleted++
110 cur.Lines = append(cur.Lines, DiffLine{Kind: "del", Old: oldLine, Text: line[1:]})
111 case strings.HasPrefix(line, " "):
112 oldLine++
113 newLine++
114 cur.Lines = append(cur.Lines, DiffLine{Kind: "ctx", Old: oldLine, New: newLine, Text: line[1:]})
115 }
116 }
117 var out []PatchFile
118 for _, f := range files {
119 if f.Path == "" {
120 continue
121 }
122 if f.Status != "renamed" {
123 f.OldPath = ""
124 }
125 out = append(out, f)
126 }
127 return out
128 }
129
130 func splitDiffPaths(line string) (oldPath, newPath string) {
131 rest := strings.TrimSpace(strings.TrimPrefix(line, "diff --git "))
132 a, b, ok := splitQuotedPair(rest)
133 if !ok {
134 return "", ""
135 }
136 return stripAB(a), stripAB(b)
137 }
138
139 func splitQuotedPair(s string) (string, string, bool) {
140 s = strings.TrimSpace(s)
141 if s == "" {
142 return "", "", false
143 }
144 if strings.HasPrefix(s, `"`) {
145 a, rest, ok := unquotePrefix(s)
146 if !ok {
147 return "", "", false
148 }
149 rest = strings.TrimSpace(rest)
150 if strings.HasPrefix(rest, `"`) {
151 b, _, ok := unquotePrefix(rest)
152 return a, b, ok
153 }
154 return a, rest, rest != ""
155 }
156 i := strings.Index(s, " b/")
157 if i < 0 {
158 return "", "", false
159 }
160 return s[:i], s[i+1:], true
161 }
162
163 func unquotePrefix(s string) (string, string, bool) {
164 if len(s) < 2 || s[0] != '"' {
165 return "", "", false
166 }
167 for i := 1; i < len(s); i++ {
168 if s[i] == '\\' {
169 i++
170 continue
171 }
172 if s[i] == '"' {
173 u, err := strconv.Unquote(s[:i+1])
174 if err != nil {
175 return "", "", false
176 }
177 return u, s[i+1:], true
178 }
179 }
180 return "", "", false
181 }
182
183 func metaPath(line string) string {
184 if i := strings.IndexByte(line, ' '); i >= 0 {
185 line = line[i+1:]
186 }
187 // "rename from pad" heeft twee spaties in het commando.
188 if i := strings.IndexByte(line, ' '); i >= 0 && !strings.HasPrefix(line, `"`) && (strings.HasPrefix(line, "from ") || strings.HasPrefix(line, "to ")) {
189 line = line[i+1:]
190 }
191 line = strings.TrimSpace(line)
192 if strings.HasPrefix(line, `"`) {
193 if u, err := strconv.Unquote(line); err == nil {
194 return u
195 }
196 }
197 return line
198 }
@@ -0,0 +1,198 @@
1package gitrepo
2
3import (
4 "context"
5 "strconv"
6 "strings"
7)
8
9// PatchFile is één bestand in de diff van een commit tegen zijn eerste parent.
10// Een root-commit wordt vergeleken met de lege boom.
11type PatchFile struct {
12 Status string
13 Path string
14 OldPath string
15 Added int
16 Deleted int
17 Binary bool
18 Lines []DiffLine
19}
20
21// CommitPatch leest de parents en de diff van sha.
22// Een mergecommit wordt tegen de eerste parent gezet.
23func CommitPatch(ctx context.Context, gitBin, dir, sha string) (parents []string, files []PatchFile, err error) {
24 out, err := run(ctx, gitBin, nil, "-C", dir, "rev-list", "--parents", "-n", "1", sha)
25 if err != nil {
26 return nil, nil, err
27 }
28 fields := strings.Fields(out)
29 if len(fields) == 0 {
30 return nil, nil, err
31 }
32 if len(fields) > 1 {
33 parents = append([]string(nil), fields[1:]...)
34 }
35 base := ""
36 if len(parents) > 0 {
37 base = parents[0]
38 } else {
39 empty, err := run(ctx, gitBin, nil, "hash-object", "-t", "tree", "--stdin")
40 if err != nil {
41 return nil, nil, err
42 }
43 base = strings.TrimSpace(empty)
44 }
45 raw, err := runAllow(ctx, gitBin, nil, 1, "-c", "core.quotepath=false", "-C", dir, "diff", "--no-color", "--find-renames", "--unified=3", base, sha)
46 if err != nil {
47 return nil, nil, err
48 }
49 return parents, ParsePatch(raw), nil
50}
51
52// ParsePatch leest de tekst van git diff, inclusief hernoemen en binaire bestanden.
53func ParsePatch(raw string) []PatchFile {
54 var files []PatchFile
55 var cur *PatchFile
56 var oldGuess, newGuess string
57 var oldLine, newLine int
58 inHunk := false
59 skipBinary := false
60 for _, line := range strings.Split(raw, "\n") {
61 switch {
62 case strings.HasPrefix(line, "diff --git "):
63 files = append(files, PatchFile{Status: "modified"})
64 cur = &files[len(files)-1]
65 oldGuess, newGuess = splitDiffPaths(line)
66 cur.Path = newGuess
67 oldLine, newLine = 0, 0
68 inHunk = false
69 skipBinary = false
70 case cur == nil || skipBinary:
71 continue
72 case strings.HasPrefix(line, "new file mode "):
73 cur.Status = "added"
74 case strings.HasPrefix(line, "deleted file mode "):
75 cur.Status = "deleted"
76 if oldGuess != "" {
77 cur.Path = oldGuess
78 }
79 case strings.HasPrefix(line, "rename from ") || strings.HasPrefix(line, "copy from "):
80 cur.Status = "renamed"
81 cur.OldPath = metaPath(line)
82 case strings.HasPrefix(line, "rename to ") || strings.HasPrefix(line, "copy to "):
83 cur.Status = "renamed"
84 if p := metaPath(line); p != "" {
85 cur.Path = p
86 }
87 case strings.HasPrefix(line, "Binary files ") || strings.HasPrefix(line, "GIT binary patch"):
88 cur.Binary = true
89 cur.Lines = nil
90 cur.Added, cur.Deleted = 0, 0
91 skipBinary = true
92 inHunk = false
93 case strings.HasPrefix(line, "@@"):
94 oldLine, newLine = hunkStart(line)
95 oldLine--
96 newLine--
97 inHunk = true
98 cur.Lines = append(cur.Lines, DiffLine{Kind: "hunk", Text: line})
99 case !inHunk:
100 continue
101 case strings.HasPrefix(line, `\`):
102 continue
103 case strings.HasPrefix(line, "+"):
104 newLine++
105 cur.Added++
106 cur.Lines = append(cur.Lines, DiffLine{Kind: "add", New: newLine, Text: line[1:]})
107 case strings.HasPrefix(line, "-"):
108 oldLine++
109 cur.Deleted++
110 cur.Lines = append(cur.Lines, DiffLine{Kind: "del", Old: oldLine, Text: line[1:]})
111 case strings.HasPrefix(line, " "):
112 oldLine++
113 newLine++
114 cur.Lines = append(cur.Lines, DiffLine{Kind: "ctx", Old: oldLine, New: newLine, Text: line[1:]})
115 }
116 }
117 var out []PatchFile
118 for _, f := range files {
119 if f.Path == "" {
120 continue
121 }
122 if f.Status != "renamed" {
123 f.OldPath = ""
124 }
125 out = append(out, f)
126 }
127 return out
128}
129
130func splitDiffPaths(line string) (oldPath, newPath string) {
131 rest := strings.TrimSpace(strings.TrimPrefix(line, "diff --git "))
132 a, b, ok := splitQuotedPair(rest)
133 if !ok {
134 return "", ""
135 }
136 return stripAB(a), stripAB(b)
137}
138
139func splitQuotedPair(s string) (string, string, bool) {
140 s = strings.TrimSpace(s)
141 if s == "" {
142 return "", "", false
143 }
144 if strings.HasPrefix(s, `"`) {
145 a, rest, ok := unquotePrefix(s)
146 if !ok {
147 return "", "", false
148 }
149 rest = strings.TrimSpace(rest)
150 if strings.HasPrefix(rest, `"`) {
151 b, _, ok := unquotePrefix(rest)
152 return a, b, ok
153 }
154 return a, rest, rest != ""
155 }
156 i := strings.Index(s, " b/")
157 if i < 0 {
158 return "", "", false
159 }
160 return s[:i], s[i+1:], true
161}
162
163func unquotePrefix(s string) (string, string, bool) {
164 if len(s) < 2 || s[0] != '"' {
165 return "", "", false
166 }
167 for i := 1; i < len(s); i++ {
168 if s[i] == '\\' {
169 i++
170 continue
171 }
172 if s[i] == '"' {
173 u, err := strconv.Unquote(s[:i+1])
174 if err != nil {
175 return "", "", false
176 }
177 return u, s[i+1:], true
178 }
179 }
180 return "", "", false
181}
182
183func metaPath(line string) string {
184 if i := strings.IndexByte(line, ' '); i >= 0 {
185 line = line[i+1:]
186 }
187 // "rename from pad" heeft twee spaties in het commando.
188 if i := strings.IndexByte(line, ' '); i >= 0 && !strings.HasPrefix(line, `"`) && (strings.HasPrefix(line, "from ") || strings.HasPrefix(line, "to ")) {
189 line = line[i+1:]
190 }
191 line = strings.TrimSpace(line)
192 if strings.HasPrefix(line, `"`) {
193 if u, err := strconv.Unquote(line); err == nil {
194 return u
195 }
196 }
197 return line
198}
internal/gitrepo/patch_test.go added +186 −0
@@ -0,0 +1,186 @@
1 package gitrepo
2
3 import (
4 "context"
5 "os"
6 "os/exec"
7 "path/filepath"
8 "strings"
9 "testing"
10 )
11
12 func TestParsePatchKinds(t *testing.T) {
13 raw := "" +
14 "diff --git a/keep.go b/keep.go\n" +
15 "index 111..222 100644\n" +
16 "--- a/keep.go\n" +
17 "+++ b/keep.go\n" +
18 "@@ -1,2 +1,3 @@\n" +
19 " package p\n" +
20 "-func old() {}\n" +
21 "+func extra() {}\n" +
22 " \n" +
23 "diff --git a/gone.txt b/gone.txt\n" +
24 "deleted file mode 100644\n" +
25 "--- a/gone.txt\n" +
26 "+++ /dev/null\n" +
27 "@@ -1 +0,0 @@\n" +
28 "-weg\n" +
29 "diff --git \"a/oude naam.txt\" \"b/nieuwe naam.txt\"\n" +
30 "similarity index 90%\n" +
31 "rename from oude naam.txt\n" +
32 "rename to nieuwe naam.txt\n" +
33 "--- \"a/oude naam.txt\"\n" +
34 "+++ \"b/nieuwe naam.txt\"\n" +
35 "@@ -1 +1 @@\n" +
36 "-oud\n" +
37 "+nieuw\n" +
38 "diff --git a/plaatje.bin b/plaatje.bin\n" +
39 "new file mode 100644\n" +
40 "index 0000000..abc\n" +
41 "Binary files /dev/null and b/plaatje.bin differ\n"
42 files := ParsePatch(raw)
43 if len(files) != 4 {
44 t.Fatalf("bestanden: %+v", files)
45 }
46 if files[0].Status != "modified" || files[0].Added != 1 || files[0].Deleted != 1 || files[0].Path != "keep.go" {
47 t.Fatalf("wijziging: %+v", files[0])
48 }
49 if files[0].Lines[2].Kind != "del" || files[0].Lines[2].Old != 2 || files[0].Lines[3].Kind != "add" || files[0].Lines[3].New != 2 {
50 t.Fatalf("regelnummers: %+v", files[0].Lines)
51 }
52 if files[1].Status != "deleted" || files[1].Path != "gone.txt" || files[1].Deleted != 1 {
53 t.Fatalf("verwijderd: %+v", files[1])
54 }
55 if files[2].Status != "renamed" || files[2].OldPath != "oude naam.txt" || files[2].Path != "nieuwe naam.txt" {
56 t.Fatalf("hernoemd: %+v", files[2])
57 }
58 if !files[3].Binary || files[3].Status != "added" || len(files[3].Lines) != 0 || files[3].Path != "plaatje.bin" {
59 t.Fatalf("binair: %+v", files[3])
60 }
61 }
62
63 func TestCommitPatchHistory(t *testing.T) {
64 if _, err := exec.LookPath("git"); err != nil {
65 t.Skip("git ontbreekt")
66 }
67 dir := t.TempDir()
68 git := func(args ...string) {
69 t.Helper()
70 cmd := exec.Command("git", append([]string{"-C", dir}, args...)...)
71 cmd.Env = append(os.Environ(), "GIT_AUTHOR_NAME=tim", "GIT_AUTHOR_EMAIL=tim@example.com", "GIT_COMMITTER_NAME=tim", "GIT_COMMITTER_EMAIL=tim@example.com")
72 if out, err := cmd.CombinedOutput(); err != nil {
73 t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
74 }
75 }
76 git("init", "-b", "master")
77 git("config", "commit.gpgsign", "false")
78 write := func(name, body string) {
79 t.Helper()
80 path := filepath.Join(dir, filepath.FromSlash(name))
81 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
82 t.Fatal(err)
83 }
84 if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
85 t.Fatal(err)
86 }
87 }
88 write("a.txt", "alpha\n")
89 write("b.txt", "beta\n")
90 write("keep.go", "package p\n\nfunc keep() {}\n")
91 git("add", ".")
92 git("commit", "-m", "begin")
93 root := rev(t, dir)
94
95 ctx := context.Background()
96 parents, files, err := CommitPatch(ctx, "git", dir, root)
97 if err != nil {
98 t.Fatal(err)
99 }
100 if len(parents) != 0 || len(files) != 3 {
101 t.Fatalf("root parents=%v files=%d", parents, len(files))
102 }
103 for _, f := range files {
104 if f.Status != "added" {
105 t.Fatalf("rootbestand: %+v", f)
106 }
107 }
108
109 write("keep.go", "package p\n\nfunc keep() {}\nfunc extra() {}\n")
110 if err := os.Remove(filepath.Join(dir, "b.txt")); err != nil {
111 t.Fatal(err)
112 }
113 write("c.txt", strings.Repeat("x", 180)+"\n")
114 write("note file.txt", "spatie\n")
115 var huge strings.Builder
116 for i := 0; i < 220; i++ {
117 huge.WriteString("regel\n")
118 }
119 write("huge.txt", huge.String())
120 write("bin.dat", "a\x00b\n")
121 git("add", "-A")
122 git("mv", "a.txt", "a2.txt")
123 git("commit", "-m", "wijzig bestanden", "-m", "tweede alinea")
124 mixed := rev(t, dir)
125
126 parents, files, err = CommitPatch(ctx, "git", dir, mixed)
127 if err != nil {
128 t.Fatal(err)
129 }
130 if len(parents) != 1 || parents[0] != root {
131 t.Fatalf("parents: %v", parents)
132 }
133 byPath := map[string]PatchFile{}
134 for _, f := range files {
135 byPath[f.Path] = f
136 }
137 if byPath["a2.txt"].Status != "renamed" || byPath["a2.txt"].OldPath != "a.txt" {
138 t.Fatalf("rename: %+v", byPath["a2.txt"])
139 }
140 if byPath["b.txt"].Status != "deleted" || byPath["b.txt"].Deleted != 1 {
141 t.Fatalf("delete: %+v", byPath["b.txt"])
142 }
143 if byPath["c.txt"].Status != "added" || byPath["c.txt"].Added != 1 {
144 t.Fatalf("add: %+v", byPath["c.txt"])
145 }
146 if byPath["note file.txt"].Status != "added" {
147 t.Fatalf("spatie: %+v", byPath["note file.txt"])
148 }
149 if !byPath["bin.dat"].Binary || len(byPath["bin.dat"].Lines) != 0 {
150 t.Fatalf("binair: %+v", byPath["bin.dat"])
151 }
152 if byPath["huge.txt"].Added != 220 {
153 t.Fatalf("groot: %+v", byPath["huge.txt"])
154 }
155 if byPath["keep.go"].Status != "modified" || byPath["keep.go"].Added < 1 {
156 t.Fatalf("go: %+v", byPath["keep.go"])
157 }
158
159 git("checkout", "-b", "side")
160 write("side.txt", "zijtak\n")
161 git("add", "side.txt")
162 git("commit", "-m", "zijtak")
163 git("checkout", "master")
164 git("merge", "--no-ff", "side", "-m", "voeg zijtak samen")
165 merge := rev(t, dir)
166 parents, files, err = CommitPatch(ctx, "git", dir, merge)
167 if err != nil {
168 t.Fatal(err)
169 }
170 if len(parents) != 2 || parents[0] != mixed {
171 t.Fatalf("merge-parents: %v mixed=%s", parents, mixed)
172 }
173 if len(files) != 1 || files[0].Path != "side.txt" || files[0].Status != "added" {
174 t.Fatalf("merge-diff: %+v", files)
175 }
176 }
177
178 func rev(t *testing.T, dir string) string {
179 t.Helper()
180 cmd := exec.Command("git", "-C", dir, "rev-parse", "HEAD")
181 out, err := cmd.Output()
182 if err != nil {
183 t.Fatal(err)
184 }
185 return strings.TrimSpace(string(out))
186 }
@@ -0,0 +1,186 @@
1package gitrepo
2
3import (
4 "context"
5 "os"
6 "os/exec"
7 "path/filepath"
8 "strings"
9 "testing"
10)
11
12func TestParsePatchKinds(t *testing.T) {
13 raw := "" +
14 "diff --git a/keep.go b/keep.go\n" +
15 "index 111..222 100644\n" +
16 "--- a/keep.go\n" +
17 "+++ b/keep.go\n" +
18 "@@ -1,2 +1,3 @@\n" +
19 " package p\n" +
20 "-func old() {}\n" +
21 "+func extra() {}\n" +
22 " \n" +
23 "diff --git a/gone.txt b/gone.txt\n" +
24 "deleted file mode 100644\n" +
25 "--- a/gone.txt\n" +
26 "+++ /dev/null\n" +
27 "@@ -1 +0,0 @@\n" +
28 "-weg\n" +
29 "diff --git \"a/oude naam.txt\" \"b/nieuwe naam.txt\"\n" +
30 "similarity index 90%\n" +
31 "rename from oude naam.txt\n" +
32 "rename to nieuwe naam.txt\n" +
33 "--- \"a/oude naam.txt\"\n" +
34 "+++ \"b/nieuwe naam.txt\"\n" +
35 "@@ -1 +1 @@\n" +
36 "-oud\n" +
37 "+nieuw\n" +
38 "diff --git a/plaatje.bin b/plaatje.bin\n" +
39 "new file mode 100644\n" +
40 "index 0000000..abc\n" +
41 "Binary files /dev/null and b/plaatje.bin differ\n"
42 files := ParsePatch(raw)
43 if len(files) != 4 {
44 t.Fatalf("bestanden: %+v", files)
45 }
46 if files[0].Status != "modified" || files[0].Added != 1 || files[0].Deleted != 1 || files[0].Path != "keep.go" {
47 t.Fatalf("wijziging: %+v", files[0])
48 }
49 if files[0].Lines[2].Kind != "del" || files[0].Lines[2].Old != 2 || files[0].Lines[3].Kind != "add" || files[0].Lines[3].New != 2 {
50 t.Fatalf("regelnummers: %+v", files[0].Lines)
51 }
52 if files[1].Status != "deleted" || files[1].Path != "gone.txt" || files[1].Deleted != 1 {
53 t.Fatalf("verwijderd: %+v", files[1])
54 }
55 if files[2].Status != "renamed" || files[2].OldPath != "oude naam.txt" || files[2].Path != "nieuwe naam.txt" {
56 t.Fatalf("hernoemd: %+v", files[2])
57 }
58 if !files[3].Binary || files[3].Status != "added" || len(files[3].Lines) != 0 || files[3].Path != "plaatje.bin" {
59 t.Fatalf("binair: %+v", files[3])
60 }
61}
62
63func TestCommitPatchHistory(t *testing.T) {
64 if _, err := exec.LookPath("git"); err != nil {
65 t.Skip("git ontbreekt")
66 }
67 dir := t.TempDir()
68 git := func(args ...string) {
69 t.Helper()
70 cmd := exec.Command("git", append([]string{"-C", dir}, args...)...)
71 cmd.Env = append(os.Environ(), "GIT_AUTHOR_NAME=tim", "GIT_AUTHOR_EMAIL=tim@example.com", "GIT_COMMITTER_NAME=tim", "GIT_COMMITTER_EMAIL=tim@example.com")
72 if out, err := cmd.CombinedOutput(); err != nil {
73 t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
74 }
75 }
76 git("init", "-b", "master")
77 git("config", "commit.gpgsign", "false")
78 write := func(name, body string) {
79 t.Helper()
80 path := filepath.Join(dir, filepath.FromSlash(name))
81 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
82 t.Fatal(err)
83 }
84 if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
85 t.Fatal(err)
86 }
87 }
88 write("a.txt", "alpha\n")
89 write("b.txt", "beta\n")
90 write("keep.go", "package p\n\nfunc keep() {}\n")
91 git("add", ".")
92 git("commit", "-m", "begin")
93 root := rev(t, dir)
94
95 ctx := context.Background()
96 parents, files, err := CommitPatch(ctx, "git", dir, root)
97 if err != nil {
98 t.Fatal(err)
99 }
100 if len(parents) != 0 || len(files) != 3 {
101 t.Fatalf("root parents=%v files=%d", parents, len(files))
102 }
103 for _, f := range files {
104 if f.Status != "added" {
105 t.Fatalf("rootbestand: %+v", f)
106 }
107 }
108
109 write("keep.go", "package p\n\nfunc keep() {}\nfunc extra() {}\n")
110 if err := os.Remove(filepath.Join(dir, "b.txt")); err != nil {
111 t.Fatal(err)
112 }
113 write("c.txt", strings.Repeat("x", 180)+"\n")
114 write("note file.txt", "spatie\n")
115 var huge strings.Builder
116 for i := 0; i < 220; i++ {
117 huge.WriteString("regel\n")
118 }
119 write("huge.txt", huge.String())
120 write("bin.dat", "a\x00b\n")
121 git("add", "-A")
122 git("mv", "a.txt", "a2.txt")
123 git("commit", "-m", "wijzig bestanden", "-m", "tweede alinea")
124 mixed := rev(t, dir)
125
126 parents, files, err = CommitPatch(ctx, "git", dir, mixed)
127 if err != nil {
128 t.Fatal(err)
129 }
130 if len(parents) != 1 || parents[0] != root {
131 t.Fatalf("parents: %v", parents)
132 }
133 byPath := map[string]PatchFile{}
134 for _, f := range files {
135 byPath[f.Path] = f
136 }
137 if byPath["a2.txt"].Status != "renamed" || byPath["a2.txt"].OldPath != "a.txt" {
138 t.Fatalf("rename: %+v", byPath["a2.txt"])
139 }
140 if byPath["b.txt"].Status != "deleted" || byPath["b.txt"].Deleted != 1 {
141 t.Fatalf("delete: %+v", byPath["b.txt"])
142 }
143 if byPath["c.txt"].Status != "added" || byPath["c.txt"].Added != 1 {
144 t.Fatalf("add: %+v", byPath["c.txt"])
145 }
146 if byPath["note file.txt"].Status != "added" {
147 t.Fatalf("spatie: %+v", byPath["note file.txt"])
148 }
149 if !byPath["bin.dat"].Binary || len(byPath["bin.dat"].Lines) != 0 {
150 t.Fatalf("binair: %+v", byPath["bin.dat"])
151 }
152 if byPath["huge.txt"].Added != 220 {
153 t.Fatalf("groot: %+v", byPath["huge.txt"])
154 }
155 if byPath["keep.go"].Status != "modified" || byPath["keep.go"].Added < 1 {
156 t.Fatalf("go: %+v", byPath["keep.go"])
157 }
158
159 git("checkout", "-b", "side")
160 write("side.txt", "zijtak\n")
161 git("add", "side.txt")
162 git("commit", "-m", "zijtak")
163 git("checkout", "master")
164 git("merge", "--no-ff", "side", "-m", "voeg zijtak samen")
165 merge := rev(t, dir)
166 parents, files, err = CommitPatch(ctx, "git", dir, merge)
167 if err != nil {
168 t.Fatal(err)
169 }
170 if len(parents) != 2 || parents[0] != mixed {
171 t.Fatalf("merge-parents: %v mixed=%s", parents, mixed)
172 }
173 if len(files) != 1 || files[0].Path != "side.txt" || files[0].Status != "added" {
174 t.Fatalf("merge-diff: %+v", files)
175 }
176}
177
178func rev(t *testing.T, dir string) string {
179 t.Helper()
180 cmd := exec.Command("git", "-C", dir, "rev-parse", "HEAD")
181 out, err := cmd.Output()
182 if err != nil {
183 t.Fatal(err)
184 }
185 return strings.TrimSpace(string(out))
186}
internal/highlight/highlight.go +20 −5
@@ -9,21 +9,36 @@ import (
9 9
10 10 // Lines geeft per regel HTML. Tekst uit het bestand is geëscaped.
11 11 func Lines(filename, src string) []string {
12 lang := langOf(filename)
13 inBlock := false
14 12 raw := strings.Split(src, "\n")
15 13 if len(raw) > 0 && raw[len(raw)-1] == "" && strings.HasSuffix(src, "\n") {
16 14 raw = raw[:len(raw)-1]
17 15 }
16 p := NewPainter(filename)
18 17 out := make([]string, 0, len(raw))
19 18 for _, line := range raw {
20 var htmlLine string
21 htmlLine, inBlock = paint(lang, line, inBlock)
22 out = append(out, htmlLine)
19 out = append(out, p.Line(line))
23 20 }
24 21 return out
25 22 }
26 23
24 // Painter kleurt opeenvolgende regels en onthoudt een blokcommentaar.
25 type Painter struct {
26 lang string
27 inBlock bool
28 }
29
30 // NewPainter kiest de taal bij de bestandsnaam.
31 func NewPainter(filename string) *Painter {
32 return &Painter{lang: langOf(filename)}
33 }
34
35 // Line geeft geëscapete HTML voor één regel.
36 func (p *Painter) Line(text string) string {
37 htmlLine, inBlock := paint(p.lang, text, p.inBlock)
38 p.inBlock = inBlock
39 return htmlLine
40 }
41
27 42 func langOf(filename string) string {
28 43 switch strings.ToLower(path.Ext(filename)) {
29 44 case ".go":
@@ -9,21 +9,36 @@ import (
9
9
10// Lines geeft per regel HTML. Tekst uit het bestand is geëscaped.
10// Lines geeft per regel HTML. Tekst uit het bestand is geëscaped.
11func Lines(filename, src string) []string {
11func Lines(filename, src string) []string {
12 lang := langOf(filename)
13 inBlock := false
14 raw := strings.Split(src, "\n")
12 raw := strings.Split(src, "\n")
15 if len(raw) > 0 && raw[len(raw)-1] == "" && strings.HasSuffix(src, "\n") {
13 if len(raw) > 0 && raw[len(raw)-1] == "" && strings.HasSuffix(src, "\n") {
16 raw = raw[:len(raw)-1]
14 raw = raw[:len(raw)-1]
17 }
15 }
16 p := NewPainter(filename)
18 out := make([]string, 0, len(raw))
17 out := make([]string, 0, len(raw))
19 for _, line := range raw {
18 for _, line := range raw {
20 var htmlLine string
19 out = append(out, p.Line(line))
21 htmlLine, inBlock = paint(lang, line, inBlock)
22 out = append(out, htmlLine)
23 }
20 }
24 return out
21 return out
25}
22}
26
23
24// Painter kleurt opeenvolgende regels en onthoudt een blokcommentaar.
25type Painter struct {
26 lang string
27 inBlock bool
28}
29
30// NewPainter kiest de taal bij de bestandsnaam.
31func NewPainter(filename string) *Painter {
32 return &Painter{lang: langOf(filename)}
33}
34
35// Line geeft geëscapete HTML voor één regel.
36func (p *Painter) Line(text string) string {
37 htmlLine, inBlock := paint(p.lang, text, p.inBlock)
38 p.inBlock = inBlock
39 return htmlLine
40}
41
27func langOf(filename string) string {
42func langOf(filename string) string {
28 switch strings.ToLower(path.Ext(filename)) {
43 switch strings.ToLower(path.Ext(filename)) {
29 case ".go":
44 case ".go":
internal/i18n/catalog_commit.go added +92 −0
@@ -0,0 +1,92 @@
1 package i18n
2
3 func init() {
4 addCatalog(en, commitEN)
5 addCatalog(nl, commitNL)
6 addCatalog(de, commitDE)
7 addCatalog(fr, commitFR)
8 }
9
10 var commitEN = map[string]string{
11 "commit.authored": "Authored",
12 "commit.sha": "Hash",
13 "commit.parent": "Parent",
14 "commit.parents": "Parents",
15 "commit.changed": "Changed files",
16 "commit.file.one": "%d file changed",
17 "commit.file.many": "%d files changed",
18 "commit.added": "added",
19 "commit.deleted": "deleted",
20 "commit.renamed": "renamed",
21 "commit.binary": "Binary file",
22 "commit.binaryHint": "The contents of this binary file are not shown.",
23 "commit.show": "Show diff",
24 "commit.hide": "Hide diff",
25 "commit.inline": "Inline",
26 "commit.side": "Side-by-side",
27 "commit.empty": "This commit does not change any files.",
28 "commit.view": "Diff view",
29 }
30
31 var commitNL = map[string]string{
32 "commit.authored": "Geschreven",
33 "commit.sha": "Hash",
34 "commit.parent": "Bovenliggende commit",
35 "commit.parents": "Bovenliggende commits",
36 "commit.changed": "Gewijzigde bestanden",
37 "commit.file.one": "%d bestand gewijzigd",
38 "commit.file.many": "%d bestanden gewijzigd",
39 "commit.added": "toegevoegd",
40 "commit.deleted": "verwijderd",
41 "commit.renamed": "hernoemd",
42 "commit.binary": "Binair bestand",
43 "commit.binaryHint": "De inhoud van dit binaire bestand wordt niet getoond.",
44 "commit.show": "Toon diff",
45 "commit.hide": "Verberg diff",
46 "commit.inline": "Onder elkaar",
47 "commit.side": "Naast elkaar",
48 "commit.empty": "Deze commit wijzigt geen bestanden.",
49 "commit.view": "Diffweergave",
50 }
51
52 var commitDE = map[string]string{
53 "commit.authored": "Verfasst",
54 "commit.sha": "Hash",
55 "commit.parent": "Übergeordneter Commit",
56 "commit.parents": "Übergeordnete Commits",
57 "commit.changed": "Geänderte Dateien",
58 "commit.file.one": "%d Datei geändert",
59 "commit.file.many": "%d Dateien geändert",
60 "commit.added": "hinzugefügt",
61 "commit.deleted": "gelöscht",
62 "commit.renamed": "umbenannt",
63 "commit.binary": "Binärdatei",
64 "commit.binaryHint": "Der Inhalt dieser Binärdatei wird nicht angezeigt.",
65 "commit.show": "Diff anzeigen",
66 "commit.hide": "Diff verbergen",
67 "commit.inline": "Untereinander",
68 "commit.side": "Nebeneinander",
69 "commit.empty": "Dieser Commit ändert keine Dateien.",
70 "commit.view": "Diff-Ansicht",
71 }
72
73 var commitFR = map[string]string{
74 "commit.authored": "Rédigé",
75 "commit.sha": "Empreinte",
76 "commit.parent": "Parent",
77 "commit.parents": "Parents",
78 "commit.changed": "Fichiers modifiés",
79 "commit.file.one": "%d fichier modifié",
80 "commit.file.many": "%d fichiers modifiés",
81 "commit.added": "ajouté",
82 "commit.deleted": "supprimé",
83 "commit.renamed": "renommé",
84 "commit.binary": "Fichier binaire",
85 "commit.binaryHint": "Le contenu de ce fichier binaire n'est pas affiché.",
86 "commit.show": "Afficher le diff",
87 "commit.hide": "Masquer le diff",
88 "commit.inline": "En ligne",
89 "commit.side": "Côte à côte",
90 "commit.empty": "Ce commit ne modifie aucun fichier.",
91 "commit.view": "Affichage du diff",
92 }
@@ -0,0 +1,92 @@
1package i18n
2
3func init() {
4 addCatalog(en, commitEN)
5 addCatalog(nl, commitNL)
6 addCatalog(de, commitDE)
7 addCatalog(fr, commitFR)
8}
9
10var commitEN = map[string]string{
11 "commit.authored": "Authored",
12 "commit.sha": "Hash",
13 "commit.parent": "Parent",
14 "commit.parents": "Parents",
15 "commit.changed": "Changed files",
16 "commit.file.one": "%d file changed",
17 "commit.file.many": "%d files changed",
18 "commit.added": "added",
19 "commit.deleted": "deleted",
20 "commit.renamed": "renamed",
21 "commit.binary": "Binary file",
22 "commit.binaryHint": "The contents of this binary file are not shown.",
23 "commit.show": "Show diff",
24 "commit.hide": "Hide diff",
25 "commit.inline": "Inline",
26 "commit.side": "Side-by-side",
27 "commit.empty": "This commit does not change any files.",
28 "commit.view": "Diff view",
29}
30
31var commitNL = map[string]string{
32 "commit.authored": "Geschreven",
33 "commit.sha": "Hash",
34 "commit.parent": "Bovenliggende commit",
35 "commit.parents": "Bovenliggende commits",
36 "commit.changed": "Gewijzigde bestanden",
37 "commit.file.one": "%d bestand gewijzigd",
38 "commit.file.many": "%d bestanden gewijzigd",
39 "commit.added": "toegevoegd",
40 "commit.deleted": "verwijderd",
41 "commit.renamed": "hernoemd",
42 "commit.binary": "Binair bestand",
43 "commit.binaryHint": "De inhoud van dit binaire bestand wordt niet getoond.",
44 "commit.show": "Toon diff",
45 "commit.hide": "Verberg diff",
46 "commit.inline": "Onder elkaar",
47 "commit.side": "Naast elkaar",
48 "commit.empty": "Deze commit wijzigt geen bestanden.",
49 "commit.view": "Diffweergave",
50}
51
52var commitDE = map[string]string{
53 "commit.authored": "Verfasst",
54 "commit.sha": "Hash",
55 "commit.parent": "Übergeordneter Commit",
56 "commit.parents": "Übergeordnete Commits",
57 "commit.changed": "Geänderte Dateien",
58 "commit.file.one": "%d Datei geändert",
59 "commit.file.many": "%d Dateien geändert",
60 "commit.added": "hinzugefügt",
61 "commit.deleted": "gelöscht",
62 "commit.renamed": "umbenannt",
63 "commit.binary": "Binärdatei",
64 "commit.binaryHint": "Der Inhalt dieser Binärdatei wird nicht angezeigt.",
65 "commit.show": "Diff anzeigen",
66 "commit.hide": "Diff verbergen",
67 "commit.inline": "Untereinander",
68 "commit.side": "Nebeneinander",
69 "commit.empty": "Dieser Commit ändert keine Dateien.",
70 "commit.view": "Diff-Ansicht",
71}
72
73var commitFR = map[string]string{
74 "commit.authored": "Rédigé",
75 "commit.sha": "Empreinte",
76 "commit.parent": "Parent",
77 "commit.parents": "Parents",
78 "commit.changed": "Fichiers modifiés",
79 "commit.file.one": "%d fichier modifié",
80 "commit.file.many": "%d fichiers modifiés",
81 "commit.added": "ajouté",
82 "commit.deleted": "supprimé",
83 "commit.renamed": "renommé",
84 "commit.binary": "Fichier binaire",
85 "commit.binaryHint": "Le contenu de ce fichier binaire n'est pas affiché.",
86 "commit.show": "Afficher le diff",
87 "commit.hide": "Masquer le diff",
88 "commit.inline": "En ligne",
89 "commit.side": "Côte à côte",
90 "commit.empty": "Ce commit ne modifie aucun fichier.",
91 "commit.view": "Affichage du diff",
92}
internal/server/commit_page.go added +269 −0
@@ -0,0 +1,269 @@
1 package server
2
3 import (
4 "html"
5 "html/template"
6 "net/url"
7 "sort"
8 "strconv"
9 "strings"
10
11 "gitlab.com/Timfa/bluegit/internal/gitrepo"
12 "gitlab.com/Timfa/bluegit/internal/highlight"
13 )
14
15 // largeChange is het aantal toegevoegde en verwijderde regels waarna een diff dicht blijft.
16 const largeChange = 200
17
18 // CommitDiff is de diff van één commit.
19 type CommitDiff struct {
20 Parents []ParentSHA
21 Files []CommitFile
22 Tree []CommitTreeRow
23 Added, Deleted, FilesN int
24 }
25
26 // ParentSHA is een parent van de commit.
27 type ParentSHA struct {
28 SHA, Short string
29 }
30
31 // CommitFile is één gewijzigd bestand, in unified en side-by-side vorm.
32 type CommitFile struct {
33 Path, OldPath, Status, Anchor, FileURL string
34 Added, Deleted int
35 Binary, Collapsed, HasBody bool
36 Lines []CommitLine
37 Pairs []CommitPair
38 }
39
40 // CommitLine is één unified diffregel. HTML is al geëscaped.
41 type CommitLine struct {
42 Kind string
43 Old int
44 New int
45 HTML template.HTML
46 }
47
48 // CommitPair is één rij in de naast-elkaar-weergave.
49 type CommitPair struct {
50 Hunk string
51 LKind, RKind string
52 LNo, RNo int
53 LHTML, RHTML template.HTML
54 }
55
56 // CommitTreeRow is een map of bestand in de boom.
57 type CommitTreeRow struct {
58 Name, Path, Anchor, Status, Icon string
59 Dir bool
60 Depth, Added, Deleted int
61 }
62
63 func presentCommitDiff(repoPath, sha string, parents []string, files []gitrepo.PatchFile) *CommitDiff {
64 d := &CommitDiff{}
65 for _, p := range parents {
66 if !safeSHA(p) {
67 continue
68 }
69 d.Parents = append(d.Parents, ParentSHA{SHA: p, Short: shortSHA(p)})
70 }
71 parent := ""
72 if len(d.Parents) > 0 {
73 parent = d.Parents[0].SHA
74 }
75 seen := map[string]int{}
76 for _, f := range files {
77 if f.Path == "" {
78 continue
79 }
80 cf := CommitFile{
81 Path: f.Path, OldPath: f.OldPath, Status: f.Status,
82 Added: f.Added, Deleted: f.Deleted, Binary: f.Binary,
83 Anchor: diffAnchor(f.Path, seen),
84 Collapsed: !f.Binary && f.Added+f.Deleted > largeChange,
85 }
86 linkPath := f.Path
87 linkRev := sha
88 if f.Status == "deleted" {
89 linkPath = f.Path
90 linkRev = parent
91 }
92 if linkRev != "" {
93 cf.FileURL = blobLink(repoPath, linkRev, linkPath)
94 }
95 if f.Binary || len(f.Lines) > 0 {
96 cf.HasBody = true
97 }
98 if !f.Binary && len(f.Lines) > 0 {
99 name := f.Path
100 if f.Status == "deleted" {
101 name = f.Path
102 }
103 painter := highlight.NewPainter(name)
104 for _, ln := range f.Lines {
105 row := CommitLine{Kind: ln.Kind, Old: ln.Old, New: ln.New}
106 if ln.Kind == "hunk" {
107 row.HTML = template.HTML(html.EscapeString(ln.Text))
108 } else {
109 row.HTML = template.HTML(painter.Line(ln.Text))
110 }
111 cf.Lines = append(cf.Lines, row)
112 }
113 cf.Pairs = pairDiff(cf.Lines)
114 }
115 d.Added += cf.Added
116 d.Deleted += cf.Deleted
117 d.Files = append(d.Files, cf)
118 }
119 d.FilesN = len(d.Files)
120 d.Tree = commitTree(d.Files)
121 return d
122 }
123
124 func pairDiff(lines []CommitLine) []CommitPair {
125 var out []CommitPair
126 for i := 0; i < len(lines); {
127 ln := lines[i]
128 if ln.Kind == "hunk" {
129 out = append(out, CommitPair{Hunk: html.UnescapeString(string(ln.HTML))})
130 i++
131 continue
132 }
133 if ln.Kind == "ctx" {
134 out = append(out, CommitPair{
135 LKind: "ctx", RKind: "ctx", LNo: ln.Old, RNo: ln.New, LHTML: ln.HTML, RHTML: ln.HTML,
136 })
137 i++
138 continue
139 }
140 var dels, adds []CommitLine
141 for i < len(lines) && lines[i].Kind == "del" {
142 dels = append(dels, lines[i])
143 i++
144 }
145 for i < len(lines) && lines[i].Kind == "add" {
146 adds = append(adds, lines[i])
147 i++
148 }
149 n := len(dels)
150 if len(adds) > n {
151 n = len(adds)
152 }
153 for k := 0; k < n; k++ {
154 p := CommitPair{}
155 if k < len(dels) {
156 p.LKind = "del"
157 p.LNo = dels[k].Old
158 p.LHTML = dels[k].HTML
159 }
160 if k < len(adds) {
161 p.RKind = "add"
162 p.RNo = adds[k].New
163 p.RHTML = adds[k].HTML
164 }
165 out = append(out, p)
166 }
167 }
168 return out
169 }
170
171 func diffAnchor(path string, seen map[string]int) string {
172 var b strings.Builder
173 b.WriteString("diff-")
174 for _, r := range path {
175 switch {
176 case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '-', r == '_':
177 b.WriteRune(r)
178 default:
179 b.WriteByte('-')
180 }
181 }
182 base := b.String()
183 n := seen[base]
184 seen[base]++
185 if n == 0 {
186 return base
187 }
188 return base + "-" + strconv.Itoa(n)
189 }
190
191 func blobLink(repoPath, rev, path string) string {
192 parts := strings.Split(path, "/")
193 for i, p := range parts {
194 parts[i] = url.PathEscape(p)
195 }
196 return "/" + repoPath + "/-/blob/" + strings.Join(parts, "/") + "?rev=" + url.QueryEscape(rev)
197 }
198
199 func commitTree(files []CommitFile) []CommitTreeRow {
200 root := &treeNode{kids: map[string]*treeNode{}}
201 for i := range files {
202 f := &files[i]
203 parts := strings.Split(f.Path, "/")
204 cur := root
205 acc := ""
206 for j, part := range parts {
207 if acc == "" {
208 acc = part
209 } else {
210 acc += "/" + part
211 }
212 n := cur.kids[part]
213 if n == nil {
214 n = &treeNode{name: part, path: acc, kids: map[string]*treeNode{}}
215 cur.kids[part] = n
216 cur.order = append(cur.order, part)
217 }
218 if j == len(parts)-1 {
219 n.file = f
220 } else {
221 n.dir = true
222 }
223 cur = n
224 }
225 }
226 var rows []CommitTreeRow
227 var walk func(n *treeNode, depth int)
228 walk = func(n *treeNode, depth int) {
229 names := append([]string(nil), n.order...)
230 sort.Slice(names, func(i, j int) bool {
231 a, b := n.kids[names[i]], n.kids[names[j]]
232 aDir := a.dir && a.file == nil
233 bDir := b.dir && b.file == nil
234 if aDir != bDir {
235 return aDir
236 }
237 return strings.ToLower(a.name) < strings.ToLower(b.name)
238 })
239 for _, name := range names {
240 child := n.kids[name]
241 shown := depth
242 if shown > 8 {
243 shown = 8
244 }
245 if child.dir && child.file == nil {
246 rows = append(rows, CommitTreeRow{
247 Name: child.name, Path: child.path, Dir: true, Depth: shown, Icon: "dir",
248 })
249 walk(child, depth+1)
250 continue
251 }
252 f := child.file
253 rows = append(rows, CommitTreeRow{
254 Name: child.name, Path: f.Path, Anchor: f.Anchor, Status: f.Status,
255 Depth: shown, Added: f.Added, Deleted: f.Deleted, Icon: fileIcon(child.name, "blob"),
256 })
257 }
258 }
259 walk(root, 0)
260 return rows
261 }
262
263 type treeNode struct {
264 name, path string
265 dir bool
266 file *CommitFile
267 kids map[string]*treeNode
268 order []string
269 }
@@ -0,0 +1,269 @@
1package server
2
3import (
4 "html"
5 "html/template"
6 "net/url"
7 "sort"
8 "strconv"
9 "strings"
10
11 "gitlab.com/Timfa/bluegit/internal/gitrepo"
12 "gitlab.com/Timfa/bluegit/internal/highlight"
13)
14
15// largeChange is het aantal toegevoegde en verwijderde regels waarna een diff dicht blijft.
16const largeChange = 200
17
18// CommitDiff is de diff van één commit.
19type CommitDiff struct {
20 Parents []ParentSHA
21 Files []CommitFile
22 Tree []CommitTreeRow
23 Added, Deleted, FilesN int
24}
25
26// ParentSHA is een parent van de commit.
27type ParentSHA struct {
28 SHA, Short string
29}
30
31// CommitFile is één gewijzigd bestand, in unified en side-by-side vorm.
32type CommitFile struct {
33 Path, OldPath, Status, Anchor, FileURL string
34 Added, Deleted int
35 Binary, Collapsed, HasBody bool
36 Lines []CommitLine
37 Pairs []CommitPair
38}
39
40// CommitLine is één unified diffregel. HTML is al geëscaped.
41type CommitLine struct {
42 Kind string
43 Old int
44 New int
45 HTML template.HTML
46}
47
48// CommitPair is één rij in de naast-elkaar-weergave.
49type CommitPair struct {
50 Hunk string
51 LKind, RKind string
52 LNo, RNo int
53 LHTML, RHTML template.HTML
54}
55
56// CommitTreeRow is een map of bestand in de boom.
57type CommitTreeRow struct {
58 Name, Path, Anchor, Status, Icon string
59 Dir bool
60 Depth, Added, Deleted int
61}
62
63func presentCommitDiff(repoPath, sha string, parents []string, files []gitrepo.PatchFile) *CommitDiff {
64 d := &CommitDiff{}
65 for _, p := range parents {
66 if !safeSHA(p) {
67 continue
68 }
69 d.Parents = append(d.Parents, ParentSHA{SHA: p, Short: shortSHA(p)})
70 }
71 parent := ""
72 if len(d.Parents) > 0 {
73 parent = d.Parents[0].SHA
74 }
75 seen := map[string]int{}
76 for _, f := range files {
77 if f.Path == "" {
78 continue
79 }
80 cf := CommitFile{
81 Path: f.Path, OldPath: f.OldPath, Status: f.Status,
82 Added: f.Added, Deleted: f.Deleted, Binary: f.Binary,
83 Anchor: diffAnchor(f.Path, seen),
84 Collapsed: !f.Binary && f.Added+f.Deleted > largeChange,
85 }
86 linkPath := f.Path
87 linkRev := sha
88 if f.Status == "deleted" {
89 linkPath = f.Path
90 linkRev = parent
91 }
92 if linkRev != "" {
93 cf.FileURL = blobLink(repoPath, linkRev, linkPath)
94 }
95 if f.Binary || len(f.Lines) > 0 {
96 cf.HasBody = true
97 }
98 if !f.Binary && len(f.Lines) > 0 {
99 name := f.Path
100 if f.Status == "deleted" {
101 name = f.Path
102 }
103 painter := highlight.NewPainter(name)
104 for _, ln := range f.Lines {
105 row := CommitLine{Kind: ln.Kind, Old: ln.Old, New: ln.New}
106 if ln.Kind == "hunk" {
107 row.HTML = template.HTML(html.EscapeString(ln.Text))
108 } else {
109 row.HTML = template.HTML(painter.Line(ln.Text))
110 }
111 cf.Lines = append(cf.Lines, row)
112 }
113 cf.Pairs = pairDiff(cf.Lines)
114 }
115 d.Added += cf.Added
116 d.Deleted += cf.Deleted
117 d.Files = append(d.Files, cf)
118 }
119 d.FilesN = len(d.Files)
120 d.Tree = commitTree(d.Files)
121 return d
122}
123
124func pairDiff(lines []CommitLine) []CommitPair {
125 var out []CommitPair
126 for i := 0; i < len(lines); {
127 ln := lines[i]
128 if ln.Kind == "hunk" {
129 out = append(out, CommitPair{Hunk: html.UnescapeString(string(ln.HTML))})
130 i++
131 continue
132 }
133 if ln.Kind == "ctx" {
134 out = append(out, CommitPair{
135 LKind: "ctx", RKind: "ctx", LNo: ln.Old, RNo: ln.New, LHTML: ln.HTML, RHTML: ln.HTML,
136 })
137 i++
138 continue
139 }
140 var dels, adds []CommitLine
141 for i < len(lines) && lines[i].Kind == "del" {
142 dels = append(dels, lines[i])
143 i++
144 }
145 for i < len(lines) && lines[i].Kind == "add" {
146 adds = append(adds, lines[i])
147 i++
148 }
149 n := len(dels)
150 if len(adds) > n {
151 n = len(adds)
152 }
153 for k := 0; k < n; k++ {
154 p := CommitPair{}
155 if k < len(dels) {
156 p.LKind = "del"
157 p.LNo = dels[k].Old
158 p.LHTML = dels[k].HTML
159 }
160 if k < len(adds) {
161 p.RKind = "add"
162 p.RNo = adds[k].New
163 p.RHTML = adds[k].HTML
164 }
165 out = append(out, p)
166 }
167 }
168 return out
169}
170
171func diffAnchor(path string, seen map[string]int) string {
172 var b strings.Builder
173 b.WriteString("diff-")
174 for _, r := range path {
175 switch {
176 case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '-', r == '_':
177 b.WriteRune(r)
178 default:
179 b.WriteByte('-')
180 }
181 }
182 base := b.String()
183 n := seen[base]
184 seen[base]++
185 if n == 0 {
186 return base
187 }
188 return base + "-" + strconv.Itoa(n)
189}
190
191func blobLink(repoPath, rev, path string) string {
192 parts := strings.Split(path, "/")
193 for i, p := range parts {
194 parts[i] = url.PathEscape(p)
195 }
196 return "/" + repoPath + "/-/blob/" + strings.Join(parts, "/") + "?rev=" + url.QueryEscape(rev)
197}
198
199func commitTree(files []CommitFile) []CommitTreeRow {
200 root := &treeNode{kids: map[string]*treeNode{}}
201 for i := range files {
202 f := &files[i]
203 parts := strings.Split(f.Path, "/")
204 cur := root
205 acc := ""
206 for j, part := range parts {
207 if acc == "" {
208 acc = part
209 } else {
210 acc += "/" + part
211 }
212 n := cur.kids[part]
213 if n == nil {
214 n = &treeNode{name: part, path: acc, kids: map[string]*treeNode{}}
215 cur.kids[part] = n
216 cur.order = append(cur.order, part)
217 }
218 if j == len(parts)-1 {
219 n.file = f
220 } else {
221 n.dir = true
222 }
223 cur = n
224 }
225 }
226 var rows []CommitTreeRow
227 var walk func(n *treeNode, depth int)
228 walk = func(n *treeNode, depth int) {
229 names := append([]string(nil), n.order...)
230 sort.Slice(names, func(i, j int) bool {
231 a, b := n.kids[names[i]], n.kids[names[j]]
232 aDir := a.dir && a.file == nil
233 bDir := b.dir && b.file == nil
234 if aDir != bDir {
235 return aDir
236 }
237 return strings.ToLower(a.name) < strings.ToLower(b.name)
238 })
239 for _, name := range names {
240 child := n.kids[name]
241 shown := depth
242 if shown > 8 {
243 shown = 8
244 }
245 if child.dir && child.file == nil {
246 rows = append(rows, CommitTreeRow{
247 Name: child.name, Path: child.path, Dir: true, Depth: shown, Icon: "dir",
248 })
249 walk(child, depth+1)
250 continue
251 }
252 f := child.file
253 rows = append(rows, CommitTreeRow{
254 Name: child.name, Path: f.Path, Anchor: f.Anchor, Status: f.Status,
255 Depth: shown, Added: f.Added, Deleted: f.Deleted, Icon: fileIcon(child.name, "blob"),
256 })
257 }
258 }
259 walk(root, 0)
260 return rows
261}
262
263type treeNode struct {
264 name, path string
265 dir bool
266 file *CommitFile
267 kids map[string]*treeNode
268 order []string
269}
internal/server/commit_page_test.go added +284 −0
@@ -0,0 +1,284 @@
1 package server
2
3 import (
4 "context"
5 "net/http"
6 "net/http/cookiejar"
7 "net/http/httptest"
8 "net/url"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "strings"
13 "testing"
14
15 "gitlab.com/Timfa/bluegit/internal/auth"
16 "gitlab.com/Timfa/bluegit/internal/config"
17 "gitlab.com/Timfa/bluegit/internal/gitrepo"
18 "gitlab.com/Timfa/bluegit/internal/store"
19 )
20
21 func TestPresentCommitTree(t *testing.T) {
22 files := []gitrepo.PatchFile{
23 {Status: "added", Path: "src/util.go", Added: 2, Lines: []gitrepo.DiffLine{{Kind: "add", New: 1, Text: "func util() {}"}}},
24 {Status: "renamed", Path: "a2.txt", OldPath: "a.txt"},
25 {Status: "added", Path: "huge.txt", Added: largeChange + 1, Lines: []gitrepo.DiffLine{{Kind: "add", New: 1, Text: "x"}}},
26 }
27 d := presentCommitDiff("tim/demo", "abcdef1234567890", []string{"1234abcd1234abcd1234abcd1234abcd1234abcd"}, files)
28 if d.FilesN != 3 || len(d.Parents) != 1 || d.Parents[0].Short != "1234abcd" {
29 t.Fatalf("kop: %+v", d)
30 }
31 if !d.Files[2].Collapsed || d.Files[0].Collapsed {
32 t.Fatalf("inklappen: util %v huge %v", d.Files[0].Collapsed, d.Files[2].Collapsed)
33 }
34 if !strings.Contains(string(d.Files[0].Lines[0].HTML), "hl-k") {
35 t.Fatalf("geen highlight: %s", d.Files[0].Lines[0].HTML)
36 }
37 if d.Files[0].Pairs[0].RKind != "add" || d.Files[0].Pairs[0].RNo != 1 || d.Files[0].Pairs[0].LKind != "" {
38 t.Fatalf("paar: %+v", d.Files[0].Pairs)
39 }
40 var dirs, nested bool
41 for _, row := range d.Tree {
42 if row.Dir && row.Name == "src" && row.Depth == 0 {
43 dirs = true
44 }
45 if row.Name == "util.go" && row.Depth == 1 && row.Anchor != "" {
46 nested = true
47 }
48 }
49 if !dirs || !nested {
50 t.Fatalf("boom: %+v", d.Tree)
51 }
52 if !strings.Contains(d.Files[0].FileURL, "/tim/demo/-/blob/src/util.go?rev=abcdef1234567890") {
53 t.Fatal(d.Files[0].FileURL)
54 }
55 }
56
57 func TestCommitDetailPage(t *testing.T) {
58 if _, err := exec.LookPath("git"); err != nil {
59 t.Skip("git ontbreekt")
60 }
61 storage := t.TempDir()
62 st, err := store.Open(filepath.Join(storage, "bluegit.db"), bytes32())
63 if err != nil {
64 t.Fatal(err)
65 }
66 t.Cleanup(func() { _ = st.Close() })
67 cfg := config.Config{
68 BaseURL: "http://127.0.0.1:9", Listen: "127.0.0.1:0", StoragePath: storage,
69 Auth: config.Auth{Mode: "dev", DevUser: "tim", DevAuthID: 1, UserAgent: "test", BaseURL: "https://auth.timfalken.com"},
70 Git: config.Git{Binary: "git", DefaultBranch: "master"},
71 }
72 srv := &Server{Cfg: cfg, Store: st, Auth: auth.Dev{Username: "tim", AuthID: 1}, Dev: true, Git: "git", HookBin: "/bin/true"}
73 ts := httptest.NewServer(srv.Handler())
74 t.Cleanup(ts.Close)
75 jar, _ := cookiejar.New(nil)
76 client := &http.Client{Jar: jar}
77 res, err := client.Get(ts.URL + "/login")
78 if err != nil {
79 t.Fatal(err)
80 }
81 page := read(t, res)
82 res, err = client.PostForm(ts.URL+"/new/repo", url.Values{
83 "csrf": {csrfOf(t, page)}, "name": {"diffdemo"}, "visibility": {"public"},
84 })
85 if err != nil {
86 t.Fatal(err)
87 }
88 page = read(t, res)
89 res, err = client.PostForm(ts.URL+"/settings/tokens", url.Values{"csrf": {csrfOf(t, page)}, "name": {"laptop"}})
90 if err != nil {
91 t.Fatal(err)
92 }
93 token := between(read(t, res), `<p class="code">`, "</p>")
94 remote := strings.Replace(ts.URL, "http://", "http://tim:"+token+"@", 1) + "/tim/diffdemo.git"
95 work := t.TempDir()
96 git(t, work, "init", "-b", "master")
97 git(t, work, "config", "user.email", "tim@users.git.timfalken.com")
98 git(t, work, "config", "user.name", "tim")
99 git(t, work, "config", "commit.gpgsign", "false")
100 writeFile(t, filepath.Join(work, "a.txt"), "alpha\n")
101 writeFile(t, filepath.Join(work, "b.txt"), "beta\n")
102 writeFile(t, filepath.Join(work, "keep.go"), "package p\n\nfunc keep() {}\n")
103 git(t, work, "add", ".")
104 git(t, work, "commit", "-m", "begin")
105 root := strings.TrimSpace(gitOutOK(t, work, "rev-parse", "HEAD"))
106 writeFile(t, filepath.Join(work, "keep.go"), "package p\n\nfunc keep() {}\nfunc extra() {}\n")
107 if err := os.Remove(filepath.Join(work, "b.txt")); err != nil {
108 t.Fatal(err)
109 }
110 writeFile(t, filepath.Join(work, "c.txt"), strings.Repeat("x", 180)+"\n")
111 writeFile(t, filepath.Join(work, "note file.txt"), "spatie\n")
112 writeFile(t, filepath.Join(work, "src", "util.go"), "package src\n\nfunc util() {}\n")
113 var huge strings.Builder
114 for i := 0; i < 220; i++ {
115 huge.WriteString("regel\n")
116 }
117 writeFile(t, filepath.Join(work, "huge.txt"), huge.String())
118 writeFile(t, filepath.Join(work, "bin.dat"), "a\x00b\n")
119 git(t, work, "add", "-A")
120 git(t, work, "mv", "a.txt", "a2.txt")
121 git(t, work, "commit", "-m", "wijzig bestanden", "-m", "tweede alinea")
122 mixed := strings.TrimSpace(gitOutOK(t, work, "rev-parse", "HEAD"))
123 git(t, work, "remote", "add", "origin", remote)
124 git(t, work, "push", "-u", "origin", "master")
125 git(t, work, "checkout", "-b", "side")
126 writeFile(t, filepath.Join(work, "side.txt"), "zijtak\n")
127 git(t, work, "add", "side.txt")
128 git(t, work, "commit", "-m", "zijtak")
129 git(t, work, "checkout", "master")
130 git(t, work, "merge", "--no-ff", "side", "-m", "voeg zijtak samen")
131 merge := strings.TrimSpace(gitOutOK(t, work, "rev-parse", "HEAD"))
132 git(t, work, "push", "origin", "master")
133
134 ctx := context.Background()
135 repo, err := st.RepoByPath(ctx, "tim", "diffdemo")
136 if err != nil {
137 t.Fatal(err)
138 }
139 pipeID, err := st.CreatePipeline(ctx, repo.ID, mixed, "refs/heads/master", "push", "tim", "wijzig bestanden", []store.NewJob{
140 {Name: "lint", Stage: "test", Script: "exit 0"},
141 })
142 if err != nil {
143 t.Fatal(err)
144 }
145 jobs, _ := st.JobsByPipeline(ctx, pipeID)
146 for _, j := range jobs {
147 if err := st.FinishJob(ctx, j.ID, "success", ""); err != nil {
148 t.Fatal(err)
149 }
150 }
151 if status, err := st.RefreshPipelineStatus(ctx, pipeID); err != nil || status != "success" {
152 t.Fatalf("pipeline: %s %v", status, err)
153 }
154
155 res, err = client.Get(ts.URL + "/tim/diffdemo/-/commit/" + mixed)
156 if err != nil {
157 t.Fatal(err)
158 }
159 body := read(t, res)
160 for _, want := range []string{
161 "wijzig bestanden", "tweede alinea", "Authored",
162 `data-copy="` + mixed + `"`,
163 "/tim/diffdemo/-/commit/" + root,
164 "Parent",
165 `class="status passed"`, "Passed",
166 "a.txt", "a2.txt", "renamed",
167 "b.txt", "deleted",
168 "note file.txt", "added",
169 "Binary file", "The contents of this binary file are not shown.",
170 `data-path="huge.txt"`, `data-collapsed="1"`, "Show diff",
171 `data-path="keep.go"`, `data-collapsed="0"`, "Hide diff",
172 "hl-k", "func", "src", "util.go",
173 `data-diff-mode="side"`, "Side-by-side",
174 "/assets/commit-mode.js", `class="d1"`,
175 strings.Repeat("x", 180),
176 "Changed files",
177 } {
178 if !strings.Contains(body, want) {
179 t.Errorf("pagina mist %q", want)
180 }
181 }
182 if strings.Contains(body, "commit.show") {
183 t.Fatal("vertaling ontbreekt")
184 }
185 keep := section(body, `data-path="keep.go"`)
186 if !strings.Contains(keep, `class="ln">1</span>`) || !strings.Contains(keep, "kind-add") || !strings.Contains(keep, "extra") || !strings.Contains(keep, "hl-k") {
187 i := strings.Index(body, `data-path="keep.go"`)
188 j := strings.Index(body[i:], "</section>")
189 k := strings.Index(body[i:], "kind-add")
190 t.Fatalf("keep.go mist delen ln=%v add=%v extra=%v hl=%v section-op=%d add-op=%d keep-len=%d",
191 strings.Contains(keep, `class="ln">1</span>`), strings.Contains(keep, "kind-add"),
192 strings.Contains(keep, "extra"), strings.Contains(keep, "hl-k"), j, k, len(keep))
193 }
194 gone := section(body, `data-path="b.txt"`)
195 if !strings.Contains(gone, "kind-del") || !strings.Contains(gone, `class="ln">1</span>`) {
196 t.Fatal("b.txt mist het verwijderde regelnummer")
197 }
198
199 res, err = client.Get(ts.URL + "/tim/diffdemo/-/commit/" + merge)
200 if err != nil {
201 t.Fatal(err)
202 }
203 mergePage := read(t, res)
204 if !strings.Contains(mergePage, "Parents") || !strings.Contains(mergePage, "/tim/diffdemo/-/commit/"+mixed) || !strings.Contains(mergePage, `data-path="side.txt"`) {
205 t.Fatal("mergepagina mist parents of side.txt")
206 }
207 if strings.Contains(mergePage, `data-path="huge.txt"`) || strings.Contains(mergePage, `data-path="keep.go"`) {
208 t.Fatal("merge-diff toont meer dan de eerste parent")
209 }
210
211 res, err = client.Get(ts.URL + "/tim/diffdemo/-/commit/" + root)
212 if err != nil {
213 t.Fatal(err)
214 }
215 rootPage := read(t, res)
216 if strings.Contains(rootPage, "Parent") || !strings.Contains(rootPage, `data-path="a.txt"`) || !strings.Contains(rootPage, "added") {
217 t.Fatal("rootcommit klopt niet")
218 }
219
220 res, err = client.Get(ts.URL + "/settings")
221 if err != nil {
222 t.Fatal(err)
223 }
224 settings := read(t, res)
225 res, err = client.PostForm(ts.URL+"/settings/language", url.Values{"csrf": {csrfOf(t, settings)}, "language": {"nl"}})
226 if err != nil {
227 t.Fatal(err)
228 }
229 _ = read(t, res)
230 res, err = client.Get(ts.URL + "/tim/diffdemo/-/commit/" + mixed)
231 if err != nil {
232 t.Fatal(err)
233 }
234 nl := read(t, res)
235 for _, want := range []string{"Toon diff", "hernoemd", "Bovenliggende commit", "Naast elkaar", "Gewijzigde bestanden", "Binair bestand"} {
236 if !strings.Contains(nl, want) {
237 t.Errorf("Nederlands mist %q", want)
238 }
239 }
240 if strings.Contains(nl, "Show diff") {
241 t.Fatal("Engelse diffknop bleef staan")
242 }
243
244 res, err = client.Get(ts.URL + "/settings")
245 if err != nil {
246 t.Fatal(err)
247 }
248 settings = read(t, res)
249 res, err = client.PostForm(ts.URL+"/settings/language", url.Values{"csrf": {csrfOf(t, settings)}, "language": {"cuneiform"}})
250 if err != nil {
251 t.Fatal(err)
252 }
253 _ = read(t, res)
254 res, err = client.Get(ts.URL + "/tim/diffdemo/-/commit/" + mixed)
255 if err != nil {
256 t.Fatal(err)
257 }
258 signs := read(t, res)
259 if strings.Contains(signs, "Show diff") || strings.Contains(signs, "Toon diff") || !strings.Contains(signs, mixed) || !strings.Contains(signs, "𒀀") {
260 t.Fatal("spijkerschrift of hash klopt niet")
261 }
262 }
263
264 func gitOutOK(t *testing.T, dir string, args ...string) string {
265 t.Helper()
266 out, err := gitOut(dir, args...)
267 if err != nil {
268 t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
269 }
270 return out
271 }
272
273 func section(body, marker string) string {
274 i := strings.Index(body, marker)
275 if i < 0 {
276 return ""
277 }
278 rest := body[i:]
279 j := strings.Index(rest, "</section>")
280 if j < 0 {
281 return rest
282 }
283 return rest[:j]
284 }
@@ -0,0 +1,284 @@
1package server
2
3import (
4 "context"
5 "net/http"
6 "net/http/cookiejar"
7 "net/http/httptest"
8 "net/url"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "strings"
13 "testing"
14
15 "gitlab.com/Timfa/bluegit/internal/auth"
16 "gitlab.com/Timfa/bluegit/internal/config"
17 "gitlab.com/Timfa/bluegit/internal/gitrepo"
18 "gitlab.com/Timfa/bluegit/internal/store"
19)
20
21func TestPresentCommitTree(t *testing.T) {
22 files := []gitrepo.PatchFile{
23 {Status: "added", Path: "src/util.go", Added: 2, Lines: []gitrepo.DiffLine{{Kind: "add", New: 1, Text: "func util() {}"}}},
24 {Status: "renamed", Path: "a2.txt", OldPath: "a.txt"},
25 {Status: "added", Path: "huge.txt", Added: largeChange + 1, Lines: []gitrepo.DiffLine{{Kind: "add", New: 1, Text: "x"}}},
26 }
27 d := presentCommitDiff("tim/demo", "abcdef1234567890", []string{"1234abcd1234abcd1234abcd1234abcd1234abcd"}, files)
28 if d.FilesN != 3 || len(d.Parents) != 1 || d.Parents[0].Short != "1234abcd" {
29 t.Fatalf("kop: %+v", d)
30 }
31 if !d.Files[2].Collapsed || d.Files[0].Collapsed {
32 t.Fatalf("inklappen: util %v huge %v", d.Files[0].Collapsed, d.Files[2].Collapsed)
33 }
34 if !strings.Contains(string(d.Files[0].Lines[0].HTML), "hl-k") {
35 t.Fatalf("geen highlight: %s", d.Files[0].Lines[0].HTML)
36 }
37 if d.Files[0].Pairs[0].RKind != "add" || d.Files[0].Pairs[0].RNo != 1 || d.Files[0].Pairs[0].LKind != "" {
38 t.Fatalf("paar: %+v", d.Files[0].Pairs)
39 }
40 var dirs, nested bool
41 for _, row := range d.Tree {
42 if row.Dir && row.Name == "src" && row.Depth == 0 {
43 dirs = true
44 }
45 if row.Name == "util.go" && row.Depth == 1 && row.Anchor != "" {
46 nested = true
47 }
48 }
49 if !dirs || !nested {
50 t.Fatalf("boom: %+v", d.Tree)
51 }
52 if !strings.Contains(d.Files[0].FileURL, "/tim/demo/-/blob/src/util.go?rev=abcdef1234567890") {
53 t.Fatal(d.Files[0].FileURL)
54 }
55}
56
57func TestCommitDetailPage(t *testing.T) {
58 if _, err := exec.LookPath("git"); err != nil {
59 t.Skip("git ontbreekt")
60 }
61 storage := t.TempDir()
62 st, err := store.Open(filepath.Join(storage, "bluegit.db"), bytes32())
63 if err != nil {
64 t.Fatal(err)
65 }
66 t.Cleanup(func() { _ = st.Close() })
67 cfg := config.Config{
68 BaseURL: "http://127.0.0.1:9", Listen: "127.0.0.1:0", StoragePath: storage,
69 Auth: config.Auth{Mode: "dev", DevUser: "tim", DevAuthID: 1, UserAgent: "test", BaseURL: "https://auth.timfalken.com"},
70 Git: config.Git{Binary: "git", DefaultBranch: "master"},
71 }
72 srv := &Server{Cfg: cfg, Store: st, Auth: auth.Dev{Username: "tim", AuthID: 1}, Dev: true, Git: "git", HookBin: "/bin/true"}
73 ts := httptest.NewServer(srv.Handler())
74 t.Cleanup(ts.Close)
75 jar, _ := cookiejar.New(nil)
76 client := &http.Client{Jar: jar}
77 res, err := client.Get(ts.URL + "/login")
78 if err != nil {
79 t.Fatal(err)
80 }
81 page := read(t, res)
82 res, err = client.PostForm(ts.URL+"/new/repo", url.Values{
83 "csrf": {csrfOf(t, page)}, "name": {"diffdemo"}, "visibility": {"public"},
84 })
85 if err != nil {
86 t.Fatal(err)
87 }
88 page = read(t, res)
89 res, err = client.PostForm(ts.URL+"/settings/tokens", url.Values{"csrf": {csrfOf(t, page)}, "name": {"laptop"}})
90 if err != nil {
91 t.Fatal(err)
92 }
93 token := between(read(t, res), `<p class="code">`, "</p>")
94 remote := strings.Replace(ts.URL, "http://", "http://tim:"+token+"@", 1) + "/tim/diffdemo.git"
95 work := t.TempDir()
96 git(t, work, "init", "-b", "master")
97 git(t, work, "config", "user.email", "tim@users.git.timfalken.com")
98 git(t, work, "config", "user.name", "tim")
99 git(t, work, "config", "commit.gpgsign", "false")
100 writeFile(t, filepath.Join(work, "a.txt"), "alpha\n")
101 writeFile(t, filepath.Join(work, "b.txt"), "beta\n")
102 writeFile(t, filepath.Join(work, "keep.go"), "package p\n\nfunc keep() {}\n")
103 git(t, work, "add", ".")
104 git(t, work, "commit", "-m", "begin")
105 root := strings.TrimSpace(gitOutOK(t, work, "rev-parse", "HEAD"))
106 writeFile(t, filepath.Join(work, "keep.go"), "package p\n\nfunc keep() {}\nfunc extra() {}\n")
107 if err := os.Remove(filepath.Join(work, "b.txt")); err != nil {
108 t.Fatal(err)
109 }
110 writeFile(t, filepath.Join(work, "c.txt"), strings.Repeat("x", 180)+"\n")
111 writeFile(t, filepath.Join(work, "note file.txt"), "spatie\n")
112 writeFile(t, filepath.Join(work, "src", "util.go"), "package src\n\nfunc util() {}\n")
113 var huge strings.Builder
114 for i := 0; i < 220; i++ {
115 huge.WriteString("regel\n")
116 }
117 writeFile(t, filepath.Join(work, "huge.txt"), huge.String())
118 writeFile(t, filepath.Join(work, "bin.dat"), "a\x00b\n")
119 git(t, work, "add", "-A")
120 git(t, work, "mv", "a.txt", "a2.txt")
121 git(t, work, "commit", "-m", "wijzig bestanden", "-m", "tweede alinea")
122 mixed := strings.TrimSpace(gitOutOK(t, work, "rev-parse", "HEAD"))
123 git(t, work, "remote", "add", "origin", remote)
124 git(t, work, "push", "-u", "origin", "master")
125 git(t, work, "checkout", "-b", "side")
126 writeFile(t, filepath.Join(work, "side.txt"), "zijtak\n")
127 git(t, work, "add", "side.txt")
128 git(t, work, "commit", "-m", "zijtak")
129 git(t, work, "checkout", "master")
130 git(t, work, "merge", "--no-ff", "side", "-m", "voeg zijtak samen")
131 merge := strings.TrimSpace(gitOutOK(t, work, "rev-parse", "HEAD"))
132 git(t, work, "push", "origin", "master")
133
134 ctx := context.Background()
135 repo, err := st.RepoByPath(ctx, "tim", "diffdemo")
136 if err != nil {
137 t.Fatal(err)
138 }
139 pipeID, err := st.CreatePipeline(ctx, repo.ID, mixed, "refs/heads/master", "push", "tim", "wijzig bestanden", []store.NewJob{
140 {Name: "lint", Stage: "test", Script: "exit 0"},
141 })
142 if err != nil {
143 t.Fatal(err)
144 }
145 jobs, _ := st.JobsByPipeline(ctx, pipeID)
146 for _, j := range jobs {
147 if err := st.FinishJob(ctx, j.ID, "success", ""); err != nil {
148 t.Fatal(err)
149 }
150 }
151 if status, err := st.RefreshPipelineStatus(ctx, pipeID); err != nil || status != "success" {
152 t.Fatalf("pipeline: %s %v", status, err)
153 }
154
155 res, err = client.Get(ts.URL + "/tim/diffdemo/-/commit/" + mixed)
156 if err != nil {
157 t.Fatal(err)
158 }
159 body := read(t, res)
160 for _, want := range []string{
161 "wijzig bestanden", "tweede alinea", "Authored",
162 `data-copy="` + mixed + `"`,
163 "/tim/diffdemo/-/commit/" + root,
164 "Parent",
165 `class="status passed"`, "Passed",
166 "a.txt", "a2.txt", "renamed",
167 "b.txt", "deleted",
168 "note file.txt", "added",
169 "Binary file", "The contents of this binary file are not shown.",
170 `data-path="huge.txt"`, `data-collapsed="1"`, "Show diff",
171 `data-path="keep.go"`, `data-collapsed="0"`, "Hide diff",
172 "hl-k", "func", "src", "util.go",
173 `data-diff-mode="side"`, "Side-by-side",
174 "/assets/commit-mode.js", `class="d1"`,
175 strings.Repeat("x", 180),
176 "Changed files",
177 } {
178 if !strings.Contains(body, want) {
179 t.Errorf("pagina mist %q", want)
180 }
181 }
182 if strings.Contains(body, "commit.show") {
183 t.Fatal("vertaling ontbreekt")
184 }
185 keep := section(body, `data-path="keep.go"`)
186 if !strings.Contains(keep, `class="ln">1</span>`) || !strings.Contains(keep, "kind-add") || !strings.Contains(keep, "extra") || !strings.Contains(keep, "hl-k") {
187 i := strings.Index(body, `data-path="keep.go"`)
188 j := strings.Index(body[i:], "</section>")
189 k := strings.Index(body[i:], "kind-add")
190 t.Fatalf("keep.go mist delen ln=%v add=%v extra=%v hl=%v section-op=%d add-op=%d keep-len=%d",
191 strings.Contains(keep, `class="ln">1</span>`), strings.Contains(keep, "kind-add"),
192 strings.Contains(keep, "extra"), strings.Contains(keep, "hl-k"), j, k, len(keep))
193 }
194 gone := section(body, `data-path="b.txt"`)
195 if !strings.Contains(gone, "kind-del") || !strings.Contains(gone, `class="ln">1</span>`) {
196 t.Fatal("b.txt mist het verwijderde regelnummer")
197 }
198
199 res, err = client.Get(ts.URL + "/tim/diffdemo/-/commit/" + merge)
200 if err != nil {
201 t.Fatal(err)
202 }
203 mergePage := read(t, res)
204 if !strings.Contains(mergePage, "Parents") || !strings.Contains(mergePage, "/tim/diffdemo/-/commit/"+mixed) || !strings.Contains(mergePage, `data-path="side.txt"`) {
205 t.Fatal("mergepagina mist parents of side.txt")
206 }
207 if strings.Contains(mergePage, `data-path="huge.txt"`) || strings.Contains(mergePage, `data-path="keep.go"`) {
208 t.Fatal("merge-diff toont meer dan de eerste parent")
209 }
210
211 res, err = client.Get(ts.URL + "/tim/diffdemo/-/commit/" + root)
212 if err != nil {
213 t.Fatal(err)
214 }
215 rootPage := read(t, res)
216 if strings.Contains(rootPage, "Parent") || !strings.Contains(rootPage, `data-path="a.txt"`) || !strings.Contains(rootPage, "added") {
217 t.Fatal("rootcommit klopt niet")
218 }
219
220 res, err = client.Get(ts.URL + "/settings")
221 if err != nil {
222 t.Fatal(err)
223 }
224 settings := read(t, res)
225 res, err = client.PostForm(ts.URL+"/settings/language", url.Values{"csrf": {csrfOf(t, settings)}, "language": {"nl"}})
226 if err != nil {
227 t.Fatal(err)
228 }
229 _ = read(t, res)
230 res, err = client.Get(ts.URL + "/tim/diffdemo/-/commit/" + mixed)
231 if err != nil {
232 t.Fatal(err)
233 }
234 nl := read(t, res)
235 for _, want := range []string{"Toon diff", "hernoemd", "Bovenliggende commit", "Naast elkaar", "Gewijzigde bestanden", "Binair bestand"} {
236 if !strings.Contains(nl, want) {
237 t.Errorf("Nederlands mist %q", want)
238 }
239 }
240 if strings.Contains(nl, "Show diff") {
241 t.Fatal("Engelse diffknop bleef staan")
242 }
243
244 res, err = client.Get(ts.URL + "/settings")
245 if err != nil {
246 t.Fatal(err)
247 }
248 settings = read(t, res)
249 res, err = client.PostForm(ts.URL+"/settings/language", url.Values{"csrf": {csrfOf(t, settings)}, "language": {"cuneiform"}})
250 if err != nil {
251 t.Fatal(err)
252 }
253 _ = read(t, res)
254 res, err = client.Get(ts.URL + "/tim/diffdemo/-/commit/" + mixed)
255 if err != nil {
256 t.Fatal(err)
257 }
258 signs := read(t, res)
259 if strings.Contains(signs, "Show diff") || strings.Contains(signs, "Toon diff") || !strings.Contains(signs, mixed) || !strings.Contains(signs, "𒀀") {
260 t.Fatal("spijkerschrift of hash klopt niet")
261 }
262}
263
264func gitOutOK(t *testing.T, dir string, args ...string) string {
265 t.Helper()
266 out, err := gitOut(dir, args...)
267 if err != nil {
268 t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
269 }
270 return out
271}
272
273func section(body, marker string) string {
274 i := strings.Index(body, marker)
275 if i < 0 {
276 return ""
277 }
278 rest := body[i:]
279 j := strings.Index(rest, "</section>")
280 if j < 0 {
281 return rest
282 }
283 return rest[:j]
284}
internal/server/repo_handlers.go +9 −1
@@ -148,8 +148,16 @@ func (s *Server) commit(w http.ResponseWriter, r *http.Request) {
148 148 }
149 149 v := s.repoView(w, r, repo, role, c.Subject)
150 150 v.Page = "commit"
151 rows := s.presentCommits(r.Context(), repo.ID, []gitrepo.Commit{c}, i18n.Parse(v.Lang))
151 v.Wide = true
152 lang := i18n.Parse(v.Lang)
153 rows := s.presentCommits(r.Context(), repo.ID, []gitrepo.Commit{c}, lang)
154 s.attachHeadPipeline(r.Context(), repo, &rows[0], lang)
152 155 v.Commit = &rows[0]
156 parents, files, err := gitrepo.CommitPatch(r.Context(), s.Git, dir, c.SHA)
157 if err != nil && s.Log != nil {
158 s.Log.Warn("commitdiff", "sha", c.SHA, "err", err)
159 }
160 v.CommitDiff = presentCommitDiff(repo.FullPath(), c.SHA, parents, files)
153 161 s.render(w, "commit", v)
154 162 }
155 163
@@ -148,8 +148,16 @@ func (s *Server) commit(w http.ResponseWriter, r *http.Request) {
148 }
148 }
149 v := s.repoView(w, r, repo, role, c.Subject)
149 v := s.repoView(w, r, repo, role, c.Subject)
150 v.Page = "commit"
150 v.Page = "commit"
151 rows := s.presentCommits(r.Context(), repo.ID, []gitrepo.Commit{c}, i18n.Parse(v.Lang))
151 v.Wide = true
152 lang := i18n.Parse(v.Lang)
153 rows := s.presentCommits(r.Context(), repo.ID, []gitrepo.Commit{c}, lang)
154 s.attachHeadPipeline(r.Context(), repo, &rows[0], lang)
152 v.Commit = &rows[0]
155 v.Commit = &rows[0]
156 parents, files, err := gitrepo.CommitPatch(r.Context(), s.Git, dir, c.SHA)
157 if err != nil && s.Log != nil {
158 s.Log.Warn("commitdiff", "sha", c.SHA, "err", err)
159 }
160 v.CommitDiff = presentCommitDiff(repo.FullPath(), c.SHA, parents, files)
153 s.render(w, "commit", v)
161 s.render(w, "commit", v)
154}
162}
155
163
internal/server/server.go +1 −0
@@ -449,6 +449,7 @@ type View struct {
449 449 CanApply bool
450 450 Commits []CommitRow
451 451 Commit *CommitRow
452 CommitDiff *CommitDiff
452 453 Entries []EntryRow
453 454 TreePath string
454 455 Blob string
@@ -449,6 +449,7 @@ type View struct {
449 CanApply bool
449 CanApply bool
450 Commits []CommitRow
450 Commits []CommitRow
451 Commit *CommitRow
451 Commit *CommitRow
452 CommitDiff *CommitDiff
452 Entries []EntryRow
453 Entries []EntryRow
453 TreePath string
454 TreePath string
454 Blob string
455 Blob string
internal/server/static/commit-mode.js added +13 −0
@@ -0,0 +1,13 @@
1 (function () {
2 var box = document.getElementById("commitdiff");
3 if (!box) {
4 return;
5 }
6 var mode = "inline";
7 try {
8 if (localStorage.getItem("bluegit-diff") === "side") {
9 mode = "side";
10 }
11 } catch (e) {}
12 box.setAttribute("data-mode", mode);
13 })();
@@ -0,0 +1,13 @@
1(function () {
2 var box = document.getElementById("commitdiff");
3 if (!box) {
4 return;
5 }
6 var mode = "inline";
7 try {
8 if (localStorage.getItem("bluegit-diff") === "side") {
9 mode = "side";
10 }
11 } catch (e) {}
12 box.setAttribute("data-mode", mode);
13})();
internal/server/static/commit.js added +39 −0
@@ -0,0 +1,39 @@
1 (function () {
2 var root = document.querySelector("[data-commit-diff]");
3 if (!root) {
4 return;
5 }
6 function mark() {
7 var mode = root.getAttribute("data-mode") === "side" ? "side" : "inline";
8 root.querySelectorAll("[data-diff-mode]").forEach(function (btn) {
9 var on = btn.getAttribute("data-diff-mode") === mode;
10 btn.classList.toggle("on", on);
11 btn.setAttribute("aria-pressed", on ? "true" : "false");
12 });
13 }
14 mark();
15 root.addEventListener("click", function (ev) {
16 var modeBtn = ev.target.closest("[data-diff-mode]");
17 if (modeBtn && root.contains(modeBtn)) {
18 var next = modeBtn.getAttribute("data-diff-mode") === "side" ? "side" : "inline";
19 root.setAttribute("data-mode", next);
20 try {
21 localStorage.setItem("bluegit-diff", next);
22 } catch (e) {}
23 mark();
24 return;
25 }
26 var tog = ev.target.closest("[data-toggle-diff]");
27 if (!tog || !root.contains(tog)) {
28 return;
29 }
30 var file = tog.closest(".commitfile");
31 if (!file) {
32 return;
33 }
34 var open = file.getAttribute("data-collapsed") === "1";
35 file.setAttribute("data-collapsed", open ? "0" : "1");
36 tog.setAttribute("aria-expanded", open ? "true" : "false");
37 tog.textContent = open ? tog.getAttribute("data-hide") : tog.getAttribute("data-show");
38 });
39 })();
@@ -0,0 +1,39 @@
1(function () {
2 var root = document.querySelector("[data-commit-diff]");
3 if (!root) {
4 return;
5 }
6 function mark() {
7 var mode = root.getAttribute("data-mode") === "side" ? "side" : "inline";
8 root.querySelectorAll("[data-diff-mode]").forEach(function (btn) {
9 var on = btn.getAttribute("data-diff-mode") === mode;
10 btn.classList.toggle("on", on);
11 btn.setAttribute("aria-pressed", on ? "true" : "false");
12 });
13 }
14 mark();
15 root.addEventListener("click", function (ev) {
16 var modeBtn = ev.target.closest("[data-diff-mode]");
17 if (modeBtn && root.contains(modeBtn)) {
18 var next = modeBtn.getAttribute("data-diff-mode") === "side" ? "side" : "inline";
19 root.setAttribute("data-mode", next);
20 try {
21 localStorage.setItem("bluegit-diff", next);
22 } catch (e) {}
23 mark();
24 return;
25 }
26 var tog = ev.target.closest("[data-toggle-diff]");
27 if (!tog || !root.contains(tog)) {
28 return;
29 }
30 var file = tog.closest(".commitfile");
31 if (!file) {
32 return;
33 }
34 var open = file.getAttribute("data-collapsed") === "1";
35 file.setAttribute("data-collapsed", open ? "0" : "1");
36 tog.setAttribute("aria-expanded", open ? "true" : "false");
37 tog.textContent = open ? tog.getAttribute("data-hide") : tog.getAttribute("data-show");
38 });
39})();
internal/server/static/style.css +83 −0
@@ -678,6 +678,89 @@ button.section-toggle {
678 678 .spec-table code { font-family: var(--mono); font-size: 0.92em; }
679 679 .spec-list { margin: 0.2rem 0 0; padding-left: 1.2rem; }
680 680 .spec-list li { margin: 0.35rem 0; }
681 main.wide:has(.commitpage) { width: min(100%, 1440px); max-width: 1440px; }
682 .commithead h1 { white-space: normal; overflow-wrap: anywhere; }
683 pre.commitmsg {
684 background: var(--card); color: var(--ink); border: 1px solid var(--line);
685 white-space: pre-wrap; overflow-wrap: anywhere; margin: 0 0 var(--sp-3);
686 }
687 .commitmeta { margin-top: 0; }
688 .commitfacts { display: grid; gap: 0.55rem; margin: 0.9rem 0 0; }
689 .commitfacts div { display: grid; grid-template-columns: 11rem minmax(0, 1fr); gap: 0.7rem; align-items: center; }
690 .commitfacts dt, .commitfacts dd { margin: 0; }
691 .commitfacts dt { color: var(--muted); }
692 .commitfacts code.sha { word-break: break-all; }
693 .commitfacts .parents { display: flex; flex-wrap: wrap; gap: 0.45rem; }
694 .commitfacts a.status { text-decoration: none; width: fit-content; }
695 .diffbar { margin-top: 0; }
696 .diffswitch { display: inline-flex; border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; flex: none; }
697 .diffswitch button { background: white; color: var(--ink); border: 0; border-radius: 0; min-width: 7.5rem; }
698 .diffswitch button + button { border-left: 1px solid var(--line); }
699 .commitdiff[data-mode="inline"] [data-diff-mode="inline"],
700 .commitdiff[data-mode="side"] [data-diff-mode="side"] { background: var(--blue-soft); color: var(--blue-deep); }
701 .commitlayout { display: grid; grid-template-columns: minmax(16rem, 22rem) minmax(0, 1fr); gap: 1rem; align-items: start; }
702 .commitfiles {
703 position: sticky; top: calc(var(--top-h) + 8px); max-height: calc(100vh - var(--top-h) - 16px);
704 overflow: auto; background: var(--card); border: 1px solid var(--line); border-radius: var(--radius-lg);
705 padding: 0.7rem 0.75rem;
706 }
707 .commitfiles h2 { margin: 0 0 0.4rem; font-size: var(--fs-sm); color: var(--muted); }
708 .commitfiles ul { list-style: none; margin: 0; padding: 0; }
709 .commitfiles li {
710 display: flex; align-items: center; gap: 0.35rem; min-height: 1.7rem;
711 font-variant-numeric: tabular-nums;
712 }
713 .commitfiles li.d1 { padding-left: 0.9rem; }
714 .commitfiles li.d2 { padding-left: 1.8rem; }
715 .commitfiles li.d3 { padding-left: 2.7rem; }
716 .commitfiles li.d4 { padding-left: 3.6rem; }
717 .commitfiles li.d5 { padding-left: 4.5rem; }
718 .commitfiles li.d6 { padding-left: 5.4rem; }
719 .commitfiles li.d7 { padding-left: 6.3rem; }
720 .commitfiles li.d8 { padding-left: 7.2rem; }
721 .commitfiles a { display: inline-flex; align-items: center; min-width: 0; color: inherit; text-decoration: none; }
722 .commitfiles .name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
723 .addstat { color: var(--ok); font-variant-numeric: tabular-nums; }
724 .delstat { color: var(--bad); font-variant-numeric: tabular-nums; }
725 .commitdiffs { min-width: 0; }
726 .commitfile {
727 background: var(--card); border: 1px solid var(--line); border-radius: var(--radius-lg);
728 margin: 0 0 0.8rem; scroll-margin-top: calc(var(--top-h) + 12px); min-width: 0;
729 }
730 .commitfile > header {
731 display: flex; align-items: center; gap: 0.5rem; min-height: 44px;
732 padding: 0.35rem 0.7rem; background: #f6f8fa; border-bottom: 1px solid var(--line);
733 border-radius: var(--radius-lg) var(--radius-lg) 0 0; position: sticky; top: var(--top-h); z-index: 2;
734 }
735 .commitfile > header .path { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
736 .commitfile > header .oldpath { color: var(--muted); text-decoration: line-through; }
737 .commitfile > header .counts { flex: none; }
738 .commitfile > header button[data-toggle-diff] { flex: none; min-width: 7.5rem; }
739 .commitfile[data-collapsed="1"] > header { border-bottom: 0; border-radius: var(--radius-lg); }
740 .commitfile[data-collapsed="1"] .diffbody { display: none; }
741 .commitdiff[data-mode="inline"] .split { display: none; }
742 .commitdiff[data-mode="side"] .unified { display: none; }
743 .commitline, .half {
744 display: grid; grid-template-columns: 3.2rem 3.2rem minmax(0, 1fr);
745 font-family: var(--mono); font-size: 0.84rem; line-height: 1.45; min-width: 0;
746 }
747 .half { grid-template-columns: 3.2rem minmax(0, 1fr); }
748 .commitline code, .half code {
749 display: block; white-space: pre; overflow-x: auto; min-width: 0;
750 padding: 0 0.7rem; font-family: inherit;
751 }
752 .commitline .ln, .half .ln { color: #8c959f; text-align: right; padding: 0 0.45rem; user-select: none; }
753 .commitline.kind-add, .half.kind-add { background: #e6ffec; }
754 .commitline.kind-del, .half.kind-del { background: #ffebe9; }
755 .commitline.kind-hunk { grid-template-columns: minmax(0, 1fr); color: #8c959f; background: #f6f8fa; }
756 .half.kind-empty { background: #f6f8fa; }
757 .pair { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); }
758 .pair .half + .half { border-left: 1px solid var(--line); }
759 .binaryhint { margin: 0; padding: 0.8rem 0.9rem; }
760 @media (max-width: 900px) {
761 .commitlayout { grid-template-columns: minmax(0, 1fr); }
762 .commitfiles { position: static; max-height: 16rem; }
763 }
681 764 @media (max-width: 800px) {
682 765 .proj, .fileview, .joblayout { grid-template-columns: minmax(0, 1fr); }
683 766 .proj > *, .fileview > *, .toolbar, .commitbar, .hscroll { min-width: 0; max-width: 100%; }
@@ -678,6 +678,89 @@ button.section-toggle {
678.spec-table code { font-family: var(--mono); font-size: 0.92em; }
678.spec-table code { font-family: var(--mono); font-size: 0.92em; }
679.spec-list { margin: 0.2rem 0 0; padding-left: 1.2rem; }
679.spec-list { margin: 0.2rem 0 0; padding-left: 1.2rem; }
680.spec-list li { margin: 0.35rem 0; }
680.spec-list li { margin: 0.35rem 0; }
681main.wide:has(.commitpage) { width: min(100%, 1440px); max-width: 1440px; }
682.commithead h1 { white-space: normal; overflow-wrap: anywhere; }
683pre.commitmsg {
684 background: var(--card); color: var(--ink); border: 1px solid var(--line);
685 white-space: pre-wrap; overflow-wrap: anywhere; margin: 0 0 var(--sp-3);
686}
687.commitmeta { margin-top: 0; }
688.commitfacts { display: grid; gap: 0.55rem; margin: 0.9rem 0 0; }
689.commitfacts div { display: grid; grid-template-columns: 11rem minmax(0, 1fr); gap: 0.7rem; align-items: center; }
690.commitfacts dt, .commitfacts dd { margin: 0; }
691.commitfacts dt { color: var(--muted); }
692.commitfacts code.sha { word-break: break-all; }
693.commitfacts .parents { display: flex; flex-wrap: wrap; gap: 0.45rem; }
694.commitfacts a.status { text-decoration: none; width: fit-content; }
695.diffbar { margin-top: 0; }
696.diffswitch { display: inline-flex; border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; flex: none; }
697.diffswitch button { background: white; color: var(--ink); border: 0; border-radius: 0; min-width: 7.5rem; }
698.diffswitch button + button { border-left: 1px solid var(--line); }
699.commitdiff[data-mode="inline"] [data-diff-mode="inline"],
700.commitdiff[data-mode="side"] [data-diff-mode="side"] { background: var(--blue-soft); color: var(--blue-deep); }
701.commitlayout { display: grid; grid-template-columns: minmax(16rem, 22rem) minmax(0, 1fr); gap: 1rem; align-items: start; }
702.commitfiles {
703 position: sticky; top: calc(var(--top-h) + 8px); max-height: calc(100vh - var(--top-h) - 16px);
704 overflow: auto; background: var(--card); border: 1px solid var(--line); border-radius: var(--radius-lg);
705 padding: 0.7rem 0.75rem;
706}
707.commitfiles h2 { margin: 0 0 0.4rem; font-size: var(--fs-sm); color: var(--muted); }
708.commitfiles ul { list-style: none; margin: 0; padding: 0; }
709.commitfiles li {
710 display: flex; align-items: center; gap: 0.35rem; min-height: 1.7rem;
711 font-variant-numeric: tabular-nums;
712}
713.commitfiles li.d1 { padding-left: 0.9rem; }
714.commitfiles li.d2 { padding-left: 1.8rem; }
715.commitfiles li.d3 { padding-left: 2.7rem; }
716.commitfiles li.d4 { padding-left: 3.6rem; }
717.commitfiles li.d5 { padding-left: 4.5rem; }
718.commitfiles li.d6 { padding-left: 5.4rem; }
719.commitfiles li.d7 { padding-left: 6.3rem; }
720.commitfiles li.d8 { padding-left: 7.2rem; }
721.commitfiles a { display: inline-flex; align-items: center; min-width: 0; color: inherit; text-decoration: none; }
722.commitfiles .name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
723.addstat { color: var(--ok); font-variant-numeric: tabular-nums; }
724.delstat { color: var(--bad); font-variant-numeric: tabular-nums; }
725.commitdiffs { min-width: 0; }
726.commitfile {
727 background: var(--card); border: 1px solid var(--line); border-radius: var(--radius-lg);
728 margin: 0 0 0.8rem; scroll-margin-top: calc(var(--top-h) + 12px); min-width: 0;
729}
730.commitfile > header {
731 display: flex; align-items: center; gap: 0.5rem; min-height: 44px;
732 padding: 0.35rem 0.7rem; background: #f6f8fa; border-bottom: 1px solid var(--line);
733 border-radius: var(--radius-lg) var(--radius-lg) 0 0; position: sticky; top: var(--top-h); z-index: 2;
734}
735.commitfile > header .path { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
736.commitfile > header .oldpath { color: var(--muted); text-decoration: line-through; }
737.commitfile > header .counts { flex: none; }
738.commitfile > header button[data-toggle-diff] { flex: none; min-width: 7.5rem; }
739.commitfile[data-collapsed="1"] > header { border-bottom: 0; border-radius: var(--radius-lg); }
740.commitfile[data-collapsed="1"] .diffbody { display: none; }
741.commitdiff[data-mode="inline"] .split { display: none; }
742.commitdiff[data-mode="side"] .unified { display: none; }
743.commitline, .half {
744 display: grid; grid-template-columns: 3.2rem 3.2rem minmax(0, 1fr);
745 font-family: var(--mono); font-size: 0.84rem; line-height: 1.45; min-width: 0;
746}
747.half { grid-template-columns: 3.2rem minmax(0, 1fr); }
748.commitline code, .half code {
749 display: block; white-space: pre; overflow-x: auto; min-width: 0;
750 padding: 0 0.7rem; font-family: inherit;
751}
752.commitline .ln, .half .ln { color: #8c959f; text-align: right; padding: 0 0.45rem; user-select: none; }
753.commitline.kind-add, .half.kind-add { background: #e6ffec; }
754.commitline.kind-del, .half.kind-del { background: #ffebe9; }
755.commitline.kind-hunk { grid-template-columns: minmax(0, 1fr); color: #8c959f; background: #f6f8fa; }
756.half.kind-empty { background: #f6f8fa; }
757.pair { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); }
758.pair .half + .half { border-left: 1px solid var(--line); }
759.binaryhint { margin: 0; padding: 0.8rem 0.9rem; }
760@media (max-width: 900px) {
761 .commitlayout { grid-template-columns: minmax(0, 1fr); }
762 .commitfiles { position: static; max-height: 16rem; }
763}
681@media (max-width: 800px) {
764@media (max-width: 800px) {
682 .proj, .fileview, .joblayout { grid-template-columns: minmax(0, 1fr); }
765 .proj, .fileview, .joblayout { grid-template-columns: minmax(0, 1fr); }
683 .proj > *, .fileview > *, .toolbar, .commitbar, .hscroll { min-width: 0; max-width: 100%; }
766 .proj > *, .fileview > *, .toolbar, .commitbar, .hscroll { min-width: 0; max-width: 100%; }
internal/server/templates/commit.html added +105 −0
@@ -0,0 +1,105 @@
1 {{define "commit"}}
2 {{template "layout-start" .}}
3 <article class="commitpage">
4 <header class="commithead"><h1>{{.Commit.Subject}}</h1></header>
5 {{if .Commit.Body}}<pre class="commitmsg">{{.Commit.Body}}</pre>{{end}}
6 <section class="card commitmeta">
7 <div class="projhead">
8 {{template "avatar" .Commit}}
9 <div>
10 <p>{{template "commitwho" .Commit}}</p>
11 <p class="muted">{{t "commit.authored"}} {{.Commit.Date}}{{if .Commit.When}} · {{.Commit.When}}{{end}}</p>
12 </div>
13 </div>
14 <dl class="commitfacts">
15 <div>
16 <dt>{{t "commit.sha"}}</dt>
17 <dd><code class="sha">{{.Commit.SHA}}</code> <button type="button" class="iconbtn" data-copy="{{.Commit.SHA}}" aria-label="{{t "action.copy"}}">{{t "action.copy"}}</button></dd>
18 </div>
19 {{if .CommitDiff.Parents}}
20 <div>
21 <dt>{{if eq (len .CommitDiff.Parents) 1}}{{t "commit.parent"}}{{else}}{{t "commit.parents"}}{{end}}</dt>
22 <dd class="parents">{{range .CommitDiff.Parents}}<a href="/{{$.Repo.FullPath}}/-/commit/{{.SHA}}"><code>{{.Short}}</code></a>{{end}}</dd>
23 </div>
24 {{end}}
25 {{if .Commit.PipeStatus}}
26 <div>
27 <dt>{{t "pipe.one"}}</dt>
28 <dd><a class="status {{.Commit.PipeStatus}}" href="/{{$.Repo.FullPath}}/-/pipelines/{{.Commit.PipeID}}"><span class="mark"></span>{{.Commit.PipeLabel}}</a></dd>
29 </div>
30 {{end}}
31 </dl>
32 </section>
33 {{if not .CommitDiff.Files}}
34 <p class="muted">{{t "commit.empty"}}</p>
35 {{else}}
36 <div class="commitdiff" id="commitdiff" data-commit-diff data-mode="inline">
37 <script src="/assets/commit-mode.js"></script>
38 <div class="commitbar diffbar">
39 <div class="grow">
40 <strong>{{tn .CommitDiff.FilesN "commit.file.one" "commit.file.many"}}</strong>
41 <span class="addstat">+{{.CommitDiff.Added}}</span>
42 <span class="delstat">−{{.CommitDiff.Deleted}}</span>
43 </div>
44 <div class="diffswitch" role="group" aria-label="{{t "commit.view"}}">
45 <button type="button" data-diff-mode="inline" aria-pressed="true">{{t "commit.inline"}}</button>
46 <button type="button" data-diff-mode="side" aria-pressed="false">{{t "commit.side"}}</button>
47 </div>
48 </div>
49 <div class="commitlayout">
50 <nav class="commitfiles" aria-label="{{t "commit.changed"}}">
51 <h2>{{t "commit.changed"}}</h2>
52 <ul>
53 {{range .CommitDiff.Tree}}
54 <li class="d{{.Depth}}">
55 {{if .Dir}}{{template "ficon" .Icon}}<span>{{.Name}}</span>{{else}}<a href="#{{.Anchor}}" data-diff-link="{{.Anchor}}">{{template "ficon" .Icon}}<span class="name">{{.Name}}</span></a> <span class="addstat">+{{.Added}}</span><span class="delstat">−{{.Deleted}}</span>{{end}}
56 </li>
57 {{end}}
58 </ul>
59 </nav>
60 <div class="commitdiffs">
61 {{range .CommitDiff.Files}}
62 <section class="commitfile" id="{{.Anchor}}" data-path="{{.Path}}" data-collapsed="{{if .Collapsed}}1{{else}}0{{end}}">
63 <header>
64 {{if .HasBody}}<button type="button" class="ghost" data-toggle-diff data-show="{{t "commit.show"}}" data-hide="{{t "commit.hide"}}" aria-expanded="{{if .Collapsed}}false{{else}}true{{end}}">{{if .Collapsed}}{{t "commit.show"}}{{else}}{{t "commit.hide"}}{{end}}</button>{{end}}
65 <span class="path">{{if .OldPath}}<span class="oldpath">{{.OldPath}}</span> <span aria-hidden="true">→</span> {{end}}{{if .FileURL}}<a href="{{.FileURL}}">{{.Path}}</a>{{else}}{{.Path}}{{end}}</span>
66 {{if eq .Status "added"}}<span class="pill">{{t "commit.added"}}</span>{{else if eq .Status "deleted"}}<span class="pill">{{t "commit.deleted"}}</span>{{else if eq .Status "renamed"}}<span class="pill">{{t "commit.renamed"}}</span>{{end}}
67 {{if .Binary}}<span class="pill">{{t "commit.binary"}}</span>{{end}}
68 <span class="counts"><span class="addstat">+{{.Added}}</span> <span class="delstat">−{{.Deleted}}</span></span>
69 </header>
70 {{if .HasBody}}
71 <div class="diffbody">
72 {{if .Binary}}<p class="muted binaryhint">{{t "commit.binaryHint"}}</p>{{else}}
73 <div class="unified">
74 {{range .Lines}}
75 <div class="commitline kind-{{.Kind}}">
76 <span class="ln">{{if .Old}}{{.Old}}{{end}}</span>
77 <span class="ln">{{if .New}}{{.New}}{{end}}</span>
78 <code>{{.HTML}}</code>
79 </div>
80 {{end}}
81 </div>
82 <div class="split">
83 {{range .Pairs}}
84 {{if .Hunk}}<div class="commitline kind-hunk"><code>{{.Hunk}}</code></div>{{else}}
85 <div class="pair">
86 <div class="half kind-{{if .LKind}}{{.LKind}}{{else}}empty{{end}}"><span class="ln">{{if .LNo}}{{.LNo}}{{end}}</span><code>{{.LHTML}}</code></div>
87 <div class="half kind-{{if .RKind}}{{.RKind}}{{else}}empty{{end}}"><span class="ln">{{if .RNo}}{{.RNo}}{{end}}</span><code>{{.RHTML}}</code></div>
88 </div>
89 {{end}}
90 {{end}}
91 </div>
92 {{end}}
93 </div>
94 {{end}}
95 </section>
96 {{end}}
97 </div>
98 </div>
99 </div>
100 <script src="/assets/commit.js"></script>
101 {{end}}
102 </article>
103 <script src="/assets/repo.js"></script>
104 {{template "layout-end" .}}
105 {{end}}
@@ -0,0 +1,105 @@
1{{define "commit"}}
2{{template "layout-start" .}}
3<article class="commitpage">
4<header class="commithead"><h1>{{.Commit.Subject}}</h1></header>
5{{if .Commit.Body}}<pre class="commitmsg">{{.Commit.Body}}</pre>{{end}}
6<section class="card commitmeta">
7 <div class="projhead">
8 {{template "avatar" .Commit}}
9 <div>
10 <p>{{template "commitwho" .Commit}}</p>
11 <p class="muted">{{t "commit.authored"}} {{.Commit.Date}}{{if .Commit.When}} · {{.Commit.When}}{{end}}</p>
12 </div>
13 </div>
14 <dl class="commitfacts">
15 <div>
16 <dt>{{t "commit.sha"}}</dt>
17 <dd><code class="sha">{{.Commit.SHA}}</code> <button type="button" class="iconbtn" data-copy="{{.Commit.SHA}}" aria-label="{{t "action.copy"}}">{{t "action.copy"}}</button></dd>
18 </div>
19 {{if .CommitDiff.Parents}}
20 <div>
21 <dt>{{if eq (len .CommitDiff.Parents) 1}}{{t "commit.parent"}}{{else}}{{t "commit.parents"}}{{end}}</dt>
22 <dd class="parents">{{range .CommitDiff.Parents}}<a href="/{{$.Repo.FullPath}}/-/commit/{{.SHA}}"><code>{{.Short}}</code></a>{{end}}</dd>
23 </div>
24 {{end}}
25 {{if .Commit.PipeStatus}}
26 <div>
27 <dt>{{t "pipe.one"}}</dt>
28 <dd><a class="status {{.Commit.PipeStatus}}" href="/{{$.Repo.FullPath}}/-/pipelines/{{.Commit.PipeID}}"><span class="mark"></span>{{.Commit.PipeLabel}}</a></dd>
29 </div>
30 {{end}}
31 </dl>
32</section>
33{{if not .CommitDiff.Files}}
34<p class="muted">{{t "commit.empty"}}</p>
35{{else}}
36<div class="commitdiff" id="commitdiff" data-commit-diff data-mode="inline">
37<script src="/assets/commit-mode.js"></script>
38<div class="commitbar diffbar">
39 <div class="grow">
40 <strong>{{tn .CommitDiff.FilesN "commit.file.one" "commit.file.many"}}</strong>
41 <span class="addstat">+{{.CommitDiff.Added}}</span>
42 <span class="delstat">−{{.CommitDiff.Deleted}}</span>
43 </div>
44 <div class="diffswitch" role="group" aria-label="{{t "commit.view"}}">
45 <button type="button" data-diff-mode="inline" aria-pressed="true">{{t "commit.inline"}}</button>
46 <button type="button" data-diff-mode="side" aria-pressed="false">{{t "commit.side"}}</button>
47 </div>
48</div>
49<div class="commitlayout">
50 <nav class="commitfiles" aria-label="{{t "commit.changed"}}">
51 <h2>{{t "commit.changed"}}</h2>
52 <ul>
53 {{range .CommitDiff.Tree}}
54 <li class="d{{.Depth}}">
55 {{if .Dir}}{{template "ficon" .Icon}}<span>{{.Name}}</span>{{else}}<a href="#{{.Anchor}}" data-diff-link="{{.Anchor}}">{{template "ficon" .Icon}}<span class="name">{{.Name}}</span></a> <span class="addstat">+{{.Added}}</span><span class="delstat">−{{.Deleted}}</span>{{end}}
56 </li>
57 {{end}}
58 </ul>
59 </nav>
60 <div class="commitdiffs">
61 {{range .CommitDiff.Files}}
62 <section class="commitfile" id="{{.Anchor}}" data-path="{{.Path}}" data-collapsed="{{if .Collapsed}}1{{else}}0{{end}}">
63 <header>
64 {{if .HasBody}}<button type="button" class="ghost" data-toggle-diff data-show="{{t "commit.show"}}" data-hide="{{t "commit.hide"}}" aria-expanded="{{if .Collapsed}}false{{else}}true{{end}}">{{if .Collapsed}}{{t "commit.show"}}{{else}}{{t "commit.hide"}}{{end}}</button>{{end}}
65 <span class="path">{{if .OldPath}}<span class="oldpath">{{.OldPath}}</span> <span aria-hidden="true">→</span> {{end}}{{if .FileURL}}<a href="{{.FileURL}}">{{.Path}}</a>{{else}}{{.Path}}{{end}}</span>
66 {{if eq .Status "added"}}<span class="pill">{{t "commit.added"}}</span>{{else if eq .Status "deleted"}}<span class="pill">{{t "commit.deleted"}}</span>{{else if eq .Status "renamed"}}<span class="pill">{{t "commit.renamed"}}</span>{{end}}
67 {{if .Binary}}<span class="pill">{{t "commit.binary"}}</span>{{end}}
68 <span class="counts"><span class="addstat">+{{.Added}}</span> <span class="delstat">−{{.Deleted}}</span></span>
69 </header>
70 {{if .HasBody}}
71 <div class="diffbody">
72 {{if .Binary}}<p class="muted binaryhint">{{t "commit.binaryHint"}}</p>{{else}}
73 <div class="unified">
74 {{range .Lines}}
75 <div class="commitline kind-{{.Kind}}">
76 <span class="ln">{{if .Old}}{{.Old}}{{end}}</span>
77 <span class="ln">{{if .New}}{{.New}}{{end}}</span>
78 <code>{{.HTML}}</code>
79 </div>
80 {{end}}
81 </div>
82 <div class="split">
83 {{range .Pairs}}
84 {{if .Hunk}}<div class="commitline kind-hunk"><code>{{.Hunk}}</code></div>{{else}}
85 <div class="pair">
86 <div class="half kind-{{if .LKind}}{{.LKind}}{{else}}empty{{end}}"><span class="ln">{{if .LNo}}{{.LNo}}{{end}}</span><code>{{.LHTML}}</code></div>
87 <div class="half kind-{{if .RKind}}{{.RKind}}{{else}}empty{{end}}"><span class="ln">{{if .RNo}}{{.RNo}}{{end}}</span><code>{{.RHTML}}</code></div>
88 </div>
89 {{end}}
90 {{end}}
91 </div>
92 {{end}}
93 </div>
94 {{end}}
95 </section>
96 {{end}}
97 </div>
98</div>
99</div>
100<script src="/assets/commit.js"></script>
101{{end}}
102</article>
103<script src="/assets/repo.js"></script>
104{{template "layout-end" .}}
105{{end}}
internal/server/templates/pages.html +0 −14
@@ -456,20 +456,6 @@
456 456 {{template "layout-end" .}}
457 457 {{end}}
458 458
459 {{define "commit"}}
460 {{template "layout-start" .}}
461 <header class="pagehead"><h1>{{.Commit.Subject}}</h1></header>
462 <div class="projhead">
463 {{template "avatar" .Commit}}
464 <div>
465 <p>{{template "commitwho" .Commit}}</p>
466 <p class="muted">{{.Commit.SHA}} · {{.Commit.Date}}</p>
467 </div>
468 </div>
469 {{if .Commit.Body}}<pre>{{.Commit.Body}}</pre>{{end}}
470 {{template "layout-end" .}}
471 {{end}}
472
473 459 {{define "branches"}}
474 460 {{template "layout-start" .}}
475 461 <header class="pagehead"><h1>{{t "title.branches"}}</h1></header>
@@ -456,20 +456,6 @@
456{{template "layout-end" .}}
456{{template "layout-end" .}}
457{{end}}
457{{end}}
458
458
459{{define "commit"}}
460{{template "layout-start" .}}
461<header class="pagehead"><h1>{{.Commit.Subject}}</h1></header>
462<div class="projhead">
463 {{template "avatar" .Commit}}
464 <div>
465 <p>{{template "commitwho" .Commit}}</p>
466 <p class="muted">{{.Commit.SHA}} · {{.Commit.Date}}</p>
467 </div>
468</div>
469{{if .Commit.Body}}<pre>{{.Commit.Body}}</pre>{{end}}
470{{template "layout-end" .}}
471{{end}}
472
473{{define "branches"}}
459{{define "branches"}}
474{{template "layout-start" .}}
460{{template "layout-start" .}}
475<header class="pagehead"><h1>{{t "title.branches"}}</h1></header>
461<header class="pagehead"><h1>{{t "title.branches"}}</h1></header>