@bstopp/git-who 0.0.0-stage → 0.2.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.
package/LICENSE ADDED
@@ -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.
package/README.md CHANGED
@@ -1,3 +1,239 @@
1
- # Temporary Holding Version
1
+ # git-who
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Manage git profiles for per-project SSH account configuration.
4
+
5
+ If you use more than one git account (work, personal, a client), `git who` keeps each one as a named **profile** and
6
+ applies it to a repo in one step: the SSH host, `user.name`, `user.email`, and commit signing. No more commits under the
7
+ wrong email.
8
+
9
+ ```
10
+ $ git who use work
11
+ Now using profile 'work'.
12
+ ```
13
+
14
+ ## Requirements
15
+
16
+ - **macOS or Linux.** Windows works through WSL. Native Windows is untested.
17
+ - **Node.js 24 or later**
18
+ - **git**
19
+ - **ssh**: required. Profiles point at host aliases from your `~/.ssh/config`, and `git who` resolves them with `ssh -G`.
20
+ - **gpg**: optional. Only needed if a profile signs commits with GPG.
21
+
22
+ ## Installation
23
+
24
+ ```
25
+ npm install --global @bstopp/git-who
26
+ ```
27
+
28
+ This puts a `git-who` executable on your `PATH`. Git runs any `git-<name>` executable on your `PATH` as `git <name>`,
29
+ so the tool is then available as `git who`.
30
+
31
+ ## Quick start
32
+
33
+ 1. Make sure each account has a host alias in `~/.ssh/config`:
34
+
35
+ ```
36
+ Host github-work
37
+ HostName github.com
38
+ User git
39
+ IdentityFile ~/.ssh/id_work
40
+
41
+ Host github-personal
42
+ HostName github.com
43
+ User git
44
+ IdentityFile ~/.ssh/id_personal
45
+ ```
46
+
47
+ 2. Create a profile for each account. You are prompted for everything:
48
+
49
+ ```
50
+ git who add
51
+ ```
52
+
53
+ 3. Use a profile in a repo, or clone with one:
54
+
55
+ ```
56
+ cd ~/code/some-work-repo
57
+ git who use work
58
+
59
+ git who clone my-org/my-repo work
60
+ ```
61
+
62
+ ## Commands
63
+
64
+ Any command that takes `[name]` prompts you to pick a profile when the name is left out. If the name you give doesn't
65
+ exist, you get a warning and the same prompt.
66
+
67
+ | Command | What it does |
68
+ | --- | --- |
69
+ | `git who add` | Create a profile interactively. Shows it for review and asks before saving. |
70
+ | `git who list` | List all profiles with their SSH hosts. The profile active in the current repo is in bold. |
71
+ | `git who show [name]` | Show a profile. With no name, show the profile for the current repo. |
72
+ | `git who use [name]` | Apply a profile to the current repo. |
73
+ | `git who clone <repo> [name]` | Clone a repo using a profile, then apply the profile to the clone. |
74
+ | `git who edit [name]` | Edit a profile. The prompts are pre-filled with the current values. |
75
+ | `git who remove [name]` | Remove a profile, after confirmation. |
76
+
77
+ Run `git who --help` for usage and `git who --version` for the version.
78
+
79
+ ### `add`
80
+
81
+ Prompts for, in order:
82
+
83
+ 1. **Profile name**: letters, numbers, dash, dot, or underscore. Must be unique.
84
+ 2. **SSH host**: chosen from the aliases in your `~/.ssh/config`.
85
+ 3. **Sign commits?**: SSH, GPG, or no.
86
+ - **SSH**: pick one of the public keys (`*.pub`) in `~/.ssh`.
87
+ - **GPG**: pick a secret key, and then an identity on that key. If the key has only one identity it is used
88
+ directly. The identity's name and email become the defaults for the next two prompts.
89
+ 4. **Git `user.name`** and **`user.email`**.
90
+
91
+ ### `use`
92
+
93
+ Applies a profile to the current repo by writing to its **local** git config:
94
+
95
+ | Config key | Value |
96
+ | --- | --- |
97
+ | `gitwho.profile` | The profile name. This is how `git who` knows which profile a repo uses. |
98
+ | `user.name`, `user.email` | From the profile. |
99
+ | `user.signingKey`, `commit.gpgsign` | Set when the profile signs commits, otherwise removed. |
100
+ | `gpg.format` | `ssh` for SSH signing, removed otherwise. |
101
+
102
+ Notes:
103
+
104
+ - It must be run inside a git repo.
105
+ - If the repo's `origin` doesn't use the profile's SSH host, you are asked whether to rewrite it to
106
+ `git@<host>:<org>/<repo>`. This works whether the current origin is an SSH or an `http(s)` URL. If there is no origin,
107
+ nothing is changed.
108
+ - The profile's signing key is checked first. If it can't be found, or can't be looked up (for example, `gpg` isn't
109
+ installed), the command fails **before** anything is written.
110
+ - Any failure while writing the config may leave it partly updated. Run the command again to retry.
111
+
112
+ ### `clone`
113
+
114
+ ```
115
+ git who clone <repo> [name]
116
+ ```
117
+
118
+ `<repo>` can be:
119
+
120
+ - an `org/repo` shorthand, for example `my-org/my-repo`
121
+ - an SSH URL: `git@host:org/repo.git` or `ssh://git@host/org/repo.git`
122
+
123
+ Whatever host the URL has is **replaced with the profile's host**, so a URL copied from GitHub works with any profile.
124
+ `http(s)` URLs are not supported. The repo is cloned into a directory named after it, in the current directory, and the
125
+ profile is applied to the clone.
126
+
127
+ The profile's signing key is checked **before** cloning, so a missing key fails without cloning anything. If the clone
128
+ succeeds but writing the profile to its git config then fails, the repo is left cloned. The error tells you to run
129
+ `git who use <name>` inside it.
130
+
131
+ ### `show`
132
+
133
+ ```
134
+ $ git who show work
135
+ Profile: work
136
+ Host: github-work
137
+ Name: Bryan Work
138
+ Email: bryan@work.com
139
+ Sign Commits: Using ssh
140
+ Signing Key: /Users/bryan/.ssh/id_work.pub
141
+ ```
142
+
143
+ With a name, it shows that profile. With no name, it works out the profile for the current repo:
144
+
145
+ 1. The profile named by the repo's `gitwho.profile`.
146
+ 2. Otherwise, the single profile whose `user.name` and `user.email` match the repo's git config. This is flagged as *derived*, with a
147
+ warning that it isn't explicitly set via `gitwho.profile`. Run `git who use` to set it.
148
+
149
+ When showing the current repo's profile, any value in the repo's git config that differs from the profile is marked with
150
+ `*` and listed in a warning, so you can see that a repo has drifted. A signing key that can't be found is marked
151
+ `(not found)`.
152
+
153
+ ### `edit`
154
+
155
+ Pre-fills every prompt with the profile's current values. If you change nothing, you are offered another pass. Otherwise
156
+ the changes are shown next to the original values (`(was: …)`) and you confirm before saving.
157
+
158
+ Editing a profile does **not** update the repos that already use it. Their git config keeps the old values, and `show`
159
+ marks the differences. Run `git who use` in a repo to refresh it.
160
+
161
+ > **Renaming a profile:** the name is what links a repo to its profile. After a rename, repos still using the old name
162
+ > need `git who use <new-name>` to pick up the new one. `edit` reminds you when you rename a profile.
163
+
164
+ ### `remove`
165
+
166
+ Shows the profile and asks for confirmation. If the profile is the active one in the current repo, you are asked a second
167
+ time and its `gitwho.profile` is cleared from that repo afterwards. Other repos that still name the removed profile are
168
+ not touched.
169
+
170
+ ## Where profiles are stored
171
+
172
+ Profiles live in `~/.git-who.cfg.json`, as a JSON array. You can edit it by hand, but `git who` validates it on every
173
+ load and reports the position of any invalid entry.
174
+
175
+ ```json
176
+ [
177
+ {
178
+ "name": "work",
179
+ "host": "github-work",
180
+ "username": "Bryan Work",
181
+ "email": "bryan@work.com",
182
+ "signingMethod": "ssh",
183
+ "signingKey": "/Users/bryan/.ssh/id_work.pub"
184
+ },
185
+ {
186
+ "name": "personal",
187
+ "host": "github-personal",
188
+ "username": "Bryan Personal",
189
+ "email": "bryan@personal.com"
190
+ }
191
+ ]
192
+ ```
193
+
194
+ `signingMethod` (`"ssh"` or `"gpg"`) and `signingKey` are either both present or both absent. For GPG, `signingKey` is
195
+ the key ID.
196
+
197
+ ## Limitations
198
+
199
+ - **`Include` directives in `~/.ssh/config` are not followed.** Hosts defined in an included file won't appear in the
200
+ host list.
201
+ - **Only SSH remotes.** `clone` rejects `http(s)` URLs, and `use` rewrites `origin` to an SSH URL.
202
+ - **Host aliases with wildcards or negation** (`*`, `?`, `!`) are skipped when listing hosts.
203
+ - **Signing keys are looked up on this machine.** SSH keys must be `*.pub` files in `~/.ssh`, and GPG keys must be in
204
+ your local GPG keyring.
205
+
206
+ ## Development
207
+
208
+ | Command | What it does |
209
+ | --- | --- |
210
+ | `npm test` | Unit tests, with a 100% coverage threshold. |
211
+ | `npm run test:e2e` | End-to-end test of the profile lifecycle (add, list, show, edit, use, remove). |
212
+ | `npm run lint` | ESLint. |
213
+ | `npm run typecheck` | TypeScript, with no emit. |
214
+
215
+ Tests may not start a process. `test/hooks.ts` replaces every `child_process` spawner with one that throws, so a test
216
+ that forgets to mock a dependency such as git, ssh or gpg fails instead of running it.
217
+
218
+ The end-to-end test runs the real prompts and config file, with git, ssh, gpg and logging faked. It runs in its own
219
+ process because it uses Node's `mock.module`, which needs the `--experimental-test-module-mocks` flag (set by the
220
+ script) and can only replace modules that nothing else has loaded yet.
221
+
222
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for how to contribute.
223
+
224
+ ## Troubleshooting
225
+
226
+ Errors are printed to stderr and the exit code is `1`. When one error wraps another, each cause is printed underneath as
227
+ `Caused by: …`.
228
+
229
+ | Message | Meaning |
230
+ | --- | --- |
231
+ | `No profiles found. Use `git who add` to create one.` | `~/.git-who.cfg.json` doesn't exist or is empty. |
232
+ | `No SSH host aliases found in ~/.ssh/config.` | There are no usable `Host` entries, or the file doesn't exist. |
233
+ | `gpg is required but was not found on PATH.` | A GPG profile or GPG key lookup needs `gpg` installed. |
234
+ | `Config file has an invalid profile at position N` | Entry N of `~/.git-who.cfg.json` is malformed. The message, or the `Caused by:` line under it, says what's wrong. |
235
+ | `Active profile '…' not found — it may have been deleted.` | The repo's `gitwho.profile` names a profile that no longer exists (deleted or renamed). Run `git who use`. |
236
+
237
+ ## License
238
+
239
+ Copyright 2026 Bryan Stopp. Licensed under the [Apache License, Version 2.0](LICENSE).
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { run } from "../src/cli.js";
3
+ await run(process.argv);
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@bstopp/git-who",
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "description": "Manage git profiles for per-project SSH account configuration.",
6
+ "license": "Apache-2.0",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/bstopp/git-who.git"
10
+ },
11
+ "homepage": "https://github.com/bstopp/git-who#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/bstopp/git-who/issues"
14
+ },
15
+ "bin": {
16
+ "git-who": "dist/bin/git-who.js"
17
+ },
18
+ "publishConfig": {
19
+ "access": "public"
20
+ },
21
+ "files": [
22
+ "dist"
23
+ ],
24
+ "scripts": {
25
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
26
+ "prepack": "npm run build",
27
+ "lint": "eslint",
28
+ "test": "c8 mocha 'test/**/*.test.ts'",
29
+ "test:e2e": "mocha --node-option experimental-test-module-mocks 'test/e2e/**/*.e2e.ts'",
30
+ "typecheck": "tsc"
31
+ },
32
+ "engines": {
33
+ "node": ">=24"
34
+ },
35
+ "devDependencies": {
36
+ "@eslint/js": "^10.0.1",
37
+ "@inquirer/testing": "^3.3.10",
38
+ "@stylistic/eslint-plugin": "^5.10.0",
39
+ "@types/mocha": "^10.0.10",
40
+ "@types/node": "^24.19.2",
41
+ "c8": "^12.0.0",
42
+ "esmock": "^3.0.0",
43
+ "mocha": "^12.0.3",
44
+ "semantic-release": "^25.0.9",
45
+ "typescript": "^6.0.3",
46
+ "typescript-eslint": "^8.65.0"
47
+ },
48
+ "dependencies": {
49
+ "@inquirer/confirm": "^6.3.5",
50
+ "@inquirer/core": "^12.0.6",
51
+ "@inquirer/input": "^5.1.2",
52
+ "@inquirer/select": "^5.2.1",
53
+ "chalk": "^6.0.0",
54
+ "commander": "^15.0.0",
55
+ "simple-git": "^4.0.2"
56
+ }
57
+ }
@@ -0,0 +1,88 @@
1
+ import { Command } from 'commander';
2
+ import { ExitPromptError } from '@inquirer/core';
3
+ import pkg from '../package.json' with { type: 'json' };
4
+ import show from "./commands/show.js";
5
+ import list from "./commands/list.js";
6
+ import use from "./commands/use.js";
7
+ import add from "./commands/add.js";
8
+ import edit from "./commands/edit.js";
9
+ import remove from "./commands/remove.js";
10
+ import clone from "./commands/clone.js";
11
+ import log from "./utils/log.js";
12
+ const SIGINT_EXIT_CODE = 130; // 128 + SIGINT, the shell convention for an interrupted command
13
+ export const program = new Command();
14
+ program
15
+ .name('git who')
16
+ .usage('[options] <command>')
17
+ .description('Manage git profiles for per-project SSH account configuration')
18
+ .version(pkg.version);
19
+ program
20
+ .command('show [name]')
21
+ .description('Show the current git profile for this repo')
22
+ .option('--json', 'Print the result as JSON')
23
+ .action(show);
24
+ program
25
+ .command('list')
26
+ .description('List all available profiles')
27
+ .option('--json', 'Print the result as JSON')
28
+ .action(list);
29
+ program
30
+ .command('use [name]')
31
+ .description('Set the profile for this repo.')
32
+ .option('--json', 'Print the result as JSON, without prompting (a profile name is required)')
33
+ .option('--update-origin', 'Update the origin remote to match the profile, without asking')
34
+ .action(use);
35
+ program
36
+ .command('add')
37
+ .description('Add a new profile.')
38
+ .action(add);
39
+ program
40
+ .command('edit [name]')
41
+ .description('Edit an existing profile.')
42
+ .action(edit);
43
+ program
44
+ .command('remove [name]')
45
+ .description('Remove a profile.')
46
+ .action(remove);
47
+ program
48
+ .command('clone <repo> [name]')
49
+ .description('Clone a remote repo using a specific profile.')
50
+ .action(clone);
51
+ /**
52
+ * The message of an error followed by those of its `cause` chain, so wrapped failures show the real reason.
53
+ */
54
+ function errorMessages(err) {
55
+ const messages = [];
56
+ let current = err;
57
+ while (current instanceof Error) {
58
+ messages.push(current.message);
59
+ current = current.cause;
60
+ }
61
+ return messages.length > 0 ? messages : [String(err)];
62
+ }
63
+ function describeError(err) {
64
+ return errorMessages(err).map((message, i) => i === 0 ? message : `Caused by: ${message}`).join('\n');
65
+ }
66
+ /**
67
+ * Run the cli, printing any failure (with its cause chain) and setting a non-zero exit code. A cancelled prompt
68
+ * (Ctrl+C) is not a failure, so it exits with the SIGINT code and prints nothing.
69
+ */
70
+ export async function run(argv) {
71
+ try {
72
+ await program.parseAsync(argv);
73
+ }
74
+ catch (err) {
75
+ if (err instanceof ExitPromptError) {
76
+ process.exitCode = SIGINT_EXIT_CODE;
77
+ return;
78
+ }
79
+ if (argv.includes('--json')) {
80
+ const [error, ...causes] = errorMessages(err);
81
+ log.json({ error, causes });
82
+ }
83
+ else {
84
+ log.error(describeError(err));
85
+ }
86
+ process.exitCode = 1;
87
+ }
88
+ }
@@ -0,0 +1,17 @@
1
+ import chalk from 'chalk';
2
+ import confirm from '@inquirer/confirm';
3
+ import log from "../utils/log.js";
4
+ import { addProfile } from "../utils/profiles.js";
5
+ import { promptForProfile } from "../utils/prompts.js";
6
+ import { printProfile } from "../utils/display.js";
7
+ export default async function add() {
8
+ const profile = await promptForProfile();
9
+ printProfile(profile);
10
+ if (await confirm({ message: 'Save this profile?', default: true })) {
11
+ await addProfile(profile);
12
+ log.info(`Profile ${chalk.bold(profile.name)} added.`);
13
+ }
14
+ else {
15
+ log.warn('Profile not added.');
16
+ }
17
+ }
@@ -0,0 +1,46 @@
1
+ import chalk from 'chalk';
2
+ import { simpleGit } from 'simple-git';
3
+ import { applyProfile, loadProfiles, verifySigningKey } from "../utils/profiles.js";
4
+ import { selectProfile } from "../utils/prompts.js";
5
+ import { parseSshUrl } from "../utils/git-url.js";
6
+ import log from "../utils/log.js";
7
+ const SHORTHAND_PATTERN = /^[^/@.][^/]*\/(?!\.{1,2}$)[^/]+$/;
8
+ /**
9
+ * Build the url to clone, using the profile's ssh host, and the directory to clone it into. The directory is passed to
10
+ * git explicitly so the profile is always applied to the directory that was cloned.
11
+ *
12
+ * @throws {Error} If the repo is neither an ssh url nor an `org/repo` shorthand, or has no repo name to clone into.
13
+ */
14
+ function getCloneInfo(host, repo) {
15
+ const rawPath = parseSshUrl(repo)?.path ?? (SHORTHAND_PATTERN.test(repo) ? repo : undefined);
16
+ const path = rawPath?.replace(/\/+$/, '');
17
+ const dir = path?.split('/').pop().replace(/\.git$/, '');
18
+ if (!path || !dir) {
19
+ throw new Error(`Unsupported repo format: ${repo}`);
20
+ }
21
+ return { url: `git@${host}:${path}`, dir };
22
+ }
23
+ /**
24
+ * Clone a repo using a profile's ssh host, then apply the profile to the clone. The profile is the one given by name or
25
+ * one picked from a prompt.
26
+ *
27
+ * @param repo - An ssh url (`git@host:org/repo.git` or `ssh://git@host/org/repo.git`) or an `org/repo` shorthand. The
28
+ * host is always replaced with the profile's.
29
+ * @throws {Error} If the repo format is not supported, the profile's signing key is missing or cannot be looked up, or
30
+ * the clone fails. The signing key is checked before cloning, so its failure leaves nothing behind. A failure to apply
31
+ * the profile after a successful clone is wrapped with its `cause`, as the repo is left cloned without the profile.
32
+ */
33
+ export default async function clone(repo, name) {
34
+ const profiles = await loadProfiles();
35
+ const profile = await selectProfile(profiles, name);
36
+ const { url, dir } = getCloneInfo(profile.host, repo);
37
+ await verifySigningKey(profile);
38
+ await simpleGit().clone(url, dir);
39
+ try {
40
+ await applyProfile(simpleGit(dir), profile);
41
+ }
42
+ catch (error) {
43
+ throw new Error(`Cloned '${dir}', but profile '${profile.name}' could not be applied. Run \`git who use ${profile.name}\` inside it to retry.`, { cause: error });
44
+ }
45
+ log.info(`Cloned ${chalk.bold(url)} to ${dir} using profile ${chalk.bold(profile.name)}.`);
46
+ }