Add env to disable version check

main
Elie 2020-12-17 11:10:33 +01:00
parent 2c06a5912a
commit 711ffde3a2
No known key found for this signature in database
GPG Key ID: 399AF69092C727B6
3 changed files with 25 additions and 4 deletions

View File

@ -4,7 +4,7 @@
#### Version check
By default, driftctl checks for a new version remotely, to disable this behavior, use flag `--no-version-check`
By default, driftctl checks for a new version remotely. To disable this behavior, use either the flag `--no-version-check` or the environment variable `DCTL_NO_VERSION_CHECK=true`.
### Usage

View File

@ -70,10 +70,11 @@ func contains(args []string, cmd string) bool {
}
func (driftctlCmd DriftctlCmd) ShouldCheckVersion() bool {
noVersionCheckEnv := os.Getenv("DCTL_NO_VERSION_CHECK") == "true"
noVersionCheckVal := contains(os.Args[1:], "--no-version-check")
hasVersionCmd := contains(os.Args[1:], "version")
isHelp := contains(os.Args[1:], "help") || contains(os.Args[1:], "--help") || contains(os.Args[1:], "-h")
return driftctlCmd.build.IsRelease() && !hasVersionCmd && !noVersionCheckVal && !isHelp
return driftctlCmd.build.IsRelease() && !hasVersionCmd && !noVersionCheckVal && !isHelp && !noVersionCheckEnv
}
// Iterate over command flags
@ -85,12 +86,18 @@ func bindEnvToFlags(cmd *cobra.Command) error {
if err != nil {
return
}
// Ignore some global flags
// no-version-check is ignored because we don't use cmd flags to retrieve flag in version check function
// as we check version before cmd, we use os.Args
if f.Name == "help" || f.Name == "no-version-check" {
return
}
envKey := strings.ReplaceAll(f.Name, "-", "_")
// Apply the viper config value to the flag when the flag is not set and viper has a value
// Allow flags precedence over env variables
if !f.Changed && viper.IsSet(envKey) {
envVal := viper.GetString(envKey)
err = cmd.Flags().Set(envKey, envVal)
err = cmd.Flags().Set(f.Name, envVal)
if err != nil {
return
}

View File

@ -168,6 +168,7 @@ func TestDriftctlCmd_ShouldCheckVersion(t *testing.T) {
Name string
IsRelease bool
args []string
env map[string]string
expected bool
}{
{
@ -212,6 +213,14 @@ func TestDriftctlCmd_ShouldCheckVersion(t *testing.T) {
args: []string{""},
expected: false,
},
{
Name: "Don't check for update when env var set",
IsRelease: true,
env: map[string]string{
"DCTL_NO_VERSION_CHECK": "true",
},
expected: false,
},
{
Name: "Should not return error when launching sub command",
IsRelease: false,
@ -224,11 +233,16 @@ func TestDriftctlCmd_ShouldCheckVersion(t *testing.T) {
t.Run(c.Name, func(tt *testing.T) {
assert := assert.New(tt)
os.Clearenv()
for key, val := range c.env {
os.Setenv(key, val)
}
cmd := NewDriftctlCmd(mocks.MockBuild{Release: c.IsRelease})
os.Args = append([]string{"driftctl"}, c.args...)
result := cmd.ShouldCheckVersion()
assert.Equal(result, c.expected)
assert.Equal(c.expected, result)
})
}
}