Skip to content

Commit

Permalink
feat: not allow state operations without a –force flag
Browse files Browse the repository at this point in the history
  • Loading branch information
c4po committed Mar 19, 2024
1 parent 7a90e7e commit 523cf85
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
22 changes: 22 additions & 0 deletions cmd/terraform-demux/main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"errors"
"io"
"log"
"os"
Expand All @@ -26,6 +27,11 @@ func main() {

log.Printf("terraform-demux version %s, using arch '%s'", version, arch)

if err := checkStateCommand(os.Args); err != nil {
log.SetOutput(os.Stderr)
log.Fatal("error: ", err)
}

exitCode, err := wrapper.RunTerraform(os.Args[1:], arch)

if err != nil {
Expand All @@ -36,3 +42,19 @@ func main() {

os.Exit(exitCode)
}

func checkStateCommand(args []string) error {
if checkArgsExists(args, "state") && !checkArgsExists(args, "--force") {
return errors.New("--force flag is required for the 'state' command")
}
return nil
}

func checkArgsExists(args []string, cmd string) bool {
for _, arg := range args {
if arg == cmd {
return true
}
}
return false
}
32 changes: 32 additions & 0 deletions cmd/terraform-demux/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package main

import (
"testing"
)

func TestCheckStateCommand(t *testing.T) {
t.Run("Valid state command with --force flag after state command", func(t *testing.T) {
args := []string{"terraform", "state", "--force", "list"}
err := checkStateCommand(args)
if err != nil {
t.Errorf("Expected no error, got: %v", err)
}
})

t.Run("Valid state command with --force flag before state command", func(t *testing.T) {
args := []string{"terraform", "--force", "state", "pull"}
err := checkStateCommand(args)
if err != nil {
t.Errorf("Expected no error, got: %v", err)
}
})

t.Run("Invalid state command without --force flag", func(t *testing.T) {
args := []string{"terraform", "state", "list"}
err := checkStateCommand(args)
expectedError := "--force flag is required for the 'state' command"
if err == nil || err.Error() != expectedError {
t.Errorf("Expected error: %s, got: %v", expectedError, err)
}
})
}

0 comments on commit 523cf85

Please sign in to comment.