|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "rules-cli/internal/formats" |
| 6 | + "rules-cli/internal/ruleset" |
| 7 | + |
| 8 | + "github.com/fatih/color" |
| 9 | + "github.com/spf13/cobra" |
| 10 | +) |
| 11 | + |
| 12 | +// listCmd represents the list command |
| 13 | +var listCmd = &cobra.Command{ |
| 14 | + Use: "list", |
| 15 | + Short: "List all rules currently installed in the project", |
| 16 | + Long: `List all rules currently installed in the project, similar to 'npm list'. |
| 17 | +This command reads from the rules.json file and displays the installed rules |
| 18 | +with their versions in a tree-like format. |
| 19 | +
|
| 20 | +The command only reads local files and does not require network access.`, |
| 21 | + Example: ` rules list`, |
| 22 | + Args: cobra.NoArgs, |
| 23 | + RunE: runListCommand, |
| 24 | +} |
| 25 | + |
| 26 | +// runListCommand implements the main logic for the list command |
| 27 | +func runListCommand(cmd *cobra.Command, args []string) error { |
| 28 | + // Get rules.json path |
| 29 | + rulesJSONPath, err := formats.GetRulesJSONPath(format) |
| 30 | + if err != nil { |
| 31 | + return fmt.Errorf("failed to get rules.json path: %w", err) |
| 32 | + } |
| 33 | + |
| 34 | + // Load the ruleset |
| 35 | + rs, err := ruleset.LoadRuleSet(rulesJSONPath) |
| 36 | + if err != nil { |
| 37 | + return fmt.Errorf("No rules.json file found in current directory\nRun 'rules init' to initialize a new project") |
| 38 | + } |
| 39 | + |
| 40 | + // Display the project name and version |
| 41 | + color.Cyan("%s@%s", rs.Name, rs.Version) |
| 42 | + |
| 43 | + // Check if rules are empty |
| 44 | + if len(rs.Rules) == 0 { |
| 45 | + color.Yellow("(empty)") |
| 46 | + return nil |
| 47 | + } |
| 48 | + |
| 49 | + // Sort rules for consistent output |
| 50 | + ruleNames := make([]string, 0, len(rs.Rules)) |
| 51 | + for name := range rs.Rules { |
| 52 | + ruleNames = append(ruleNames, name) |
| 53 | + } |
| 54 | + |
| 55 | + // Simple alphabetical sort |
| 56 | + for i := 0; i < len(ruleNames); i++ { |
| 57 | + for j := i + 1; j < len(ruleNames); j++ { |
| 58 | + if ruleNames[i] > ruleNames[j] { |
| 59 | + ruleNames[i], ruleNames[j] = ruleNames[j], ruleNames[i] |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + // Display rules in tree format |
| 65 | + for i, name := range ruleNames { |
| 66 | + version := rs.Rules[name] |
| 67 | + |
| 68 | + // Use appropriate tree characters |
| 69 | + var prefix string |
| 70 | + if i == len(ruleNames)-1 { |
| 71 | + prefix = "└── " |
| 72 | + } else { |
| 73 | + prefix = "├── " |
| 74 | + } |
| 75 | + |
| 76 | + fmt.Printf("%s%s@%s\n", prefix, name, version) |
| 77 | + } |
| 78 | + |
| 79 | + return nil |
| 80 | +} |
| 81 | + |
| 82 | +func init() { |
| 83 | + rootCmd.AddCommand(listCmd) |
| 84 | +} |
0 commit comments