codeownerinsights 0.4.0__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.4.0
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
 
@@ -14,13 +14,15 @@ from .codeowners import (
14
14
  from .git import (
15
15
  DEFAULT_GIT,
16
16
  exec_command,
17
- get_git_changed_files_compared_to_branch,
18
- get_git_changed_files_compared_to_default_branch,
17
+ get_default_branch_remote_ref,
19
18
  get_git_staged_files,
20
19
  get_git_unstaged_files,
21
20
  )
22
-
23
- PR_DIFF_FILTER = 'ACMRD'
21
+ from .pull_request import (
22
+ PULL_REQUEST_DIFF_FILTER,
23
+ get_code_owner_specifications_at_ref,
24
+ get_pull_request_changed_files,
25
+ )
24
26
 
25
27
 
26
28
  def _build_parser() -> argparse.ArgumentParser:
@@ -28,7 +30,7 @@ def _build_parser() -> argparse.ArgumentParser:
28
30
  prog='codeownerinsights',
29
31
  description=(
30
32
  'Resolve the CODEOWNERS owners of files the way GitHub does. '
31
- 'With no paths, use the files the current branch changes compared with the '
33
+ 'With no paths, use the files the current branch commits change compared with the '
32
34
  "default branch, which are the files GitHub requests a pull request's reviewers for."
33
35
  ),
34
36
  )
@@ -50,6 +52,17 @@ def _build_parser() -> argparse.ArgumentParser:
50
52
  nargs='*',
51
53
  help="files to resolve, relative to the current directory; '-' reads paths from stdin",
52
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
+ )
53
66
  parser.add_argument(
54
67
  '--repo',
55
68
  type=Path,
@@ -59,11 +72,48 @@ def _build_parser() -> argparse.ArgumentParser:
59
72
  '--base',
60
73
  help='compare the current branch with this ref instead of the default branch',
61
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
+ )
62
83
  parser.add_argument(
63
84
  '--no-fetch',
64
85
  action='store_true',
65
86
  help='use the local origin/<default> ref without fetching it first',
66
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
+ )
67
117
  parser.add_argument(
68
118
  '--all-rules',
69
119
  action='store_true',
@@ -108,44 +158,73 @@ def _check_sources(parser: argparse.ArgumentParser, args: argparse.Namespace) ->
108
158
  working_tree = [
109
159
  flag for flag, on in (('--staged', args.staged), ('--unstaged', args.unstaged)) if on
110
160
  ]
111
- if not working_tree:
112
- return
113
- if args.paths:
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:
114
176
  parser.error(f'{working_tree[0]} cannot be combined with paths')
115
- if args.base or args.no_fetch:
116
- other = '--base' if args.base else '--no-fetch'
117
- parser.error(f'{working_tree[0]} cannot be combined with {other}')
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)
118
195
 
119
196
 
120
197
  def _collect_paths(
121
- args: argparse.Namespace, cwd: Path, repo_root: Path, stdin: TextIO
198
+ args: argparse.Namespace, cwd: Path, repo_root: Path, stdin: TextIO, base: Optional[str]
122
199
  ) -> List[Path]:
200
+ changed: List[Path] = []
123
201
  if args.staged or args.unstaged:
124
- changed: List[Path] = []
125
202
  if args.staged:
126
- changed += get_git_staged_files(repo_root, git=args.git, diff_filter=PR_DIFF_FILTER)
203
+ changed += get_git_staged_files(
204
+ repo_root, git=args.git, diff_filter=PULL_REQUEST_DIFF_FILTER
205
+ )
127
206
  if args.unstaged:
128
- changed += get_git_unstaged_files(repo_root, git=args.git, diff_filter=PR_DIFF_FILTER)
207
+ changed += get_git_unstaged_files(
208
+ repo_root, git=args.git, diff_filter=PULL_REQUEST_DIFF_FILTER
209
+ )
129
210
  return sorted(set(changed))
130
211
 
131
212
  if args.paths:
132
213
  raw: List[str] = []
133
214
  for path in args.paths:
134
- if path == '-':
215
+ if path == '-' and args.null_separated:
216
+ raw.extend(entry for entry in stdin.read().split('\0') if entry)
217
+ elif path == '-':
135
218
  raw.extend(line.strip() for line in stdin if line.strip())
136
219
  else:
137
220
  raw.append(path)
