-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.go
More file actions
581 lines (529 loc) Β· 20.2 KB
/
Copy pathcli.go
File metadata and controls
581 lines (529 loc) Β· 20.2 KB
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
package main
import (
"fmt"
"slices"
"strings"
"github.com/alecthomas/kong"
clib "github.com/gechr/clib/cli/kong"
"github.com/gechr/clib/help"
"github.com/gechr/clib/theme"
"github.com/gechr/clog"
"github.com/gechr/conductor"
cli "github.com/gechr/conductor/cli/kong"
"github.com/gechr/forge"
"github.com/gechr/x/ansi"
xslices "github.com/gechr/x/slices"
xstrings "github.com/gechr/x/strings"
)
const (
defaultParallelism = 20
keywordAll = "all"
methodSSH = forge.SchemeSSH
methodHTTPS = forge.SchemeHTTPS
nameGit = "git"
nameJJ = "jj"
vcsGit = nameGit
vcsJJ = nameJJ
mirrorDocsURL = "https://docs.github.com/en/repositories/creating-and-managing-repositories/duplicating-a-repository"
)
type CLI struct {
clib.CompletionFlags
cli.SelfUpdateFlag
Repos []string `name:"repo" help:"Repositories to clone." arg:"" optional:""`
Owner string `help:"GitHub owner/organization" short:"O" aliases:"org,organization" placeholder:"<owner>" clib:"terse='Owner/org',group='Filters/1'" env:"CLONE_OWNER"`
Archived bool `help:"Include archived repositories" aliases:"archive,archives" clib:"terse='Include archived',group='Filters/2'"`
Forked bool `help:"Include forked repositories" aliases:"fork,forks" clib:"terse='Include forked',group='Filters/2'"`
Languages []string `help:"Filter by language (repeatable)" clib:"terse='Language',group='Filters/2'" name:"language" short:"l" placeholder:"<lang>"`
Topics []string `help:"Filter by topic (repeatable)" clib:"terse='Topic',group='Filters/2'" name:"topic" short:"t" placeholder:"<topic>"`
Stars string "help:\"Filter by star count (e.g. `5`, `>=5`, `<10`, `5..50`)\" clib:\"terse='Stars',group='Filters/2'\" placeholder:\"<expr>\""
Visibility string `help:"Filter by visibility" aliases:"viz" clib:"terse='Visibility',group='Filters/2'" placeholder:"<viz>" default:"all" enum:"all,public,private,internal"`
Starred bool `help:"Clone repositories starred by the user" clib:"terse='Starred',group='Filters/3'"`
Watching bool `help:"Clone repositories watched by the user" clib:"terse='Watching',group='Filters/3'"`
IncludePatterns []string `name:"include-pattern" help:"Only clone repositories matching regex (repeatable)" short:"i" placeholder:"<regex>" clib:"hide-long,terse='Include (regex)',group='Filters/4'"`
Includes []string `name:"include" help:"Only clone repositories by exact name (repeatable)" placeholder:"<name>" clib:"no-indent,terse='Include',group='Filters/4'"`
ExcludePatterns []string `name:"exclude-pattern" help:"Skip repositories matching regex (repeatable)" short:"e" placeholder:"<regex>" clib:"hide-long,terse='Exclude (regex)',group='Filters/5'"`
Excludes []string `name:"exclude" help:"Skip repositories by exact name (repeatable)" placeholder:"<name>" clib:"no-indent,terse='Exclude',group='Filters/5'"`
Branch string `help:"Clone a specific branch" short:"b" aliases:"bookmark" placeholder:"<name>" clib:"terse='Branch',group='Options/1'"`
Depth int `help:"Create a shallow clone of the given depth" placeholder:"<n>" clib:"terse='Depth',group='Options/1'" xor:"shallow"`
Quick bool "help:\"Shallow single-branch clone (alias for `--depth=1 --single-branch`)\" short:\"Q\" clib:\"terse='Quick clone',group='Options/1'\" xor:\"shallow\""
Method string `help:"Clone method" short:"m" placeholder:"<method>" clib:"terse='Clone method',enum='ssh,https',group='Options/1'" default:"ssh" enum:"ssh,https,http" env:"CLONE_METHOD"`
Mirror bool `help:"Create a mirror clone" clib:"terse='Mirror clone',group='Options/1'" xor:"fetch-mirror"`
Forge string `help:"Forge to use for bare owner/repo arguments" placeholder:"<forge>" clib:"terse='Forge',group='Options/2'"`
VCS string `help:"Version control system" placeholder:"<vcs>" clib:"terse='VCS',enum='git,jj',group='Options/2'" default:"git" enum:"git,jj"`
JJ bool "help:\"Clone with `jj` (alias for `--vcs=jj`)\" clib:\"terse='Jujutsu',group='Options/2'\" xor:\"vcs\""
Git bool "help:\"Clone with `git` (alias for `--vcs=git`)\" clib:\"terse='Git',group='Options/2'\" xor:\"vcs\""
Directory string `help:"Clone into a specific directory" short:"d" aliases:"dir" placeholder:"<path>" clib:"terse='Directory',group='Options/3'" xor:"location" type:"path"`
OwnerDir bool `help:"Clone into a subdirectory named after the repository owner" short:"D" clib:"terse='Owner subdirectory',group='Options/3'" env:"CLONE_OWNER_DIR"`
Temp bool `help:"Clone into a temporary directory" short:"T" clib:"terse='Temporary directory',group='Options/3'" xor:"location"`
Print bool "help:\"Print temp directory path to stdout (requires `--temp`; implies `--quiet`)\" clib:\"terse='Print temp path',group='Options/3'\""
Fetch bool `help:"Fetch updates for existing clones instead of skipping" clib:"terse='Fetch existing',group='Options/4'" xor:"fetch-force,fetch-mirror"`
Pull bool `help:"Pull updates for existing clones" clib:"terse='Pull existing',group='Options/4'"`
Force bool `help:"Overwrite existing clones" short:"f" clib:"terse='Force overwrite',group='Options/4'" xor:"fetch-force"`
Parallelism int `help:"Number of parallel clones" short:"P" placeholder:"<n>" clib:"terse='Parallelism',group='Options/4'" default:"20"`
Quiet bool `help:"Suppress informational output" short:"q" clib:"terse='Quiet',group='Miscellaneous/2'" xor:"verbosity"`
Verbose bool `help:"Show additional progress information" short:"v" clib:"terse='Verbose',group='Miscellaneous/2'" xor:"verbosity"`
Debug bool `help:"Show debug logs" clib:"terse='Debug logs',group='Miscellaneous/2'" xor:"verbosity"`
DryRun bool `help:"Show what would be cloned without cloning" short:"n" aliases:"dry" clib:"terse='Dry run',group='Options/5'"`
Color clog.ColorMode `help:"When to use color" aliases:"colour" clib:"terse='Color mode',group='Miscellaneous/1'" default:"auto" enum:"auto,always,never"`
Version bool `help:"Print version" clib:"terse='Version',group='Miscellaneous/3'" short:"V"`
Height float64 `help:"Maximum height as a percentage of the terminal (0.0-1.0)." hidden:"" default:"0.5"`
binGit string `kong:"-"`
binJJ string `kong:"-"`
explicitVCS bool `kong:"-"`
forge forge.Forge `kong:"-"`
StarsFilter rangeFilter `kong:"-"`
LanguageFilters [][]string `kong:"-"`
TopicFilters [][]string `kong:"-"`
}
// ConductorFlags implements [conductor.FlagSource]. Clone's --verbose and
// --quiet steer its own progress output, not clog; only --debug maps to clog
// verbosity.
func (c *CLI) ConductorFlags() conductor.Flags {
return conductor.Flags{Verbose: c.Debug, Color: c.Color}
}
// afterParse applies the post-parse validation and env fallbacks that kong
// cannot express: the --vcs/--git/--jj exclusivity and the CLONE_VCS default.
func (c *CLI) afterParse(kctx *kong.Context) error {
explicitVCS, explicitAlias := explicitVCSFlags(kctx)
if explicitVCS && explicitAlias != "" {
return &userError{
msg: fmt.Sprintf("--%s and --vcs can't be used together", explicitAlias),
exitCode: exitCodeUsage,
}
}
if explicitVCS || explicitAlias != "" {
c.explicitVCS = true
return nil
}
v := envLower(envCloneVCS)
if v == "" {
return nil
}
c.VCS = v
if err := c.Validate(); err != nil {
return &userError{msg: err.Error(), exitCode: exitCodeUsage}
}
return nil
}
func vcsDefault() string {
if v := envLower(envCloneVCS); v != "" {
return v
}
return vcsGit
}
// methodForToken picks the default clone method when the user has set neither
// --method nor CLONE_METHOD. SSH suits a configured account, but it fails on a
// machine with no SSH key - which strongly correlates with having no token
// either - so anonymous use defaults to HTTPS, which clones public
// repositories without any credentials.
func methodForToken(hasToken bool) string {
if hasToken {
return methodSSH
}
return methodHTTPS
}
func (c *CLI) Normalize() {
if c.Method == "http" {
c.Method = methodHTTPS
}
switch {
case c.Git:
c.VCS = vcsGit
case c.JJ:
c.VCS = vcsJJ
case c.VCS == "":
c.VCS = vcsGit
}
c.Languages = xslices.UniqueFold(c.Languages)
if c.Quick && c.Depth == 0 {
c.Depth = 1
}
if c.Print {
c.Quiet = true
}
if c.Forge == "" {
c.Forge = envLower(envCloneForge)
}
}
func (c *CLI) hasRepoSelector() bool {
switch {
case len(c.Repos) > 0,
len(c.Languages) > 0,
len(c.Topics) > 0,
c.StarsFilter.present(),
c.Starred,
c.Watching,
c.Owner != "",
c.Visibility != keywordAll:
return true
}
return false
}
func (c *CLI) validateStarsFilter() error {
if c.Stars == "" {
return nil
}
r, err := parseRangeFilter(c.Stars)
if err != nil {
return fmt.Errorf("--stars: %w", err)
}
c.StarsFilter = r
return nil
}
func (c *CLI) Validate() error {
if c.Version {
return nil
}
c.Normalize()
if c.VCS != vcsGit && c.VCS != vcsJJ {
return fmt.Errorf("--vcs must be one of: git, jj (got %q)", c.VCS)
}
languageGroups, err := parseFilters("language", c.Languages)
if err != nil {
return err
}
var langs []string
for _, group := range languageGroups {
langs = append(langs, group...)
}
c.Languages = xslices.UniqueFold(langs)
if len(c.Languages) > 0 {
c.LanguageFilters = [][]string{c.Languages}
}
topicFilters, err := parseFilters("topic", c.Topics)
if err != nil {
return err
}
c.TopicFilters = uniqueTopicFilters(topicFilters)
if starsErr := c.validateStarsFilter(); starsErr != nil {
return starsErr
}
if !c.hasRepoSelector() {
return fmt.Errorf("at least one repository is required")
}
if c.Print && !c.Temp {
return fmt.Errorf("--print requires --temp")
}
if c.Parallelism < 1 {
return fmt.Errorf("--parallelism must be at least 1")
}
if c.Depth < 0 {
return fmt.Errorf("--depth must be non-negative")
}
if c.Mirror && c.VCS == vcsJJ {
return fmt.Errorf("--mirror is not supported with jj (use --vcs=git)")
}
if c.Pull && c.Mirror {
return fmt.Errorf("--pull and --mirror can't be used together")
}
resolved, err := forge.Resolve(c.Forge)
if err != nil {
return err
}
c.forge = resolved
return c.validateForgeFlags()
}
func (c *CLI) validateForgeFlags() error {
if c.forge.Host == forge.HostGitHub {
return nil
}
var offending []string
if c.Archived {
offending = append(offending, "--archived")
}
if c.Forked {
offending = append(offending, "--forked")
}
if len(c.Languages) > 0 {
offending = append(offending, "--language")
}
if len(c.Topics) > 0 {
offending = append(offending, "--topic")
}
if c.StarsFilter.present() {
offending = append(offending, "--stars")
}
if c.Starred {
offending = append(offending, "--starred")
}
if c.Watching {
offending = append(offending, "--watching")
}
if c.Visibility != "" && c.Visibility != keywordAll {
offending = append(offending, "--visibility")
}
if len(offending) == 0 {
return nil
}
return fmt.Errorf(
"%s is only currently supported for GitHub hosts",
strings.Join(offending, "/"),
)
}
func parseFilters(key string, values []string) ([][]string, error) {
var filters [][]string
for _, value := range values {
if xstrings.IsBlank(value) {
return nil, fmt.Errorf("invalid %s filter %q", key, value)
}
for clause := range strings.SplitSeq(value, ",") {
clause = strings.TrimSpace(clause)
if clause == "" {
return nil, fmt.Errorf("invalid %s filter %q", key, value)
}
var group []string
for option := range strings.SplitSeq(clause, "/") {
option = strings.TrimSpace(option)
if option == "" {
return nil, fmt.Errorf("invalid %s filter %q", key, value)
}
group = append(group, option)
}
filters = append(filters, group)
}
}
return filters, nil
}
func uniqueTopicFilters(filters [][]string) [][]string {
folded := xslices.Map(filters, xslices.UniqueFold)
return xslices.UniqueFunc(folded, func(group []string) string {
keyParts := xslices.Map(group, func(option string) string {
return strings.ToLower(strings.TrimSpace(option))
})
slices.SortFunc(keyParts, xstrings.CompareNatural)
return strings.Join(keyParts, "\x00")
})
}
// setMethodDefault overrides the --method flag's parse default with the
// auth-aware choice. See methodForToken.
func setMethodDefault(parser *kong.Kong) {
method := methodForToken(githubToken() != "")
for _, flag := range parser.Model.Flags {
if flag.Name == "method" {
flag.Default = method
return
}
}
}
func explicitVCSFlags(ctx *kong.Context) (bool, string) {
var explicitVCS bool
var explicitAlias string
for _, path := range ctx.Path {
if path.Flag == nil || path.Resolved {
continue
}
switch path.Flag.Name {
case "vcs":
explicitVCS = true
case "git", "jj":
explicitAlias = path.Flag.Name
}
}
return explicitVCS, explicitAlias
}
func cloneHelpSections(th *theme.Theme) func(*kong.Context) ([]help.Section, error) {
return func(ctx *kong.Context) ([]help.Section, error) {
sections, err := clib.NodeSections(ctx, clib.WithArguments(&CLI{}))
if err != nil {
return nil, err
}
replaceHelpSectionContent(sections, "Usage", styledUsageText(th))
replaceHelpSectionContent(sections, "Arguments", styledArgumentsText(th))
patchHelpFlag(sections, "mirror", func(flag *help.Flag) {
flag.Desc = fmt.Sprintf(
"Create a %s clone (git only)",
ansi.Auto().Hyperlink(mirrorDocsURL, "mirror"),
)
})
patchHelpFlag(sections, "vcs", func(flag *help.Flag) {
flag.EnumDefault = vcsDefault()
})
patchHelpFlag(sections, "method", func(flag *help.Flag) {
flag.EnumDefault = methodForToken(githubToken() != "")
})
return sections, nil
}
}
func cloneHelpOrdering() help.Option {
return help.OptionFunc(func(sections []help.Section) []help.Section {
for i := range sections {
if sections[i].Title != "Miscellaneous" {
continue
}
var (
otherGroups []help.Content
helpGroup help.Content
versionGroup help.Content
)
for _, content := range sections[i].Content {
flagGroup, ok := content.(help.FlagGroup)
if !ok {
otherGroups = append(otherGroups, content)
continue
}
switch {
case flagGroupHasLong(flagGroup, "version"):
versionGroup = content
case flagGroupHasLong(flagGroup, "help") || flagGroupHasShort(flagGroup, "h"):
helpGroup = content
default:
otherGroups = append(otherGroups, content)
}
}
if versionGroup != nil {
otherGroups = append(otherGroups, versionGroup)
}
if helpGroup != nil {
otherGroups = append(otherGroups, helpGroup)
}
sections[i].Content = otherGroups
break
}
return sections
})
}
func replaceHelpSectionContent(sections []help.Section, title string, content help.Content) {
for i := range sections {
if sections[i].Title != title {
continue
}
sections[i].Content = []help.Content{content}
return
}
}
func patchHelpFlag(sections []help.Section, long string, fn func(*help.Flag)) {
for i := range sections {
for j, content := range sections[i].Content {
flagGroup, ok := content.(help.FlagGroup)
if !ok {
continue
}
changed := false
for k := range flagGroup {
if flagGroup[k].Long != long {
continue
}
fn(&flagGroup[k])
changed = true
}
if changed {
sections[i].Content[j] = flagGroup
return
}
}
}
}
func flagGroupHasLong(flagGroup help.FlagGroup, long string) bool {
for _, flag := range flagGroup {
if flag.Long == long {
return true
}
}
return false
}
func flagGroupHasShort(flagGroup help.FlagGroup, short string) bool {
for _, flag := range flagGroup {
if flag.Short == short {
return true
}
}
return false
}
func styledUsageText(th *theme.Theme) help.Text {
return help.Text(fmt.Sprintf(
"%s %s %s",
th.HelpCommand.Render("clone"),
th.HelpFlag.Render("[options]"),
th.HelpArg.Render("[<owner>/]<repo>[=<dir>]β¦"),
))
}
func styledArgumentsText(th *theme.Theme) help.Text {
return help.Text(fmt.Sprintf(
`%s
Repositories to clone (use %s to clone everything)
If specified, %s takes precedence over the %s flag
Use %s to override the local directory name`,
th.HelpArg.Render("[<owner>/<repo>[=<dir>]]"),
th.HelpArg.Render("all"),
th.HelpArg.Render("<owner>"),
th.HelpFlag.Render("--owner"),
th.HelpArg.Render("=<dir>"),
))
}
func buildExamplesSection() help.Section {
return help.Section{
Title: "Examples",
Content: []help.Content{
help.Examples{
{
Comment: "Clone a specific repository",
Command: "clone owner/repo",
},
{
Comment: "Clone multiple repositories",
Command: "clone owner/repo-one owner/repo-two",
},
{
Comment: "Clone all Go repositories",
Command: "clone --language=Go",
},
{
Comment: "Clone specific repos only if they match filter",
Command: "clone repo-a repo-b --language=Go",
},
{
Comment: "Quick shallow clone (no history, default branch only)",
Command: "clone --quick owner/repo",
},
{
Comment: "Clone a repository from a different owner",
Command: "clone other-owner/repo",
},
{
Comment: "Clone into a custom directory name",
Command: "clone owner/repo=local-dir",
},
{
Comment: "Clone all repositories from a different owner",
Command: "clone -O other-owner all",
},
{
Comment: "Clone into a specific directory",
Command: "clone -d ~/projects/go --language=Go",
},
{
Comment: "Preserve owner/repository directory structure",
Command: "clone -D gechr/clone",
},
{
Comment: "Clone a specific branch with shallow depth",
Command: "clone --branch=main --depth=1 owner/repo",
},
{
Comment: "Clone using HTTPS instead of SSH",
Command: "clone --method=https owner/repo",
},
{
Comment: "Clone from a GitHub URL",
Command: "clone https://github.com/owner/repo",
},
{
Comment: "Clone a pull request (checks out the PR branch)",
Command: "clone https://github.com/owner/repo/pull/21",
},
{
Comment: "Clone a PR using shorthand",
Command: "clone owner/repo#21",
},
{
Comment: "Clone from an SSH clone URL",
Command: "clone git@github.com:owner/repo.git",
},
{
Comment: "Fetch existing repos, clone new ones",
Command: "clone --fetch --language=Go",
},
},
},
}
}