Completed
Pull Request — master (#34)
by Gonzalo
01:03
created

main()   F

Complexity

Conditions 11

Size

Total Lines 149

Duplication

Lines 0
Ratio 0 %

Importance

Changes 8
Bugs 0 Features 0
Metric Value
cc 11
c 8
b 0
f 0
dl 0
loc 149
rs 3.1764

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 main() 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 main():
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
    create_changelog(
166
        repo=options.repository,
167
        username=username,
168
        password=password,
169
        token=options.token,
170
        milestone=milestone,
171
        since_tag=options.since_tag,
172
        until_tag=options.until_tag,
173
        branch=options.branch,
174
        issue_label_regex=options.issue_label_regex,
175
        pr_label_regex=options.pr_label_regex,
176
        output_format=options.output_format,
177
        template_file=options.template,
178
        issue_label_groups=new_issue_label_groups)
179
180
181
def create_changelog(repo=None,
182
                     username=None,
183
                     password=None,
184
                     token=None,
185
                     milestone=None,
186
                     since_tag=None,
187
                     until_tag=None,
188
                     branch=None,
189
                     output_format='changelog',
190
                     issue_label_regex='',
191
                     pr_label_regex='',
192
                     template_file=None,
193
                     issue_label_groups=None):
194
    """Create changelog data."""
195
    # Instantiate Github API
196
    gh = GitHubRepo(
197
        username=username,
198
        password=password,
199
        token=token,
200
        repo=repo, )
201
202
    version = until_tag or None
203
    milestone_number = None
204
    closed_at = None
205
    since = None
206
    until = None
207
208
    # Set milestone or from tag
209
    if milestone and not since_tag:
210
        milestone_data = gh.milestone(milestone)
211
        milestone_number = milestone_data['number']
212
        closed_at = milestone_data['closed_at']
213
        version = milestone.replace('v', '')
214
    elif not milestone and since_tag:
215
        since = gh.tag(since_tag)['tagger']['date']
216
        if until_tag:
217
            until = gh.tag(until_tag)['tagger']['date']
218
            closed_at = until
219
220
    # This returns issues and pull requests
221
    issues = gh.issues(
222
        milestone=milestone_number,
223
        state='closed',
224
        since=since,
225
        until=until,
226
        branch=branch, )
227
228
    # Filter by regex if available
229
    filtered_issues, filtered_prs = [], []
230
    issue_pattern = re.compile(issue_label_regex)
231
    pr_pattern = re.compile(pr_label_regex)
232
    for issue in issues:
233
        is_pr = bool(issue.get('pull_request'))
234
        is_issue = not is_pr
235
        labels = ' '.join(issue.get('loghub_label_names'))
236
237
        if is_issue and issue_label_regex:
238
            issue_valid = bool(issue_pattern.search(labels))
239
            if issue_valid:
240
                filtered_issues.append(issue)
241
        elif is_pr and pr_label_regex:
242
            pr_valid = bool(pr_pattern.search(labels))
243
            if pr_valid:
244
                filtered_prs.append(issue)
245
        elif is_issue and not issue_label_regex:
246
            filtered_issues.append(issue)
247
        elif is_pr and not pr_label_regex:
248
            filtered_prs.append(issue)
249
250
    # If issue label grouping, filter issues
251
    new_filtered_issues = []
252
    if issue_label_groups:
253
        for issue in issues:
254
            for label_group_dic in issue_label_groups:
255
                labels = issue.get('loghub_label_names')
256
                label = label_group_dic['label']
257
                if label in labels:
258
                    new_filtered_issues.append(issue)
259
    else:
260
        new_filtered_issues = filtered_issues
261
262
    return format_changelog(
263
        repo,
264
        new_filtered_issues,
265
        filtered_prs,
266
        version,
267
        closed_at=closed_at,
268
        output_format=output_format,
269
        template_file=template_file,
270
        issue_label_groups=issue_label_groups)
271
272
273
def format_changelog(repo,
274
                     issues,
275
                     prs,
276
                     version,
277
                     closed_at=None,
278
                     output_format='changelog',
279
                     output_file='CHANGELOG.temp',
280
                     template_file=None,
281
                     issue_label_groups=None):
282
    """Create changelog data."""
283
    # Header
284
    if version and version[0] == 'v':
285
        version = version.replace('v', '')
286
    else:
287
        version = '<RELEASE_VERSION>'
288
289
    if closed_at:
290
        close_date = closed_at.split('T')[0]
291
    else:
292
        close_date = time.strftime("%Y/%m/%d")
293
294
    # Load template
295
    if template_file:
296
        filepath = template_file
297
    else:
298
        if output_format == 'changelog':
299
            filepath = CHANGELOG_TEMPLATE_PATH
300
        else:
301
            filepath = RELEASE_TEMPLATE_PATH
302
303
    if issue_label_groups:
304
        filepath = CHANGELOG_GROUPS_TEMPLATE_PATH
305
306
    with open(filepath) as f:
307
        data = f.read()
308
309
    repo_owner, repo_name = repo.split('/')
310
    template = Template(data)
311
    rendered = template.render(
312
        issues=issues,
313
        pull_requests=prs,
314
        version=version,
315
        close_date=close_date,
316
        repo_full_name=repo,
317
        repo_owner=repo_owner,
318
        repo_name=repo_name,
319
        issue_label_groups=issue_label_groups, )
320
321
    print('#' * 79)
322
    print(rendered)
323
    print('#' * 79)
324
325
    with open(output_file, 'w') as f:
326
        f.write(rendered)
327
328
    return rendered
329
330
331
if __name__ == '__main__':  # yapf: disable
332
    main()
333