1package backend
2
3import (
4 "path/filepath"
5
6 "github.com/charmbracelet/soft-serve/git"
7 "github.com/gobwas/glob"
8)
9
10// LatestFile returns the contents of the latest file at the specified path in
11// the repository and its file path.
12func LatestFile(r Repository, pattern string) (string, string, error) {
13 g := glob.MustCompile(pattern)
14 dir := filepath.Dir(pattern)
15 repo, err := r.Open()
16 if err != nil {
17 return "", "", err
18 }
19 head, err := repo.HEAD()
20 if err != nil {
21 return "", "", err
22 }
23 t, err := repo.TreePath(head, dir)
24 if err != nil {
25 return "", "", err
26 }
27 ents, err := t.Entries()
28 if err != nil {
29 return "", "", err
30 }
31 for _, e := range ents {
32 fp := filepath.Join(dir, e.Name())
33 if e.IsTree() {
34 continue
35 }
36 if g.Match(fp) {
37 bts, err := e.Contents()
38 if err != nil {
39 return "", "", err
40 }
41 return string(bts), fp, nil
42 }
43 }
44 return "", "", git.ErrFileNotFound
45}
46
47// Readme returns the repository's README.
48func Readme(r Repository) (readme string, path string, err error) {
49 readme, path, err = LatestFile(r, "README*")
50 return
51}