| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "io" |
| 6 | "os" |
| 7 | |
| 8 | "github.com/spf13/cobra" |
| 9 | |
| 10 | "go.bigb.es/confluence-md-utilities/converter" |
| 11 | "go.bigb.es/confluence-md-utilities/template" |
| 12 | ) |
| 13 | |
| 14 | var ( |
| 15 | extractOutput string |
| 16 | extractMarkerStart string |
| 17 | extractMarkerEnd string |
| 18 | extractRaw bool |
| 19 | ) |
| 20 | |
| 21 | var extractCmd = &cobra.Command{ |
| 22 | Use: "extract [input.xml]", |
| 23 | Short: "Extract Markdown from a Confluence XML document", |
| 24 | Long: `Extract content between marker comments from a Confluence XML document |
| 25 | and convert it back to Markdown. |
| 26 |
|
| 27 | The document must contain marker comments: |
| 28 | <!-- MD_CONTENT_START --> |
| 29 | <!-- MD_CONTENT_END --> |
| 30 |
|
| 31 | Use --raw to get the Confluence XML without converting to Markdown. |
| 32 | Reads from stdin if no file is specified.`, |
| 33 | Args: cobra.MaximumNArgs(1), |
| 34 | RunE: func(cmd *cobra.Command, args []string) error { |
| 35 | // Read input |
| 36 | var input []byte |
| 37 | var err error |
| 38 | if len(args) > 0 { |
| 39 | input, err = os.ReadFile(args[0]) |
| 40 | } else { |
| 41 | input, err = io.ReadAll(os.Stdin) |
| 42 | } |
| 43 | if err != nil { |
| 44 | return fmt.Errorf("reading input: %w", err) |
| 45 | } |
| 46 | |
| 47 | // Extract content between markers |
| 48 | xmlContent, err := template.Extract(string(input), extractMarkerStart, extractMarkerEnd) |
| 49 | if err != nil { |
| 50 | return fmt.Errorf("extracting: %w", err) |
| 51 | } |
| 52 | |
| 53 | var result string |
| 54 | if extractRaw { |
| 55 | result = xmlContent |
| 56 | } else { |
| 57 | result, err = converter.ConfluenceToMarkdown(xmlContent) |
| 58 | if err != nil { |
| 59 | return fmt.Errorf("converting to markdown: %w", err) |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | if extractOutput != "" { |
| 64 | return os.WriteFile(extractOutput, []byte(result), 0644) |
| 65 | } |
| 66 | fmt.Print(result) |
| 67 | return nil |
| 68 | }, |
| 69 | } |
| 70 | |
| 71 | func init() { |
| 72 | extractCmd.Flags().StringVarP(&extractOutput, "output", "o", "", "Output file (default: stdout)") |
| 73 | extractCmd.Flags().StringVar(&extractMarkerStart, "marker-start", template.DefaultMarkerStart, "Start marker comment") |
| 74 | extractCmd.Flags().StringVar(&extractMarkerEnd, "marker-end", template.DefaultMarkerEnd, "End marker comment") |
| 75 | extractCmd.Flags().BoolVar(&extractRaw, "raw", false, "Output raw Confluence XML instead of Markdown") |
| 76 | rootCmd.AddCommand(extractCmd) |
| 77 | } |
| 78 | |