~bigbes/confluence-md-utilities

ref: f6c846a1f16d1f6d0045c92a1c0f24429e6b901f confluence-md-utilities/cmd/mdcx/pull.go -rw-r--r-- 3.6 KiB
f6c846a1 — Eugene Blikh fix: preserve inline spacing in fmt and code-block round-trip a month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
package main

import (
	"encoding/json"
	"fmt"
	"os"

	"github.com/spf13/cobra"

	"go.bigb.es/confluence-md-utilities/api"
	"go.bigb.es/confluence-md-utilities/converter"
)

var (
	pullOutput       string
	pullRaw          bool
	pullWithComments bool
)

var pullCmd = &cobra.Command{
	Use:   "pull <confluence-url>",
	Short: "Pull a page from Confluence and convert to Markdown",
	Long: `Fetch a Confluence page by URL, extract its storage format body,
and convert it to Markdown.

Supported URL formats:
  https://confluence.example.com/pages/viewpage.action?pageId=12345
  https://confluence.example.com/display/SPACE/Page+Title

Use --raw to get the Confluence storage XML without converting to Markdown.

Authentication via --token flag or CONFLUENCE_TOKEN environment variable.`,
	Args: cobra.ExactArgs(1),
	RunE: func(cmd *cobra.Command, args []string) error {
		token := resolveToken()
		if token == "" {
			return fmt.Errorf("Confluence token required: use --token flag or set CONFLUENCE_TOKEN env var")
		}

		if pullWithComments && pullOutput == "" {
			return fmt.Errorf("--with-comments requires --output")
		}

		ref, err := api.ParsePageURL(args[0])
		if err != nil {
			return err
		}

		client := api.NewClient(ref.BaseURL, token)
		page, err := client.GetPage(ref)
		if err != nil {
			return err
		}

		xmlBody := page.Body.Storage.Value
		fmt.Fprintf(os.Stderr, "Pulled page: %s (id=%s, version=%d)\n", page.Title, page.ID, page.Version.Number)

		var result string
		if pullRaw {
			result = xmlBody
		} else {
			result, err = converter.ConfluenceToMarkdown(xmlBody)
			if err != nil {
				return fmt.Errorf("converting to markdown: %w", err)
			}
		}

		if pullOutput != "" {
			if err := os.WriteFile(pullOutput, []byte(result), 0644); err != nil {
				return err
			}
			fmt.Fprintf(os.Stderr, "Written to %s\n", pullOutput)

			if pullWithComments {
				if err := pullSaveComments(client, page, pullOutput); err != nil {
					return fmt.Errorf("fetching comments: %w", err)
				}
			}
			return nil
		}
		fmt.Print(result)
		return nil
	},
}

type commentSidecar struct {
	Page           sidecarPage    `json:"page"`
	InlineComments []*api.Comment `json:"inline_comments"`
	PageComments   []*api.Comment `json:"page_comments"`
}

type sidecarPage struct {
	ID      string `json:"id"`
	Title   string `json:"title"`
	Version int    `json:"version"`
}

func pullSaveComments(client *api.Client, page *api.ContentResponse, mdPath string) error {
	comments, err := client.GetComments(page.ID)
	if err != nil {
		return err
	}
	inline, footer := splitComments(comments)
	sidecar := commentSidecar{
		Page: sidecarPage{
			ID:      page.ID,
			Title:   page.Title,
			Version: page.Version.Number,
		},
		InlineComments: inline,
		PageComments:   footer,
	}
	data, err := json.MarshalIndent(sidecar, "", "  ")
	if err != nil {
		return err
	}
	sidecarPath := mdPath + ".comments.json"
	if err := os.WriteFile(sidecarPath, data, 0644); err != nil {
		return err
	}
	fmt.Fprintf(os.Stderr, "Saved %d inline + %d page comments to %s\n",
		len(inline), len(footer), sidecarPath)
	return nil
}

func splitComments(all []*api.Comment) (inline, footer []*api.Comment) {
	for _, c := range all {
		if c.Location == "inline" {
			inline = append(inline, c)
		} else {
			footer = append(footer, c)
		}
	}
	return
}

func init() {
	pullCmd.Flags().StringVarP(&pullOutput, "output", "o", "", "Output file (default: stdout)")
	pullCmd.Flags().BoolVar(&pullRaw, "raw", false, "Output raw Confluence storage XML instead of Markdown")
	pullCmd.Flags().BoolVar(&pullWithComments, "with-comments", false, "Also save inline + page comments to <output>.comments.json (requires --output)")
	rootCmd.AddCommand(pullCmd)
}