|
| 1 | +package cli |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + |
| 8 | + "github.com/glincker/stacklit/internal/renderer" |
| 9 | + "github.com/glincker/stacklit/internal/schema" |
| 10 | + "github.com/spf13/cobra" |
| 11 | +) |
| 12 | + |
| 13 | +func newExportCmd() *cobra.Command { |
| 14 | + var format, source, output string |
| 15 | + |
| 16 | + cmd := &cobra.Command{ |
| 17 | + Use: "export", |
| 18 | + Short: "Export the index in a human-readable format", |
| 19 | + Long: `Renders stacklit.json in a different format for sharing. |
| 20 | +
|
| 21 | +Currently supports markdown, which produces a readable project overview |
| 22 | +suitable for pasting into PR descriptions, GitHub issues, or chat. |
| 23 | +
|
| 24 | +Examples: |
| 25 | + stacklit export Print markdown to stdout |
| 26 | + stacklit export --format md Same as above |
| 27 | + stacklit export -o stacklit.md Write markdown to a file |
| 28 | + stacklit export --source ./other.json Read from a non-default index`, |
| 29 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 30 | + data, err := os.ReadFile(source) |
| 31 | + if err != nil { |
| 32 | + return fmt.Errorf("could not read %s: %w (run 'stacklit generate' first, or 'stacklit init')", source, err) |
| 33 | + } |
| 34 | + var idx schema.Index |
| 35 | + if err := json.Unmarshal(data, &idx); err != nil { |
| 36 | + return fmt.Errorf("could not parse %s: %w", source, err) |
| 37 | + } |
| 38 | + |
| 39 | + switch format { |
| 40 | + case "md", "markdown": |
| 41 | + if output == "" { |
| 42 | + fmt.Print(renderer.RenderMarkdown(&idx)) |
| 43 | + return nil |
| 44 | + } |
| 45 | + if err := renderer.WriteMarkdown(&idx, output); err != nil { |
| 46 | + return fmt.Errorf("could not write %s: %w", output, err) |
| 47 | + } |
| 48 | + fmt.Fprintf(cmd.OutOrStderr(), "Wrote %s\n", output) |
| 49 | + return nil |
| 50 | + default: |
| 51 | + return fmt.Errorf("unknown format %q (supported: md, markdown)", format) |
| 52 | + } |
| 53 | + }, |
| 54 | + } |
| 55 | + |
| 56 | + cmd.Flags().StringVar(&format, "format", "md", "Output format (md)") |
| 57 | + cmd.Flags().StringVar(&source, "source", "stacklit.json", "Path to the index JSON") |
| 58 | + cmd.Flags().StringVarP(&output, "output", "o", "", "Write to file instead of stdout") |
| 59 | + return cmd |
| 60 | +} |
0 commit comments