detached fda3c2b

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	if s.cfg.Releases != nil {
160		l.Sections = append(l.Sections, mk("l", "Releases", releasesBase(d.name()), "releases"))
161	}
162	l.Sections = s.withActions(l.Sections, d.name(), section)
163	l.Crumbs = []Crumb{{Label: d.name(), Href: repoHref(d.name()), Current: section == "summary"}}
164
165	l.Cmd = append(l.Cmd, CmdItem{Kind: "go", Label: "home", Href: "/"})
166	for _, sec := range l.Sections {
167		l.Cmd = append(l.Cmd, CmdItem{Kind: "section", Label: strings.ToLower(sec.Label), Href: sec.Href})
168	}
169	if l.Ref != "" {
170		for _, b := range d.branches {
171			it := RefItem{Name: b.ShortName, Href: repoHref(d.name(), "tree", b.ShortName), Current: b.ShortName == d.head.ShortName}
172			l.Heads = append(l.Heads, it)
173			l.Cmd = append(l.Cmd, CmdItem{Kind: "branch", Label: it.Name, Href: it.Href})
174		}
175		for _, t := range d.tags {
176			it := RefItem{Name: t.ShortName, Href: repoHref(d.name(), "tree", t.ShortName)}
177			l.Tags = append(l.Tags, it)
178			l.Cmd = append(l.Cmd, CmdItem{Kind: "tag", Label: it.Name, Href: it.Href})
179		}
180	}
181	// Other repositories, when the list is reachable; the page does not
182	// depend on it.
183	if repos, err := s.listRepos(ctx); err == nil {
184		l.Cmd = append(l.Cmd, repoCmds(repos, d.name())...)
185	}
186	return l
187}
188
189// withActions adds the Actions tab when the server runs CI.
190func (s *Server) withActions(sections []Section, repo, current string) []Section {
191	if s.cfg.Runs == nil {
192		return sections
193	}
194	return append(sections, Section{Key: "a", Label: "Actions", Href: actionsBase(repo), Current: current == "actions"})
195}
196
197// cloneURL is the HTTPS clone URL of a repository.
198func (s *Server) cloneURL(name string) string {
199	return s.cfg.PublicURL + "/" + name + ".git"
200}
201
202// refCommit is what a ref shows: the commit it designates.
203type refCommit struct {
204	short, subject, when, whenAt string
205	at                           int64 // unix time, to sort tags
206}
207
208// commitsOf reads the head commit of each ref, a few at a time. A ref whose
209// commit cannot be read (a tag on a tree, say) has no entry.
210func (s *Server) commitsOf(ctx context.Context, repo domain.RepoName, refs []domain.Ref) map[string]refCommit {
211	const workers = 8
212	var (
213		mu  sync.Mutex
214		out = make(map[string]refCommit, len(refs))
215		sem = make(chan struct{}, workers)
216		wg  sync.WaitGroup
217	)
218	now := s.cfg.Now()
219	for _, r := range refs {
220		if r.CommitID.IsZero() {
221			continue
222		}
223		id := r.CommitID.String()
224		mu.Lock()
225		_, done := out[id]
226		if !done {
227			out[id] = refCommit{} // reserved: one lookup per commit
228		}
229		mu.Unlock()
230		if done {
231			continue
232		}
233		sem <- struct{}{}
234		wg.Add(1)
235		go func() {
236			defer func() { <-sem; wg.Done() }()
237			// By id, not by name: a branch and a tag may share a name.
238			res, err := s.commitList(ctx, repo, id, "", 1, "")
239			var rc refCommit
240			if err == nil && len(res.Commits) == 1 {
241				row := commitRow(repo.String(), res.Commits[0], now)
242				rc.short, rc.subject, rc.when, rc.whenAt = row.Short, row.Subject, row.When, row.WhenAt
243				rc.at = unixSeconds(res.Commits[0].Committer.Time)
244			}
245			mu.Lock()
246			out[id] = rc
247			mu.Unlock()
248		}()
249	}
250	wg.Wait()
251	return out
252}
253
254// whenOf is the relative and the machine form of a time; both are "" when
255// the time is unknown (the zero time).
256func whenOf(now time.Time, t time.Time) (when, at string) {
257	if t.IsZero() {
258		return "", ""
259	}
260	return ago(now, t), rfc3339(t)
261}
262
263// unixSeconds is the Unix time of t in seconds, 0 for the zero time.
264func unixSeconds(t time.Time) int64 {
265	if t.IsZero() {
266		return 0
267	}
268	return t.Unix()
269}
270
271// commitRow is the row every list of commits starts from: the short id, the
272// subject, the author and the date of the committer, all fit to display. The
273// caller adds what is specific to its list.
274func commitRow(repo string, c domain.Commit, now time.Time) CommitRow {
275	row := CommitRow{
276		Short: short(c.ID.String()), Subject: visibleText(c.Summary),
277		CHref:  repoHref(repo, "commit", c.ID.String()),
278		Author: visibleText(c.Author.Name), Merge: len(c.Parents) > 1,
279		Sig: signatureBadge(c.Verification, false),
280	}
281	row.When, row.WhenAt = whenOf(now, c.Committer.Time)
282	return row
283}
284
285// namesAt maps commit ids to the names of the refs that designate them.
286func namesAt(refs []domain.Ref) map[string][]string {
287	m := map[string][]string{}
288	for _, r := range refs {
289		m[r.CommitID.String()] = append(m[r.CommitID.String()], r.ShortName)
290	}
291	for _, v := range m {
292		sort.Strings(v)
293	}
294	return m
295}
296
297// emptyState is the page of a repository without a branch.
298func (s *Server) emptyState(ctx context.Context, d *repoData) (Layout, StatePage) {
299	l := s.repoLayout(ctx, d, "summary")
300	l.Title = d.name() + " · " + s.instance
301	l.Sections = nil
302	l.Cmd = slices.DeleteFunc(l.Cmd, func(c CmdItem) bool { return c.Kind == "section" })
303	branch := d.repo.DefaultBranch
304	return l, StatePage{
305		Code: "empty", Title: d.name() + " is empty",
306		Lines: []string{"no commits yet. push a branch to create one."},
307		Clone: &Clone{ID: "clone-" + d.name(), Lines: []string{
308			"git remote add origin " + s.cloneURL(d.name()),
309			"git push -u origin " + branch,
310		}},
311		Back: []Link{{Label: "home", Href: "/"}},
312	}
313}

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