Debian Codegraph @

bugwarrior/services/gitlab.py

raw ◀ ▶
1 Debian patch touch this file
1 # coding: utf-8
2 from builtins import map
3 from builtins import filter
4
5 try:
6 from urllib import quote, urlencode # Python 2.X
7 except ImportError:
8 from urllib.parse import quote, urlencode # Python 3+
9 from six.moves.configparser import NoOptionError
10 import re
11 import requests
12 import six
13
14 from jinja2 import Template
15
16 from bugwarrior.config import asbool, aslist, die
17 from bugwarrior.services import IssueService, Issue, ServiceClient
18
19 import logging
20 log = logging.getLogger(__name__)
21
22
23 class GitlabIssue(Issue):
24 TITLE = 'gitlabtitle'
25 DESCRIPTION = 'gitlabdescription'
26 CREATED_AT = 'gitlabcreatedon'
27 UPDATED_AT = 'gitlabupdatedat'
28 DUEDATE = 'gitlabduedate'
29 MILESTONE = 'gitlabmilestone'
30 URL = 'gitlaburl'
31 REPO = 'gitlabrepo'
32 TYPE = 'gitlabtype'
33 NUMBER = 'gitlabnumber'
34 STATE = 'gitlabstate'
35 UPVOTES = 'gitlabupvotes'
36 DOWNVOTES = 'gitlabdownvotes'
37 WORK_IN_PROGRESS = 'gitlabwip'
38 AUTHOR = 'gitlabauthor'
39 ASSIGNEE = 'gitlabassignee'
40 NAMESPACE = 'gitlabnamespace'
41 WEIGHT = 'gitlabweight'
42
43 UDAS = {
44 TITLE: {
45 'type': 'string',
46 'label': 'Gitlab Title',
47 },
48 DESCRIPTION: {
49 'type': 'string',
50 'label': 'Gitlab Description',
51 },
52 CREATED_AT: {
53 'type': 'date',
54 'label': 'Gitlab Created',
55 },
56 UPDATED_AT: {
57 'type': 'date',
58 'label': 'Gitlab Updated',
59 },
60 DUEDATE: {
61 'type': 'date',
62 'label': 'Gitlab Due Date',
63 },
64 MILESTONE: {
65 'type': 'string',
66 'label': 'Gitlab Milestone',
67 },
68 URL: {
69 'type': 'string',
70 'label': 'Gitlab URL',
71 },
72 REPO: {
73 'type': 'string',
74 'label': 'Gitlab Repo Slug',
75 },
76 TYPE: {
77 'type': 'string',
78 'label': 'Gitlab Type',
79 },
80 NUMBER: {
81 'type': 'string',
82 'label': 'Gitlab Issue/MR #',
83 },
84 STATE: {
85 'type': 'string',
86 'label': 'Gitlab Issue/MR State',
87 },
88 UPVOTES: {
89 'type': 'numeric',
90 'label': 'Gitlab Upvotes',
91 },
92 DOWNVOTES: {
93 'type': 'numeric',
94 'label': 'Gitlab Downvotes',
95 },
96 WORK_IN_PROGRESS: {
97 'type': 'numeric',
98 'label': 'Gitlab MR Work-In-Progress Flag',
99 },
100 AUTHOR: {
101 'type': 'string',
102 'label': 'Gitlab Author',
103 },
104 ASSIGNEE: {
105 'type': 'string',
106 'label': 'Gitlab Assignee',
107 },
108 NAMESPACE: {
109 'type': 'string',
110 'label': 'Gitlab Namespace',
111 },
112 WEIGHT: {
113 'type': 'numeric',
114 'label': 'Gitlab Weight',
115 },
116 }
117 UNIQUE_KEY = (REPO, TYPE, NUMBER,)
118
119 def _normalize_label_to_tag(self, label):
120 return re.sub(r'[^a-zA-Z0-9]', '_', label)
121
122 def to_taskwarrior(self):
123 author = self.record['author']
124 milestone = self.record.get('milestone')
125 created = self.record['created_at']
126 updated = self.record.get('updated_at')
127 state = self.record['state']
128 upvotes = self.record.get('upvotes', 0)
129 downvotes = self.record.get('downvotes', 0)
130 work_in_progress = int(asbool(self.record.get('work_in_progress', 0)))
131 assignee = self.record.get('assignee')
132 duedate = self.record.get('due_date')
133 weight = self.record.get('weight')
134 number = (
135 self.record['id'] if self.extra['type'] == 'todo'
136 else self.record['iid'])
137 priority = (
138 self.origin['default_priority'] if self.extra['type'] == 'issue'
139 else 'H')
140 title = (
141 'Todo from %s for %s' % (author['name'], self.extra['project'])
142 if self.extra['type'] == 'todo' else self.record['title'])
143 description = (
144 self.record['body'] if self.extra['type'] == 'todo'
145 else self.record['description'])
146
147 if milestone and (
148 self.extra['type'] == 'issue' or
149 (self.extra['type'] == 'merge_request' and duedate is None)):
150 duedate = milestone['due_date']
151 if milestone:
152 milestone = milestone['title']
153 if created:
154 created = self.parse_date(created).replace(microsecond=0)
155 if updated:
156 updated = self.parse_date(updated).replace(microsecond=0)
157 if duedate:
158 duedate = self.parse_date(duedate)
159 if author:
160 author = author['username']
161 if assignee:
162 assignee = assignee['username']
163
164
165 self.title = title
166
167 return {
168 'project': self.extra['project'],
169 'priority': priority,
170 'annotations': self.extra.get('annotations', []),
171 'tags': self.get_tags(),
172 'due': duedate,
173 'entry': created,
174
175 self.URL: self.extra['issue_url'],
176 self.REPO: self.extra['project'],
177 self.TYPE: self.extra['type'],
178 self.TITLE: title,
179 self.DESCRIPTION: description,
180 self.MILESTONE: milestone,
181 self.NUMBER: str(number),
182 self.CREATED_AT: created,
183 self.UPDATED_AT: updated,
184 self.DUEDATE: duedate,
185 self.STATE: state,
186 self.UPVOTES: upvotes,
187 self.DOWNVOTES: downvotes,
188 self.WORK_IN_PROGRESS: work_in_progress,
189 self.AUTHOR: author,
190 self.ASSIGNEE: assignee,
191 self.NAMESPACE: self.extra['namespace'],
192 self.WEIGHT: weight,
193 }
194
195 def get_tags(self):
196 tags = []
197
198 if not self.origin['import_labels_as_tags']:
199 return tags
200
201 context = self.record.copy()
202 label_template = Template(self.origin['label_template'])
203
204 for label in self.record.get('labels', []):
205 context.update({
206 'label': self._normalize_label_to_tag(label)
207 })
208 tags.append(
209 label_template.render(context)
210 )
211
212 return tags
213
214 def get_default_description(self):
215 return self.build_default_description(
216 title=self.title,
217 url=self.get_processed_url(self.extra['issue_url']),
218 number=self.record.get('iid', ''),
219 cls=self.extra['type'],
220 )
221
222
223 class GitlabService(IssueService, ServiceClient):
224 ISSUE_CLASS = GitlabIssue
225 CONFIG_PREFIX = 'gitlab'
226
227 def __init__(self, *args, **kw):
228 super(GitlabService, self).__init__(*args, **kw)
229
230 host = self.config.get(
231 'host', default='gitlab.com', to_type=six.text_type)
232 self.login = self.config.get('login')
233 token = self.get_password('token', self.login)
234 self.auth = (host, token)
235
236 if self.config.get('use_https', default=True, to_type=asbool):
237 self.scheme = 'https'
238 else:
239 self.scheme = 'http'
240
241 self.verify_ssl = self.config.get(
242 'verify_ssl', default=True, to_type=asbool
243 )
244
245 self.membership = self.config.get('membership', False)
246
247 self.owned = self.config.get('owned', False)
248
249 self.exclude_repos = self.config.get('exclude_repos', [], aslist)
250 self.include_repos = self.config.get('include_repos', [], aslist)
251 self.exclude_regex = self.config.get('exclude_regex', None)
252 self.include_regex = self.config.get('include_regex', None)
253
254 self.include_repos = list(map(self.add_default_namespace, self.include_repos))
255 self.exclude_repos = list(map(self.add_default_namespace, self.exclude_repos))
256 self.include_regex = re.compile(self.include_regex) if self.include_regex else None
257 self.exclude_regex = re.compile(self.exclude_regex) if self.exclude_regex else None
258
259 self.import_labels_as_tags = self.config.get(
260 'import_labels_as_tags', default=False, to_type=asbool
261 )
262 self.label_template = self.config.get(
263 'label_template', default='{{label}}', to_type=six.text_type
264 )
265 self.filter_merge_requests = self.config.get(
266 'filter_merge_requests', default=False, to_type=asbool
267 )
268 self.include_todos = self.config.get(
269 'include_todos', default=False, to_type=asbool
270 )
271 self.include_all_todos = self.config.get(
272 'include_all_todos', default=True, to_type=asbool
273 )
274 self.project_owner_prefix = self.config.get(
275 'project_owner_prefix', default=False, to_type=asbool
276 )
277
278 def add_default_namespace(self, repo):
279 """ Add a default namespace to a repository name. If the name already
280 contains a namespace, it will be returned unchanged:
281 e.g. "foo/bar" → "foo/bar"
282 otherwise, the loggin will be prepended as namespace:
283 e.g. "bar" → "<login>/bar"
284 """
285 if not repo.startswith('id:') and repo.find('/') < 0:
286 return self.login + '/' + repo
287 else:
288 return repo
289
290 @staticmethod
291 def get_keyring_service(service_config):
292 login = service_config.get('login')
293 host = service_config.get('host', default='gitlab.com')
294 return "gitlab://%s@%s" % (login, host)
295
296 def get_service_metadata(self):
297 return {
298 'import_labels_as_tags': self.import_labels_as_tags,
299 'label_template': self.label_template,
300 }
301
302
303 def get_owner(self, issue):
304 if issue[1]['assignee'] != None and issue[1]['assignee']['username']:
305 return issue[1]['assignee']['username']
306
307 def get_author(self, issue):
308 if issue[1]['author'] != None and issue[1]['author']['username']:
309 return issue[1]['author']['username']
310
311 def filter_repos(self, repo):
312 if self.exclude_repos:
313 if repo['path_with_namespace'] in self.exclude_repos or "id:%d" % repo['id'] in self.exclude_repos:
314 return False
315
316 if self.exclude_regex:
317 if self.exclude_regex.match(repo['path_with_namespace']):
318 return False
319
320 # fallback if no filter is set
321 is_included = True
322
323 if self.include_repos:
324 if repo['path_with_namespace'] in self.include_repos or "id:%d" % repo['id'] in self.include_repos:
325 return True
326 else:
327 is_included = False
328
329 if self.include_regex:
330 if self.include_regex.match(repo['path_with_namespace']):
331 return True
332 else:
333 is_included = False
334
335 return is_included
336
337 def _get_notes(self, rid, issue_type, issueid):
338 tmpl = '{scheme}://{host}/api/v4/projects/%d/%s/%d/notes' % (rid, issue_type, issueid)
339 return self._fetch_paged(tmpl)
340
341 def annotations(self, repo, url, issue_type, issue, issue_obj):
342 annotations = []
343
344 if self.annotation_comments:
345 notes = self._get_notes(repo['id'], issue_type, issue['iid'])
346 annotations = ((
347 n['author']['username'],
348 n['body']
349 ) for n in notes)
350
351 return self.build_annotations(
352 annotations,
353 issue_obj.get_processed_url(url)
354 )
355
356 def _fetch(self, tmpl, **kwargs):
357 url = tmpl.format(scheme=self.scheme, host=self.auth[0])
358 headers = {'PRIVATE-TOKEN': self.auth[1]}
359
360 if not self.verify_ssl:
361 requests.packages.urllib3.disable_warnings()
362 response = requests.get(url, headers=headers, verify=self.verify_ssl, **kwargs)
363
364 return self.json_response(response)
365
366 def _fetch_paged(self, tmpl):
367 params = {
368 'page': 1,
369 'per_page': 100,
370 }
371
372 full = []
373 detect_broken_gitlab_pagination = []
374 while True:
375 items = self._fetch(tmpl, params=params)
376 if not items:
377 break
378
379 # XXX: Some gitlab versions have a bug where pagination doesn't
380 # work and instead return the entire result no matter what. Detect
381 # this by seeing if the results are the same as the last time
382 # around and bail if so. Unfortunately, while it is a GitLab bug,
383 # we have to deal with instances where it exists.
384 if items == detect_broken_gitlab_pagination:
385 break
386 detect_broken_gitlab_pagination = items
387
388 full += items
389
390 if len(items) < params['per_page']:
391 break
392 params['page'] += 1
393
394 return full
395
396 def get_repo_issues(self, rid):
397 tmpl = '{scheme}://{host}/api/v4/projects/%d/issues?state=opened' % rid
398 issues = {}
399 try:
400 repo_issues = self._fetch_paged(tmpl)
401 except IOError:
402 # Projects may have issues disabled.
403 return {}
404 for issue in repo_issues:
405 issues[issue['id']] = (rid, issue)
406 return issues
407
408 def get_repo_merge_requests(self, rid):
409 tmpl = '{scheme}://{host}/api/v4/projects/%d/merge_requests?state=opened' % rid
410 issues = {}
411 try:
412 repo_merge_requests = self._fetch_paged(tmpl)
413 except IOError:
414 # Projects may have merge requests disabled.
415 return {}
416 for issue in repo_merge_requests:
417 issues[issue['id']] = (rid, issue)
418 return issues
419
420 def get_todos(self):
421 tmpl = '{scheme}://{host}/api/v4/todos?state=pending'
422 todos = []
423 try:
424 fetched_todos = self._fetch_paged(tmpl)
425 except IOError:
426 # Older gitlab versions do not have todo items.
427 return {}
428 for todo in fetched_todos:
429 todos.append((todo.get('project'), todo))
430 return todos
431
432 def include_todo(self, repos):
433 ids = list(r['id'] for r in repos)
434
435 def include_todo(todo):
436 project, todo = todo
437 return project is None or project['id'] in ids
438 return include_todo
439
440 def _get_issue_objs(self, issues, issue_type, repo_map):
441 type_plural = issue_type + 's'
442
443 for rid, issue in issues:
444 repo = repo_map[rid]
445 issue['repo'] = repo['path']
446 projectName = repo['path']
447 if self.project_owner_prefix:
448 projectName = repo['namespace']['path'] + "." + projectName
449 issue_obj = self.get_issue_for_record(issue)
450 issue_url = '%s/%s/%d' % (repo['web_url'], type_plural, issue['iid'])
451 extra = {
452 'issue_url': issue_url,
453 'project': repo['path'],
454 'namespace': repo['namespace']['full_path'],
455 'type': issue_type,
456 'annotations': self.annotations(repo, issue_url, type_plural, issue, issue_obj)
457 }
458 issue_obj.update_extra(extra)
459 yield issue_obj
460
461 def issues(self):
462 tmpl = '{scheme}://{host}/api/v4/projects'
463
464 all_repos = []
465 if self.include_repos and not self.include_regex:
466 for repo in self.include_repos:
467 if repo.startswith("id:"):
468 repo = repo[3:]
469 indiv_tmpl = tmpl + '/' + quote(repo, '') + '?simple=true'
470 item = self._fetch(indiv_tmpl)
471 if not item:
472 break
473
474 all_repos.append(item)
475
476 else:
477 querystring = { 'simple': True }
478 if self.membership:
479 querystring['membership'] = True
480 if self.owned:
481 querystring['owned'] = True
482 all_repos = self._fetch_paged(tmpl + '?' + urlencode(querystring))
483
484 repos = list(filter(self.filter_repos, all_repos))
485
486 repo_map = {}
487 issues = {}
488 for repo in repos:
489 rid = repo['id']
490 repo_map[rid] = repo
491 issues.update(
492 self.get_repo_issues(rid)
493 )
494 log.debug(" Found %i issues.", len(issues))
495 issues = list(filter(self.include, issues.values()))
496 log.debug(" Pruned down to %i issues.", len(issues))
497
498 for issue in self._get_issue_objs(issues, 'issue', repo_map):
499 yield issue
500
501 if not self.filter_merge_requests:
502 merge_requests = {}
503 for repo in repos:
504 rid = repo['id']
505 merge_requests.update(
506 self.get_repo_merge_requests(rid)
507 )
508 log.debug(" Found %i merge requests.", len(merge_requests))
509 merge_requests = list(filter(self.include, merge_requests.values()))
510 log.debug(" Pruned down to %i merge requests.", len(merge_requests))
511
512 for issue in self._get_issue_objs(merge_requests,
513 'merge_request',
514 repo_map):
515 yield issue
516
517 if self.include_todos:
518 todos = self.get_todos()
519 log.debug(" Found %i todo items.", len(todos))
520 if not self.include_all_todos:
521 todos = list(filter(self.include_todo(repos), todos))
522 log.debug(" Pruned down to %i todos.", len(todos))
523
524 for project, todo in todos:
525 if project is not None:
526 repo = project
527 else:
528 repo = {
529 'path': 'the instance',
530 }
531 todo['repo'] = repo['path']
532
533 todo_obj = self.get_issue_for_record(todo)
534 todo_url = todo['target_url']
535 projectName = repo['path']
536 if self.project_owner_prefix:
537 projectName = repo['namespace']['path'] + "." + projectName
538 extra = {
539 'issue_url': todo_url,
540 'project': projectName,
541 'namespace': "todo",
542 'type': 'todo',
543 'annotations': [],
544 }
545 todo_obj.update_extra(extra)
546 yield todo_obj
547
548 @classmethod
549 def validate_config(cls, service_config, target):
550 if 'host' not in service_config:
551 die("[%s] has no 'gitlab.host'" % target)
552
553 if 'login' not in service_config:
554 die("[%s] has no 'gitlab.login'" % target)
555
556 if 'token' not in service_config:
557 die("[%s] has no 'gitlab.token'" % target)
558
559 super(GitlabService, cls).validate_config(service_config, target)