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