Adrià Vilanova MartÃnez | f19ea43 | 2024-01-23 20:20:52 +0100 | [diff] [blame^] | 1 | # Copyright 2019 The Chromium Authors |
| 2 | # Use of this source code is governed by a BSD-style license that can be |
| 3 | # found in the LICENSE file. |
Copybara | 854996b | 2021-09-07 19:36:02 +0000 | [diff] [blame] | 4 | |
| 5 | """Logic for storing and representing issues from external trackers.""" |
| 6 | |
| 7 | from __future__ import print_function |
| 8 | from __future__ import division |
| 9 | from __future__ import absolute_import |
| 10 | |
| 11 | import re |
| 12 | |
| 13 | from framework.exceptions import InvalidExternalIssueReference |
| 14 | |
| 15 | |
| 16 | class FederatedIssue(object): |
| 17 | """Abstract base class for holding one federated issue. |
| 18 | |
| 19 | Each distinct external tracker should subclass this. |
| 20 | """ |
| 21 | shortlink_re = None |
| 22 | |
| 23 | def __init__(self, shortlink): |
| 24 | if not self.IsShortlinkValid(shortlink): |
| 25 | raise InvalidExternalIssueReference( |
| 26 | 'Shortlink does not match any valid tracker: %s' % shortlink) |
| 27 | |
| 28 | self.shortlink = shortlink |
| 29 | |
| 30 | @classmethod |
| 31 | def IsShortlinkValid(cls, shortlink): |
| 32 | """Returns whether given shortlink is correctly formatted.""" |
| 33 | if not cls.shortlink_re: |
| 34 | raise NotImplementedError() |
| 35 | return re.match(cls.shortlink_re, shortlink) |
| 36 | |
| 37 | |
| 38 | class GoogleIssueTrackerIssue(FederatedIssue): |
| 39 | """Holds one Google Issue Tracker issue. |
| 40 | |
| 41 | URL: https://issuetracker.google.com/ |
| 42 | """ |
| 43 | shortlink_re = r'^b\/\d+$' |
| 44 | url_format = 'https://issuetracker.google.com/issues/{issue_id}' |
| 45 | |
| 46 | def __init__(self, shortlink): |
| 47 | super(GoogleIssueTrackerIssue, self).__init__(shortlink) |
| 48 | self.issue_id = int(self.shortlink[2:]) |
| 49 | |
| 50 | def ToURL(self): |
| 51 | return self.url_format.format(issue_id=self.issue_id) |
| 52 | |
| 53 | def Summary(self): |
| 54 | """Returns a short string description for UI.""" |
| 55 | return 'Google Issue Tracker issue %s.' % self.issue_id |
| 56 | |
| 57 | |
| 58 | # All supported tracker classes. |
| 59 | _federated_issue_classes = [GoogleIssueTrackerIssue] |
| 60 | |
| 61 | |
| 62 | def IsShortlinkValid(shortlink): |
| 63 | """Returns whether the given string is valid for any issue tracker.""" |
| 64 | return any(tracker_class.IsShortlinkValid(shortlink) |
| 65 | for tracker_class in _federated_issue_classes) |
| 66 | |
| 67 | |
| 68 | def FromShortlink(shortlink): |
| 69 | """Returns a FederatedIssue for the first matching tracker. |
| 70 | |
| 71 | If no matching tracker is found, returns None. |
| 72 | """ |
| 73 | for tracker_class in _federated_issue_classes: |
| 74 | if tracker_class.IsShortlinkValid(shortlink): |
| 75 | return tracker_class(shortlink) |
| 76 | |
| 77 | return None |