acp-push 1.0.2 → 1.3.2

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 (3) hide show
  1. package/README.md +31 -0
  2. package/bin/acp.js +186 -18
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -43,6 +43,37 @@ acp -u -b staging # git push upstream staging
43
43
  acp -m "Fix login bug" # custom message
44
44
  ```
45
45
 
46
+ ## Multiple GitHub accounts
47
+
48
+ If you have the [GitHub CLI](https://cli.github.com) (`gh`) installed, `acp` picks the right account for each repo automatically:
49
+
50
+ | Remote | Account used |
51
+ | --- | --- |
52
+ | `https://github.com/SENODROOM/acp-push` | `SENODROOM` |
53
+ | `https://github.com/Gobibahu/some-repo` | `GobiBahu` (names are case-insensitive) |
54
+ | `https://github.com/some-org/project` (no matching account) | the account you used last |
55
+
56
+ Log in to each account once:
57
+
58
+ ```bash
59
+ gh auth login # log in as the first account
60
+ gh auth login # run again for the second account
61
+ ```
62
+
63
+ `acp` switches gh's active account to whichever one it used, so "last used" is always the most recent one. The token is only used for that one push and doesn't replace your saved git login. SSH remotes and non-GitHub remotes use your normal git login.
64
+
65
+ ## git-multi-commit projects
66
+
67
+ If your repo root contains a `.git-multi-commit.json` file (created by [`git-multi-commit --config`](https://www.npmjs.com/package/git-multi-commit)), `acp` still runs `git add .` and `git commit` locally, but then runs `git-multi-commit` instead of `git push`:
68
+
69
+ ```bash
70
+ git add .
71
+ git commit -m "<one of 25 random messages>"
72
+ git-multi-commit
73
+ ```
74
+
75
+ No `origin` remote is needed in this case, and `-u` / `-b` are ignored. Install it with `npm install -g git-multi-commit`.
76
+
46
77
  ## Notes
47
78
 
48
79
  - If there is nothing new to commit, `acp` skips the commit and still pushes, so any commits you made earlier get sent.
package/bin/acp.js CHANGED
@@ -2,6 +2,8 @@
2
2
  'use strict';
3
3
 
4
4
  const { spawnSync } = require('child_process');
5
+ const fs = require('fs');
6
+ const path = require('path');
5
7
  const messages = require('../lib/messages');
6
8
  const pkg = require('../package.json');
7
9
 
@@ -26,12 +28,22 @@ Options:
26
28
  -h, --help Show this help
27
29
  -v, --version Show the version
28
30
 
31
+ GitHub accounts:
32
+ If the GitHub CLI (gh) is installed, acp picks the gh account that matches
33
+ the repo owner (github.com/<owner>/...). If none matches, it uses the
34
+ account you used last. Log in to each account once with: gh auth login
35
+
36
+ git-multi-commit:
37
+ If the repo root has a .git-multi-commit.json file, acp still adds and
38
+ commits locally, then runs git-multi-commit instead of git push.
39
+ -u and -b are ignored in that case.
40
+
29
41
  Examples:
30
- acp ${dim('# git push origin main')}
31
- acp -u ${dim('# git push upstream main')}
32
- acp -b dev ${dim('# git push origin dev')}
33
- acp -u --branch staging ${dim('# git push upstream staging')}
34
- acp -m "Fix login bug" ${dim('# custom message, git push origin main')}
42
+ acp ${dim('# push to origin/main')}
43
+ acp -u ${dim('# push to upstream/main')}
44
+ acp -b dev ${dim('# push to origin/dev')}
45
+ acp -u --branch staging ${dim('# push to upstream/staging')}
46
+ acp -m "Fix login bug" ${dim('# custom message, push to origin/main')}
35
47
  `;
36
48
 
37
49
  function fail(message) {
@@ -95,14 +107,21 @@ function parseArgs(argv) {
95
107
  return options;
96
108
  }
97
109
 
98
- // ---------- git helpers ----------
110
+ // ---------- process helpers ----------
99
111
  // Arguments are passed as an array (no shell), so commit messages with
100
- // quotes, spaces or special characters are always safe.
101
- function git(args, quiet = false) {
102
- const result = spawnSync('git', args, {
103
- stdio: quiet ? 'pipe' : 'inherit',
112
+ // quotes, spaces or special characters are always safe. Only pass
113
+ // `shell: true` for commands that take no user input.
114
+ function run(cmd, args, { quiet = false, env, stdio, shell = false } = {}) {
115
+ return spawnSync(cmd, args, {
116
+ stdio: stdio || (quiet ? 'pipe' : 'inherit'),
104
117
  encoding: 'utf8',
118
+ env: env ? { ...process.env, ...env } : process.env,
119
+ shell,
105
120
  });
121
+ }
122
+
123
+ function git(args, options) {
124
+ const result = run('git', args, options);
106
125
  if (result.error) {
107
126
  if (result.error.code === 'ENOENT') fail('git is not installed or not on your PATH.');
108
127
  fail(result.error.message);
@@ -110,41 +129,190 @@ function git(args, quiet = false) {
110
129
  return result;
111
130
  }
112
131
 
113
- function step(args) {
132
+ function step(args, { extraArgs = [], env, hint } = {}) {
114
133
  const shown = args.map((a) => (/[\s"']/.test(a) ? JSON.stringify(a) : a)).join(' ');
115
134
  console.log(cyan(`› git ${shown}`));
116
- const result = git(args);
117
- if (result.status !== 0) fail(`"git ${args[0]}" failed (exit code ${result.status}).`);
135
+ // When a hint is set, capture git's error output so we can tell whether
136
+ // the push failed because of permissions (403, denied, auth failed).
137
+ const result = git([...extraArgs, ...args], {
138
+ env,
139
+ stdio: hint ? ['inherit', 'inherit', 'pipe'] : undefined,
140
+ });
141
+ if (hint && result.stderr) process.stderr.write(result.stderr);
142
+ if (result.status !== 0) {
143
+ const authError = /\b403\b|permission|denied|authentication failed|could not read username|repository not found/i;
144
+ if (hint && authError.test(result.stderr || '')) console.error(yellow(hint));
145
+ fail(`"git ${args[0]}" failed (exit code ${result.status}).`);
146
+ }
118
147
  }
119
148
 
120
149
  function randomMessage() {
121
150
  return messages[Math.floor(Math.random() * messages.length)];
122
151
  }
123
152
 
153
+ // ---------- GitHub account picking (via gh CLI) ----------
154
+ function githubOwner(url) {
155
+ const match = url.match(/^https?:\/\/(?:[^@/]+@)?github\.com\/([^/]+)\//i);
156
+ return match ? match[1] : null;
157
+ }
158
+
159
+ // Returns { accounts: [...logins], active: login } or null.
160
+ function ghAccounts() {
161
+ const json = run('gh', ['auth', 'status', '--hostname', 'github.com', '--json', 'hosts'], { quiet: true });
162
+ if (json.error) return null; // gh is not installed
163
+
164
+ try {
165
+ const list = JSON.parse(json.stdout).hosts['github.com'] || [];
166
+ if (list.length) {
167
+ const active = list.find((a) => a.active) || list[0];
168
+ return { accounts: list.map((a) => a.login), active: active.login };
169
+ }
170
+ return null;
171
+ } catch (_) {
172
+ // Older gh without --json: read the plain-text status instead.
173
+ }
174
+
175
+ const plain = run('gh', ['auth', 'status', '--hostname', 'github.com'], { quiet: true });
176
+ const text = `${plain.stdout || ''}\n${plain.stderr || ''}`;
177
+ const found = [...text.matchAll(/github\.com (?:account|as) ([A-Za-z0-9-]+)/g)];
178
+ if (!found.length) return null;
179
+
180
+ const accounts = found.map((m) => m[1]);
181
+ let active = accounts[0];
182
+ found.forEach((m, i) => {
183
+ const block = text.slice(m.index, found[i + 1] ? found[i + 1].index : undefined);
184
+ if (/Active account: true/.test(block)) active = m[1];
185
+ });
186
+ return { accounts, active };
187
+ }
188
+
189
+ function ghToken(login, isActive) {
190
+ let result = run('gh', ['auth', 'token', '--hostname', 'github.com', '--user', login], { quiet: true });
191
+ if (result.status !== 0 && isActive) {
192
+ result = run('gh', ['auth', 'token', '--hostname', 'github.com'], { quiet: true });
193
+ }
194
+ return result.status === 0 ? result.stdout.trim() : null;
195
+ }
196
+
197
+ // Works out which gh account to push with and returns the extra git
198
+ // arguments + env needed to use it. Returns null to use normal git login.
199
+ function githubAuth(remoteUrl) {
200
+ if (/^(ssh:\/\/)?git@github\.com[:/]/i.test(remoteUrl)) {
201
+ console.log(dim('• SSH remote, using your SSH key.'));
202
+ return null;
203
+ }
204
+
205
+ const owner = githubOwner(remoteUrl);
206
+ if (!owner) return null; // not a GitHub https remote
207
+
208
+ const gh = ghAccounts();
209
+ if (!gh) {
210
+ console.log(dim('• GitHub CLI not found or not logged in, using your normal git login.'));
211
+ return null;
212
+ }
213
+
214
+ // GitHub usernames are case-insensitive (Gobibahu === GobiBahu).
215
+ const match = gh.accounts.find((a) => a.toLowerCase() === owner.toLowerCase());
216
+ const account = match || gh.active;
217
+
218
+ if (match) {
219
+ console.log(cyan(`• Using GitHub account "${account}" (owner of this repo)`));
220
+ } else {
221
+ console.log(cyan(`• No gh account for "${owner}", using last used account "${account}"`));
222
+ }
223
+
224
+ // Make it gh's active account, so it becomes the "last used" one.
225
+ if (account !== gh.active) {
226
+ const switched = run('gh', ['auth', 'switch', '--hostname', 'github.com', '--user', account], { quiet: true });
227
+ if (switched.status !== 0) console.log(yellow(`⚠ Could not switch gh to "${account}", continuing anyway.`));
228
+ }
229
+
230
+ const token = ghToken(account, account === gh.active);
231
+ if (!token) {
232
+ console.log(yellow(`⚠ Could not get a token for "${account}", using your normal git login.`));
233
+ return null;
234
+ }
235
+
236
+ // A one-off credential helper just for this push: it clears any saved
237
+ // helpers (like Windows Credential Manager) and hands git the gh token.
238
+ // The token travels in an env var, never on the command line.
239
+ const helper =
240
+ '!f() { if [ "$1" = get ]; then echo "username=$ACP_GH_USER"; echo "password=$ACP_GH_TOKEN"; fi; }; f';
241
+
242
+ return {
243
+ extraArgs: ['-c', 'credential.helper=', '-c', `credential.helper=${helper}`],
244
+ env: { ACP_GH_USER: account, ACP_GH_TOKEN: token },
245
+ hint:
246
+ `⚠ GitHub account "${account}" may not have push access to this repo.\n` +
247
+ ` Log in to an account that does with: gh auth login`,
248
+ };
249
+ }
250
+
251
+ // ---------- git-multi-commit ----------
252
+ // Projects set up with git-multi-commit keep this file in the repo root
253
+ // (the same place git-multi-commit looks for it). For those, acp runs
254
+ // git-multi-commit instead of git push.
255
+ const MULTI_COMMIT_CONFIG = '.git-multi-commit.json';
256
+
257
+ function usesMultiCommit() {
258
+ const root = git(['rev-parse', '--show-toplevel'], { quiet: true }).stdout.trim();
259
+ return fs.existsSync(path.join(root, MULTI_COMMIT_CONFIG));
260
+ }
261
+
262
+ function multiCommit() {
263
+ const notInstalled = 'git-multi-commit is not installed. Install it with: npm install -g git-multi-commit';
264
+ // npm installs global CLIs as .cmd shims on Windows, which only start
265
+ // through a shell. No arguments are passed, so no user input reaches it.
266
+ // cmd.exe's "not found" exit code isn't reliable, so look it up first.
267
+ const isWindows = process.platform === 'win32';
268
+ if (isWindows && run('where', ['git-multi-commit'], { quiet: true }).status !== 0) fail(notInstalled);
269
+
270
+ console.log(cyan('› git-multi-commit'));
271
+ const result = run('git-multi-commit', [], { shell: isWindows });
272
+ if (result.error) fail(result.error.code === 'ENOENT' ? notInstalled : result.error.message);
273
+ if (result.status !== 0) fail(`"git-multi-commit" failed (exit code ${result.status}).`);
274
+ }
275
+
124
276
  // ---------- main ----------
125
277
  function main() {
126
278
  const { remote, branch, message } = parseArgs(process.argv.slice(2));
127
279
 
128
- if (git(['rev-parse', '--is-inside-work-tree'], true).status !== 0) {
280
+ if (git(['rev-parse', '--is-inside-work-tree'], { quiet: true }).status !== 0) {
129
281
  fail('Not inside a git repository.');
130
282
  }
131
283
 
132
- if (git(['remote', 'get-url', remote], true).status !== 0) {
133
- fail(`Remote "${remote}" does not exist. Add it with: git remote add ${remote} <url>`);
284
+ const multi = usesMultiCommit();
285
+ let remoteUrl;
286
+ if (multi) {
287
+ console.log(cyan(`• Found ${MULTI_COMMIT_CONFIG}, pushing with git-multi-commit instead of git push.`));
288
+ if (remote !== 'origin' || branch !== 'main') console.log(yellow('⚠ -u and -b are ignored for git-multi-commit.'));
289
+ } else {
290
+ remoteUrl = git(['remote', 'get-url', remote], { quiet: true });
291
+ if (remoteUrl.status !== 0) {
292
+ fail(`Remote "${remote}" does not exist. Add it with: git remote add ${remote} <url>`);
293
+ }
134
294
  }
135
295
 
136
296
  step(['add', '.']);
137
297
 
138
298
  // "git diff --cached --quiet" exits 0 when nothing is staged.
139
- if (git(['diff', '--cached', '--quiet'], true).status === 0) {
299
+ if (git(['diff', '--cached', '--quiet'], { quiet: true }).status === 0) {
140
300
  console.log(yellow('• Nothing new to commit, pushing existing commits.'));
141
301
  } else {
142
302
  step(['commit', '-m', message || randomMessage()]);
143
303
  }
144
304
 
305
+ if (multi) {
306
+ multiCommit();
307
+ console.log(green('✔ Pushed with git-multi-commit'));
308
+ return;
309
+ }
310
+
311
+ const auth = githubAuth(remoteUrl.stdout.trim()) || {};
312
+
145
313
  // "HEAD:<branch>" pushes whatever branch you're on (main, master, anything)
146
314
  // to <branch> on the remote, so the default always lands on "main".
147
- step(['push', remote, `HEAD:${branch}`]);
315
+ step(['push', remote, `HEAD:${branch}`], auth);
148
316
  console.log(green(`✔ Pushed to ${remote}/${branch}`));
149
317
  }
150
318
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "acp-push",
3
- "version": "1.0.2",
3
+ "version": "1.3.2",
4
4
  "description": "git add, commit (with a random message) and push in one command: acp",
5
5
  "bin": {
6
6
  "acp": "bin/acp.js"