|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + "text/tabwriter" |
| 8 | + |
| 9 | + "github.com/spf13/cobra" |
| 10 | + "github.com/wesm/msgvault/internal/query" |
| 11 | + "github.com/wesm/msgvault/internal/store" |
| 12 | +) |
| 13 | + |
| 14 | +var listAccountsJSON bool |
| 15 | + |
| 16 | +var listAccountsCmd = &cobra.Command{ |
| 17 | + Use: "list-accounts", |
| 18 | + Short: "List synced email accounts", |
| 19 | + Long: `List all email accounts that have been added to msgvault. |
| 20 | +
|
| 21 | +Examples: |
| 22 | + msgvault list-accounts |
| 23 | + msgvault list-accounts --json`, |
| 24 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 25 | + dbPath := cfg.DatabasePath() |
| 26 | + s, err := store.Open(dbPath) |
| 27 | + if err != nil { |
| 28 | + return fmt.Errorf("open database: %w", err) |
| 29 | + } |
| 30 | + defer s.Close() |
| 31 | + |
| 32 | + engine := query.NewSQLiteEngine(s.DB()) |
| 33 | + |
| 34 | + accounts, err := engine.ListAccounts(cmd.Context()) |
| 35 | + if err != nil { |
| 36 | + return fmt.Errorf("list accounts: %w", err) |
| 37 | + } |
| 38 | + |
| 39 | + if len(accounts) == 0 { |
| 40 | + fmt.Println("No accounts found. Use 'msgvault add-account <email>' to add one.") |
| 41 | + return nil |
| 42 | + } |
| 43 | + |
| 44 | + if listAccountsJSON { |
| 45 | + return outputAccountsJSON(accounts) |
| 46 | + } |
| 47 | + outputAccountsTable(accounts) |
| 48 | + return nil |
| 49 | + }, |
| 50 | +} |
| 51 | + |
| 52 | +func outputAccountsTable(accounts []query.AccountInfo) { |
| 53 | + w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) |
| 54 | + fmt.Fprintln(w, "ID\tEMAIL\tTYPE\tDISPLAY NAME") |
| 55 | + fmt.Fprintln(w, "──\t─────\t────\t────────────") |
| 56 | + |
| 57 | + for _, acc := range accounts { |
| 58 | + displayName := acc.DisplayName |
| 59 | + if displayName == "" { |
| 60 | + displayName = "-" |
| 61 | + } |
| 62 | + fmt.Fprintf(w, "%d\t%s\t%s\t%s\n", acc.ID, acc.Identifier, acc.SourceType, displayName) |
| 63 | + } |
| 64 | + |
| 65 | + w.Flush() |
| 66 | + fmt.Printf("\n%d account(s)\n", len(accounts)) |
| 67 | +} |
| 68 | + |
| 69 | +func outputAccountsJSON(accounts []query.AccountInfo) error { |
| 70 | + output := make([]map[string]interface{}, len(accounts)) |
| 71 | + for i, acc := range accounts { |
| 72 | + output[i] = map[string]interface{}{ |
| 73 | + "id": acc.ID, |
| 74 | + "email": acc.Identifier, |
| 75 | + "type": acc.SourceType, |
| 76 | + "display_name": acc.DisplayName, |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + enc := json.NewEncoder(os.Stdout) |
| 81 | + enc.SetIndent("", " ") |
| 82 | + return enc.Encode(output) |
| 83 | +} |
| 84 | + |
| 85 | +func init() { |
| 86 | + rootCmd.AddCommand(listAccountsCmd) |
| 87 | + listAccountsCmd.Flags().BoolVar(&listAccountsJSON, "json", false, "Output as JSON") |
| 88 | +} |
0 commit comments