|
| 1 | +package add |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "net/http" |
| 8 | + "os" |
| 9 | + |
| 10 | + "github.com/cli/cli/internal/ghinstance" |
| 11 | + "github.com/cli/cli/pkg/cmdutil" |
| 12 | + "github.com/cli/cli/pkg/iostreams" |
| 13 | + "github.com/spf13/cobra" |
| 14 | +) |
| 15 | + |
| 16 | +type AddOptions struct { |
| 17 | + IO *iostreams.IOStreams |
| 18 | + HTTPClient func() (*http.Client, error) |
| 19 | + |
| 20 | + KeyFile string |
| 21 | + Title string |
| 22 | +} |
| 23 | + |
| 24 | +func NewCmdAdd(f *cmdutil.Factory, runF func(*AddOptions) error) *cobra.Command { |
| 25 | + opts := &AddOptions{ |
| 26 | + HTTPClient: f.HttpClient, |
| 27 | + IO: f.IOStreams, |
| 28 | + } |
| 29 | + |
| 30 | + cmd := &cobra.Command{ |
| 31 | + Use: "add [<key-file>]", |
| 32 | + Short: "Add an SSH key to your GitHub account", |
| 33 | + Args: cobra.MaximumNArgs(1), |
| 34 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 35 | + if len(args) == 0 { |
| 36 | + if opts.IO.IsStdoutTTY() && opts.IO.IsStdinTTY() { |
| 37 | + return &cmdutil.FlagError{Err: errors.New("public key file missing")} |
| 38 | + } |
| 39 | + opts.KeyFile = "-" |
| 40 | + } else { |
| 41 | + opts.KeyFile = args[0] |
| 42 | + } |
| 43 | + |
| 44 | + if runF != nil { |
| 45 | + return runF(opts) |
| 46 | + } |
| 47 | + return runAdd(opts) |
| 48 | + }, |
| 49 | + } |
| 50 | + |
| 51 | + cmd.Flags().StringVarP(&opts.Title, "title", "t", "", "Title for the new key") |
| 52 | + return cmd |
| 53 | +} |
| 54 | + |
| 55 | +func runAdd(opts *AddOptions) error { |
| 56 | + httpClient, err := opts.HTTPClient() |
| 57 | + if err != nil { |
| 58 | + return err |
| 59 | + } |
| 60 | + |
| 61 | + var keyReader io.Reader |
| 62 | + if opts.KeyFile == "-" { |
| 63 | + keyReader = opts.IO.In |
| 64 | + defer opts.IO.In.Close() |
| 65 | + } else { |
| 66 | + f, err := os.Open(opts.KeyFile) |
| 67 | + if err != nil { |
| 68 | + return err |
| 69 | + } |
| 70 | + defer f.Close() |
| 71 | + keyReader = f |
| 72 | + } |
| 73 | + |
| 74 | + hostname := ghinstance.OverridableDefault() |
| 75 | + err = SSHKeyUpload(httpClient, hostname, keyReader, opts.Title) |
| 76 | + if err != nil { |
| 77 | + if errors.Is(err, scopesError) { |
| 78 | + cs := opts.IO.ColorScheme() |
| 79 | + fmt.Fprint(opts.IO.ErrOut, "Error: insufficient OAuth scopes to list SSH keys\n") |
| 80 | + fmt.Fprintf(opts.IO.ErrOut, "Run the following to grant scopes: %s\n", cs.Bold("gh auth refresh -s write:public_key")) |
| 81 | + return cmdutil.SilentError |
| 82 | + } |
| 83 | + return err |
| 84 | + } |
| 85 | + |
| 86 | + if opts.IO.IsStdoutTTY() { |
| 87 | + cs := opts.IO.ColorScheme() |
| 88 | + fmt.Fprintf(opts.IO.ErrOut, "%s Public key added to your account\n", cs.SuccessIcon()) |
| 89 | + } |
| 90 | + return nil |
| 91 | +} |
0 commit comments