codeownerinsights 0.1.0__tar.gz → 0.3.1__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.1.0
3
+ Version: 0.3.1
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
@@ -100,6 +100,39 @@ get_code_owners_file(Path('.'))
100
100
  # .github/CODEOWNERS, CODEOWNERS, or docs/CODEOWNERS
101
101
  ```
102
102
 
103
+ ## Command line
104
+
105
+ `codeownerinsights` (or `python -m codeownerinsights`) prints the owner of each
106
+ file and the rule that decides it, then the owners those files need. With no
107
+ arguments it uses the files the current branch changes compared with
108
+ `origin/<default>`, deletions included, which are the files GitHub requests a
109
+ pull request's reviewers for.
110
+
111
+ ```sh
112
+ $ codeownerinsights
113
+ source/app/config/routes.php @org/backend CODEOWNERS:2 *
114
+ source/src/Model/Identity/User.php @org/identity CODEOWNERS:91 source/**/Identity/
115
+
116
+ Owners:
117
+ @org/backend (1 file)
118
+ @org/identity (1 file)
119
+ ```
120
+
121
+ - Pass paths to resolve those files instead, relative to the current directory.
122
+ `-` reads paths from stdin, so `git diff --name-only main... | codeownerinsights -`
123
+ works too.
124
+ - `--repo <path>` resolves files against a repository other than the current git
125
+ top level.
126
+ - `--base <ref>` compares with another ref, and `--no-fetch` skips refreshing
127
+ `origin/<default>`.
128
+ - `--all-rules` lists every matching rule under each file and marks the one that
129
+ applies with `*`. With `--json`, this includes `matching_rules` for each file.
130
+ - `--json` prints the same result as JSON, with an `owners` map from each owner
131
+ to its files.
132
+ - `--git <executable>` uses a different git executable (default: `git`).
133
+
134
+ The exit code is 2 when the repository has no `CODEOWNERS` file.
135
+
103
136
  ## Git integration
104
137
 
105
138
  `codeownerinsights.git` shells out to git to find what changed relative to a
@@ -116,7 +149,7 @@ for changed in get_git_changed_files_compared_to_default_branch(Path('.')):
116
149
  By default this refreshes `origin/<default>` first, so the result reflects the
117
150
  real remote baseline; pass `fetch_remote=False` to skip the network round trip
118
151
  and accept a possibly stale baseline. Renamed files are reported under their new
119
- path only, and deletions are dropped.
152
+ path only, and deletions are dropped unless you pass `diff_filter='ACMRD'`.
120
153
 
121
154
  Every helper accepts an optional `git=` parameter, so a wrapper can be
122
155
  substituted by replacing the leading command token — useful for injecting
@@ -80,6 +80,39 @@ get_code_owners_file(Path('.'))
80
80
  # .github/CODEOWNERS, CODEOWNERS, or docs/CODEOWNERS
81
81
  ```
82
82
 
83
+ ## Command line
84
+
85
+ `codeownerinsights` (or `python -m codeownerinsights`) prints the owner of each
86
+ file and the rule that decides it, then the owners those files need. With no
87
+ arguments it uses the files the current branch changes compared with
88
+ `origin/<default>`, deletions included, which are the files GitHub requests a
89
+ pull request's reviewers for.
90
+
91
+ ```sh
92
+ $ codeownerinsights
93
+ source/app/config/routes.php @org/backend CODEOWNERS:2 *
94
+ source/src/Model/Identity/User.php @org/identity CODEOWNERS:91 source/**/Identity/
95
+
96
+ Owners:
97
+ @org/backend (1 file)
98
+ @org/identity (1 file)
99
+ ```
100
+
101
+ - Pass paths to resolve those files instead, relative to the current directory.
102
+ `-` reads paths from stdin, so `git diff --name-only main... | codeownerinsights -`
103
+ works too.
104
+ - `--repo <path>` resolves files against a repository other than the current git
105
+ top level.
106
+ - `--base <ref>` compares with another ref, and `--no-fetch` skips refreshing
107
+ `origin/<default>`.
108
+ - `--all-rules` lists every matching rule under each file and marks the one that
109
+ applies with `*`. With `--json`, this includes `matching_rules` for each file.
110
+ - `--json` prints the same result as JSON, with an `owners` map from each owner
111
+ to its files.
112
+ - `--git <executable>` uses a different git executable (default: `git`).
113
+
114
+ The exit code is 2 when the repository has no `CODEOWNERS` file.
115
+
83
116
  ## Git integration
