support nested subcommands with TF_CLI_ARGS

This commit is contained in:
Mitchell Hashimoto 2017-02-13 15:18:50 -08:00
parent df93e5120c
commit 518ae5ef02
No known key found for this signature in database
GPG Key ID: 744E147AA52F5B0A
2 changed files with 34 additions and 5 deletions

19
main.go
View File

@ -148,15 +148,17 @@ func wrappedMain() int {
}
// Prefix the args with any args from the EnvCLI
args, err = mergeEnvArgs(EnvCLI, args)
args, err = mergeEnvArgs(EnvCLI, cliRunner.Subcommand(), args)
if err != nil {
Ui.Error(err.Error())
return 1
}
// Prefix the args with any args from the EnvCLI targeting this command
suffix := strings.Replace(cliRunner.Subcommand(), "-", "_", -1)
args, err = mergeEnvArgs(fmt.Sprintf("%s_%s", EnvCLI, suffix), args)
suffix := strings.Replace(strings.Replace(
cliRunner.Subcommand(), "-", "_", -1), " ", "_", -1)
args, err = mergeEnvArgs(
fmt.Sprintf("%s_%s", EnvCLI, suffix), cliRunner.Subcommand(), args)
if err != nil {
Ui.Error(err.Error())
return 1
@ -275,7 +277,7 @@ func copyOutput(r io.Reader, doneCh chan<- struct{}) {
wg.Wait()
}
func mergeEnvArgs(envName string, args []string) ([]string, error) {
func mergeEnvArgs(envName string, cmd string, args []string) ([]string, error) {
v := os.Getenv(envName)
if v == "" {
return args, nil
@ -289,11 +291,18 @@ func mergeEnvArgs(envName string, args []string) ([]string, error) {
envName, err)
}
// Find the command to look for in the args. If there is a space,
// we need to find the last part.
search := cmd
if idx := strings.LastIndex(search, " "); idx >= 0 {
search = cmd[idx+1:]
}
// Find the index to place the flags. We put them exactly
// after the first non-flag arg.
idx := -1
for i, v := range args {
if len(v) > 0 && v[0] != '-' {
if v == search {
idx = i
break
}

View File

@ -178,6 +178,26 @@ func TestMain_cliArgsFromEnvAdvanced(t *testing.T) {
[]string{"-flag", "foo", "bar"},
false,
},
{
"targeted to a command with a hyphen",
"command-name",
EnvCLI + "_command_name",
[]string{"command-name", "foo", "bar"},
"-flag",
[]string{"-flag", "foo", "bar"},
false,
},
{
"targeted to a command with a space",
"command name",
EnvCLI + "_command_name",
[]string{"command", "name", "foo", "bar"},
"-flag",
[]string{"-flag", "foo", "bar"},
false,
},
}
for i, tc := range cases {