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