xonecas.io
8356
Wx

www-xonecas-io / files

www-xonecas-io / internal / site / browse.go

4.3 KB
1package site
2
3import (
4	"bytes"
5	"fmt"
6	"html"
7	"html/template"
8	"io"
9	"path"
10	"strings"
11	"unicode/utf8"
12
13	"github.com/alecthomas/chroma/v2"
14	"github.com/alecthomas/chroma/v2/lexers"
15
16	"xonecas.io/site/internal/repo"
17)
18
19// MaxShow is the largest file a page shows. Bigger files, and binary ones, get a placeholder.
20const MaxShow = 256 << 10
21
22// Crumb is one link in a path's breadcrumb.
23type Crumb struct{ Name, Href string }
24
25// BrowsePage is a folder or a file on the default branch.
26type BrowsePage struct {
27	Row     ProjectRow
28	Name    string
29	Path    string
30	Crumbs  []Crumb
31	Side    []SideEntry   // the sidebar
32	Entries []TreeEntry   // a folder's contents
33	Code    template.HTML // a file, highlighted
34	Size    string        // a file's size
35	Note    string        // why a file is not shown
36}
37
38// NewBrowsePage is the folder or file at path p of project name, whose bare repo is dir. kids is Children(name, t).
39func NewBrowsePage(name, dir string, row ProjectRow, t Tree, kids map[string][]TreeEntry, p string) (BrowsePage, error) {
40	page := BrowsePage{Row: row, Name: name, Path: p, Crumbs: crumbs(name, p), Side: sidebar(kids, p)}
41	if t.Dirs[p] {
42		page.Entries = kids[p]
43		return page, nil
44	}
45	size, ok := t.Files[p]
46	if !ok {
47		return page, ErrNotFound
48	}
49	page.Size = bytesize(size)
50	if size > MaxShow {
51		page.Note = "Too big to show."
52		return page, nil
53	}
54	b, err := repo.Blob(dir, "HEAD:"+p)
55	if err != nil {
56		return page, err
57	}
58	if bytes.IndexByte(b[:min(len(b), 8000)], 0) >= 0 || !utf8.Valid(b) {
59		page.Note = "Binary file, not shown."
60		return page, nil
61	}
62	page.Code, err = highlight(p, string(b))
63	return page, err
64}
65
66// highlight renders text as numbered lines with #L anchors, coloured by the lexer for its file name.
67// Each line is a span with its number as a link to itself; site.css lays them out.
68func highlight(name, text string) (template.HTML, error) {
69	lexer := lexers.Match(path.Base(name))
70	if lexer == nil {
71		lexer = lexers.Fallback
72	}
73	tokens, err := tokenise(lexer, text)
74	if err != nil {
75		return "", err
76	}
77	var buf strings.Builder
78	buf.WriteString(`<pre class="code">`)
79	for i, line := range chroma.SplitTokensIntoLines(tokens) {
80		fmt.Fprintf(&buf, `<span id="L%d"><a href="#L%d">%d</a>`, i+1, i+1, i+1)
81		writeTokens(&buf, line)
82		buf.WriteString("</span>")
83	}
84	buf.WriteString("</pre>")
85	return template.HTML(buf.String()), nil
86}
87
88// tokenise lexes text into the palette's token types, merging neighbours of the same type.
89func tokenise(lexer chroma.Lexer, text string) ([]chroma.Token, error) {
90	it, err := lexer.Tokenise(nil, text)
91	if err != nil {
92		return nil, err
93	}
94	var tokens []chroma.Token
95	for _, t := range it.Tokens() {
96		t.Type = colour(t.Type)
97		if n := len(tokens); n > 0 && tokens[n-1].Type == t.Type {
98			tokens[n-1].Value += t.Value
99		} else {
100			tokens = append(tokens, t)
101		}
102	}
103	return tokens, nil
104}
105
106// writeTokens writes tokens as escaped text, each coloured one in a <b> with its class.
107func writeTokens(w io.StringWriter, tokens []chroma.Token) {
108	for _, t := range tokens {
109		if c := chroma.StandardTypes[t.Type]; c != "" {
110			w.WriteString(`<b class="` + c + `">` + html.EscapeString(t.Value) + `</b>`)
111		} else {
112			w.WriteString(html.EscapeString(t.Value))
113		}
114	}
115}
116
117// palette is the token types site.css colours. Every other token is plain text, which needs no span,
118// and that keeps the pages small.
119var palette = map[chroma.TokenType]bool{chroma.Comment: true, chroma.CommentPreproc: true, chroma.Keyword: true, chroma.NameBuiltin: true,
120	chroma.NameClass: true, chroma.NameFunction: true, chroma.NameTag: true, chroma.NameAttribute: true, chroma.LiteralString: true, chroma.LiteralNumber: true}
121
122func colour(t chroma.TokenType) chroma.TokenType {
123	for _, c := range []chroma.TokenType{t, t.SubCategory(), t.Category()} {
124		if palette[c] {
125			return c
126		}
127	}
128	return chroma.Text
129}
130
131// crumbs links each folder on the way to p, starting at the project.
132func crumbs(name, p string) []Crumb {
133	list := []Crumb{{name, "/projects/" + name + "/"}}
134	parts := strings.Split(p, "/")
135	for i, part := range parts {
136		list = append(list, Crumb{part, href(name, "tree", strings.Join(parts[:i+1], "/"))})
137	}
138	return list
139}
140
141func bytesize(n int64) string {
142	switch {
143	case n >= 1<<20:
144		return fmt.Sprintf("%.1f MB", float64(n)/(1<<20))
145	case n >= 1<<10:
146		return fmt.Sprintf("%.1f KB", float64(n)/(1<<10))
147	}
148	return fmt.Sprintf("%d bytes", n)
149}