ownerloom 0.0.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.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
ownerloom-0.0.1/NOTICE ADDED
@@ -0,0 +1,9 @@
1
+ Ownerloom
2
+ Copyright 2026 Astrivant LLC
3
+
4
+ The compiler, CLI and extraction tests originate in Astrivant's Polyad project
5
+ at de7115d208ec2d02e6cb73a13016302c0bc70085. Astrivant LLC authorizes this
6
+ extracted work under Apache-2.0. See docs/provenance.json for source bindings.
7
+
8
+ Development helpers under scripts/ and their tooling tests retain separate terms
9
+ in scripts/NOTICE.md. They are not included in the installed Python package.
@@ -0,0 +1,138 @@
1
+ Metadata-Version: 2.4
2
+ Name: ownerloom
3
+ Version: 0.0.1
4
+ Summary: Compile readable CODEOWNERS policies without changing ownership precedence
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ License-File: NOTICE
8
+ Keywords: codeowners,git,pre-commit,compiler,ownership
9
+ Author: Astrivant LLC
10
+ Requires-Python: >=3.12,!=3.14.1,<4
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: MacOS
15
+ Classifier: Operating System :: POSIX :: Linux
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Topic :: Software Development :: Quality Assurance
22
+ Classifier: Topic :: Software Development :: Version Control :: Git
23
+ Classifier: Typing :: Typed
24
+ Requires-Dist: networkx (>=3.7,<4)
25
+ Project-URL: Documentation, https://github.com/astrivant/ownerloom/tree/main/docs
26
+ Project-URL: Homepage, https://github.com/astrivant/ownerloom
27
+ Project-URL: Issues, https://github.com/astrivant/ownerloom/issues
28
+ Description-Content-Type: text/markdown
29
+
30
+ # Ownerloom
31
+
32
+ [![Coverage](https://raw.githubusercontent.com/astrivant/ownerloom/gh-pages/badges/coverage.svg)](https://github.com/astrivant/ownerloom/blob/gh-pages/badges/coverage.json)
33
+
34
+ Keep CODEOWNERS readable as your repository grows. Ownerloom groups literal paths
35
+ by directory, removes redundant rules, and preserves the order that decides who
36
+ owns each path. One Python package replaces copied formatting scripts across projects.
37
+
38
+ <!-- toc:start -->
39
+ **Table of contents**
40
+
41
+ - [Quick start](#quick-start)
42
+ - [Why Ownerloom](#why-ownerloom)
43
+ - [Architecture](#architecture)
44
+ - [Inputs and results](#inputs-and-results)
45
+ - [Integrations and development](#integrations-and-development)
46
+ - [License and provenance](#license-and-provenance)
47
+ <!-- toc:end -->
48
+
49
+ ## Quick start
50
+
51
+ From this checkout, with Python 3.12+ and Git available:
52
+
53
+ ```bash
54
+ python -m pip install .
55
+ ownerloom --check
56
+ ownerloom --write
57
+ git diff -- .github/CODEOWNERS
58
+ ```
59
+
60
+ Review and stage the result yourself. Ownerloom never commits, pushes or changes
61
+ repository permissions. Python 3.14.1 is excluded by the NetworkX dependency.
62
+
63
+ ## Why Ownerloom
64
+
65
+ - **Readable policy:** keep related directories together without moving an override
66
+ ahead of the rule it overrides.
67
+ - **Conservative changes:** preserve comments, GitLab sections, wildcard rules and
68
+ unfamiliar syntax as boundaries. Retained syntax still needs provider validation.
69
+ - **Reviewable automation:** check the exact committed file and tree before push,
70
+ rather than allowing an unstaged fix to mask stale committed policy.
71
+ - **Reusable integration:** the same typed library powers the CLI, pre-commit and CI.
72
+ Normal compilation is offline and does not execute repository hooks or source.
73
+
74
+ ## Architecture
75
+
76
+ ```mermaid
77
+ flowchart LR
78
+ A[CODEOWNERS text] --> C[Literal runs and opaque boundaries]
79
+ B[Tracked Git inventory] --> C
80
+ C --> D[Remove shadowed and inherited rules]
81
+ D --> E[Precedence DAG]
82
+ E --> F[Deterministic tree order]
83
+ F --> G[Compilation result]
84
+ G --> H[Check or atomic write]
85
+ classDef input fill:#829B85,stroke:#647D8B,color:#243746
86
+ classDef pass fill:#C4AC70,stroke:#647D8B,color:#243746
87
+ class A,B input
88
+ class C,D,E,F,G,H pass
89
+ ```
90
+
91
+ The pure compiler accepts explicit text and paths. The CLI owns Git reads and
92
+ atomic writes. NetworkX orders the precedence graph; it does not interpret
93
+ provider policy. See the [compiler contract](docs/compiler.md) for supported
94
+ syntax, consolidation and failure behavior.
95
+
96
+ ## Inputs and results
97
+
98
+ | Input | Default | Purpose |
99
+ | --- | --- | --- |
100
+ | `--repo PATH` | Current directory | Existing repository root |
101
+ | `--file PATH` | `.github/CODEOWNERS` | Relative ownership file; select GitLab's path explicitly |
102
+ | `--check` | Required choice | Report whether selected text is normalized |
103
+ | `--write` | Required choice | Atomically replace working text; never stage it |
104
+ | `--revision REV` | Index inventory and working text | Check committed text and its tree together; check mode only |
105
+ | `--consolidate` | Off | Explicitly combine complete uniform subtrees, including future files |
106
+
107
+ Exit status is **0** for normalized or written content, **1** for formatting drift,
108
+ and **2** for invalid inputs or operational errors. Runtime use requires no credentials.
109
+ Release jobs use the repository secrets `PYPI_API_TOKEN`, `COSIGN_PRIVATE_KEY` and
110
+ `COSIGN_PASSWORD`, plus the trusted `COSIGN_PUBLIC_KEY_SHA256` variable. GitHub
111
+ supplies the repository, source SHA, tag and job token. See [release setup](docs/releases.md#configure-signing-and-publication)
112
+ for these administrator-managed inputs.
113
+
114
+ ```python
115
+ from ownerloom import compile_owners
116
+
117
+ result = compile_owners("/z @team\n/a @team\n", frozenset({"a", "z"}))
118
+ assert result.text == "/a @team\n/z @team\n"
119
+ ```
120
+
121
+ ## Integrations and development
122
+
123
+ Use the [pre-commit and migration guide](docs/integrations.md) to replace local
124
+ copies. Keep a provider-aware syntax/path linter alongside Ownerloom; formatting
125
+ does not establish account eligibility or enforce required reviews.
126
+
127
+ See [development](docs/development.md), [release verification](docs/releases.md),
128
+ [CI permissions](docs/permissions.md), and the portable [SKILL.md](SKILL.md)
129
+ ([browse online](https://github.com/astrivant/ownerloom/blob/main/SKILL.md)).
130
+ The implementation follows [RFC #94](https://github.com/astrivant/product-research/pull/94).
131
+
132
+ ## License and provenance
133
+
134
+ The runtime compiler is [Apache-2.0](LICENSE), copyright Astrivant LLC.
135
+ The [extraction manifest](docs/provenance.json) binds its source to Polyad's merged
136
+ compiler and records the owner's licensing choice. Development helpers retain
137
+ their [separate notices](scripts/NOTICE.md); they are excluded from the wheel.
138
+
@@ -0,0 +1,108 @@
1
+ # Ownerloom
2
+
3
+ [![Coverage](https://raw.githubusercontent.com/astrivant/ownerloom/gh-pages/badges/coverage.svg)](https://github.com/astrivant/ownerloom/blob/gh-pages/badges/coverage.json)
4
+
5
+ Keep CODEOWNERS readable as your repository grows. Ownerloom groups literal paths
6
+ by directory, removes redundant rules, and preserves the order that decides who
7
+ owns each path. One Python package replaces copied formatting scripts across projects.
8
+
9
+ <!-- toc:start -->
10
+ **Table of contents**
11
+
12
+ - [Quick start](#quick-start)
13
+ - [Why Ownerloom](#why-ownerloom)
14
+ - [Architecture](#architecture)
15
+ - [Inputs and results](#inputs-and-results)
16
+ - [Integrations and development](#integrations-and-development)
17
+ - [License and provenance](#license-and-provenance)
18
+ <!-- toc:end -->
19
+
20
+ ## Quick start
21
+
22
+ From this checkout, with Python 3.12+ and Git available:
23
+
24
+ ```bash
25
+ python -m pip install .
26
+ ownerloom --check
27
+ ownerloom --write
28
+ git diff -- .github/CODEOWNERS
29
+ ```
30
+
31
+ Review and stage the result yourself. Ownerloom never commits, pushes or changes
32
+ repository permissions. Python 3.14.1 is excluded by the NetworkX dependency.
33
+
34
+ ## Why Ownerloom
35
+
36
+ - **Readable policy:** keep related directories together without moving an override
37
+ ahead of the rule it overrides.
38
+ - **Conservative changes:** preserve comments, GitLab sections, wildcard rules and
39
+ unfamiliar syntax as boundaries. Retained syntax still needs provider validation.
40
+ - **Reviewable automation:** check the exact committed file and tree before push,
41
+ rather than allowing an unstaged fix to mask stale committed policy.
42
+ - **Reusable integration:** the same typed library powers the CLI, pre-commit and CI.
43
+ Normal compilation is offline and does not execute repository hooks or source.
44
+
45
+ ## Architecture
46
+
47
+ ```mermaid
48
+ flowchart LR
49
+ A[CODEOWNERS text] --> C[Literal runs and opaque boundaries]
50
+ B[Tracked Git inventory] --> C
51
+ C --> D[Remove shadowed and inherited rules]
52
+ D --> E[Precedence DAG]
53
+ E --> F[Deterministic tree order]
54
+ F --> G[Compilation result]
55
+ G --> H[Check or atomic write]
56
+ classDef input fill:#829B85,stroke:#647D8B,color:#243746
57
+ classDef pass fill:#C4AC70,stroke:#647D8B,color:#243746
58
+ class A,B input
59
+ class C,D,E,F,G,H pass
60
+ ```
61
+
62
+ The pure compiler accepts explicit text and paths. The CLI owns Git reads and
63
+ atomic writes. NetworkX orders the precedence graph; it does not interpret
64
+ provider policy. See the [compiler contract](docs/compiler.md) for supported
65
+ syntax, consolidation and failure behavior.
66
+
67
+ ## Inputs and results
68
+
69
+ | Input | Default | Purpose |
70
+ | --- | --- | --- |
71
+ | `--repo PATH` | Current directory | Existing repository root |
72
+ | `--file PATH` | `.github/CODEOWNERS` | Relative ownership file; select GitLab's path explicitly |
73
+ | `--check` | Required choice | Report whether selected text is normalized |
74
+ | `--write` | Required choice | Atomically replace working text; never stage it |
75
+ | `--revision REV` | Index inventory and working text | Check committed text and its tree together; check mode only |
76
+ | `--consolidate` | Off | Explicitly combine complete uniform subtrees, including future files |
77
+
78
+ Exit status is **0** for normalized or written content, **1** for formatting drift,
79
+ and **2** for invalid inputs or operational errors. Runtime use requires no credentials.
80
+ Release jobs use the repository secrets `PYPI_API_TOKEN`, `COSIGN_PRIVATE_KEY` and
81
+ `COSIGN_PASSWORD`, plus the trusted `COSIGN_PUBLIC_KEY_SHA256` variable. GitHub
82
+ supplies the repository, source SHA, tag and job token. See [release setup](docs/releases.md#configure-signing-and-publication)
83
+ for these administrator-managed inputs.
84
+
85
+ ```python
86
+ from ownerloom import compile_owners
87
+
88
+ result = compile_owners("/z @team\n/a @team\n", frozenset({"a", "z"}))
89
+ assert result.text == "/a @team\n/z @team\n"
90
+ ```
91
+
92
+ ## Integrations and development
93
+
94
+ Use the [pre-commit and migration guide](docs/integrations.md) to replace local
95
+ copies. Keep a provider-aware syntax/path linter alongside Ownerloom; formatting
96
+ does not establish account eligibility or enforce required reviews.
97
+
98
+ See [development](docs/development.md), [release verification](docs/releases.md),
99
+ [CI permissions](docs/permissions.md), and the portable [SKILL.md](SKILL.md)
100
+ ([browse online](https://github.com/astrivant/ownerloom/blob/main/SKILL.md)).
101
+ The implementation follows [RFC #94](https://github.com/astrivant/product-research/pull/94).
102
+
103
+ ## License and provenance
104
+
105
+ The runtime compiler is [Apache-2.0](LICENSE), copyright Astrivant LLC.
106
+ The [extraction manifest](docs/provenance.json) binds its source to Polyad's merged
107
+ compiler and records the owner's licensing choice. Development helpers retain
108
+ their [separate notices](scripts/NOTICE.md); they are excluded from the wheel.
@@ -0,0 +1,9 @@
1
+ """
2
+ Compile readable ownership rules while preserving literal policy precedence.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from ownerloom.compiler import Compilation, compile_owners
8
+
9
+ __all__ = ["Compilation", "compile_owners"]
@@ -0,0 +1,10 @@
1
+ """
2
+ Run the same command interface as the installed Ownerloom entry point.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from ownerloom.cli import main
8
+
9
+ if __name__ == "__main__":
10
+ raise SystemExit(main())
@@ -0,0 +1,137 @@
1
+ """
2
+ Check or explicitly rewrite CODEOWNERS using the selected repository inventory.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import argparse
8
+ import os
9
+ import subprocess
10
+ import tempfile
11
+ from pathlib import Path
12
+ from typing import TYPE_CHECKING
13
+
14
+ from ownerloom.compiler import compile_owners
15
+
16
+ if TYPE_CHECKING:
17
+ from collections.abc import Sequence
18
+
19
+ __all__ = ["main"]
20
+
21
+
22
+ def _git(root: Path, *arguments: str) -> str:
23
+ """
24
+ Read Git metadata without evaluating hooks or repository filesystem monitors.
25
+
26
+ Args:
27
+ root (Path): Explicit existing worktree.
28
+ *arguments (str): Literal read-only Git arguments.
29
+
30
+ Returns:
31
+ str: Strict UTF-8 output, including NUL-separated inventories.
32
+ """
33
+ environment = {key: value for key, value in os.environ.items() if not key.startswith("GIT_")}
34
+ # Honor the index selected by pre-commit, but do not inherit repository routing or tracing.
35
+ if "GIT_INDEX_FILE" in os.environ:
36
+ environment["GIT_INDEX_FILE"] = os.environ["GIT_INDEX_FILE"]
37
+ result = subprocess.run(
38
+ ["git", "-c", "core.fsmonitor=false", "-C", str(root), *arguments],
39
+ env=environment,
40
+ capture_output=True,
41
+ check=True,
42
+ timeout=30,
43
+ )
44
+ return result.stdout.decode("utf-8")
45
+
46
+
47
+ def _replace(path: Path, before: bytes, after: bytes) -> None:
48
+ """
49
+ Replace reviewed text atomically while preserving permissions and detecting intervening edits.
50
+
51
+ Args:
52
+ path (Path): Existing regular CODEOWNERS file.
53
+ before (bytes): Previously read source bytes.
54
+ after (bytes): Compiled candidate bytes.
55
+
56
+ Returns:
57
+ None: The candidate replaces the file; nothing is staged or committed.
58
+ """
59
+ descriptor, name = tempfile.mkstemp(prefix=".codeowners-", dir=path.parent)
60
+ temporary = Path(name)
61
+ try:
62
+ with os.fdopen(descriptor, "wb") as stream:
63
+ os.fchmod(stream.fileno(), path.stat().st_mode & 0o777)
64
+ stream.write(after)
65
+ stream.flush()
66
+ os.fsync(stream.fileno())
67
+ if path.is_symlink() or path.read_bytes() != before:
68
+ raise ValueError("CODEOWNERS changed during compilation; retry after reviewing the concurrent edit")
69
+ os.replace(temporary, path)
70
+ finally:
71
+ temporary.unlink(missing_ok=True)
72
+
73
+
74
+ def main(argv: Sequence[str] | None = None) -> int:
75
+ """
76
+ Compile working text or check an immutable revision without remote access.
77
+
78
+ Args:
79
+ argv (Sequence[str] | None): Explicit arguments, or the process argument list.
80
+
81
+ Returns:
82
+ int: Zero for normalized/written content, one for drift, two for invalid input or I/O failure.
83
+ """
84
+ parser = argparse.ArgumentParser(description=__doc__)
85
+ parser.add_argument("--repo", type=Path, default=Path.cwd())
86
+ parser.add_argument("--file", default=".github/CODEOWNERS", help="Repository-relative ownership file; select GitLab's path explicitly")
87
+ mode = parser.add_mutually_exclusive_group(required=True)
88
+ mode.add_argument("--check", action="store_true")
89
+ mode.add_argument("--write", action="store_true")
90
+ parser.add_argument("--revision", help="Check committed text and tree together, for example HEAD at pre-push")
91
+ parser.add_argument("--consolidate", action="store_true", help="Opt in to new directory scopes, including their future files")
92
+ args = parser.parse_args(argv)
93
+ try:
94
+ root = args.repo.resolve(strict=True)
95
+ if Path(_git(root, "rev-parse", "--show-toplevel").strip()).resolve() != root:
96
+ raise ValueError("--repo must name the repository root, not a subdirectory")
97
+ relative = Path(args.file)
98
+ if relative.is_absolute() or any(part in {"..", ".git"} for part in relative.parts):
99
+ raise ValueError("--file must stay within the worktree, outside Git metadata")
100
+ target = root / relative
101
+ if any(parent.is_symlink() for parent in (target, *target.parents) if parent != root and root in parent.parents):
102
+ raise ValueError("CODEOWNERS must not be reached through a symlink")
103
+ if args.revision:
104
+ if args.write:
105
+ raise ValueError("--revision supports --check only")
106
+ revision = _git(root, "rev-parse", "--verify", "--end-of-options", args.revision + "^{commit}").strip()
107
+ source = _git(root, "show", f"{revision}:{relative.as_posix()}")
108
+ inventory = _git(root, "ls-tree", "-r", "--name-only", "-z", revision)
109
+ else:
110
+ if _git(root, "ls-files", "--unmerged"):
111
+ raise ValueError("Resolve index conflicts before compiling ownership")
112
+ source = target.read_bytes().decode("utf-8")
113
+ inventory = _git(root, "ls-files", "--cached", "-z")
114
+ paths = frozenset(inventory.rstrip("\0").split("\0")) - {""}
115
+ result = compile_owners(source, paths, consolidate=args.consolidate)
116
+ if result.barriers:
117
+ print(f"Retained {len(result.barriers)} opaque lines as ordering boundaries (patterns, sections, exclusions or absent paths).")
118
+ for scope in result.consolidated:
119
+ print(f"Review directory ownership including future files: {scope}")
120
+ if result.text == source:
121
+ print("CODEOWNERS is normalized.")
122
+ return 0
123
+ if args.check:
124
+ print("CODEOWNERS needs normalization; run with --write, review the diff and commit it before pushing.")
125
+ return 1
126
+ _replace(target, source.encode("utf-8"), result.text.encode("utf-8"))
127
+ print("Normalized CODEOWNERS; review and stage the diff explicitly.")
128
+ return 0
129
+ except (OSError, UnicodeError, ValueError, subprocess.SubprocessError) as error:
130
+ # Git diagnostics can contain remote or local configuration; report only the failure category.
131
+ detail = str(error) if isinstance(error, ValueError) and not isinstance(error, UnicodeError) else type(error).__name__
132
+ print(f"CODEOWNERS compilation failed: {detail}")
133
+ return 2
134
+
135
+
136
+ if __name__ == "__main__":
137
+ raise SystemExit(main())
@@ -0,0 +1,242 @@
1
+ """
2
+ Normalize literal CODEOWNERS rules without changing ordered ownership policy.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import re
8
+ from dataclasses import dataclass
9
+ from typing import TYPE_CHECKING
10
+
11
+ import networkx as nx
12
+
13
+ if TYPE_CHECKING:
14
+ from collections.abc import Sequence
15
+
16
+ __all__ = ["Compilation", "compile_owners"]
17
+
18
+ _LITERAL = re.compile(r"/(?:[A-Za-z0-9_.-]+/)*[A-Za-z0-9_.-]+/?")
19
+ _OWNER = re.compile(r"(?:@@?[A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+)*|[^\s@#]+@[^\s@#]+)")
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class Rule:
24
+ """
25
+ Retain an anchored literal rule and its exact source line.
26
+
27
+ Attributes:
28
+ pattern (str): Root-relative literal file or directory pattern.
29
+ owners (tuple[str, ...]): Ordered owner tokens, without interpreting host eligibility.
30
+ source (str): Original line including its terminator.
31
+ """
32
+
33
+ pattern: str
34
+ owners: tuple[str, ...]
35
+ source: str
36
+
37
+ def covers(self, path: str) -> bool:
38
+ """
39
+ Match one repository-relative path under this literal scope.
40
+
41
+ Args:
42
+ path (str): Relative path without a leading slash.
43
+
44
+ Returns:
45
+ bool: Whether the literal scope includes the path.
46
+ """
47
+ base = self.pattern.strip("/")
48
+ return path.startswith(base + "/") or (not self.pattern.endswith("/") and path == base)
49
+
50
+ def contains(self, other: Rule) -> bool:
51
+ """
52
+ Establish containment for every path, including future additions.
53
+
54
+ Args:
55
+ other (Rule): Candidate narrower ownership scope.
56
+
57
+ Returns:
58
+ bool: Whether this rule covers every path the other could match.
59
+ """
60
+ base, child = self.pattern.strip("/"), other.pattern.strip("/")
61
+ return child.startswith(base + "/") or (base == child and (not self.pattern.endswith("/") or other.pattern.endswith("/")))
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class Compilation:
66
+ """
67
+ Return normalized text and a visible account of untouched syntax.
68
+
69
+ Attributes:
70
+ text (str): Candidate ownership document.
71
+ barriers (tuple[int, ...]): One-based non-comment lines retained as opaque boundaries.
72
+ consolidated (tuple[str, ...]): New directory scopes requiring explicit review.
73
+ """
74
+
75
+ text: str
76
+ barriers: tuple[int, ...]
77
+ consolidated: tuple[str, ...]
78
+
79
+
80
+ def _parse(line: str, paths: frozenset[str]) -> Rule | None:
81
+ """
82
+ Accept only existing, anchored literal scopes with explicit plain owners.
83
+
84
+ Args:
85
+ line (str): Original source line.
86
+ paths (frozenset[str]): Tracked repository paths supplied by the caller.
87
+
88
+ Returns:
89
+ Rule | None: Transformable rule or an opaque boundary.
90
+ """
91
+ fields = line.split()
92
+ if len(fields) < 2 or not _LITERAL.fullmatch(fields[0]):
93
+ return None
94
+ if any(part in {".", ".."} for part in fields[0].strip("/").split("/")):
95
+ return None
96
+ if not all(_OWNER.fullmatch(owner) for owner in fields[1:]):
97
+ return None
98
+ rule = Rule(fields[0], tuple(fields[1:]), line)
99
+ return rule if any(rule.covers(path) for path in paths) else None
100
+
101
+
102
+ def _overlap(left: Rule, right: Rule) -> bool:
103
+ """
104
+ Conservatively identify scopes whose order could affect ownership.
105
+
106
+ Args:
107
+ left (Rule): First scope.
108
+ right (Rule): Second scope.
109
+
110
+ Returns:
111
+ bool: Whether either literal scope contains the other.
112
+ """
113
+ return left.contains(right) or right.contains(left)
114
+
115
+
116
+ def _simplify(rules: Sequence[Rule]) -> list[Rule]:
117
+ """
118
+ Remove shadowed rules and inherited duplicates without broadening ownership.
119
+
120
+ Args:
121
+ rules (Sequence[Rule]): One contiguous run, in its original evaluation order.
122
+
123
+ Returns:
124
+ list[Rule]: Equivalent scopes for present and future paths.
125
+ """
126
+ kept: list[Rule] = []
127
+ for index, rule in enumerate(rules):
128
+ # A later covering rule wins on every path this rule could affect.
129
+ if any(later.contains(rule) for later in rules[index + 1 :]):
130
+ continue
131
+ previous = next((earlier for earlier in reversed(kept) if _overlap(earlier, rule)), None)
132
+ if previous is not None and previous.contains(rule) and previous.owners == rule.owners:
133
+ continue
134
+ kept.append(rule)
135
+ return kept
136
+
137
+
138
+ def _ordered(rules: Sequence[Rule]) -> list[Rule]:
139
+ """
140
+ Group directory branches while retaining precedence for overlapping scopes.
141
+
142
+ Args:
143
+ rules (Sequence[Rule]): Simplified literal run.
144
+
145
+ Returns:
146
+ list[Rule]: Deterministic directory-tree order subject to precedence constraints.
147
+ """
148
+ graph: nx.DiGraph[int, dict[str, object], dict[str, object]] = nx.DiGraph()
149
+ graph.add_nodes_from(range(len(rules)))
150
+ # Preserve policy dependencies; sorting strings alone could move an override before its parent.
151
+ for index, rule in enumerate(rules):
152
+ for later in range(index + 1, len(rules)):
153
+ if _overlap(rule, rules[later]):
154
+ graph.add_edge(index, later)
155
+ order = nx.lexicographical_topological_sort(graph, key=lambda index: tuple(rules[index].pattern.strip("/").split("/")))
156
+ return [rules[index] for index in order]
157
+
158
+
159
+ def _fold(rules: Sequence[Rule], paths: frozenset[str], newline: str) -> tuple[list[Rule], list[str]]:
160
+ """
161
+ Optionally combine complete tracked subtrees under a reviewed directory scope.
162
+
163
+ Args:
164
+ rules (Sequence[Rule]): Literal scopes in one boundary-delimited run.
165
+ paths (frozenset[str]): Complete tracked repository path inventory.
166
+ newline (str): Original document line-ending convention.
167
+
168
+ Returns:
169
+ tuple[list[Rule], list[str]]: Rules and the new future-facing directory scopes.
170
+ """
171
+ result = list(rules)
172
+ folded: list[str] = []
173
+ directories = {path.rsplit("/", 1)[0] for path in paths if "/" in path}
174
+ directories |= {
175
+ "/".join(directory.split("/")[:depth]) for directory in tuple(directories) for depth in range(1, len(directory.split("/")))
176
+ }
177
+ for directory in sorted(directories, key=lambda value: (-value.count("/"), value)):
178
+ prefix = directory + "/"
179
+ selected = [rule for rule in result if rule.pattern.lstrip("/").startswith(prefix)]
180
+ if len(selected) < 2 or any(rule.owners != selected[0].owners for rule in selected):
181
+ continue
182
+ members = [path for path in paths if path.startswith(prefix)]
183
+ if not members or any(not any(rule.covers(path) for rule in selected) for path in members):
184
+ continue
185
+ # All intersecting rules in this run must be selected: an intervening parent may override them.
186
+ replacement = Rule("/" + prefix, selected[0].owners, "/" + prefix + " " + " ".join(selected[0].owners) + newline)
187
+ if any(_overlap(rule, replacement) and rule not in selected for rule in result):
188
+ continue
189
+ first = result.index(selected[0])
190
+ result = [rule for rule in result if rule not in selected]
191
+ result.insert(first, replacement)
192
+ folded.append(replacement.pattern)
193
+ return result, folded
194
+
195
+
196
+ def compile_owners(source: str, paths: frozenset[str], *, consolidate: bool = False) -> Compilation:
197
+ """
198
+ Parse, simplify, order and emit without executing repository-owned content.
199
+
200
+ Args:
201
+ source (str): Complete CODEOWNERS text; comments and opaque syntax stay in place.
202
+ paths (frozenset[str]): Tracked file paths, including symlinks as entries, never followed.
203
+ consolidate (bool): Explicitly allow new directory scopes covering future files too.
204
+
205
+ Returns:
206
+ Compilation: Candidate text, untouched boundary lines, and new directory scopes.
207
+ """
208
+ output: list[str] = []
209
+ run: list[Rule] = []
210
+ barriers: list[int] = []
211
+ folded: list[str] = []
212
+ newline = "\r\n" if "\r\n" in source else "\n"
213
+
214
+ def flush() -> None:
215
+ """
216
+ Emit one independently transformable run without crossing an opaque boundary.
217
+
218
+ Returns:
219
+ None: Output buffers receive the normalized run.
220
+ """
221
+ rules = _simplify(run)
222
+ if consolidate:
223
+ rules, changes = _fold(rules, paths, newline)
224
+ folded.extend(changes)
225
+ ordered = _ordered(rules)
226
+ output.extend(rule.source.rstrip("\r\n") + newline for rule in ordered)
227
+ run.clear()
228
+
229
+ for number, line in enumerate(source.splitlines(keepends=True), 1):
230
+ rule = _parse(line, paths)
231
+ if rule is not None:
232
+ run.append(rule)
233
+ else:
234
+ flush()
235
+ output.append(line)
236
+ if line.strip() and not line.lstrip().startswith("#"):
237
+ barriers.append(number)
238
+ flush()
239
+ text = "".join(output)
240
+ if source and not source.endswith(("\n", "\r")):
241
+ text = text.rstrip("\r\n")
242
+ return Compilation(text, tuple(barriers), tuple(folded))
File without changes
@@ -0,0 +1,120 @@
1
+ [project]
2
+ name = "ownerloom"
3
+ version = "0.0.1"
4
+ description = "Compile readable CODEOWNERS policies without changing ownership precedence"
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE", "NOTICE"]
8
+ requires-python = ">=3.12,!=3.14.1,<4"
9
+ dependencies = ["networkx>=3.7,<4"]
10
+ authors = [{name = "Astrivant LLC"}]
11
+ keywords = ["codeowners", "git", "pre-commit", "compiler", "ownership"]
12
+ classifiers = [
13
+ "Development Status :: 3 - Alpha",
14
+ "Environment :: Console",
15
+ "Intended Audience :: Developers",
16
+ "Operating System :: MacOS",
17
+ "Operating System :: POSIX :: Linux",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3 :: Only",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Programming Language :: Python :: 3.14",
23
+ "Topic :: Software Development :: Quality Assurance",
24
+ "Topic :: Software Development :: Version Control :: Git",
25
+ "Typing :: Typed",
26
+ ]
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/astrivant/ownerloom"
30
+ Documentation = "https://github.com/astrivant/ownerloom/tree/main/docs"
31
+ Issues = "https://github.com/astrivant/ownerloom/issues"
32
+
33
+ [project.scripts]
34
+ ownerloom = "ownerloom.cli:main"
35
+
36
+ [tool.poetry]
37
+ packages = [{include = "ownerloom", from = "pkg"}]
38
+ include = [{path = "pkg/ownerloom/py.typed", format = ["sdist", "wheel"]}]
39
+
40
+ [build-system]
41
+ requires = ["poetry-core==2.5.0"]
42
+ build-backend = "poetry.core.masonry.api"
43
+
44
+ [tool.ruff]
45
+ cache-dir = ".cache/ruff"
46
+ src = ["pkg"]
47
+ line-length = 140
48
+ target-version = "py312"
49
+
50
+ [tool.ruff.lint]
51
+ select = ["E", "F", "I", "UP", "B", "D", "TC"]
52
+ ignore = ["D200", "D202", "D212"]
53
+ extend-select = ["D213"]
54
+
55
+ [tool.ruff.lint.isort]
56
+ required-imports = ["from __future__ import annotations"]
57
+
58
+ [tool.ruff.lint.pydocstyle]
59
+ convention = "google"
60
+
61
+ [tool.mypy]
62
+ cache_dir = ".cache/mypy"
63
+ python_version = "3.12"
64
+ strict = true
65
+ files = ["pkg", "tests", "scripts"]
66
+ disallow_any_explicit = true
67
+ disallow_any_unimported = true
68
+
69
+ [tool.pydocstyle]
70
+ convention = "google"
71
+ add-ignore = ["D200", "D202", "D212"]
72
+ add-select = ["D213"]
73
+ match = ".*\\.py"
74
+ match-dir = "^(?!node_modules$|\\.).*"
75
+
76
+ [tool.pydoclint]
77
+ style = "google"
78
+ exclude = "node_modules|\\.venv|\\.cache"
79
+ allow-init-docstring = true
80
+ skip-checking-short-docstrings = false
81
+ arg-type-hints-in-docstring = true
82
+ arg-type-hints-in-signature = true
83
+ check-return-types = true
84
+ check-arg-order = true
85
+ require-return-section-when-returning-nothing = true
86
+ skip-checking-raises = true
87
+
88
+ [tool.pytest.ini_options]
89
+ testpaths = ["tests"]
90
+ pythonpath = ["pkg", "."]
91
+ addopts = "-ra --import-mode=importlib"
92
+
93
+ [dependency-groups]
94
+ dev = [
95
+ "pytest==9.1.1",
96
+ "pytest-cov==7.1.0",
97
+ "hypothesis==6.170.1",
98
+ "ruff==0.17.1",
99
+ "mypy==2.4.0",
100
+ "pydocstyle==6.3.0",
101
+ "pydoclint==0.11.1",
102
+ "pre-commit==4.7.0",
103
+ "pip-audit==2.10.1",
104
+ "twine==7.0.0",
105
+ "pyyaml==6.0.3",
106
+ "types-networkx==3.6.1.20261006",
107
+ "types-pyyaml==6.0.12.20260906",
108
+ "shellcheck-py==0.11.0.1",
109
+ "shfmt-py==4.2.0",
110
+ ]
111
+
112
+ [tool.coverage.run]
113
+ source = ["ownerloom"]
114
+ branch = true
115
+ relative_files = true
116
+
117
+ [tool.coverage.report]
118
+ show_missing = true
119
+ skip_covered = true
120
+ fail_under = 85