1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package web
4
5import (
6 "context"
7 "errors"
8 "fmt"
9 "html"
10 "html/template"
11 "io"
12 "net/http"
13 "strings"
14 "time"
15
16 "github.com/a-h/templ"
17 "github.com/bnema/zerowrap"
18
19 "bnema.dev/ermite/internal/domain"
20 "bnema.dev/ermite/internal/ports"
21)
22
23// maxReadmeBytes is the largest README that is rendered in the page; a
24// larger one is replaced by a note.
25const maxReadmeBytes = 512 << 10
26
27// recentCommits is how many commits the rail of the summary lists.
28const recentCommits = 5
29
30// recentRuns is how many runs the rail of the summary lists.
31const recentRuns = 5
32
33// readmeNames are the README file names in order of preference (compared
34// lowercase): Markdown first.
35var readmeNames = []string{"readme.md", "readme.markdown", "readme", "readme.txt"}
36
37// summary is the page of a repository: description, README, and in the rail
38// the clone URL, the facts, the recent commits and the README outline.
39func (s *Server) summary(ctx context.Context, r *http.Request) (templ.Component, int, error) {
40 d, err := s.loadRepo(ctx, r.PathValue("repo"))
41 if err != nil {
42 return nil, 0, err
43 }
44 if d.head == nil {
45 l, st := s.emptyState(ctx, d)
46 return State(l, st), http.StatusOK, nil
47 }
48 ref := d.head.ShortName
49 now := s.cfg.Now()
50
51 p := SummaryPage{
52 AllHref: repoHref(d.name(), "commits", ref),
53 Clone: Clone{ID: "clone-" + d.name(), Lines: []string{"git clone " + s.cloneURL(d.name())}},
54 }
55
56 commits, err := s.commitList(ctx, d.repo.Name, d.head.CommitID.String(), "", recentCommits, "")
57 if err != nil {
58 return nil, 0, err
59 }
60 branchesAt, tagsAt := namesAt(d.branches), namesAt(d.tags)
61 for i, c := range commits.Commits {
62 id := c.ID.String()
63 row := commitRow(d.name(), c, now)
64 row.Branches, row.Tags, row.Cursor = branchesAt[id], tagsAt[id], i == 0
65 p.Recent = append(p.Recent, row)
66 }
67
68 p.Facts = s.facts(d, now)
69 p.Latest = s.latest(ctx, d)
70 p.Actions = s.recentActions(ctx, d.repo.Name, now)
71
72 if rd, err := s.readme(ctx, d, ref); err != nil {
73 return nil, 0, err
74 } else if rd != nil {
75 p.Readme, p.Outline = rd.readme, rd.outline
76 }
77
78 l := s.repoLayout(ctx, d, "summary")
79 l.Title = d.name() + " · " + s.instance
80 l.Live, l.LiveURL = true, liveURL("repo:"+d.name(), "view=summary")
81 l.HasRail = true
82 l.Lede = d.repo.Description
83 return Summary(l, p), http.StatusOK, nil
84}
85
86// maxTagDates is the most tags whose commit dates are read to name the
87// latest one; with more, the rail shows the count only.
88const maxTagDates = 20
89
90// latest is the newest tag of the repository for the rail, nil without tags.
91func (s *Server) latest(ctx context.Context, d *repoData) *LatestTag {
92 n := len(d.tags)
93 if n == 0 {
94 return nil
95 }
96 lt := &LatestTag{Count: n, RefsHref: repoHref(d.name(), "refs")}
97 if n <= maxTagDates {
98 if name, c := latestTag(d.tags, s.commitsOf(ctx, d.repo.Name, d.tags)); name != "" {
99 lt.Name, lt.Href = name, repoHref(d.name(), "tree", name)
100 lt.Subject, lt.When, lt.WhenAt = c.subject, c.when, c.whenAt
101 }
102 }
103 return lt
104}
105
106// facts are the key/value rows of the rail.
107func (s *Server) facts(d *repoData, now time.Time) []Fact {
108 fs := []Fact{
109 lastPushFact(d.repo, now),
110 {Key: "branch", Val: d.head.ShortName + " · " + plural(len(d.branches), "branch", "branches")},
111 }
112 if c := d.repo.CreatedAt; !c.IsZero() {
113 fs = append(fs, Fact{Key: "created", Val: absolute(c), Time: rfc3339(c)})
114 }
115 return fs
116}
117
118// lastPushFact is the "last push" fact of a repository; the live updates
119// render it again.
120func lastPushFact(r ports.RepoView, now time.Time) Fact {
121 last := Fact{Key: "last push", Val: "never", ID: "last-push-" + r.Name.String()}
122 if t := r.PushedAt; !t.IsZero() {
123 last.Val = ago(now, t) + " · " + absolute(t)
124 last.Time = rfc3339(t)
125 }
126 return last
127}
128
129// latestTag is the tag whose commit is the newest.
130func latestTag(tags []domain.Ref, commits map[string]refCommit) (string, refCommit) {
131 var name string
132 var best refCommit
133 for _, t := range tags {
134 c, ok := commits[t.CommitID.String()]
135 if ok && c.short != "" && (name == "" || c.at > best.at) {
136 name, best = t.ShortName, c
137 }
138 }
139 return name, best
140}
141
142// renderedReadme is the README of a repository, ready for the page.
143type renderedReadme struct {
144 readme *Readme
145 outline []Heading
146}
147
148// readme finds the README at the root of the tree of the head commit, reads
149// it and renders it. It is nil when the repository has none. Rendering
150// problems degrade to plain text; only use case failures are errors.
151func (s *Server) readme(ctx context.Context, d *repoData, ref string) (*renderedReadme, error) {
152 rev := d.head.CommitID.String()
153 tree, err := s.getTree(ctx, d.repo.Name, rev, "", false)
154 if err != nil {
155 return nil, err
156 }
157 return s.readmeIn(ctx, d.repo.Name, rev, ref, "", tree.Entries)
158}
159
160// readmeIn picks the README among the entries of the directory dir ("" for
161// the root) of the commit rev, reads it and renders it. Links in it are
162// relative to dir, on the ref ref. It is nil when the directory has none.
163//
164//hexcheck:ignore suspicious-business-logic-in-adapter picks the README among the entries of a directory to show; display only
165func (s *Server) readmeIn(ctx context.Context, repo domain.RepoName, rev, ref, dir string, entries []domain.TreeEntry) (*renderedReadme, error) {
166 var best *domain.TreeEntry
167 rank := len(readmeNames)
168 for i := range entries {
169 e := &entries[i]
170 if e.Kind != domain.EntryFile && e.Kind != domain.EntryExecutable {
171 continue
172 }
173 for i, n := range readmeNames {
174 if i < rank && strings.EqualFold(e.Name, n) {
175 best, rank = e, i
176 }
177 }
178 }
179 if best == nil {
180 return nil, nil
181 }
182 rd := &Readme{Name: best.Name}
183 if best.Size > maxReadmeBytes {
184 rd.Note = best.Name + " is too large to show here (" + humanSize(best.Size) + ")."
185 return &renderedReadme{readme: rd}, nil
186 }
187 body, binary, err := s.readBlob(ctx, repo, rev, best.Path, maxReadmeBytes)
188 if err != nil {
189 return nil, err
190 }
191 if binary {
192 rd.Note = best.Name + " is not text."
193 return &renderedReadme{readme: rd}, nil
194 }
195 name := strings.ToLower(best.Name)
196 if strings.HasSuffix(name, ".md") || strings.HasSuffix(name, ".markdown") {
197 h, outline, err := s.md.render(body, repo.String(), ref, dir)
198 if err == nil {
199 rd.HTML = h
200 return &renderedReadme{readme: rd, outline: outline}, nil
201 }
202 log := zerowrap.FromCtx(ctx)
203 log.Warn().Err(err).Str("repo", repo.String()).Msg("render README, showing plain text")
204 }
205 rd.HTML = template.HTML("<pre>" + html.EscapeString(string(body)) + "</pre>") // #nosec G203 -- escaped
206 return &renderedReadme{readme: rd}, nil
207}
208
209// readBlob reads a file, at most limit bytes. It reports a binary file
210// without its content.
211func (s *Server) readBlob(ctx context.Context, repo domain.RepoName, rev, path string, limit int64) (body []byte, binary bool, err error) {
212 info, rc, err := s.openBlobAt(ctx, repo, rev, path)
213 if err != nil {
214 return nil, false, err
215 }
216 defer func() { _ = rc.Close() }()
217 if info.Binary {
218 return nil, true, nil
219 }
220 body, err = io.ReadAll(io.LimitReader(rc, limit+1))
221 if err != nil {
222 return nil, false, err
223 }
224 if int64(len(body)) > limit {
225 return body[:limit], false, nil
226 }
227 return body, false, nil
228}
229
230// humanSize formats a size in bytes.
231func humanSize(n int64) string {
232 switch {
233 case n < 1024:
234 return itoa(int(n)) + " B"
235 case n < 1<<20:
236 return fmt.Sprintf("%.1f KiB", float64(n)/1024)
237 case n < 1<<30:
238 return fmt.Sprintf("%.1f MiB", float64(n)/(1<<20))
239 }
240 return fmt.Sprintf("%.1f GiB", float64(n)/(1<<30))
241}
242
243// recentActions is the newest runs for the rail, as the caller of the request
244// sees them (the permission of the actions page). It is nil when the server
245// runs no CI or the caller cannot read it; a failure of the read is logged and
246// the page goes on without, since the code does not depend on CI.
247func (s *Server) recentActions(ctx context.Context, repo domain.RepoName, now time.Time) *RecentActions {
248 if s.cfg.Runs == nil {
249 return nil
250 }
251 a, err := s.listRecentActions(ctx, repo, now)
252 if err != nil {
253 if !errors.Is(err, domain.ErrNotFound) {
254 log := zerowrap.FromCtx(ctx)
255 log.Warn().Err(err).Str("repo", repo.String()).Msg("read the recent runs")
256 }
257 return nil
258 }
259 return &a
260}
261
262// listRecentActions reads the newest runs of a repository.
263func (s *Server) listRecentActions(ctx context.Context, repo domain.RepoName, now time.Time) (RecentActions, error) {
264 page, err := s.cfg.Runs.ListRuns(ctx, principal(ctx), repo, ports.ListRunsParams{PageSize: recentRuns})
265 if err != nil {
266 return RecentActions{}, err
267 }
268 a := RecentActions{AllHref: actionsBase(repo.String())}
269 for _, run := range page.Runs {
270 a.Runs = append(a.Runs, s.runRow(repo.String(), run, now))
271 }
272 return a, nil
273}