Migration
This is my new public git source viewer. Source coming soon. Please contact with concerns/bugs.
Contact me
internal/modules/readme.go
4bda28df3ab3dbfcc789dcbbb184cabc8cac9398
· 1.2 KB · 58 lines
raw
| 1 | package modules |
| 2 | |
| 3 | import ( |
| 4 | "html/template" |
| 5 | "strings" |
| 6 | |
| 7 | "gsg/internal/core" |
| 8 | ) |
| 9 | |
| 10 | type Readme struct { |
| 11 | Name string |
| 12 | HTML template.HTML |
| 13 | } |
| 14 | |
| 15 | var readmeNames = []string{"README.md", "readme.md", "README.markdown", "README", "readme"} |
| 16 | |
| 17 | func init() { core.Register("readme", readmeMod) } |
| 18 | |
| 19 | // readme: first README found at Ctx.Path, rendered. |
| 20 | // Returns nil (not an error) when absent, so `with` in a template just skips it. |
| 21 | func readmeMod(c *core.Ctx, args ...string) (any, error) { |
| 22 | rev := c.Commit |
| 23 | if rev == "" { |
| 24 | rev = c.Ref |
| 25 | } |
| 26 | // Same (rev, path) listing the `tree` module already computes for this |
| 27 | // page -- go through it instead of forking a second identical ls-tree. |
| 28 | v, err := c.Mod("tree") |
| 29 | if err != nil { |
| 30 | return nil, nil |
| 31 | } |
| 32 | t, ok := v.(Tree) |
| 33 | if !ok { |
| 34 | return nil, nil |
| 35 | } |
| 36 | present := map[string]bool{} |
| 37 | for _, e := range t.Entries { |
| 38 | if e.Type == "blob" { |
| 39 | present[e.Name] = true |
| 40 | } |
| 41 | } |
| 42 | for _, name := range readmeNames { |
| 43 | if !present[name] { |
| 44 | continue |
| 45 | } |
| 46 | full := strings.TrimPrefix(c.Path+"/"+name, "/") |
| 47 | src, err := c.Repo.Blob(rev, full) |
| 48 | if err != nil { |
| 49 | continue |
| 50 | } |
| 51 | out, err := Markdown(src, "/"+c.Info.Slug, c.Ref, c.Path) |
| 52 | if err != nil { |
| 53 | return nil, err |
| 54 | } |
| 55 | return Readme{Name: name, HTML: out}, nil |
| 56 | } |
| 57 | return nil, nil |
| 58 | } |