codeownerinsights 0.1.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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 STealthy and haSTy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,165 @@
1
+ Metadata-Version: 2.4
2
+ Name: codeownerinsights
3
+ Version: 0.1.0
4
+ Summary: Parse GitHub's CODEOWNERS file and resolve code owners for a path, with optional git integration.
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Keywords: codeowners,git,github,code-review,ownership
8
+ Author: Keith Hall
9
+ Author-email: keith.hall@available.systems
10
+ Requires-Python: >=3.11,<4.0
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Software Development :: Version Control :: Git
15
+ Requires-Dist: wcmatch (>=10.0,<11.0)
16
+ Project-URL: Homepage, https://github.com/STealthy-and-haSTy/CodeOwnerInsights
17
+ Project-URL: Issues, https://github.com/STealthy-and-haSTy/CodeOwnerInsights/issues
18
+ Project-URL: Repository, https://github.com/STealthy-and-haSTy/CodeOwnerInsights
19
+ Description-Content-Type: text/markdown
20
+
21
+ # codeownerinsights
22
+
23
+ Parse GitHub's [`CODEOWNERS`](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners)
24
+ file and work out who owns a given file: which rules match it, and which one
25
+ wins. Pure Python, no editor dependency.
26
+
27
+ ```sh
28
+ pip install codeownerinsights
29
+ ```
30
+
31
+ Requires Python 3.8 or newer. The only runtime dependency is
32
+ [`wcmatch`](https://pypi.org/project/wcmatch/), for GitHub-compatible glob
33
+ matching.
34
+
35
+ ## Usage
36
+
37
+ ```python
38
+ from pathlib import Path
39
+
40
+ from codeownerinsights import (
41
+ parse_code_owners,
42
+ get_matching_code_owner_specifications_for_file,
43
+ get_resolved_code_owners_for_file,
44
+ )
45
+
46
+ codeowners_path = Path('.github/CODEOWNERS')
47
+ codeowners = list(parse_code_owners(codeowners_path, codeowners_path.read_text(encoding='utf-8')))
48
+
49
+ # every rule that matches, in file order
50
+ for spec in get_matching_code_owner_specifications_for_file(codeowners, Path('src/main.py')):
51
+ print(spec.glob_pattern, '->', spec.owners)
52
+
53
+ # the resolved owner: the last matching rule wins
54
+ owner = get_resolved_code_owners_for_file(codeowners, Path('src/main.py'))
55
+ print(owner.owners)
56
+ ```
57
+
58
+ ## What it gives you
59
+
60
+ **All matching rules, not just the winner.** Most parsers stop at the resolved
61
+ owner. `get_matching_code_owner_specifications_for_file` yields every rule that
62
+ hits a path, in file order, so you can show a user which earlier rule is being
63
+ overridden by a later one — or why an intended rule did not match at all.
64
+
65
+ **Nearest comment carried with each rule.** Every parsed
66
+ `CodeOwnerSpecification` remembers the comment block immediately above it, so a
67
+ rule can be presented with its documentation rather than as a bare pattern.
68
+
69
+ ```python
70
+ spec.nearest_comment # '# Frontend rules\n# owned by the web team'
71
+ spec.glob_pattern # '/web/'
72
+ spec.owners # ['@web-team']
73
+ spec.line_number # 5
74
+ spec.codeowners_file_path
75
+ ```
76
+
77
+ **GitHub's documented semantics, not git's.** Patterns follow GitHub's
78
+ `CODEOWNERS` rules literally: a leading `/` anchors the pattern to the repository
79
+ root, and a trailing `/` matches the directory and its contents. This is
80
+ deliberately *not* the `git check-ignore` convention where a leading slash means
81
+ "do not match". The asymmetry that matters in practice is between anchored and
82
+ unslashed directory patterns — with a `CODEOWNERS` at the repository root,
83
+ `docs/` matches `docs/readme.md` *and* `src/docs/readme.md`, while `/docs/` matches
84
+ `docs/readme.md` but not `src/docs/readme.md`. A slash in the middle anchors a
85
+ pattern just as a leading one does, so `docs/*` matches `docs/intro.md` but not
86
+ `src/docs/intro.md`. A pattern that matches a directory covers everything beneath it,
87
+ except that `docs/*` stops at the files directly inside `docs`.
88
+
89
+ Where the two differ, we follow GitHub. `git check-ignore` additionally supports
90
+ `!` to negate a pattern, `\` to escape a leading `#`, and `[ ]` character classes;
91
+ GitHub's `CODEOWNERS` docs list all three as unsupported, and this library does not
92
+ handle them. `test/test_matching.py` pins the matching rules, checked against how
93
+ GitHub itself resolves the `CODEOWNERS` files of public repositories.
94
+
95
+ **Locating the file.** `get_code_owners_file(root)` looks in the three places
96
+ GitHub searches, in GitHub's order, and returns the first hit:
97
+
98
+ ```python
99
+ get_code_owners_file(Path('.'))
100
+ # .github/CODEOWNERS, CODEOWNERS, or docs/CODEOWNERS
101
+ ```
102
+
103
+ ## Git integration
104
+
105
+ `codeownerinsights.git` shells out to git to find what changed relative to a
106
+ branch, which is what you want to answer "who reviews this PR".
107
+
108
+ ```python
109
+ from pathlib import Path
110
+ from codeownerinsights.git import get_git_changed_files_compared_to_default_branch
111
+
112
+ for changed in get_git_changed_files_compared_to_default_branch(Path('.')):
113
+ print(changed)
114
+ ```
115
+
116
+ By default this refreshes `origin/<default>` first, so the result reflects the
117
+ real remote baseline; pass `fetch_remote=False` to skip the network round trip
118
+ and accept a possibly stale baseline. Renamed files are reported under their new
119
+ path only, and deletions are dropped.
120
+
121
+ Every helper accepts an optional `git=` parameter, so a wrapper can be
122
+ substituted by replacing the leading command token — useful for injecting
123
+ credentials:
124
+
125
+ ```python
126
+ get_git_changed_files_compared_to_default_branch(Path('.'), git='my-git-wrapper')
127
+ ```
128
+
129
+ No function changes the process working directory; commands run against the
130
+ folder passed in via `cwd=`. This matters in hosts like the Sublime Text plugin
131
+ host, where all packages share one interpreter.
132
+
133
+ ## Status bar text
134
+
135
+ `status_text` renders a resolved rule into a status-bar line from a template,
136
+ for callers that want configurable wording.
137
+
138
+ ```python
139
+ from codeownerinsights.status_text import render_status_text
140
+
141
+ render_status_text('Code Owner: {comment? - }{owners}', spec)
142
+ # 'Code Owner: Frontend rules owned by the web team - @web-team'
143
+ ```
144
+
145
+ Available keys are `{owners}`, `{owner}` (the first owner only), `{comment}`,
146
+ `{pattern}`, `{line_number}` and `{codeowners_file}`. A key with nothing to say
147
+ renders as nothing and the surrounding whitespace is collapsed, so one template
148
+ serves every rule. A misspelled key is left in place rather than silently
149
+ blanked, and nothing raises on a bad template.
150
+
151
+ A key can be made conditional: `{key?text}` includes the literal `text` only
152
+ when the key has a value, and drops it when it does not. That is how the
153
+ example keeps the dash beside `{comment}` when there is a comment and omits it
154
+ when there is not, instead of leaving a stray dash behind.
155
+
156
+ ## Used by
157
+
158
+ This library is the engine behind
159
+ [CodeOwnerInsights](https://github.com/STealthy-and-haSTy/CodeOwnerInsights), a
160
+ Sublime Text plugin that surfaces the current file's code owner in the status
161
+ bar.
162
+
163
+ ## License
164
+
165
+ MIT.
@@ -0,0 +1,145 @@
1
+ # codeownerinsights
2
+
3
+ Parse GitHub's [`CODEOWNERS`](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners)
4
+ file and work out who owns a given file: which rules match it, and which one
5
+ wins. Pure Python, no editor dependency.
6
+
7
+ ```sh
8
+ pip install codeownerinsights
9
+ ```
10
+
11
+ Requires Python 3.8 or newer. The only runtime dependency is
12
+ [`wcmatch`](https://pypi.org/project/wcmatch/), for GitHub-compatible glob
13
+ matching.
14
+
15
+ ## Usage
16
+
17
+ ```python
18
+ from pathlib import Path
19
+
20
+ from codeownerinsights import (
21
+ parse_code_owners,
22
+ get_matching_code_owner_specifications_for_file,
23
+ get_resolved_code_owners_for_file,
24
+ )
25
+
26
+ codeowners_path = Path('.github/CODEOWNERS')
27
+ codeowners = list(parse_code_owners(codeowners_path, codeowners_path.read_text(encoding='utf-8')))
28
+
29
+ # every rule that matches, in file order
30
+ for spec in get_matching_code_owner_specifications_for_file(codeowners, Path('src/main.py')):
31
+ print(spec.glob_pattern, '->', spec.owners)
32
+
33
+ # the resolved owner: the last matching rule wins
34
+ owner = get_resolved_code_owners_for_file(codeowners, Path('src/main.py'))
35
+ print(owner.owners)
36
+ ```
37
+
38
+ ## What it gives you
39
+
40
+ **All matching rules, not just the winner.** Most parsers stop at the resolved
41
+ owner. `get_matching_code_owner_specifications_for_file` yields every rule that
42
+ hits a path, in file order, so you can show a user which earlier rule is being
43
+ overridden by a later one — or why an intended rule did not match at all.
44
+
45
+ **Nearest comment carried with each rule.** Every parsed
46
+ `CodeOwnerSpecification` remembers the comment block immediately above it, so a
47
+ rule can be presented with its documentation rather than as a bare pattern.
48
+
49
+ ```python
50
+ spec.nearest_comment # '# Frontend rules\n# owned by the web team'
51
+ spec.glob_pattern # '/web/'
52
+ spec.owners # ['@web-team']
53
+ spec.line_number # 5
54
+ spec.codeowners_file_path
55
+ ```
56
+
57
+ **GitHub's documented semantics, not git's.** Patterns follow GitHub's
58
+ `CODEOWNERS` rules literally: a leading `/` anchors the pattern to the repository
59
+ root, and a trailing `/` matches the directory and its contents. This is
60
+ deliberately *not* the `git check-ignore` convention where a leading slash means
61
+ "do not match". The asymmetry that matters in practice is between anchored and
62
+ unslashed directory patterns — with a `CODEOWNERS` at the repository root,
63
+ `docs/` matches `docs/readme.md` *and* `src/docs/readme.md`, while `/docs/` matches
64
+ `docs/readme.md` but not `src/docs/readme.md`. A slash in the middle anchors a
65
+ pattern just as a leading one does, so `docs/*` matches `docs/intro.md` but not
66
+ `src/docs/intro.md`. A pattern that matches a directory covers everything beneath it,
67
+ except that `docs/*` stops at the files directly inside `docs`.
68
+
69
+ Where the two differ, we follow GitHub. `git check-ignore` additionally supports
70
+ `!` to negate a pattern, `\` to escape a leading `#`, and `[ ]` character classes;
71
+ GitHub's `CODEOWNERS` docs list all three as unsupported, and this library does not
72
+ handle them. `test/test_matching.py` pins the matching rules, checked against how
73
+ GitHub itself resolves the `CODEOWNERS` files of public repositories.
74
+
75
+ **Locating the file.** `get_code_owners_file(root)` looks in the three places
76
+ GitHub searches, in GitHub's order, and returns the first hit:
77
+
78
+ ```python
79
+ get_code_owners_file(Path('.'))
80
+ # .github/CODEOWNERS, CODEOWNERS, or docs/CODEOWNERS
81
+ ```
82
+
83
+ ## Git integration
84
+
85
+ `codeownerinsights.git` shells out to git to find what changed relative to a
86
+ branch, which is what you want to answer "who reviews this PR".
87
+
88
+ ```python
89
+ from pathlib import Path
90
+ from codeownerinsights.git import get_git_changed_files_compared_to_default_branch
91
+
92
+ for changed in get_git_changed_files_compared_to_default_branch(Path('.')):
93
+ print(changed)
94
+ ```
95
+
96
+ By default this refreshes `origin/<default>` first, so the result reflects the
97
+ real remote baseline; pass `fetch_remote=False` to skip the network round trip
98
+ and accept a possibly stale baseline. Renamed files are reported under their new
99
+ path only, and deletions are dropped.
100
+
101
+ Every helper accepts an optional `git=` parameter, so a wrapper can be
102
+ substituted by replacing the leading command token — useful for injecting
103
+ credentials:
104
+
105
+ ```python
106
+ get_git_changed_files_compared_to_default_branch(Path('.'), git='my-git-wrapper')
107
+ ```
108
+
109
+ No function changes the process working directory; commands run against the
110
+ folder passed in via `cwd=`. This matters in hosts like the Sublime Text plugin
111
+ host, where all packages share one interpreter.
112
+
113
+ ## Status bar text
114
+
115
+ `status_text` renders a resolved rule into a status-bar line from a template,
116
+ for callers that want configurable wording.
117
+
118
+ ```python
119
+ from codeownerinsights.status_text import render_status_text
120
+
121
+ render_status_text('Code Owner: {comment? - }{owners}', spec)
122
+ # 'Code Owner: Frontend rules owned by the web team - @web-team'
123
+ ```
124
+
125
+ Available keys are `{owners}`, `{owner}` (the first owner only), `{comment}`,
126
+ `{pattern}`, `{line_number}` and `{codeowners_file}`. A key with nothing to say
127
+ renders as nothing and the surrounding whitespace is collapsed, so one template
128
+ serves every rule. A misspelled key is left in place rather than silently
129
+ blanked, and nothing raises on a bad template.
130
+
131
+ A key can be made conditional: `{key?text}` includes the literal `text` only
132
+ when the key has a value, and drops it when it does not. That is how the
133
+ example keeps the dash beside `{comment}` when there is a comment and omits it
134
+ when there is not, instead of leaving a stray dash behind.
135
+
136
+ ## Used by
137
+
138
+ This library is the engine behind
139
+ [CodeOwnerInsights](https://github.com/STealthy-and-haSTy/CodeOwnerInsights), a
140
+ Sublime Text plugin that surfaces the current file's code owner in the status
141
+ bar.
142
+
143
+ ## License
144
+
145
+ MIT.
@@ -0,0 +1,36 @@
1
+ """codeownerinsights
2
+
3
+ Framework-agnostic helpers for parsing GitHub's CODEOWNERS file and resolving
4
+ owners for a path, plus thin wrappers around git for finding changed files.
5
+
6
+ The package is intentionally free of any editor dependency so the logic can be
7
+ imported and unit tested from any Python environment.
8
+ """
9
+
10
+ from .codeowners import (
11
+ CodeOwnerSpecification,
12
+ does_codeowner_glob_match,
13
+ get_code_owners_file,
14
+ get_matching_code_owner_specifications_for_file,
15
+ get_resolved_code_owners_for_file,
16
+ is_path_relative_to,
17
+ parse_code_owners,
18
+ )
19
+ from .status_text import (
20
+ DEFAULT_STATUS_TEMPLATE,
21
+ get_template_replacements,
22
+ render_status_text,
23
+ )
24
+
25
+ __all__ = [
26
+ 'CodeOwnerSpecification',
27
+ 'DEFAULT_STATUS_TEMPLATE',
28
+ 'does_codeowner_glob_match',
29
+ 'get_code_owners_file',
30
+ 'get_matching_code_owner_specifications_for_file',
31
+ 'get_resolved_code_owners_for_file',
32
+ 'get_template_replacements',
33
+ 'is_path_relative_to',
34
+ 'parse_code_owners',
35
+ 'render_status_text',
36
+ ]
@@ -0,0 +1,142 @@
1
+ import functools
2
+ import re
3
+ from collections import deque
4
+ from pathlib import Path, PurePath
5
+ from typing import Iterable, Optional, Pattern, Tuple
6
+ from dataclasses import dataclass
7
+ from wcmatch.glob import translate, CASE, DOTGLOB, FORCEUNIX, GLOBSTAR
8
+
9
+ # https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners
10
+
11
+ # Characters that wcmatch treats as glob syntax but GitHub's CODEOWNERS docs
12
+ # say do not work. They must be matched literally, so the pattern is escaped
13
+ # before being handed to wcmatch. ``*``, ``?`` and ``**`` are left alone --
14
+ # those are the wildcards CODEOWNERS does support.
15
+ _LITERAL_GLOB_CHARS = str.maketrans({'[': r'\[', ']': r'\]'})
16
+
17
+
18
+ @functools.lru_cache(maxsize=None)
19
+ def _compile_codeowner_glob(glob_pattern: str) -> Optional[Tuple[str, Pattern[str]]]:
20
+ # Any path the pattern matches contains its longest wildcard-free run, so a
21
+ # substring check rules out most paths without running the regex.
22
+ required_literal = max(re.split(r'[*?/]', glob_pattern), key=len)
23
+ glob_pattern = glob_pattern.translate(_LITERAL_GLOB_CHARS)
24
+ directory_only = glob_pattern.endswith('/')
25
+ body = glob_pattern.strip('/')
26
+ if body == '':
27
+ return None
28
+ # A slash at the start or in the middle anchors the pattern to the root;
29
+ # a trailing slash alone does not.
30
+ anchored = glob_pattern.startswith('/') or '/' in body
31
+
32
+ patterns_to_try = list()
33
+ if not directory_only:
34
+ patterns_to_try.append(body)
35
+ # GitHub keeps `docs/*` to the files directly inside `docs`.
36
+ if directory_only or body.split('/')[-1] != '*':
37
+ patterns_to_try.append(body + '/**')
38
+ if not anchored:
39
+ patterns_to_try = ['**/' + pattern for pattern in patterns_to_try]
40
+
41
+ # GitHub's matching does not vary by platform, while wcmatch's defaults do.
42
+ regexes, _ = translate(patterns_to_try, flags=GLOBSTAR | DOTGLOB | CASE | FORCEUNIX)
43
+ return required_literal, re.compile('|'.join(regexes))
44
+
45
+
46
+ def does_codeowner_glob_match(glob_pattern: str, path: PurePath) -> bool:
47
+ compiled = _compile_codeowner_glob(glob_pattern)
48
+ if compiled is None:
49
+ return False
50
+ required_literal, regex = compiled
51
+ posix_path = path.as_posix() if isinstance(path, PurePath) else str(path)
52
+ if required_literal not in posix_path:
53
+ return False
54
+ return regex.match(posix_path.lstrip('/')) is not None
55
+
56
+
57
+ @dataclass
58
+ class CodeOwnerSpecification:
59
+ """Data class for showing the code owner specification parsed from a line in a CODEOWNERS file."""
60
+
61
+ nearest_comment: Optional[str]
62
+ glob_pattern: str
63
+ owners: list # [str]
64
+ line_number: int
65
+ codeowners_file_path: Path
66
+
67
+ def does_match(self, path: Path) -> bool:
68
+ return does_codeowner_glob_match(self.glob_pattern, path)
69
+
70
+
71
+ def parse_code_owners(
72
+ codeowners_file_path: Path, codeowners_content: str
73
+ ) -> Iterable[CodeOwnerSpecification]:
74
+ last_comment = None
75
+ line_number = 0
76
+ prev_line_was_a_rule = False
77
+ for line in codeowners_content.splitlines():
78
+ line_number += 1
79
+ if line.lstrip().startswith('#'):
80
+ if last_comment is None or prev_line_was_a_rule:
81
+ last_comment = line
82
+ else:
83
+ last_comment += '\n' + line
84
+ prev_line_was_a_rule = False
85
+ continue
86
+
87
+ if line.strip() == '':
88
+ last_comment = None
89
+ prev_line_was_a_rule = False
90
+ continue
91
+
92
+ prev_line_was_a_rule = True
93
+ inline_comment_pos = line.find('#')
94
+ if inline_comment_pos > -1:
95
+ line = line[0:inline_comment_pos]
96
+ # assume no spaces in file path glob for now
97
+ glob_pattern, *owners = line.split()
98
+
99
+ yield CodeOwnerSpecification(
100
+ last_comment, glob_pattern, owners, line_number, codeowners_file_path
101
+ )
102
+
103
+
104
+ def get_matching_code_owner_specifications_for_file(
105
+ codeowners: Iterable[CodeOwnerSpecification], path: Path
106
+ ) -> Iterable[CodeOwnerSpecification]:
107
+ for owner_specification in codeowners:
108
+ if owner_specification.does_match(path):
109
+ yield owner_specification
110
+
111
+
112
+ def get_resolved_code_owners_for_file(
113
+ codeowners: Iterable[CodeOwnerSpecification], path: Path
114
+ ) -> Optional[CodeOwnerSpecification]:
115
+ # TODO: option to skip * root entry
116
+
117
+ queue = deque(get_matching_code_owner_specifications_for_file(codeowners, path), maxlen=1)
118
+ if queue:
119
+ last_element = queue.pop()
120
+ return last_element
121
+
122
+ return None
123
+
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.
128
+
129
+ for folder in try_locations:
130
+ path = repo_root / folder / 'CODEOWNERS'
131
+ if path.is_file():
132
+ return path
133
+
134
+ return None
135
+
136
+
137
+ def is_path_relative_to(path: Path, possible_ancestor_folder: Path) -> bool:
138
+ try:
139
+ path.relative_to(possible_ancestor_folder)
140
+ return True
141
+ except ValueError:
142
+ return False
@@ -0,0 +1,36 @@
1
+ """Pure helpers for narrowing values that arrive as untyped data.
2
+
3
+ Settings are user-editable JSON, and command arguments can be supplied by a
4
+ keybinding, so neither is guaranteed to be the type the caller wants. These
5
+ helpers narrow such values at the boundary rather than asserting a type that
6
+ has not actually been checked, which keeps a typo from silently inverting a
7
+ setting.
8
+
9
+ Free of Sublime Text imports, in keeping with codeowners.py and git.py, so the
10
+ logic here is testable without a running editor.
11
+ """
12
+
13
+
14
+ def coerce_bool(value: object, default: bool) -> bool:
15
+ """Interpret a value from a settings file or command argument as a boolean.
16
+
17
+ Recognises the spellings a user can realistically write. An unrecognised
18
+ value falls back to ``default`` rather than being guessed at, so that a
19
+ malformed entry cannot silently flip the setting.
20
+ """
21
+ if isinstance(value, bool):
22
+ return value
23
+ if isinstance(value, str):
24
+ # strip quotes as well as space, so a value that was double-quoted by
25
+ # mistake ("\"false\"") is read the same as a bare one
26
+ lowered = value.strip().strip('"\'').strip().lower()
27
+ if lowered in ('true', 'yes', 'on', '1'):
28
+ return True
29
+ if lowered in ('false', 'no', 'off', '0'):
30
+ return False
31
+ return default
32
+ if isinstance(value, (int, float)):
33
+ # a numeric boolean means what it looks like, so 0 reads as off rather
34
+ # than as an unrecognised value falling back to the default
35
+ return bool(value)
36
+ return default
@@ -0,0 +1,152 @@
1
+ from pathlib import Path
2
+ from typing import Iterable, List, Optional
3
+ import subprocess
4
+ from subprocess import run
5
+ import time
6
+ from dataclasses import dataclass
7
+
8
+ DEFAULT_GIT = 'git'
9
+
10
+
11
+ @dataclass
12
+ class ShellExecutionSummary:
13
+ process: Optional[subprocess.CompletedProcess]
14
+ time_taken: float
15
+
16
+
17
+ def _git_cmd(git: str, *args: str) -> List[str]:
18
+ """Build a git command list, substituting the configured git binary.
19
+
20
+ Commands are assembled as ``["git", ...]`` so that the binary can be swapped
21
+ out (e.g. for a git wrapper that injects credentials) by replacing the
22
+ leading token.
23
+ """
24
+ return [git, *args]
25
+
26
+
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
29
+ ) -> Iterable[Path]:
30
+ """filter can be like --relative=source/ or '*.php' etc."""
31
+ current_branch = get_current_branch(folder_path, git=git)
32
+ if not current_branch:
33
+ return []
34
+ # find the common ancestor incase local or remote base branch is more up to date than the feature branch
35
+ merge_base = exec_command(
36
+ folder_path, _git_cmd(git, 'merge-base', base_branch_name, current_branch)
37
+ )
38
+ if not merge_base or merge_base.process.returncode != 0:
39
+ return []
40
+ diff_cmd = _git_cmd(
41
+ git,
42
+ 'diff',
43
+ merge_base.process.stdout.rstrip(),
44
+ '--name-only',
45
+ '--diff-filter=ACMR',
46
+ )
47
+ if filter:
48
+ diff_cmd.append(filter)
49
+ files = exec_command(folder_path, diff_cmd)
50
+ if not files:
51
+ return []
52
+ return (
53
+ Path(file) for file in files.process.stdout.split('\n') if file
54
+ ) # purists would say that files can be named with \n chars...
55
+
56
+
57
+ def get_git_changed_files_compared_to_default_branch(
58
+ folder_path: Path,
59
+ filter: Optional[str] = None,
60
+ fetch_remote: bool = True,
61
+ git: str = DEFAULT_GIT,
62
+ ) -> Iterable[Path]:
63
+ """filter can be like --relative=source/ or '*.php' etc."""
64
+ # Compare against the remote-tracking ref for the default branch (e.g.
65
+ # origin/main), which is the real baseline for a PR. The local default
66
+ # branch is frequently stale, and comparing against it would drag the merge
67
+ # base back and surface unrelated default-branch commits.
68
+ base_branch_name = get_default_branch_remote_ref(folder_path, fetch_remote, git=git)
69
+ if not base_branch_name:
70
+ return []
71
+ return get_git_changed_files_compared_to_branch(folder_path, base_branch_name, filter, git=git)
72
+
73
+
74
+ def get_default_branch(folder_path: Path, git: str = DEFAULT_GIT) -> Optional[str]:
75
+ result = exec_command(folder_path, _git_cmd(git, 'rev-parse', '--abbrev-ref', 'origin/HEAD'))
76
+ if result and result.process.returncode == 0:
77
+ # origin/HEAD points to something like 'origin/main' - extract the branch name
78
+ ref = result.process.stdout.rstrip()
79
+ if ref.startswith('origin/'):
80
+ return ref[len('origin/') :]
81
+ return ref
82
+ return None
83
+
84
+
85
+ def get_default_branch_remote_ref(
86
+ folder_path: Path, fetch_remote: bool = True, git: str = DEFAULT_GIT
87
+ ) -> Optional[str]:
88
+ """Return the remote-tracking ref for the default branch, e.g. ``origin/main``.
89
+
90
+ The local default branch is often stale behind ``origin/<default>``, and a
91
+ feature branch is typically created from the up-to-date remote ref. Comparing
92
+ against the local branch would therefore fall back to an old merge base and
93
+ surface every commit the default branch has made since as if they were this
94
+ branch's changes. Prefer the remote ref that actually represents the baseline
95
+ for the PR, falling back to the local branch only when the remote ref is not
96
+ available locally.
97
+
98
+ When ``fetch_remote`` is true (the default) the remote-tracking ref is
99
+ refreshed first, so the baseline reflects the real remote. When false the
100
+ local ref is used as-is, which is fast but can be stale if the remote has
101
+ moved since the last fetch.
102
+ """
103
+ branch = get_default_branch(folder_path, git=git)
104
+ if not branch:
105
+ return None
106
+ if fetch_remote:
107
+ # Refresh the remote-tracking ref first. The local ref can lag behind
108
+ # the remote (e.g. the user has not run fetch/pull since the default
109
+ # branch moved), and a stale ref would drag the merge base back and
110
+ # surface unrelated default-branch commits. Failures are ignored: the
111
+ # verify below falls back to the local branch when the remote ref is
112
+ # unavailable.
113
+ fetch_default_branch(folder_path, branch, git=git)
114
+ remote_ref = f'origin/{branch}'
115
+ result = exec_command(folder_path, _git_cmd(git, 'rev-parse', '--verify', remote_ref))
116
+ if result and result.process.returncode == 0:
117
+ return remote_ref
118
+ return branch
119
+
120
+
121
+ def fetch_default_branch(folder_path: Path, branch: str, git: str = DEFAULT_GIT) -> None:
122
+ """Best-effort refresh of the remote-tracking ref for ``branch``.
123
+
124
+ Network or permission failures are intentionally ignored: the caller falls
125
+ back to the local ref when the fetch does not succeed.
126
+ """
127
+ result = exec_command(folder_path, _git_cmd(git, 'fetch', 'origin', branch))
128
+ if not result or result.process.returncode != 0:
129
+ return
130
+
131
+
132
+ def get_current_branch(folder_path: Path, git: str = DEFAULT_GIT) -> Optional[str]:
133
+ result = exec_command(folder_path, _git_cmd(git, 'rev-parse', '--abbrev-ref', 'HEAD'))
134
+ if result and result.process.returncode == 0:
135
+ return result.process.stdout.rstrip()
136
+ return None
137
+
138
+
139
+ def exec_command(
140
+ folder_path: Path, cmd: List[str], git: str = DEFAULT_GIT
141
+ ) -> ShellExecutionSummary:
142
+ return execute_with_stdin(cmd, False, '', folder_path)
143
+
144
+
145
+ # returns the completed subpress and how long it took to complete as a float
146
+ def execute_with_stdin(cmd, shell, text, cwd: Optional[Path] = None) -> ShellExecutionSummary:
147
+ before = time.perf_counter()
148
+ # https://docs.python.org/3/library/subprocess.html#subprocess.run - new in version 3.5
149
+ # therefore, you need to be using ST build >= 4050 and the package should be opting in to Python 3.8 plugin host
150
+ p = run(cmd, shell=shell, capture_output=True, input=text, encoding='utf-8', cwd=cwd)
151
+ after = time.perf_counter()
152
+ return ShellExecutionSummary(p, after - before)
@@ -0,0 +1,103 @@
1
+ """Rendering of the status bar text for a resolved code owner.
2
+
3
+ The text is a user-configurable template with ``{key}`` placeholders, so the
4
+ substitution lives here rather than in the plugin: a malformed template is
5
+ something worth asserting on, and this module has to stay free of Sublime Text
6
+ imports to be importable at all.
7
+ """
8
+
9
+ import re
10
+ from typing import Dict, Optional
11
+
12
+ from .codeowners import CodeOwnerSpecification
13
+
14
+ DEFAULT_STATUS_TEMPLATE = 'Code Owner: {comment? - }{owners}'
15
+
16
+ # A placeholder is either ``{key}``, substituted with the key's value, or
17
+ # ``{key?text}``, where the literal text is included only when the key has a
18
+ # value. The second form is what lets a separator sit beside a comment and be
19
+ # dropped when there is none, instead of leaving a stray dash behind.
20
+ _PLACEHOLDER = re.compile(r'\{(\w+)(\?[^}]*)?\}')
21
+
22
+
23
+ def format_comment(comment: Optional[str], separator: str = ' ') -> str:
24
+ """Flatten a comment block onto one line, dropping the leading ``#``s.
25
+
26
+ ``separator`` joins the lines: a space suits a status bar, where the result
27
+ has to stay on one line, while the rules quick panel has a second row per
28
+ entry to be a little more readable.
29
+ """
30
+ if not comment:
31
+ return ''
32
+
33
+ lines = []
34
+ for line in comment.split('\n'):
35
+ line = line.strip()
36
+ if line.startswith('#'):
37
+ line = line[1:]
38
+ line = line.strip()
39
+ if line:
40
+ lines.append(line)
41
+ return separator.join(lines)
42
+
43
+
44
+ def get_template_replacements(
45
+ specification: CodeOwnerSpecification,
46
+ ) -> Dict[str, str]:
47
+ """The values a template may refer to, all as strings.
48
+
49
+ ``owner`` is the first owner rather than all of them because the status bar
50
+ is width constrained and the first entry is the one usually meant.
51
+ """
52
+ owners = list(specification.owners)
53
+ return {
54
+ 'owners': ', '.join(owners),
55
+ 'owner': owners[0] if owners else '',
56
+ 'comment': format_comment(specification.nearest_comment),
57
+ 'pattern': specification.glob_pattern,
58
+ 'line_number': str(specification.line_number),
59
+ 'codeowners_file': str(specification.codeowners_file_path),
60
+ }
61
+
62
+
63
+ def render_status_text(template: str, specification: CodeOwnerSpecification) -> str:
64
+ """Fill in a status bar template for a resolved code owner.
65
+
66
+ A recognised key with nothing to say -- ``{comment}`` for a rule that has no
67
+ comment above it -- renders as nothing, so one template can serve every rule
68
+ rather than needing a special case per rule. A key that is not recognised is
69
+ left exactly as written, because an unsubstituted ``{key}`` is the only clue
70
+ the user gets that their spelling is wrong; nothing here raises on a bad
71
+ template, since a status bar is not worth an exception in the editor.
72
+
73
+ Whitespace runs are collapsed afterwards, so a value that came out empty
74
+ cannot leave the gap it was sitting in.
75
+ """
76
+ replacements = get_template_replacements(specification)
77
+ text = _PLACEHOLDER.sub(
78
+ # a function replacement, so a value containing backslashes is not
79
+ # mistaken for a group reference
80
+ lambda match: _render_placeholder(match, replacements),
81
+ template,
82
+ )
83
+ return ' '.join(text.split())
84
+
85
+
86
+ def _render_placeholder(match: re.Match, replacements: Dict[str, str]) -> str:
87
+ key = match.group(1)
88
+ conditional = match.group(2)
89
+ if conditional is None:
90
+ # a plain {key}: substitute the value, or leave it alone when the key
91
+ # is not recognised, since an unsubstituted key is the only clue the
92
+ # user gets that their spelling is wrong
93
+ return replacements.get(key, match.group(0))
94
+ # a {key?text} conditional: the value is followed by the literal text when
95
+ # the key has a value, and the whole thing is dropped when it does not. The
96
+ # text sits after the key, so it is a suffix -- that is what lets a
97
+ # separator beside {comment} vanish with the comment instead of leaving a
98
+ # stray dash in the status bar. A key that is not recognised is left
99
+ # exactly as written, so a misspelled conditional is still obvious.
100
+ if key not in replacements:
101
+ return match.group(0)
102
+ value = replacements[key]
103
+ return value + conditional[1:] if value else ''
@@ -0,0 +1,43 @@
1
+ [project]
2
+ name = "codeownerinsights"
3
+ version = "0.1.0"
4
+ description = "Parse GitHub's CODEOWNERS file and resolve code owners for a path, with optional git integration."
5
+ authors = [{ name = "Keith Hall", email = "keith.hall@available.systems" }]
6
+ license = "MIT"
7
+ readme = "README-pypi.md"
8
+ requires-python = ">=3.11,<4.0"
9
+ keywords = ["codeowners", "git", "github", "code-review", "ownership"]
10
+ dependencies = ["wcmatch (>=10.0,<11.0)"]
11
+ classifiers = [
12
+ "Development Status :: 4 - Beta",
13
+ "Intended Audience :: Developers",
14
+ "Programming Language :: Python :: 3",
15
+ "Topic :: Software Development :: Version Control :: Git",
16
+ ]
17
+
18
+ [project.urls]
19
+ Homepage = "https://github.com/STealthy-and-haSTy/CodeOwnerInsights"
20
+ Repository = "https://github.com/STealthy-and-haSTy/CodeOwnerInsights"
21
+ Issues = "https://github.com/STealthy-and-haSTy/CodeOwnerInsights/issues"
22
+
23
+ [tool.poetry]
24
+ packages = [{ include = "codeownerinsights" }]
25
+
26
+ [tool.poetry.group.dev.dependencies]
27
+ pytest = "^8.3.3"
28
+ ruff = "^0.12.0"
29
+
30
+ [tool.pytest.ini_options]
31
+ # the repo root holds the modules under test, which are not installed as a package
32
+ pythonpath = ["."]
33
+ testpaths = ["test"]
34
+
35
+ [tool.ruff]
36
+ line-length = 100
37
+
38
+ [tool.ruff.format]
39
+ quote-style = "single"
40
+
41
+ [build-system]
42
+ requires = ["poetry-core"]
43
+ build-backend = "poetry.core.masonry.api"