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		te := e
33		fp := filepath.Join(dir, te.Name())
34		if te.IsTree() {
35			continue
36		}
37		if g.Match(fp) {
38			if te.IsSymlink() {
39				bts, err := te.Contents()
40				if err != nil {
41					return "", "", err
42				}
43				fp = string(bts)
44				te, err = t.TreeEntry(fp)
45				if err != nil {
46					return "", "", err
47				}
48			}
49			bts, err := te.Contents()
50			if err != nil {
51				return "", "", err
52			}
53			return string(bts), fp, nil
54		}
55	}
56	return "", "", git.ErrFileNotFound
57}
58
59// Readme returns the repository's README.
60func Readme(r Repository) (readme string, path string, err error) {
61	readme, path, err = LatestFile(r, "README*")
62	return
63}