-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
repo_override.go
70 lines (62 loc) · 1.8 KB
/
repo_override.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
package cmdutil
import (
"os"
"sort"
"strings"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/spf13/cobra"
)
func executeParentHooks(cmd *cobra.Command, args []string) error {
for cmd.HasParent() {
cmd = cmd.Parent()
if cmd.PersistentPreRunE != nil {
return cmd.PersistentPreRunE(cmd, args)
}
}
return nil
}
func EnableRepoOverride(cmd *cobra.Command, f *Factory) {
cmd.PersistentFlags().StringP("repo", "R", "", "Select another repository using the `[HOST/]OWNER/REPO` format")
_ = cmd.RegisterFlagCompletionFunc("repo", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
remotes, err := f.Remotes()
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
config, err := f.Config()
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
defaultHost, _ := config.Authentication().DefaultHost()
var results []string
for _, remote := range remotes {
repo := remote.RepoOwner() + "/" + remote.RepoName()
if !strings.EqualFold(remote.RepoHost(), defaultHost) {
repo = remote.RepoHost() + "/" + repo
}
if strings.HasPrefix(repo, toComplete) {
results = append(results, repo)
}
}
sort.Strings(results)
return results, cobra.ShellCompDirectiveNoFileComp
})
cmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
if err := executeParentHooks(cmd, args); err != nil {
return err
}
repoOverride, _ := cmd.Flags().GetString("repo")
f.BaseRepo = OverrideBaseRepoFunc(f, repoOverride)
return nil
}
}
func OverrideBaseRepoFunc(f *Factory, override string) func() (ghrepo.Interface, error) {
if override == "" {
override = os.Getenv("GH_REPO")
}
if override != "" {
return func() (ghrepo.Interface, error) {
return ghrepo.FromFullName(override)
}
}
return f.BaseRepo
}