summaryrefslogtreecommitdiff
path: root/bzxmltophill
blob: 64fdddafa68a011d3a4a8b2608f73e685f52b3b0 (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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
#!/usr/bin/env python3

"""Converts Bugzilla XML files to something Phabricator's Phill may like.

Usage:
  bzxmltophill <data>

Options:
  -h --help         Show this screen.
  --version         Show version.
"""

from docopt import docopt
from datetime import datetime
import xml.etree.ElementTree as ET
import json
import os
import re
import glob

try:
    from config import project_ids
except:
    project_ids = {}

try:
    from config import project_names
except:
    project_names = {}

class Converter:
    def __init__(self):
        self.root = None

    def url(self, i):
        return self.base_url + "/show_bug.cgi?id=" + i.findtext("bug_id")

    def load(self, filename):
        self.root = ET.parse(filename).getroot()
        self.base_url = self.root.get("urlbase")

    def convert(self):
        projects = self.projects_convert()
        tasks = self.issues_convert()
        r = {
            'projects': projects,
            'tasks': tasks
        }
        return r

    def date_to_iso(self, datestr):
        iso = datetime.strptime(datestr, '%Y-%m-%d %H:%M:%S +%f').isoformat()
        return iso

    def user_email(self, key):
        return self.bytype['users'][key]['emailAddress']

    def markup_parse(self, markup):
        if not markup:
            return None
        # turn [text|link] to [[link|text]]
        markup = re.sub(r'\[(.*)\|(.*)\]', r'[[\2|\1]]', markup)
        # turn {{code}} to ##code##
        markup = re.sub(r'{{(.*?)}}', r'##\1##', markup)
        markup = markup.replace('{code}', '```')
        return markup

    def get_project_ids(self, bug):
        id_cleaner = re.compile('[^a-zA-Z]')
        product_id = project_ids.get(bug.findtext("product"),
                                     id_cleaner.sub("", bug.findtext("product")).upper())

        product_name = self.clean_project_name(bug.findtext("product"))

        component_id = project_ids.get(bug.findtext("component"),
                                       id_cleaner.sub("", bug.findtext("component")).upper())
        component_name = self.clean_project_name(bug.findtext("component"))

        return [(product_id, product_name),
                (component_id, component_name)]

    def clean_project_name(self, name):
        try:
            return project_names[name]
        except KeyError:
            return name.replace("-", " ").replace("_", " ")

    def projects_convert(self):
        all_projects = {}
        for bug in self.root.findall('bug'):

            project_ids = self.get_project_ids(bug)
            for project_id, project_name in project_ids:
                project = all_projects.get(project_id)
                if not project:
                    project = self.create_project(project_id,
                                                  project_name,
                                                  bug)
                    all_projects[project_id] = project
        return [p for _, p in sorted(all_projects.items())]

    def create_project(self, pid, name, bug):
        ret = {
            'id': pid,
            'name': name,
            'description': "Please add a project description",
            'tracker': 'Bugzilla',
            'url': "%s/buglist.cgi?component=%s&product=%s" % (self.base_url, bug.findtext("component"), bug.findtext("product")),
            'creator': bug.findtext("assigned_to"),
            'creationDate': self.date_to_iso(bug.findtext("creation_ts")),
        }

        members = []
        for bug in self.root.findall('bug'):
            members.append(bug.findtext("reporter"))
            members.append(bug.findtext("assigned_to"))
            for member in bug.findall("cc"):
                members.append(member.text)

        ret['members'] = list(set(members))
        return ret

    def transaction_create(self, actor, date, kind, value=None, comment=None):
        ret = {
            'actor': actor,
            'date': date,
            'type': kind,
        }
        if value:
            ret['value'] = value
        if comment:
            ret['comment'] = comment
        return ret

    def issues_convert(self):
        tasks = [self.issue_convert(bug) for bug in self.root.findall("bug")]
        return tasks

    def priority_parse(self, status):
        m = {
            "blocker": 100,
            "critical": 80,
            "major": 80,
            "normal": 50,
            "minor": 25,
            "trivial": 25,
            "enhancement": 0,
            "---": 0,
        }

        return m[status]

    def status_parse(self, bug):
        status = bug.findtext("bug_status")
        resolution = bug.findtext("resolution")
        if resolution:
            status = resolution

        m = {
            "NEW": "open",
            "REOPENED": "open",
            "NEEDINFO": "open",
            "ASSIGNED": "open",
            "FIXED": "resolved",
            "INCOMPLETE": "spite",
            "NOTGNOME": "spite",
            "NOTABUG": "spite",
            "WONTFIX": "spite",
            "INVALID": "spite",
            "OBSOLETE": "spite",
            "DUPLICATE": "duplicate",
            "UNCONFIRMED": "open",
            "WORKSFORME": "open",
            "WAITING_FOR_UPSTREAM": "spite",
            "CONFIRMED": "open",
            "CLOSED": "resolved",
            "IN_PROGRESS": "open",
            "FIX_PROPOSED": "spite",
            "FIX_SUBMITTED": "spite",
        }
        return m[status]

    def find_attachement(self, bug, id):
        for attachment in bug.findall("attachment"):
            if attachment.findtext("attachid") == id:
                return attachment

        return None

    def get_attachement(self, attachment):
        attachid = attachment.findtext("attachid")
        return "attachement/attach.%s.dat" % attachid

    def convert_transactions(self, bug):
        transactions = []

        transactions.append(self.transaction_create(bug.findtext("assigned_to"),
                                                    self.date_to_iso(bug.findtext("creation_ts")),
                                                    "projects",
                                                    {'=': [id_name[0] for id_name in self.get_project_ids(bug)]}))

        for comment in bug.findall("long_desc")[1:]:
            attachid = comment.find("attachid")
            if attachid is not None:
                attachid = attachid.text
                attachment = self.find_attachement(bug, attachid)

                value = {
                    'author': attachment.findtext("attacher"),
                    'data': self.get_attachement(attachment),
                    'name': attachment.findtext("filename"),
                    'mimetype': attachment.findtext("type"),
                    'ispatch': attachment.attrib["ispatch"],
                    'isobsolete': attachment.attrib["isobsolete"],
                    'patchstatus': attachment.findtext("gnome_attachment_status"),
                }

                transaction = self.transaction_create(comment.findtext("who"),
                                                      self.date_to_iso(comment.findtext("bug_when")),
                                                      "attachment",
                                                      value)
                transactions.append(transaction)

            transaction = self.transaction_create(comment.findtext("who"),
                                                  self.date_to_iso(comment.findtext("bug_when")),
                                                  "comment",
                                                  comment=comment.findtext("thetext"))
            transactions.append(transaction)

        transactions.append(self.transaction_create(bug.findtext("assigned_to"),
                                                    self.date_to_iso(bug.findtext("creation_ts")),
                                                    "priority",
                                                    self.priority_parse(bug.findtext("bug_severity"))))

        transactions.append(self.transaction_create(bug.findtext("assigned_to"),
                                                    self.date_to_iso(bug.findtext("creation_ts")),
                                                    "status",
                                                    self.status_parse(bug)))

        transactions.append(self.transaction_create(bug.findtext("assigned_to"),
                                                    self.date_to_iso(bug.findtext("creation_ts")),
                                                    "owner",
                                                    bug.findtext("assigned_to")))

        transactions.append(self.transaction_create(bug.findtext("assigned_to"),
                                                    self.date_to_iso(bug.findtext("creation_ts")),
                                                    "owner",
                                                    bug.findtext("assigned_to")))

        for cc in bug.findall("cc"):
            transactions.append(self.transaction_create(bug.findtext("assigned_to"),
                                                        self.date_to_iso(bug.findtext("creation_ts")),
                                                        "subscribers",
                                                        {"+": [cc.text]}))

        return transactions

    def issue_convert(self, i):
        reporter = i.findtext("reporter")
        date = self.date_to_iso(i.findtext("creation_ts"))
        ret = {
            'id': i.findtext("bug_id"),
            'url': self.url(i),
            'title': i.findtext("short_desc"),
            'creationDate': date,
            'creator': reporter,
            'description': i.find("long_desc").findtext("thetext"),
            'transactions': self.convert_transactions(i)
        }
        return ret


def main(arguments):
    data = arguments.get("<data>")
    if os.path.isdir(data):
        filenames = glob.glob(os.path.join(data, "bugs.*.xml"))
    else:
        filenames = [data]

    converter = Converter()

    for filename in filenames:
        converter.load(filename)
        data = converter.convert()

        with open(os.path.splitext(filename)[0]+".json", "w") as f:
            json.dump(data, f, sort_keys=True, indent=4)

if __name__ == '__main__':
    arguments = docopt(__doc__, version='bztophill 0.1')
    main(arguments)