v0.7.0 45bfc5b

mergerequest.go RawHistoryFolder

1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package domain
4
5import (
6	"fmt"
7	"slices"
8	"strings"
9	"time"
10)
11
12// MergeMode is how a merge request is merged (ADR 0017).
13type MergeMode string
14
15// Merge modes.
16const (
17	// MergeModeFastForward moves the target to the head; no commit is made.
18	MergeModeFastForward MergeMode = "fast-forward"
19	// MergeModeSquash makes one new signed commit with the tree of the head.
20	MergeModeSquash MergeMode = "squash"
21)
22
23// MergeModes returns the two modes in their canonical order.
24func MergeModes() []MergeMode { return []MergeMode{MergeModeFastForward, MergeModeSquash} }
25
26// ParseMergeMode parses "fast-forward" or "squash".
27func ParseMergeMode(s string) (MergeMode, error) {
28	m := MergeMode(s)
29	if slices.Contains(MergeModes(), m) {
30		return m, nil
31	}
32	return "", fmt.Errorf("%w: merge mode %q (want fast-forward or squash)", ErrInvalid, s)
33}
34
35// String returns the mode as text.
36func (m MergeMode) String() string { return string(m) }
37
38// RepoSettings are the settings of a repository that govern its merge
39// requests.
40type RepoSettings struct {
41	// AllowedMergeModes is never empty, in canonical order, without
42	// duplicates.
43	AllowedMergeModes []MergeMode
44	// FailingChecksBlock says that a failing check prevents the merge.
45	FailingChecksBlock bool
46}
47
48// DefaultRepoSettings are the settings of a new repository: both modes, and
49// failing checks block the merge.
50func DefaultRepoSettings() RepoSettings {
51	return RepoSettings{AllowedMergeModes: MergeModes(), FailingChecksBlock: true}
52}
53
54// IsZero reports whether s holds no mode, which only the zero value does.
55func (s RepoSettings) IsZero() bool { return len(s.AllowedMergeModes) == 0 }
56
57// Allows reports whether the mode may be used.
58func (s RepoSettings) Allows(m MergeMode) bool { return slices.Contains(s.AllowedMergeModes, m) }
59
60// NormalizeMergeModes validates a list of modes for the settings: it must not
61// be empty or hold an unknown mode. The result is in canonical order, without
62// duplicates.
63func NormalizeMergeModes(modes []MergeMode) ([]MergeMode, error) {
64	if len(modes) == 0 {
65		return nil, fmt.Errorf("%w: at least one merge mode is required", ErrInvalid)
66	}
67	for _, m := range modes {
68		if _, err := ParseMergeMode(m.String()); err != nil {
69			return nil, err
70		}
71	}
72	var out []MergeMode
73	for _, m := range MergeModes() {
74		if slices.Contains(modes, m) {
75			out = append(out, m)
76		}
77	}
78	return out, nil
79}
80
81// MRState is where a merge request is in its life.
82type MRState string
83
84// Merge request states.
85const (
86	// MRStateOpen awaits review.
87	MRStateOpen MRState = "open"
88	// MRStateMerged is final: the branch was merged.
89	MRStateMerged MRState = "merged"
90	// MRStateClosed is final: the request was closed without merging.
91	MRStateClosed MRState = "closed"
92)
93
94// DiffSide is the side of a diff a comment is attached to.
95type DiffSide string
96
97// Diff sides. The empty side marks a general comment.
98const (
99	// SideNone is the side of a general comment.
100	SideNone DiffSide = ""
101	// SideOld counts lines of the old file.
102	SideOld DiffSide = "old"
103	// SideNew counts lines of the new file.
104	SideNew DiffSide = "new"
105)
106
107// MergeRequest asks to merge one branch into another of the same repository.
108type MergeRequest struct {
109	Repo   RepoName
110	Number int64
111	Title  MRTitle
112	// Description may be empty.
113	Description PlainText
114	// Source and Target are short branch names.
115	Source, Target string
116	State          MRState
117	// Author is the label of the token that opened it, "root" or "owner".
118	Author    string
119	CreatedAt time.Time
120	UpdatedAt time.Time
121	// HeadID is the head of the source branch: stored when the request is
122	// merged or closed, and filled from Git at every read while it is open
123	// (zero when the branch is gone).
124	HeadID ObjectID
125	// BaseID is the merge base of the target and the head when the request
126	// was merged or closed; zero while it is open.
127	BaseID ObjectID
128	// MergedCommitID is the tip of the target after the merge; zero unless
129	// merged.
130	MergedCommitID ObjectID
131	// MergeMode is the mode used; empty unless merged.
132	MergeMode MergeMode
133	// CommentSeq is the id of the last comment of the request.
134	CommentSeq int64
135	// Version is set by the store on read: Update fails with ErrConflict when
136	// the stored request changed since. Opaque to everyone else.
137	Version uint64
138}
139
140// IsOpen reports whether the request awaits review.
141func (m MergeRequest) IsOpen() bool { return m.State == MRStateOpen }
142
143// Comment is a note on a merge request, general or on a line of its diff.
144type Comment struct {
145	// ID is unique within the merge request, in order of creation.
146	ID     int64
147	Author string
148	// Path, Line and Side are empty for a general comment.
149	Path string
150	Line int
151	Side DiffSide
152	// CommitID is the head of the request when the comment was written; zero
153	// when the source branch was gone.
154	CommitID  ObjectID
155	Text      PlainText
156	Resolved  bool
157	CreatedAt time.Time
158	// Version is set by the store on read, like MergeRequest.Version.
159	Version uint64
160}
161
162// IsGeneral reports whether the comment is not attached to a line.
163func (c Comment) IsGeneral() bool { return c.Path == "" }
164
165// HasLine reports whether the diff has a line numbered line on side in the
166// file path: the new path of a file, or the old path of a deleted one. The new
167// side holds the context and addition lines, the old side the context and
168// deletion lines. A file the diff truncated has no lines.
169func (d Diff) HasLine(path string, side DiffSide, line int) bool {
170	if path == "" || line < 1 {
171		return false
172	}
173	for _, f := range d.Files {
174		name := f.NewPath
175		if f.Status == FileDeleted {
176			name = f.OldPath
177		}
178		if name != path {
179			continue
180		}
181		for _, h := range f.Hunks {
182			for _, l := range h.Lines {
183				switch {
184				case side == SideNew && l.Kind != LineDeletion && l.NewNumber == line:
185					return true
186				case side == SideOld && l.Kind != LineAddition && l.OldNumber == line:
187					return true
188				}
189			}
190		}
191	}
192	return false
193}
194
195// Identity is a name and an email address, such as the committer of the
196// commits ermite creates.
197type Identity struct {
198	Name, Email string
199}
200
201// SquashCommit is the commit a squash merge creates: the tree of the head on
202// top of the target.
203type SquashCommit struct {
204	Tree, Parent      ObjectID
205	Author, Committer Signature
206	Message           string
207}
208
209// MaxSquashCommits bounds the commits a squash lists in its message.
210const MaxSquashCommits = 1000
211
212// NewSquashCommit builds the squash commit of a merge request (ADR 0022).
213// commits are the commits of the branch that the target lacks, newest first,
214// as Git lists them, and not empty. The author is the author of the oldest
215// one, with its date; the other distinct authors become Co-authored-by
216// trailers, in order of appearance. The message is the title, " (!<number>)",
217// a blank line, the summaries of the commits oldest first as a list, and the
218// trailers.
219func NewSquashCommit(mr MergeRequest, tree, parent ObjectID, commits []Commit, committer Identity, at time.Time) SquashCommit {
220	oldest := slices.Clone(commits)
221	slices.Reverse(oldest)
222	var first Signature
223	if len(oldest) > 0 {
224		first = oldest[0].Author
225	}
226
227	var msg strings.Builder
228	fmt.Fprintf(&msg, "%s (!%d)\n", mr.Title.String(), mr.Number)
229	if len(oldest) > 0 {
230		msg.WriteString("\n")
231	}
232	var trailers []string
233	seen := map[string]bool{strings.ToLower(first.Email): true}
234	for _, c := range oldest {
235		msg.WriteString("- " + singleLine(c.Summary) + "\n")
236		key := strings.ToLower(c.Author.Email)
237		if !seen[key] {
238			seen[key] = true
239			trailers = append(trailers, "Co-authored-by: "+identLine(c.Author.Name, c.Author.Email))
240		}
241	}
242	if len(trailers) > 0 {
243		msg.WriteString("\n" + strings.Join(trailers, "\n") + "\n")
244	}
245	return SquashCommit{
246		Tree: tree, Parent: parent,
247		Author:    first,
248		Committer: Signature{Name: committer.Name, Email: committer.Email, Time: at.UTC()},
249		Message:   msg.String(),
250	}
251}
252
253// Payload returns the text of the commit object without a signature, which is
254// what the signature covers.
255func (c SquashCommit) Payload() []byte { return c.encode("") }
256
257// Signed returns the text of the commit object with the armored SSH signature
258// in its gpgsig header.
259func (c SquashCommit) Signed(armored string) []byte { return c.encode(armored) }
260
261func (c SquashCommit) encode(armored string) []byte {
262	var b strings.Builder
263	b.WriteString("tree " + c.Tree.String() + "\n")
264	b.WriteString("parent " + c.Parent.String() + "\n")
265	b.WriteString("author " + signatureLine(c.Author) + "\n")
266	b.WriteString("committer " + signatureLine(c.Committer) + "\n")
267	if armored != "" {
268		lines := strings.Split(strings.TrimRight(armored, "\n"), "\n")
269		b.WriteString("gpgsig " + lines[0] + "\n")
270		for _, l := range lines[1:] {
271			b.WriteString(" " + l + "\n")
272		}
273	}
274	b.WriteString("\n")
275	b.WriteString(c.Message)
276	return []byte(b.String())
277}
278
279func signatureLine(s Signature) string {
280	return fmt.Sprintf("%s %d +0000", identLine(s.Name, s.Email), s.Time.Unix())
281}
282
283// identLine formats "Name <email>", dropping the characters Git does not
284// allow in an identity.
285func identLine(name, email string) string {
286	clean := func(s string) string {
287		return strings.TrimSpace(strings.Map(func(r rune) rune {
288			if r == '<' || r == '>' || r < 0x20 || r == 0x7f {
289				return -1
290			}
291			return r
292		}, s))
293	}
294	return clean(name) + " <" + clean(email) + ">"
295}
296
297// singleLine replaces the control characters of a commit summary, so that it
298// stays one line of the message.
299func singleLine(s string) string {
300	return strings.Map(func(r rune) rune {
301		if r < 0x20 || r == 0x7f {
302			return ' '
303		}
304		return r
305	}, s)
306}

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