From c2445e6539837cc3f5f23a4cbd60460ff945e20e Mon Sep 17 00:00:00 2001 From: Sylvain Witmeyer Date: Sat, 11 Mar 2023 09:31:01 -0500 Subject: [PATCH] feat: not display module with --unused-flag --- cmd/root.go | 33 ++++++++++++++++++++++++++------- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index 53b19a3..d6dc51b 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -31,20 +31,28 @@ func rootCmdExec(cmd *cobra.Command, args []string) error { return err } - for path, _ := range modules { + for path := range modules { stats, err := findVariablesUsage(path) if err != nil { return err } - fmt.Printf("Module: %s (%d variables found)\n", path, len(stats.variables)) - for name, count := range stats.variables { - if fUnusedOnly && count > 0 { + if fUnusedOnly { + for name, count := range stats.variables { + if count > 0 { + delete(stats.variables, name) + } + } + if len(stats.variables) == 0 { continue } - fmt.Printf("%s : %d\n", name, count) } - fmt.Println("") + + err = displayModule(path, &stats) + if err != nil { + return err + } + } fmt.Printf("%d modules processed", len(modules)) @@ -52,6 +60,17 @@ func rootCmdExec(cmd *cobra.Command, args []string) error { return nil } +func displayModule(path string, stats *VariablesUsage) error { + fmt.Printf("Module: %s (%d variables found)\n", path, len(stats.variables)) + + for name, count := range stats.variables { + fmt.Printf("%s : %d\n", name, count) + } + fmt.Println("") + + return nil +} + type VariablesUsage struct { variables map[string]int } @@ -91,7 +110,7 @@ func countVariables(path string, tfconfig *tfconfig.Module) (map[string]int, err content := string(data) - for variable, _ := range tfconfig.Variables { + for variable := range tfconfig.Variables { regex := regexp.MustCompile(fmt.Sprintf(`var\.%s\W`, variable)) matches := regex.FindAllStringIndex(content, -1)