beman-submodule 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,219 @@
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.
203
+
204
+
205
+ ---- LLVM Exceptions to the Apache 2.0 License ----
206
+
207
+ As an exception, if, as a result of your compiling your source code, portions
208
+ of this Software are embedded into an Object form of such source code, you
209
+ may redistribute such embedded portions in such Object form without complying
210
+ with the conditions of Sections 4(a), 4(b) and 4(d) of the License.
211
+
212
+ In addition, if you combine or link compiled forms of this Software with
213
+ software that is licensed under the GPLv2 ("Combined Software") and if a
214
+ court of competent jurisdiction determines that the patent provision (Section
215
+ 3), the indemnity provision (Section 9) or other Section of the License
216
+ conflicts with the conditions of the GPLv2, you may retroactively and
217
+ prospectively choose to deem waived or otherwise exclude such Section(s) of
218
+ the License, but only in their entirety and only with respect to the Combined
219
+ Software.
@@ -0,0 +1,163 @@
1
+ Metadata-Version: 2.4
2
+ Name: beman-submodule
3
+ Version: 0.1.0
4
+ Summary: A pseudo-submodule tool for vendoring Git repositories in Beman projects
5
+ Keywords: beman,bemanproject,git,submodule,vendoring,cli tool
6
+ Author-email: The Beman Project <eddiejnolan@gmail.com>
7
+ Requires-Python: >=3.12
8
+ Description-Content-Type: text/markdown
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Environment :: Console
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Topic :: Software Development :: Version Control :: Git
17
+ License-File: LICENSE
18
+ Project-URL: Homepage, https://github.com/bemanproject/beman-submodule
19
+ Project-URL: Issues, https://github.com/bemanproject/beman-submodule/issues
20
+ Project-URL: Repository, https://github.com/bemanproject/beman-submodule
21
+
22
+ # beman-submodule
23
+
24
+ <!-- SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -->
25
+
26
+ A pseudo-submodule tool for vendoring Git repositories in Beman projects.
27
+
28
+ ## What is beman-submodule?
29
+
30
+ `beman-submodule` provides some of the features of `git submodule`, adding child git
31
+ repositories to a parent git repository, but unlike with `git submodule`, the entire child
32
+ repo is directly checked in, so only maintainers, not users, need to run this script. The
33
+ command line interface mimics `git submodule`'s.
34
+
35
+ ## Installation
36
+
37
+ ```sh
38
+ pip install beman-submodule
39
+ ```
40
+
41
+ Or with [uv](https://github.com/astral-sh/uv):
42
+
43
+ ```sh
44
+ uv tool install beman-submodule
45
+ ```
46
+
47
+ ## Usage
48
+
49
+ ### Adding a beman submodule
50
+
51
+ ```sh
52
+ beman-submodule add https://github.com/bemanproject/infra.git
53
+ ```
54
+
55
+ This will clone the repository and create a `.beman_submodule` file tracking the remote and commit.
56
+
57
+ You can also specify a custom path:
58
+
59
+ ```sh
60
+ beman-submodule add https://github.com/bemanproject/infra.git infra/
61
+ ```
62
+
63
+ ### Updating beman submodules
64
+
65
+ Update all beman submodules to match their `.beman_submodule` configuration:
66
+
67
+ ```sh
68
+ beman-submodule update
69
+ ```
70
+
71
+ Update all beman submodules to the latest from upstream:
72
+
73
+ ```sh
74
+ beman-submodule update --remote
75
+ ```
76
+
77
+ Update only a specific submodule:
78
+
79
+ ```sh
80
+ beman-submodule update --remote infra/
81
+ ```
82
+
83
+ ### Checking status
84
+
85
+ Show the status of all beman submodules:
86
+
87
+ ```sh
88
+ beman-submodule status
89
+ ```
90
+
91
+ A `+` prefix indicates the submodule contents differ from the configured commit.
92
+
93
+ ## How does it work?
94
+
95
+ Along with the files from the child repository, it creates a dotfile called
96
+ `.beman_submodule`, which looks like this:
97
+
98
+ ```ini
99
+ [beman_submodule]
100
+ remote=https://github.com/bemanproject/infra.git
101
+ commit_hash=9b88395a86c4290794e503e94d8213b6c442ae77
102
+ ```
103
+
104
+ ### Updating to a specific commit or changing the remote URL
105
+
106
+ Edit the corresponding lines in the `.beman_submodule` file and run
107
+ `beman-submodule update` to update the state of the beman submodule to the new
108
+ settings.
109
+
110
+ ### Allow untracked files
111
+
112
+ If you need to add local files alongside the vendored content, use:
113
+
114
+ ```sh
115
+ beman-submodule add --allow-untracked-files https://github.com/example/repo.git path/
116
+ ```
117
+
118
+ This adds `allow_untracked_files=True` to the `.beman_submodule` config, preserving local
119
+ files during updates.
120
+
121
+ ## CI Integration
122
+
123
+ Add this job to your CI workflow to ensure beman submodules are in a valid state:
124
+
125
+ ```yaml
126
+ beman-submodule-test:
127
+ runs-on: ubuntu-latest
128
+ name: "Check beman submodules for consistency"
129
+ steps:
130
+ - name: Checkout
131
+ uses: actions/checkout@v4
132
+ - name: Install beman-submodule
133
+ run: pip install beman-submodule
134
+ - name: beman submodule consistency check
135
+ run: |
136
+ (set -o pipefail; beman-submodule status | grep -qvF '+')
137
+ ```
138
+
139
+ This will fail if the contents of any beman submodule don't match what's specified in the
140
+ `.beman_submodule` file.
141
+
142
+ ## Development
143
+
144
+ This project uses [uv](https://github.com/astral-sh/uv) for development:
145
+
146
+ ```sh
147
+ # Install dependencies
148
+ uv sync --group dev
149
+
150
+ # Run tests
151
+ uv run pytest
152
+
153
+ # Run linter
154
+ uv run ruff check .
155
+
156
+ # Format code
157
+ uv run ruff format .
158
+ ```
159
+
160
+ ## License
161
+
162
+ Apache-2.0 WITH LLVM-exception
163
+
@@ -0,0 +1,141 @@
1
+ # beman-submodule
2
+
3
+ <!-- SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -->
4
+
5
+ A pseudo-submodule tool for vendoring Git repositories in Beman projects.
6
+
7
+ ## What is beman-submodule?
8
+
9
+ `beman-submodule` provides some of the features of `git submodule`, adding child git
10
+ repositories to a parent git repository, but unlike with `git submodule`, the entire child
11
+ repo is directly checked in, so only maintainers, not users, need to run this script. The
12
+ command line interface mimics `git submodule`'s.
13
+
14
+ ## Installation
15
+
16
+ ```sh
17
+ pip install beman-submodule
18
+ ```
19
+
20
+ Or with [uv](https://github.com/astral-sh/uv):
21
+
22
+ ```sh
23
+ uv tool install beman-submodule
24
+ ```
25
+
26
+ ## Usage
27
+
28
+ ### Adding a beman submodule
29
+
30
+ ```sh
31
+ beman-submodule add https://github.com/bemanproject/infra.git
32
+ ```
33
+
34
+ This will clone the repository and create a `.beman_submodule` file tracking the remote and commit.
35
+
36
+ You can also specify a custom path:
37
+
38
+ ```sh
39
+ beman-submodule add https://github.com/bemanproject/infra.git infra/
40
+ ```
41
+
42
+ ### Updating beman submodules
43
+
44
+ Update all beman submodules to match their `.beman_submodule` configuration:
45
+
46
+ ```sh
47
+ beman-submodule update
48
+ ```
49
+
50
+ Update all beman submodules to the latest from upstream:
51
+
52
+ ```sh
53
+ beman-submodule update --remote
54
+ ```
55
+
56
+ Update only a specific submodule:
57
+
58
+ ```sh
59
+ beman-submodule update --remote infra/
60
+ ```
61
+
62
+ ### Checking status
63
+
64
+ Show the status of all beman submodules:
65
+
66
+ ```sh
67
+ beman-submodule status
68
+ ```
69
+
70
+ A `+` prefix indicates the submodule contents differ from the configured commit.
71
+
72
+ ## How does it work?
73
+
74
+ Along with the files from the child repository, it creates a dotfile called
75
+ `.beman_submodule`, which looks like this:
76
+
77
+ ```ini
78
+ [beman_submodule]
79
+ remote=https://github.com/bemanproject/infra.git
80
+ commit_hash=9b88395a86c4290794e503e94d8213b6c442ae77
81
+ ```
82
+
83
+ ### Updating to a specific commit or changing the remote URL
84
+
85
+ Edit the corresponding lines in the `.beman_submodule` file and run
86
+ `beman-submodule update` to update the state of the beman submodule to the new
87
+ settings.
88
+
89
+ ### Allow untracked files
90
+
91
+ If you need to add local files alongside the vendored content, use:
92
+
93
+ ```sh
94
+ beman-submodule add --allow-untracked-files https://github.com/example/repo.git path/
95
+ ```
96
+
97
+ This adds `allow_untracked_files=True` to the `.beman_submodule` config, preserving local
98
+ files during updates.
99
+
100
+ ## CI Integration
101
+
102
+ Add this job to your CI workflow to ensure beman submodules are in a valid state:
103
+
104
+ ```yaml
105
+ beman-submodule-test:
106
+ runs-on: ubuntu-latest
107
+ name: "Check beman submodules for consistency"
108
+ steps:
109
+ - name: Checkout
110
+ uses: actions/checkout@v4
111
+ - name: Install beman-submodule
112
+ run: pip install beman-submodule
113
+ - name: beman submodule consistency check
114
+ run: |
115
+ (set -o pipefail; beman-submodule status | grep -qvF '+')
116
+ ```
117
+
118
+ This will fail if the contents of any beman submodule don't match what's specified in the
119
+ `.beman_submodule` file.
120
+
121
+ ## Development
122
+
123
+ This project uses [uv](https://github.com/astral-sh/uv) for development:
124
+
125
+ ```sh
126
+ # Install dependencies
127
+ uv sync --group dev
128
+
129
+ # Run tests
130
+ uv run pytest
131
+
132
+ # Run linter
133
+ uv run ruff check .
134
+
135
+ # Format code
136
+ uv run ruff format .
137
+ ```
138
+
139
+ ## License
140
+
141
+ Apache-2.0 WITH LLVM-exception
@@ -0,0 +1,5 @@
1
+ # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
2
+
3
+ """A pseudo-submodule tool for vendoring Git repositories in Beman projects."""
4
+
5
+ __version__ = '0.1.0'
@@ -0,0 +1,82 @@
1
+ #!/usr/bin/env python3
2
+ # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3
+
4
+ import argparse
5
+ import sys
6
+
7
+ from beman_submodule.lib.core import (
8
+ add_command,
9
+ check_for_git,
10
+ status_command,
11
+ update_command,
12
+ )
13
+
14
+
15
+ def get_parser():
16
+ """Build and return the argument parser."""
17
+ parser = argparse.ArgumentParser(description='Beman pseudo-submodule tool')
18
+ subparsers = parser.add_subparsers(dest='command', help='available commands')
19
+
20
+ parser_update = subparsers.add_parser('update', help='update beman_submodules')
21
+ parser_update.add_argument(
22
+ '--remote',
23
+ action='store_true',
24
+ help='update a beman_submodule to its latest from upstream',
25
+ )
26
+ parser_update.add_argument(
27
+ 'beman_submodule_path',
28
+ nargs='?',
29
+ help='relative path to the beman_submodule to update',
30
+ )
31
+
32
+ parser_add = subparsers.add_parser('add', help='add a new beman_submodule')
33
+ parser_add.add_argument('repository', help='git repository to add')
34
+ parser_add.add_argument('path', nargs='?', help='path where the repository will be added')
35
+ parser_add.add_argument(
36
+ '--allow-untracked-files',
37
+ action='store_true',
38
+ help='the beman_submodule will not occupy the subdirectory exclusively',
39
+ )
40
+
41
+ parser_status = subparsers.add_parser('status', help='show the status of beman_submodules')
42
+ parser_status.add_argument('paths', nargs='*')
43
+
44
+ return parser
45
+
46
+
47
+ def parse_args(args):
48
+ """Parse command line arguments."""
49
+ return get_parser().parse_args(args)
50
+
51
+
52
+ def usage():
53
+ """Return the help text."""
54
+ return get_parser().format_help()
55
+
56
+
57
+ def run_command(args):
58
+ """Execute the appropriate command based on parsed arguments."""
59
+ if args.command == 'update':
60
+ update_command(args.remote, args.beman_submodule_path)
61
+ elif args.command == 'add':
62
+ add_command(args.repository, args.path, args.allow_untracked_files)
63
+ elif args.command == 'status':
64
+ status_command(args.paths)
65
+ else:
66
+ raise Exception(usage())
67
+
68
+
69
+ def main():
70
+ """Main entry point for the CLI."""
71
+ try:
72
+ if not check_for_git(None):
73
+ raise Exception('git not found in PATH')
74
+ args = parse_args(sys.argv[1:])
75
+ run_command(args)
76
+ except Exception as e:
77
+ print('Error:', e, file=sys.stderr)
78
+ sys.exit(1)
79
+
80
+
81
+ if __name__ == '__main__':
82
+ main()
@@ -0,0 +1 @@
1
+ # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
@@ -0,0 +1,261 @@
1
+ # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
2
+
3
+ import configparser
4
+ import filecmp
5
+ import glob
6
+ import os
7
+ import shutil
8
+ import subprocess
9
+ import tempfile
10
+ from pathlib import Path
11
+
12
+
13
+ def directory_compare(
14
+ reference: str | Path, actual: str | Path, ignore, allow_untracked_files: bool
15
+ ):
16
+ """Compare two directories recursively, optionally ignoring certain files."""
17
+ reference, actual = Path(reference), Path(actual)
18
+
19
+ compared = filecmp.dircmp(reference, actual, ignore=ignore)
20
+ if (
21
+ compared.left_only
22
+ or (compared.right_only and not allow_untracked_files)
23
+ or compared.diff_files
24
+ ):
25
+ return False
26
+ for common_dir in compared.common_dirs:
27
+ path1 = reference / common_dir
28
+ path2 = actual / common_dir
29
+ if not directory_compare(path1, path2, ignore, allow_untracked_files):
30
+ return False
31
+ return True
32
+
33
+
34
+ class BemanSubmodule:
35
+ """Represents a beman submodule configuration."""
36
+
37
+ def __init__(
38
+ self,
39
+ dirpath: str | Path,
40
+ remote: str,
41
+ commit_hash: str,
42
+ allow_untracked_files: bool,
43
+ ):
44
+ self.dirpath = Path(dirpath)
45
+ self.remote = remote
46
+ self.commit_hash = commit_hash
47
+ self.allow_untracked_files = allow_untracked_files
48
+
49
+
50
+ def parse_beman_submodule_file(path):
51
+ """Parse a .beman_submodule configuration file."""
52
+ config = configparser.ConfigParser()
53
+ read_result = config.read(path)
54
+
55
+ def fail():
56
+ raise Exception(f'Failed to parse {path} as a .beman_submodule file')
57
+
58
+ if not read_result:
59
+ fail()
60
+ if 'beman_submodule' not in config:
61
+ fail()
62
+ if 'remote' not in config['beman_submodule']:
63
+ fail()
64
+ if 'commit_hash' not in config['beman_submodule']:
65
+ fail()
66
+ allow_untracked_files = config.getboolean(
67
+ 'beman_submodule', 'allow_untracked_files', fallback=False
68
+ )
69
+ return BemanSubmodule(
70
+ Path(path).resolve().parent,
71
+ config['beman_submodule']['remote'],
72
+ config['beman_submodule']['commit_hash'],
73
+ allow_untracked_files,
74
+ )
75
+
76
+
77
+ def get_beman_submodule(path: str | Path):
78
+ """Get a BemanSubmodule from a directory path, or None if not found."""
79
+ beman_submodule_filepath = Path(path) / '.beman_submodule'
80
+
81
+ if beman_submodule_filepath.is_file():
82
+ return parse_beman_submodule_file(beman_submodule_filepath)
83
+ else:
84
+ return None
85
+
86
+
87
+ def find_beman_submodules_in(path):
88
+ """Find all beman submodules in a directory tree."""
89
+ path = Path(path)
90
+ assert path.is_dir()
91
+
92
+ result = []
93
+ for dirpath, _, filenames in path.walk():
94
+ if '.beman_submodule' in filenames:
95
+ result.append(parse_beman_submodule_file(dirpath / '.beman_submodule'))
96
+ return sorted(result, key=lambda module: module.dirpath)
97
+
98
+
99
+ def cwd_git_repository_path():
100
+ """Get the root path of the current git repository, or None if not in a repo."""
101
+ process = subprocess.run(
102
+ ['git', 'rev-parse', '--show-toplevel'],
103
+ capture_output=True,
104
+ text=True,
105
+ check=False,
106
+ )
107
+ if process.returncode == 0:
108
+ return process.stdout.strip()
109
+ elif 'fatal: not a git repository' in process.stderr:
110
+ return None
111
+ else:
112
+ raise Exception('git rev-parse --show-toplevel failed')
113
+
114
+
115
+ def clone_beman_submodule_into_tmpdir(beman_submodule, remote):
116
+ """Clone a beman submodule into a temporary directory."""
117
+ tmpdir = tempfile.TemporaryDirectory()
118
+ subprocess.run(
119
+ ['git', 'clone', beman_submodule.remote, tmpdir.name],
120
+ capture_output=True,
121
+ check=True,
122
+ )
123
+ if not remote:
124
+ subprocess.run(
125
+ ['git', '-C', tmpdir.name, 'reset', '--hard', beman_submodule.commit_hash],
126
+ capture_output=True,
127
+ check=True,
128
+ )
129
+ return tmpdir
130
+
131
+
132
+ def get_paths(beman_submodule):
133
+ """Get all paths in a beman submodule (excluding .git)."""
134
+ tmpdir = clone_beman_submodule_into_tmpdir(beman_submodule, False)
135
+ paths = set(glob.glob('*', root_dir=Path(tmpdir.name), include_hidden=True))
136
+ paths.remove('.git')
137
+ return paths
138
+
139
+
140
+ def beman_submodule_status(beman_submodule):
141
+ """Get the status string for a beman submodule."""
142
+ tmpdir = clone_beman_submodule_into_tmpdir(beman_submodule, False)
143
+ if directory_compare(
144
+ tmpdir.name,
145
+ beman_submodule.dirpath,
146
+ ['.beman_submodule', '.git'],
147
+ beman_submodule.allow_untracked_files,
148
+ ):
149
+ status_character = ' '
150
+ else:
151
+ status_character = '+'
152
+ parent_repo_path = cwd_git_repository_path()
153
+ if not parent_repo_path:
154
+ raise Exception('this is not a git repository')
155
+ relpath = Path(beman_submodule.dirpath).relative_to(Path(parent_repo_path))
156
+ return status_character + ' ' + beman_submodule.commit_hash + ' ' + str(relpath)
157
+
158
+
159
+ def beman_submodule_update(beman_submodule, remote):
160
+ """Update a beman submodule to match its configured state."""
161
+ tmpdir = clone_beman_submodule_into_tmpdir(beman_submodule, remote)
162
+ tmp_path = Path(tmpdir.name)
163
+ sha_process = subprocess.run(
164
+ ['git', 'rev-parse', 'HEAD'],
165
+ capture_output=True,
166
+ check=True,
167
+ text=True,
168
+ cwd=tmp_path,
169
+ )
170
+
171
+ if beman_submodule.allow_untracked_files:
172
+ for path in get_paths(beman_submodule):
173
+ path2 = Path(beman_submodule.dirpath) / path
174
+ if Path(path2).is_dir():
175
+ shutil.rmtree(path2)
176
+ elif Path(path2).is_file():
177
+ os.remove(path2)
178
+ else:
179
+ shutil.rmtree(beman_submodule.dirpath)
180
+
181
+ submodule_path = tmp_path / '.beman_submodule'
182
+ with open(submodule_path, 'w') as f:
183
+ f.write('[beman_submodule]\n')
184
+ f.write(f'remote={beman_submodule.remote}\n')
185
+ f.write(f'commit_hash={sha_process.stdout.strip()}\n')
186
+ if beman_submodule.allow_untracked_files:
187
+ f.write('allow_untracked_files=True\n')
188
+ shutil.rmtree(tmp_path / '.git')
189
+ shutil.copytree(tmp_path, beman_submodule.dirpath, dirs_exist_ok=True)
190
+
191
+
192
+ def update_command(remote, path):
193
+ """Execute the update command."""
194
+ if not path:
195
+ parent_repo_path = cwd_git_repository_path()
196
+ if not parent_repo_path:
197
+ raise Exception('this is not a git repository')
198
+ beman_submodules = find_beman_submodules_in(parent_repo_path)
199
+ else:
200
+ beman_submodule = get_beman_submodule(path)
201
+ if not beman_submodule:
202
+ raise Exception(f'{path} is not a beman_submodule')
203
+ beman_submodules = [beman_submodule]
204
+ for beman_submodule in beman_submodules:
205
+ beman_submodule_update(beman_submodule, remote)
206
+
207
+
208
+ def add_command(repository, path, allow_untracked_files):
209
+ """Execute the add command."""
210
+ tmpdir = tempfile.TemporaryDirectory()
211
+ subprocess.run(['git', 'clone', repository], capture_output=True, check=True, cwd=tmpdir.name)
212
+ repository_name = os.listdir(tmpdir.name)[0]
213
+ if not path:
214
+ path = Path(repository_name)
215
+ else:
216
+ path = Path(path)
217
+ if not allow_untracked_files and path.exists():
218
+ raise Exception(f'{path} exists')
219
+ path.mkdir(exist_ok=allow_untracked_files)
220
+ tmpdir_repo = Path(tmpdir.name) / repository_name
221
+ sha_process = subprocess.run(
222
+ ['git', 'rev-parse', 'HEAD'],
223
+ capture_output=True,
224
+ check=True,
225
+ text=True,
226
+ cwd=tmpdir_repo,
227
+ )
228
+ with open(tmpdir_repo / '.beman_submodule', 'w') as f:
229
+ f.write('[beman_submodule]\n')
230
+ f.write(f'remote={repository}\n')
231
+ f.write(f'commit_hash={sha_process.stdout.strip()}\n')
232
+ if allow_untracked_files:
233
+ f.write('allow_untracked_files=True\n')
234
+ shutil.rmtree(tmpdir_repo / '.git')
235
+ shutil.copytree(tmpdir_repo, path, dirs_exist_ok=True)
236
+
237
+
238
+ def status_command(paths):
239
+ """Execute the status command."""
240
+ if not paths:
241
+ parent_repo_path = cwd_git_repository_path()
242
+ if not parent_repo_path:
243
+ raise Exception('this is not a git repository')
244
+ beman_submodules = find_beman_submodules_in(parent_repo_path)
245
+ else:
246
+ beman_submodules = []
247
+ for path in paths:
248
+ beman_submodule = get_beman_submodule(path)
249
+ if not beman_submodule:
250
+ raise Exception(f'{path} is not a beman_submodule')
251
+ beman_submodules.append(beman_submodule)
252
+ for beman_submodule in beman_submodules:
253
+ print(beman_submodule_status(beman_submodule))
254
+
255
+
256
+ def check_for_git(path):
257
+ """Check if git is available in PATH."""
258
+ env = os.environ.copy()
259
+ if path is not None:
260
+ env['PATH'] = path
261
+ return shutil.which('git', path=env.get('PATH')) is not None
@@ -0,0 +1,54 @@
1
+ [project]
2
+ name = "beman-submodule"
3
+ version = "0.1.0"
4
+ description = "A pseudo-submodule tool for vendoring Git repositories in Beman projects"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ authors = [{ name = "The Beman Project", email = "eddiejnolan@gmail.com" }]
8
+ dependencies = []
9
+ keywords = [
10
+ "beman",
11
+ "bemanproject",
12
+ "git",
13
+ "submodule",
14
+ "vendoring",
15
+ "cli tool",
16
+ ]
17
+ classifiers = [
18
+ "Development Status :: 4 - Beta",
19
+ "Environment :: Console",
20
+ "License :: OSI Approved :: Apache Software License",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Programming Language :: Python :: 3.13",
24
+ "Intended Audience :: Developers",
25
+ "Topic :: Software Development :: Version Control :: Git",
26
+ ]
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/bemanproject/beman-submodule"
30
+ Repository = "https://github.com/bemanproject/beman-submodule"
31
+ Issues = "https://github.com/bemanproject/beman-submodule/issues"
32
+
33
+ [build-system]
34
+ requires = ["flit_core >=3.2,<4"]
35
+ build-backend = "flit_core.buildapi"
36
+
37
+ [dependency-groups]
38
+ dev = ["pytest>=8.4.0", "ruff>=0.11.13"]
39
+
40
+ [project.scripts]
41
+ beman-submodule = "beman_submodule.cli:main"
42
+
43
+ [tool.pytest.ini_options]
44
+ addopts = "-v"
45
+
46
+ [tool.ruff]
47
+ line-length = 100
48
+ target-version = "py312"
49
+
50
+ [tool.ruff.format]
51
+ quote-style = "single"
52
+
53
+ [tool.ruff.lint]
54
+ select = ["E", "F", "I", "W"]