feat: stuur bestandsdetails en een diff-URL mee in webhooks
Push-commits en merge requests bevatten reviewers, comments, commits en regelaantallen. De difftekst zelf blijft achter een token-API. Co-authored-by: tim <tim@timfalken.com>
@@ -0,0 +1,208 @@
1
package gitrepo
2
3
import (
4
"context"
5
"fmt"
6
"strconv"
7
"strings"
8
)
9
10
// Change is één bestand in een diff, zonder de difftekst zelf.
11
// Status is added, modified, removed of renamed.
12
type Change struct {
13
Path string
14
OldPath string
15
Status string
16
Added int
17
Deleted int
18
Binary bool
19
}
20
21
// CommitChanges geeft de bestanden die sha tegen zijn eerste parent wijzigt.
22
// Een root-commit wordt met de lege boom vergeleken.
23
func CommitChanges(ctx context.Context, gitBin, dir, sha string) ([]Change, error) {
24
base, err := diffBase(ctx, gitBin, dir, sha)
25
if err != nil {
26
return nil, err
27
}
28
return diffChanges(ctx, gitBin, dir, base, sha)
29
}
30
31
// CompareChanges is de three-dot diff van from...to, zonder de difftekst.
32
func CompareChanges(ctx context.Context, gitBin, dir, from, to string) ([]Change, error) {
33
if from == "" || to == "" {
34
return nil, fmt.Errorf("lege vergelijking")
35
}
36
return diffChanges(ctx, gitBin, dir, from+"..."+to)
37
}
38
39
// CommitDiff is de unified diff van sha tegen zijn eerste parent.
40
func CommitDiff(ctx context.Context, gitBin, dir, sha string) (string, error) {
41
base, err := diffBase(ctx, gitBin, dir, sha)
42
if err != nil {
43
return "", err
44
}
45
return unifiedDiff(ctx, gitBin, dir, base, sha)
46
}
47
48
// CompareDiff is de unified three-dot diff van from...to.
49
func CompareDiff(ctx context.Context, gitBin, dir, from, to string) (string, error) {
50
if from == "" || to == "" {
51
return "", fmt.Errorf("lege vergelijking")
52
}
53
return unifiedDiff(ctx, gitBin, dir, from+"..."+to)
54
}
55
56
func diffBase(ctx context.Context, gitBin, dir, sha string) (string, error) {
57
out, err := run(ctx, gitBin, nil, "-C", dir, "rev-list", "--parents", "-n", "1", sha)
58
if err != nil {
59
return "", err
60
}
61
fields := strings.Fields(out)
62
if len(fields) == 0 {
63
return "", fmt.Errorf("commit niet gevonden")
64
}
65
if len(fields) > 1 {
66
return fields[1], nil
67
}
68
empty, err := run(ctx, gitBin, nil, "hash-object", "-t", "tree", "--stdin")
69
if err != nil {
70
return "", err
71
}
72
return strings.TrimSpace(empty), nil
73
}
74
75
func diffChanges(ctx context.Context, gitBin, dir string, revs ...string) ([]Change, error) {
76
nameRaw, err := gitDiff(ctx, gitBin, dir, append([]string{"--name-status", "--find-renames", "-z"}, revs...)...)
77
if err != nil {
78
return nil, err
79
}
80
numRaw, err := gitDiff(ctx, gitBin, dir, append([]string{"--numstat", "--find-renames", "-z"}, revs...)...)
81
if err != nil {
82
return nil, err
83
}
84
files := parseNameStatus(nameRaw)
85
counts, binary := parseNumstat(numRaw)
86
for i := range files {
87
key := files[i].Path
88
if n, ok := counts[key]; ok {
89
files[i].Added, files[i].Deleted = n[0], n[1]
90
}
91
if binary[key] {
92
files[i].Binary = true
93
files[i].Added, files[i].Deleted = 0, 0
94
}
95
}
96
if files == nil {
97
files = []Change{}
98
}
99
return files, nil
100
}
101
102
func unifiedDiff(ctx context.Context, gitBin, dir string, revs ...string) (string, error) {
103
return gitDiff(ctx, gitBin, dir, append([]string{"--no-color", "--find-renames", "--unified=3"}, revs...)...)
104
}
105
106
func gitDiff(ctx context.Context, gitBin, dir string, flags ...string) (string, error) {
107
args := []string{"-c", "core.quotepath=false", "-C", dir, "diff"}
108
args = append(args, flags...)
109
return runAllow(ctx, gitBin, nil, 1, args...)
110
}
111
112
func parseNameStatus(raw string) []Change {
113
parts := strings.Split(raw, "\x00")
114
var out []Change
115
for i := 0; i < len(parts); {
116
status := parts[i]
117
if status == "" {
118
i++
119
continue
120
}
121
i++
122
if i >= len(parts) {
123
break
124
}
125
if strings.HasPrefix(status, "R") || strings.HasPrefix(status, "C") {
126
old := parts[i]
127
i++
128
if i >= len(parts) {
129
break
130
}
131
path := parts[i]
132
i++
133
st := "renamed"
134
if strings.HasPrefix(status, "C") {
135
st = "modified"
136
}
137
out = append(out, Change{Path: path, OldPath: old, Status: st})
138
continue
139
}
140
out = append(out, Change{Path: parts[i], Status: changeStatus(status)})
141
i++
142
}
143
return out
144
}
145
146
func changeStatus(status string) string {
147
switch status {
148
case "A":
149
return "added"
150
case "D":
151
return "removed"
152
default:
153
return "modified"
154
}
155
}
156
157
func parseNumstat(raw string) (map[string][2]int, map[string]bool) {
158
counts := map[string][2]int{}
159
binary := map[string]bool{}
160
for _, rec := range strings.Split(raw, "\x00") {
161
rec = strings.TrimRight(rec, "\n")
162
if rec == "" {
163
continue
164
}
165
added, deleted, path, ok := splitNumstat(rec)
166
if !ok || path == "" {
167
continue
168
}
169
path = numstatPath(path)
170
if added == "-" || deleted == "-" {
171
binary[path] = true
172
continue
173
}
174
a, aErr := strconv.Atoi(added)
175
d, dErr := strconv.Atoi(deleted)
176
if aErr != nil || dErr != nil {
177
continue
178
}
179
counts[path] = [2]int{a, d}
180
}
181
return counts, binary
182
}
183
184
func splitNumstat(rec string) (added, deleted, path string, ok bool) {
185
tab := strings.IndexByte(rec, '\t')
186
if tab < 0 {
187
return "", "", "", false
188
}
189
tab2 := strings.IndexByte(rec[tab+1:], '\t')
190
if tab2 < 0 {
191
return "", "", "", false
192
}
193
tab2 += tab + 1
194
return rec[:tab], rec[tab+1 : tab2], rec[tab2+1:], true
195
}
196
197
func numstatPath(path string) string {
198
brace := strings.Index(path, "{")
199
arrow := strings.Index(path, " => ")
200
end := strings.Index(path, "}")
201
if brace >= 0 && arrow > brace && end > arrow {
202
return path[:brace] + path[arrow+4:end] + path[end+1:]
203
}
204
if arrow >= 0 {
205
return path[arrow+4:]
206
}
207
return path
208
}
@@ -0,0 +1,208 @@1
package gitrepo2
3
import (4
"context"5
"fmt"6
"strconv"7
"strings"8
)9
10
// Change is één bestand in een diff, zonder de difftekst zelf.11
// Status is added, modified, removed of renamed.12
type Change struct {13
Path string14
OldPath string15
Status string16
Added int17
Deleted int18
Binary bool19
}20
21
// CommitChanges geeft de bestanden die sha tegen zijn eerste parent wijzigt.22
// Een root-commit wordt met de lege boom vergeleken.23
func CommitChanges(ctx context.Context, gitBin, dir, sha string) ([]Change, error) {24
base, err := diffBase(ctx, gitBin, dir, sha)25
if err != nil {26
return nil, err27
}28
return diffChanges(ctx, gitBin, dir, base, sha)29
}30
31
// CompareChanges is de three-dot diff van from...to, zonder de difftekst.32
func CompareChanges(ctx context.Context, gitBin, dir, from, to string) ([]Change, error) {33
if from == "" || to == "" {34
return nil, fmt.Errorf("lege vergelijking")35
}36
return diffChanges(ctx, gitBin, dir, from+"..."+to)37
}38
39
// CommitDiff is de unified diff van sha tegen zijn eerste parent.40
func CommitDiff(ctx context.Context, gitBin, dir, sha string) (string, error) {41
base, err := diffBase(ctx, gitBin, dir, sha)42
if err != nil {43
return "", err44
}45
return unifiedDiff(ctx, gitBin, dir, base, sha)46
}47
48
// CompareDiff is de unified three-dot diff van from...to.49
func CompareDiff(ctx context.Context, gitBin, dir, from, to string) (string, error) {50
if from == "" || to == "" {51
return "", fmt.Errorf("lege vergelijking")52
}53
return unifiedDiff(ctx, gitBin, dir, from+"..."+to)54
}55
56
func diffBase(ctx context.Context, gitBin, dir, sha string) (string, error) {57
out, err := run(ctx, gitBin, nil, "-C", dir, "rev-list", "--parents", "-n", "1", sha)58
if err != nil {59
return "", err60
}61
fields := strings.Fields(out)62
if len(fields) == 0 {63
return "", fmt.Errorf("commit niet gevonden")64
}65
if len(fields) > 1 {66
return fields[1], nil67
}68
empty, err := run(ctx, gitBin, nil, "hash-object", "-t", "tree", "--stdin")69
if err != nil {70
return "", err71
}72
return strings.TrimSpace(empty), nil73
}74
75
func diffChanges(ctx context.Context, gitBin, dir string, revs ...string) ([]Change, error) {76
nameRaw, err := gitDiff(ctx, gitBin, dir, append([]string{"--name-status", "--find-renames", "-z"}, revs...)...)77
if err != nil {78
return nil, err79
}80
numRaw, err := gitDiff(ctx, gitBin, dir, append([]string{"--numstat", "--find-renames", "-z"}, revs...)...)81
if err != nil {82
return nil, err83
}84
files := parseNameStatus(nameRaw)85
counts, binary := parseNumstat(numRaw)86
for i := range files {87
key := files[i].Path88
if n, ok := counts[key]; ok {89
files[i].Added, files[i].Deleted = n[0], n[1]90
}91
if binary[key] {92
files[i].Binary = true93
files[i].Added, files[i].Deleted = 0, 094
}95
}96
if files == nil {97
files = []Change{}98
}99
return files, nil100
}101
102
func unifiedDiff(ctx context.Context, gitBin, dir string, revs ...string) (string, error) {103
return gitDiff(ctx, gitBin, dir, append([]string{"--no-color", "--find-renames", "--unified=3"}, revs...)...)104
}105
106
func gitDiff(ctx context.Context, gitBin, dir string, flags ...string) (string, error) {107
args := []string{"-c", "core.quotepath=false", "-C", dir, "diff"}108
args = append(args, flags...)109
return runAllow(ctx, gitBin, nil, 1, args...)110
}111
112
func parseNameStatus(raw string) []Change {113
parts := strings.Split(raw, "\x00")114
var out []Change115
for i := 0; i < len(parts); {116
status := parts[i]117
if status == "" {118
i++119
continue120
}121
i++122
if i >= len(parts) {123
break124
}125
if strings.HasPrefix(status, "R") || strings.HasPrefix(status, "C") {126
old := parts[i]127
i++128
if i >= len(parts) {129
break130
}131
path := parts[i]132
i++133
st := "renamed"134
if strings.HasPrefix(status, "C") {135
st = "modified"136
}137
out = append(out, Change{Path: path, OldPath: old, Status: st})138
continue139
}140
out = append(out, Change{Path: parts[i], Status: changeStatus(status)})141
i++142
}143
return out144
}145
146
func changeStatus(status string) string {147
switch status {148
case "A":149
return "added"150
case "D":151
return "removed"152
default:153
return "modified"154
}155
}156
157
func parseNumstat(raw string) (map[string][2]int, map[string]bool) {158
counts := map[string][2]int{}159
binary := map[string]bool{}160
for _, rec := range strings.Split(raw, "\x00") {161
rec = strings.TrimRight(rec, "\n")162
if rec == "" {163
continue164
}165
added, deleted, path, ok := splitNumstat(rec)166
if !ok || path == "" {167
continue168
}169
path = numstatPath(path)170
if added == "-" || deleted == "-" {171
binary[path] = true172
continue173
}174
a, aErr := strconv.Atoi(added)175
d, dErr := strconv.Atoi(deleted)176
if aErr != nil || dErr != nil {177
continue178
}179
counts[path] = [2]int{a, d}180
}181
return counts, binary182
}183
184
func splitNumstat(rec string) (added, deleted, path string, ok bool) {185
tab := strings.IndexByte(rec, '\t')186
if tab < 0 {187
return "", "", "", false188
}189
tab2 := strings.IndexByte(rec[tab+1:], '\t')190
if tab2 < 0 {191
return "", "", "", false192
}193
tab2 += tab + 1194
return rec[:tab], rec[tab+1 : tab2], rec[tab2+1:], true195
}196
197
func numstatPath(path string) string {198
brace := strings.Index(path, "{")199
arrow := strings.Index(path, " => ")200
end := strings.Index(path, "}")201
if brace >= 0 && arrow > brace && end > arrow {202
return path[:brace] + path[arrow+4:end] + path[end+1:]203
}204
if arrow >= 0 {205
return path[arrow+4:]206
}207
return path208
}@@ -0,0 +1,92 @@
1
package gitrepo
2
3
import (
4
"context"
5
"os"
6
"os/exec"
7
"path/filepath"
8
"strings"
9
"testing"
10
)
11
12
func TestParseNameStatusAndNumstat(t *testing.T) {
13
files := parseNameStatus("M\x00README.md\x00A\x00extra.txt\x00D\x00oud.txt\x00R100\x00oude naam.txt\x00nieuwe naam.txt\x00")
14
if len(files) != 4 {
15
t.Fatalf("bestanden %d", len(files))
16
}
17
if files[0].Status != "modified" || files[0].Path != "README.md" {
18
t.Fatalf("gewijzigd %v", files[0])
19
}
20
if files[1].Status != "added" || files[2].Status != "removed" {
21
t.Fatalf("toegevoegd of weg %v %v", files[1], files[2])
22
}
23
if files[3].Status != "renamed" || files[3].OldPath != "oude naam.txt" || files[3].Path != "nieuwe naam.txt" {
24
t.Fatalf("hernoemd %v", files[3])
25
}
26
counts, binary := parseNumstat("1\t2\tREADME.md\x00-\t-\tplaatje.bin\x00")
27
if counts["README.md"] != [2]int{1, 2} || !binary["plaatje.bin"] {
28
t.Fatalf("numstat %v %v", counts, binary)
29
}
30
if got := numstatPath("dir/{oud => nieuw}/a.txt"); got != "dir/nieuw/a.txt" {
31
t.Fatalf("brace %s", got)
32
}
33
}
34
35
func TestCommitChangesAndDiff(t *testing.T) {
36
if _, err := exec.LookPath("git"); err != nil {
37
t.Skip("git ontbreekt")
38
}
39
dir := t.TempDir()
40
git := func(args ...string) {
41
t.Helper()
42
cmd := exec.Command("git", args...)
43
cmd.Dir = dir
44
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")
45
if out, err := cmd.CombinedOutput(); err != nil {
46
t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
47
}
48
}
49
git("init", "-b", "master")
50
if err := os.WriteFile(filepath.Join(dir, "README.md"), []byte("a\n"), 0o644); err != nil {
51
t.Fatal(err)
52
}
53
git("add", "README.md")
54
git("commit", "-m", "eerste")
55
sha := strings.TrimSpace(mustGit(t, dir, "rev-parse", "HEAD"))
56
ctx := context.Background()
57
files, err := CommitChanges(ctx, "git", dir, sha)
58
if err != nil {
59
t.Fatal(err)
60
}
61
if len(files) != 1 || files[0].Path != "README.md" || files[0].Status != "added" || files[0].Added != 1 || files[0].Deleted != 0 {
62
t.Fatalf("root %v", files)
63
}
64
diff, err := CommitDiff(ctx, "git", dir, sha)
65
if err != nil || !strings.Contains(diff, "diff --git") || !strings.Contains(diff, "+a") {
66
t.Fatalf("diff %v %q", err, diff)
67
}
68
if err := os.WriteFile(filepath.Join(dir, "README.md"), []byte("b\n"), 0o644); err != nil {
69
t.Fatal(err)
70
}
71
git("add", "README.md")
72
git("commit", "-m", "tweede")
73
sha = strings.TrimSpace(mustGit(t, dir, "rev-parse", "HEAD"))
74
files, err = CommitChanges(ctx, "git", dir, sha)
75
if err != nil {
76
t.Fatal(err)
77
}
78
if len(files) != 1 || files[0].Status != "modified" || files[0].Added != 1 || files[0].Deleted != 1 {
79
t.Fatalf("wijziging %v", files)
80
}
81
}
82
83
func mustGit(t *testing.T, dir string, args ...string) string {
84
t.Helper()
85
cmd := exec.Command("git", args...)
86
cmd.Dir = dir
87
out, err := cmd.CombinedOutput()
88
if err != nil {
89
t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
90
}
91
return string(out)
92
}
@@ -0,0 +1,92 @@1
package gitrepo2
3
import (4
"context"5
"os"6
"os/exec"7
"path/filepath"8
"strings"9
"testing"10
)11
12
func TestParseNameStatusAndNumstat(t *testing.T) {13
files := parseNameStatus("M\x00README.md\x00A\x00extra.txt\x00D\x00oud.txt\x00R100\x00oude naam.txt\x00nieuwe naam.txt\x00")14
if len(files) != 4 {15
t.Fatalf("bestanden %d", len(files))16
}17
if files[0].Status != "modified" || files[0].Path != "README.md" {18
t.Fatalf("gewijzigd %v", files[0])19
}20
if files[1].Status != "added" || files[2].Status != "removed" {21
t.Fatalf("toegevoegd of weg %v %v", files[1], files[2])22
}23
if files[3].Status != "renamed" || files[3].OldPath != "oude naam.txt" || files[3].Path != "nieuwe naam.txt" {24
t.Fatalf("hernoemd %v", files[3])25
}26
counts, binary := parseNumstat("1\t2\tREADME.md\x00-\t-\tplaatje.bin\x00")27
if counts["README.md"] != [2]int{1, 2} || !binary["plaatje.bin"] {28
t.Fatalf("numstat %v %v", counts, binary)29
}30
if got := numstatPath("dir/{oud => nieuw}/a.txt"); got != "dir/nieuw/a.txt" {31
t.Fatalf("brace %s", got)32
}33
}34
35
func TestCommitChangesAndDiff(t *testing.T) {36
if _, err := exec.LookPath("git"); err != nil {37
t.Skip("git ontbreekt")38
}39
dir := t.TempDir()40
git := func(args ...string) {41
t.Helper()42
cmd := exec.Command("git", args...)43
cmd.Dir = dir44
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")45
if out, err := cmd.CombinedOutput(); err != nil {46
t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)47
}48
}49
git("init", "-b", "master")50
if err := os.WriteFile(filepath.Join(dir, "README.md"), []byte("a\n"), 0o644); err != nil {51
t.Fatal(err)52
}53
git("add", "README.md")54
git("commit", "-m", "eerste")55
sha := strings.TrimSpace(mustGit(t, dir, "rev-parse", "HEAD"))56
ctx := context.Background()57
files, err := CommitChanges(ctx, "git", dir, sha)58
if err != nil {59
t.Fatal(err)60
}61
if len(files) != 1 || files[0].Path != "README.md" || files[0].Status != "added" || files[0].Added != 1 || files[0].Deleted != 0 {62
t.Fatalf("root %v", files)63
}64
diff, err := CommitDiff(ctx, "git", dir, sha)65
if err != nil || !strings.Contains(diff, "diff --git") || !strings.Contains(diff, "+a") {66
t.Fatalf("diff %v %q", err, diff)67
}68
if err := os.WriteFile(filepath.Join(dir, "README.md"), []byte("b\n"), 0o644); err != nil {69
t.Fatal(err)70
}71
git("add", "README.md")72
git("commit", "-m", "tweede")73
sha = strings.TrimSpace(mustGit(t, dir, "rev-parse", "HEAD"))74
files, err = CommitChanges(ctx, "git", dir, sha)75
if err != nil {76
t.Fatal(err)77
}78
if len(files) != 1 || files[0].Status != "modified" || files[0].Added != 1 || files[0].Deleted != 1 {79
t.Fatalf("wijziging %v", files)80
}81
}82
83
func mustGit(t *testing.T, dir string, args ...string) string {84
t.Helper()85
cmd := exec.Command("git", args...)86
cmd.Dir = dir87
out, err := cmd.CombinedOutput()88
if err != nil {89
t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)90
}91
return string(out)92
}@@ -10,7 +10,7 @@ func init() {
10
10
var webhookEN = map[string]string{
11
11
"info.sec.webhooks": "Webhook payloads",
12
12
"info.wh.spec": "OpenAPI",
13
"info.wh.lead": "An empty body template sends this JSON document. pipeline_success and pipeline_failure include the pipeline id, status, ref, sha, commit message, author and duration, and every job with its name, stage, status, duration, allow_failure, web URL and console output. Each log is the last 200 lines, at most 64 KiB. Secret values of at least 8 characters are replaced with [MASKED]. log_truncated is true when the log was cut. log_url is then present and is GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. That request needs Authorization: Bearer and a personal token that can read the repo. A push includes ref, before, after and up to 20 commits, each with sha, message, author and URL. A merge request includes id, title, description, source branch, target branch, status, author and the action opened, merged or commented. A comment action also includes the comment text. A release includes the tag, name, commit and assets with URLs.",
13
"info.wh.lead": "An empty body template sends this JSON document. pipeline_success and pipeline_failure include the pipeline id, status, ref, sha, commit message, author and duration, and every job with its name, stage, status, duration, allow_failure, web URL and console output. Each log is the last 200 lines, at most 64 KiB. Secret values of at least 8 characters are replaced with [MASKED]. log_truncated is true when the log was cut. log_url is then present and is GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. That request needs Authorization: Bearer and a personal token that can read the repo. A push includes ref, before, after and up to 20 commits. Each commit has sha, message, author, timestamp, URL, changed files and diff_url. A file has status added, modified, removed or renamed, plus added and deleted line counts. The payload has no diff text. diff_url is GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff. A merge request includes id, title, description, source branch, target branch, status, author, action, reviewers, comments, up to 20 commits, diff statistics and diff_url, and no diff text. That diff_url is GET /api/v1/repos/{owner}/{repo}/merge-requests/{id}/diff. Both diff requests need Authorization: Bearer and a personal token that can read the repo. A comment action also includes the comment text. A release includes the tag, name, commit and assets with URLs.",
14
14
"hook.mrMerged": "merge request !%s merged: %s",
15
15
"hook.mrComment": "comment on merge request !%s",
16
16
}
@@ -18,7 +18,7 @@ var webhookEN = map[string]string{
18
18
var webhookNL = map[string]string{
19
19
"info.sec.webhooks": "Webhook-payloads",
20
20
"info.wh.spec": "OpenAPI",
21
"info.wh.lead": "Een leeg body-sjabloon stuurt dit JSON-document. pipeline_success en pipeline_failure bevatten het pipeline-id, de status, ref, sha, commitboodschap, auteur en duur, en elke job met naam, stage, status, duur, allow_failure, web-URL en console-output. Elke log bevat de laatste 200 regels, maximaal 64 KiB. Geheimwaarden van minstens 8 tekens worden [MASKED]. log_truncated is true als de log is afgekapt. log_url staat er dan bij en is GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. Die aanvraag heeft Authorization: Bearer en een persoonlijk token dat de repo mag lezen. Een push bevat ref, before, after en hoogstens 20 commits, elk met sha, message, auteur en URL. Een merge request bevat id, titel, beschrijving, bronbranch, doelbranch, status, auteur en de actie opened, merged of commented. Bij een commentaar hoort ook de tekst. Een release bevat tag, naam, commit en assets met URL's.",
21
"info.wh.lead": "Een leeg body-sjabloon stuurt dit JSON-document. pipeline_success en pipeline_failure bevatten het pipeline-id, de status, ref, sha, commitboodschap, auteur en duur, en elke job met naam, stage, status, duur, allow_failure, web-URL en console-output. Elke log bevat de laatste 200 regels, maximaal 64 KiB. Geheimwaarden van minstens 8 tekens worden [MASKED]. log_truncated is true als de log is afgekapt. log_url staat er dan bij en is GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. Die aanvraag heeft Authorization: Bearer en een persoonlijk token dat de repo mag lezen. Een push bevat ref, before, after en hoogstens 20 commits. Elke commit heeft sha, message, auteur, timestamp, URL, gewijzigde bestanden en diff_url. Een bestand heeft status added, modified, removed of renamed, plus het aantal toegevoegde en verwijderde regels. De payload bevat geen difftekst. diff_url is GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff. Een merge request bevat id, titel, beschrijving, bronbranch, doelbranch, status, auteur, actie, reviewers, comments, hoogstens 20 commits, diffstatistieken en diff_url, en geen difftekst. Die diff_url is GET /api/v1/repos/{owner}/{repo}/merge-requests/{id}/diff. Beide diff-aanvragen hebben Authorization: Bearer en een persoonlijk token dat de repo mag lezen. Bij een commentaar hoort ook de tekst. Een release bevat tag, naam, commit en assets met URL's.",
22
22
"hook.mrMerged": "merge request !%s samengevoegd: %s",
23
23
"hook.mrComment": "reactie op merge request !%s",
24
24
}
@@ -26,7 +26,7 @@ var webhookNL = map[string]string{
26
26
var webhookDE = map[string]string{
27
27
"info.sec.webhooks": "Webhook-Nutzdaten",
28
28
"info.wh.spec": "OpenAPI",
29
"info.wh.lead": "Eine leere Body-Vorlage sendet dieses JSON-Dokument. pipeline_success und pipeline_failure enthalten Pipeline-Id, Status, Ref, SHA, Commit-Nachricht, Autor und Dauer, sowie jeden Job mit Name, Stage, Status, Dauer, allow_failure, Web-URL und Konsolenausgabe. Jedes Log enthält die letzten 200 Zeilen, höchstens 64 KiB. Geheimwerte ab 8 Zeichen werden zu [MASKED]. log_truncated ist true, wenn das Log gekürzt wurde. log_url steht dann dabei und ist GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. Diese Anfrage braucht Authorization: Bearer und ein persönliches Token, das das Repo lesen darf. Ein Push enthält ref, before, after und höchstens 20 Commits mit SHA, Nachricht, Autor und URL. Ein Merge Request enthält Id, Titel, Beschreibung, Quellbranch, Zielbranch, Status, Autor und die Aktion opened, merged oder commented. Bei einem Kommentar steht der Text dabei. Ein Release enthält Tag, Name, Commit und Assets mit URLs.",
29
"info.wh.lead": "Eine leere Body-Vorlage sendet dieses JSON-Dokument. pipeline_success und pipeline_failure enthalten Pipeline-Id, Status, Ref, SHA, Commit-Nachricht, Autor und Dauer, sowie jeden Job mit Name, Stage, Status, Dauer, allow_failure, Web-URL und Konsolenausgabe. Jedes Log enthält die letzten 200 Zeilen, höchstens 64 KiB. Geheimwerte ab 8 Zeichen werden zu [MASKED]. log_truncated ist true, wenn das Log gekürzt wurde. log_url steht dann dabei und ist GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. Diese Anfrage braucht Authorization: Bearer und ein persönliches Token, das das Repo lesen darf. Ein Push enthält ref, before, after und höchstens 20 Commits. Jeder Commit hat SHA, Nachricht, Autor, Zeitstempel, URL, geänderte Dateien und diff_url. Eine Datei hat den Status added, modified, removed oder renamed, plus die Zahl hinzugefügter und gelöschter Zeilen. Die Nutzdaten enthalten keinen Diff-Text. diff_url ist GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff. Ein Merge Request enthält Id, Titel, Beschreibung, Quellbranch, Zielbranch, Status, Autor, Aktion, Reviewer, Kommentare, höchstens 20 Commits, Diff-Statistik und diff_url, und keinen Diff-Text. Diese diff_url ist GET /api/v1/repos/{owner}/{repo}/merge-requests/{id}/diff. Beide Diff-Anfragen brauchen Authorization: Bearer und ein persönliches Token, das das Repo lesen darf. Bei einem Kommentar steht der Text dabei. Ein Release enthält Tag, Name, Commit und Assets mit URLs.",
30
30
"hook.mrMerged": "Merge-Request !%s zusammengeführt: %s",
31
31
"hook.mrComment": "Kommentar zu Merge-Request !%s",
32
32
}
@@ -34,7 +34,7 @@ var webhookDE = map[string]string{
34
34
var webhookFR = map[string]string{
35
35
"info.sec.webhooks": "Charges utiles des webhooks",
36
36
"info.wh.spec": "OpenAPI",
37
"info.wh.lead": "Un modèle de corps vide envoie ce document JSON. pipeline_success et pipeline_failure contiennent l'id du pipeline, le statut, la ref, le sha, le message de commit, l'auteur et la durée, plus chaque job avec nom, stage, statut, durée, allow_failure, URL web et sortie console. Chaque log contient les 200 dernières lignes, 64 KiB au plus. Les valeurs secrètes d'au moins 8 caractères deviennent [MASKED]. log_truncated vaut true quand le log est coupé. log_url est alors présent et vaut GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. Cette requête exige Authorization: Bearer et un jeton personnel qui peut lire le dépôt. Un push contient ref, before, after et 20 commits au plus, chacun avec sha, message, auteur et URL. Une merge request contient id, titre, description, branche source, branche cible, statut, auteur et l'action opened, merged ou commented. Une action commented contient aussi le texte. Une release contient le tag, le nom, le commit et les assets avec leurs URL.",
37
"info.wh.lead": "Un modèle de corps vide envoie ce document JSON. pipeline_success et pipeline_failure contiennent l'id du pipeline, le statut, la ref, le sha, le message de commit, l'auteur et la durée, plus chaque job avec nom, stage, statut, durée, allow_failure, URL web et sortie console. Chaque log contient les 200 dernières lignes, 64 KiB au plus. Les valeurs secrètes d'au moins 8 caractères deviennent [MASKED]. log_truncated vaut true quand le log est coupé. log_url est alors présent et vaut GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. Cette requête exige Authorization: Bearer et un jeton personnel qui peut lire le dépôt. Un push contient ref, before, after et 20 commits au plus. Chaque commit a sha, message, auteur, horodatage, URL, fichiers modifiés et diff_url. Un fichier a le statut added, modified, removed ou renamed, plus le nombre de lignes ajoutées et supprimées. La charge utile ne contient pas le texte du diff. diff_url vaut GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff. Une merge request contient id, titre, description, branche source, branche cible, statut, auteur, action, relecteurs, commentaires, 20 commits au plus, statistiques de diff et diff_url, sans le texte du diff. Cette diff_url vaut GET /api/v1/repos/{owner}/{repo}/merge-requests/{id}/diff. Les deux requêtes de diff exigent Authorization: Bearer et un jeton personnel qui peut lire le dépôt. Une action commented contient aussi le texte. Une release contient le tag, le nom, le commit et les assets avec leurs URL.",
38
38
"hook.mrMerged": "merge request !%s fusionnée : %s",
39
39
"hook.mrComment": "commentaire sur la merge request !%s",
40
40
}
@@ -10,7 +10,7 @@ func init() {10
var webhookEN = map[string]string{10
var webhookEN = map[string]string{11
"info.sec.webhooks": "Webhook payloads",11
"info.sec.webhooks": "Webhook payloads",12
"info.wh.spec": "OpenAPI",12
"info.wh.spec": "OpenAPI",13
"info.wh.lead": "An empty body template sends this JSON document. pipeline_success and pipeline_failure include the pipeline id, status, ref, sha, commit message, author and duration, and every job with its name, stage, status, duration, allow_failure, web URL and console output. Each log is the last 200 lines, at most 64 KiB. Secret values of at least 8 characters are replaced with [MASKED]. log_truncated is true when the log was cut. log_url is then present and is GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. That request needs Authorization: Bearer and a personal token that can read the repo. A push includes ref, before, after and up to 20 commits, each with sha, message, author and URL. A merge request includes id, title, description, source branch, target branch, status, author and the action opened, merged or commented. A comment action also includes the comment text. A release includes the tag, name, commit and assets with URLs.",13
"info.wh.lead": "An empty body template sends this JSON document. pipeline_success and pipeline_failure include the pipeline id, status, ref, sha, commit message, author and duration, and every job with its name, stage, status, duration, allow_failure, web URL and console output. Each log is the last 200 lines, at most 64 KiB. Secret values of at least 8 characters are replaced with [MASKED]. log_truncated is true when the log was cut. log_url is then present and is GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. That request needs Authorization: Bearer and a personal token that can read the repo. A push includes ref, before, after and up to 20 commits. Each commit has sha, message, author, timestamp, URL, changed files and diff_url. A file has status added, modified, removed or renamed, plus added and deleted line counts. The payload has no diff text. diff_url is GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff. A merge request includes id, title, description, source branch, target branch, status, author, action, reviewers, comments, up to 20 commits, diff statistics and diff_url, and no diff text. That diff_url is GET /api/v1/repos/{owner}/{repo}/merge-requests/{id}/diff. Both diff requests need Authorization: Bearer and a personal token that can read the repo. A comment action also includes the comment text. A release includes the tag, name, commit and assets with URLs.",14
"hook.mrMerged": "merge request !%s merged: %s",14
"hook.mrMerged": "merge request !%s merged: %s",15
"hook.mrComment": "comment on merge request !%s",15
"hook.mrComment": "comment on merge request !%s",16
}16
}@@ -18,7 +18,7 @@ var webhookEN = map[string]string{18
var webhookNL = map[string]string{18
var webhookNL = map[string]string{19
"info.sec.webhooks": "Webhook-payloads",19
"info.sec.webhooks": "Webhook-payloads",20
"info.wh.spec": "OpenAPI",20
"info.wh.spec": "OpenAPI",21
"info.wh.lead": "Een leeg body-sjabloon stuurt dit JSON-document. pipeline_success en pipeline_failure bevatten het pipeline-id, de status, ref, sha, commitboodschap, auteur en duur, en elke job met naam, stage, status, duur, allow_failure, web-URL en console-output. Elke log bevat de laatste 200 regels, maximaal 64 KiB. Geheimwaarden van minstens 8 tekens worden [MASKED]. log_truncated is true als de log is afgekapt. log_url staat er dan bij en is GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. Die aanvraag heeft Authorization: Bearer en een persoonlijk token dat de repo mag lezen. Een push bevat ref, before, after en hoogstens 20 commits, elk met sha, message, auteur en URL. Een merge request bevat id, titel, beschrijving, bronbranch, doelbranch, status, auteur en de actie opened, merged of commented. Bij een commentaar hoort ook de tekst. Een release bevat tag, naam, commit en assets met URL's.",21
"info.wh.lead": "Een leeg body-sjabloon stuurt dit JSON-document. pipeline_success en pipeline_failure bevatten het pipeline-id, de status, ref, sha, commitboodschap, auteur en duur, en elke job met naam, stage, status, duur, allow_failure, web-URL en console-output. Elke log bevat de laatste 200 regels, maximaal 64 KiB. Geheimwaarden van minstens 8 tekens worden [MASKED]. log_truncated is true als de log is afgekapt. log_url staat er dan bij en is GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. Die aanvraag heeft Authorization: Bearer en een persoonlijk token dat de repo mag lezen. Een push bevat ref, before, after en hoogstens 20 commits. Elke commit heeft sha, message, auteur, timestamp, URL, gewijzigde bestanden en diff_url. Een bestand heeft status added, modified, removed of renamed, plus het aantal toegevoegde en verwijderde regels. De payload bevat geen difftekst. diff_url is GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff. Een merge request bevat id, titel, beschrijving, bronbranch, doelbranch, status, auteur, actie, reviewers, comments, hoogstens 20 commits, diffstatistieken en diff_url, en geen difftekst. Die diff_url is GET /api/v1/repos/{owner}/{repo}/merge-requests/{id}/diff. Beide diff-aanvragen hebben Authorization: Bearer en een persoonlijk token dat de repo mag lezen. Bij een commentaar hoort ook de tekst. Een release bevat tag, naam, commit en assets met URL's.",22
"hook.mrMerged": "merge request !%s samengevoegd: %s",22
"hook.mrMerged": "merge request !%s samengevoegd: %s",23
"hook.mrComment": "reactie op merge request !%s",23
"hook.mrComment": "reactie op merge request !%s",24
}24
}@@ -26,7 +26,7 @@ var webhookNL = map[string]string{26
var webhookDE = map[string]string{26
var webhookDE = map[string]string{27
"info.sec.webhooks": "Webhook-Nutzdaten",27
"info.sec.webhooks": "Webhook-Nutzdaten",28
"info.wh.spec": "OpenAPI",28
"info.wh.spec": "OpenAPI",29
"info.wh.lead": "Eine leere Body-Vorlage sendet dieses JSON-Dokument. pipeline_success und pipeline_failure enthalten Pipeline-Id, Status, Ref, SHA, Commit-Nachricht, Autor und Dauer, sowie jeden Job mit Name, Stage, Status, Dauer, allow_failure, Web-URL und Konsolenausgabe. Jedes Log enthält die letzten 200 Zeilen, höchstens 64 KiB. Geheimwerte ab 8 Zeichen werden zu [MASKED]. log_truncated ist true, wenn das Log gekürzt wurde. log_url steht dann dabei und ist GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. Diese Anfrage braucht Authorization: Bearer und ein persönliches Token, das das Repo lesen darf. Ein Push enthält ref, before, after und höchstens 20 Commits mit SHA, Nachricht, Autor und URL. Ein Merge Request enthält Id, Titel, Beschreibung, Quellbranch, Zielbranch, Status, Autor und die Aktion opened, merged oder commented. Bei einem Kommentar steht der Text dabei. Ein Release enthält Tag, Name, Commit und Assets mit URLs.",29
"info.wh.lead": "Eine leere Body-Vorlage sendet dieses JSON-Dokument. pipeline_success und pipeline_failure enthalten Pipeline-Id, Status, Ref, SHA, Commit-Nachricht, Autor und Dauer, sowie jeden Job mit Name, Stage, Status, Dauer, allow_failure, Web-URL und Konsolenausgabe. Jedes Log enthält die letzten 200 Zeilen, höchstens 64 KiB. Geheimwerte ab 8 Zeichen werden zu [MASKED]. log_truncated ist true, wenn das Log gekürzt wurde. log_url steht dann dabei und ist GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. Diese Anfrage braucht Authorization: Bearer und ein persönliches Token, das das Repo lesen darf. Ein Push enthält ref, before, after und höchstens 20 Commits. Jeder Commit hat SHA, Nachricht, Autor, Zeitstempel, URL, geänderte Dateien und diff_url. Eine Datei hat den Status added, modified, removed oder renamed, plus die Zahl hinzugefügter und gelöschter Zeilen. Die Nutzdaten enthalten keinen Diff-Text. diff_url ist GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff. Ein Merge Request enthält Id, Titel, Beschreibung, Quellbranch, Zielbranch, Status, Autor, Aktion, Reviewer, Kommentare, höchstens 20 Commits, Diff-Statistik und diff_url, und keinen Diff-Text. Diese diff_url ist GET /api/v1/repos/{owner}/{repo}/merge-requests/{id}/diff. Beide Diff-Anfragen brauchen Authorization: Bearer und ein persönliches Token, das das Repo lesen darf. Bei einem Kommentar steht der Text dabei. Ein Release enthält Tag, Name, Commit und Assets mit URLs.",30
"hook.mrMerged": "Merge-Request !%s zusammengeführt: %s",30
"hook.mrMerged": "Merge-Request !%s zusammengeführt: %s",31
"hook.mrComment": "Kommentar zu Merge-Request !%s",31
"hook.mrComment": "Kommentar zu Merge-Request !%s",32
}32
}@@ -34,7 +34,7 @@ var webhookDE = map[string]string{34
var webhookFR = map[string]string{34
var webhookFR = map[string]string{35
"info.sec.webhooks": "Charges utiles des webhooks",35
"info.sec.webhooks": "Charges utiles des webhooks",36
"info.wh.spec": "OpenAPI",36
"info.wh.spec": "OpenAPI",37
"info.wh.lead": "Un modèle de corps vide envoie ce document JSON. pipeline_success et pipeline_failure contiennent l'id du pipeline, le statut, la ref, le sha, le message de commit, l'auteur et la durée, plus chaque job avec nom, stage, statut, durée, allow_failure, URL web et sortie console. Chaque log contient les 200 dernières lignes, 64 KiB au plus. Les valeurs secrètes d'au moins 8 caractères deviennent [MASKED]. log_truncated vaut true quand le log est coupé. log_url est alors présent et vaut GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. Cette requête exige Authorization: Bearer et un jeton personnel qui peut lire le dépôt. Un push contient ref, before, after et 20 commits au plus, chacun avec sha, message, auteur et URL. Une merge request contient id, titre, description, branche source, branche cible, statut, auteur et l'action opened, merged ou commented. Une action commented contient aussi le texte. Une release contient le tag, le nom, le commit et les assets avec leurs URL.",37
"info.wh.lead": "Un modèle de corps vide envoie ce document JSON. pipeline_success et pipeline_failure contiennent l'id du pipeline, le statut, la ref, le sha, le message de commit, l'auteur et la durée, plus chaque job avec nom, stage, statut, durée, allow_failure, URL web et sortie console. Chaque log contient les 200 dernières lignes, 64 KiB au plus. Les valeurs secrètes d'au moins 8 caractères deviennent [MASKED]. log_truncated vaut true quand le log est coupé. log_url est alors présent et vaut GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. Cette requête exige Authorization: Bearer et un jeton personnel qui peut lire le dépôt. Un push contient ref, before, after et 20 commits au plus. Chaque commit a sha, message, auteur, horodatage, URL, fichiers modifiés et diff_url. Un fichier a le statut added, modified, removed ou renamed, plus le nombre de lignes ajoutées et supprimées. La charge utile ne contient pas le texte du diff. diff_url vaut GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff. Une merge request contient id, titre, description, branche source, branche cible, statut, auteur, action, relecteurs, commentaires, 20 commits au plus, statistiques de diff et diff_url, sans le texte du diff. Cette diff_url vaut GET /api/v1/repos/{owner}/{repo}/merge-requests/{id}/diff. Les deux requêtes de diff exigent Authorization: Bearer et un jeton personnel qui peut lire le dépôt. Une action commented contient aussi le texte. Une release contient le tag, le nom, le commit et les assets avec leurs URL.",38
"hook.mrMerged": "merge request !%s fusionnée : %s",38
"hook.mrMerged": "merge request !%s fusionnée : %s",39
"hook.mrComment": "commentaire sur la merge request !%s",39
"hook.mrComment": "commentaire sur la merge request !%s",40
}40
}@@ -10,6 +10,7 @@ import (
10
10
11
11
"gitlab.com/Timfa/bluegit/internal/access"
12
12
"gitlab.com/Timfa/bluegit/internal/ci"
13
"gitlab.com/Timfa/bluegit/internal/gitrepo"
13
14
"gitlab.com/Timfa/bluegit/internal/i18n"
14
15
"gitlab.com/Timfa/bluegit/internal/store"
15
16
)
@@ -94,40 +95,106 @@ func (s *Server) jobLogAPI(w http.ResponseWriter, r *http.Request) {
94
95
http.NotFound(w, r)
95
96
return
96
97
}
98
if !s.authorizeRepoRead(w, r, repo) {
99
return
100
}
101
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
102
if err != nil || id <= 0 {
103
http.NotFound(w, r)
104
return
105
}
106
job, err := s.Store.JobByID(r.Context(), repo.ID, id)
107
if err != nil {
108
http.NotFound(w, r)
109
return
110
}
111
text := ci.Mask(job.Log, s.maskSecrets(r.Context(), repo))
112
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
113
w.Header().Set("Cache-Control", "no-store")
114
_, _ = w.Write([]byte(text))
115
}
116
117
// authorizeRepoRead eist een persoonlijk token. Op een publieke repo volstaat
118
// elk geldig token. Op een privérepo moet het token de repo mogen lezen.
119
func (s *Server) authorizeRepoRead(w http.ResponseWriter, r *http.Request, repo store.Repo) bool {
97
120
token := bearer(r)
98
121
if token == "" {
99
122
http.Error(w, s.tr(r, "err.tokenAbsent"), http.StatusUnauthorized)
100
return
123
return false
101
124
}
102
125
if strings.HasPrefix(token, "bgj_") || !strings.HasPrefix(token, "bg_") {
103
126
http.Error(w, s.tr(r, "err.tokenBad"), http.StatusUnauthorized)
104
return
127
return false
105
128
}
106
129
u, err := s.Store.UserByToken(r.Context(), token)
107
130
if err != nil {
108
131
http.Error(w, s.tr(r, "err.tokenBad"), http.StatusUnauthorized)
109
return
132
return false
110
133
}
111
134
role, err := s.Store.EffectiveRole(r.Context(), u.ID, repo.ID)
112
135
if err != nil {
113
136
http.Error(w, s.tr(r, "err.rights"), http.StatusInternalServerError)
114
return
137
return false
115
138
}
116
139
if !role.CanRead() && repo.Visibility != "public" {
117
140
http.Error(w, s.tr(r, "err.forbidden"), http.StatusForbidden)
141
return false
142
}
143
return true
144
}
145
146
// commitDiffAPI geeft de unified diff van één commit.
147
func (s *Server) commitDiffAPI(w http.ResponseWriter, r *http.Request) {
148
repo, err := s.Store.RepoByPath(r.Context(), r.PathValue("owner"), r.PathValue("repo"))
149
if err != nil {
150
http.NotFound(w, r)
118
151
return
119
152
}
120
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
121
if err != nil || id <= 0 {
153
if !s.authorizeRepoRead(w, r, repo) {
154
return
155
}
156
sha := r.PathValue("sha")
157
if !safeSHA(sha) || s.Git == "" || s.StoragePath() == "" {
122
158
http.NotFound(w, r)
123
159
return
124
160
}
125
job, err := s.Store.JobByID(r.Context(), repo.ID, id)
161
text, err := gitrepo.CommitDiff(r.Context(), s.Git, gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name), sha)
126
162
if err != nil {
127
163
http.NotFound(w, r)
128
164
return
129
165
}
130
text := ci.Mask(job.Log, s.maskSecrets(r.Context(), repo))
166
writePlain(w, text)
167
}
168
169
// mrDiffAPI geeft de three-dot diff van een merge request.
170
func (s *Server) mrDiffAPI(w http.ResponseWriter, r *http.Request) {
171
repo, err := s.Store.RepoByPath(r.Context(), r.PathValue("owner"), r.PathValue("repo"))
172
if err != nil {
173
http.NotFound(w, r)
174
return
175
}
176
if !s.authorizeRepoRead(w, r, repo) {
177
return
178
}
179
number, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
180
if err != nil || number <= 0 || s.Git == "" || s.StoragePath() == "" {
181
http.NotFound(w, r)
182
return
183
}
184
mr, err := s.Store.MergeRequestByNumber(r.Context(), repo.ID, number)
185
if err != nil || safeRev(mr.SourceBranch, "") != mr.SourceBranch || safeRev(mr.TargetBranch, "") != mr.TargetBranch {
186
http.NotFound(w, r)
187
return
188
}
189
text, err := gitrepo.CompareDiff(r.Context(), s.Git, gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name), mr.TargetBranch, mr.SourceBranch)
190
if err != nil {
191
http.NotFound(w, r)
192
return
193
}
194
writePlain(w, text)
195
}
196
197
func writePlain(w http.ResponseWriter, text string) {
131
198
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
132
199
w.Header().Set("Cache-Control", "no-store")
133
200
_, _ = w.Write([]byte(text))
@@ -10,6 +10,7 @@ import (10
10
11
"gitlab.com/Timfa/bluegit/internal/access"11
"gitlab.com/Timfa/bluegit/internal/access"12
"gitlab.com/Timfa/bluegit/internal/ci"12
"gitlab.com/Timfa/bluegit/internal/ci"13
"gitlab.com/Timfa/bluegit/internal/gitrepo"13
"gitlab.com/Timfa/bluegit/internal/i18n"14
"gitlab.com/Timfa/bluegit/internal/i18n"14
"gitlab.com/Timfa/bluegit/internal/store"15
"gitlab.com/Timfa/bluegit/internal/store"15
)16
)@@ -94,40 +95,106 @@ func (s *Server) jobLogAPI(w http.ResponseWriter, r *http.Request) {94
http.NotFound(w, r)95
http.NotFound(w, r)95
return96
return96
}97
}98
if !s.authorizeRepoRead(w, r, repo) {99
return100
}101
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)102
if err != nil || id <= 0 {103
http.NotFound(w, r)104
return105
}106
job, err := s.Store.JobByID(r.Context(), repo.ID, id)107
if err != nil {108
http.NotFound(w, r)109
return110
}111
text := ci.Mask(job.Log, s.maskSecrets(r.Context(), repo))112
w.Header().Set("Content-Type", "text/plain; charset=utf-8")113
w.Header().Set("Cache-Control", "no-store")114
_, _ = w.Write([]byte(text))115
}116
117
// authorizeRepoRead eist een persoonlijk token. Op een publieke repo volstaat118
// elk geldig token. Op een privérepo moet het token de repo mogen lezen.119
func (s *Server) authorizeRepoRead(w http.ResponseWriter, r *http.Request, repo store.Repo) bool {97
token := bearer(r)120
token := bearer(r)98
if token == "" {121
if token == "" {99
http.Error(w, s.tr(r, "err.tokenAbsent"), http.StatusUnauthorized)122
http.Error(w, s.tr(r, "err.tokenAbsent"), http.StatusUnauthorized)100
return123
return false101
}124
}102
if strings.HasPrefix(token, "bgj_") || !strings.HasPrefix(token, "bg_") {125
if strings.HasPrefix(token, "bgj_") || !strings.HasPrefix(token, "bg_") {103
http.Error(w, s.tr(r, "err.tokenBad"), http.StatusUnauthorized)126
http.Error(w, s.tr(r, "err.tokenBad"), http.StatusUnauthorized)104
return127
return false105
}128
}106
u, err := s.Store.UserByToken(r.Context(), token)129
u, err := s.Store.UserByToken(r.Context(), token)107
if err != nil {130
if err != nil {108
http.Error(w, s.tr(r, "err.tokenBad"), http.StatusUnauthorized)131
http.Error(w, s.tr(r, "err.tokenBad"), http.StatusUnauthorized)109
return132
return false110
}133
}111
role, err := s.Store.EffectiveRole(r.Context(), u.ID, repo.ID)134
role, err := s.Store.EffectiveRole(r.Context(), u.ID, repo.ID)112
if err != nil {135
if err != nil {113
http.Error(w, s.tr(r, "err.rights"), http.StatusInternalServerError)136
http.Error(w, s.tr(r, "err.rights"), http.StatusInternalServerError)114
return137
return false115
}138
}116
if !role.CanRead() && repo.Visibility != "public" {139
if !role.CanRead() && repo.Visibility != "public" {117
http.Error(w, s.tr(r, "err.forbidden"), http.StatusForbidden)140
http.Error(w, s.tr(r, "err.forbidden"), http.StatusForbidden)141
return false142
}143
return true144
}145
146
// commitDiffAPI geeft de unified diff van één commit.147
func (s *Server) commitDiffAPI(w http.ResponseWriter, r *http.Request) {148
repo, err := s.Store.RepoByPath(r.Context(), r.PathValue("owner"), r.PathValue("repo"))149
if err != nil {150
http.NotFound(w, r)118
return151
return119
}152
}120
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)153
if !s.authorizeRepoRead(w, r, repo) {121
if err != nil || id <= 0 {154
return155
}156
sha := r.PathValue("sha")157
if !safeSHA(sha) || s.Git == "" || s.StoragePath() == "" {122
http.NotFound(w, r)158
http.NotFound(w, r)123
return159
return124
}160
}125
job, err := s.Store.JobByID(r.Context(), repo.ID, id)161
text, err := gitrepo.CommitDiff(r.Context(), s.Git, gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name), sha)126
if err != nil {162
if err != nil {127
http.NotFound(w, r)163
http.NotFound(w, r)128
return164
return129
}165
}130
text := ci.Mask(job.Log, s.maskSecrets(r.Context(), repo))166
writePlain(w, text)167
}168
169
// mrDiffAPI geeft de three-dot diff van een merge request.170
func (s *Server) mrDiffAPI(w http.ResponseWriter, r *http.Request) {171
repo, err := s.Store.RepoByPath(r.Context(), r.PathValue("owner"), r.PathValue("repo"))172
if err != nil {173
http.NotFound(w, r)174
return175
}176
if !s.authorizeRepoRead(w, r, repo) {177
return178
}179
number, err := strconv.ParseInt(r.PathValue("number"), 10, 64)180
if err != nil || number <= 0 || s.Git == "" || s.StoragePath() == "" {181
http.NotFound(w, r)182
return183
}184
mr, err := s.Store.MergeRequestByNumber(r.Context(), repo.ID, number)185
if err != nil || safeRev(mr.SourceBranch, "") != mr.SourceBranch || safeRev(mr.TargetBranch, "") != mr.TargetBranch {186
http.NotFound(w, r)187
return188
}189
text, err := gitrepo.CompareDiff(r.Context(), s.Git, gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name), mr.TargetBranch, mr.SourceBranch)190
if err != nil {191
http.NotFound(w, r)192
return193
}194
writePlain(w, text)195
}196
197
func writePlain(w http.ResponseWriter, text string) {131
w.Header().Set("Content-Type", "text/plain; charset=utf-8")198
w.Header().Set("Content-Type", "text/plain; charset=utf-8")132
w.Header().Set("Cache-Control", "no-store")199
w.Header().Set("Cache-Control", "no-store")133
_, _ = w.Write([]byte(text))200
_, _ = w.Write([]byte(text))@@ -21,6 +21,8 @@ func (s *Server) enrichEvent(ctx context.Context, repo store.Repo, ev webhook.Ev
21
21
s.fillPipelineEvent(ctx, repo, &ev)
22
22
case webhook.EventPush:
23
23
s.fillPushEvent(ctx, repo, &ev)
24
case webhook.EventMergeRequest:
25
s.fillMREvent(ctx, repo, &ev)
24
26
}
25
27
return ev
26
28
}
@@ -106,15 +108,104 @@ func (s *Server) fillPushEvent(ctx context.Context, repo store.Repo, ev *webhook
106
108
if len(list) > webhook.MaxPushCommits {
107
109
list = list[:webhook.MaxPushCommits]
108
110
}
109
base := strings.TrimRight(s.Cfg.BaseURL, "/")
110
111
ev.Commits = make([]webhook.CommitInfo, 0, len(list))
111
112
for i := len(list) - 1; i >= 0; i-- {
112
c := list[i]
113
ev.Commits = append(ev.Commits, webhook.CommitInfo{
114
SHA: c.SHA, Message: commitText(c), Author: commitAuthor(c),
115
URL: base + "/" + repo.FullPath() + "/-/commit/" + c.SHA,
113
ev.Commits = append(ev.Commits, s.commitInfo(ctx, repo, list[i]))
114
}
115
}
116
117
func (s *Server) fillMREvent(ctx context.Context, repo store.Repo, ev *webhook.Event) {
118
if ev.MergeRequest == nil {
119
return
120
}
121
mr := ev.MergeRequest
122
if mr.Reviewers == nil {
123
mr.Reviewers = []webhook.ReviewerInfo{}
124
}
125
if mr.Comments == nil {
126
mr.Comments = []webhook.CommentInfo{}
127
}
128
if mr.Commits == nil {
129
mr.Commits = []webhook.CommitInfo{}
130
}
131
if mr.DiffStats.Files == nil {
132
mr.DiffStats.Files = []webhook.FileChange{}
133
}
134
mr.DiffURL = mrDiffAPIURL(s.Cfg.BaseURL, repo, mr.ID)
135
if s.Store != nil && mr.ID > 0 {
136
if stored, err := s.Store.MergeRequestByNumber(ctx, repo.ID, mr.ID); err == nil {
137
if revs, err := s.Store.ListReviews(ctx, stored.ID); err == nil {
138
mr.Reviewers = make([]webhook.ReviewerInfo, 0, len(revs))
139
for _, rev := range revs {
140
mr.Reviewers = append(mr.Reviewers, webhook.ReviewerInfo{Username: rev.Username, Status: rev.Status})
141
}
142
}
143
if notes, err := s.Store.ListNotes(ctx, stored.ID); err == nil {
144
mr.Comments = make([]webhook.CommentInfo, 0, len(notes))
145
for _, n := range notes {
146
mr.Comments = append(mr.Comments, webhook.CommentInfo{
147
ID: n.ID, Author: n.Author, Body: n.Body,
148
CreatedAt: n.CreatedAt.UTC().Format(time.RFC3339),
149
FilePath: n.FilePath, LineStart: n.LineStart, LineEnd: n.LineEnd,
150
ParentID: n.ParentID,
151
})
152
}
153
}
154
}
155
}
156
if s.Git == "" || s.StoragePath() == "" || mr.SourceBranch == "" || mr.TargetBranch == "" {
157
return
158
}
159
dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
160
if changes, err := gitrepo.CompareChanges(ctx, s.Git, dir, mr.TargetBranch, mr.SourceBranch); err == nil {
161
stats := webhook.DiffStats{Files: fileChanges(changes)}
162
for _, f := range stats.Files {
163
stats.Additions += f.Additions
164
stats.Deletions += f.Deletions
165
}
166
mr.DiffStats = stats
167
}
168
list, err := gitrepo.Log(ctx, s.Git, dir, mr.TargetBranch+".."+mr.SourceBranch, webhook.MaxPushCommits)
169
if err != nil || len(list) == 0 {
170
mr.Commits = []webhook.CommitInfo{}
171
return
172
}
173
mr.Commits = make([]webhook.CommitInfo, 0, len(list))
174
for i := len(list) - 1; i >= 0; i-- {
175
mr.Commits = append(mr.Commits, s.commitInfo(ctx, repo, list[i]))
176
}
177
}
178
179
func (s *Server) commitInfo(ctx context.Context, repo store.Repo, c gitrepo.Commit) webhook.CommitInfo {
180
base := strings.TrimRight(s.Cfg.BaseURL, "/")
181
info := webhook.CommitInfo{
182
SHA: c.SHA, Message: commitText(c), Author: commitAuthor(c),
183
Timestamp: time.Unix(c.Unix, 0).UTC().Format(time.RFC3339),
184
URL: base + "/" + repo.FullPath() + "/-/commit/" + c.SHA,
185
DiffURL: commitDiffAPIURL(base, repo, c.SHA),
186
Files: []webhook.FileChange{},
187
}
188
if s.Git == "" || s.StoragePath() == "" {
189
return info
190
}
191
dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
192
files, err := gitrepo.CommitChanges(ctx, s.Git, dir, c.SHA)
193
if err != nil {
194
return info
195
}
196
info.Files = fileChanges(files)
197
return info
198
}
199
200
func fileChanges(list []gitrepo.Change) []webhook.FileChange {
201
out := make([]webhook.FileChange, 0, len(list))
202
for _, c := range list {
203
out = append(out, webhook.FileChange{
204
Path: c.Path, Status: c.Status, PreviousPath: c.OldPath,
205
Additions: c.Added, Deletions: c.Deleted, Binary: c.Binary,
116
206
})
117
207
}
208
return out
118
209
}
119
210
120
211
func (s *Server) maskSecrets(ctx context.Context, repo store.Repo) []string {
@@ -186,6 +277,14 @@ func (s *Server) releaseEvent(repo store.Repo, tag, name, commit string, assets
186
277
}
187
278
}
188
279
280
func commitDiffAPIURL(base string, repo store.Repo, sha string) string {
281
return strings.TrimRight(base, "/") + "/api/v1/repos/" + url.PathEscape(repo.OwnerPath) + "/" + url.PathEscape(repo.Name) + "/commits/" + url.PathEscape(sha) + "/diff"
282
}
283
284
func mrDiffAPIURL(base string, repo store.Repo, number int64) string {
285
return strings.TrimRight(base, "/") + "/api/v1/repos/" + url.PathEscape(repo.OwnerPath) + "/" + url.PathEscape(repo.Name) + "/merge-requests/" + strconv.FormatInt(number, 10) + "/diff"
286
}
287
189
288
func jobLogAPIURL(base string, repo store.Repo, jobID int64) string {
190
289
return strings.TrimRight(base, "/") + "/api/v1/repos/" + url.PathEscape(repo.OwnerPath) + "/" + url.PathEscape(repo.Name) + "/jobs/" + strconv.FormatInt(jobID, 10) + "/log"
191
290
}
@@ -21,6 +21,8 @@ func (s *Server) enrichEvent(ctx context.Context, repo store.Repo, ev webhook.Ev21
s.fillPipelineEvent(ctx, repo, &ev)21
s.fillPipelineEvent(ctx, repo, &ev)22
case webhook.EventPush:22
case webhook.EventPush:23
s.fillPushEvent(ctx, repo, &ev)23
s.fillPushEvent(ctx, repo, &ev)24
case webhook.EventMergeRequest:25
s.fillMREvent(ctx, repo, &ev)24
}26
}25
return ev27
return ev26
}28
}@@ -106,15 +108,104 @@ func (s *Server) fillPushEvent(ctx context.Context, repo store.Repo, ev *webhook106
if len(list) > webhook.MaxPushCommits {108
if len(list) > webhook.MaxPushCommits {107
list = list[:webhook.MaxPushCommits]109
list = list[:webhook.MaxPushCommits]108
}110
}109
base := strings.TrimRight(s.Cfg.BaseURL, "/")110
ev.Commits = make([]webhook.CommitInfo, 0, len(list))111
ev.Commits = make([]webhook.CommitInfo, 0, len(list))111
for i := len(list) - 1; i >= 0; i-- {112
for i := len(list) - 1; i >= 0; i-- {112
c := list[i]113
ev.Commits = append(ev.Commits, s.commitInfo(ctx, repo, list[i]))113
ev.Commits = append(ev.Commits, webhook.CommitInfo{114
}114
SHA: c.SHA, Message: commitText(c), Author: commitAuthor(c),115
}115
URL: base + "/" + repo.FullPath() + "/-/commit/" + c.SHA,116
117
func (s *Server) fillMREvent(ctx context.Context, repo store.Repo, ev *webhook.Event) {118
if ev.MergeRequest == nil {119
return120
}121
mr := ev.MergeRequest122
if mr.Reviewers == nil {123
mr.Reviewers = []webhook.ReviewerInfo{}124
}125
if mr.Comments == nil {126
mr.Comments = []webhook.CommentInfo{}127
}128
if mr.Commits == nil {129
mr.Commits = []webhook.CommitInfo{}130
}131
if mr.DiffStats.Files == nil {132
mr.DiffStats.Files = []webhook.FileChange{}133
}134
mr.DiffURL = mrDiffAPIURL(s.Cfg.BaseURL, repo, mr.ID)135
if s.Store != nil && mr.ID > 0 {136
if stored, err := s.Store.MergeRequestByNumber(ctx, repo.ID, mr.ID); err == nil {137
if revs, err := s.Store.ListReviews(ctx, stored.ID); err == nil {138
mr.Reviewers = make([]webhook.ReviewerInfo, 0, len(revs))139
for _, rev := range revs {140
mr.Reviewers = append(mr.Reviewers, webhook.ReviewerInfo{Username: rev.Username, Status: rev.Status})141
}142
}143
if notes, err := s.Store.ListNotes(ctx, stored.ID); err == nil {144
mr.Comments = make([]webhook.CommentInfo, 0, len(notes))145
for _, n := range notes {146
mr.Comments = append(mr.Comments, webhook.CommentInfo{147
ID: n.ID, Author: n.Author, Body: n.Body,148
CreatedAt: n.CreatedAt.UTC().Format(time.RFC3339),149
FilePath: n.FilePath, LineStart: n.LineStart, LineEnd: n.LineEnd,150
ParentID: n.ParentID,151
})152
}153
}154
}155
}156
if s.Git == "" || s.StoragePath() == "" || mr.SourceBranch == "" || mr.TargetBranch == "" {157
return158
}159
dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)160
if changes, err := gitrepo.CompareChanges(ctx, s.Git, dir, mr.TargetBranch, mr.SourceBranch); err == nil {161
stats := webhook.DiffStats{Files: fileChanges(changes)}162
for _, f := range stats.Files {163
stats.Additions += f.Additions164
stats.Deletions += f.Deletions165
}166
mr.DiffStats = stats167
}168
list, err := gitrepo.Log(ctx, s.Git, dir, mr.TargetBranch+".."+mr.SourceBranch, webhook.MaxPushCommits)169
if err != nil || len(list) == 0 {170
mr.Commits = []webhook.CommitInfo{}171
return172
}173
mr.Commits = make([]webhook.CommitInfo, 0, len(list))174
for i := len(list) - 1; i >= 0; i-- {175
mr.Commits = append(mr.Commits, s.commitInfo(ctx, repo, list[i]))176
}177
}178
179
func (s *Server) commitInfo(ctx context.Context, repo store.Repo, c gitrepo.Commit) webhook.CommitInfo {180
base := strings.TrimRight(s.Cfg.BaseURL, "/")181
info := webhook.CommitInfo{182
SHA: c.SHA, Message: commitText(c), Author: commitAuthor(c),183
Timestamp: time.Unix(c.Unix, 0).UTC().Format(time.RFC3339),184
URL: base + "/" + repo.FullPath() + "/-/commit/" + c.SHA,185
DiffURL: commitDiffAPIURL(base, repo, c.SHA),186
Files: []webhook.FileChange{},187
}188
if s.Git == "" || s.StoragePath() == "" {189
return info190
}191
dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)192
files, err := gitrepo.CommitChanges(ctx, s.Git, dir, c.SHA)193
if err != nil {194
return info195
}196
info.Files = fileChanges(files)197
return info198
}199
200
func fileChanges(list []gitrepo.Change) []webhook.FileChange {201
out := make([]webhook.FileChange, 0, len(list))202
for _, c := range list {203
out = append(out, webhook.FileChange{204
Path: c.Path, Status: c.Status, PreviousPath: c.OldPath,205
Additions: c.Added, Deletions: c.Deleted, Binary: c.Binary,116
})206
})117
}207
}208
return out118
}209
}119
210
120
func (s *Server) maskSecrets(ctx context.Context, repo store.Repo) []string {211
func (s *Server) maskSecrets(ctx context.Context, repo store.Repo) []string {@@ -186,6 +277,14 @@ func (s *Server) releaseEvent(repo store.Repo, tag, name, commit string, assets186
}277
}187
}278
}188
279
280
func commitDiffAPIURL(base string, repo store.Repo, sha string) string {281
return strings.TrimRight(base, "/") + "/api/v1/repos/" + url.PathEscape(repo.OwnerPath) + "/" + url.PathEscape(repo.Name) + "/commits/" + url.PathEscape(sha) + "/diff"282
}283
284
func mrDiffAPIURL(base string, repo store.Repo, number int64) string {285
return strings.TrimRight(base, "/") + "/api/v1/repos/" + url.PathEscape(repo.OwnerPath) + "/" + url.PathEscape(repo.Name) + "/merge-requests/" + strconv.FormatInt(number, 10) + "/diff"286
}287
189
func jobLogAPIURL(base string, repo store.Repo, jobID int64) string {288
func jobLogAPIURL(base string, repo store.Repo, jobID int64) string {190
return strings.TrimRight(base, "/") + "/api/v1/repos/" + url.PathEscape(repo.OwnerPath) + "/" + url.PathEscape(repo.Name) + "/jobs/" + strconv.FormatInt(jobID, 10) + "/log"289
return strings.TrimRight(base, "/") + "/api/v1/repos/" + url.PathEscape(repo.OwnerPath) + "/" + url.PathEscape(repo.Name) + "/jobs/" + strconv.FormatInt(jobID, 10) + "/log"191
}290
}@@ -101,6 +101,37 @@ func TestWebhookPayloads(t *testing.T) {
101
101
if push["after"] != second["sha"] {
102
102
t.Fatalf("after %v tip %v", push["after"], second["sha"])
103
103
}
104
if strings.Contains(mustJSON(t, push), "diff --git") {
105
t.Fatal("push bevat een diff")
106
}
107
if _, err := time.Parse(time.RFC3339, first["timestamp"].(string)); err != nil {
108
t.Fatalf("timestamp %v", first["timestamp"])
109
}
110
readme := fileByPath(t, first["files"].([]any), "README.md")
111
if readme["status"] != "added" || readme["additions"] != float64(1) || readme["deletions"] != float64(0) {
112
t.Fatalf("eerste bestand %v", readme)
113
}
114
changed := fileByPath(t, second["files"].([]any), "README.md")
115
if changed["status"] != "modified" || changed["additions"] != float64(1) || changed["deletions"] != float64(1) {
116
t.Fatalf("tweede bestand %v", changed)
117
}
118
diffPath := mustParse(t, first["diff_url"].(string)).Path
119
if !strings.Contains(diffPath, "/api/v1/repos/tim/hooks/commits/") || !strings.HasSuffix(diffPath, "/diff") {
120
t.Fatalf("diff_url %s", diffPath)
121
}
122
noDiff := mustGet(t, http.DefaultClient, ts.URL+diffPath)
123
if noDiff.StatusCode != http.StatusUnauthorized {
124
t.Fatalf("diff zonder token %d", noDiff.StatusCode)
125
}
126
noDiff.Body.Close()
127
diffRes := getBearer(t, ts.URL+diffPath, token)
128
if diffRes.StatusCode != http.StatusOK || !strings.HasPrefix(diffRes.Header.Get("Content-Type"), "text/plain") {
129
t.Fatalf("commitdiff %d %s", diffRes.StatusCode, diffRes.Header.Get("Content-Type"))
130
}
131
diffText := read(t, diffRes)
132
if !strings.Contains(diffText, "diff --git") || !strings.Contains(diffText, "README.md") || !strings.Contains(diffText, "+a") {
133
t.Fatalf("commitdiff tekst %s", diffText)
134
}
104
135
105
136
git(t, work, "checkout", "-b", "topic")
106
137
writeFile(t, filepath.Join(work, "extra.txt"), "c\n")
@@ -121,6 +152,40 @@ func TestWebhookPayloads(t *testing.T) {
121
152
if _, ok := opened["comment"]; ok {
122
153
t.Fatalf("opened heeft een comment: %s", mustJSON(t, opened))
123
154
}
155
if strings.Contains(mustJSON(t, opened), "diff --git") {
156
t.Fatal("merge request bevat een diff")
157
}
158
if len(mr["reviewers"].([]any)) != 0 || len(mr["comments"].([]any)) != 0 {
159
t.Fatalf("opened heeft al reviewers of comments: %s", mustJSON(t, mr))
160
}
161
mrCommits := mr["commits"].([]any)
162
if len(mrCommits) != 1 || mrCommits[0].(map[string]any)["message"] != "derde" {
163
t.Fatalf("mr commits %s", mustJSON(t, mrCommits))
164
}
165
extra := fileByPath(t, mrCommits[0].(map[string]any)["files"].([]any), "extra.txt")
166
if extra["status"] != "added" || extra["additions"] != float64(1) {
167
t.Fatalf("mr bestand %v", extra)
168
}
169
stats := mr["diff_stats"].(map[string]any)
170
statFile := fileByPath(t, stats["files"].([]any), "extra.txt")
171
if stats["additions"] != float64(1) || stats["deletions"] != float64(0) || statFile["status"] != "added" {
172
t.Fatalf("diff_stats %s", mustJSON(t, stats))
173
}
174
mrDiffPath := mustParse(t, mr["diff_url"].(string)).Path
175
if mrDiffPath != "/api/v1/repos/tim/hooks/merge-requests/1/diff" {
176
t.Fatalf("mr diff_url %s", mrDiffPath)
177
}
178
timUser, err := st.UserByUsername(ctx, "tim")
179
if err != nil {
180
t.Fatal(err)
181
}
182
storedMR, err := st.MergeRequestByNumber(ctx, repo.ID, 1)
183
if err != nil {
184
t.Fatal(err)
185
}
186
if err := st.UpsertReview(ctx, repo.ID, storedMR.ID, timUser.ID, "approved"); err != nil {
187
t.Fatal(err)
188
}
124
189
125
190
page = read(t, mustPost(t, tim, ts.URL+"/tim/hooks/-/merge-requests/1/notes", url.Values{
126
191
"csrf": {csrfOf(t, page)}, "body": {"dit is het commentaar"},
@@ -129,6 +194,23 @@ func TestWebhookPayloads(t *testing.T) {
129
194
if commented["comment"] != "dit is het commentaar" {
130
195
t.Fatalf("comment %s", mustJSON(t, commented))
131
196
}
197
commentedMR := commented["merge_request"].(map[string]any)
198
reviewers := commentedMR["reviewers"].([]any)
199
if len(reviewers) != 1 || reviewers[0].(map[string]any)["username"] != "tim" || reviewers[0].(map[string]any)["status"] != "approved" {
200
t.Fatalf("reviewers %s", mustJSON(t, reviewers))
201
}
202
notes := commentedMR["comments"].([]any)
203
if len(notes) != 1 || notes[0].(map[string]any)["body"] != "dit is het commentaar" || notes[0].(map[string]any)["author"] != "tim" {
204
t.Fatalf("comments %s", mustJSON(t, notes))
205
}
206
mrDiff := getBearer(t, ts.URL+mrDiffPath, token)
207
if mrDiff.StatusCode != http.StatusOK || !strings.HasPrefix(mrDiff.Header.Get("Content-Type"), "text/plain") {
208
t.Fatalf("mr diff %d", mrDiff.StatusCode)
209
}
210
mrDiffText := read(t, mrDiff)
211
if !strings.Contains(mrDiffText, "diff --git") || !strings.Contains(mrDiffText, "extra.txt") {
212
t.Fatalf("mr diff tekst %s", mrDiffText)
213
}
132
214
133
215
page = read(t, mustPost(t, tim, ts.URL+"/tim/hooks/-/merge-requests/1/merge", url.Values{
134
216
"csrf": {csrfOf(t, page)},
@@ -303,7 +385,7 @@ func TestWebhookPayloads(t *testing.T) {
303
385
}
304
386
305
387
infoPage := read(t, mustGet(t, tim, ts.URL+"/-/info"))
306
for _, want := range []string{"Webhook payloads", "log_truncated", "log_url", "/api/v1/webhooks/openapi.json", "/api/v1/repos/{owner}/{repo}/jobs/{id}/log", "commit_message", "source_branch"} {
388
for _, want := range []string{"Webhook payloads", "log_truncated", "log_url", "/api/v1/webhooks/openapi.json", "/api/v1/repos/{owner}/{repo}/jobs/{id}/log", "diff_url", "reviewers", "commit_message", "source_branch"} {
307
389
if !strings.Contains(infoPage, want) {
308
390
t.Errorf("infopagina mist %q", want)
309
391
}
@@ -441,6 +523,18 @@ func TestJobLogAPI(t *testing.T) {
441
523
}
442
524
}
443
525
526
func fileByPath(t *testing.T, files []any, path string) map[string]any {
527
t.Helper()
528
for _, item := range files {
529
file := item.(map[string]any)
530
if file["path"] == path {
531
return file
532
}
533
}
534
t.Fatalf("geen bestand %s in %v", path, files)
535
return nil
536
}
537
444
538
func seedJobLog(t *testing.T, st *store.Store, repoID int64, log string) int64 {
445
539
t.Helper()
446
540
ctx := context.Background()
@@ -101,6 +101,37 @@ func TestWebhookPayloads(t *testing.T) {101
if push["after"] != second["sha"] {101
if push["after"] != second["sha"] {102
t.Fatalf("after %v tip %v", push["after"], second["sha"])102
t.Fatalf("after %v tip %v", push["after"], second["sha"])103
}103
}104
if strings.Contains(mustJSON(t, push), "diff --git") {105
t.Fatal("push bevat een diff")106
}107
if _, err := time.Parse(time.RFC3339, first["timestamp"].(string)); err != nil {108
t.Fatalf("timestamp %v", first["timestamp"])109
}110
readme := fileByPath(t, first["files"].([]any), "README.md")111
if readme["status"] != "added" || readme["additions"] != float64(1) || readme["deletions"] != float64(0) {112
t.Fatalf("eerste bestand %v", readme)113
}114
changed := fileByPath(t, second["files"].([]any), "README.md")115
if changed["status"] != "modified" || changed["additions"] != float64(1) || changed["deletions"] != float64(1) {116
t.Fatalf("tweede bestand %v", changed)117
}118
diffPath := mustParse(t, first["diff_url"].(string)).Path119
if !strings.Contains(diffPath, "/api/v1/repos/tim/hooks/commits/") || !strings.HasSuffix(diffPath, "/diff") {120
t.Fatalf("diff_url %s", diffPath)121
}122
noDiff := mustGet(t, http.DefaultClient, ts.URL+diffPath)123
if noDiff.StatusCode != http.StatusUnauthorized {124
t.Fatalf("diff zonder token %d", noDiff.StatusCode)125
}126
noDiff.Body.Close()127
diffRes := getBearer(t, ts.URL+diffPath, token)128
if diffRes.StatusCode != http.StatusOK || !strings.HasPrefix(diffRes.Header.Get("Content-Type"), "text/plain") {129
t.Fatalf("commitdiff %d %s", diffRes.StatusCode, diffRes.Header.Get("Content-Type"))130
}131
diffText := read(t, diffRes)132
if !strings.Contains(diffText, "diff --git") || !strings.Contains(diffText, "README.md") || !strings.Contains(diffText, "+a") {133
t.Fatalf("commitdiff tekst %s", diffText)134
}104
135
105
git(t, work, "checkout", "-b", "topic")136
git(t, work, "checkout", "-b", "topic")106
writeFile(t, filepath.Join(work, "extra.txt"), "c\n")137
writeFile(t, filepath.Join(work, "extra.txt"), "c\n")@@ -121,6 +152,40 @@ func TestWebhookPayloads(t *testing.T) {121
if _, ok := opened["comment"]; ok {152
if _, ok := opened["comment"]; ok {122
t.Fatalf("opened heeft een comment: %s", mustJSON(t, opened))153
t.Fatalf("opened heeft een comment: %s", mustJSON(t, opened))123
}154
}155
if strings.Contains(mustJSON(t, opened), "diff --git") {156
t.Fatal("merge request bevat een diff")157
}158
if len(mr["reviewers"].([]any)) != 0 || len(mr["comments"].([]any)) != 0 {159
t.Fatalf("opened heeft al reviewers of comments: %s", mustJSON(t, mr))160
}161
mrCommits := mr["commits"].([]any)162
if len(mrCommits) != 1 || mrCommits[0].(map[string]any)["message"] != "derde" {163
t.Fatalf("mr commits %s", mustJSON(t, mrCommits))164
}165
extra := fileByPath(t, mrCommits[0].(map[string]any)["files"].([]any), "extra.txt")166
if extra["status"] != "added" || extra["additions"] != float64(1) {167
t.Fatalf("mr bestand %v", extra)168
}169
stats := mr["diff_stats"].(map[string]any)170
statFile := fileByPath(t, stats["files"].([]any), "extra.txt")171
if stats["additions"] != float64(1) || stats["deletions"] != float64(0) || statFile["status"] != "added" {172
t.Fatalf("diff_stats %s", mustJSON(t, stats))173
}174
mrDiffPath := mustParse(t, mr["diff_url"].(string)).Path175
if mrDiffPath != "/api/v1/repos/tim/hooks/merge-requests/1/diff" {176
t.Fatalf("mr diff_url %s", mrDiffPath)177
}178
timUser, err := st.UserByUsername(ctx, "tim")179
if err != nil {180
t.Fatal(err)181
}182
storedMR, err := st.MergeRequestByNumber(ctx, repo.ID, 1)183
if err != nil {184
t.Fatal(err)185
}186
if err := st.UpsertReview(ctx, repo.ID, storedMR.ID, timUser.ID, "approved"); err != nil {187
t.Fatal(err)188
}124
189
125
page = read(t, mustPost(t, tim, ts.URL+"/tim/hooks/-/merge-requests/1/notes", url.Values{190
page = read(t, mustPost(t, tim, ts.URL+"/tim/hooks/-/merge-requests/1/notes", url.Values{126
"csrf": {csrfOf(t, page)}, "body": {"dit is het commentaar"},191
"csrf": {csrfOf(t, page)}, "body": {"dit is het commentaar"},@@ -129,6 +194,23 @@ func TestWebhookPayloads(t *testing.T) {129
if commented["comment"] != "dit is het commentaar" {194
if commented["comment"] != "dit is het commentaar" {130
t.Fatalf("comment %s", mustJSON(t, commented))195
t.Fatalf("comment %s", mustJSON(t, commented))131
}196
}197
commentedMR := commented["merge_request"].(map[string]any)198
reviewers := commentedMR["reviewers"].([]any)199
if len(reviewers) != 1 || reviewers[0].(map[string]any)["username"] != "tim" || reviewers[0].(map[string]any)["status"] != "approved" {200
t.Fatalf("reviewers %s", mustJSON(t, reviewers))201
}202
notes := commentedMR["comments"].([]any)203
if len(notes) != 1 || notes[0].(map[string]any)["body"] != "dit is het commentaar" || notes[0].(map[string]any)["author"] != "tim" {204
t.Fatalf("comments %s", mustJSON(t, notes))205
}206
mrDiff := getBearer(t, ts.URL+mrDiffPath, token)207
if mrDiff.StatusCode != http.StatusOK || !strings.HasPrefix(mrDiff.Header.Get("Content-Type"), "text/plain") {208
t.Fatalf("mr diff %d", mrDiff.StatusCode)209
}210
mrDiffText := read(t, mrDiff)211
if !strings.Contains(mrDiffText, "diff --git") || !strings.Contains(mrDiffText, "extra.txt") {212
t.Fatalf("mr diff tekst %s", mrDiffText)213
}132
214
133
page = read(t, mustPost(t, tim, ts.URL+"/tim/hooks/-/merge-requests/1/merge", url.Values{215
page = read(t, mustPost(t, tim, ts.URL+"/tim/hooks/-/merge-requests/1/merge", url.Values{134
"csrf": {csrfOf(t, page)},216
"csrf": {csrfOf(t, page)},@@ -303,7 +385,7 @@ func TestWebhookPayloads(t *testing.T) {303
}385
}304
386
305
infoPage := read(t, mustGet(t, tim, ts.URL+"/-/info"))387
infoPage := read(t, mustGet(t, tim, ts.URL+"/-/info"))306
for _, want := range []string{"Webhook payloads", "log_truncated", "log_url", "/api/v1/webhooks/openapi.json", "/api/v1/repos/{owner}/{repo}/jobs/{id}/log", "commit_message", "source_branch"} {388
for _, want := range []string{"Webhook payloads", "log_truncated", "log_url", "/api/v1/webhooks/openapi.json", "/api/v1/repos/{owner}/{repo}/jobs/{id}/log", "diff_url", "reviewers", "commit_message", "source_branch"} {307
if !strings.Contains(infoPage, want) {389
if !strings.Contains(infoPage, want) {308
t.Errorf("infopagina mist %q", want)390
t.Errorf("infopagina mist %q", want)309
}391
}@@ -441,6 +523,18 @@ func TestJobLogAPI(t *testing.T) {441
}523
}442
}524
}443
525
526
func fileByPath(t *testing.T, files []any, path string) map[string]any {527
t.Helper()528
for _, item := range files {529
file := item.(map[string]any)530
if file["path"] == path {531
return file532
}533
}534
t.Fatalf("geen bestand %s in %v", path, files)535
return nil536
}537
444
func seedJobLog(t *testing.T, st *store.Store, repoID int64, log string) int64 {538
func seedJobLog(t *testing.T, st *store.Store, repoID int64, log string) int64 {445
t.Helper()539
t.Helper()446
ctx := context.Background()540
ctx := context.Background()@@ -117,6 +117,8 @@ func (s *Server) Handler() http.Handler {
117
117
mux.HandleFunc("POST /{owner}/{repo}/git-receive-pack", s.gitHTTP)
118
118
mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/releases", s.createRelease)
119
119
mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log", s.jobLogAPI)
120
mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff", s.commitDiffAPI)
121
mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/merge-requests/{number}/diff", s.mrDiffAPI)
120
122
mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/webhook-secrets", s.repoWebhookSecrets)
121
123
mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/webhooks", s.repoWebhookAPI)
122
124
mux.HandleFunc("PUT /api/v1/repos/{owner}/{repo}/webhooks/{id}", s.repoWebhookUpdate)
@@ -117,6 +117,8 @@ func (s *Server) Handler() http.Handler {117
mux.HandleFunc("POST /{owner}/{repo}/git-receive-pack", s.gitHTTP)117
mux.HandleFunc("POST /{owner}/{repo}/git-receive-pack", s.gitHTTP)118
mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/releases", s.createRelease)118
mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/releases", s.createRelease)119
mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log", s.jobLogAPI)119
mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log", s.jobLogAPI)120
mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff", s.commitDiffAPI)121
mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/merge-requests/{number}/diff", s.mrDiffAPI)120
mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/webhook-secrets", s.repoWebhookSecrets)122
mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/webhook-secrets", s.repoWebhookSecrets)121
mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/webhooks", s.repoWebhookAPI)123
mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/webhooks", s.repoWebhookAPI)122
mux.HandleFunc("PUT /api/v1/repos/{owner}/{repo}/webhooks/{id}", s.repoWebhookUpdate)124
mux.HandleFunc("PUT /api/v1/repos/{owner}/{repo}/webhooks/{id}", s.repoWebhookUpdate)@@ -44,12 +44,58 @@ func OpenAPI() []byte {
44
44
"pipeline_success and pipeline_failure include the pipeline and every job. " +
45
45
"Every job includes its console output: the last 200 lines, at most 64 KiB. Secret values of at least 8 characters are replaced with [MASKED]. " +
46
46
"log_truncated is true when the log was cut. log_url is then GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log and needs Authorization Bearer with a personal token that can read the repo. " +
47
"A push lists ref, before, after and up to 20 commits. " +
47
"A push lists ref, before, after and up to 20 commits. Each commit has sha, message, author, timestamp, URL, changed files and diff_url. A file has status added, modified, removed or renamed, plus added and deleted line counts. The payload does not include the diff text. " +
48
"diff_url for a commit is GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff. " +
49
"A merge request includes reviewers, comments, up to 20 commits, diff statistics and diff_url, and no diff text. " +
50
"diff_url for a merge request is GET /api/v1/repos/{owner}/{repo}/merge-requests/{id}/diff. " +
51
"Both diff requests need Authorization Bearer and a personal token that can read the repo. " +
48
52
"A merge request uses action opened, merged or commented, and commented includes the comment text. " +
49
53
"A release lists the tag, name, commit and asset URLs.",
50
54
},
51
55
"servers": []any{map[string]any{"url": "/api/v1"}},
52
56
"paths": map[string]any{
57
"/repos/{owner}/{repo}/commits/{sha}/diff": map[string]any{
58
"get": map[string]any{
59
"summary": "Commit diff",
60
"description": "Returns the unified diff of the commit against its first parent as text/plain. A root commit is compared with an empty tree. Requires a personal access token that can read the repo. On a public repo any valid personal token is enough. Job tokens are rejected.",
61
"security": []any{map[string]any{"bearer": []any{}}},
62
"parameters": []any{
63
map[string]any{"name": "owner", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},
64
map[string]any{"name": "repo", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},
65
map[string]any{"name": "sha", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},
66
},
67
"responses": map[string]any{
68
"200": map[string]any{
69
"description": "Unified diff.",
70
"content": map[string]any{"text/plain": map[string]any{"schema": map[string]any{"type": "string"}}},
71
},
72
"401": map[string]any{"description": "Missing or invalid token."},
73
"403": map[string]any{"description": "The token cannot read this private repo."},
74
"404": map[string]any{"description": "Unknown repo or commit."},
75
},
76
},
77
},
78
"/repos/{owner}/{repo}/merge-requests/{id}/diff": map[string]any{
79
"get": map[string]any{
80
"summary": "Merge request diff",
81
"description": "Returns the three-dot unified diff from the target branch to the source branch as text/plain. Requires a personal access token that can read the repo. On a public repo any valid personal token is enough. Job tokens are rejected.",
82
"security": []any{map[string]any{"bearer": []any{}}},
83
"parameters": []any{
84
map[string]any{"name": "owner", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},
85
map[string]any{"name": "repo", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},
86
map[string]any{"name": "id", "in": "path", "required": true, "schema": map[string]any{"type": "integer"}},
87
},
88
"responses": map[string]any{
89
"200": map[string]any{
90
"description": "Unified diff.",
91
"content": map[string]any{"text/plain": map[string]any{"schema": map[string]any{"type": "string"}}},
92
},
93
"401": map[string]any{"description": "Missing or invalid token."},
94
"403": map[string]any{"description": "The token cannot read this private repo."},
95
"404": map[string]any{"description": "Unknown repo or merge request."},
96
},
97
},
98
},
53
99
"/repos/{owner}/{repo}/jobs/{id}/log": map[string]any{
54
100
"get": map[string]any{
55
101
"summary": "Full job log",
@@ -125,12 +171,23 @@ func OpenAPI() []byte {
125
171
"after": str("New SHA."),
126
172
"commits": map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/Commit"}},
127
173
}, []string{"object_kind", "type", "project", "ref", "before", "after", "commits"}),
128
"Commit": obj("One commit made reachable by the push.", map[string]any{
129
"sha": str("Commit SHA."),
130
"message": str("Subject and body."),
131
"author": str("Name and email."),
132
"url": str("Commit page."),
133
}, []string{"sha", "message", "author", "url"}),
174
"Commit": obj("One commit. The diff text is not included.", map[string]any{
175
"sha": str("Commit SHA."),
176
"message": str("Subject and body."),
177
"author": str("Name and email."),
178
"timestamp": str("Author time in RFC3339."),
179
"url": str("Commit page."),
180
"files": map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/FileChange"}},
181
"diff_url": str("GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff. Requires Authorization Bearer and a personal token that can read the repo. The response is the unified diff as text/plain."),
182
}, []string{"sha", "message", "author", "timestamp", "url", "files", "diff_url"}),
183
"FileChange": obj("One changed file, without the diff text.", map[string]any{
184
"path": str("Path after the change."),
185
"status": str("added, modified, removed or renamed."),
186
"previous_path": str("Path before a rename."),
187
"additions": map[string]any{"type": "integer", "description": "Added lines. Zero for a binary file."},
188
"deletions": map[string]any{"type": "integer", "description": "Deleted lines. Zero for a binary file."},
189
"binary": boolean("True when the file is binary."),
190
}, []string{"path", "status", "additions", "deletions"}),
134
191
"MergeRequestEvent": obj("Opened, merged or commented.", map[string]any{
135
192
"object_kind": str("Always merge_request."),
136
193
"type": str("Always merge_request."),
@@ -149,7 +206,31 @@ func OpenAPI() []byte {
149
206
"author": str("User who opened the merge request."),
150
207
"action": str("opened, merged or commented."),
151
208
"url": str("Merge request page."),
152
}, []string{"id", "title", "description", "source_branch", "target_branch", "status", "author", "action"}),
209
"reviewers": map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/Reviewer"}},
210
"comments": map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/Comment"}},
211
"commits": map[string]any{"type": "array", "description": "Up to 20 commits on the source branch that the target does not have, oldest first.", "items": map[string]any{"$ref": "#/components/schemas/Commit"}},
212
"diff_stats": map[string]any{"$ref": "#/components/schemas/DiffStats"},
213
"diff_url": str("GET /api/v1/repos/{owner}/{repo}/merge-requests/{id}/diff. Requires Authorization Bearer and a personal token that can read the repo. The response is the three-dot unified diff as text/plain."),
214
}, []string{"id", "title", "description", "source_branch", "target_branch", "status", "author", "action", "reviewers", "comments", "commits", "diff_stats", "diff_url"}),
215
"Reviewer": obj("The current review of one person.", map[string]any{
216
"username": str("Username."),
217
"status": str("approved, changes, rejected or dismissed."),
218
}, []string{"username", "status"}),
219
"Comment": obj("One comment on the merge request.", map[string]any{
220
"id": map[string]any{"type": "integer", "description": "Comment id."},
221
"author": str("Username."),
222
"body": str("Comment text."),
223
"created_at": str("Time in RFC3339."),
224
"file_path": str("File, when the comment is on a line."),
225
"line_start": map[string]any{"type": "integer", "description": "First line."},
226
"line_end": map[string]any{"type": "integer", "description": "Last line."},
227
"parent_id": map[string]any{"type": "integer", "description": "Parent comment, when this is a reply."},
228
}, []string{"id", "author", "body", "created_at"}),
229
"DiffStats": obj("Line counts of the merge request diff. The diff text is not included.", map[string]any{
230
"additions": map[string]any{"type": "integer", "description": "Added lines."},
231
"deletions": map[string]any{"type": "integer", "description": "Deleted lines."},
232
"files": map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/FileChange"}},
233
}, []string{"additions", "deletions", "files"}),
153
234
"ReleaseEvent": obj("A published release.", map[string]any{
154
235
"object_kind": str("Always release."),
155
236
"type": str("Always release_published."),
@@ -44,12 +44,58 @@ func OpenAPI() []byte {44
"pipeline_success and pipeline_failure include the pipeline and every job. " +44
"pipeline_success and pipeline_failure include the pipeline and every job. " +45
"Every job includes its console output: the last 200 lines, at most 64 KiB. Secret values of at least 8 characters are replaced with [MASKED]. " +45
"Every job includes its console output: the last 200 lines, at most 64 KiB. Secret values of at least 8 characters are replaced with [MASKED]. " +46
"log_truncated is true when the log was cut. log_url is then GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log and needs Authorization Bearer with a personal token that can read the repo. " +46
"log_truncated is true when the log was cut. log_url is then GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log and needs Authorization Bearer with a personal token that can read the repo. " +47
"A push lists ref, before, after and up to 20 commits. " +47
"A push lists ref, before, after and up to 20 commits. Each commit has sha, message, author, timestamp, URL, changed files and diff_url. A file has status added, modified, removed or renamed, plus added and deleted line counts. The payload does not include the diff text. " +48
"diff_url for a commit is GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff. " +49
"A merge request includes reviewers, comments, up to 20 commits, diff statistics and diff_url, and no diff text. " +50
"diff_url for a merge request is GET /api/v1/repos/{owner}/{repo}/merge-requests/{id}/diff. " +51
"Both diff requests need Authorization Bearer and a personal token that can read the repo. " +48
"A merge request uses action opened, merged or commented, and commented includes the comment text. " +52
"A merge request uses action opened, merged or commented, and commented includes the comment text. " +49
"A release lists the tag, name, commit and asset URLs.",53
"A release lists the tag, name, commit and asset URLs.",50
},54
},51
"servers": []any{map[string]any{"url": "/api/v1"}},55
"servers": []any{map[string]any{"url": "/api/v1"}},52
"paths": map[string]any{56
"paths": map[string]any{57
"/repos/{owner}/{repo}/commits/{sha}/diff": map[string]any{58
"get": map[string]any{59
"summary": "Commit diff",60
"description": "Returns the unified diff of the commit against its first parent as text/plain. A root commit is compared with an empty tree. Requires a personal access token that can read the repo. On a public repo any valid personal token is enough. Job tokens are rejected.",61
"security": []any{map[string]any{"bearer": []any{}}},62
"parameters": []any{63
map[string]any{"name": "owner", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},64
map[string]any{"name": "repo", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},65
map[string]any{"name": "sha", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},66
},67
"responses": map[string]any{68
"200": map[string]any{69
"description": "Unified diff.",70
"content": map[string]any{"text/plain": map[string]any{"schema": map[string]any{"type": "string"}}},71
},72
"401": map[string]any{"description": "Missing or invalid token."},73
"403": map[string]any{"description": "The token cannot read this private repo."},74
"404": map[string]any{"description": "Unknown repo or commit."},75
},76
},77
},78
"/repos/{owner}/{repo}/merge-requests/{id}/diff": map[string]any{79
"get": map[string]any{80
"summary": "Merge request diff",81
"description": "Returns the three-dot unified diff from the target branch to the source branch as text/plain. Requires a personal access token that can read the repo. On a public repo any valid personal token is enough. Job tokens are rejected.",82
"security": []any{map[string]any{"bearer": []any{}}},83
"parameters": []any{84
map[string]any{"name": "owner", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},85
map[string]any{"name": "repo", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},86
map[string]any{"name": "id", "in": "path", "required": true, "schema": map[string]any{"type": "integer"}},87
},88
"responses": map[string]any{89
"200": map[string]any{90
"description": "Unified diff.",91
"content": map[string]any{"text/plain": map[string]any{"schema": map[string]any{"type": "string"}}},92
},93
"401": map[string]any{"description": "Missing or invalid token."},94
"403": map[string]any{"description": "The token cannot read this private repo."},95
"404": map[string]any{"description": "Unknown repo or merge request."},96
},97
},98
},53
"/repos/{owner}/{repo}/jobs/{id}/log": map[string]any{99
"/repos/{owner}/{repo}/jobs/{id}/log": map[string]any{54
"get": map[string]any{100
"get": map[string]any{55
"summary": "Full job log",101
"summary": "Full job log",@@ -125,12 +171,23 @@ func OpenAPI() []byte {125
"after": str("New SHA."),171
"after": str("New SHA."),126
"commits": map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/Commit"}},172
"commits": map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/Commit"}},127
}, []string{"object_kind", "type", "project", "ref", "before", "after", "commits"}),173
}, []string{"object_kind", "type", "project", "ref", "before", "after", "commits"}),128
"Commit": obj("One commit made reachable by the push.", map[string]any{174
"Commit": obj("One commit. The diff text is not included.", map[string]any{129
"sha": str("Commit SHA."),175
"sha": str("Commit SHA."),130
"message": str("Subject and body."),176
"message": str("Subject and body."),131
"author": str("Name and email."),177
"author": str("Name and email."),132
"url": str("Commit page."),178
"timestamp": str("Author time in RFC3339."),133
}, []string{"sha", "message", "author", "url"}),179
"url": str("Commit page."),180
"files": map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/FileChange"}},181
"diff_url": str("GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff. Requires Authorization Bearer and a personal token that can read the repo. The response is the unified diff as text/plain."),182
}, []string{"sha", "message", "author", "timestamp", "url", "files", "diff_url"}),183
"FileChange": obj("One changed file, without the diff text.", map[string]any{184
"path": str("Path after the change."),185
"status": str("added, modified, removed or renamed."),186
"previous_path": str("Path before a rename."),187
"additions": map[string]any{"type": "integer", "description": "Added lines. Zero for a binary file."},188
"deletions": map[string]any{"type": "integer", "description": "Deleted lines. Zero for a binary file."},189
"binary": boolean("True when the file is binary."),190
}, []string{"path", "status", "additions", "deletions"}),134
"MergeRequestEvent": obj("Opened, merged or commented.", map[string]any{191
"MergeRequestEvent": obj("Opened, merged or commented.", map[string]any{135
"object_kind": str("Always merge_request."),192
"object_kind": str("Always merge_request."),136
"type": str("Always merge_request."),193
"type": str("Always merge_request."),@@ -149,7 +206,31 @@ func OpenAPI() []byte {149
"author": str("User who opened the merge request."),206
"author": str("User who opened the merge request."),150
"action": str("opened, merged or commented."),207
"action": str("opened, merged or commented."),151
"url": str("Merge request page."),208
"url": str("Merge request page."),152
}, []string{"id", "title", "description", "source_branch", "target_branch", "status", "author", "action"}),209
"reviewers": map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/Reviewer"}},210
"comments": map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/Comment"}},211
"commits": map[string]any{"type": "array", "description": "Up to 20 commits on the source branch that the target does not have, oldest first.", "items": map[string]any{"$ref": "#/components/schemas/Commit"}},212
"diff_stats": map[string]any{"$ref": "#/components/schemas/DiffStats"},213
"diff_url": str("GET /api/v1/repos/{owner}/{repo}/merge-requests/{id}/diff. Requires Authorization Bearer and a personal token that can read the repo. The response is the three-dot unified diff as text/plain."),214
}, []string{"id", "title", "description", "source_branch", "target_branch", "status", "author", "action", "reviewers", "comments", "commits", "diff_stats", "diff_url"}),215
"Reviewer": obj("The current review of one person.", map[string]any{216
"username": str("Username."),217
"status": str("approved, changes, rejected or dismissed."),218
}, []string{"username", "status"}),219
"Comment": obj("One comment on the merge request.", map[string]any{220
"id": map[string]any{"type": "integer", "description": "Comment id."},221
"author": str("Username."),222
"body": str("Comment text."),223
"created_at": str("Time in RFC3339."),224
"file_path": str("File, when the comment is on a line."),225
"line_start": map[string]any{"type": "integer", "description": "First line."},226
"line_end": map[string]any{"type": "integer", "description": "Last line."},227
"parent_id": map[string]any{"type": "integer", "description": "Parent comment, when this is a reply."},228
}, []string{"id", "author", "body", "created_at"}),229
"DiffStats": obj("Line counts of the merge request diff. The diff text is not included.", map[string]any{230
"additions": map[string]any{"type": "integer", "description": "Added lines."},231
"deletions": map[string]any{"type": "integer", "description": "Deleted lines."},232
"files": map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/FileChange"}},233
}, []string{"additions", "deletions", "files"}),153
"ReleaseEvent": obj("A published release.", map[string]any{234
"ReleaseEvent": obj("A published release.", map[string]any{154
"object_kind": str("Always release."),235
"object_kind": str("Always release."),155
"type": str("Always release_published."),236
"type": str("Always release_published."),@@ -72,25 +72,72 @@ type JobInfo struct {
72
72
LogURL string `json:"log_url,omitempty"`
73
73
}
74
74
75
// CommitInfo is één commit in een push.
75
// CommitInfo is één commit in een push of merge request.
76
// Files noemt de wijzigingen. De difftekst zelf staat niet in de payload;
77
// diff_url wijst naar de API die hem teruggeeft.
76
78
type CommitInfo struct {
77
SHA string `json:"sha"`
78
Message string `json:"message"`
79
Author string `json:"author"`
80
URL string `json:"url"`
79
SHA string `json:"sha"`
80
Message string `json:"message"`
81
Author string `json:"author"`
82
Timestamp string `json:"timestamp"`
83
URL string `json:"url"`
84
Files []FileChange `json:"files"`
85
DiffURL string `json:"diff_url"`
86
}
87
88
// FileChange is één gewijzigd bestand, met status en regelaantallen.
89
// Status is added, modified, removed of renamed.
90
type FileChange struct {
91
Path string `json:"path"`
92
Status string `json:"status"`
93
PreviousPath string `json:"previous_path,omitempty"`
94
Additions int `json:"additions"`
95
Deletions int `json:"deletions"`
96
Binary bool `json:"binary,omitempty"`
81
97
}
82
98
83
99
// MRInfo is de merge request van het event.
100
// DiffStats is de three-dot vergelijking. De difftekst staat op diff_url.
84
101
type MRInfo struct {
85
ID int64 `json:"id"`
86
Title string `json:"title"`
87
Description string `json:"description"`
88
SourceBranch string `json:"source_branch"`
89
TargetBranch string `json:"target_branch"`
90
Status string `json:"status"`
91
Author string `json:"author"`
92
Action string `json:"action"`
93
URL string `json:"url,omitempty"`
102
ID int64 `json:"id"`
103
Title string `json:"title"`
104
Description string `json:"description"`
105
SourceBranch string `json:"source_branch"`
106
TargetBranch string `json:"target_branch"`
107
Status string `json:"status"`
108
Author string `json:"author"`
109
Action string `json:"action"`
110
URL string `json:"url,omitempty"`
111
Reviewers []ReviewerInfo `json:"reviewers"`
112
Comments []CommentInfo `json:"comments"`
113
Commits []CommitInfo `json:"commits"`
114
DiffStats DiffStats `json:"diff_stats"`
115
DiffURL string `json:"diff_url"`
116
}
117
118
// ReviewerInfo is de huidige review van één persoon.
119
type ReviewerInfo struct {
120
Username string `json:"username"`
121
Status string `json:"status"`
122
}
123
124
// CommentInfo is een reactie op de merge request.
125
type CommentInfo struct {
126
ID int64 `json:"id"`
127
Author string `json:"author"`
128
Body string `json:"body"`
129
CreatedAt string `json:"created_at"`
130
FilePath string `json:"file_path,omitempty"`
131
LineStart int `json:"line_start,omitempty"`
132
LineEnd int `json:"line_end,omitempty"`
133
ParentID int64 `json:"parent_id,omitempty"`
134
}
135
136
// DiffStats telt de regels van de vergelijking, per bestand.
137
type DiffStats struct {
138
Additions int `json:"additions"`
139
Deletions int `json:"deletions"`
140
Files []FileChange `json:"files"`
94
141
}
95
142
96
143
// ReleaseInfo is een gepubliceerde release.
@@ -135,6 +182,11 @@ func (ev Event) Document() Document {
135
182
if commits == nil {
136
183
commits = []CommitInfo{}
137
184
}
185
for i := range commits {
186
if commits[i].Files == nil {
187
commits[i].Files = []FileChange{}
188
}
189
}
138
190
d.Commits = &commits
139
191
case EventPipelineSuccess, EventPipelineFailure:
140
192
jobs := ev.Jobs
@@ -143,8 +195,29 @@ func (ev Event) Document() Document {
143
195
}
144
196
d.Jobs = &jobs
145
197
case EventMergeRequest:
146
if ev.MergeRequest != nil && ev.MergeRequest.Action == "commented" {
147
d.Comment = ev.Comment
198
if ev.MergeRequest != nil {
199
mr := *ev.MergeRequest
200
if mr.Reviewers == nil {
201
mr.Reviewers = []ReviewerInfo{}
202
}
203
if mr.Comments == nil {
204
mr.Comments = []CommentInfo{}
205
}
206
if mr.Commits == nil {
207
mr.Commits = []CommitInfo{}
208
}
209
for i := range mr.Commits {
210
if mr.Commits[i].Files == nil {
211
mr.Commits[i].Files = []FileChange{}
212
}
213
}
214
if mr.DiffStats.Files == nil {
215
mr.DiffStats.Files = []FileChange{}
216
}
217
d.MergeRequest = &mr
218
if mr.Action == "commented" {
219
d.Comment = ev.Comment
220
}
148
221
}
149
222
}
150
223
if d.Release != nil && d.Release.Assets == nil {
@@ -233,7 +306,12 @@ func Example() string {
233
306
Ref: "refs/heads/master", Before: strings.Repeat("0", 40), After: "abc123",
234
307
Commits: []CommitInfo{{
235
308
SHA: "abc123", Message: "fix de build", Author: "Tim <tim@example.com>",
236
URL: "https://git.example/tim/app/-/commit/abc123",
309
Timestamp: "2026-10-22T12:00:00Z",
310
URL: "https://git.example/tim/app/-/commit/abc123",
311
DiffURL: "https://git.example/api/v1/repos/tim/app/commits/abc123/diff",
312
Files: []FileChange{{
313
Path: "README.md", Status: "modified", Additions: 1, Deletions: 1,
314
}},
237
315
}},
238
316
},
239
317
{
@@ -242,7 +320,21 @@ func Example() string {
242
320
ID: 4, Title: "Toon de kloon-URL", Description: "SSH en HTTPS.",
243
321
SourceBranch: "feature", TargetBranch: "master", Status: "open",
244
322
Author: "ada", Action: "opened",
245
URL: "https://git.example/tim/app/-/merge-requests/4",
323
URL: "https://git.example/tim/app/-/merge-requests/4",
324
DiffURL: "https://git.example/api/v1/repos/tim/app/merge-requests/4/diff",
325
Reviewers: []ReviewerInfo{{Username: "tim", Status: "approved"}},
326
Comments: []CommentInfo{},
327
Commits: []CommitInfo{{
328
SHA: "abc123", Message: "fix de build", Author: "Tim <tim@example.com>",
329
Timestamp: "2026-10-22T12:00:00Z",
330
URL: "https://git.example/tim/app/-/commit/abc123",
331
DiffURL: "https://git.example/api/v1/repos/tim/app/commits/abc123/diff",
332
Files: []FileChange{{Path: "README.md", Status: "modified", Additions: 1, Deletions: 1}},
333
}},
334
DiffStats: DiffStats{
335
Additions: 1, Deletions: 1,
336
Files: []FileChange{{Path: "README.md", Status: "modified", Additions: 1, Deletions: 1}},
337
},
246
338
},
247
339
},
248
340
{
@@ -72,25 +72,72 @@ type JobInfo struct {72
LogURL string `json:"log_url,omitempty"`72
LogURL string `json:"log_url,omitempty"`73
}73
}74
74
75
// CommitInfo is één commit in een push.75
// CommitInfo is één commit in een push of merge request.76
// Files noemt de wijzigingen. De difftekst zelf staat niet in de payload;77
// diff_url wijst naar de API die hem teruggeeft.76
type CommitInfo struct {78
type CommitInfo struct {77
SHA string `json:"sha"`79
SHA string `json:"sha"`78
Message string `json:"message"`80
Message string `json:"message"`79
Author string `json:"author"`81
Author string `json:"author"`80
URL string `json:"url"`82
Timestamp string `json:"timestamp"`83
URL string `json:"url"`84
Files []FileChange `json:"files"`85
DiffURL string `json:"diff_url"`86
}87
88
// FileChange is één gewijzigd bestand, met status en regelaantallen.89
// Status is added, modified, removed of renamed.90
type FileChange struct {91
Path string `json:"path"`92
Status string `json:"status"`93
PreviousPath string `json:"previous_path,omitempty"`94
Additions int `json:"additions"`95
Deletions int `json:"deletions"`96
Binary bool `json:"binary,omitempty"`81
}97
}82
98
83
// MRInfo is de merge request van het event.99
// MRInfo is de merge request van het event.100
// DiffStats is de three-dot vergelijking. De difftekst staat op diff_url.84
type MRInfo struct {101
type MRInfo struct {85
ID int64 `json:"id"`102
ID int64 `json:"id"`86
Title string `json:"title"`103
Title string `json:"title"`87
Description string `json:"description"`104
Description string `json:"description"`88
SourceBranch string `json:"source_branch"`105
SourceBranch string `json:"source_branch"`89
TargetBranch string `json:"target_branch"`106
TargetBranch string `json:"target_branch"`90
Status string `json:"status"`107
Status string `json:"status"`91
Author string `json:"author"`108
Author string `json:"author"`92
Action string `json:"action"`109
Action string `json:"action"`93
URL string `json:"url,omitempty"`110
URL string `json:"url,omitempty"`111
Reviewers []ReviewerInfo `json:"reviewers"`112
Comments []CommentInfo `json:"comments"`113
Commits []CommitInfo `json:"commits"`114
DiffStats DiffStats `json:"diff_stats"`115
DiffURL string `json:"diff_url"`116
}117
118
// ReviewerInfo is de huidige review van één persoon.119
type ReviewerInfo struct {120
Username string `json:"username"`121
Status string `json:"status"`122
}123
124
// CommentInfo is een reactie op de merge request.125
type CommentInfo struct {126
ID int64 `json:"id"`127
Author string `json:"author"`128
Body string `json:"body"`129
CreatedAt string `json:"created_at"`130
FilePath string `json:"file_path,omitempty"`131
LineStart int `json:"line_start,omitempty"`132
LineEnd int `json:"line_end,omitempty"`133
ParentID int64 `json:"parent_id,omitempty"`134
}135
136
// DiffStats telt de regels van de vergelijking, per bestand.137
type DiffStats struct {138
Additions int `json:"additions"`139
Deletions int `json:"deletions"`140
Files []FileChange `json:"files"`94
}141
}95
142
96
// ReleaseInfo is een gepubliceerde release.143
// ReleaseInfo is een gepubliceerde release.@@ -135,6 +182,11 @@ func (ev Event) Document() Document {135
if commits == nil {182
if commits == nil {136
commits = []CommitInfo{}183
commits = []CommitInfo{}137
}184
}185
for i := range commits {186
if commits[i].Files == nil {187
commits[i].Files = []FileChange{}188
}189
}138
d.Commits = &commits190
d.Commits = &commits139
case EventPipelineSuccess, EventPipelineFailure:191
case EventPipelineSuccess, EventPipelineFailure:140
jobs := ev.Jobs192
jobs := ev.Jobs@@ -143,8 +195,29 @@ func (ev Event) Document() Document {143
}195
}144
d.Jobs = &jobs196
d.Jobs = &jobs145
case EventMergeRequest:197
case EventMergeRequest:146
if ev.MergeRequest != nil && ev.MergeRequest.Action == "commented" {198
if ev.MergeRequest != nil {147
d.Comment = ev.Comment199
mr := *ev.MergeRequest200
if mr.Reviewers == nil {201
mr.Reviewers = []ReviewerInfo{}202
}203
if mr.Comments == nil {204
mr.Comments = []CommentInfo{}205
}206
if mr.Commits == nil {207
mr.Commits = []CommitInfo{}208
}209
for i := range mr.Commits {210
if mr.Commits[i].Files == nil {211
mr.Commits[i].Files = []FileChange{}212
}213
}214
if mr.DiffStats.Files == nil {215
mr.DiffStats.Files = []FileChange{}216
}217
d.MergeRequest = &mr218
if mr.Action == "commented" {219
d.Comment = ev.Comment220
}148
}221
}149
}222
}150
if d.Release != nil && d.Release.Assets == nil {223
if d.Release != nil && d.Release.Assets == nil {@@ -233,7 +306,12 @@ func Example() string {233
Ref: "refs/heads/master", Before: strings.Repeat("0", 40), After: "abc123",306
Ref: "refs/heads/master", Before: strings.Repeat("0", 40), After: "abc123",234
Commits: []CommitInfo{{307
Commits: []CommitInfo{{235
SHA: "abc123", Message: "fix de build", Author: "Tim <tim@example.com>",308
SHA: "abc123", Message: "fix de build", Author: "Tim <tim@example.com>",236
URL: "https://git.example/tim/app/-/commit/abc123",309
Timestamp: "2026-10-22T12:00:00Z",310
URL: "https://git.example/tim/app/-/commit/abc123",311
DiffURL: "https://git.example/api/v1/repos/tim/app/commits/abc123/diff",312
Files: []FileChange{{313
Path: "README.md", Status: "modified", Additions: 1, Deletions: 1,314
}},237
}},315
}},238
},316
},239
{317
{@@ -242,7 +320,21 @@ func Example() string {242
ID: 4, Title: "Toon de kloon-URL", Description: "SSH en HTTPS.",320
ID: 4, Title: "Toon de kloon-URL", Description: "SSH en HTTPS.",243
SourceBranch: "feature", TargetBranch: "master", Status: "open",321
SourceBranch: "feature", TargetBranch: "master", Status: "open",244
Author: "ada", Action: "opened",322
Author: "ada", Action: "opened",245
URL: "https://git.example/tim/app/-/merge-requests/4",323
URL: "https://git.example/tim/app/-/merge-requests/4",324
DiffURL: "https://git.example/api/v1/repos/tim/app/merge-requests/4/diff",325
Reviewers: []ReviewerInfo{{Username: "tim", Status: "approved"}},326
Comments: []CommentInfo{},327
Commits: []CommitInfo{{328
SHA: "abc123", Message: "fix de build", Author: "Tim <tim@example.com>",329
Timestamp: "2026-10-22T12:00:00Z",330
URL: "https://git.example/tim/app/-/commit/abc123",331
DiffURL: "https://git.example/api/v1/repos/tim/app/commits/abc123/diff",332
Files: []FileChange{{Path: "README.md", Status: "modified", Additions: 1, Deletions: 1}},333
}},334
DiffStats: DiffStats{335
Additions: 1, Deletions: 1,336
Files: []FileChange{{Path: "README.md", Status: "modified", Additions: 1, Deletions: 1}},337
},246
},338
},247
},339
},248
{340
{@@ -70,17 +70,32 @@ func TestDocumentShapes(t *testing.T) {
70
70
t.Fatalf("korte log heeft een url: %v", ok)
71
71
}
72
72
73
push := Event{Type: EventPush, Project: "tim/app", Ref: "refs/heads/master", Before: "a", After: "b"}
73
push := Event{Type: EventPush, Project: "tim/app", Ref: "refs/heads/master", Before: "a", After: "b", Commits: []CommitInfo{{
74
SHA: "abc", Message: "fix", Author: "tim <tim@example.com>", Timestamp: "2026-10-22T12:00:00Z",
75
URL: "https://git.example/commit", DiffURL: "https://git.example/api/v1/repos/tim/app/commits/abc/diff",
76
Files: []FileChange{{Path: "README.md", Status: "modified", Additions: 1, Deletions: 1}},
77
}}}
74
78
body, err = RenderBody("", push, nil)
75
79
if err != nil {
76
80
t.Fatal(err)
77
81
}
82
if strings.Contains(string(body), "diff --git") {
83
t.Fatalf("push bevat een diff: %s", body)
84
}
78
85
if err := json.Unmarshal(body, &doc); err != nil {
79
86
t.Fatal(err)
80
87
}
81
88
if doc["object_kind"] != "push" || doc["before"] != "a" || doc["commits"] == nil {
82
89
t.Fatalf("push %s", body)
83
90
}
91
commit := doc["commits"].([]any)[0].(map[string]any)
92
file := commit["files"].([]any)[0].(map[string]any)
93
if commit["timestamp"] != "2026-10-22T12:00:00Z" || commit["diff_url"] == "" || file["status"] != "modified" || file["additions"] != float64(1) || file["deletions"] != float64(1) {
94
t.Fatalf("commit %s", body)
95
}
96
if _, has := commit["diff"]; has || file["path"] != "README.md" {
97
t.Fatalf("commit lekt een diff: %s", body)
98
}
84
99
85
100
mr := Event{
86
101
Type: EventMergeRequest, Project: "tim/app", Comment: "hoort niet mee",
@@ -90,8 +105,15 @@ func TestDocumentShapes(t *testing.T) {
90
105
if err != nil {
91
106
t.Fatal(err)
92
107
}
93
if strings.Contains(string(body), "hoort niet mee") || !strings.Contains(string(body), `"action":"opened"`) {
94
t.Fatalf("opened lekt commentaar: %s", body)
108
if strings.Contains(string(body), "hoort niet mee") || !strings.Contains(string(body), `"action":"opened"`) || strings.Contains(string(body), "diff --git") {
109
t.Fatalf("opened lekt commentaar of een diff: %s", body)
110
}
111
if err := json.Unmarshal(body, &doc); err != nil {
112
t.Fatal(err)
113
}
114
openedMR := doc["merge_request"].(map[string]any)
115
if openedMR["reviewers"] == nil || openedMR["comments"] == nil || openedMR["commits"] == nil || openedMR["diff_stats"] == nil || openedMR["diff_url"] == nil {
116
t.Fatalf("mr mist details: %s", body)
95
117
}
96
118
mr.MergeRequest.Action = "commented"
97
119
mr.Comment = "mooie opmerking"
@@ -139,6 +161,7 @@ func TestOpenAPIMatchesExample(t *testing.T) {
139
161
"PipelineEvent", "PushEvent", "MergeRequestEvent", "ReleaseEvent",
140
162
"commit_message", "allow_failure", "log_truncated", "log_url",
141
163
"/repos/{owner}/{repo}/jobs/{id}/log",
164
"diff_url", "reviewers", "diff_stats", "/commits/{sha}/diff", "/merge-requests/{id}/diff",
142
165
"source_branch", "target_branch", "before", "after", "assets",
143
166
} {
144
167
if !strings.Contains(raw, want) {
@@ -146,7 +169,7 @@ func TestOpenAPIMatchesExample(t *testing.T) {
146
169
}
147
170
}
148
171
example := Example()
149
for _, want := range []string{"log_truncated", "commit_message", "source_branch", "refs/heads/master", "assets", "commented"} {
172
for _, want := range []string{"log_truncated", "commit_message", "source_branch", "refs/heads/master", "assets", "commented", "diff_url", "reviewers", "additions"} {
150
173
if !strings.Contains(example, want) && want != "commented" {
151
174
t.Errorf("voorbeeld mist %s", want)
152
175
}
@@ -70,17 +70,32 @@ func TestDocumentShapes(t *testing.T) {70
t.Fatalf("korte log heeft een url: %v", ok)70
t.Fatalf("korte log heeft een url: %v", ok)71
}71
}72
72
73
push := Event{Type: EventPush, Project: "tim/app", Ref: "refs/heads/master", Before: "a", After: "b"}73
push := Event{Type: EventPush, Project: "tim/app", Ref: "refs/heads/master", Before: "a", After: "b", Commits: []CommitInfo{{74
SHA: "abc", Message: "fix", Author: "tim <tim@example.com>", Timestamp: "2026-10-22T12:00:00Z",75
URL: "https://git.example/commit", DiffURL: "https://git.example/api/v1/repos/tim/app/commits/abc/diff",76
Files: []FileChange{{Path: "README.md", Status: "modified", Additions: 1, Deletions: 1}},77
}}}74
body, err = RenderBody("", push, nil)78
body, err = RenderBody("", push, nil)75
if err != nil {79
if err != nil {76
t.Fatal(err)80
t.Fatal(err)77
}81
}82
if strings.Contains(string(body), "diff --git") {83
t.Fatalf("push bevat een diff: %s", body)84
}78
if err := json.Unmarshal(body, &doc); err != nil {85
if err := json.Unmarshal(body, &doc); err != nil {79
t.Fatal(err)86
t.Fatal(err)80
}87
}81
if doc["object_kind"] != "push" || doc["before"] != "a" || doc["commits"] == nil {88
if doc["object_kind"] != "push" || doc["before"] != "a" || doc["commits"] == nil {82
t.Fatalf("push %s", body)89
t.Fatalf("push %s", body)83
}90
}91
commit := doc["commits"].([]any)[0].(map[string]any)92
file := commit["files"].([]any)[0].(map[string]any)93
if commit["timestamp"] != "2026-10-22T12:00:00Z" || commit["diff_url"] == "" || file["status"] != "modified" || file["additions"] != float64(1) || file["deletions"] != float64(1) {94
t.Fatalf("commit %s", body)95
}96
if _, has := commit["diff"]; has || file["path"] != "README.md" {97
t.Fatalf("commit lekt een diff: %s", body)98
}84
99
85
mr := Event{100
mr := Event{86
Type: EventMergeRequest, Project: "tim/app", Comment: "hoort niet mee",101
Type: EventMergeRequest, Project: "tim/app", Comment: "hoort niet mee",@@ -90,8 +105,15 @@ func TestDocumentShapes(t *testing.T) {90
if err != nil {105
if err != nil {91
t.Fatal(err)106
t.Fatal(err)92
}107
}93
if strings.Contains(string(body), "hoort niet mee") || !strings.Contains(string(body), `"action":"opened"`) {108
if strings.Contains(string(body), "hoort niet mee") || !strings.Contains(string(body), `"action":"opened"`) || strings.Contains(string(body), "diff --git") {94
t.Fatalf("opened lekt commentaar: %s", body)109
t.Fatalf("opened lekt commentaar of een diff: %s", body)110
}111
if err := json.Unmarshal(body, &doc); err != nil {112
t.Fatal(err)113
}114
openedMR := doc["merge_request"].(map[string]any)115
if openedMR["reviewers"] == nil || openedMR["comments"] == nil || openedMR["commits"] == nil || openedMR["diff_stats"] == nil || openedMR["diff_url"] == nil {116
t.Fatalf("mr mist details: %s", body)95
}117
}96
mr.MergeRequest.Action = "commented"118
mr.MergeRequest.Action = "commented"97
mr.Comment = "mooie opmerking"119
mr.Comment = "mooie opmerking"@@ -139,6 +161,7 @@ func TestOpenAPIMatchesExample(t *testing.T) {139
"PipelineEvent", "PushEvent", "MergeRequestEvent", "ReleaseEvent",161
"PipelineEvent", "PushEvent", "MergeRequestEvent", "ReleaseEvent",140
"commit_message", "allow_failure", "log_truncated", "log_url",162
"commit_message", "allow_failure", "log_truncated", "log_url",141
"/repos/{owner}/{repo}/jobs/{id}/log",163
"/repos/{owner}/{repo}/jobs/{id}/log",164
"diff_url", "reviewers", "diff_stats", "/commits/{sha}/diff", "/merge-requests/{id}/diff",142
"source_branch", "target_branch", "before", "after", "assets",165
"source_branch", "target_branch", "before", "after", "assets",143
} {166
} {144
if !strings.Contains(raw, want) {167
if !strings.Contains(raw, want) {@@ -146,7 +169,7 @@ func TestOpenAPIMatchesExample(t *testing.T) {146
}169
}147
}170
}148
example := Example()171
example := Example()149
for _, want := range []string{"log_truncated", "commit_message", "source_branch", "refs/heads/master", "assets", "commented"} {172
for _, want := range []string{"log_truncated", "commit_message", "source_branch", "refs/heads/master", "assets", "commented", "diff_url", "reviewers", "additions"} {150
if !strings.Contains(example, want) && want != "commented" {173
if !strings.Contains(example, want) && want != "commented" {151
t.Errorf("voorbeeld mist %s", want)174
t.Errorf("voorbeeld mist %s", want)152
}175
}