forked from apheris/cz-github-jira-conventional
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cz_psee.py
317 lines (287 loc) · 11.7 KB
/
cz_psee.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
import os
import re
from typing import Any, Dict, List
from commitizen import defaults, git, config
from commitizen.cz.base import BaseCommitizen
from commitizen.cz.utils import multiple_line_breaker, required_validator
from commitizen.cz.exceptions import CzException
__all__ = ["PSEECz"]
DEFAULT_GITHUB_BASE_URL = "https://github.com/"
DEFAULT_CHANGE_TYPE_MAP = {
"BREAKING CHANGES": "BREAKING CHANGES",
"feat": "Features",
"fix": "Bug Fixes",
"hotfix:": "Hotfix",
"perf": "Performance improvements",
"refactor": "Refactor"
}
def parse_subject(text):
if isinstance(text, str):
text = text.strip(".").strip()
return required_validator(text, msg="Subject is required.")
class PSEECz(BaseCommitizen):
bump_pattern = r"^(BREAKING CHANGE|feat|fix|hotfix)"
bump_map = {"BREAKING CHANGE": "MAJOR", "feat": "MINOR", "fix": "PATCH", "hotfix": "PATCH"}
commit_parser = defaults.commit_parser
changelog_pattern = r"^(feat|BREAKING CHANGE|fix|hotfix|refactor|build)"
re_change_type_emoji = "|".join(["test","feat","fix","docs","style","refactor","perf","ci","build","chore","BREAKING CHANGE","hotfix"])
regex_scope = "[^()\r\n]*"
regex_breaking = "!"
regex_message = ".*"
re_emoji = f'^(?P<change_type>^{re_change_type_emoji})[ ]?(?P<emoji>[ ]:[^:]*:)?(?:\((?P<scope>{regex_scope})\)|\()?(?P<breaking>{regex_breaking})?:\s(?P<message>{regex_message})?'
commit_parser = fr'{re_emoji}'
# Read the config file and check if required settings are available
conf = config.read_cfg()
jira_prefix_hint = ""
if "jira_prefix" in conf.settings:
jira_prefix = conf.settings["jira_prefix"]
issue_multiple_hint = "42, 123"
# if there is only one project prefix, show it as prefix hint
if not isinstance(jira_prefix, list):
jira_prefix_hint = jira_prefix
else:
jira_prefix = ""
issue_multiple_hint = "XZ-42, XY-123"
if "jira_base_url" not in conf.settings:
print(
"Please add the key jira_base_url to your .cz.yaml|json|toml config file."
)
quit()
if "github_repo" not in conf.settings:
print("Please add the key github_repo to your .cz.yaml|json|toml config file.")
quit()
jira_base_url = conf.settings["jira_base_url"]
github_repo = conf.settings["github_repo"]
if "github_base_url" not in conf.settings:
github_base_url = DEFAULT_GITHUB_BASE_URL
else:
github_base_url = conf.settings["github_base_url"]
if "change_type_map" not in conf.settings:
change_type_map = DEFAULT_CHANGE_TYPE_MAP
else:
#change_type_map = conf.settings["change_type_map"]
print("Only default change type map is supported at the moment.")
quit()
def questions(self) -> List[Dict[str, Any]]:
questions: List[Dict[str, Any]] = [
{
"type": "list",
"name": "prefix",
"message": "Select the type of change you are committing",
"choices": [
{
"value": "fix :bug:",
"name": "fix 🐛: A bug fix. Correlates with PATCH in SemVer",
},
{
"value": "hotfix :ambulance:",
"name": "hotfix 🚑️: Critical hotfix. Correlates with PATCH in SemVer",
},
{
"value": "feat :sparkles:",
"name": "feat ✨: A new feature. Correlates with MINOR in SemVer",
},
{
"value": "BREAKING CHANGE :boom:",
"name": "BREAKING CHANGE 💥: Introduce breaking changes. Correlates with MAJOR in SemVer",
},
{"value": "docs :memo:", "name": "docs 📝: Documentation only changes"},
{
"value": ":art:",
"name": (
"style 🎨: Changes that do not affect the "
"meaning of the code (white-space, formatting,"
" missing semi-colons, etc)"
),
},
{
"value": "refactor :recycle:",
"name": (
"refactor ♻️: A code change that neither fixes "
"a bug nor adds a feature"
),
},
{
"value": "perf :zap:",
"name": "perf ⚡️: A code change that improves performance",
},
{
"value": "test :test_tube:",
"name": (
"test 🧪: Adding missing or correcting " "existing tests"
),
},
{
"value": "chore :wrench:",
"name": (
"chore 🔧: changes that do not relate to a fix or feature and don't modify"
" src or test files (for example updating dependencies)"
),
},
{
"value": "build :construction_worker:",
"name": (
"build 👷: Changes that affect the build system or "
"external dependencies (example scopes: pip, docker, npm)"
),
},
{
"value": "ci :green_heart:",
"name": (
"ci 💚: Changes to our CI configuration files and "
"scripts (example scopes: GitLabCI)"
),
},
],
},
{
"type": "input",
"name": "scope",
"message": (
f'JIRA issue number (multiple "{self.issue_multiple_hint}"). {self.jira_prefix_hint}: (press [enter] to skip)'
),
"filter": self.parse_scope,
},
{
"type": "input",
"name": "subject",
"filter": parse_subject,
"message": (
"Write a short and imperative summary of the code changes: (lower case and no period)\n"
),
},
{
"type": "input",
"name": "body",
"message": (
"Provide additional contextual information about the code changes: (press [enter] to skip)\n"
),
"filter": multiple_line_breaker,
},
{
"type": "confirm",
"message": "Is this a BREAKING CHANGE? Correlates with MAJOR in SemVer",
"name": "is_breaking_change",
"default": False,
},
{
"type": "input",
"name": "footer",
"message": (
"Footer. Information about Breaking Changes and "
"reference issues that this commit closes: (press [enter] to skip)\n"
),
},
]
# If there are multiple Jira prefixes let the user select one
if isinstance(self.jira_prefix, list):
questions.insert(
1,
{
"type": "list",
"name": "issue_jira_prefix",
"message": "JIRA project",
"choices": [
{"value": prefix, "name": prefix} for prefix in self.jira_prefix
],
},
)
return questions
def parse_scope(self, text):
"""
Require and validate the scope to be Jira ids.
"""
if self.jira_prefix:
issueRE = re.compile(r"\d+")
else:
issueRE = re.compile(r"\w+-\d+")
if not text:
return ""
issues = [i.strip() for i in text.strip().split(",")]
for issue in issues:
if not issueRE.fullmatch(issue):
raise InvalidAnswerError(f"JIRA issue '{issue}' is not valid.")
return required_validator(issues, msg="JIRA scope is required")
def message(self, answers: dict) -> str:
prefix = answers["prefix"]
issue_jira_prefix = (
answers["issue_jira_prefix"]
if "issue_jira_prefix" in answers
else self.jira_prefix
)
issues = answers["scope"]
subject = answers["subject"]
body = answers["body"]
footer = answers["footer"]
is_breaking_change = answers["is_breaking_change"]
if issues:
# Add Jira prefixes to the issue numbers.
issues_str = ",".join([issue_jira_prefix + i for i in issues])
scope = f"({issues_str})"
else:
scope=""
if body:
body = f"\n\n{body}"
if is_breaking_change:
footer = f"BREAKING CHANGE: {footer}"
if footer:
footer = f"\n\n{footer}"
if scope:
message = f"{prefix}{scope}: {subject}{body}{footer}"
else:
message = f"{prefix}: {subject}{body}{footer}"
return message
def example(self) -> str:
return (
"fix: correct minor typos in code\n"
"\n"
"see the issue for details on the typos fixed\n"
"\n"
"closes issue #12"
)
def schema(self) -> str:
return (
"<type>(<scope>): <subject>\n"
"<BLANK LINE>\n"
"<body>\n"
"<BLANK LINE>\n"
"(BREAKING CHANGE: )<footer>"
)
def schema_pattern(self) -> str:
re_change_type_emoji = "|".join(["test","feat","fix","docs","style","refactor","perf","ci","build","chore","BREAKING CHANGE","hotfix","bump"])
regex_scope = "[^()\r\n]*"
regex_breaking = "!"
regex_message = ".*"
re_emoji = f'^(?P<change_type>^{re_change_type_emoji})[ ]?(?P<emoji>[ ]:[^:]*:)?(?:\((?P<scope>{regex_scope})\)|\()?(?P<breaking>{regex_breaking})?:\s(?P<message>{regex_message})?'
return fr'{re_emoji}'
def info(self) -> str:
dir_path = os.path.dirname(os.path.realpath(__file__))
filepath = os.path.join(dir_path, "conventional_commits_info.txt")
with open(filepath, "r") as f:
content = f.read()
return content
def process_commit(self, commit: str) -> str:
pat = re.compile(self.schema_pattern())
m = re.match(pat, commit)
if m is None:
return ""
return m.group(3).strip()
def changelog_message_builder_hook(
self, parsed_message: dict, commit: git.GitCommit
) -> dict:
"""add github and jira links to the readme"""
rev = commit.rev
m = parsed_message["message"]
if parsed_message["scope"]:
parsed_message["scope"] = " ".join(
[
f"[{issue_id}]({self.jira_base_url}/browse/{issue_id})"
for issue_id in parsed_message["scope"].split(",")
]
)
parsed_message[
"message"
] = f"{m} [{rev[:5]}]({self.github_base_url}/{self.github_repo}/commit/{commit.rev})"
return parsed_message
class InvalidAnswerError(CzException):
...