forked from x-motemen/ghq
/
commands.go
343 lines (295 loc) · 8.06 KB
/
commands.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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
package main
import (
"bufio"
"fmt"
"net/url"
"os"
"os/exec"
"runtime"
"strings"
"syscall"
"github.com/codegangsta/cli"
"github.com/motemen/ghq/utils"
)
var Commands = []cli.Command{
commandGet,
commandList,
commandLook,
commandImport,
}
var commandGet = cli.Command{
Name: "get",
Usage: "Clone/sync with a remote repository",
Description: `
Clone a GitHub repository under ghq root direcotry. If the repository is
already cloned to local, nothing will happen unless '-u' ('--update')
flag is supplied, in which case 'git remote update' is executed.
When you use '-p' option, the repository is cloned via SSH.
`,
Action: doGet,
Flags: []cli.Flag{
cli.BoolFlag{Name: "update, u", Usage: "Update local repository if cloned already"},
cli.BoolFlag{Name: "p", Usage: "Clone with SSH"},
cli.BoolFlag{Name: "shallow", Usage: "Do a shallow clone"},
},
}
var commandList = cli.Command{
Name: "list",
Usage: "List local repositories",
Description: `
List locally cloned repositories. If a query argument is given, only
repositories whose names contain that query text are listed. '-e'
('--exact') forces the match to be an exact one (i.e. the query equals to
_project_ or _user_/_project_) If '-p' ('--full-path') is given, the full paths
to the repository root are printed instead of relative ones.
`,
Action: doList,
Flags: []cli.Flag{
cli.BoolFlag{Name: "exact, e", Usage: "Perform an exact match"},
cli.BoolFlag{Name: "full-path, p", Usage: "Print full paths"},
cli.BoolFlag{Name: "unique", Usage: "Print unique subpaths"},
},
}
var commandLook = cli.Command{
Name: "look",
Usage: "Look into a local repository",
Description: `
Look into a locally cloned repository with the shell.
`,
Action: doLook,
}
var commandImport = cli.Command{
Name: "import",
Usage: "Bulk get repositories from a file or stdin",
Action: doImport,
}
type commandDoc struct {
Parent string
Arguments string
}
var commandDocs = map[string]commandDoc{
"get": {"", "[-u] <repository URL> | [-u] [-p] <user>/<project>"},
"list": {"", "[-p] [-e] [<query>]"},
"look": {"", "<project> | <user>/<project> | <host>/<user>/<project>"},
"import": {"", "< file"},
}
// Makes template conditionals to generate per-command documents.
func mkCommandsTemplate(genTemplate func(commandDoc) string) string {
template := "{{if false}}"
for _, command := range append(Commands) {
template = template + fmt.Sprintf("{{else if (eq .Name %q)}}%s", command.Name, genTemplate(commandDocs[command.Name]))
}
return template + "{{end}}"
}
func init() {
argsTemplate := mkCommandsTemplate(func(doc commandDoc) string { return doc.Arguments })
parentTemplate := mkCommandsTemplate(func(doc commandDoc) string { return string(strings.TrimLeft(doc.Parent+" ", " ")) })
cli.CommandHelpTemplate = `NAME:
{{.Name}} - {{.Usage}}
USAGE:
ghq ` + parentTemplate + `{{.Name}} ` + argsTemplate + `
{{if (len .Description)}}
DESCRIPTION: {{.Description}}
{{end}}{{if (len .Flags)}}
OPTIONS:
{{range .Flags}}{{.}}
{{end}}
{{end}}`
}
func doGet(c *cli.Context) {
argURL := c.Args().Get(0)
doUpdate := c.Bool("update")
isShallow := c.Bool("shallow")
if argURL == "" {
cli.ShowCommandHelp(c, "get")
os.Exit(1)
}
url, err := NewURL(argURL)
utils.DieIf(err)
isSSH := c.Bool("p")
if isSSH {
// Assume Git repository if `-p` is given.
url, err = ConvertGitURLHTTPToSSH(url)
utils.DieIf(err)
}
remote, err := NewRemoteRepository(url)
utils.DieIf(err)
if remote.IsValid() == false {
utils.Log("error", fmt.Sprintf("Not a valid repository: %s", url))
os.Exit(1)
}
getRemoteRepository(remote, doUpdate, isShallow)
}
// getRemoteRepository clones or updates a remote repository remote.
// If doUpdate is true, updates the locally cloned repository. Otherwise does nothing.
// If isShallow is true, does shallow cloning. (no effect if already cloned or the VCS is Mercurial)
func getRemoteRepository(remote RemoteRepository, doUpdate bool, isShallow bool) {
remoteURL := remote.URL()
local := LocalRepositoryFromURL(remoteURL)
path := local.FullPath
newPath := false
_, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
newPath = true
err = nil
}
utils.PanicIf(err)
}
if newPath {
utils.Log("clone", fmt.Sprintf("%s -> %s", remoteURL, path))
vcs := remote.VCS()
if vcs == nil {
utils.Log("error", fmt.Sprintf("Could not find version control system: %s", remoteURL))
os.Exit(1)
}
vcs.Clone(remoteURL, path, isShallow)
} else {
if doUpdate {
utils.Log("update", path)
local.VCS().Update(path)
} else {
utils.Log("exists", path)
}
}
}
func doList(c *cli.Context) {
query := c.Args().First()
exact := c.Bool("exact")
printFullPaths := c.Bool("full-path")
printUniquePaths := c.Bool("unique")
var filterFn func(*LocalRepository) bool
if query == "" {
filterFn = func(_ *LocalRepository) bool {
return true
}
} else if exact {
filterFn = func(repo *LocalRepository) bool {
return repo.Matches(query)
}
} else {
filterFn = func(repo *LocalRepository) bool {
return strings.Contains(repo.NonHostPath(), query)
}
}
repos := []*LocalRepository{}
walkLocalRepositories(func(repo *LocalRepository) {
if filterFn(repo) == false {
return
}
repos = append(repos, repo)
})
if printUniquePaths {
subpathCount := map[string]int{} // Count duplicated subpaths (ex. foo/dotfiles and bar/dotfiles)
reposCount := map[string]int{} // Check duplicated repositories among roots
// Primary first
for _, repo := range repos {
if reposCount[repo.RelPath] == 0 {
for _, p := range repo.Subpaths() {
subpathCount[p] = subpathCount[p] + 1
}
}
reposCount[repo.RelPath] = reposCount[repo.RelPath] + 1
}
for _, repo := range repos {
if reposCount[repo.RelPath] > 1 && repo.IsUnderPrimaryRoot() == false {
continue
}
for _, p := range repo.Subpaths() {
if subpathCount[p] == 1 {
fmt.Println(p)
break
}
}
}
} else {
for _, repo := range repos {
if printFullPaths {
fmt.Println(repo.FullPath)
} else {
fmt.Println(repo.RelPath)
}
}
}
}
func doLook(c *cli.Context) {
name := c.Args().First()
if name == "" {
cli.ShowCommandHelp(c, "look")
os.Exit(1)
}
reposFound := []*LocalRepository{}
walkLocalRepositories(func(repo *LocalRepository) {
if repo.Matches(name) {
reposFound = append(reposFound, repo)
}
})
switch len(reposFound) {
case 0:
utils.Log("error", "No repository found")
os.Exit(1)
case 1:
if runtime.GOOS == "windows" {
cmd := exec.Command(os.Getenv("COMSPEC"))
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = reposFound[0].FullPath
err := cmd.Start()
if err == nil {
cmd.Wait()
os.Exit(0)
}
} else {
shell := os.Getenv("SHELL")
if shell == "" {
shell = "/bin/sh"
}
utils.Log("cd", reposFound[0].FullPath)
err := os.Chdir(reposFound[0].FullPath)
utils.PanicIf(err)
syscall.Exec(shell, []string{shell}, syscall.Environ())
}
default:
utils.Log("error", "More than one repositories are found; Try more precise name")
for _, repo := range reposFound {
utils.Log("error", "- "+strings.Join(repo.PathParts, "/"))
}
}
}
func doImport(c *cli.Context) {
var (
doUpdate = c.Bool("update")
isSSH = c.Bool("p")
isShallow = c.Bool("shallow")
)
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line := scanner.Text()
url, err := url.Parse(line)
if err != nil {
utils.Log("error", fmt.Sprintf("Could not parse URL <%s>: %s", line, err))
continue
}
if isSSH {
url, err = ConvertGitURLHTTPToSSH(url)
if err != nil {
utils.Log("error", fmt.Sprintf("Could not convert URL <%s>: %s", url, err))
continue
}
}
remote, err := NewRemoteRepository(url)
if utils.ErrorIf(err) {
continue
}
if remote.IsValid() == false {
utils.Log("error", fmt.Sprintf("Not a valid repository: %s", url))
continue
}
getRemoteRepository(remote, doUpdate, isShallow)
}
if err := scanner.Err(); err != nil {
utils.Log("error", fmt.Sprintf("While reading input: %s", err))
os.Exit(1)
}
}