| 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/format" |
| 11 | ) |
| 12 | |
| 13 | var ( |
| 14 | fmtOutput string |
| 15 | fmtIndent string |
| 16 | fmtColor string |
| 17 | ) |
| 18 | |
| 19 | var fmtCmd = &cobra.Command{ |
| 20 | Use: "fmt [input.xml]", |
| 21 | Short: "Pretty-print Confluence storage XML", |
| 22 | Long: `Format Confluence storage XML with sensible indentation. |
| 23 |
|
| 24 | Block elements (p, h1-h6, ul, ol, li, table, tr, td, th, macros, layout) |
| 25 | get their own lines with indentation. Inline elements (strong, em, code, |
| 26 | a, ac:link, ac:image) stay on the same line. CDATA content inside code |
| 27 | blocks is preserved as-is. |
| 28 |
|
| 29 | Syntax highlighting is enabled by default when outputting to a terminal. |
| 30 |
|
| 31 | Reads from stdin if no file is specified.`, |
| 32 | Args: cobra.MaximumNArgs(1), |
| 33 | RunE: func(cmd *cobra.Command, args []string) error { |
| 34 | var input []byte |
| 35 | var err error |
| 36 | |
| 37 | if len(args) > 0 { |
| 38 | input, err = os.ReadFile(args[0]) |
| 39 | } else { |
| 40 | input, err = io.ReadAll(os.Stdin) |
| 41 | } |
| 42 | if err != nil { |
| 43 | return fmt.Errorf("reading input: %w", err) |
| 44 | } |
| 45 | |
| 46 | result := format.PrettyXML(string(input), fmtIndent) |
| 47 | |
| 48 | useColor := resolveColor(fmtColor, fmtOutput) |
| 49 | if useColor { |
| 50 | result = format.Colorize(result) |
| 51 | } |
| 52 | |
| 53 | if fmtOutput != "" { |
| 54 | return os.WriteFile(fmtOutput, []byte(result), 0644) |
| 55 | } |
| 56 | fmt.Print(result) |
| 57 | return nil |
| 58 | }, |
| 59 | } |
| 60 | |
| 61 | func init() { |
| 62 | fmtCmd.Flags().StringVarP(&fmtOutput, "output", "o", "", "Output file (default: stdout)") |
| 63 | fmtCmd.Flags().StringVar(&fmtIndent, "indent", " ", "Indentation string (default: 2 spaces)") |
| 64 | fmtCmd.Flags().StringVar(&fmtColor, "color", "auto", "Colorize output: auto, force, disabled") |
| 65 | _ = fmtCmd.RegisterFlagCompletionFunc("color", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { |
| 66 | return []string{"auto", "force", "disabled"}, cobra.ShellCompDirectiveNoFileComp |
| 67 | }) |
| 68 | rootCmd.AddCommand(fmtCmd) |
| 69 | } |
| 70 | |
| 71 | func resolveColor(mode string, outputFile string) bool { |
| 72 | switch mode { |
| 73 | case "force": |
| 74 | return true |
| 75 | case "disabled": |
| 76 | return false |
| 77 | default: // "auto" |
| 78 | if outputFile != "" { |
| 79 | return false |
| 80 | } |
| 81 | return isTerminal(os.Stdout) |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | func isTerminal(f *os.File) bool { |
| 86 | stat, err := f.Stat() |
| 87 | if err != nil { |
| 88 | return false |
| 89 | } |
| 90 | return (stat.Mode() & os.ModeCharDevice) != 0 |
| 91 | } |
| 92 | |