codeownerinsights 0.3.1__tar.gz → 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: codeownerinsights
3
- Version: 0.3.1
3
+ Version: 0.5.0
4
4
  Summary: Parse GitHub's CODEOWNERS file and resolve code owners for a path, with optional git integration.
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -28,7 +28,7 @@ wins. Pure Python, no editor dependency.
28
28
  pip install codeownerinsights
29
29
  ```
30
30
 
31
- Requires Python 3.8 or newer. The only runtime dependency is
31
+ Requires Python 3.11 or newer. The only runtime dependency is
32
32
  [`wcmatch`](https://pypi.org/project/wcmatch/), for GitHub-compatible glob
33
33
  matching.
34
34
 
@@ -8,7 +8,7 @@ wins. Pure Python, no editor dependency.
8
8
  pip install codeownerinsights
9
9
  ```
10
10
 
11
- Requires Python 3.8 or newer. The only runtime dependency is
11
+ Requires Python 3.11 or newer. The only runtime dependency is
12
12
  [`wcmatch`](https://pypi.org/project/wcmatch/), for GitHub-compatible glob
13
13
  matching.
14
14
 
@@ -0,0 +1,465 @@
1
+ import argparse
2
+ import json
3
+ import os
4
+ import sys
5
+ from pathlib import Path, PurePath
6
+ from typing import Dict, Iterable, List, Mapping, Optional, Sequence, TextIO, Tuple
7
+
8
+ from .codeowners import (
9
+ CodeOwnerSpecification,
10
+ get_code_owners_file,
11
+ get_matching_code_owner_specifications_for_file,
12
+ parse_code_owners,
13
+ )
14
+ from .git import (
15
+ DEFAULT_GIT,
16
+ exec_command,
17
+ get_default_branch_remote_ref,
18
+ get_git_staged_files,
19
+ get_git_unstaged_files,
20
+ )
21
+ from .pull_request import (
22
+ PULL_REQUEST_DIFF_FILTER,
23
+ get_code_owner_specifications_at_ref,
24
+ get_pull_request_changed_files,
25
+ )
26
+
27
+
28
+ def _build_parser() -> argparse.ArgumentParser:
29
+ parser = argparse.ArgumentParser(
30
+ prog='codeownerinsights',
31
+ description=(
32
+ 'Resolve the CODEOWNERS owners of files the way GitHub does. '
33
+ 'With no paths, use the files the current branch commits change compared with the '
34
+ "default branch, which are the files GitHub requests a pull request's reviewers for."
35
+ ),
36
+ )
37
+ parser.add_argument(
38
+ '--staged',
39
+ action='store_true',
40
+ help='use the files changed in the index instead of the branch changes',
41
+ )
42
+ parser.add_argument(
43
+ '--unstaged',
44
+ action='store_true',
45
+ help=(
46
+ 'use the files changed in the working tree, and untracked files, instead of the '
47
+ 'branch changes; combine with --staged for every uncommitted change'
48
+ ),
49
+ )
50
+ parser.add_argument(
51
+ 'paths',
52
+ nargs='*',
53
+ help="files to resolve, relative to the current directory; '-' reads paths from stdin",
54
+ )
55
+ parser.add_argument(
56
+ '--root-relative',
57
+ action='store_true',
58
+ help='paths, including those read from stdin, are relative to the repository root, as git prints them',
59
+ )
60
+ parser.add_argument(
61
+ '-z',
62
+ dest='null_separated',
63
+ action='store_true',
64
+ help="paths read from stdin are separated by NUL characters, as git's -z prints them",
65
+ )
66
+ parser.add_argument(
67
+ '--repo',
68
+ type=Path,
69
+ help='repository root (default: the git top level of the current directory)',
70
+ )
71
+ parser.add_argument(
72
+ '--base',
73
+ help='compare the current branch with this ref instead of the default branch',
74
+ )
75
+ parser.add_argument(
76
+ '--with-uncommitted',
77
+ action='store_true',
78
+ help=(
79
+ 'add uncommitted changes, untracked files included, to the branch changes: the files '
80
+ 'the pull request would change once everything is committed'
81
+ ),
82
+ )
83
+ parser.add_argument(
84
+ '--no-fetch',
85
+ action='store_true',
86
+ help='use the local origin/<default> ref without fetching it first',
87
+ )
88
+ codeowners_source = parser.add_mutually_exclusive_group()
89
+ codeowners_source.add_argument(
90
+ '--codeowners-ref',
91
+ metavar='REF',
92
+ help=(
93
+ 'read CODEOWNERS at this ref (default: the base for branch changes, as GitHub does; '
94
+ 'the working tree otherwise)'
95
+ ),
96
+ )
97
+ codeowners_source.add_argument(
98
+ '--worktree-codeowners',
99
+ action='store_true',
100
+ help='read CODEOWNERS from the working tree for branch changes too, to preview edits to it',
101
+ )
102
+ parser.add_argument(
103
+ '--owner',
104
+ action='append',
105
+ default=[],
106
+ help=(
107
+ 'only show files this owner covers; repeat for any of several. Case is ignored, and '
108
+ '@ and the org are optional: core-banking matches @TransferGo/core-banking'
109
+ ),
110
+ )
111
+ parser.add_argument(
112
+ '--not-owner',
113
+ action='append',
114
+ default=[],
115
+ help='leave out files this owner covers; repeat for several. Matches as --owner does',
116
+ )
117
+ parser.add_argument(
118
+ '--all-rules',
119
+ action='store_true',
120
+ help='also list every rule that matches each file, not only the one that applies',
121
+ )
122
+ parser.add_argument(
123
+ '--group-by',
124
+ choices=('file', 'owner'),
125
+ default='file',
126
+ help=(
127
+ 'text output only: list one file per line (file, the default), or list the files '
128
+ 'under each set of owners that applies to them (owner)'
129
+ ),
130
+ )
131
+ parser.add_argument(
132
+ '--color',
133
+ choices=('auto', 'always', 'never'),
134
+ default='auto',
135
+ help=(
136
+ 'colour text output: always, never, or auto (the default) when stdout is a terminal '
137
+ 'and NO_COLOR is not set'
138
+ ),
139
+ )
140
+ parser.add_argument('--json', action='store_true', help='print JSON instead of text')
141
+ parser.add_argument('--git', default=DEFAULT_GIT, help='git executable (default: git)')
142
+ return parser
143
+
144
+
145
+ def _find_repo_root(start: Path, git: str) -> Path:
146
+ result = exec_command(start, [git, 'rev-parse', '--show-toplevel'])
147
+ if result and result.process.returncode == 0 and result.process.stdout.strip():
148
+ return Path(result.process.stdout.strip())
149
+ return start
150
+
151
+
152
+ def _repo_relative(path: str, cwd: Path, repo_root: Path) -> Path:
153
+ absolute = Path(path) if os.path.isabs(path) else cwd / path
154
+ return Path(os.path.relpath(os.path.normpath(str(absolute)), str(repo_root)))
155
+
156
+
157
+ def _check_sources(parser: argparse.ArgumentParser, args: argparse.Namespace) -> None:
158
+ working_tree = [
159
+ flag for flag, on in (('--staged', args.staged), ('--unstaged', args.unstaged)) if on
160
+ ]
161
+ branch_only = [
162
+ flag
163
+ for flag, on in (
164
+ ('--base', args.base),
165
+ ('--no-fetch', args.no_fetch),
166
+ ('--with-uncommitted', args.with_uncommitted),
167
+ )
168
+ if on
169
+ ]
170
+ if (args.root_relative or args.null_separated) and not args.paths:
171
+ flag = '--root-relative' if args.root_relative else '-z'
172
+ parser.error(f'{flag} needs paths')
173
+ if args.null_separated and '-' not in args.paths:
174
+ parser.error("-z needs '-' to read paths from stdin")
175
+ if working_tree and args.paths:
176
+ parser.error(f'{working_tree[0]} cannot be combined with paths')
177
+ if branch_only and (working_tree or args.paths):
178
+ other = working_tree[0] if working_tree else 'paths'
179
+ parser.error(f'{branch_only[0]} cannot be combined with {other}')
180
+
181
+
182
+ def _is_branch_mode(args: argparse.Namespace) -> bool:
183
+ return not (args.staged or args.unstaged or args.paths)
184
+
185
+
186
+ def _load_specifications(
187
+ repo_root: Path, ref: Optional[str], git: str
188
+ ) -> Optional[List[CodeOwnerSpecification]]:
189
+ if ref is None:
190
+ codeowners_file = get_code_owners_file(repo_root)
191
+ if codeowners_file is None:
192
+ return None
193
+ return list(parse_code_owners(codeowners_file, codeowners_file.read_text(encoding='utf-8')))
194
+ return get_code_owner_specifications_at_ref(repo_root, ref, git=git)
195
+
196
+
197
+ def _collect_paths(
198
+ args: argparse.Namespace, cwd: Path, repo_root: Path, stdin: TextIO, base: Optional[str]
199
+ ) -> List[Path]:
200
+ changed: List[Path] = []
201
+ if args.staged or args.unstaged:
202
+ if args.staged:
203
+ changed += get_git_staged_files(
204
+ repo_root, git=args.git, diff_filter=PULL_REQUEST_DIFF_FILTER
205
+ )
206
+ if args.unstaged:
207
+ changed += get_git_unstaged_files(
208
+ repo_root, git=args.git, diff_filter=PULL_REQUEST_DIFF_FILTER
209
+ )
210
+ return sorted(set(changed))
211
+
212
+ if args.paths:
213
+ raw: List[str] = []
214
+ for path in args.paths:
215
+ if path == '-' and args.null_separated:
216
+ raw.extend(entry for entry in stdin.read().split('\0') if entry)
217
+ elif path == '-':
218
+ raw.extend(line.strip() for line in stdin if line.strip())
219
+ else:
220
+ raw.append(path)
221
+ relative_to = repo_root if args.root_relative else cwd
222
+ return [_repo_relative(path, relative_to, repo_root) for path in raw]
223
+
224
+ assert base is not None
225
+ return get_pull_request_changed_files(
226
+ repo_root, base, git=args.git, with_uncommitted=args.with_uncommitted
227
+ )
228
+
229
+
230
+ def _relative_to_repo(path: Path, repo_root: Path) -> PurePath:
231
+ return PurePath(os.path.relpath(str(path), str(repo_root)))
232
+
233
+
234
+ def _rule_dict(spec: CodeOwnerSpecification, repo_root: Path) -> Dict[str, object]:
235
+ return {
236
+ 'pattern': spec.glob_pattern,
237
+ 'owners': list(spec.owners),
238
+ 'line': spec.line_number,
239
+ 'codeowners_file': _relative_to_repo(spec.codeowners_file_path, repo_root).as_posix(),
240
+ }
241
+
242
+
243
+ def _resolve(
244
+ specifications: Sequence[CodeOwnerSpecification],
245
+ paths: Iterable[Path],
246
+ repo_root: Path,
247
+ all_rules: bool = False,
248
+ ) -> List[Dict[str, object]]:
249
+ results = []
250
+ for path in paths:
251
+ matching = list(get_matching_code_owner_specifications_for_file(specifications, path))
252
+ applied = matching[-1] if matching else None
253
+ result = {
254
+ 'path': path.as_posix(),
255
+ 'owners': list(applied.owners) if applied else [],
256
+ 'rule': _rule_dict(applied, repo_root) if applied else None,
257
+ }
258
+ if all_rules:
259
+ result['matching_rules'] = [_rule_dict(spec, repo_root) for spec in matching]
260
+ results.append(result)
261
+ return results
262
+
263
+
264
+ def _owner_matches(wanted: str, owner: str) -> bool:
265
+ wanted = wanted.lower().lstrip('@')
266
+ owner = owner.lower().lstrip('@')
267
+ return wanted == owner or ('/' not in wanted and owner.endswith(f'/{wanted}'))
268
+
269
+
270
+ def _covered_by_any(result: Dict[str, object], wanted: Sequence[str]) -> bool:
271
+ return any(
272
+ _owner_matches(w, owner)
273
+ for w in wanted
274
+ for owner in result['owners'] # type: ignore[union-attr]
275
+ )
276
+
277
+
278
+ def _filter_by_owner(
279
+ results: List[Dict[str, object]], owner: Sequence[str], not_owner: Sequence[str]
280
+ ) -> List[Dict[str, object]]:
281
+ return [
282
+ result
283
+ for result in results
284
+ if (not owner or _covered_by_any(result, owner))
285
+ and not (not_owner and _covered_by_any(result, not_owner))
286
+ ]
287
+
288
+
289
+ def _owners_summary(results: List[Dict[str, object]]) -> Dict[str, List[str]]:
290
+ summary: Dict[str, List[str]] = {}
291
+ for result in results:
292
+ for owner in result['owners']: # type: ignore[union-attr]
293
+ summary.setdefault(owner, []).append(result['path']) # type: ignore[arg-type]
294
+ return dict(sorted(summary.items()))
295
+
296
+
297
+ def _describe_rule(rule: Dict[str, object]) -> str:
298
+ return f'{rule["codeowners_file"]}:{rule["line"]} {rule["pattern"]}'
299
+
300
+
301
+ class _Style:
302
+ def __init__(self, enabled: bool) -> None:
303
+ self.enabled = enabled
304
+
305
+ def _wrap(self, code: str, text: str) -> str:
306
+ return f'\033[{code}m{text}\033[0m' if self.enabled and text else text
307
+
308
+ def owners(self, text: str) -> str:
309
+ return self._wrap('1;36', text)
310
+
311
+ def rule(self, text: str) -> str:
312
+ return self._wrap('2', text)
313
+
314
+ def unowned(self, text: str) -> str:
315
+ return self._wrap('33', text)
316
+
317
+ def heading(self, text: str) -> str:
318
+ return self._wrap('1', text)
319
+
320
+
321
+ def _use_color(choice: str, stdout: TextIO, environ: Mapping[str, str]) -> bool:
322
+ if choice != 'auto':
323
+ return choice == 'always'
324
+ isatty = getattr(stdout, 'isatty', None)
325
+ return bool(isatty and isatty()) and not environ.get('NO_COLOR')
326
+
327
+
328
+ def _files(count: int) -> str:
329
+ return f'{count} file{"s" if count != 1 else ""}'
330
+
331
+
332
+ def _print_matching_rules(
333
+ result: Dict[str, object], indent: str, style: _Style, out: TextIO
334
+ ) -> None:
335
+ for matching in result['matching_rules']: # type: ignore[union-attr]
336
+ line = f'{_describe_rule(matching)} -> {" ".join(matching["owners"])}'
337
+ if matching == result['rule']:
338
+ out.write(f'{indent}* {line}\n')
339
+ else:
340
+ out.write(f'{indent} {style.rule(line)}\n')
341
+
342
+
343
+ def _print_text(
344
+ results: List[Dict[str, object]], all_rules: bool, style: _Style, out: TextIO
345
+ ) -> None:
346
+ for result in results:
347
+ rule = result['rule']
348
+ if rule is None:
349
+ out.write(f'{result["path"]}\t{style.unowned("(no owner)")}\n')
350
+ else:
351
+ owners = style.owners(' '.join(result['owners'])) # type: ignore[arg-type]
352
+ out.write(f'{result["path"]}\t{owners}\t{style.rule(_describe_rule(rule))}\n') # type: ignore[arg-type]
353
+ if all_rules:
354
+ _print_matching_rules(result, ' ', style, out)
355
+
356
+ summary = _owners_summary(results)
357
+ if summary:
358
+ out.write(f'\n{style.heading("Owners:")}\n')
359
+ for owner, paths in summary.items():
360
+ out.write(f' {style.owners(owner)} ({_files(len(paths))})\n')
361
+ unowned = [result['path'] for result in results if result['rule'] is None]
362
+ if unowned:
363
+ out.write(f'\n{style.unowned("No owner:")} {_files(len(unowned))}\n')
364
+
365
+
366
+ def _print_text_by_owner(
367
+ results: List[Dict[str, object]], all_rules: bool, style: _Style, out: TextIO
368
+ ) -> None:
369
+ groups: Dict[Tuple[str, ...], List[Dict[str, object]]] = {}
370
+ for result in results:
371
+ groups.setdefault(tuple(result['owners']), []).append(result) # type: ignore[arg-type]
372
+ width = max(len(str(result['path'])) for result in results)
373
+
374
+ for index, owners in enumerate(sorted(groups, key=lambda owners: (not owners, owners))):
375
+ members = groups[owners]
376
+ heading = style.owners(' '.join(owners)) if owners else style.unowned('(no owner)')
377
+ if index:
378
+ out.write('\n')
379
+ out.write(f'{heading} ({_files(len(members))})\n')
380
+ for result in members:
381
+ rule = result['rule']
382
+ if rule is None:
383
+ out.write(f' {result["path"]}\n')
384
+ else:
385
+ path = f'{str(result["path"]):<{width}}'
386
+ out.write(f' {path} {style.rule(_describe_rule(rule))}\n') # type: ignore[arg-type]
387
+ if all_rules:
388
+ _print_matching_rules(result, ' ', style, out)
389
+
390
+
391
+ def main(
392
+ argv: Optional[Sequence[str]] = None,
393
+ stdin: TextIO = sys.stdin,
394
+ stdout: TextIO = sys.stdout,
395
+ stderr: TextIO = sys.stderr,
396
+ cwd: Optional[Path] = None,
397
+ environ: Optional[Mapping[str, str]] = None,
398
+ ) -> int:
399
+ parser = _build_parser()
400
+ args = parser.parse_args(argv)
401
+ _check_sources(parser, args)
402
+ cwd = (cwd or Path.cwd()).resolve()
403
+ repo_root = (args.repo if args.repo.is_absolute() else cwd / args.repo) if args.repo else None
404
+ repo_root = (repo_root or _find_repo_root(cwd, args.git)).resolve()
405
+
406
+ def fail(message: str, code: int) -> int:
407
+ if args.json:
408
+ json.dump({'error': message}, stderr)
409
+ stderr.write('\n')
410
+ else:
411
+ stderr.write(f'{message}\n')
412
+ return code
413
+
414
+ base: Optional[str] = None
415
+ if _is_branch_mode(args):
416
+ base = args.base or get_default_branch_remote_ref(
417
+ repo_root, fetch_remote=not args.no_fetch, git=args.git
418
+ )
419
+ if not base:
420
+ return fail('Could not find the default branch from origin/HEAD; pass --base <ref>', 1)
421
+
422
+ codeowners_ref = args.codeowners_ref
423
+ if codeowners_ref is None and base and not args.worktree_codeowners:
424
+ codeowners_ref = base
425
+
426
+ specifications = _load_specifications(repo_root, codeowners_ref, args.git)
427
+ if specifications is None:
428
+ if codeowners_ref is None:
429
+ return fail(f'No CODEOWNERS file found in {repo_root}', 2)
430
+ message = f'No CODEOWNERS file found at {codeowners_ref}'
431
+ if not args.codeowners_ref:
432
+ message += (
433
+ ". GitHub requests code owners from the base branch's CODEOWNERS file; "
434
+ "pass --worktree-codeowners to use the working tree's instead"
435
+ )
436
+ return fail(message, 2)
437
+
438
+ results = _resolve(
439
+ specifications, _collect_paths(args, cwd, repo_root, stdin, base), repo_root, args.all_rules
440
+ )
441
+ filtered = bool(results) and bool(args.owner or args.not_owner)
442
+ results = _filter_by_owner(results, args.owner, args.not_owner)
443
+
444
+ if args.json:
445
+ json.dump(
446
+ {
447
+ 'files': results,
448
+ 'owners': _owners_summary(results),
449
+ 'codeowners_ref': codeowners_ref,
450
+ },
451
+ stdout,
452
+ indent=2,
453
+ )
454
+ stdout.write('\n')
455
+ elif results:
456
+ style = _Style(_use_color(args.color, stdout, os.environ if environ is None else environ))
457
+ printer = _print_text_by_owner if args.group_by == 'owner' else _print_text
458
+ printer(results, args.all_rules, style, stdout)
459
+ if codeowners_ref:
460
+ stdout.write(f'\n{style.rule(f"CODEOWNERS at {codeowners_ref}")}\n')
461
+ elif filtered:
462
+ stderr.write('No files match --owner or --not-owner\n')
463
+ else:
464
+ stderr.write('No files to resolve\n')
465
+ return 0
@@ -122,12 +122,13 @@ def get_resolved_code_owners_for_file(
122
122
  return None
123
123
 
124
124
 
125
- def get_code_owners_file(repo_root: Path) -> Optional[Path]:
126
- try_locations = ['./.github/', './', './docs']
127
- # If CODEOWNERS files exist in more than one of those locations, GitHub will search for them in that order and use the first one it finds.
125
+ # If CODEOWNERS files exist in more than one of these locations, GitHub will search for them in this order and use the first one it finds.
126
+ CODEOWNERS_LOCATIONS = ('.github/CODEOWNERS', 'CODEOWNERS', 'docs/CODEOWNERS')
127
+
128
128
 
129
- for folder in try_locations:
130
- path = repo_root / folder / 'CODEOWNERS'
129
+ def get_code_owners_file(repo_root: Path) -> Optional[Path]:
130
+ for location in CODEOWNERS_LOCATIONS:
131
+ path = repo_root / location
131
132
  if path.is_file():
132
133
  return path
133
134
 
@@ -30,8 +30,13 @@ def get_git_changed_files_compared_to_branch(
30
30
  filter: Optional[str] = None,
31
31
  git: str = DEFAULT_GIT,
32
32
  diff_filter: str = 'ACMR',
33
+ head: Optional[str] = None,
33
34
  ) -> Iterable[Path]:
34
- """filter can be like --relative=source/ or '*.php' etc."""
35
+ """filter can be like --relative=source/ or '*.php' etc.
36
+
37
+ With ``head`` (e.g. ``'HEAD'``) only committed changes are compared. Without it the merge base
38
+ is compared with the working tree, which includes uncommitted changes to tracked files.
39
+ """
35
40
  current_branch = get_current_branch(folder_path, git=git)
36
41
  if not current_branch:
37
42
  return []
@@ -45,6 +50,7 @@ def get_git_changed_files_compared_to_branch(
45
50
  git,
46
51
  'diff',
47
52
  merge_base.process.stdout.rstrip(),
53
+ *([head] if head else []),
48
54
  '--name-only',
49
55
  f'--diff-filter={diff_filter}',
50
56
  )
@@ -78,6 +84,51 @@ def get_git_changed_files_compared_to_default_branch(
78
84
  )
79
85
 
80
86
 
87
+ def _null_separated_paths(summary: ShellExecutionSummary) -> List[Path]:
88
+ if not summary or summary.process.returncode != 0:
89
+ return []
90
+ return [Path(file) for file in summary.process.stdout.split('\0') if file]
91
+
92
+
93
+ def get_git_staged_files(
94
+ folder_path: Path, git: str = DEFAULT_GIT, diff_filter: str = 'ACMR'
95
+ ) -> List[Path]:
96
+ return _null_separated_paths(
97
+ exec_command(
98
+ folder_path,
99
+ _git_cmd(git, 'diff', '--cached', '--name-only', '-z', f'--diff-filter={diff_filter}'),
100
+ )
101
+ )
102
+
103
+
104
+ def get_git_unstaged_files(
105
+ folder_path: Path, git: str = DEFAULT_GIT, diff_filter: str = 'ACMR'
106
+ ) -> List[Path]:
107
+ """Return tracked files changed in the working tree, then untracked files that are not ignored."""
108
+ tracked = _null_separated_paths(
109
+ exec_command(
110
+ folder_path, _git_cmd(git, 'diff', '--name-only', '-z', f'--diff-filter={diff_filter}')
111
+ )
112
+ )
113
+ return tracked + get_git_untracked_files(folder_path, git=git)
114
+
115
+
116
+ def get_git_untracked_files(folder_path: Path, git: str = DEFAULT_GIT) -> List[Path]:
117
+ return _null_separated_paths(
118
+ exec_command(folder_path, _git_cmd(git, 'ls-files', '--others', '--exclude-standard', '-z'))
119
+ )
120
+
121
+
122
+ def read_file_at_ref(
123
+ folder_path: Path, ref: str, path: str, git: str = DEFAULT_GIT
124
+ ) -> Optional[str]:
125
+ """Return the content of ``path`` (relative to the repo root, ``/``-separated) at ``ref``, or None."""
126
+ result = exec_command(folder_path, _git_cmd(git, 'show', f'{ref}:{path}'))
127
+ if result and result.process.returncode == 0:
128
+ return result.process.stdout
129
+ return None
130
+
131
+
81
132
  def get_default_branch(folder_path: Path, git: str = DEFAULT_GIT) -> Optional[str]:
82
133
  result = exec_command(folder_path, _git_cmd(git, 'rev-parse', '--abbrev-ref', 'origin/HEAD'))
83
134
  if result and result.process.returncode == 0:
@@ -152,8 +203,6 @@ def exec_command(
152
203
  # returns the completed subpress and how long it took to complete as a float
153
204
  def execute_with_stdin(cmd, shell, text, cwd: Optional[Path] = None) -> ShellExecutionSummary:
154
205
  before = time.perf_counter()
155
- # https://docs.python.org/3/library/subprocess.html#subprocess.run - new in version 3.5
156
- # therefore, you need to be using ST build >= 4050 and the package should be opting in to Python 3.8 plugin host
157
206
  p = run(cmd, shell=shell, capture_output=True, input=text, encoding='utf-8', cwd=cwd)
158
207
  after = time.perf_counter()
159
208
  return ShellExecutionSummary(p, after - before)
@@ -0,0 +1,40 @@
1
+ from pathlib import Path
2
+ from typing import List, Optional
3
+
4
+ from .codeowners import CODEOWNERS_LOCATIONS, CodeOwnerSpecification, parse_code_owners
5
+ from .git import (
6
+ DEFAULT_GIT,
7
+ get_git_changed_files_compared_to_branch,
8
+ get_git_untracked_files,
9
+ read_file_at_ref,
10
+ )
11
+
12
+ PULL_REQUEST_DIFF_FILTER = 'ACMRD'
13
+
14
+
15
+ def get_pull_request_changed_files(
16
+ repo_root: Path, base: str, git: str = DEFAULT_GIT, with_uncommitted: bool = False
17
+ ) -> List[Path]:
18
+ """Committed changes only, deletions included. ``with_uncommitted`` adds the working tree and untracked files."""
19
+ changed = list(
20
+ get_git_changed_files_compared_to_branch(
21
+ repo_root,
22
+ base,
23
+ git=git,
24
+ diff_filter=PULL_REQUEST_DIFF_FILTER,
25
+ head=None if with_uncommitted else 'HEAD',
26
+ )
27
+ )
28
+ if not with_uncommitted:
29
+ return changed
30
+ return sorted(set(changed + get_git_untracked_files(repo_root, git=git)))
31
+
32
+
33
+ def get_code_owner_specifications_at_ref(
34
+ repo_root: Path, ref: str, git: str = DEFAULT_GIT
35
+ ) -> Optional[List[CodeOwnerSpecification]]:
36
+ for location in CODEOWNERS_LOCATIONS:
37
+ content = read_file_at_ref(repo_root, ref, location, git=git)
38
+ if content is not None:
39
+ return list(parse_code_owners(repo_root / location, content))
40
+ return None
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "codeownerinsights"
3
- version = "0.3.1"
3
+ version = "0.5.0"
4
4
  description = "Parse GitHub's CODEOWNERS file and resolve code owners for a path, with optional git integration."
5
5
  authors = [{ name = "Keith Hall", email = "keith.hall@available.systems" }]
6
6
  license = "MIT"
@@ -38,6 +38,9 @@ testpaths = ["test"]
38
38
  [tool.ruff]
39
39
  line-length = 100
40
40
 
41
+ [tool.ruff.lint.per-file-ignores]
42
+ "subl_codeowners.py" = ["E402"]
43
+
41
44
  [tool.ruff.format]
42
45
  quote-style = "single"
43
46
 
@@ -1,201 +0,0 @@
1
- import argparse
2
- import json
3
- import os
4
- import sys
5
- from pathlib import Path, PurePath
6
- from typing import Dict, Iterable, List, Optional, Sequence, TextIO
7
-
8
- from .codeowners import (
9
- CodeOwnerSpecification,
10
- get_code_owners_file,
11
- get_matching_code_owner_specifications_for_file,
12
- parse_code_owners,
13
- )
14
- from .git import (
15
- DEFAULT_GIT,
16
- exec_command,
17
- get_git_changed_files_compared_to_branch,
18
- get_git_changed_files_compared_to_default_branch,
19
- )
20
-
21
- PR_DIFF_FILTER = 'ACMRD'
22
-
23
-
24
- def _build_parser() -> argparse.ArgumentParser:
25
- parser = argparse.ArgumentParser(
26
- prog='codeownerinsights',
27
- description=(
28
- 'Resolve the CODEOWNERS owners of files the way GitHub does. '
29
- 'With no paths, use the files the current branch changes compared with the '
30
- "default branch, which are the files GitHub requests a pull request's reviewers for."
31
- ),
32
- )
33
- parser.add_argument(
34
- 'paths',
35
- nargs='*',
36
- help="files to resolve, relative to the current directory; '-' reads paths from stdin",
37
- )
38
- parser.add_argument(
39
- '--repo',
40
- type=Path,
41
- help='repository root (default: the git top level of the current directory)',
42
- )
43
- parser.add_argument(
44
- '--base',
45
- help='compare the current branch with this ref instead of the default branch',
46
- )
47
- parser.add_argument(
48
- '--no-fetch',
49
- action='store_true',
50
- help='use the local origin/<default> ref without fetching it first',
51
- )
52
- parser.add_argument(
53
- '--all-rules',
54
- action='store_true',
55
- help='also list every rule that matches each file, not only the one that applies',
56
- )
57
- parser.add_argument('--json', action='store_true', help='print JSON instead of text')
58
- parser.add_argument('--git', default=DEFAULT_GIT, help='git executable (default: git)')
59
- return parser
60
-
61
-
62
- def _find_repo_root(start: Path, git: str) -> Path:
63
- result = exec_command(start, [git, 'rev-parse', '--show-toplevel'])
64
- if result and result.process.returncode == 0 and result.process.stdout.strip():
65
- return Path(result.process.stdout.strip())
66
- return start
67
-
68
-
69
- def _repo_relative(path: str, cwd: Path, repo_root: Path) -> Path:
70
- absolute = Path(path) if os.path.isabs(path) else cwd / path
71
- return Path(os.path.relpath(os.path.normpath(str(absolute)), str(repo_root)))
72
-
73
-
74
- def _collect_paths(
75
- args: argparse.Namespace, cwd: Path, repo_root: Path, stdin: TextIO
76
- ) -> List[Path]:
77
- if args.paths:
78
- raw: List[str] = []
79
- for path in args.paths:
80
- if path == '-':
81
- raw.extend(line.strip() for line in stdin if line.strip())
82
- else:
83
- raw.append(path)
84
- return [_repo_relative(path, cwd, repo_root) for path in raw]
85
-
86
- if args.base:
87
- changed = get_git_changed_files_compared_to_branch(
88
- repo_root, args.base, git=args.git, diff_filter=PR_DIFF_FILTER
89
- )
90
- else:
91
- changed = get_git_changed_files_compared_to_default_branch(
92
- repo_root, fetch_remote=not args.no_fetch, git=args.git, diff_filter=PR_DIFF_FILTER
93
- )
94
- return list(changed)
95
-
96
-
97
- def _relative_to_repo(path: Path, repo_root: Path) -> PurePath:
98
- return PurePath(os.path.relpath(str(path), str(repo_root)))
99
-
100
-
101
- def _rule_dict(spec: CodeOwnerSpecification, repo_root: Path) -> Dict[str, object]:
102
- return {
103
- 'pattern': spec.glob_pattern,
104
- 'owners': list(spec.owners),
105
- 'line': spec.line_number,
106
- 'codeowners_file': _relative_to_repo(spec.codeowners_file_path, repo_root).as_posix(),
107
- }
108
-
109
-
110
- def _resolve(
111
- specifications: Sequence[CodeOwnerSpecification],
112
- paths: Iterable[Path],
113
- repo_root: Path,
114
- all_rules: bool = False,
115
- ) -> List[Dict[str, object]]:
116
- results = []
117
- for path in paths:
118
- matching = list(get_matching_code_owner_specifications_for_file(specifications, path))
119
- applied = matching[-1] if matching else None
120
- result = {
121
- 'path': path.as_posix(),
122
- 'owners': list(applied.owners) if applied else [],
123
- 'rule': _rule_dict(applied, repo_root) if applied else None,
124
- }
125
- if all_rules:
126
- result['matching_rules'] = [_rule_dict(spec, repo_root) for spec in matching]
127
- results.append(result)
128
- return results
129
-
130
-
131
- def _owners_summary(results: List[Dict[str, object]]) -> Dict[str, List[str]]:
132
- summary: Dict[str, List[str]] = {}
133
- for result in results:
134
- for owner in result['owners']: # type: ignore[union-attr]
135
- summary.setdefault(owner, []).append(result['path']) # type: ignore[arg-type]
136
- return dict(sorted(summary.items()))
137
-
138
-
139
- def _describe_rule(rule: Dict[str, object]) -> str:
140
- return f'{rule["codeowners_file"]}:{rule["line"]} {rule["pattern"]}'
141
-
142
-
143
- def _print_text(results: List[Dict[str, object]], all_rules: bool, out: TextIO) -> None:
144
- for result in results:
145
- rule = result['rule']
146
- if rule is None:
147
- out.write(f'{result["path"]}\t(no owner)\n')
148
- else:
149
- owners = ' '.join(result['owners']) # type: ignore[arg-type]
150
- out.write(f'{result["path"]}\t{owners}\t{_describe_rule(rule)}\n') # type: ignore[arg-type]
151
- if all_rules:
152
- for matching in result['matching_rules']: # type: ignore[union-attr]
153
- marker = '*' if matching == rule else ' '
154
- owners = ' '.join(matching['owners'])
155
- out.write(f' {marker} {_describe_rule(matching)} -> {owners}\n')
156
-
157
- summary = _owners_summary(results)
158
- if summary:
159
- out.write('\nOwners:\n')
160
- for owner, paths in summary.items():
161
- out.write(f' {owner} ({len(paths)} file{"s" if len(paths) != 1 else ""})\n')
162
- unowned = [result['path'] for result in results if result['rule'] is None]
163
- if unowned:
164
- out.write(f'\nNo owner: {len(unowned)} file{"s" if len(unowned) != 1 else ""}\n')
165
-
166
-
167
- def main(
168
- argv: Optional[Sequence[str]] = None,
169
- stdin: TextIO = sys.stdin,
170
- stdout: TextIO = sys.stdout,
171
- stderr: TextIO = sys.stderr,
172
- cwd: Optional[Path] = None,
173
- ) -> int:
174
- args = _build_parser().parse_args(argv)
175
- cwd = (cwd or Path.cwd()).resolve()
176
- repo_root = (args.repo if args.repo.is_absolute() else cwd / args.repo) if args.repo else None
177
- repo_root = (repo_root or _find_repo_root(cwd, args.git)).resolve()
178
-
179
- codeowners_file = get_code_owners_file(repo_root)
180
- if codeowners_file is None:
181
- message = f'No CODEOWNERS file found in {repo_root}'
182
- if args.json:
183
- json.dump({'error': message}, stderr)
184
- stderr.write('\n')
185
- else:
186
- stderr.write(f'{message}\n')
187
- return 2
188
-
189
- specifications = list(
190
- parse_code_owners(codeowners_file, codeowners_file.read_text(encoding='utf-8'))
191
- )
192
- results = _resolve(
193
- specifications, _collect_paths(args, cwd, repo_root, stdin), repo_root, args.all_rules
194
- )
195
-
196
- if args.json:
197
- json.dump({'files': results, 'owners': _owners_summary(results)}, stdout, indent=2)
198
- stdout.write('\n')
199
- else:
200
- _print_text(results, args.all_rules, stdout)
201
- return 0