84
117
 
85
118
  `codeownerinsights.git` shells out to git to find what changed relative to a
@@ -96,7 +129,7 @@ for changed in get_git_changed_files_compared_to_default_branch(Path('.')):
96
129
  By default this refreshes `origin/<default>` first, so the result reflects the
97
130
  real remote baseline; pass `fetch_remote=False` to skip the network round trip
98
131
  and accept a possibly stale baseline. Renamed files are reported under their new
99
- path only, and deletions are dropped.
132
+ path only, and deletions are dropped unless you pass `diff_filter='ACMRD'`.
100
133
 
101
134
  Every helper accepts an optional `git=` parameter, so a wrapper can be
102
135
  substituted by replacing the leading command token — useful for injecting
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == '__main__':
6
+ sys.exit(main())
@@ -0,0 +1,201 @@
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
@@ -25,7 +25,11 @@ def _git_cmd(git: str, *args: str) -> List[str]:
25
25
 
26
26
 
27
27
  def get_git_changed_files_compared_to_branch(
28
- folder_path: Path, base_branch_name: str, filter: Optional[str] = None, git: str = DEFAULT_GIT
28
+ folder_path: Path,
29
+ base_branch_name: str,
30
+ filter: Optional[str] = None,
31
+ git: str = DEFAULT_GIT,
32
+ diff_filter: str = 'ACMR',
29
33
  ) -> Iterable[Path]:
30
34
  """filter can be like --relative=source/ or '*.php' etc."""
31
35
  current_branch = get_current_branch(folder_path, git=git)
@@ -42,7 +46,7 @@ def get_git_changed_files_compared_to_branch(
42
46
  'diff',
43
47
  merge_base.process.stdout.rstrip(),
44
48
  '--name-only',
45
- '--diff-filter=ACMR',
49
+ f'--diff-filter={diff_filter}',
46
50
  )
47
51
  if filter:
48
52
  diff_cmd.append(filter)
@@ -59,6 +63,7 @@ def get_git_changed_files_compared_to_default_branch(
59
63
  filter: Optional[str] = None,
60
64
  fetch_remote: bool = True,
61
65
  git: str = DEFAULT_GIT,
66
+ diff_filter: str = 'ACMR',
62
67
  ) -> Iterable[Path]:
63
68
  """filter can be like --relative=source/ or '*.php' etc."""
64
69
  # Compare against the remote-tracking ref for the default branch (e.g.
@@ -68,7 +73,9 @@ def get_git_changed_files_compared_to_default_branch(
68
73
  base_branch_name = get_default_branch_remote_ref(folder_path, fetch_remote, git=git)
69
74
  if not base_branch_name:
70
75
  return []
71
- return get_git_changed_files_compared_to_branch(folder_path, base_branch_name, filter, git=git)
76
+ return get_git_changed_files_compared_to_branch(
77
+ folder_path, base_branch_name, filter, git=git, diff_filter=diff_filter
78
+ )
72
79
 
73
80
 
74
81
  def get_default_branch(folder_path: Path, git: str = DEFAULT_GIT) -> Optional[str]:
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "codeownerinsights"
3
- version = "0.1.0"
3
+ version = "0.3.1"
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"
@@ -15,6 +15,9 @@ classifiers = [
15
15
  "Topic :: Software Development :: Version Control :: Git",
16
16
  ]
17
17
 
18
+ [project.scripts]
19
+ codeownerinsights = "codeownerinsights.cli:main"
20
+
18
21
  [project.urls]
19
22
  Homepage = "https://github.com/STealthy-and-haSTy/CodeOwnerInsights"
20
23
  Repository = "https://github.com/STealthy-and-haSTy/CodeOwnerInsights"
@@ -40,4 +43,4 @@ quote-style = "single"
40
43
 
41
44
  [build-system]
42
45
  requires = ["poetry-core"]
43
- build-backend = "poetry.core.masonry.api"
46
+ build-backend = "poetry.core.masonry.api"