138
- return [_repo_relative(path, cwd, repo_root) for path in raw]
221
+ relative_to = repo_root if args.root_relative else cwd
222
+ return [_repo_relative(path, relative_to, repo_root) for path in raw]
139
223
 
140
- if args.base:
141
- changed = get_git_changed_files_compared_to_branch(
142
- repo_root, args.base, git=args.git, diff_filter=PR_DIFF_FILTER
143
- )
144
- else:
145
- changed = get_git_changed_files_compared_to_default_branch(
146
- repo_root, fetch_remote=not args.no_fetch, git=args.git, diff_filter=PR_DIFF_FILTER
147
- )
148
- return list(changed)
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
+ )
149
228
 
150
229
 
151
230
  def _relative_to_repo(path: Path, repo_root: Path) -> PurePath:
@@ -182,6 +261,31 @@ def _resolve(
182
261
  return results
183
262
 
184
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
+
185
289
  def _owners_summary(results: List[Dict[str, object]]) -> Dict[str, List[str]]:
186
290
  summary: Dict[str, List[str]] = {}
187
291
  for result in results:
@@ -299,30 +403,63 @@ def main(
299
403
  repo_root = (args.repo if args.repo.is_absolute() else cwd / args.repo) if args.repo else None
300
404
  repo_root = (repo_root or _find_repo_root(cwd, args.git)).resolve()
301
405
 
302
- codeowners_file = get_code_owners_file(repo_root)
303
- if codeowners_file is None:
304
- message = f'No CODEOWNERS file found in {repo_root}'
406
+ def fail(message: str, code: int) -> int:
305
407
  if args.json:
306
408
  json.dump({'error': message}, stderr)
307
409
  stderr.write('\n')
308
410
  else:
309
411
  stderr.write(f'{message}\n')
310
- return 2
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)
311
437
 
312
- specifications = list(
313
- parse_code_owners(codeowners_file, codeowners_file.read_text(encoding='utf-8'))
314
- )
315
438
  results = _resolve(
316
- specifications, _collect_paths(args, cwd, repo_root, stdin), repo_root, args.all_rules
439
+ specifications, _collect_paths(args, cwd, repo_root, stdin, base), repo_root, args.all_rules
317
440
  )
441
+ filtered = bool(results) and bool(args.owner or args.not_owner)
442
+ results = _filter_by_owner(results, args.owner, args.not_owner)
318
443
 
319
444
  if args.json:
320
- json.dump({'files': results, 'owners': _owners_summary(results)}, stdout, indent=2)
445
+ json.dump(
446
+ {
447
+ 'files': results,
448
+ 'owners': _owners_summary(results),
449
+ 'codeowners_ref': codeowners_ref,
450
+ },
451
+ stdout,
452
+ indent=2,
453
+ )
321
454
  stdout.write('\n')
322
455
  elif results:
323
456
  style = _Style(_use_color(args.color, stdout, os.environ if environ is None else environ))
324
457
  printer = _print_text_by_owner if args.group_by == 'owner' else _print_text
325
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')
326
463
  else:
327
464
  stderr.write('No files to resolve\n')
328
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
  )
@@ -104,10 +110,23 @@ def get_git_unstaged_files(
104
110
  folder_path, _git_cmd(git, 'diff', '--name-only', '-z', f'--diff-filter={diff_filter}')
105
111
  )
106
112
  )
107
- untracked = _null_separated_paths(
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(
108
118
  exec_command(folder_path, _git_cmd(git, 'ls-files', '--others', '--exclude-standard', '-z'))
109
119
  )
110
- return tracked + untracked
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
111
130
 
112
131
 
113
132
  def get_default_branch(folder_path: Path, git: str = DEFAULT_GIT) -> Optional[str]:
@@ -184,8 +203,6 @@ def exec_command(
184
203
  # returns the completed subpress and how long it took to complete as a float
185
204
  def execute_with_stdin(cmd, shell, text, cwd: Optional[Path] = None) -> ShellExecutionSummary:
186
205
  before = time.perf_counter()
187
- # https://docs.python.org/3/library/subprocess.html#subprocess.run - new in version 3.5
188
- # therefore, you need to be using ST build >= 4050 and the package should be opting in to Python 3.8 plugin host
189
206
  p = run(cmd, shell=shell, capture_output=True, input=text, encoding='utf-8', cwd=cwd)
190
207
  after = time.perf_counter()
191
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.4.0"
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