-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgito.go
280 lines (229 loc) · 5.73 KB
/
gito.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package gito
import (
"bytes"
"fmt"
"io/fs"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"sync"
)
type G struct {
config *Config
}
func New(config *Config) *G {
return &G{config: config}
}
func (g *G) Get(repo string) error {
parsed, err := url.Parse(repo)
if err != nil {
return fmt.Errorf("gito: error parsing repo URL: %v", err)
}
repo = path.Join(parsed.Host, parsed.Path)
// where repo will live in the PATH
fullPath := filepath.Join(g.config.active.path[0], repo)
err = os.MkdirAll(filepath.Dir(fullPath), 0755)
if err != nil {
return err
}
if exists, err := gitCloneAt(repo, fullPath); exists {
return fmt.Errorf("gito: something already exists at %q", fullPath)
} else if err != nil {
return err
}
return nil
}
func gitCloneAt(repo, fullPath string) (bool, error) {
_, err := os.Stat(fullPath)
if !os.IsNotExist(err) {
return true, nil
}
gitRepo := fmt.Sprintf("https://%s.git", repo) // simpler than ssh
cmd := exec.Command("git", "clone", "--", gitRepo, fullPath)
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
if err := cmd.Run(); err != nil {
return false, fmt.Errorf("gito: error cloning repo: %v", err)
}
cmd = exec.Command("git", "submodule", "update", "--init", "--recursive")
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
cmd.Dir = fullPath
if err := cmd.Run(); err != nil {
return false, fmt.Errorf("gito: error updating submodules: %v", err)
}
return false, nil
}
func (g *G) Where(repo string) ([]string, error) {
repo, _ = g.config.active.Alias(repo)
path, ok := g.config.active.CustomPath(repo)
if ok {
return []string{path}, nil
}
return g.where(repo, true)
}
func (g *G) where(maybePath string, checkIsRepo bool) ([]string, error) {
matches := map[string]struct{}{}
mtx := sync.Mutex{}
for _, dir := range g.config.active.path {
newMatches, ok := in(maybePath, "", filepath.Join(dir), map[string]struct{}{}, checkIsRepo, 0, &mtx)
if ok {
for match := range newMatches {
matches[match] = struct{}{}
}
}
}
if len(matches) == 0 {
return nil, fmt.Errorf("%q not found", maybePath)
}
paths := []string{}
for match := range matches {
paths = append(paths, match)
}
return paths, nil
}
func in(repo, dir, soFar string, matches map[string]struct{}, checkIsRepo bool, depth int, mtx *sync.Mutex) (map[string]struct{}, bool) {
// limit recursion depth
if depth == 3 {
return matches, len(matches) > 0
}
fullPath := filepath.Join(soFar, dir, repo)
// check if the directory is a repository
dirIsRepo := !checkIsRepo || isRepo(fullPath)
if repo == dir && dirIsRepo {
mtx.Lock()
matches[fullPath] = struct{}{}
mtx.Unlock()
return matches, true
}
// handle partial name matches
f, err := os.Stat(fullPath)
if err == nil && f.IsDir() && dirIsRepo {
mtx.Lock()
matches[fullPath] = struct{}{}
mtx.Unlock()
return matches, len(matches) > 0
}
files, err := os.ReadDir(filepath.Join(soFar, dir))
if err != nil {
return matches, len(matches) > 0
}
// collect results in a thread-local manner
localMatches := make(map[string]struct{})
var localMtx sync.Mutex
wg := sync.WaitGroup{}
for _, file := range files {
if !file.IsDir() {
continue
}
wg.Add(1)
go func(file fs.DirEntry) {
defer wg.Done()
newMatches, ok := in(repo, file.Name(), filepath.Join(soFar, dir), make(map[string]struct{}), checkIsRepo, depth+1, mtx)
if ok {
localMtx.Lock()
for match := range newMatches {
localMatches[match] = struct{}{}
}
localMtx.Unlock()
}
}(file)
}
wg.Wait()
// merge local matches into global matches
mtx.Lock()
for match := range localMatches {
matches[match] = struct{}{}
}
mtx.Unlock()
return matches, len(matches) > 0
}
// isRepo tests for the existence of a .git directory at dir.
func isRepo(dir string) bool {
_, err := os.Stat(filepath.Join(dir, ".git"))
return !os.IsNotExist(err)
}
func (g *G) URL(repo string) ([]string, error) {
var paths = []string{"."}
if repo != "." {
var err error
paths, err = g.Where(repo)
if err != nil {
return nil, err
}
}
urls := []string{}
errs := []error{}
for _, path := range paths {
url, err := getURL(path)
if err != nil {
errs = append(errs, err)
continue
}
urls = append(urls, url)
}
if len(errs) == len(paths) {
return nil, fmt.Errorf("gito: no URLs found")
}
return urls, nil
}
func getURL(repo string) (string, error) {
cmd := exec.Command("git", "remote", "get-url", "origin")
cmd.Dir = repo
buf := &bytes.Buffer{}
cmd.Stdout = buf
if err := cmd.Run(); err != nil {
return "", fmt.Errorf("error getting git remote for %q: %v", repo, err)
}
return extractURL(buf.String()), nil
}
func extractURL(url string) string {
url = strings.TrimSpace(url)
// removes prefix of url if it starts with ssh:// or git@
url = strings.Replace(url, "git@", "", 1)
url = strings.Replace(url, "ssh://", "", 1)
url = strings.Replace(url, "http://", "", 1)
url = strings.Replace(url, "https://", "", 1)
url = strings.Replace(url, ":", "/", 1)
url = strings.Replace(url, ".git", "", 1)
return "https://" + url
}
func (g *G) Alias(from, to string) error {
_, err := g.Where(to)
if err != nil {
return err
}
aliases := g.config.active.Aliases
aliases[from] = to
return g.config.Sync()
}
func (g *G) Set(name, loc string) error {
if !isRepo(loc) {
return fmt.Errorf("no repo @ %q", loc)
}
custom := g.config.active.Custom
custom[name] = loc
return g.config.Sync()
}
func (g *G) SetSelf(self string) error {
_, err := g.where(self, false)
if err != nil {
return err
}
g.config.active.Self = self
return g.config.Sync()
}
func (g *G) Self() (string, error) {
self := g.config.active.Self
if self == "" {
return "", nil
}
where, err := g.where(self, false)
if err != nil {
return "", err
}
return where[0], nil
}