@@ -0,0 +1,170 @@
1+package site
2+
3+import (
4+ "bytes"
5+ "errors"
6+ "fmt"
7+ "html"
8+ "html/template"
9+ "os"
10+ "path"
11+ "path/filepath"
12+ "runtime"
13+ "strings"
14+ "sync"
15+ "unicode/utf8"
16+
17+ "github.com/alecthomas/chroma/v2"
18+ "github.com/alecthomas/chroma/v2/lexers"
19+
20+ "xonecas.io/site/internal/project"
21+ "xonecas.io/site/internal/repo"
22+)
23+
24+// MaxShow is the largest file a page shows. Bigger files, and binary ones, get a placeholder.
25+const MaxShow = 256 << 10
26+
27+// Crumb is one link in a path's breadcrumb.
28+type Crumb struct{ Name, Href string }
29+
30+// BrowsePage is a folder or a file on the default branch.
31+type BrowsePage struct {
32+ Row ProjectRow
33+ Name string
34+ Path string
35+ Crumbs []Crumb
36+ Entries []TreeEntry // a folder's contents
37+ Code template.HTML // a file, highlighted
38+ Size string // a file's size
39+ Note string // why a file is not shown
40+}
41+
42+// writeBrowse writes tree/ and blob/ for project p. It skips the project when its HEAD and the
43+// program are unchanged since the last build, and otherwise starts over, so deleted files go too.
44+func writeBrowse(out string, p project.Project, row ProjectRow, t Tree, fresh bool) error {
45+ dir, base := p.Sources[0].Dir, filepath.Join(out, "projects", p.Name)
46+ head, err := repo.Git(dir, "rev-parse", "HEAD")
47+ if err != nil {
48+ return err
49+ }
50+ mark := filepath.Join(base, ".head")
51+ if old, _ := os.ReadFile(mark); fresh && string(old) == head {
52+ return nil
53+ }
54+ for _, d := range []string{"tree", "blob"} {
55+ if err := os.RemoveAll(filepath.Join(base, d)); err != nil {
56+ return err
57+ }
58+ }
59+ for d := range t.Dirs {
60+ page := BrowsePage{Row: row, Name: p.Name, Path: d, Crumbs: crumbs(p.Name, d), Entries: entries(p.Name, d, t)}
61+ if err := render(filepath.Join(base, "tree", filepath.FromSlash(d), "index.html"), "browse.html", page); err != nil {
62+ return err
63+ }
64+ }
65+ var wg sync.WaitGroup
66+ errs := make(chan error, len(t.Files))
67+ sem := make(chan struct{}, runtime.NumCPU())
68+ for f, size := range t.Files {
69+ wg.Go(func() {
70+ sem <- struct{}{}
71+ defer func() { <-sem }()
72+ page := BrowsePage{Row: row, Name: p.Name, Path: f, Crumbs: crumbs(p.Name, f), Size: bytesize(size)}
73+ if size > MaxShow {
74+ page.Note = "Too big to show."
75+ } else if b, err := repo.Blob(dir, "HEAD:"+f); err != nil {
76+ errs <- fmt.Errorf("%s: %w", f, err)
77+ return
78+ } else if bytes.IndexByte(b[:min(len(b), 8000)], 0) >= 0 || !utf8.Valid(b) {
79+ page.Note = "Binary file, not shown."
80+ } else if page.Code, err = highlight(f, string(b)); err != nil {
81+ errs <- fmt.Errorf("%s: %w", f, err)
82+ return
83+ }
84+ if err := render(filepath.Join(base, "blob", filepath.FromSlash(f), "index.html"), "browse.html", page); err != nil {
85+ errs <- err
86+ }
87+ })
88+ }
89+ wg.Wait()
90+ close(errs)
91+ var all []error
92+ for err := range errs {
93+ all = append(all, err)
94+ }
95+ if err := errors.Join(all...); err != nil {
96+ return err
97+ }
98+ return os.WriteFile(mark, []byte(head), 0o644)
99+}
100+
101+// highlight renders text as numbered lines with #L anchors, coloured by the lexer for its file name.
102+// Each line is a span with its number as a link to itself; site.css lays them out.
103+func highlight(name, text string) (template.HTML, error) {
104+ lexer := lexers.Match(path.Base(name))
105+ if lexer == nil {
106+ lexer = lexers.Fallback
107+ }
108+ it, err := lexer.Tokenise(nil, text)
109+ if err != nil {
110+ return "", err
111+ }
112+ var tokens []chroma.Token
113+ for _, t := range it.Tokens() {
114+ t.Type = colour(t.Type)
115+ if n := len(tokens); n > 0 && tokens[n-1].Type == t.Type {
116+ tokens[n-1].Value += t.Value
117+ } else {
118+ tokens = append(tokens, t)
119+ }
120+ }
121+ var buf strings.Builder
122+ buf.WriteString(`<pre class="code">`)
123+ for i, line := range chroma.SplitTokensIntoLines(tokens) {
124+ fmt.Fprintf(&buf, `<span id="L%d"><a href="#L%d">%d</a>`, i+1, i+1, i+1)
125+ for _, t := range line {
126+ if c := chroma.StandardTypes[t.Type]; c != "" {
127+ fmt.Fprintf(&buf, `<b class="%s">%s</b>`, c, html.EscapeString(t.Value))
128+ } else {
129+ buf.WriteString(html.EscapeString(t.Value))
130+ }
131+ }
132+ buf.WriteString("</span>")
133+ }
134+ buf.WriteString("</pre>")
135+ return template.HTML(buf.String()), nil
136+}
137+
138+// palette is the token types site.css colours. Every other token is plain text, which needs no span,
139+// and that keeps the pages small.
140+var palette = map[chroma.TokenType]bool{chroma.Comment: true, chroma.CommentPreproc: true, chroma.Keyword: true, chroma.NameBuiltin: true,
141+ chroma.NameClass: true, chroma.NameFunction: true, chroma.NameTag: true, chroma.NameAttribute: true, chroma.LiteralString: true, chroma.LiteralNumber: true}
142+
143+func colour(t chroma.TokenType) chroma.TokenType {
144+ for _, c := range []chroma.TokenType{t, t.SubCategory(), t.Category()} {
145+ if palette[c] {
146+ return c
147+ }
148+ }
149+ return chroma.Text
150+}
151+
152+// crumbs links each folder on the way to p, starting at the project.
153+func crumbs(name, p string) []Crumb {
154+ list := []Crumb{{name, "/projects/" + name + "/"}}
155+ parts := strings.Split(p, "/")
156+ for i, part := range parts {
157+ list = append(list, Crumb{part, href(name, "tree", strings.Join(parts[:i+1], "/"))})
158+ }
159+ return list
160+}
161+
162+func bytesize(n int64) string {
163+ switch {
164+ case n >= 1<<20:
165+ return fmt.Sprintf("%.1f MB", float64(n)/(1<<20))
166+ case n >= 1<<10:
167+ return fmt.Sprintf("%.1f KB", float64(n)/(1<<10))
168+ }
169+ return fmt.Sprintf("%d bytes", n)
170+}