aboutsummaryrefslogtreecommitdiffstats
path: root/divergence
blob: f72d4db59af8527bea39a2a4fc7ac33d63ca30ba (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
#!/usr/bin/env python3
"""
License: MIT
Author: Bryan Newbold <bnewbold@archive.org>
Date: July 2017

See README
"""

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


class DivergenceProgram:

    def __init__(self, user, password, url, space):
        self.api = requests.Session()
        self.api.auth = (user, password)
        self.api.headers.update({'Content-Type': 'application/json'})
        self.base_url = url
        self.space = space

        # TODO: find lua path?

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

        log.debug(resp)
        log.debug(resp.content)
        assert resp.status_code == 200
        respj = resp.json()
        if respj['size'] == 0:
            return None
        assert respj['size'] == 1, "Expect single result for title lookup"
        page = respj['results'][0]
        assert page['space']['key'].upper() == self.space.upper(), "Expect spaces to match"

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

    def create_page(self, title, body):
        resp = self.api.post(self.base_url + "/rest/api/content",
            json={"space": { "key": self.space },
                  "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", "pandoc_confluence.lua", f],
                              stdout=subprocess.PIPE)
        assert proc.returncode == 0
        return proc.stdout.decode('UTF-8')

    def run(self, files):
        
        for f in files:
            title = self.title_from_path(f)
            log.debug(title)
            body = self.convert(f)
            prev = self.get_page(title)
            log.debug(prev)
            if prev is None:
                self.create_page(title, body)
                print(f + ": created")
            else:
                if prev['body'] != body:
                    self.update_page(title, body, prev['id'], prev['version'])
                    print(f + ": updated")
                else:
                    print(f + ": no change")

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

Specify credentials and site URL with 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",
        required=True,
        help='Confluence Space Key (usually like "PROJ" or "~username")')
    parser.add_argument("FILE", nargs='+')

    args = parser.parse_args()

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

    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")

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

    dp = DivergenceProgram(user, password, url, args.space_key)
    dp.run(args.FILE)

if __name__ == '__main__':
    main()