Completed
Push — master ( f0fc46...b442ce )
by Gonzalo
9s
created

parse_arguments()   F

Complexity

Conditions 12

Size

Total Lines 152

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 12
c 1
b 0
f 0
dl 0
loc 152
rs 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like parse_arguments() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
# -*- coding: utf-8 -*-
2
# -----------------------------------------------------------------------------
3
# Copyright (c) The Spyder Development Team
4
#
5
# Licensed under the terms of the MIT License
6
# (See LICENSE.txt for details)
7
# -----------------------------------------------------------------------------
8
"""Build a list of issues and pull requests per Github milestone."""
9
10
from __future__ import print_function
11
12
# Standard library imports
13
import argparse
14
import getpass
15
import re
16
import sys
17
import time
18
19
# Third party imports
20
from jinja2 import Template
21
22
# Local imports
23
from loghub.repo import GitHubRepo
24
from loghub.templates import (CHANGELOG_GROUPS_TEMPLATE_PATH,
25
                              CHANGELOG_TEMPLATE_PATH, RELEASE_TEMPLATE_PATH)
26
27
PY2 = sys.version[0] == '2'
28
29
30
def parse_arguments(skip=False):
31
    """Main script."""
32
    # Cli options
33
    parser = argparse.ArgumentParser(
34
        description='Script to print the list of issues and pull requests '
35
        'closed in a given milestone')
36
    parser.add_argument(
37
        'repository',
38
        help="Repository name to generate the Changelog for, in the form "
39
        "user/repo or org/repo (e.g. spyder-ide/spyder)")
40
    parser.add_argument(
41
        '-m',
42
        '--milestone',
43
        action="store",
44
        dest="milestone",
45
        default='',
46
        help="Github milestone to get issues and pull requests for")
47
    parser.add_argument(
48
        '-ilg',
49
        '--issue-label-group',
50
        action="append",
51
        nargs='+',
52
        dest="issue_label_groups",
53
        help="Groups the generated issues by the specified label. This option"
54
        "Takes 1 or 2 arguments, where the first one is the label to "
55
        "match and the second one is the label to print on the final"
56
        "output")
57
    parser.add_argument(
58
        '-ilr',
59
        '--issue-label-regex',
60
        action="store",
61
        dest="issue_label_regex",
62
        default='',
63
        help="Label issue filter using a regular expression filter")
64
    parser.add_argument(
65
        '-plr',
66
        '--pr-label-regex',
67
        action="store",
68
        dest="pr_label_regex",
69
        default='',
70
        help="Label pull requets filter using a regular expression filter")
71
    parser.add_argument(
72
        '-st',
73
        '--since-tag',
74
        action="store",
75
        dest="since_tag",
76
        default='',
77
        help="Github issues and pull requests since tag")
78
    parser.add_argument(
79
        '-ut',
80
        '--until-tag',
81
        action="store",
82
        dest="until_tag",
83
        default='',
84
        help="Github issues and pull requests until tag")
85
    parser.add_argument(
86
        '-b',
87
        '--branch',
88
        action="store",
89
        dest="branch",
90
        default='',
91
        help="Github base branch for merged PRs")
92
    parser.add_argument(
93
        '-f',
94
        '--format',
95
        action="store",
96
        dest="output_format",
97
        default='changelog',
98
        help="Format for print, either 'changelog' (for "
99
        "Changelog.md file) or 'release' (for the Github "
100
        "Releases page). Default is 'changelog'. The "
101
        "'release' option doesn't generate Markdown "
102
        "hyperlinks.")
103
    parser.add_argument(
104
        '--template',
105
        action="store",
106
        dest="template",
107
        default='',
108
        help="Use a custom Jinja2 template file ")
109
    parser.add_argument(
110
        '-u',
111
        '--user',
112
        action="store",
113
        dest="user",
114
        default='',
115
        help="Github user name")
116
    parser.add_argument(
117
        '-p',
118
        '--password',
119
        action="store",
120
        dest="password",
121
        default='',
122
        help="Github user password")
123
    parser.add_argument(
124
        '-t',
125
        '--token',
126
        action="store",
127
        dest="token",
128
        default='',
129
        help="Github access token")
130
    options = parser.parse_args()
131
132
    username = options.user
133
    password = options.password
134
    milestone = options.milestone
135
    issue_label_groups = options.issue_label_groups
136
137
    if username and not password:
138
        password = getpass.getpass()
139
140
    # Check if repo given
141
    if not options.repository:
142
        print('LOGHUB: Please define a repository name to this script. '
143
              'See its help')
144
        sys.exit(1)
145
146
    # Check if milestone or tag given
147
    if not milestone and not options.since_tag:
148
        print('\nLOGHUB: Querying all issues\n')
149
    elif milestone:
150
        print('\nLOGHUB: Querying issues for milestone {0}'
151
              '\n'.format(milestone))
152
153
    new_issue_label_groups = []
154
    if issue_label_groups:
155
        for item in issue_label_groups:
156
            dic = {}
157
            if len(item) == 1:
158
                dic['label'] = item[0]
159
                dic['name'] = item[0]
160
            elif len(item) >= 2:
161
                dic['label'] = item[0]
162
                dic['name'] = item[1]
163
            new_issue_label_groups.append(dic)
164
165
    if not skip:
