detached fda3c2b

mergerequest_test.go RawHistoryFolder

1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package domain_test
4
5import (
6	"strconv"
7	"strings"
8	"testing"
9	"time"
10
11	"github.com/stretchr/testify/assert"
12	"github.com/stretchr/testify/require"
13
14	"bnema.dev/ermite/internal/domain"
15)
16
17func oid(t *testing.T, c byte) domain.ObjectID {
18	t.Helper()
19	id, err := domain.ParseObjectID(strings.Repeat(string(c), domain.ObjectIDLen))
20	require.NoError(t, err)
21	return id
22}
23
24func TestDefaultRepoSettings(t *testing.T) {
25	t.Parallel()
26	s := domain.DefaultRepoSettings()
27	assert.Equal(t, []domain.MergeMode{domain.MergeModeFastForward, domain.MergeModeSquash, domain.MergeModeMerge}, s.AllowedMergeModes)
28	assert.True(t, s.Allows(domain.MergeModeSquash))
29	assert.False(t, domain.RepoSettings{}.Allows(domain.MergeModeSquash))
30	assert.True(t, domain.RepoSettings{}.IsZero())
31	assert.False(t, s.IsZero())
32
33	// The default list is a copy: callers cannot alter the next default.
34	s.AllowedMergeModes[0] = domain.MergeModeSquash
35	assert.Equal(t, domain.MergeModeFastForward, domain.DefaultRepoSettings().AllowedMergeModes[0])
36}
37
38func TestNormalizeMergeModes(t *testing.T) {
39	t.Parallel()
40	got, err := domain.NormalizeMergeModes([]domain.MergeMode{domain.MergeModeSquash, domain.MergeModeFastForward, domain.MergeModeSquash})
41	require.NoError(t, err)
42	assert.Equal(t, []domain.MergeMode{domain.MergeModeFastForward, domain.MergeModeSquash}, got)
43
44	got, err = domain.NormalizeMergeModes([]domain.MergeMode{domain.MergeModeSquash})
45	require.NoError(t, err)
46	assert.Equal(t, []domain.MergeMode{domain.MergeModeSquash}, got)
47
48	_, err = domain.NormalizeMergeModes(nil)
49	assert.ErrorIs(t, err, domain.ErrInvalid)
50	_, err = domain.NormalizeMergeModes([]domain.MergeMode{"rebase"})
51	assert.ErrorIs(t, err, domain.ErrInvalid)
52}
53
54func TestParseMergeMode(t *testing.T) {
55	t.Parallel()
56	m, err := domain.ParseMergeMode("fast-forward")
57	require.NoError(t, err)
58	assert.Equal(t, domain.MergeModeFastForward, m)
59	m, err = domain.ParseMergeMode("merge")
60	require.NoError(t, err)
61	assert.Equal(t, domain.MergeModeMerge, m)
62	_, err = domain.ParseMergeMode("rebase")
63	assert.ErrorIs(t, err, domain.ErrInvalid)
64}
65
66func hunkDiff() domain.Diff {
67	return domain.Diff{Files: []domain.FileDiff{
68		{OldPath: "a.txt", NewPath: "a.txt", Status: domain.FileModified, Hunks: []domain.Hunk{{
69			Lines: []domain.Line{
70				{Kind: domain.LineContext, OldNumber: 4, NewNumber: 4},
71				{Kind: domain.LineDeletion, OldNumber: 5},
72				{Kind: domain.LineAddition, NewNumber: 5},
73				{Kind: domain.LineAddition, NewNumber: 6},
74			},
75		}}},
76		{OldPath: "gone.txt", Status: domain.FileDeleted, Hunks: []domain.Hunk{{
77			Lines: []domain.Line{{Kind: domain.LineDeletion, OldNumber: 1}},
78		}}},
79		{NewPath: "big.txt", Status: domain.FileAdded, Omitted: domain.OmitLarge},
80		{OldPath: "old.txt", NewPath: "new.txt", Status: domain.FileRenamed, Hunks: []domain.Hunk{{
81			Lines: []domain.Line{{Kind: domain.LineAddition, NewNumber: 2}},
82		}}},
83	}}
84}
85
86func TestDiffHasLine(t *testing.T) {
87	t.Parallel()
88	d := hunkDiff()
89	tests := []struct {
90		name string
91		path string
92		side domain.DiffSide
93		line int
94		want bool
95	}{
96		{"context on the new side", "a.txt", domain.SideNew, 4, true},
97		{"context on the old side", "a.txt", domain.SideOld, 4, true},
98		{"deletion on the old side", "a.txt", domain.SideOld, 5, true},
99		{"addition on the new side", "a.txt", domain.SideNew, 6, true},
100		{"addition is not on the old side", "a.txt", domain.SideOld, 6, false},
101		{"new line 5 is the addition, not the deletion", "a.txt", domain.SideNew, 5, true},
102		{"line outside the hunk", "a.txt", domain.SideNew, 99, false},
103		{"line zero", "a.txt", domain.SideNew, 0, false},
104		{"negative line", "a.txt", domain.SideNew, -1, false},
105		{"no side", "a.txt", domain.SideNone, 4, false},
106		{"unknown path", "nope.txt", domain.SideNew, 4, false},
107		{"empty path", "", domain.SideNew, 4, false},
108		{"deleted file by its old path", "gone.txt", domain.SideOld, 1, true},
109		{"deleted file has no new side", "gone.txt", domain.SideNew, 1, false},
110		{"truncated file has no lines", "big.txt", domain.SideNew, 1, false},
111		{"renamed file by its new path", "new.txt", domain.SideNew, 2, true},
112		{"renamed file by its old path", "old.txt", domain.SideNew, 2, false},
113	}
114	for _, tc := range tests {
115		t.Run(tc.name, func(t *testing.T) {
116			t.Parallel()
117			assert.Equal(t, tc.want, d.HasLine(tc.path, tc.side, tc.line))
118		})
119	}
120}
121
122func sig(name, email string, sec int64) domain.Signature {
123	return domain.Signature{Name: name, Email: email, Time: time.Unix(sec, 0).UTC()}
124}
125
126func TestNewSquashCommit(t *testing.T) {
127	t.Parallel()
128	title, err := domain.ParseMRTitle("Add search")
129	require.NoError(t, err)
130	mr := domain.MergeRequest{Number: 7, Title: title}
131	// Newest first, as Git lists them.
132	commits := []domain.Commit{
133		{Summary: "fix typo", Author: sig("Bob", "bob@example.org", 300)},
134		{Summary: "add tests", Author: sig("Ada", "ADA@example.org", 200)},
135		{Summary: "add search", Author: sig("Ada", "ada@example.org", 100)},
136		{Summary: "wip", Author: sig("Cy", "cy@example.org", 150)},
137		{Summary: "polish", Author: sig("Bob", "bob@example.org", 160)},
138	}
139	committer := domain.Identity{Name: "ermite", Email: "ermite@git.example.org"}
140	at := time.Unix(1_800_000_000, 0)
141
142	c := domain.NewSquashCommit(mr, oid(t, 'a'), oid(t, 'b'), commits, committer, at)
143
144	// The author is the author of the oldest commit (the last one listed).
145	assert.Equal(t, sig("Bob", "bob@example.org", 160), c.Author)
146	assert.Equal(t, domain.Signature{Name: "ermite", Email: "ermite@git.example.org", Time: at.UTC()}, c.Committer)
147	assert.Equal(t, "Add search (!7)\n"+
148		"\n"+
149		"- polish\n- wip\n- add search\n- add tests\n- fix typo\n"+
150		"\n"+
151		"Co-authored-by: Cy <cy@example.org>\n"+
152		"Co-authored-by: Ada <ada@example.org>\n", c.Message)
153
154	want := "tree " + strings.Repeat("a", 40) + "\n" +
155		"parent " + strings.Repeat("b", 40) + "\n" +
156		"author Bob <bob@example.org> 160 +0000\n" +
157		"committer ermite <ermite@git.example.org> 1800000000 +0000\n" +
158		"\n" + c.Message
159	assert.Equal(t, want, string(c.Payload()))
160}
161
162func TestSquashCommitSigned(t *testing.T) {
163	t.Parallel()
164	title, err := domain.ParseMRTitle("T")
165	require.NoError(t, err)
166	c := domain.NewSquashCommit(domain.MergeRequest{Number: 1, Title: title}, oid(t, 'a'), oid(t, 'b'),
167		[]domain.Commit{{Summary: "s", Author: sig("A", "a@x.org", 1)}}, domain.Identity{Name: "e", Email: "e@x.org"}, time.Unix(2, 0))
168
169	got := string(c.Signed("-----BEGIN SSH SIGNATURE-----\nAAAA\nBBBB\n-----END SSH SIGNATURE-----\n"))
170	assert.Equal(t, "tree "+strings.Repeat("a", 40)+"\n"+
171		"parent "+strings.Repeat("b", 40)+"\n"+
172		"author A <a@x.org> 1 +0000\n"+
173		"committer e <e@x.org> 2 +0000\n"+
174		"gpgsig -----BEGIN SSH SIGNATURE-----\n"+
175		" AAAA\n"+
176		" BBBB\n"+
177		" -----END SSH SIGNATURE-----\n"+
178		"\n"+c.Message, got)
179}
180
181func TestSquashCommitCleansIdentitiesAndSummaries(t *testing.T) {
182	t.Parallel()
183	title, err := domain.ParseMRTitle("T")
184	require.NoError(t, err)
185	commits := []domain.Commit{
186		{Summary: "second", Author: sig("Eve <evil@x.org>\nCo-authored-by: Z", "eve@x.org", 2)},
187		{Summary: "first\x1b[0m", Author: sig("Ada", "ada@x.org", 1)},
188	}
189	c := domain.NewSquashCommit(domain.MergeRequest{Number: 2, Title: title}, oid(t, 'a'), oid(t, 'b'), commits,
190		domain.Identity{Name: "e", Email: "e@x.org"}, time.Unix(3, 0))
191	assert.Contains(t, c.Message, "- first [0m\n")
192	assert.Contains(t, c.Message, "\nCo-authored-by: Eve evil@x.orgCo-authored-by: Z <eve@x.org>\n")
193	assert.NotContains(t, c.Message, "\nCo-authored-by: Z")
194}
195
196func TestSigningKeyInfoAllowedSigners(t *testing.T) {
197	t.Parallel()
198	i := domain.SigningKeyInfo{
199		Key:       domain.SigningPublicKey{AuthorizedKey: "ssh-ed25519 AAAA"},
200		Committer: domain.Identity{Name: "ermite", Email: "ermite@git.example.org"},
201	}
202	assert.Equal(t, "ermite@git.example.org ssh-ed25519 AAAA", i.AllowedSigners())
203}
204
205func TestParseBranchName(t *testing.T) {
206	t.Parallel()
207	for _, ok := range []string{"main", "feat/x", "v1.2", "a-b_c"} {
208		got, err := domain.ParseBranchName(ok)
209		require.NoError(t, err, ok)
210		assert.Equal(t, ok, got)
211	}
212	for _, bad := range []string{"", "refs/heads/main", "-x", "a..b", "a b", "x/", "a:b", "x.lock", "a\x00b"} {
213		_, err := domain.ParseBranchName(bad)
214		assert.ErrorIs(t, err, domain.ErrInvalidRevision, "%q", bad)
215	}
216}
217
218// A title that starts with "WIP:" or "[WIP]", in any case, is a draft; ready
219// drops the prefix and the spaces after it.
220func TestMergeRequestDraft(t *testing.T) {
221	for _, tc := range []struct {
222		title, ready string
223		draft        bool
224	}{
225		{"WIP: feat: drag and drop", "feat: drag and drop", true},
226		{"wip:fix", "fix", true},
227		{"  [WIP]  tidy", "tidy", true},
228		{"WIP: [wip] both", "both", true}, // every prefix goes
229		{"feat: wip: later", "", false},
230		{"WIPE the cache", "", false},
231		{"WIP:", "", true}, // a draft, but nothing would be left
232	} {
233		title, err := domain.ParseMRTitle(tc.title)
234		require.NoError(t, err)
235		assert.Equal(t, tc.draft, domain.MergeRequest{Title: title}.IsDraft(), tc.title)
236		ready, ok := domain.ReadyTitle(title)
237		assert.Equal(t, tc.ready != "", ok, tc.title)
238		assert.Equal(t, tc.ready, ready.String(), tc.title)
239	}
240}
241
242func TestNoteVerdicts(t *testing.T) {
243	head, old := oid(t, 'a'), oid(t, 'b')
244	for _, tc := range []struct {
245		text    string
246		verdict domain.Verdict
247	}{{"", domain.VerdictNone}, {"approve", domain.VerdictApprove}, {"changes_requested", domain.VerdictChangesRequested}} {
248		v, err := domain.ParseVerdict(tc.text)
249		require.NoError(t, err)
250		assert.Equal(t, tc.verdict, v)
251		assert.Equal(t, tc.text, v.String())
252	}
253	_, err := domain.ParseVerdict("unknown")
254	require.ErrorIs(t, err, domain.ErrInvalid)
255	comments := []domain.Comment{{ID: 3, Author: "a", Verdict: domain.VerdictApprove, CommitID: old, Deleted: true}, {ID: 1, Author: "a", Verdict: domain.VerdictChangesRequested}, {ID: 2, Author: "b", Verdict: domain.VerdictChangesRequested, CommitID: old}, {ID: 4, Author: "a"}}
256	for _, h := range []domain.ObjectID{head, {}} {
257		got := domain.CurrentVerdicts(comments, h)
258		require.Len(t, got, 2)
259		assert.Equal(t, int64(2), got[0].CommentID)
260		assert.False(t, got[0].Stale)
261		assert.Equal(t, int64(3), got[1].CommentID)
262		assert.True(t, got[1].Stale)
263	}
264	comments[0].CommitID = head
265	assert.False(t, domain.CurrentVerdicts(comments, head)[1].Stale)
266	assert.True(t, (domain.Comment{ReplyTo: 1}).IsReply())
267	assert.True(t, (domain.Comment{StartLine: 1}).IsRange())
268}
269
270func TestReviewScopeOwnerRights(t *testing.T) {
271	var old []domain.Scope
272	for _, s := range domain.AllScopes() {
273		if s != domain.ScopeMRReview {
274			old = append(old, s)
275		}
276	}
277	assert.False(t, domain.TokenPrincipal(domain.Token{Scopes: old}).HasOwnerRights())
278	assert.True(t, domain.TokenPrincipal(domain.Token{Scopes: domain.AllScopes()}).HasOwnerRights())
279	s, err := domain.ParseScope("mr:review")
280	require.NoError(t, err)
281	assert.Equal(t, domain.ScopeMRReview, s)
282	for _, tc := range []struct {
283		p    domain.Principal
284		want string
285	}{{domain.Root(), "root"}, {domain.Owner(), "owner"}, {domain.Anonymous(), "owner"}, {domain.TokenPrincipal(domain.Token{Label: "bot"}), "bot"}} {
286		assert.Equal(t, tc.want, domain.AuthorName(tc.p))
287	}
288}
289
290func TestNewMergeCommit(t *testing.T) {
291	t.Parallel()
292	title, err := domain.ParseMRTitle("Add things")
293	require.NoError(t, err)
294	mr := domain.MergeRequest{Number: 7, Title: title, Source: "feat/x", Target: "main"}
295	at := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
296	c := domain.NewMergeCommit(mr, oid(t, 'a'), oid(t, 'b'), oid(t, 'c'), domain.Identity{Name: "ermite", Email: "e@x"}, at)
297	assert.Equal(t, []domain.ObjectID{oid(t, 'b'), oid(t, 'c')}, c.Parents)
298	assert.Equal(t, c.Author, c.Committer)
299	want := "tree " + strings.Repeat("a", 40) + "\nparent " + strings.Repeat("b", 40) + "\nparent " + strings.Repeat("c", 40) + "\n" +
300		"author ermite <e@x> " + strconv.FormatInt(at.Unix(), 10) + " +0000\ncommitter ermite <e@x> " + strconv.FormatInt(at.Unix(), 10) + " +0000\n\n" +
301		"Merge branch 'feat/x' into main (!7)\n\nAdd things\n"
302	assert.Equal(t, want, string(c.Payload()))
303	assert.Contains(t, string(c.Signed("-----BEGIN-----\nabc\n-----END-----\n")), "gpgsig -----BEGIN-----\n abc\n -----END-----\n")
304}
305
306func TestMergeabilityAllowsAndIsFor(t *testing.T) {
307	t.Parallel()
308	for _, tc := range []struct {
309		state          domain.MergeabilityState
310		ff, squash, mg bool
311	}{
312		{domain.MergeabilityUpToDate, true, true, true},
313		{domain.MergeabilityBehind, false, true, true},
314		{domain.MergeabilityConflict, false, false, false},
315		{domain.MergeabilityChecking, false, false, false},
316	} {
317		m := domain.Mergeability{State: tc.state}
318		ok, reason := m.Allows(domain.MergeModeFastForward)
319		assert.Equal(t, tc.ff, ok, tc.state)
320		assert.Equal(t, !ok, reason != "")
321		ok, _ = m.Allows(domain.MergeModeSquash)
322		assert.Equal(t, tc.squash, ok, tc.state)
323		ok, _ = m.Allows(domain.MergeModeMerge)
324		assert.Equal(t, tc.mg, ok, tc.state)
325	}
326	m := domain.Mergeability{State: domain.MergeabilityBehind, TargetID: oid(t, 'a'), HeadID: oid(t, 'b')}
327	assert.True(t, m.IsFor(oid(t, 'a'), oid(t, 'b')))
328	assert.False(t, m.IsFor(oid(t, 'c'), oid(t, 'b')))
329	assert.False(t, m.IsFor(oid(t, 'a'), oid(t, 'c')))
330	assert.False(t, domain.Mergeability{}.IsFor(domain.ObjectID{}, domain.ObjectID{}))
331}
332
333func TestRepoSettingsAllowAutoMergeDefaultOff(t *testing.T) {
334	t.Parallel()
335	assert.False(t, domain.DefaultRepoSettings().AllowAutoMerge)
336	assert.False(t, domain.RepoSettings{}.AllowAutoMerge)
337}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 2

Tags 45

↑↓ moveenter openesc close