forked from x-motemen/ghq
/
commands.go
409 lines (340 loc) · 9.52 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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
package main
import (
"fmt"
"net/url"
"os"
"strings"
"syscall"
"github.com/codegangsta/cli"
"github.com/google/go-github/github"
"github.com/motemen/ghq/pocket"
"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.
`,
Action: doGet,
Flags: []cli.Flag{
cli.BoolFlag{"update, u", "Update local repository if cloned already"},
},
}
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{"exact, e", "Perform an exact match"},
cli.BoolFlag{"full-path, p", "Print full paths"},
cli.BoolFlag{"unique", "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: "Import repositories from other web services",
Subcommands: []cli.Command{
commandImportStarred,
commandImportPocket,
},
}
var commandImportStarred = cli.Command{
Name: "starred",
Usage: "Get all starred GitHub repositories",
Description: `
Retrieves GitHub repositories that are starred by the user specified and
performs 'get' for each of them.
`,
Action: doImportStarred,
Flags: []cli.Flag{
cli.BoolFlag{"update, u", "Update local repository if cloned already"},
},
}
var commandImportPocket = cli.Command{
Name: "pocket",
Usage: "Get all github.com entries in Pocket",
Description: `
Retrieves Pocket <http://getpocket.com/> entries of github.com and
performs 'get' for each of them.
`,
Action: doImportPocket,
Flags: []cli.Flag{
cli.BoolFlag{"update, u", "Update local repository if cloned already"},
},
}
type commandDoc struct {
Parent string
Arguments string
}
var commandDocs = map[string]commandDoc{
"get": {"", "[-u] <repository URL> | <user>/<project>"},
"list": {"", "[-p] [-e] [<query>]"},
"look": {"", "<project> | <user>/<project> | <host>/<user>/<project>"},
"import": {"", "[-u] starred <user> | pocket"},
"starred": {"import", "[-u] <user>"},
"pocket": {"import", "[-u]"},
}
// Makes template conditionals to generate per-command documents.
func mkCommandsTemplate(genTemplate func(commandDoc) string) string {
template := "{{if false}}"
for _, command := range append(Commands, commandImportStarred, commandImportPocket) {
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")
if argURL == "" {
cli.ShowCommandHelp(c, "get")
os.Exit(1)
}
url, err := url.Parse(argURL)
utils.DieIf(err)
if !url.IsAbs() {
url.Scheme = "https"
url.Host = "github.com"
if url.Path[0] != '/' {
url.Path = "/" + url.Path
}
}
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)
}
func getRemoteRepository(remote RemoteRepository, doUpdate 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))
remote.VCS().Clone(remoteURL, path)
} 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")
case 1:
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 doImportStarred(c *cli.Context) {
user := c.Args().First()
if user == "" {
cli.ShowCommandHelp(c, "starred")
os.Exit(1)
}
client := github.NewClient(nil)
options := &github.ActivityListStarredOptions{Sort: "created"}
for page := 1; ; page++ {
options.Page = page
repositories, res, err := client.Activity.ListStarred(user, options)
utils.DieIf(err)
utils.Log("page", fmt.Sprintf("%d/%d", page, res.LastPage))
for _, repo := range repositories {
url, err := url.Parse(*repo.HTMLURL)
if err != nil {
utils.Log("error", fmt.Sprintf("Could not parse URL <%s>: %s", repo.HTMLURL, err))
continue
}
remote, err := NewRemoteRepository(url)
if utils.ErrorIf(err) {
continue
}
if remote.IsValid() == false {
utils.Log("skip", fmt.Sprintf("Not a valid repository: %s", url))
continue
}
getRemoteRepository(remote, c.Bool("update"))
}
if page >= res.LastPage {
break
}
}
}
func doImportPocket(c *cli.Context) {
if pocket.ConsumerKey == "" {
utils.Log("error", "Built without consumer key set")
return
}
accessToken, err := GitConfig("ghq.pocket.token")
utils.PanicIf(err)
if accessToken == "" {
receiverURL, ch, err := pocket.StartAccessTokenReceiver()
utils.PanicIf(err)
utils.Log("pocket", "Waiting for Pocket authentication callback at "+receiverURL)
utils.Log("pocket", "Obtaining request token")
authRequest, err := pocket.ObtainRequestToken(receiverURL)
utils.DieIf(err)
url := pocket.GenerateAuthorizationURL(authRequest.Code, receiverURL)
utils.Log("open", url)
<-ch
utils.Log("pocket", "Obtaining access token")
authorized, err := pocket.ObtainAccessToken(authRequest.Code)
utils.DieIf(err)
utils.Log("authorized", authorized.Username)
accessToken = authorized.AccessToken
utils.Run("git", "config", "ghq.pocket.token", authorized.AccessToken)
}
utils.Log("pocket", "Retrieving github.com entries")
res, err := pocket.RetrieveGitHubEntries(accessToken)
utils.DieIf(err)
for _, item := range res.List {
url, err := url.Parse(item.ResolvedURL)
if err != nil {
utils.Log("error", fmt.Sprintf("Could not parse URL <%s>: %s", item.ResolvedURL, err))
continue
}
remote, err := NewRemoteRepository(url)
if utils.ErrorIf(err) {
continue
}
if remote.IsValid() == false {
utils.Log("skip", fmt.Sprintf("Not a valid repository: %s", url))
continue
}
getRemoteRepository(remote, c.Bool("update"))
}
}