Parent directory

utils.go

1477 bytes
 1package git
 2
 3import (
 4	"os"
 5	"path"
 6	"path/filepath"
 7
 8	"github.com/gobwas/glob"
 9)
10
11// LatestFile returns the contents of the first file at the specified path pattern in the repository and its file path.
12func LatestFile(repo *Repository, ref *Reference, pattern string) (string, string, error) {
13	g := glob.MustCompile(pattern)
14	dir := path.Dir(pattern)
15	if ref == nil {
16		head, err := repo.HEAD()
17		if err != nil {
18			return "", "", err
19		}
20		ref = head
21	}
22	t, err := repo.TreePath(ref, dir)
23	if err != nil {
24		return "", "", err
25	}
26	ents, err := t.Entries()
27	if err != nil {
28		return "", "", err
29	}
30	for _, e := range ents {
31		te := e
32		fp := path.Join(dir, te.Name())
33		if te.IsTree() {
34			continue
35		}
36		if g.Match(fp) {
37			if te.IsSymlink() {
38				bts, err := te.Contents()
39				if err != nil {
40					return "", "", err
41				}
42				fp = string(bts)
43				te, err = t.TreeEntry(fp)
44				if err != nil {
45					return "", "", err
46				}
47			}
48			bts, err := te.Contents()
49			if err != nil {
50				return "", "", err
51			}
52			return string(bts), fp, nil
53		}
54	}
55	return "", "", ErrFileNotFound
56}
57
58// Returns true if path is a directory containing an `objects` directory and a
59// `HEAD` file.
60func isGitDir(path string) bool {
61	stat, err := os.Stat(filepath.Join(path, "objects"))
62	if err != nil {
63		return false
64	}
65	if !stat.IsDir() {
66		return false
67	}
68
69	stat, err = os.Stat(filepath.Join(path, "HEAD"))
70	if err != nil {
71		return false
72	}
73	if stat.IsDir() {
74		return false
75	}
76
77	return true
78}