Skip to content

Commit

Permalink
fix: avoid asking env variables in non-interactive mode
Browse files Browse the repository at this point in the history
We use a heuristics to determine if the command is called interactively or not:
IsInteractive in util.go. Currently, we assume that a command is not interactive
if more than 2 flags were set.
  • Loading branch information
metacosm committed Oct 9, 2019
1 parent b6c5779 commit e2c362a
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 9 deletions.
18 changes: 10 additions & 8 deletions pkg/cmdutil/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,21 +23,23 @@ func SetupEnvOptions(o WithEnv, cmd *cobra.Command) {
cmd.Flags().StringSliceVarP(&env.EnvPairs, "env", "e", []string{}, "Environment variables as 'name=value' pairs")
}

func (o *EnvOptions) Complete() error {
func (o *EnvOptions) Complete(name string, cmd *cobra.Command, args []string) error {
if len(o.EnvPairs) > 0 {
for _, pair := range o.EnvPairs {
if _, e := o.addToEnv(pair); e != nil {
return e
}
}
} else {
for {
envAsString := ui.AskOrReturnToExit("Env variable in the 'name=value' format, simply press enter when finished")
if len(envAsString) == 0 {
break
}
if _, e := o.addToEnv(envAsString); e != nil {
return e
if IsInteractive(cmd) {
for {
envAsString := ui.AskOrReturnToExit("Env variable in the 'name=value' format, simply press enter when finished")
if len(envAsString) == 0 {
break
}
if _, e := o.addToEnv(envAsString); e != nil {
return e
}
}
}
}
Expand Down
12 changes: 12 additions & 0 deletions pkg/cmdutil/util.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
package cmdutil

import "github.com/spf13/cobra"

func CommandName(name, fullParentName string) string {
return fullParentName + " " + name
}

// FlagValueIfSet retrieves the value of the specified flag if it is set for the given command
func FlagValueIfSet(cmd *cobra.Command, flagName string) string {
flag, _ := cmd.Flags().GetString(flagName)
return flag
}

func IsInteractive(cmd *cobra.Command) bool {
return cmd.Flags().NFlag() <= 2 // heuristics to determine whether we're running in interactive mode
}
2 changes: 1 addition & 1 deletion pkg/hal/cli/link/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func (o *createOptions) Complete(name string, cmd *cobra.Command, args []string)
} else {
o.linkType = link.EnvLinkType
ui.OutputSelection("Selected link type", o.linkType.String())
if err := o.EnvOptions.Complete(); err != nil {
if err := o.EnvOptions.Complete(name, cmd, args); err != nil {
return err
}
}
Expand Down

0 comments on commit e2c362a

Please sign in to comment.