github.com/ungtb10d/cli/v2@v2.0.0-20221110210412-98537dd9d6a1/pkg/cmd/auth/token/token.go (about) 1 package token 2 3 import ( 4 "fmt" 5 6 "github.com/ungtb10d/cli/v2/internal/config" 7 "github.com/ungtb10d/cli/v2/internal/ghinstance" 8 "github.com/ungtb10d/cli/v2/pkg/cmdutil" 9 "github.com/ungtb10d/cli/v2/pkg/iostreams" 10 "github.com/spf13/cobra" 11 ) 12 13 type TokenOptions struct { 14 IO *iostreams.IOStreams 15 Config func() (config.Config, error) 16 17 Hostname string 18 } 19 20 func NewCmdToken(f *cmdutil.Factory, runF func(*TokenOptions) error) *cobra.Command { 21 opts := &TokenOptions{ 22 IO: f.IOStreams, 23 Config: f.Config, 24 } 25 26 cmd := &cobra.Command{ 27 Use: "token", 28 Short: "Print the auth token gh is configured to use", 29 Args: cobra.ExactArgs(0), 30 RunE: func(cmd *cobra.Command, args []string) error { 31 if runF != nil { 32 return runF(opts) 33 } 34 35 return tokenRun(opts) 36 }, 37 } 38 39 cmd.Flags().StringVarP(&opts.Hostname, "hostname", "h", "", "The hostname of the GitHub instance authenticated with") 40 41 return cmd 42 } 43 44 func tokenRun(opts *TokenOptions) error { 45 hostname := opts.Hostname 46 if hostname == "" { 47 hostname = ghinstance.Default() 48 } 49 50 cfg, err := opts.Config() 51 if err != nil { 52 return err 53 } 54 55 key := "oauth_token" 56 val, err := cfg.GetOrDefault(hostname, key) 57 if err != nil { 58 return fmt.Errorf("no oauth token") 59 } 60 61 if val != "" { 62 fmt.Fprintf(opts.IO.Out, "%s\n", val) 63 } 64 return nil 65 }