forked from cli/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd.go
More file actions
95 lines (81 loc) · 1.82 KB
/
add.go
File metadata and controls
95 lines (81 loc) · 1.82 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
package add
import (
"fmt"
"io"
"net/http"
"os"
"github.com/cli/cli/v2/internal/config"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type AddOptions struct {
IO *iostreams.IOStreams
Config func() (config.Config, error)
HTTPClient func() (*http.Client, error)
KeyFile string
Title string
}
func NewCmdAdd(f *cmdutil.Factory, runF func(*AddOptions) error) *cobra.Command {
opts := &AddOptions{
HTTPClient: f.HttpClient,
Config: f.Config,
IO: f.IOStreams,
}
cmd := &cobra.Command{
Use: "add [<key-file>]",
Short: "Add an SSH key to your GitHub account",
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
if opts.IO.IsStdoutTTY() && opts.IO.IsStdinTTY() {
return cmdutil.FlagErrorf("public key file missing")
}
opts.KeyFile = "-"
} else {
opts.KeyFile = args[0]
}
if runF != nil {
return runF(opts)
}
return runAdd(opts)
},
}
cmd.Flags().StringVarP(&opts.Title, "title", "t", "", "Title for the new key")
return cmd
}
func runAdd(opts *AddOptions) error {
httpClient, err := opts.HTTPClient()
if err != nil {
return err
}
var keyReader io.Reader
if opts.KeyFile == "-" {
keyReader = opts.IO.In
defer opts.IO.In.Close()
} else {
f, err := os.Open(opts.KeyFile)
if err != nil {
return err
}
defer f.Close()
keyReader = f
}
cfg, err := opts.Config()
if err != nil {
return err
}
hostname, err := cfg.DefaultHost()
if err != nil {
return err
}
err = SSHKeyUpload(httpClient, hostname, keyReader, opts.Title)
if err != nil {
return err
}
if opts.IO.IsStdoutTTY() {
cs := opts.IO.ColorScheme()
fmt.Fprintf(opts.IO.ErrOut, "%s Public key added to your account\n", cs.SuccessIcon())
}
return nil
}