forked from nrfconnect/sdk-nrf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpygit2_helpers.py
284 lines (232 loc) · 10 KB
/
pygit2_helpers.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
# Copyright 2018 Open Source Foundries, Limited
# Copyright 2018 Foundries.io, Limited
# Copyright (c) 2019 Nordic Semiconductor ASA
#
# SPDX-License-Identifier: Apache-2.0
# Helper code used by NCS to augment the pygit2 APIs. Used by
# maintainers to help synchronize upstream open source projects and
# keep changelogs/release notes up to date.
#
# Portions were copied from:
# https://github.com/foundriesio/zephyr_tools/.
from __future__ import annotations
__all__ = [
'title_is_revert', 'title_reverts_what', 'title_has_sauce',
'title_no_sauce',
'commit_reverts_what', 'commit_title', 'commit_affects_files',
'zephyr_commit_area',
]
from collections.abc import Iterable, Iterator
from pathlib import Path
from typing import Optional
import os
import re
import pygit2 # type: ignore
def title_is_revert(title: str) -> bool:
'''Return True if and only if the title starts with 'Revert '.
:param title: Git commit message title.'''
return title.startswith('Revert ')
def title_reverts_what(title: str) -> str:
'''If the title is a revert, returns title of what it reverted.
:param title: Git commit message title
For example, if title is:
'Revert "whoops: this turned out to be a bad idea"'
The return value is 'whoops: this turned out to be a bad idea';
i.e. the double quotes are also stripped.
'''
revert = 'Revert '
return title[len(revert) + 1:-1]
def title_has_sauce(title: str, sauce='nrf') -> bool:
'''Check if a Git title has a 'sauce tag'.
:param title: Git commit message title, which might begin
with a "sauce tag" that looks like '[sauce <tag>] '
:param sauce: String (or iterable of strings) indicating a source of
"sauce". This is organization-specific but defaults to
'nrf'.
For example, sauce="xyz" and the title is:
[xyz fromlist] area: something
Then the return value is True. If the title is any of these,
the return value is False:
area: something
[abc fromlist] area: something
[WIP] area: something
'''
if isinstance(sauce, str):
sauce = '[' + sauce
else:
sauce = tuple('[' + s for s in sauce)
return title.startswith(sauce)
def title_no_sauce(title: str, sauce: str = 'nrf') -> str:
'''Return a Git title without a 'sauce tag'.
:param title: Git commit message title, which might begin
with a "sauce tag" that looks like '[sauce <tag>] '
:param sauce: String (or iterable of strings) indicating a source of
"sauce". This is organization-specific but defaults to
'nrf'.
For example, sauce="xyz" and the title is:
"[xyz fromlist] area: something"
Then the return value is "area: something".
As another example with the same sauce, if title is "foo: bar",
the return value is "foo: bar".
'''
if isinstance(sauce, str):
sauce = '[' + sauce
else:
sauce = tuple('[' + s for s in sauce)
if title.startswith(sauce):
return title[title.find(']') + 1:].strip()
else:
return title
def commit_reverts_what(commit: pygit2.Commit) -> str:
'''Look for the string "reverts commit SOME_SHA" in the commit message,
and return SOME_SHA. Raises ValueError if the string is not found.'''
match = re.search(r'reverts\s+commit\s+([0-9a-f]+)',
' '.join(commit.message.split()))
if not match:
raise ValueError(commit.message)
return match.groups()[0]
def commit_title(commit: pygit2.Commit) -> str:
'''Return the first line in a commit's log message.
:param commit: pygit2 commit object'''
return commit.message.splitlines()[0]
def commit_affects_files(commit: pygit2.Commit,
files: Iterable[os.PathLike]) -> bool:
'''True if and only if the commit affects one or more files.
:param commit: pygit2 commit object
:param files: sequence of paths relative to commit object
repository root
'''
as_paths = set(Path(f) for f in files)
for p in commit.parents:
diff = commit.tree.diff_to_tree(p.tree)
for d in diff.deltas:
if (Path(d.old_file.path) in as_paths or
Path(d.new_file.path) in as_paths):
return True
return False
# The code this was copied from has finer-grained area heuristics than
# NCS currently tracks. This kludge preserves the work that's already
# been done while making a rougher-grained breakdown.
AREAS_NCS_SUBSET = set([
'Bluetooth',
'Devicetree',
'Documentation',
'Drivers',
'Kernel',
'Networking',
'Testing',
# Keep this list sorted alphabetically.
])
def zephyr_commit_area(commit: pygit2.Commit) -> str:
'''Make a guess about what area a zephyr commit affected.
This is entirely based on heuristics and may return complete
nonsense, but it's correct enough for our purposes of roughly
segmenting commits to areas so the appropriate maintainers can
analyze them for NCS release notes.
The return value is one of these strings: 'Kernel', 'Bluetooth',
'Drivers', 'Networking', 'Arches/Boards', 'Other'
:param commit: pygit2.Commit object
'''
area_pfx = _commit_area_prefix(commit_title(commit))
if area_pfx is None:
return 'Other'
for test_regex, area in _SHORTLOG_RE_TO_AREA:
match = test_regex.fullmatch(area_pfx)
if match:
break
else:
area = 'Other'
if area in AREAS_NCS_SUBSET:
return area
if area in ('Arches', 'Boards'):
return 'Arches/Boards'
return 'Other'
def _commit_area_prefix(commit_title: str) -> Optional[str]:
'''Get the prefix of a pull request title which describes its area.
This returns the "raw" prefix as it appears in the title. To
canonicalize this to one of a known set of areas for a zephyr PR, use
zephyr_pr_area() instead. If no prefix is present, returns None.
'''
# Base case for recursion.
if not commit_title:
return None
# 'Revert "foo"' should map to foo's area prefix.
if title_is_revert(commit_title):
commit_title = title_reverts_what(commit_title)
return _commit_area_prefix(commit_title)
# If there is no ':', there is no area. Otherwise, the candidate
# area is the substring up to the first ':'.
if ':' not in commit_title:
return None
area, rest = [s.strip() for s in commit_title.split(':', 1)]
# subsys: foo should map to foo's area prefix, etc.
if area in ['subsys', 'include', 'api']:
return _commit_area_prefix(rest)
return area
def _invert_keys_val_list(kvs: list[tuple[str, list[str]]],
) -> Iterator[tuple[str, str]]:
for k, vs in kvs:
for v in vs:
yield v, k
# This list maps the 'area' a commit affects to a list of
# title prefixes (the content before the first ':') in the Zephyr
# commit titles that belong to it.
#
# The values are lists of case-insensitive regular expressions that
# are matched against the title prefix of each commit. Matches are
# done with regex.fullmatch().
#
# Keep its definition sorted alphabetically by key.
_AREA_TO_SHORTLOG_RES = [
('Arches', ['arch(/.*)?', 'arc(/.*)?', 'arm(/.*)?', 'esp32(/.*)?',
'imx(/.*)?', 'native(/.*)?', 'native_posix', 'nios2(/.*)?',
'posix(/.*)?', 'lpc(/.*)?', 'riscv(32)?(/.*)?', 'soc(/.*)?',
'x86(_64)?(/.*)?', 'xtensa(/.*)?']),
('Bluetooth', ['bluetooth', 'bt']),
('Boards', ['boards?(/.*)?', 'mimxrt1050_evk']),
('Build', ['build', 'c[+][+]', 'clang(/.*)?', 'cmake', 'kconfig',
'gen_isr_tables?', 'gen_syscall_header', 'genrest',
'isr_tables?', 'ld', 'linker', 'menuconfig', 'size_report',
'toolchains?']),
('Continuous Integration', ['ci', 'coverage', 'sanitycheck', 'gitlint']),
('Cryptography', ['crypto', 'mbedtls']),
('Debugging', ['debug']),
('Devicetree', ['dt', 'dts(/.*)?', 'dt-bindings',
'dtlib', 'edtlib', 'devicetree',
'extract_dts_includes?']),
('Documentation', ['docs?(/.*)?', 'CONTRIBUTING.rst', 'doxygen']),
('Drivers', ['drivers?(/.*)?',
'adc', 'aio', 'can', 'clock_control', 'counter', 'crc',
'device([.]h)?', 'display', 'dma', 'entropy', 'eth',
'ethernet',
'flash', 'flash_map', 'gpio', 'grove', 'hid', 'i2c', 'i2s',
'interrupt_controller', 'ipm', 'led_strip', 'led', 'netusb',
'pci', 'pinmux', 'pwm', 'rtc', 'sensors?(/.*)?',
'serial(/.*)?', 'shared_irq', 'spi', 'timer', 'uart',
'uart_pipe', 'usb(/.*)?', 'watchdog',
# Technically in subsys/ (or parts are), but treated
# as drivers
'console', 'random', 'storage']),
('Firmware Update', ['dfu(/.*)?', 'mgmt']),
('Kernel', ['kernel(/.*)?', 'poll', 'mempool', 'spinlock', 'syscalls',
'work_q', 'init.h', 'userspace', 'k_queue', 'k_poll',
'app_memory']),
('Libraries', ['libc?', 'json', 'jwt', 'ring_buffer', 'lib(/.*)',
'misc/dlist']),
('Logging', ['logging', 'logger', 'log']),
('Maintainers', ['CODEOWNERS([.]rst)?']),
('Miscellaneous', ['misc', 'release', 'shell', 'printk', 'version']),
('Networking', ['net(/.*)?', 'openthread', 'slip', 'ieee802154']),
('Power Management', ['power']),
('Samples', ['samples?(/.*)?']),
('Scripts', ['scripts?(/.*)?', 'coccinelle', 'runner',
'gen_app_partitions(.py)?', 'gen_syscalls.py',
'gen_syscall_header.py', 'kconfiglib', 'west']),
('Storage', ['fs(/.*)?', 'disks?', 'fcb', 'settings']),
('Testing', ['tests?(/.*)?', 'testing', 'unittest', 'ztest', 'tracing']),
]
# This 'inverts' the key/value relationship in _AREA_TO_SHORTLOG_RES to
# make a list from title prefix REs to areas.
_SHORTLOG_RE_TO_AREA: list[tuple[re.Pattern, str]] = [
(re.compile(k, flags=re.IGNORECASE), v) for k, v in
_invert_keys_val_list(_AREA_TO_SHORTLOG_RES)]