aboutsummaryrefslogtreecommitdiffstats
path: root/divergence
blob: e54805f96fb6e9454bfd3a3aaebf771f0186a288 (plain)
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
#!/usr/bin/env python3
"""
License: MIT
Author: Bryan Newbold <bnewbold@archive.org>
Date: July 2017

See README.md and LICENSE.
"""

from __future__ import print_function
import re
import json
import sys, os
import difflib
import argparse
import requests
import subprocess
import logging as log


class DivergenceProgram:

    def __init__(self, user, password, url, space,
            force_update=False,
            include_toc=False,
            include_header=True):
        self.api = requests.Session()
        self.api.auth = (user, password)
        self.api.headers.update({'Content-Type': 'application/json'})
        self.base_url = url
        self.default_space = space
        self.force_update = force_update
        self.include_toc = include_toc
        self.include_header = include_header
        # TODO: clean up this code duplication... use pandoc data directory
        # instead?
        self.pandoc_helper_path = None
        for p in ('./pandoc_confluence.lua',
                  '/usr/local/lib/divergence/pandoc_confluence.lua',
                  '/usr/lib/divergence/pandoc_confluence.lua'):
            if os.path.exists(p):
                self.pandoc_helper_path = p
                break
        if self.pandoc_helper_path is None:
            log.error("Could not find pandoc helper (pandoc_confluence.lua), bailing")
            sys.exit(-1)
        self.pandoc_meta_path = None
        for p in ('./meta-json.template',
                  '/usr/local/lib/divergence/meta-json.template',
                  '/usr/lib/divergence/meta-json.template'):
            if os.path.exists(p):
                self.pandoc_meta_path = p
                break
        if self.pandoc_meta_path is None:
            log.error("Could not find pandoc helper (meta-json.template), bailing")
            sys.exit(-1)

    def get_page(self, title, space_key=None, page_id=None):
        """
        Returns None if not found, otherwise a dict with id, space, and body (in storage format)
        """
        if space_key is None:
            space_key = self.default_space
        if not page_id:
            resp = self.api.get(self.base_url + "/rest/api/content",
                params={"spaceKey": space_key,
                        "title": title,
                        "expand": "body.storage,body.editor,version,space",
                        "type": "page"})
        else:
            resp = self.api.get(self.base_url + "/rest/api/content/%d" % int(page_id),
                params={"expand": "body.storage,body.editor,version,space",
                        "type": "page"})

        log.debug(resp)
        log.debug(resp.content)
        assert resp.status_code == 200
        respj = resp.json()
        if not page_id:
            if respj['size'] == 0:
                assert page_id is None, "Couldn't fetch given page id"
                return None
            assert respj['size'] == 1, "Expect single result for title lookup"
            page = respj['results'][0]
        else:
            # We did a fetch by page_id directly
            page = respj
        assert page['space']['key'].upper() == space_key.upper(), "Expect spaces to match"

        return {"id": int(page['id']),
                "version": int(page['version']['number']),
                "space": page['space']['key'],
                "body": page['body']['storage']['value'],
                "body_editor": page['body']['editor']['value']}

    def get_conversion(self, body):
        """
        Uses the REST API to convert from storage to 'editor' format.
        """
        resp = self.api.post(self.base_url + "/rest/api/contentbody/convert/editor",
            json={"representation": "storage",
                  "value": body })

        log.debug(resp)
        log.debug(resp.content)
        assert resp.status_code == 200
        return resp.json()['value']

    def create_page(self, title, body, space_key=None):
        if space_key is None:
            space_key = self.default_space
        resp = self.api.post(self.base_url + "/rest/api/content",
            json={"space": { "key": space_key },
                  "type": "page",
                  "title": title,
                  "body": {
                    "storage": {
                        "representation": "storage",
                        "value": body } } } )
        log.debug(resp)
        log.debug(resp.content)
        assert resp.status_code == 200

    def update_page(self, title, body, page_id, prev_version):
        resp = self.api.put(self.base_url + "/rest/api/content/%d" % page_id,
            json={"type": "page",
                  "title": title,
                  "version": {"number": prev_version+1},
                  "body": {
                    "storage": {
                        "representation": "storage",
                        "value": body } } } )
        log.debug(resp)
        log.debug(resp.content)
        assert resp.status_code == 200

    def title_from_path(self, path):
        title = path.split('.')[0].replace('_', ' ')
        # TODO: only alphanum and spaces?
        return title

    def convert(self, f):
        proc = subprocess.run(["pandoc", "-t", self.pandoc_helper_path, f],
                              stdout=subprocess.PIPE)
        assert proc.returncode == 0
        body = proc.stdout.decode('UTF-8')
        if self.include_toc:
            body = """<ac:structured-macro ac:name="toc">
  <ac:parameter ac:name="minLevel">1</ac:parameter>
  <ac:parameter ac:name="maxLevel">3</ac:parameter>
</ac:structured-macro>""" + body
        if self.include_header:
            body = """<ac:structured-macro ac:name="info">
  <ac:rich-text-body>
    <p>This page was generated automatically from Markdown using the
        'divergence' tool. Edits will need to be merged manually. </p>
  </ac:rich-text-body>
</ac:structured-macro>\n""" + body
        return body

    def metadata(self, f):
        proc = subprocess.run(["pandoc", "--template", self.pandoc_meta_path, f],
                              stdout=subprocess.PIPE)
        assert proc.returncode == 0
        return json.loads(proc.stdout.decode('UTF-8'))

    def strip_tags(self, text):
        """
        THIS IS NOT A SANITIZER, just a naive way to strip (most?) HTML tags.
        """
        return re.sub('<[^<]+?>', '', text)

    def run(self, files):
        
        for f in files:
            meta = self.metadata(f)
            title = meta.get('confluence-page-title',
                             self.title_from_path(f))
            space_key = meta.get('confluence-space-key',
                                 self.default_space)
            page_id = meta.get('confluence-page-id')
            log.debug(title)
            body = self.convert(f)
            prev = self.get_page(title, space_key=space_key, page_id=page_id)
            log.debug(prev)
            log.debug(self.metadata(f))
            if prev is None:
                self.create_page(title, body, space_key=space_key)
                print(f + ": created")
            else:
                prev_body = self.strip_tags(prev['body_editor'])
                this_body = self.strip_tags(self.get_conversion(body))
                if prev_body != this_body or self.force_update:
                    # Show a diff in verbose mode
                    log.info('Diff of ' + f + ' changes:\n' + ''.join(difflib.unified_diff(
                        prev_body.splitlines(keepends=True),
                        this_body.splitlines(keepends=True),
                        fromfile='old',
                        tofile='new')))
                    self.update_page(title, body, prev['id'], prev['version'])
                    print(f + ": updated")
                else:
                    print(f + ": no change")

