detached 5f5b000

repo.go RawHistoryFolder

1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package web
4
5import (
6	"context"
7	"slices"
8	"sort"
9	"strings"
10	"sync"
11	"time"
12
13	"bnema.dev/ermite/internal/domain"
14	"bnema.dev/ermite/internal/ports"
15)
16
17// maxRefs bounds the refs one page reads. A repository with more has its
18// lists cut, and the pages say so.
19const maxRefs = 1000
20
21// repoData is what the pages of one repository start from: its metadata and
22// its refs, read once per request.
23type repoData struct {
24	repo     ports.RepoView
25	branches []domain.Ref
26	tags     []domain.Ref
27	// cut is true when the repository has more refs than maxRefs.
28	cut bool
29	// head is the branch the repository opens on: its default branch, or the
30	// first one when the default does not exist. nil for an empty repository.
31	head *domain.Ref
32}
33
34// repoView reads a repository as the caller of the request may see it, with
35// the Git state of its summary. A missing or private repository is
36// domain.ErrNotFound.
37func (s *Server) repoView(ctx context.Context, name domain.RepoName) (ports.RepoView, error) {
38	repo, err := s.repoRecord(ctx, name)
39	if err != nil {
40		return ports.RepoView{}, err
41	}
42	return s.cfg.Repos.View(ctx, repo)
43}
44
45// repoRecord reads the repository record only, without Git: its name,
46// visibility and settings (the defaults when it has none).
47func (s *Server) repoRecord(ctx context.Context, name domain.RepoName) (domain.Repo, error) {
48	repo, err := s.cfg.Repos.Get(ctx, principal(ctx), name)
49	if err != nil {
50		return domain.Repo{}, err
51	}
52	repo.Settings = repo.EffectiveSettings()
53	return repo, nil
54}
55
56// loadRepo reads a repository and its refs. A missing, private or invalidly
57// named repository is a domain.ErrNotFound / invalid name error, which the
58// caller turns into the 404 page.
59func (s *Server) loadRepo(ctx context.Context, rawName string) (*repoData, error) {
60	name, err := domain.ParseRepoName(rawName)
61	if err != nil {
62		return nil, err
63	}
64	view, err := s.repoView(ctx, name)
65	if err != nil {
66		return nil, err
67	}
68	d := &repoData{repo: view}
69	// Each page of ListRefs runs the whole for-each-ref again: the refs are
70	// asked in one page of up to maxRefs (the use case lowers it to its cap,
71	// and the token then leads to the rest).
72	token, n := "", 0
73	for {
74		page, err := s.cfg.Browse.ListRefs(ctx, principal(ctx), name, ports.ListRefsParams{
75			Kinds:    []domain.RefKind{domain.RefKindBranch, domain.RefKindTag},
76			PageSize: maxRefs, PageToken: token,
77		})
78		if err != nil {
79			return nil, err
80		}
81		for _, r := range page.Refs {
82			switch r.Kind {
83			case domain.RefKindBranch:
84				d.branches = append(d.branches, r)
85			case domain.RefKindTag:
86				d.tags = append(d.tags, r)
87			}
88			n++
89		}
90		if token = page.NextPageToken; token == "" {
91			break
92		}
93		if n >= maxRefs {
94			d.cut = true
95			break
96		}
97	}
98	for i := range d.branches {
99		if d.branches[i].ShortName == d.repo.DefaultBranch {
100			d.head = &d.branches[i]
101		}
102	}
103	if d.head == nil && len(d.branches) > 0 {
104		d.head = &d.branches[0]
105	}
106	return d, nil
107}
108
109// allRefs is the branches then the tags.
110func (d *repoData) allRefs() []domain.Ref {
111	return append(append([]domain.Ref(nil), d.branches...), d.tags...)
112}
113
114// name is the repository name.
115func (d *repoData) name() string { return d.repo.Name.String() }
116
117// openMRCount is the number of open merge requests shown on the tab, empty
118// when there are none or they cannot be counted (the tab still works).
119func (s *Server) openMRCount(ctx context.Context, name domain.RepoName) string {
120	n, err := s.cfg.MergeRequests.CountOpen(ctx, principal(ctx), name)
121	if err != nil || n == 0 {
122		return ""
123	}
124	return itoa(n)
125}
126
127// layout is the Layout of the pages of a repository: the sections, the ref
128// switcher on the head ref and the ":" targets. The caller sets the title,
129// the crumbs, the status and the rail.
130//
131//hexcheck:ignore suspicious-business-logic-in-adapter renders repository navigation; the issues tab uses the domain IssuesEnabled predicate
132func (s *Server) repoLayout(ctx context.Context, d *repoData, section string) Layout {
133	l := s.base()
134	l.Repo = d.name()
135	def := d.repo.DefaultBranch
136	if d.head != nil {
137		def = d.head.ShortName
138		l.Ref, l.RefPath = def, def
139		l.SHA, l.Short = d.head.CommitID.String(), short(d.head.CommitID.String())
140		l.setFinder(l.SHA, def)
141	}
142	mk := func(key, label, href, id string) Section {
143		return Section{Key: key, Label: label, Href: href, Current: section == id}
144	}
145	l.Sections = []Section{
146		mk("s", "Summary", repoHref(d.name()), "summary"),
147		mk("t", "Files", repoHref(d.name(), "tree", def), "tree"),
148		mk("c", "Commits", repoHref(d.name(), "commits", def), "commits"),
149		mk("r", "Branches & tags", repoHref(d.name(), "refs"), "refs"),
150	}
151	if s.cfg.MergeRequests != nil {
152		mrs := mk("m", "Merge requests", mrBase(d.name()), "merge-requests")
153		mrs.Count = s.openMRCount(ctx, d.repo.Name)
154		l.Sections = append(l.Sections, mrs)
155	}
156	if s.cfg.Issues != nil && d.repo.EffectiveSettings().IssuesEnabled() {
157		l.Sections = append(l.Sections, mk("i", "Issues", issuesBase(d.name()), "issues"))
158	}
159	l.Sections = s.withActions(l.Sections, d.name(), section)
160	l.Crumbs = []Crumb{{Label: d.name(), Href: repoHref(d.name()), Current: section == "summary"}}
161
162	l.Cmd = append(l.Cmd, CmdItem{Kind: "go", Label: "home", Href: "/"})
163	for _, sec := range l.Sections {
164		l.Cmd = append(l.Cmd, CmdItem{Kind: "section", Label: strings.ToLower(sec.Label), Href: sec.Href})
165	}
166	if l.Ref != "" {
167		for _, b := range d.branches {
168			it := RefItem{Name: b.ShortName, Href: repoHref(d.name(), "tree", b.ShortName), Current: b.ShortName == d.head.ShortName}
169			l.Heads = append(l.Heads, it)
170			l.Cmd = append(l.Cmd, CmdItem{Kind: "branch", Label: it.Name, Href: it.Href})
171		}
172		for _, t := range d.tags {
173			it := RefItem{Name: t.ShortName, Href: repoHref(d.name(), "tree", t.ShortName)}
174			l.Tags = append(l.Tags, it)
175			l.Cmd = append(l.Cmd, CmdItem{Kind: "tag", Label: it.Name, Href: it.Href})
176		}
177	}
178	// Other repositories, when the list is reachable; the page does not
179	// depend on it.
180	if repos, err := s.listRepos(ctx); err == nil {
181		l.Cmd = append(l.Cmd, repoCmds(repos, d.name())...)
182	}
183	return l
184}
185
186// withActions adds the Actions tab when the server runs CI.
187func (s *Server) withActions(sections []Section, repo, current string) []Section {
188	if s.cfg.Runs == nil {
189		return sections
190	}
191	return append(sections, Section{Key: "a", Label: "Actions", Href: actionsBase(repo), Current: current == "actions"})
192}
193
194// cloneURL is the HTTPS clone URL of a repository.
195func (s *Server) cloneURL(name string) string {
196	return s.cfg.PublicURL + "/" + name + ".git"
197}
198
199// refCommit is what a ref shows: the commit it designates.
200type refCommit struct {
201	short, subject, when, whenAt string
202	at                           int64 // unix time, to sort tags
203}
204
205// commitsOf reads the head commit of each ref, a few at a time. A ref whose
206// commit cannot be read (a tag on a tree, say) has no entry.
207func (s *Server) commitsOf(ctx context.Context, repo domain.RepoName, refs []domain.Ref) map[string]refCommit {
208	const workers = 8
209	var (
210		mu  sync.Mutex
211		out = make(map[string]refCommit, len(refs))
212		sem = make(chan struct{}, workers)
213		wg  sync.WaitGroup
214	)
215	now := s.cfg.Now()
216	for _, r := range refs {
217		if r.CommitID.IsZero() {
218			continue
219		}
220		id := r.CommitID.String()
221		mu.Lock()
222		_, done := out[id]
223		if !done {
224			out[id] = refCommit{} // reserved: one lookup per commit
225		}
226		mu.Unlock()
227		if done {
228			continue
229		}
230		sem <- struct{}{}
231		wg.Add(1)
232		go func() {
233			defer func() { <-sem; wg.Done() }()
234			// By id, not by name: a branch and a tag may share a name.
235			res, err := s.commitList(ctx, repo, id, "", 1, "")
236			var rc refCommit
237			if err == nil && len(res.Commits) == 1 {
238				row := commitRow(repo.String(), res.Commits[0], now)
239				rc.short, rc.subject, rc.when, rc.whenAt = row.Short, row.Subject, row.When, row.WhenAt
240				rc.at = unixSeconds(res.Commits[0].Committer.Time)
241			}
242			mu.Lock()
243			out[id] = rc
244			mu.Unlock()
245		}()
246	}
247	wg.Wait()
248	return out
249}
250
251// whenOf is the relative and the machine form of a time; both are "" when
252// the time is unknown (the zero time).
253func whenOf(now time.Time, t time.Time) (when, at string) {
254	if t.IsZero() {
255		return "", ""
256	}
257	return ago(now, t), rfc3339(t)
258}
259
260// unixSeconds is the Unix time of t in seconds, 0 for the zero time.
261func unixSeconds(t time.Time) int64 {
262	if t.IsZero() {
263		return 0
264	}
265	return t.Unix()
266}
267
268// commitRow is the row every list of commits starts from: the short id, the
269// subject, the author and the date of the committer, all fit to display. The
270// caller adds what is specific to its list.
271func commitRow(repo string, c domain.Commit, now time.Time) CommitRow {
272	row := CommitRow{
273		Short: short(c.ID.String()), Subject: visibleText(c.Summary),
274		CHref:  repoHref(repo, "commit", c.ID.String()),
275		Author: visibleText(c.Author.Name), Merge: len(c.Parents) > 1,
276		Sig: signatureBadge(c.Verification, false),
277	}
278	row.When, row.WhenAt = whenOf(now, c.Committer.Time)
279	return row
280}
281
282// namesAt maps commit ids to the names of the refs that designate them.
283func namesAt(refs []domain.Ref) map[string][]string {
284	m := map[string][]string{}
285	for _, r := range refs {
286		m[r.CommitID.String()] = append(m[r.CommitID.String()], r.ShortName)
287	}
288	for _, v := range m {
289		sort.Strings(v)
290	}
291	return m
292}
293
294// emptyState is the page of a repository without a branch.
295func (s *Server) emptyState(ctx context.Context, d *repoData) (Layout, StatePage) {
296	l := s.repoLayout(ctx, d, "summary")
297	l.Title = d.name() + " · " + s.instance
298	l.Sections = nil
299	l.Cmd = slices.DeleteFunc(l.Cmd, func(c CmdItem) bool { return c.Kind == "section" })
300	branch := d.repo.DefaultBranch
301	return l, StatePage{
302		Code: "empty", Title: d.name() + " is empty",
303		Lines: []string{"no commits yet. push a branch to create one."},
304		Clone: &Clone{ID: "clone-" + d.name(), Lines: []string{
305			"git remote add origin " + s.cloneURL(d.name()),
306			"git push -u origin " + branch,
307		}},
308		Back: []Link{{Label: "home", Href: "/"}},
309	}
310}

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 4

Tags 45

↑↓ moveenter openesc close