github.com/ungtb10d/cli/v2@v2.0.0-20221110210412-98537dd9d6a1/pkg/cmd/auth/setupgit/setupgit.go (about) 1 package setupgit 2 3 import ( 4 "fmt" 5 "strings" 6 7 "github.com/ungtb10d/cli/v2/internal/config" 8 "github.com/ungtb10d/cli/v2/pkg/cmd/auth/shared" 9 "github.com/ungtb10d/cli/v2/pkg/cmdutil" 10 "github.com/ungtb10d/cli/v2/pkg/iostreams" 11 "github.com/spf13/cobra" 12 ) 13 14 type gitConfigurator interface { 15 Setup(hostname, username, authToken string) error 16 } 17 18 type SetupGitOptions struct { 19 IO *iostreams.IOStreams 20 Config func() (config.Config, error) 21 Hostname string 22 gitConfigure gitConfigurator 23 } 24 25 func NewCmdSetupGit(f *cmdutil.Factory, runF func(*SetupGitOptions) error) *cobra.Command { 26 opts := &SetupGitOptions{ 27 IO: f.IOStreams, 28 Config: f.Config, 29 } 30 31 cmd := &cobra.Command{ 32 Short: "Configure git to use GitHub CLI as a credential helper", 33 Use: "setup-git", 34 RunE: func(cmd *cobra.Command, args []string) error { 35 opts.gitConfigure = &shared.GitCredentialFlow{ 36 Executable: f.Executable(), 37 GitClient: f.GitClient, 38 } 39 40 if runF != nil { 41 return runF(opts) 42 } 43 return setupGitRun(opts) 44 }, 45 } 46 47 cmd.Flags().StringVarP(&opts.Hostname, "hostname", "h", "", "The hostname to configure git for") 48 49 return cmd 50 } 51 52 func setupGitRun(opts *SetupGitOptions) error { 53 cfg, err := opts.Config() 54 if err != nil { 55 return err 56 } 57 58 hostnames := cfg.Hosts() 59 60 stderr := opts.IO.ErrOut 61 cs := opts.IO.ColorScheme() 62 63 if len(hostnames) == 0 { 64 fmt.Fprintf( 65 stderr, 66 "You are not logged into any GitHub hosts. Run %s to authenticate.\n", 67 cs.Bold("gh auth login"), 68 ) 69 70 return cmdutil.SilentError 71 } 72 73 hostnamesToSetup := hostnames 74 75 if opts.Hostname != "" { 76 if !has(opts.Hostname, hostnames) { 77 return fmt.Errorf("You are not logged into the GitHub host %q\n", opts.Hostname) 78 } 79 hostnamesToSetup = []string{opts.Hostname} 80 } 81 82 for _, hostname := range hostnamesToSetup { 83 if err := opts.gitConfigure.Setup(hostname, "", ""); err != nil { 84 return fmt.Errorf("failed to set up git credential helper: %w", err) 85 } 86 } 87 88 return nil 89 } 90 91 func has(needle string, haystack []string) bool { 92 for _, s := range haystack { 93 if strings.EqualFold(s, needle) { 94 return true 95 } 96 } 97 return false 98 }