def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description="""
Simple Markdown-to-Confluence uploader, using pandoc and the Confluence REST
API.

required environment variables:
    CONFLUENCE_USER
    CONFLUENCE_PASSWORD
    CONFLUENCE_URL
""")
        #usage="%(prog)s [options] -s <space-key> <files>")
    parser.add_argument("-v", "--verbose",
        action="count",
        default=0,
        help="Show more debugging statements (can be repeated)")
    parser.add_argument("-s", "--space-key",
        default=None,
        help='Confluence Space Key (usually like "PROJ" or "~username")')
    parser.add_argument("-f", "--force",
        action='store_true',
        help='Forces an update even if we think nothing has changed')
    parser.add_argument("--no-header",
        action='store_true',
        help='Disables inserting disclaimer headers into the confluence document')
    parser.add_argument("--toc",
        action='store_true',
        help='Inserts table-of-contents into the confluence document')
    parser.add_argument("FILE", nargs='+')

    args = parser.parse_args()

    if args.verbose > 1:
        log.basicConfig(format="%(levelname)s: %(message)s", level=log.DEBUG)
    elif args.verbose > 0:
        log.basicConfig(format="%(levelname)s: %(message)s", level=log.INFO)
    else:
        log.basicConfig(format="%(levelname)s: %(message)s", level=log.WARN)

    try:
        user = os.environ['CONFLUENCE_USER']
        password = os.environ['CONFLUENCE_PASSWORD']
        url = os.environ['CONFLUENCE_URL']
    except KeyError:
        parser.exit(-1, "Need to pass environment variable configs (see --help)\n")

    log.info("User: " + user)
    log.info("URL: " + url)

    if url.endswith('/'):
        url = url[:-1]

    if args.space_key is None:
        args.space_key = "~" + user
        log.warn("Defaulting to home space: %s" % args.space_key)

    try:
        subprocess.check_output(['pandoc', '--version'])
    except:
        parser.exit(-1, "This script depends on 'pandoc', which doesn't "
            "seem to be installed.\n")

    dp = DivergenceProgram(user,password, url, args.space_key,
        force_update=args.force,
        include_header=not args.no_header,
        include_toc=args.toc)
    dp.run(args.FILE)

if __name__ == '__main__':
    main()