Skip to content

Commit

Permalink
cmd: use spf13/cobra for dexctl cli logic
Browse files Browse the repository at this point in the history
  • Loading branch information
ericchiang committed Dec 28, 2015
1 parent 71f5021 commit 8e5115c
Show file tree
Hide file tree
Showing 5 changed files with 139 additions and 218 deletions.
16 changes: 9 additions & 7 deletions cmd/dexctl/command_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,24 @@ import (
"net/url"

"github.com/coreos/go-oidc/oidc"
"github.com/spf13/cobra"
)

var (
cmdNewClient = &command{
Name: "new-client",
Summary: "Create a new client with the provided redirect URL(s)",
Usage: "<URL>...",
Run: runNewClient,
cmdNewClient = &cobra.Command{
Use: "new-client",
Short: "Create a new client with one or more redirect URLs.",
Long: "Create a new client with one or more redirect URLs,",
Example: ` dexctl new-client --db-url=${DB_URL} 'https://example.com/callback'`,
Run: wrapRun(runNewClient),
}
)

func init() {
commands = append(commands, cmdNewClient)
rootCmd.AddCommand(cmdNewClient)
}

func runNewClient(args []string) int {
func runNewClient(cmd *cobra.Command, args []string) int {
if len(args) < 1 {
stderr("Provide at least one redirect URL.")
return 2
Expand Down
31 changes: 17 additions & 14 deletions cmd/dexctl/command_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,30 +4,33 @@ import (
"fmt"

"github.com/coreos/dex/connector"
"github.com/spf13/cobra"
)

var (
cmdGetConnectorConfigs = &command{
Name: "get-connector-configs",
Summary: "Enumerate current IdP connector configs.",
Usage: "",
Run: runGetConnectorConfigs,
cmdGetConnectorConfigs = &cobra.Command{
Use: "get-connector-configs",
Short: "Enumerate current IdP connector configs.",
Long: "Enumerate current IdP connector configs.",
Example: ` dexctl get-connector-configs --db-url=${DB_URL}`,
Run: wrapRun(runGetConnectorConfigs),
}

cmdSetConnectorConfigs = &command{
Name: "set-connector-configs",
Summary: "Overwrite the current IdP connector configs with those from a local file.",
Usage: "<FILE>",
Run: runSetConnectorConfigs,
cmdSetConnectorConfigs = &cobra.Command{
Use: "set-connector-configs",
Short: "Overwrite the current IdP connector configs with those from a local file.",
Long: "Overwrite the current IdP connector configs with those from a local file.",
Example: ` dexctl set-connector-configs --db-url=${DB_URL} ./static/conn_conf.json`,
Run: wrapRun(runSetConnectorConfigs),
}
)

func init() {
commands = append(commands, cmdSetConnectorConfigs)
commands = append(commands, cmdGetConnectorConfigs)
rootCmd.AddCommand(cmdGetConnectorConfigs)
rootCmd.AddCommand(cmdSetConnectorConfigs)
}

func runSetConnectorConfigs(args []string) int {
func runSetConnectorConfigs(cmd *cobra.Command, args []string) int {
if len(args) != 1 {
stderr("Provide a single argument.")
return 2
Expand Down Expand Up @@ -55,7 +58,7 @@ func runSetConnectorConfigs(args []string) int {
return 0
}

func runGetConnectorConfigs(args []string) int {
func runGetConnectorConfigs(cmd *cobra.Command, args []string) int {
if len(args) != 0 {
stderr("Provide zero arguments.")
return 2
Expand Down
135 changes: 0 additions & 135 deletions cmd/dexctl/command_help.go

This file was deleted.

103 changes: 41 additions & 62 deletions cmd/dexctl/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,46 @@ package main

import (
"errors"
"flag"
"net/http"
"os"
"strings"

pflag "github.com/coreos/dex/pkg/flag"
"github.com/coreos/dex/pkg/log"
"github.com/coreos/go-oidc/oidc"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)

var (
cliName = "dexctl"
cliDescription = "???"

commands []*command
globalFS = flag.NewFlagSet(cliName, flag.ExitOnError)
rootCmd = &cobra.Command{
Use: "dexctl",
Short: "A command line tool for interacting with the dex system",
Long: "",
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
// initialize flags from environment
fs := cmd.Flags()

// don't override flags set by command line flags
alreadySet := make(map[string]bool)
fs.Visit(func(f *pflag.Flag) { alreadySet[f.Name] = true })

var err error
fs.VisitAll(func(f *pflag.Flag) {
if err != nil || alreadySet[f.Name] {
return
}
key := "DEXCTL_" + strings.ToUpper(strings.Replace(f.Name, "-", "_", -1))
if val := os.Getenv(key); val != "" {
err = fs.Set(f.Name, val)
}
})
return err
},
Run: func(cmd *cobra.Command, args []string) {
cmd.Help()
os.Exit(2)
},
}

global struct {
endpoint string
Expand All @@ -30,69 +55,23 @@ var (
func init() {
log.EnableTimestamps()

globalFS.StringVar(&global.endpoint, "endpoint", "", "URL of dex API")
globalFS.StringVar(&global.creds.ID, "client-id", "", "dex API user ID")
globalFS.StringVar(&global.creds.Secret, "client-secret", "", "dex API user password")
globalFS.StringVar(&global.dbURL, "db-url", "", "DSN-formatted database connection string")
globalFS.BoolVar(&global.help, "help", false, "Print usage information and exit")
globalFS.BoolVar(&global.help, "h", false, "Print usage information and exit")
globalFS.BoolVar(&global.logDebug, "log-debug", false, "Log debug-level information")
rootCmd.PersistentFlags().StringVar(&global.endpoint, "endpoint", "", "URL of dex API")
rootCmd.PersistentFlags().StringVar(&global.creds.ID, "client-id", "", "dex API user ID")
rootCmd.PersistentFlags().StringVar(&global.creds.Secret, "client-secret", "", "dex API user password")
rootCmd.PersistentFlags().StringVar(&global.dbURL, "db-url", "", "DSN-formatted database connection string")
rootCmd.PersistentFlags().BoolVar(&global.logDebug, "log-debug", false, "Log debug-level information")
}

func main() {
err := parseFlags()
if err != nil {
stderr(err.Error())
os.Exit(2)
}

if global.logDebug {
log.EnableDebug()
}

args := globalFS.Args()
if len(args) < 1 || global.help {
args = []string{"help"}
}

var cmd *command
for _, c := range commands {
if c.Name == args[0] {
cmd = c
if err := c.Flags.Parse(args[1:]); err != nil {
stderr("%v", err)
os.Exit(2)
}
break
}
}

if cmd == nil {
stderr("%v: unknown subcommand: %q", cliName, args[0])
stderr("Run '%v help' for usage.", cliName)
if err := rootCmd.Execute(); err != nil {
os.Exit(2)
}

os.Exit(cmd.Run(cmd.Flags.Args()))
}

type command struct {
Name string // Name of the command and the string to use to invoke it
Summary string // One-sentence summary of what the command does
Usage string // Usage options/arguments
Description string // Detailed description of command
Flags flag.FlagSet // Set of flags associated with this command

Run func(args []string) int // Run a command with the given arguments, return exit status

}

func parseFlags() error {
if err := globalFS.Parse(os.Args[1:]); err != nil {
return err
func wrapRun(run func(cmd *cobra.Command, args []string) int) func(cmd *cobra.Command, args []string) {
return func(cmd *cobra.Command, args []string) {
os.Exit(run(cmd, args))
}

return pflag.SetFlagsFromEnv(globalFS, "DEXCTL")
}

func getDriver() (drv driver) {
Expand Down
Loading

0 comments on commit 8e5115c

Please sign in to comment.