github.com/ungtb10d/cli/v2@v2.0.0-20221110210412-98537dd9d6a1/pkg/cmd/repo/deploy-key/add/add.go (about) 1 package add 2 3 import ( 4 "fmt" 5 "io" 6 "net/http" 7 "os" 8 9 "github.com/MakeNowJust/heredoc" 10 "github.com/ungtb10d/cli/v2/internal/ghrepo" 11 "github.com/ungtb10d/cli/v2/pkg/cmdutil" 12 "github.com/ungtb10d/cli/v2/pkg/iostreams" 13 "github.com/spf13/cobra" 14 ) 15 16 type AddOptions struct { 17 IO *iostreams.IOStreams 18 HTTPClient func() (*http.Client, error) 19 BaseRepo func() (ghrepo.Interface, error) 20 21 KeyFile string 22 Title string 23 AllowWrite bool 24 } 25 26 func NewCmdAdd(f *cmdutil.Factory, runF func(*AddOptions) error) *cobra.Command { 27 opts := &AddOptions{ 28 HTTPClient: f.HttpClient, 29 IO: f.IOStreams, 30 } 31 32 cmd := &cobra.Command{ 33 Use: "add <key-file>", 34 Short: "Add a deploy key to a GitHub repository", 35 Long: heredoc.Doc(` 36 Add a deploy key to a GitHub repository. 37 38 Note that any key added by gh will be associated with the current authentication token. 39 If you de-authorize the GitHub CLI app or authentication token from your account, any 40 deploy keys added by GitHub CLI will be removed as well. 41 `), 42 Example: heredoc.Doc(` 43 # generate a passwordless SSH key and add it as a deploy key to a repository 44 $ ssh-keygen -t ed25519 -C "my description" -N "" -f ~/.ssh/gh-test 45 $ gh repo deploy-key add ~/.ssh/gh-test.pub 46 `), 47 Args: cobra.ExactArgs(1), 48 RunE: func(cmd *cobra.Command, args []string) error { 49 opts.BaseRepo = f.BaseRepo 50 opts.KeyFile = args[0] 51 52 if runF != nil { 53 return runF(opts) 54 } 55 return addRun(opts) 56 }, 57 } 58 59 cmd.Flags().StringVarP(&opts.Title, "title", "t", "", "Title of the new key") 60 cmd.Flags().BoolVarP(&opts.AllowWrite, "allow-write", "w", false, "Allow write access for the key") 61 return cmd 62 } 63 64 func addRun(opts *AddOptions) error { 65 httpClient, err := opts.HTTPClient() 66 if err != nil { 67 return err 68 } 69 70 var keyReader io.Reader 71 if opts.KeyFile == "-" { 72 keyReader = opts.IO.In 73 defer opts.IO.In.Close() 74 } else { 75 f, err := os.Open(opts.KeyFile) 76 if err != nil { 77 return err 78 } 79 defer f.Close() 80 keyReader = f 81 } 82 83 repo, err := opts.BaseRepo() 84 if err != nil { 85 return err 86 } 87 88 if err := uploadDeployKey(httpClient, repo, keyReader, opts.Title, opts.AllowWrite); err != nil { 89 return err 90 } 91 92 if !opts.IO.IsStdoutTTY() { 93 return nil 94 } 95 96 cs := opts.IO.ColorScheme() 97 _, err = fmt.Fprintf(opts.IO.Out, "%s Deploy key added to %s\n", cs.SuccessIcon(), cs.Bold(ghrepo.FullName(repo))) 98 return err 99 }