/
git.go
115 lines (91 loc) · 2.1 KB
/
git.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package storage
import (
"fmt"
"net/url"
"strings"
"github.com/go-git/go-billy/v5"
"github.com/go-git/go-billy/v5/memfs"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/cache"
"github.com/go-git/go-git/v5/storage/filesystem"
"github.com/go-git/go-git/v5/storage/memory"
"golang.org/x/exp/slices"
)
type GitStorage struct {
billy.Filesystem
}
func (s GitStorage) Load(path string) (Storage, *StoragePathInfo, error) {
uri, err := url.Parse(path)
if err != nil {
return nil, nil, err
}
slashCount := strings.Count(uri.Path, "/")
i := strings.LastIndexFunc(uri.Path, func(c rune) bool {
if c == '/' {
slashCount--
return slashCount-1 == 0
}
return false
})
if i > 0 {
uri.Path = uri.Path[:i]
}
if uri.Scheme == "" {
uri.Scheme = "https"
}
if uri.Host == "" {
uri.Host = "github.com"
}
repoUrl := uri.String()
ref, err := getGitMainRef(repoUrl)
if err != nil {
return nil, nil, err
}
gitFs, _ := s.Chroot(".git")
storage := filesystem.NewStorage(gitFs, cache.NewObjectLRUDefault())
_, err = git.Clone(storage, s, &git.CloneOptions{
URL: repoUrl,
SingleBranch: true,
ReferenceName: ref.Name(),
Tags: git.NoTags,
// Progress: os.Stdout,
})
if err != nil {
return nil, nil, err
}
return s, &StoragePathInfo{
Dir: "",
TrimPrefix: uri.Path,
}, nil
}
func (s GitStorage) Save(path string) (Storage, error) {
return s, nil
}
func NewGit() Storage {
return GitStorage{
memfs.New(),
}
}
func getGitMainRef(repoPath string) (*plumbing.Reference, error) {
mainRefNames := []string{"master", "main"}
rem := git.NewRemote(memory.NewStorage(), &config.RemoteConfig{
Name: "origin",
URLs: []string{repoPath},
})
refs, err := rem.List(&git.ListOptions{})
if err != nil {
return nil, err
}
for _, ref := range refs {
refName := ref.Name().Short()
if !ref.Name().IsBranch() {
continue
}
if slices.Contains(mainRefNames, refName) {
return ref, nil
}
}
return nil, fmt.Errorf("reference not found (master/main)")
}