Debian Codegraph @

scripts/new-change

raw
1 #!/usr/bin/env python
2 """Generate a new changelog entry.
3
4 Usage
5 =====
6
7 To generate a new changelog entry::
8
9 scripts/new-change
10
11 This will open up a file in your editor (via the ``EDITOR`` env var).
12 You'll see this template::
13
14 # Type should be one of: feature, bugfix
15 type:
16
17 # Category is the high level feature area.
18 # This can be a service identifier (e.g ``s3``),
19 # or something like: Paginator.
20 category:
21
22 # A brief description of the change. You can
23 # use github style references to issues such as
24 # "fixes #489", "boto/boto3#100", etc. These
25 # will get automatically replaced with the correct
26 # link.
27 description:
28
29 Fill in the appropriate values, save and exit the editor.
30 Make sure to commit these changes as part of your pull request.
31
32 If, when your editor is open, you decide don't don't want to add a changelog
33 entry, save an empty file and no entry will be generated.
34
35 You can then use the ``scripts/gen-changelog`` to generate the
36 CHANGELOG.rst file.
37
38 """
39
40 import argparse
41 import json
42 import os
43 import random
44 import re
45 import string
46 import subprocess
47 import sys
48 import tempfile
49
50 VALID_CHARS = set(string.ascii_letters + string.digits)
51 CHANGES_DIR = os.path.join(
52 os.path.dirname(os.path.dirname(os.path.abspath(__file__))), '.changes'
53 )
54 TEMPLATE = """\
55 # Type should be one of: feature, bugfix, enhancement, api-change
56 # feature: A larger feature or change in behavior, usually resulting in a
57 # minor version bump.
58 # bugfix: Fixing a bug in an existing code path.
59 # enhancement: Small change to an underlying implementation detail.
60 # api-change: Changes to a modeled API.
61 type: {change_type}
62
63 # Category is the high level feature area.
64 # This can be a service identifier (e.g ``s3``),
65 # or something like: Paginator.
66 category: {category}
67
68 # A brief description of the change. You can
69 # use github style references to issues such as
70 # "fixes #489", "boto/boto3#100", etc. These
71 # will get automatically replaced with the correct
72 # link.
73 description: {description}
74 """
75
76
77 def new_changelog_entry(args):
78 # Changelog values come from one of two places.
79 # Either all values are provided on the command line,
80 # or we open a text editor and let the user provide
81 # enter their values.
82 if all_values_provided(args):
83 parsed_values = {
84 'type': args.change_type,
85 'category': args.category,
86 'description': args.description,
87 }
88 else:
89 parsed_values = get_values_from_editor(args)
90 if has_empty_values(parsed_values):
91 sys.stderr.write(
92 "Empty changelog values received, skipping entry creation.\n"
93 )
94 return 1
95 replace_issue_references(parsed_values, args.repo)
96 write_new_change(parsed_values)
97 return 0
98
99
100 def has_empty_values(parsed_values):
101 return not (
102 parsed_values.get('type')
103 and parsed_values.get('category')
104 and parsed_values.get('description')
105 )
106
107
108 def all_values_provided(args):
109 return args.change_type and args.category and args.description
110
111
112 def get_values_from_editor(args):
113 with tempfile.NamedTemporaryFile('w') as f:
114 contents = TEMPLATE.format(
115 change_type=args.change_type,
116 category=args.category,
117 description=args.description,
118 )
119 f.write(contents)
120 f.flush()
121 env = os.environ
122 editor = env.get('VISUAL', env.get('EDITOR', 'vim'))
123 p = subprocess.Popen(f'{editor} {f.name}', shell=True)
124 p.communicate()
125 with open(f.name) as f:
126 filled_in_contents = f.read()
127 parsed_values = parse_filled_in_contents(filled_in_contents)
128 return parsed_values
129
130
131 def replace_issue_references(parsed, repo_name):
132 description = parsed['description']
133
134 def linkify(match):
135 number = match.group()[1:]
136 return f'`{match.group()} <https://github.com/{repo_name}/issues/{number}>`__'
137
138 new_description = re.sub(r'#\d+', linkify, description)
139 parsed['description'] = new_description
140
141
142 def write_new_change(parsed_values):
143 if not os.path.isdir(CHANGES_DIR):
144 os.makedirs(CHANGES_DIR)
145 # Assume that new changes go into the next release.
146 dirname = os.path.join(CHANGES_DIR, 'next-release')
147 if not os.path.isdir(dirname):
148 os.makedirs(dirname)
149 # Need to generate a unique filename for this change.
150 # We'll try a couple things until we get a unique match.
151 category = parsed_values['category']
152 short_summary = ''.join(filter(lambda x: x in VALID_CHARS, category))
153 filename = '{type_name}-{summary}'.format(
154 type_name=parsed_values['type'], summary=short_summary
155 )
156 possible_filename = os.path.join(
157 dirname, f'{filename}-{str(random.randint(1, 100000))}.json'
158 )
159 while os.path.isfile(possible_filename):
160 possible_filename = os.path.join(
161 dirname, f'{filename}-{str(random.randint(1, 100000))}.json'
162 )
163 with open(possible_filename, 'w') as f:
164 f.write(json.dumps(parsed_values, indent=2) + "\n")
165
166
167 def parse_filled_in_contents(contents):
168 """Parse filled in file contents and returns parsed dict.
169
170 Return value will be::
171 {
172 "type": "bugfix",
173 "category": "category",
174 "description": "This is a description"
175 }
176
177 """
178 if not contents.strip():
179 return {}
180 parsed = {}
181 lines = iter(contents.splitlines())
182 for line in lines:
183 line = line.strip()
184 if line.startswith('#'):
185 continue
186 if 'type' not in parsed and line.startswith('type:'):
187 parsed['type'] = line.split(':')[1].strip()
188 elif 'category' not in parsed and line.startswith('category:'):
189 parsed['category'] = line.split(':')[1].strip()
190 elif 'description' not in parsed and line.startswith('description:'):
191 # Assume that everything until the end of the file is part
192 # of the description, so we can break once we pull in the
193 # remaining lines.
194 first_line = line.split(':')[1].strip()
195 full_description = '\n'.join([first_line] + list(lines))
196 parsed['description'] = full_description.strip()
197 break
198 return parsed
199
200
201 def main():
202 parser = argparse.ArgumentParser()
203 parser.add_argument(
204 '-t',
205 '--type',
206 dest='change_type',
207 default='',
208 choices=('bugfix', 'feature', 'enhancement', 'api-change'),
209 )
210 parser.add_argument('-c', '--category', dest='category', default='')
211 parser.add_argument('-d', '--description', dest='description', default='')
212 parser.add_argument(
213 '-r',
214 '--repo',
215 default='boto/boto3',
216 help='Optional repo name, e.g: boto/boto3',
217 )
218 args = parser.parse_args()
219 sys.exit(new_changelog_entry(args))
220
221
222 if __name__ == '__main__':
223 main()