aboutsummaryrefslogtreecommitdiff
blob: 4d958b7f332ed1bff379c70a7f329ed7e7590199 (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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# Copyright 2023 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2

# Origins: bugz.cli
# Modifyed by Gentoo Authors.

import re
import os
import xmlrpc

from twisted.internet import defer

from buildbot.process.buildstep import BuildStep
from buildbot.process.results import SUCCESS
from buildbot.process.results import FAILURE
from buildbot.process.results import SKIPPED
from buildbot.plugins import util

from bugz.cli import check_bugz_token, login, list_bugs
from bugz.cli_argparser import make_arg_parser
from bugz.configfile import load_config
from bugz.settings import Settings
from bugz.exceptions import BugzError
from bugz.log import log_error, log_info

from portage.versions import cpv_getversion, pkgsplit, catpkgsplit

# main
def main_bugz(args):
    ArgParser = make_arg_parser()
    opt = ArgParser.parse_args(args)

    ConfigParser = load_config(getattr(opt, 'config_file', None))

    check_bugz_token()
    settings = Settings(opt, ConfigParser)
    return settings

# search
def search_bugz(args):
    settings = main_bugz(args)
    valid_keys = ['alias', 'assigned_to', 'component', 'creator',
                'limit', 'offset', 'op_sys', 'platform',
                'priority', 'product', 'resolution', 'severity',
                'version', 'whiteboard', 'cc']

    params = {}
    d = vars(settings)
    for key in d:
        if key in valid_keys:
            params[key] = d[key]
    if 'search_statuses' in d:
        if 'all' not in d['search_statuses']:
            params['status'] = d['search_statuses']
    if 'terms' in d:
        params['summary'] = d['terms']

    if not params:
        raise BugzError('Please give search terms or options.')

    log_info('Searching for bugs meeting the following criteria:')
    for key in params:
        log_info('   {0:<20} = {1}'.format(key, params[key]))

    login(settings)

    result = settings.call_bz(settings.bz.Bug.search, params)['bugs']

    if not len(result):
        log_info('No bugs found.')
        return []
    else:
        list_bugs(result, settings)
        return result

# post
def post_bugs(args, params):
    """Post a new bug"""
    settings = main_bugz(args)
    result = settings.call_bz(settings.bz.Bug.create, params)
    log_info('Bug %d submitted' % result['id'])
    return result

# modify
def modify_bugs(args, params):
    """Modify an existing bug (eg. adding a comment or changing resolution.)"""
    settings = main_bugz(args)
    if len(params) < 2:
        raise BugzError('No changes were specified')
    result = settings.call_bz(settings.bz.Bug.update, params)
    return result

def attach_bugs(args, params):
    """ Attach a file to a bug given a filename. """
    settings = main_bugz(args)
    fd = open(params['filename'], 'rb')
    params['data'] = xmlrpc.client.Binary(fd.read())
    fd.close()
    result =  settings.call_bz(settings.bz.Bug.add_attachment, params)
    return result

class GetBugs(BuildStep):
    
    name = 'GetBugs'
    description = 'Running'
    descriptionDone = 'Ran'
    descriptionSuffix = None
    haltOnFailure = True
    flunkOnFailure = True

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    @defer.inlineCallbacks
    def find_match(self, buglist):
        log = yield self.addLog('Bugs')
        yield log.addStdout('Open Bugs\n')
        match = False
        for bug in buglist:
            yield log.addStdout(f"Bug: {str(bug['id'])} Summary: {bug['summary']}\n")
            # we splite the lines to lists and try to match the words
            matches = 0
            match_search_text = list(self.getProperty('error_dict')['title_issue'].split())
            match_bug_text = list(bug['summary'].split())
            #FIXME: add check for cp
            for match_word in match_search_text:
                if match_word in match_bug_text:
                    matches = matches + 1
            # try to match the nice words
            matches_nice = 0
            match_search_text_nice = list(self.getProperty('error_dict')['title_issue_nice'].split())
            #FIXME: add check for cp
            for match_word in match_search_text_nice:
                if match_word in match_bug_text:
                    matches_nice = matches_nice + 1
            print(f"Bug: {str(bug['id'])} Matched words: {str(matches)} {str(matches_nice)} Summary: {bug['summary']}")
            #FIXME: set it in bug_config
            if matches >= 6 or matches_nice >= 6:
                match = {}
                match['match'] = True
                match['id'] = bug['id']
                match['summary'] = bug['summary']
        yield log.addStdout(f"Line to match: {self.getProperty('error_dict')['title_issue']}\n")
        yield log.addStdout(f"Line to match: {self.getProperty('error_dict')['title_issue_nice']}\n")
        if match:
            yield log.addStdout('Match bug: YES\n')
            yield log.addStdout(f"Bug: {str(match['id'])} Summary: {match['summary']}\n")
            self.setProperty("bgo", match, 'bgo')
            return match
        yield log.addStdout('Match bug: NO\n')
        return match

    @defer.inlineCallbacks
    def run(self):
        # self.gentooci = self.master.namedServices['services'].namedServices['gentooci']
        cpv = self.getProperty('error_dict')['cpv']
        c = yield catpkgsplit(cpv)[0]
        p = yield catpkgsplit(cpv)[1]
        cp = c + '/' + p
        # search for open bugs
        args = []
        args.append('--skip-auth')
        args.append('search')
        # set limit
        # set date last 30 days
        # search for cp
        args.append(cp)
        print(args)
        buglist = search_bugz(args)
        print(buglist)
        match = self.find_match(buglist)
        #FIXME: set bug id on build in db
        return SUCCESS

class Post(BuildStep):

    name = 'Post bug'
    description = 'Running'
    descriptionSuffix = None
    haltOnFailure = True
    flunkOnFailure = True

    def __init__(self, bug_args, bugs_params, **kwargs):
        self.bug_args = bug_args
        self.bugs_params = bugs_params
        super().__init__(**kwargs)

    @defer.inlineCallbacks
    def run(self):
        #self.gentooci = self.master.namedServices['services'].namedServices['gentooci']
        #bug_config = self.gentooci.config.project['bug_config']
        args = []
        args.append('-u')
        args.append(self.bug_args['user'])
        args.append('-p')
        args.append(self.bug_args['passwd'])
        args.append('post')
        params = {}
        params['product'] = "Gentoo Linux"
        params['component'] = "Current packages"
        params['version'] = "unspecified"
        params['op_sys'] = "Linux"
        params['platform'] = "All"
        params['priority'] = "Normal"
        params['description'] = self.bugs_params['description']
        params['summary'] = self.bugs_params['summary']
        params['assigned_to'] = self.bugs_params['assigned_to']
        #params['cc'] = settings.cc
        params['url'] = self.bugs_params['url']
        bug_info = yield post_bugs(args, params)
        match = {}
        match['match'] = True
        match['id'] = bug_info['id']
        match['summary'] = self.bugs_params['summary']
        self.setProperty("bgo", match, 'bgo')
        print(match)
        self.descriptionDone = f"Bug: {bug_info['id']} submitted"
        #FIXME: update build with bug id
        return SUCCESS

class Modify(BuildStep):
    name = 'Modify'
    description = 'Running'
    descriptionSuffix = None
    haltOnFailure = True
    flunkOnFailure = True

    def __init__(self, bug_args, bug_params, **kwargs):
        self.bug_args = bug_args
        self.bug_params = bug_params
        super().__init__(**kwargs)

    @defer.inlineCallbacks
    def run(self):
        bugid = str(self.getProperty('bgo')['id'])
        args = []
        args.append('-u')
        args.append(self.bug_args['user'])
        args.append('-p')
        args.append(self.bug_args['passwd'])
        args.append('modify')
        args.append(bugid)
        params = {}
        if self.bug_params['comment'] is not None:
            params['comment'] = {}
            params['comment']['body'] = self.bug_params['comment']
        params['ids'] = [bugid]
        print(params)
        bug_info = yield modify_bugs(args, params)
        for bug in bug_info['bugs']:
            changes = bug['changes']
            if not len(changes):
                log_info('Added comment to bug %s' % bug['id'])
            else:
                log_info('Modified the following fields in bug %s' % bug['id'])
                for key in changes:
                    log_info('%-12s: removed %s' %(key, changes[key]['removed']))
                    log_info('%-12s: added %s' %(key, changes[key]['added']))
        self.descriptionDone = f"Modified bug {self.getProperty('bgo')['id']}"
        return SUCCESS

class Attach(BuildStep):
    name = 'Attach'
    description = 'Running'
    descriptionSuffix = None
    haltOnFailure = True
    flunkOnFailure = True

    def __init__(self, bug_args, bug_params, **kwargs):
        self.bug_args = bug_args
        self.bug_params = bug_params
        super().__init__(**kwargs)

    @defer.inlineCallbacks
    def run(self):
        bugid = str(self.getProperty('bgo')['id'])
        args = []
        args.append('-u')
        args.append(self.bug_args['user'])
        args.append('-p')
        args.append(self.bug_args['passwd'])
        args.append('attach')
        args.append(bugid)
        args.append(self.bug_params['filename'])
        summary = os.path.basename(self.bug_params['filename'])

        if not os.path.exists(self.bug_params['filename']):
            raise BugzError('File not found: %s' % self.bug_params['filename'])

        params = {}
        params['ids'] = bugid
        params['file_name'] = summary
        params['summary'] = summary
        if self.bug_params['filename'].endswith('gz'):
            params['content_type'] = 'application/gzip'
        elif self.bug_params['filename'].endswith('bz2'):
            params['content_type'] = 'application/x-bzip'
        elif self.bug_params['filename'].endswith('xz'):
            params['content_type'] = 'application/x-xz'
        else:
            params['content_type'] = 'text/plain'
        #params['comment'] = self.bug_params['comment']
        params['filename'] = self.bug_params['filename']
        print(f"Add params['filename'] to bug {bugid}")
        #params['is_patch'] = is_patch
        bug_info = yield attach_bugs(args, params)
        log_info("'%s' has been attached to bug %s" % (params['filename'], bugid))
        self.descriptionDone = f"{os.path.basename(params['filename'])} has been attached to bug {bugid}"
        return SUCCESS