Merge pull request #3942 from dscho/complete--repo-flag

Allow auto-completing the `--repo` values
This commit is contained in:
Mislav Marohnić 2021-07-28 17:27:56 +02:00 committed by GitHub
commit 4b499be96b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -2,6 +2,8 @@ package cmdutil
import (
"os"
"sort"
"strings"
"github.com/cli/cli/internal/ghrepo"
"github.com/spf13/cobra"
@ -19,6 +21,34 @@ func executeParentHooks(cmd *cobra.Command, args []string) error {
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, err := config.DefaultHost()
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
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 {