From 5db90f0912f8f6fca19149c6f3997aedac069c8b Mon Sep 17 00:00:00 2001 From: Thorsten Hans Date: Wed, 9 Oct 2024 19:20:52 +0200 Subject: [PATCH] chore: Add remove flag to cleanup command By specifying the remove flag (shorthand r) users can alter the behavior of the cleanup command to actually remove the OTel containers, instead of just stopping them Signed-off-by: Thorsten Hans --- cmd/cleanup.go | 46 ++++++++++++++++++++++++++++++---------------- 1 file changed, 30 insertions(+), 16 deletions(-) diff --git a/cmd/cleanup.go b/cmd/cleanup.go index ff02d53..8c0ef5c 100644 --- a/cmd/cleanup.go +++ b/cmd/cleanup.go @@ -8,15 +8,22 @@ import ( "github.com/spf13/cobra" ) -var cleanUpCmd = &cobra.Command{ - Use: "cleanup", - Short: "Clean up OTel dependencies", - RunE: func(cmd *cobra.Command, args []string) error { - if err := cleanUp(); err != nil { - return err - } - return nil - }, +var ( + removeContainers = false + cleanUpCmd = &cobra.Command{ + Use: "cleanup", + Short: "Clean up OTel dependencies", + RunE: func(cmd *cobra.Command, args []string) error { + if err := cleanUp(); err != nil { + return err + } + return nil + }, + } +) + +func init() { + cleanUpCmd.Flags().BoolVarP(&removeContainers, "remove", "r", false, "If specified, OTel containers will be removed") } func getIDs(dockerOutput []byte) []string { @@ -53,13 +60,20 @@ func cleanUp() error { containerIDs := getIDs(dockerPsOutput) // The `docker stop` command will throw an error if there are no containers to stop - if len(containerIDs) != 0 { - stopContainers := exec.Command("docker", append([]string{"stop"}, containerIDs...)...) - stopContainersOutput, err := stopContainers.CombinedOutput() - if err != nil { - fmt.Println(string(stopContainersOutput)) - return err - } + if len(containerIDs) == 0 { + fmt.Println("No Spin OTel resources found. Nothing to clean up.") + return nil + } + + cleanupArgs := []string{"stop"} + if removeContainers { + cleanupArgs = []string{"rm", "-f"} + } + stopContainers := exec.Command("docker", append(cleanupArgs, containerIDs...)...) + stopContainersOutput, err := stopContainers.CombinedOutput() + if err != nil { + fmt.Println(string(stopContainersOutput)) + return err } fmt.Println("All Spin OTel resources have been cleaned up.")