From 6592c4784b8058499b18574ca9529f9d0c7266ee Mon Sep 17 00:00:00 2001 From: Mariano Cano Date: Mon, 18 Mar 2019 12:38:19 -0700 Subject: [PATCH] Fix flag parsing after the configuration file Fixes #52 --- cmd/step-ca/main.go | 78 +++++++++++++++++++++++++-------------------- 1 file changed, 44 insertions(+), 34 deletions(-) diff --git a/cmd/step-ca/main.go b/cmd/step-ca/main.go index 6bdf3497..2513b552 100644 --- a/cmd/step-ca/main.go +++ b/cmd/step-ca/main.go @@ -2,6 +2,7 @@ package main import ( "bytes" + "flag" "fmt" "io/ioutil" "log" @@ -143,40 +144,12 @@ intermediate private key.`, } app.Action = func(ctx *cli.Context) error { - passFile := ctx.String("password-file") - - // If zero cmd line args show help, if >1 cmd line args show error. - if ctx.NArg() == 0 { - return cli.ShowAppHelp(ctx) - } - if err := errs.NumberOfArguments(ctx, 1); err != nil { - return err - } - - configFile := ctx.Args().Get(0) - config, err := authority.LoadConfiguration(configFile) - if err != nil { - fatal(err) - } - - var password []byte - if passFile != "" { - if password, err = ioutil.ReadFile(passFile); err != nil { - fatal(errors.Wrapf(err, "error reading %s", passFile)) - } - password = bytes.TrimRightFunc(password, unicode.IsSpace) - } - - srv, err := ca.New(config, ca.WithConfigFile(configFile), ca.WithPassword(password)) - if err != nil { - fatal(err) - } - - go ca.StopReloaderHandler(srv) - if err = srv.Run(); err != nil && err != http.ErrServerClosed { - fatal(err) - } - return nil + // Hack to be able to run a the top action as a subcommand + cmd := cli.Command{Name: "start", Action: startAction, Flags: app.Flags} + set := flag.NewFlagSet(app.Name, flag.ContinueOnError) + set.Parse(os.Args) + ctx = cli.NewContext(app, set, nil) + return cmd.Run(ctx) } if err := app.Run(os.Args); err != nil { @@ -189,6 +162,43 @@ intermediate private key.`, } } +func startAction(ctx *cli.Context) error { + passFile := ctx.String("password-file") + + // If zero cmd line args show help, if >1 cmd line args show error. + if ctx.NArg() == 0 { + return cli.ShowAppHelp(ctx) + } + if err := errs.NumberOfArguments(ctx, 1); err != nil { + return err + } + + configFile := ctx.Args().Get(0) + config, err := authority.LoadConfiguration(configFile) + if err != nil { + fatal(err) + } + + var password []byte + if passFile != "" { + if password, err = ioutil.ReadFile(passFile); err != nil { + fatal(errors.Wrapf(err, "error reading %s", passFile)) + } + password = bytes.TrimRightFunc(password, unicode.IsSpace) + } + + srv, err := ca.New(config, ca.WithConfigFile(configFile), ca.WithPassword(password)) + if err != nil { + fatal(err) + } + + go ca.StopReloaderHandler(srv) + if err = srv.Run(); err != nil && err != http.ErrServerClosed { + fatal(err) + } + return nil +} + // fatal writes the passed error on the standard error and exits with the exit // code 1. If the environment variable STEPDEBUG is set to 1 it shows the // stack trace of the error.