Debian Codegraph @

bugwarrior/services/gitlab.py

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