@cldmv/git-embedded 1.0.0

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.
Files changed (48) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +145 -0
  3. package/bin/git-embedded.mjs +185 -0
  4. package/docs/design.md +122 -0
  5. package/docs/use-case-private-tests.md +97 -0
  6. package/hooks/_dispatch.template +67 -0
  7. package/hooks/reference-transaction +54 -0
  8. package/hooks/update-embedded-repos +56 -0
  9. package/messages/setup-bare-githooks.md +25 -0
  10. package/messages/setup-dispatcher-canonical-complete.md +30 -0
  11. package/messages/setup-dispatcher-missing-symlinks.md +56 -0
  12. package/messages/setup-dispatcher-non-conforming.md +35 -0
  13. package/messages/setup-husky.md +35 -0
  14. package/messages/setup-init-templatedir.md +21 -0
  15. package/messages/setup-lefthook.md +48 -0
  16. package/messages/setup-none.md +27 -0
  17. package/messages/setup-pre-commit.md +47 -0
  18. package/messages/setup-simple-git-hooks.md +40 -0
  19. package/messages/setup-system-hookspath.md +25 -0
  20. package/package.json +96 -0
  21. package/src/api/cli/doctor.mjs +15 -0
  22. package/src/api/cli/init.mjs +26 -0
  23. package/src/api/cli/install-hooks.mjs +124 -0
  24. package/src/api/cli/install-template.mjs +43 -0
  25. package/src/api/cli/link.mjs +42 -0
  26. package/src/api/cli/print-hook-script.mjs +35 -0
  27. package/src/api/cli/uninstall-hooks.mjs +21 -0
  28. package/src/api/cli/version.mjs +17 -0
  29. package/src/api/commander/custom-help.mjs +249 -0
  30. package/src/api/detect/dispatcher.mjs +218 -0
  31. package/src/api/detect/husky.mjs +23 -0
  32. package/src/api/detect/lefthook.mjs +37 -0
  33. package/src/api/detect/pre-commit.mjs +35 -0
  34. package/src/api/detect/run.mjs +71 -0
  35. package/src/api/detect/simple-git-hooks.mjs +26 -0
  36. package/src/api/git.mjs +59 -0
  37. package/src/api/install/dispatcher.mjs +51 -0
  38. package/src/api/install/hooks.mjs +80 -0
  39. package/src/api/install/template.mjs +15 -0
  40. package/src/api/link/batch.mjs +130 -0
  41. package/src/api/link/copy-executable.mjs +27 -0
  42. package/src/api/link/elevate-windows.mjs +52 -0
  43. package/src/api/log.mjs +38 -0
  44. package/src/api/messages/load.mjs +27 -0
  45. package/src/api/paths.mjs +43 -0
  46. package/src/api/prompt.mjs +26 -0
  47. package/src/api/report.mjs +83 -0
  48. package/src/lib/elevate-windows-child.mjs +43 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 CLDMV
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,145 @@
1
+ # @cldmv/git-embedded
2
+
3
+ [![npm version]][npm_version_url] [![npm downloads]][npm_downloads_url] [![Last commit]][last_commit_url] [![npm last update]][npm_last_update_url]
4
+
5
+ [![Contributors]][contributors_url] [![Sponsor shinrai]][sponsor_url]
6
+
7
+ Manage embedded git repositories (anonymous gitlinks) without `.gitmodules`. Provides hooks that restore standard git-command ergonomics for embedded child repos while keeping the child's origin URL out of the public parent repo.
8
+
9
+ ## What this is
10
+
11
+ Git uses **gitlinks** internally to track sub-repositories: a tree entry of mode `160000` pointing at a specific commit SHA in another repository. Submodules are built on top of gitlinks, with a registry file (`.gitmodules`) that records the child's URL alongside the gitlink. The URL is what makes `git clone --recurse-submodules`, `git submodule update`, and `submodule.recurse=true` checkout-flavored automation work — but it's also what publicly advertises the child repo's existence and location.
12
+
13
+ A gitlink without a `.gitmodules` entry is sometimes called an "anonymous submodule" or "embedded git repo." It's a fully supported git state: the gitlink still pins a specific child SHA, git still recognizes the child as a submodule boundary, and the parent commits a clean reference to the child's pinned version. What's missing is git's automatic update behavior, because the submodule machinery requires registration to act.
14
+
15
+ This package fills that gap with two git hooks:
16
+
17
+ - **`reference-transaction`** — blocks `git checkout`, `git switch`, `git reset`, `git pull`, `git merge`, `git rebase`, `git bisect`, and `git cherry-pick` when any embedded child repo has uncommitted changes. Prevents the silent inconsistent-state failure mode where the parent moves to a new commit but the child stays behind, dirty.
18
+ - **`update-embedded-repos`** — installed as `post-checkout`, `post-merge`, and `post-rewrite`. After a HEAD-moving operation, walks every gitlink in the new HEAD and updates the embedded child to its pinned SHA, using the child's own `origin` remote to fetch missing commits.
19
+
20
+ Together, the two hooks make embedded gitlinks behave like properly-registered submodules for the common workflow operations — without ever recording the child's URL in the public parent repo.
21
+
22
+ ## Why this matters
23
+
24
+ The motivating use case is OSS repositories that want comprehensive test coverage running in CI but cannot afford to publish the full test suite. Tests are a high-fidelity behavioral specification of the code under test; modern AI tooling makes clean-room reimplementation from tests fast and effective. Hiding the tests is the most direct mitigation. See [`docs/use-case-private-tests.md`](docs/use-case-private-tests.md) for the full motivation, threat model, and licensing strategy.
25
+
26
+ The mechanism is general, though. The hooks don't know or care that the embedded repo is a test suite — they work for any gitlink. Other plausible uses: private vendor directories, license-restricted dependencies, encrypted asset trees, internal tooling sub-repos.
27
+
28
+ ## Install
29
+
30
+ ```bash
31
+ npm install -g @cldmv/git-embedded
32
+ ```
33
+
34
+ That places a `git-embedded` executable in npm's global `bin` directory, which makes git's subcommand discovery surface it as `git embedded …`.
35
+
36
+ ## Usage
37
+
38
+ Run inside the parent repo (the one that holds the embedded gitlinks):
39
+
40
+ ```bash
41
+ git embedded doctor # inspect environment; takes no action
42
+ git embedded install-hooks # install hooks into this repo's .git/hooks
43
+ git embedded uninstall-hooks # remove hooks installed by this CLI
44
+ ```
45
+
46
+ `install-hooks` adapts to whatever's already in place:
47
+
48
+ - **Nothing configured** — offers to install a small dispatcher script at `~/.config/git/hooks/_dispatch`, link every standard hook name to it, and set `git config --global core.hooksPath` to that directory. Then drops this package's hook scripts into the repo's `.git/hooks/`. The dispatcher chains to per-repo hooks, so every other repo on the machine keeps working as before.
49
+ - **Canonical dispatcher already present** — installs only the per-repo hook scripts; the existing dispatcher activates them.
50
+ - **Dispatcher present but missing required entries** — offers to add the missing symlinks (with explicit confirmation), then installs per-repo hooks.
51
+ - **Foreign hook manager detected** (Husky, lefthook, simple-git-hooks, pre-commit) — refuses to install and prints instructions for hand-integrating, since clobbering those tools' generated files would be reverted on their next run.
52
+ - **Non-conforming dispatcher / bare `.githooks/`** — refuses and prints integration options; the CLI never rewrites someone else's dispatcher.
53
+
54
+ ### Flags
55
+
56
+ ```text
57
+ --no-symlinks use hard links instead of symbolic links
58
+ (avoids the Windows UAC prompt; same-volume only)
59
+ --yes skip confirmation prompts
60
+ --dispatcher-dir <path> override the default ~/.config/git/hooks
61
+ ```
62
+
63
+ ### Other subcommands
64
+
65
+ ```bash
66
+ git embedded install-template # install hooks into git config init.templateDir/hooks
67
+ # so new repos start with them already wired
68
+ git embedded print-hook-script <name>
69
+ # emit a packaged hook script to stdout
70
+ # (post-checkout / post-merge / post-rewrite /
71
+ # reference-transaction / update-embedded-repos / _dispatch)
72
+ ```
73
+
74
+ ## Quick start: embed a child repo
75
+
76
+ After the hooks are installed:
77
+
78
+ ```bash
79
+ git clone <private-child-url> embedded-child
80
+ git add embedded-child
81
+ git commit -m "embed child"
82
+
83
+ # silence the harmless 'embedded git repository' warning if desired
84
+ git config advice.addEmbeddedRepo false
85
+ ```
86
+
87
+ The committed parent tree now contains a gitlink at `embedded-child` pinning the child's current HEAD. No `.gitmodules` is created; the child's URL never lands in the public repo.
88
+
89
+ ## Manual install (no CLI)
90
+
91
+ If you'd rather wire things up by hand:
92
+
93
+ ```bash
94
+ mkdir -p .githooks
95
+ cp /path/to/git-embedded/hooks/reference-transaction .githooks/
96
+ cp /path/to/git-embedded/hooks/update-embedded-repos .githooks/
97
+ chmod +x .githooks/*
98
+
99
+ ln -sf update-embedded-repos .githooks/post-checkout
100
+ ln -sf update-embedded-repos .githooks/post-merge
101
+ ln -sf update-embedded-repos .githooks/post-rewrite
102
+
103
+ git config core.hooksPath .githooks
104
+ ```
105
+
106
+ ## Documentation
107
+
108
+ - [`docs/design.md`](docs/design.md) — how the hooks work, coverage matrix, limitations, comparison to standard submodules.
109
+ - [`docs/use-case-private-tests.md`](docs/use-case-private-tests.md) — the OSS-tests-in-private-repo motivation, threat model, licensing strategy, why anonymous gitlinks rather than alternatives.
110
+
111
+ ## Compatibility
112
+
113
+ - **Git 2.28 or newer** for the `reference-transaction` hook (released July 2020). The `update-embedded-repos` hook works on older git but loses its guard.
114
+ - **Node 20.19+** for the CLI. The hooks themselves are shell scripts with no Node dependency at hook execution time.
115
+ - **Linux / macOS / Windows.** On Windows, symlink creation needs admin elevation (a one-shot UAC prompt the CLI requests). Pass `--no-symlinks` to use hard links instead and skip the prompt.
116
+
117
+ ## Links
118
+
119
+ - **npm**: [@cldmv/git-embedded](https://www.npmjs.com/package/@cldmv/git-embedded)
120
+ - **GitHub**: [CLDMV/git-embedded](https://github.com/CLDMV/git-embedded)
121
+ - **Issues**: [GitHub Issues](https://github.com/CLDMV/git-embedded/issues)
122
+ - **Releases**: [GitHub Releases](https://github.com/CLDMV/git-embedded/releases)
123
+
124
+ ## License
125
+
126
+ [![GitHub license]][github_license_url] [![npm license]][npm_license_url]
127
+
128
+ Apache-2.0 © Shinrai / CLDMV. See [LICENSE](LICENSE).
129
+
130
+ [npm version]: https://img.shields.io/npm/v/%40cldmv%2Fgit-embedded.svg?style=for-the-badge&logo=npm&logoColor=white&labelColor=CB3837
131
+ [npm_version_url]: https://www.npmjs.com/package/@cldmv/git-embedded
132
+ [npm downloads]: https://img.shields.io/npm/dm/%40cldmv%2Fgit-embedded.svg?style=for-the-badge&logo=npm&logoColor=white&labelColor=CB3837
133
+ [npm_downloads_url]: https://www.npmjs.com/package/@cldmv/git-embedded
134
+ [npm last update]: https://img.shields.io/npm/last-update/%40cldmv%2Fgit-embedded?style=for-the-badge&logo=npm&logoColor=white&labelColor=CB3837
135
+ [npm_last_update_url]: https://www.npmjs.com/package/@cldmv/git-embedded
136
+ [last commit]: https://img.shields.io/github/last-commit/CLDMV/git-embedded?style=for-the-badge&logo=github&logoColor=white&labelColor=181717
137
+ [last_commit_url]: https://github.com/CLDMV/git-embedded/commits
138
+ [contributors]: https://img.shields.io/github/contributors/CLDMV/git-embedded.svg?style=for-the-badge&logo=github&logoColor=white&labelColor=181717
139
+ [contributors_url]: https://github.com/CLDMV/git-embedded/graphs/contributors
140
+ [sponsor shinrai]: https://img.shields.io/github/sponsors/shinrai?style=for-the-badge&logo=githubsponsors&logoColor=white&labelColor=EA4AAA&label=Sponsor
141
+ [sponsor_url]: https://github.com/sponsors/shinrai
142
+ [github license]: https://img.shields.io/github/license/CLDMV/git-embedded.svg?style=for-the-badge&logo=github&logoColor=white&labelColor=181717
143
+ [github_license_url]: https://github.com/CLDMV/git-embedded/blob/HEAD/LICENSE
144
+ [npm license]: https://img.shields.io/npm/l/%40cldmv%2Fgit-embedded.svg?style=for-the-badge&logo=npm&logoColor=white&labelColor=CB3837
145
+ [npm_license_url]: https://www.npmjs.com/package/@cldmv/git-embedded
@@ -0,0 +1,185 @@
1
+ #!/usr/bin/env node
2
+
3
+ import slothlet from "@cldmv/slothlet";
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import os from "node:os";
7
+ import * as readline from "node:readline";
8
+ import { spawn, spawnSync } from "node:child_process";
9
+ import { fileURLToPath, pathToFileURL } from "node:url";
10
+ import chalk from "chalk";
11
+ import { Command, Help } from "commander";
12
+ import { wisp, wispSync } from "@cldmv/wisp";
13
+ import { marked } from "marked";
14
+ import { markedTerminal } from "marked-terminal";
15
+
16
+ // `showSectionPrefix: false` strips `##` from headers; marked-terminal hard-codes
17
+ // `* ` as the bullet point, so swap it back to `-` to match the source markdown.
18
+ marked.use(markedTerminal({ showSectionPrefix: false }));
19
+ const renderMarkdown = (md) => marked.parse(md).replace(/^(\s*)\* /gm, "$1- ");
20
+
21
+ if (typeof Command.prototype.examples !== "function") {
22
+ Command.prototype.examples = function (arr) {
23
+ if (arguments.length === 0) return this._exampleList || [];
24
+ this._exampleList = Array.isArray(arr) ? arr : [];
25
+ return this;
26
+ };
27
+ }
28
+
29
+ const here = path.dirname(fileURLToPath(import.meta.url));
30
+ const packageRoot = path.resolve(here, "..");
31
+ const apiDir = path.join(packageRoot, "src", "api");
32
+
33
+ const api = await slothlet({
34
+ dir: apiDir,
35
+ context: {
36
+ fs,
37
+ path,
38
+ os,
39
+ chalk,
40
+ readline,
41
+ spawn,
42
+ spawnSync,
43
+ fileURLToPath,
44
+ pathToFileURL,
45
+ commander: { Command, Help },
46
+ wisp,
47
+ wispSync,
48
+ renderMarkdown,
49
+ packageRoot
50
+ }
51
+ });
52
+
53
+ const { CustomHelp, applyCustomHelpRecursive } = api.commander.customHelp.makeCustomHelp(Help, { chalk });
54
+
55
+ const program = new Command();
56
+ program.createHelp = () => new CustomHelp();
57
+ program
58
+ .name("git-embedded")
59
+ .description(
60
+ "Manage embedded git repositories (anonymous gitlinks). Installs hooks that keep embedded children in sync without writing a .gitmodules entry."
61
+ )
62
+ .configureOutput({ writeErr: () => {} })
63
+ .exitOverride();
64
+
65
+ registerCommandsFromApi(api, program);
66
+
67
+ program
68
+ .command("help [cmd...]")
69
+ .description("Show help for a command")
70
+ .action((cmds) => {
71
+ if (cmds && cmds.length) {
72
+ let sub = program;
73
+ for (const c of cmds) sub = sub.commands.find((x) => x.name() === c) || sub;
74
+ sub.help();
75
+ } else {
76
+ program.help();
77
+ }
78
+ });
79
+
80
+ program.action(() => {
81
+ program.outputHelp();
82
+ process.exit(0);
83
+ });
84
+
85
+ applyCustomHelpRecursive(program);
86
+
87
+ process.on("uncaughtException", (error) => {
88
+ console.error(chalk.red(`✗ unexpected error: ${error && error.message ? error.message : error}`));
89
+ if (process.env.DEBUG) console.error(error);
90
+ process.exit(1);
91
+ });
92
+
93
+ try {
94
+ await program.parseAsync(process.argv);
95
+ } catch (err) {
96
+ if (err && (err.code === "commander.helpDisplayed" || err.code === "commander.help" || err.code === "commander.version")) {
97
+ process.exit(0);
98
+ }
99
+ if (err && typeof err.code === "string" && err.code.startsWith("commander.")) {
100
+ let helpShown = false;
101
+ if (err.command && typeof err.command.outputHelp === "function") {
102
+ err.command.outputHelp();
103
+ helpShown = true;
104
+ } else if (process.argv[2]) {
105
+ const sub = program.commands.find((cmd) => {
106
+ if (cmd.name() === process.argv[2]) return true;
107
+ const aliases = typeof cmd.aliases === "function" ? cmd.aliases() : cmd._aliases;
108
+ return Array.isArray(aliases) && aliases.includes(process.argv[2]);
109
+ });
110
+ if (sub && typeof sub.outputHelp === "function") {
111
+ sub.outputHelp();
112
+ helpShown = true;
113
+ }
114
+ }
115
+ if (!helpShown) program.outputHelp();
116
+ console.error(chalk.red(`\n${(err.message || "").trim()}`));
117
+ process.exit(typeof err.exitCode === "number" ? err.exitCode : 1);
118
+ }
119
+ throw err;
120
+ }
121
+
122
+ /**
123
+ * Build commander subcommands from every leaf under `api.cli.*` that exposes
124
+ * `{ spec, run }`. Third-party plugins can extend the CLI surface at runtime
125
+ * via `api.slothlet.api.add("cli.myCommand", "/abs/path/to/leaf-folder")`
126
+ * before this is called.
127
+ */
128
+ function registerCommandsFromApi(rootApi, programInstance) {
129
+ const cli = rootApi && rootApi.cli;
130
+ if (!cli) return;
131
+ for (const key of Object.keys(cli)) {
132
+ const leaf = cli[key];
133
+ if (!leaf || typeof leaf !== "object") continue;
134
+ const spec = leaf.spec;
135
+ const run = leaf.run;
136
+ if (!spec || typeof run !== "function") continue;
137
+ registerCommand(programInstance, spec, run);
138
+ }
139
+ }
140
+
141
+ function registerCommand(programInstance, spec, run) {
142
+ const commandName = spec.command;
143
+ if (!commandName) return;
144
+ const cmd = programInstance.command(commandName);
145
+ const aliases = Array.isArray(spec.aliases) ? spec.aliases : asArray(spec.aliases);
146
+ if (aliases.length) cmd.aliases(aliases);
147
+ if (spec.description) cmd.description(spec.description);
148
+ const args = asArray(spec.args);
149
+ for (const rawEntry of args) {
150
+ const entry = asArray(rawEntry);
151
+ const [a, desc] = entry;
152
+ if (a) cmd.argument(a, desc || "");
153
+ }
154
+ const options = asArray(spec.options);
155
+ for (const rawEntry of options) {
156
+ const entry = asArray(rawEntry);
157
+ const [flags, desc] = entry;
158
+ if (flags) cmd.option(flags, desc || "");
159
+ }
160
+ const examples = Array.isArray(spec.examples) ? spec.examples : asArray(spec.examples);
161
+ if (examples.length) cmd.examples(examples);
162
+ cmd.action(async (...actionArgs) => {
163
+ const last = actionArgs[actionArgs.length - 1];
164
+ const isCmd = last && typeof last === "object" && typeof last.opts === "function";
165
+ const trimmed = isCmd ? actionArgs.slice(0, -1) : actionArgs;
166
+ await run(...trimmed);
167
+ });
168
+ }
169
+
170
+ /**
171
+ * Slothlet wraps spec arrays as Function-shaped proxies — `.length` returns
172
+ * `Function.prototype.length` (0), but numeric-keyed elements are intact. Walk
173
+ * indices until one is missing.
174
+ */
175
+ function asArray(maybe) {
176
+ if (Array.isArray(maybe)) return maybe;
177
+ if (maybe == null || typeof maybe !== "object") return [];
178
+ const out = [];
179
+ let i = 0;
180
+ while (i in maybe) {
181
+ out.push(maybe[i]);
182
+ i++;
183
+ }
184
+ return out;
185
+ }
package/docs/design.md ADDED
@@ -0,0 +1,122 @@
1
+ # Design: hooks for embedded git repositories
2
+
3
+ This document describes the hook system that `@cldmv/git-embedded` installs and the design choices behind it. It is intended for anyone evaluating the approach, debugging an installed hook, or working on the planned CLI.
4
+
5
+ ## Background: gitlinks, submodules, and the registration gap
6
+
7
+ Git internally tracks embedded sub-repositories as **gitlinks**: a tree entry with mode `160000` whose "value" is a 40-character commit SHA. The gitlink is the actual pinning machinery — it records "this directory should be at commit X" in the parent's history.
8
+
9
+ Submodules are layered on top of gitlinks. A submodule is a gitlink **plus** a registry entry that declares the submodule's URL and (optionally) other configuration. The registry lives in two places:
10
+
11
+ - `.gitmodules` — a tracked file at the parent repo root. The committed source of truth. Contains `[submodule "name"] path = ..., url = ...` blocks.
12
+ - `.git/config` — the local-only runtime view, populated from `.gitmodules` by `git submodule init`.
13
+
14
+ Git's high-level submodule commands (`git submodule update`, `submodule.recurse=true` behavior in `checkout`/`switch`/`pull`/`bisect`, `git clone --recurse-submodules`) require an entry in the registry to operate. They do not infer submodules from the mere presence of a gitlink and an embedded `.git/` directory, even though the information needed to do so is locally available.
15
+
16
+ This produces what this package calls the **registration gap**: a gitlink that has no registry entry is fully tracked at the tree level (the SHA pin travels with commits, `git status` still flags divergence between the tree and the working state, `git add` infers the new SHA from the child's HEAD), but the working-tree-update automation is silent. Standard `git checkout` moves the parent forward; the embedded child stays at whatever SHA it was at before the operation.
17
+
18
+ The hooks in this package close the registration gap without requiring a registry entry. They use the gitlink SHA from the parent's tree directly (via `git ls-tree`) and the child's own `origin` remote configuration (which the child has if it was cloned normally) to do the same work `git submodule update` would do.
19
+
20
+ ## Why this matters: the URL is the leak
21
+
22
+ For most submodule use cases, the URL in `.gitmodules` is uncontroversial — the parent is open and the child is open, the URL is just a convenience for `clone --recurse-submodules`. For a parent that wants to hide the *existence* of a private child repo, the `.gitmodules` URL is the leak. Anyone who can read the public parent can read `.gitmodules`, see the URL of the private child, and at minimum learn that a private resource exists at that location.
23
+
24
+ Avoiding `.gitmodules` is the obvious fix, but doing so loses the working-tree automation. This package restores the automation while keeping the parent free of URL data.
25
+
26
+ ## The two hooks
27
+
28
+ ### `reference-transaction` (guard)
29
+
30
+ **Purpose.** Refuse to apply HEAD-moving ref updates when any embedded child repo has uncommitted changes. Without this guard, a `git checkout B` in the parent silently leaves a dirty child stranded at the previous pin, producing an inconsistent state that is easy to miss.
31
+
32
+ **Mechanism.** `reference-transaction` is a git hook introduced in git 2.28 (July 2020). It fires for any ref-update transaction with one of three phase arguments:
33
+
34
+ - `prepared` — updates queued, not yet applied. Exiting non-zero ABORTS the transaction.
35
+ - `committed` — updates already applied.
36
+ - `aborted` — informational.
37
+
38
+ The hook script acts only on the `prepared` phase, where rejection is possible. It reads the proposed ref updates from stdin (one `old_sha new_sha ref` per line), filters to lines where `ref` is `HEAD` and `old_sha != new_sha` (an actual HEAD move), and walks every gitlink in the current tree checking for uncommitted changes via `git diff-index --quiet HEAD --` inside each child. If any child is dirty, the hook prints a message to stderr and exits non-zero, which aborts the parent operation.
39
+
40
+ **What it catches.** Every git command that ultimately moves HEAD goes through a reference transaction. That includes `git checkout <ref>`, `git switch <branch>`, `git reset` (any mode that moves HEAD), `git pull` (both fast-forward and rebase variants), `git merge`, `git rebase` (each step), `git bisect` (each step), `git cherry-pick`, and others.
41
+
42
+ **What it does not catch.** Operations that don't move HEAD aren't guarded, by design: `git commit` (creates a new commit but doesn't update the gitlink without explicit staging), `git checkout -- file` (file-level checkout), `git stash` itself (records stash refs, not HEAD), and so on. These don't require child-update behavior.
43
+
44
+ **Caveat about error messaging.** When the hook exits non-zero, git wraps its own message around the script's stderr output. The user sees a message like:
45
+
46
+ ```text
47
+ git-embedded: ✗ embedded-child has uncommitted changes
48
+ commit or stash inside embedded-child/ before moving HEAD here
49
+ fatal: reference transaction hook declined
50
+ ```
51
+
52
+ The `fatal: reference transaction hook declined` line is from git, not the hook. The script's two lines above it are what the user actually needs. Hook output should remain short and unambiguous because it appears alongside git's wrapping.
53
+
54
+ ### `update-embedded-repos` (auto-update)
55
+
56
+ **Purpose.** After a successful HEAD-moving operation in the parent, walk every gitlink in the new HEAD and update the corresponding embedded child to its pinned SHA. This is the post-condition that `git submodule update` provides for registered submodules; the hook provides the equivalent for unregistered gitlinks.
57
+
58
+ **Mechanism.** A single script installed under three hook names: `post-checkout`, `post-merge`, and `post-rewrite`. Each of these fires after a different family of operations:
59
+
60
+ - `post-checkout` — `git checkout`, `git switch`, `git clone` (for the initial checkout), and each step of `git bisect`. Also fires when `git pull` does a fast-forward checkout-style update.
61
+ - `post-merge` — successful `git merge` and the merge phase of `git pull`.
62
+ - `post-rewrite` — `git rebase`, `git commit --amend`, and any command that rewrites commits.
63
+
64
+ For each gitlink path, the script:
65
+
66
+ 1. Reads the pinned SHA from `git ls-tree -r HEAD`.
67
+ 2. Confirms a working git repo exists at the path (`tests/.git` is a directory or file).
68
+ 3. Compares the pinned SHA to the child's current HEAD; skips if already in sync.
69
+ 4. If the pinned SHA is not in the child's local object store, runs `git fetch` inside the child (using the child's own remote config — `.gitmodules` is not consulted).
70
+ 5. Runs `git checkout --detach <sha>` inside the child.
71
+
72
+ The detached-HEAD checkout matches standard submodule behavior: parents pin specific commits, not branches, so the child ends up in detached-HEAD state after each parent operation. If the child needs to be on a branch for editing, the developer attaches to one (`git -C embedded-child switch -c work` or `git -C embedded-child checkout main`) after the operation completes.
73
+
74
+ **What it catches.** Together, the three hook names cover essentially every checkout-flavored parent operation. See the coverage matrix below.
75
+
76
+ **What it does not catch.** Two notable gaps:
77
+
78
+ - `git reset --hard <commit>` updates the index and working tree but does **not** fire `post-checkout`, `post-merge`, or `post-rewrite`. The `reference-transaction` guard catches this case at the prepared phase (because `reset` does move HEAD via a ref transaction), so a `--hard` reset with a dirty child is refused — but a `--hard` reset with a clean child completes without the children being auto-updated. The mitigation is to either accept the gap, manually re-run the script, or use a `git-foo` wrapper command.
79
+ - `git stash pop` modifies the working tree without moving HEAD. It does not affect embedded children (stash entries are recorded in the parent's stash ref, not in the children), but anyone expecting "all working-tree-modifying commands are guarded" will not see consistency here.
80
+
81
+ ## Coverage matrix
82
+
83
+ | Operation | `reference-transaction` (guard) | `update-embedded-repos` (update) |
84
+ |---|---|---|
85
+ | `git checkout <ref>` | Refuses if any child is dirty | Updates children to new pins |
86
+ | `git switch <branch>` | Refuses if any child is dirty | Updates children to new pins |
87
+ | `git reset --hard <commit>` | Refuses if any child is dirty | **Gap** — does not fire `post-*` hooks |
88
+ | `git reset --soft/--mixed <commit>` | Refuses if any child is dirty (HEAD moves) | Does not fire `post-*` hooks (HEAD-only change) |
89
+ | `git pull` (fast-forward) | Refuses if any child is dirty | Updates children |
90
+ | `git pull --rebase` | Refuses at each rebase step | Updates children after rebase completes |
91
+ | `git merge <commit>` | Refuses if any child is dirty | Updates children via `post-merge` |
92
+ | `git rebase` | Refuses at each step | Updates children via `post-rewrite` |
93
+ | `git bisect <good/bad/run>` | Refuses if any child is dirty | Updates children at each bisect step |
94
+ | `git cherry-pick` | Refuses if any child is dirty | Updates children via `post-checkout` |
95
+ | `git stash pop` | Not guarded (no HEAD move) | Not updated (no HEAD move; not needed) |
96
+ | `git commit` | Not guarded (no HEAD move) | Not updated (no HEAD move; not needed) |
97
+ | `git checkout -- file` | Not guarded (no HEAD move) | Not updated (no HEAD move; not needed) |
98
+
99
+ ## Comparison to standard submodules
100
+
101
+ | Property | Standard submodule | Anonymous gitlink + these hooks |
102
+ |---|---|---|
103
+ | Child URL in parent | Yes, in `.gitmodules` | No |
104
+ | Tree-level pin | Gitlink | Gitlink |
105
+ | Public viewer sees | URL, path, current SHA | Just the SHA (no link to follow) |
106
+ | `git submodule update` | Works | Not used (registry-bound; hooks replace it) |
107
+ | `submodule.recurse=true` | Works | Not used (registry-bound; hooks replace it) |
108
+ | `git status` divergence | Yes | Yes |
109
+ | `git add path` infers SHA | Yes | Yes |
110
+ | `--recurse-submodules` clone | Pulls child | No-op (no registry) |
111
+ | Initial child clone | Automatic via registry | Manual or via the planned CLI |
112
+ | Dirty-child guard | Default refuses on update | Hook refuses on the HEAD move itself |
113
+
114
+ The most useful difference is the **guard timing**. Standard submodules let the parent operation proceed and then refuse the child update, leaving the developer in a parent-moved-child-stale state that has to be backed out. The `reference-transaction` guard refuses the whole transaction at the parent level, so the working tree never reaches the inconsistent state.
115
+
116
+ ## Implementation notes
117
+
118
+ - The hooks are POSIX-shell scripts to avoid Node or other runtime dependencies at hook execution time. They use `git ls-tree`, `git diff-index`, `git rev-parse`, `git cat-file`, `git fetch`, and `git checkout` — all standard plumbing.
119
+ - All hook scripts are idempotent. Running them twice in a row is harmless: the second invocation detects the children are already at the pinned SHAs and is a no-op.
120
+ - The `update-embedded-repos` script always exits 0. A failure to update a child writes to stderr but does not signal failure to git, because the parent operation has already completed and signalling failure here would not undo it. The `reference-transaction` guard is what prevents getting into this state.
121
+ - The hooks operate on `HEAD`'s tree, not the index. This is correct after a checkout (HEAD has been updated), correct after a merge (HEAD is the merge commit), and correct after a rewrite (HEAD is the new commit). Reading the index instead would be wrong in some merge cases.
122
+ - Embedded children are detected by the presence of `<path>/.git` (a directory for normal clones, a file for worktrees or for child submodules that have been moved into the gitdir). The check `[ -d "$path/.git" ] || [ -f "$path/.git" ]` covers both.