|
| 1 | +package command |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "sort" |
| 6 | + "strings" |
| 7 | + |
| 8 | + "github.com/geekloper/zut/internal/core" |
| 9 | + "github.com/geekloper/zut/pkg/storage" |
| 10 | + "github.com/spf13/cobra" |
| 11 | +) |
| 12 | + |
| 13 | +// NewListCommand creates the list command |
| 14 | +func NewListCommand() *cobra.Command { |
| 15 | + var search string |
| 16 | + |
| 17 | + cmd := &cobra.Command{ |
| 18 | + Use: "list", |
| 19 | + Short: "List all saved commands", |
| 20 | + Long: "Display all saved commands or search/filter by alias, tag, or command content", |
| 21 | + Example: ` zut list |
| 22 | + zut list -s "git" |
| 23 | + zut list --search "docker"`, |
| 24 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 25 | + // Create manager |
| 26 | + manager, err := core.NewManager() |
| 27 | + if err != nil { |
| 28 | + return fmt.Errorf("failed to initialize: %w", err) |
| 29 | + } |
| 30 | + |
| 31 | + // Get commands (filtered or all) |
| 32 | + var entries []storage.CommandEntry |
| 33 | + if search != "" { |
| 34 | + entries = manager.SearchCommands(search) |
| 35 | + } else { |
| 36 | + entries = manager.ListCommands() |
| 37 | + } |
| 38 | + |
| 39 | + // Check if empty |
| 40 | + if len(entries) == 0 { |
| 41 | + if search != "" { |
| 42 | + fmt.Println("No commands found matching the search term") |
| 43 | + } else { |
| 44 | + fmt.Println("No commands saved yet. Use 'zut add' to add a command.") |
| 45 | + } |
| 46 | + return nil |
| 47 | + } |
| 48 | + |
| 49 | + // Sort by alias for consistent output |
| 50 | + sort.Slice(entries, func(i, j int) bool { |
| 51 | + return entries[i].Alias < entries[j].Alias |
| 52 | + }) |
| 53 | + |
| 54 | + // Print header |
| 55 | + fmt.Println() |
| 56 | + printTableRow("ALIAS", "COMMAND", "TAG") |
| 57 | + fmt.Println(strings.Repeat("─", 100)) |
| 58 | + |
| 59 | + // Print entries |
| 60 | + for _, entry := range entries { |
| 61 | + printTableRow(entry.Alias, truncate(entry.Command, 50), entry.Tag) |
| 62 | + } |
| 63 | + fmt.Println() |
| 64 | + fmt.Printf("Total: %d command(s)\n", len(entries)) |
| 65 | + |
| 66 | + return nil |
| 67 | + }, |
| 68 | + } |
| 69 | + |
| 70 | + // Add flags |
| 71 | + cmd.Flags().StringVarP(&search, "search", "s", "", "Search term to filter commands") |
| 72 | + |
| 73 | + return cmd |
| 74 | +} |
| 75 | + |
| 76 | +// printTableRow prints a formatted table row |
| 77 | +func printTableRow(alias, command, tag string) { |
| 78 | + fmt.Printf("%-20s %-52s %-25s\n", truncate(alias, 20), truncate(command, 50), truncate(tag, 25)) |
| 79 | +} |
| 80 | + |
| 81 | +// truncate truncates a string to the specified length |
| 82 | +func truncate(s string, maxLen int) string { |
| 83 | + if len(s) <= maxLen { |
| 84 | + return s |
| 85 | + } |
| 86 | + if maxLen <= 3 { |
| 87 | + return s[:maxLen] |
| 88 | + } |
| 89 | + return s[:maxLen-3] + "..." |
| 90 | +} |
0 commit comments