166
        create_changelog(
167
            repo=options.repository,
168
            username=username,
169
            password=password,
170
            token=options.token,
171
            milestone=milestone,
172
            since_tag=options.since_tag,
173
            until_tag=options.until_tag,
174
            branch=options.branch,
175
            issue_label_regex=options.issue_label_regex,
176
            pr_label_regex=options.pr_label_regex,
177
            output_format=options.output_format,
178
            template_file=options.template,
179
            issue_label_groups=new_issue_label_groups)
180
181
    return options
182
183
184
def create_changelog(repo=None,
185
                     username=None,
186
                     password=None,
187
                     token=None,
188
                     milestone=None,
189
                     since_tag=None,
190
                     until_tag=None,
191
                     branch=None,
192
                     output_format='changelog',
193
                     issue_label_regex='',
194
                     pr_label_regex='',
195
                     template_file=None,
196
                     issue_label_groups=None):
197
    """Create changelog data."""
198
    # Instantiate Github API
199
    gh = GitHubRepo(
200
        username=username,
201
        password=password,
202
        token=token,
203
        repo=repo, )
204
205
    version = until_tag or None
206
    milestone_number = None
207
    closed_at = None
208
    since = None
209
    until = None
210
211
    # Set milestone or from tag
212
    if milestone and not since_tag:
213
        milestone_data = gh.milestone(milestone)
214
        milestone_number = milestone_data['number']
215
        closed_at = milestone_data['closed_at']
216
        version = milestone.replace('v', '')
217
    elif not milestone and since_tag:
218
        since = gh.tag(since_tag)['tagger']['date']
219
        if until_tag:
220
            until = gh.tag(until_tag)['tagger']['date']
221
            closed_at = until
222
223
    # This returns issues and pull requests
224
    issues = gh.issues(
225
        milestone=milestone_number,
226
        state='closed',
227
        since=since,
228
        until=until,
229
        branch=branch, )
230
231
    # Filter by regex if available
232
    filtered_issues, filtered_prs = [], []
233
    issue_pattern = re.compile(issue_label_regex)
234
    pr_pattern = re.compile(pr_label_regex)
235
    for issue in issues:
236
        is_pr = bool(issue.get('pull_request'))
237
        is_issue = not is_pr
238
        labels = ' '.join(issue.get('loghub_label_names'))
239
240
        if is_issue and issue_label_regex:
241
            issue_valid = bool(issue_pattern.search(labels))
242
            if issue_valid:
243
                filtered_issues.append(issue)
244
        elif is_pr and pr_label_regex:
245
            pr_valid = bool(pr_pattern.search(labels))
246
            if pr_valid:
247
                filtered_prs.append(issue)
248
        elif is_issue and not issue_label_regex:
249
            filtered_issues.append(issue)
250
        elif is_pr and not pr_label_regex:
251
            filtered_prs.append(issue)
252
253
    # If issue label grouping, filter issues
254
    new_filtered_issues = []
255
    if issue_label_groups:
256
        for issue in issues:
257
            for label_group_dic in issue_label_groups:
258
                labels = issue.get('loghub_label_names')
259
                label = label_group_dic['label']
260
                if label in labels:
261
                    new_filtered_issues.append(issue)
262
    else:
263
        new_filtered_issues = filtered_issues
264
265
    return format_changelog(
266
        repo,
267
        new_filtered_issues,
268
        filtered_prs,
269
        version,
270
        closed_at=closed_at,
271
        output_format=output_format,
272
        template_file=template_file,
273
        issue_label_groups=issue_label_groups)
274
275
276
def format_changelog(repo,
277
                     issues,
278
                     prs,
279
                     version,
280
                     closed_at=None,
281
                     output_format='changelog',
282
                     output_file='CHANGELOG.temp',
283
                     template_file=None,
284
                     issue_label_groups=None):
285
    """Create changelog data."""
286
    # Header
287
    if version and version[0] == 'v':
288
        version = version.replace('v', '')
289
    else:
290
        version = '<RELEASE_VERSION>'
291
292
    if closed_at:
293
        close_date = closed_at.split('T')[0]
294
    else:
295
        close_date = time.strftime("%Y/%m/%d")
296
297
    # Load template
298
    if template_file:
299
        filepath = template_file
300
    else:
301
        if output_format == 'changelog':
302
            filepath = CHANGELOG_TEMPLATE_PATH
303
        else:
304
            filepath = RELEASE_TEMPLATE_PATH
305
306
    if issue_label_groups:
307
        filepath = CHANGELOG_GROUPS_TEMPLATE_PATH
308
309
    with open(filepath) as f:
310
        data = f.read()
311
312
    repo_owner, repo_name = repo.split('/')
313
    template = Template(data)
314
    rendered = template.render(
315
        issues=issues,
316
        pull_requests=prs,
317
        version=version,
318
        close_date=close_date,
319
        repo_full_name=repo,
320
        repo_owner=repo_owner,
321
        repo_name=repo_name,
322
        issue_label_groups=issue_label_groups, )
323
324
    print('#' * 79)
325
    print(rendered)
326
    print('#' * 79)
327
328
    with open(output_file, 'w') as f:
329
        f.write(rendered)
330
331
    return rendered
332
333
334
if __name__ == '__main__':  # yapf: disable
335
    parse_arguments()
336