git-module

git clone git://git.lin.moe/fork/git-module.git

 1package git
 2
 3import (
 4	"context"
 5	"path"
 6	"strings"
 7)
 8
 9// TreeEntry returns the TreeEntry by given subpath of the tree.
10func (t *Tree) TreeEntry(ctx context.Context, subpath string, opts ...LsTreeOptions) (*TreeEntry, error) {
11	if len(subpath) == 0 {
12		return &TreeEntry{
13			id:   t.id,
14			typ:  ObjectTree,
15			mode: EntryTree,
16		}, nil
17	}
18
19	subpath = path.Clean(subpath)
20	paths := strings.Split(subpath, "/")
21	var err error
22	tree := t
23	for i, name := range paths {
24		// Reached end of the loop
25		if i == len(paths)-1 {
26			entries, err := tree.Entries(ctx, opts...)
27			if err != nil {
28				return nil, err
29			}
30
31			for _, v := range entries {
32				if v.name == name {
33					return v, nil
34				}
35			}
36		} else {
37			tree, err = tree.Subtree(ctx, name, opts...)
38			if err != nil {
39				return nil, err
40			}
41		}
42	}
43	return nil, ErrRevisionNotExist
44}
45
46// Blob returns the blob object by given subpath of the tree.
47func (t *Tree) Blob(ctx context.Context, subpath string, opts ...LsTreeOptions) (*Blob, error) {
48	e, err := t.TreeEntry(ctx, subpath, opts...)
49	if err != nil {
50		return nil, err
51	}
52
53	if e.IsBlob() || e.IsExec() {
54		return e.Blob(), nil
55	}
56
57	return nil, ErrNotBlob
58}
59
60// BlobByIndex returns blob object by given index.
61func (t *Tree) BlobByIndex(ctx context.Context, index string) (*Blob, error) {
62	typ, err := t.repo.CatFileType(ctx, index)
63	if err != nil {
64		return nil, err
65	}
66
67	if typ != ObjectBlob {
68		return nil, ErrNotBlob
69	}
70
71	id, err := t.repo.RevParse(ctx, index)
72	if err != nil {
73		return nil, err
74	}
75
76	return &Blob{
77		TreeEntry: &TreeEntry{
78			mode:   EntryBlob,
79			typ:    ObjectBlob,
80			id:     MustIDFromString(id),
81			parent: t,
82		},
83	}, nil
84}