acp-push 1.4.2 → 2.1.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 (3) hide show
  1. package/README.md +126 -112
  2. package/bin/acp.js +641 -552
  3. package/package.json +1 -1
package/bin/acp.js CHANGED
@@ -1,552 +1,641 @@
1
- #!/usr/bin/env node
2
- 'use strict';
3
-
4
- const { spawnSync } = require('child_process');
5
- const fs = require('fs');
6
- const path = require('path');
7
- const messages = require('../lib/messages');
8
- const pkg = require('../package.json');
9
-
10
- // ---------- output helpers ----------
11
- const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
12
- const paint = (code) => (text) => (useColor ? `\x1b[${code}m${text}\x1b[0m` : text);
13
- const red = paint('31');
14
- const green = paint('32');
15
- const yellow = paint('33');
16
- const cyan = paint('36');
17
- const dim = paint('2');
18
-
19
- const HELP = `
20
- ${cyan('acp')} — git add, commit and push in one go
21
-
22
- Usage: acp [options]
23
-
24
- Options:
25
- -u, --upstream Push to origin, then open a pull request to "upstream"
26
- -ua, --upstream-merge Same as -u, then merge it if you have write access
27
- -b, --branch <name> Push to <name> instead of "main"
28
- -m, --message <text> Use your own commit message instead of a random one
29
- -c, --chunks Split your changes into 10 smaller commits. With -u or
30
- -ua, each commit is pushed with its own pull request
31
- -h, --help Show this help
32
- -v, --version Show the version
33
-
34
- GitHub accounts:
35
- If the GitHub CLI (gh) is installed, acp picks the gh account that matches
36
- the repo owner (github.com/<owner>/...). If none matches, it uses the
37
- account you used last. Log in to each account once with: gh auth login
38
-
39
- Pull requests:
40
- -u and -ua need the GitHub CLI (gh) and a remote called "upstream". The
41
- pull request goes from <branch> on origin (your fork) to the default
42
- branch of upstream. If one is already open, the push just updates it.
43
- -ua only merges if your account can write to upstream (write, maintain
44
- or admin role). Otherwise the pull request is left open.
45
-
46
- git-multi-commit:
47
- If the repo root has a .git-multi-commit.json file, acp still adds and
48
- commits locally, then runs git-multi-commit instead of git push.
49
- -u, -ua and -b are ignored in that case.
50
-
51
- Examples:
52
- acp ${dim('# push to origin/main')}
53
- acp -u ${dim('# push to origin/main, open a PR to upstream')}
54
- acp -ua ${dim('# same, then merge the PR if you can')}
55
- acp -b dev ${dim('# push to origin/dev')}
56
- acp -u --branch fix ${dim('# push to origin/fix, open a PR to upstream')}
57
- acp -m "Fix login bug" ${dim('# custom message, push to origin/main')}
58
- acp -c ${dim('# commit in 10 chunks, then push')}
59
- acp -c -ua ${dim('# each chunk: push, open a PR, merge it')}
60
- `;
61
-
62
- function fail(message) {
63
- console.error(red(`✖ ${message}`));
64
- process.exit(1);
65
- }
66
-
67
- // ---------- argument parsing ----------
68
- function parseArgs(argv) {
69
- const options = { branch: 'main', message: null, pr: false, merge: false, chunks: false };
70
-
71
- for (let i = 0; i < argv.length; i++) {
72
- let flag = argv[i];
73
- let inlineValue;
74
-
75
- // Support --branch=dev and --message="text"
76
- if (flag.startsWith('--') && flag.includes('=')) {
77
- inlineValue = flag.slice(flag.indexOf('=') + 1);
78
- flag = flag.slice(0, flag.indexOf('='));
79
- }
80
-
81
- const takeValue = () => {
82
- if (inlineValue !== undefined) {
83
- if (!inlineValue) fail(`${flag} needs a value`);
84
- return inlineValue;
85
- }
86
- const next = argv[i + 1];
87
- if (next === undefined || next.startsWith('-')) fail(`${flag} needs a value`);
88
- i++;
89
- return next;
90
- };
91
-
92
- switch (flag) {
93
- case '-u':
94
- case '--upstream':
95
- options.pr = true;
96
- break;
97
- case '-ua':
98
- case '--upstream-merge':
99
- options.pr = true;
100
- options.merge = true;
101
- break;
102
- case '-b':
103
- case '--branch':
104
- options.branch = takeValue();
105
- break;
106
- case '-m':
107
- case '--message':
108
- options.message = takeValue();
109
- break;
110
- case '-c':
111
- case '--chunks':
112
- options.chunks = true;
113
- break;
114
- case '-h':
115
- case '--help':
116
- console.log(HELP);
117
- process.exit(0);
118
- break;
119
- case '-v':
120
- case '--version':
121
- console.log(pkg.version);
122
- process.exit(0);
123
- break;
124
- default:
125
- fail(`Unknown option "${flag}". Run "acp --help" to see all options.`);
126
- }
127
- }
128
-
129
- return options;
130
- }
131
-
132
- // ---------- process helpers ----------
133
- // Arguments are passed as an array (no shell), so commit messages with
134
- // quotes, spaces or special characters are always safe. Only pass
135
- // `shell: true` for commands that take no user input.
136
- function run(cmd, args, { quiet = false, env, stdio, shell = false } = {}) {
137
- return spawnSync(cmd, args, {
138
- stdio: stdio || (quiet ? 'pipe' : 'inherit'),
139
- encoding: 'utf8',
140
- env: env ? { ...process.env, ...env } : process.env,
141
- shell,
142
- });
143
- }
144
-
145
- function git(args, options) {
146
- const result = run('git', args, options);
147
- if (result.error) {
148
- if (result.error.code === 'ENOENT') fail('git is not installed or not on your PATH.');
149
- fail(result.error.message);
150
- }
151
- return result;
152
- }
153
-
154
- function step(args, { extraArgs = [], env, hint } = {}) {
155
- const shown = args.map((a) => (/[\s"']/.test(a) ? JSON.stringify(a) : a)).join(' ');
156
- console.log(cyan(`› git ${shown}`));
157
- // When a hint is set, capture git's error output so we can tell whether
158
- // the push failed because of permissions (403, denied, auth failed).
159
- const result = git([...extraArgs, ...args], {
160
- env,
161
- stdio: hint ? ['inherit', 'inherit', 'pipe'] : undefined,
162
- });
163
- if (hint && result.stderr) process.stderr.write(result.stderr);
164
- if (result.status !== 0) {
165
- const authError = /\b403\b|permission|denied|authentication failed|could not read username|repository not found/i;
166
- if (hint && authError.test(result.stderr || '')) console.error(yellow(hint));
167
- fail(`"git ${args[0]}" failed (exit code ${result.status}).`);
168
- }
169
- }
170
-
171
- function randomMessage() {
172
- return messages[Math.floor(Math.random() * messages.length)];
173
- }
174
-
175
- // ---------- chunked commits ----------
176
- const MAX_CHUNKS = 10;
177
-
178
- // The changes that are still uncommitted, as a list of units: each hunk of
179
- // a tracked file's diff, any change without hunks (binary, mode change), and
180
- // each untracked file as a whole. Units of one file stay in file order.
181
- function changeUnits() {
182
- const diff = git(['diff', '--no-color', '--no-renames', '--binary', '-U0'], { quiet: true }).stdout;
183
- const units = [];
184
-
185
- for (const section of diff.split(/^(?=diff --git )/m).filter(Boolean)) {
186
- const at = section.search(/^@@ /m);
187
- if (at === -1) {
188
- units.push({ patch: section });
189
- continue;
190
- }
191
- const header = section.slice(0, at);
192
- for (const hunk of section.slice(at).split(/^(?=@@ )/m)) units.push({ patch: header + hunk });
193
- }
194
-
195
- const untracked = git(['ls-files', '-o', '--exclude-standard', '-z'], { quiet: true }).stdout;
196
- for (const file of untracked.split('\0').filter(Boolean)) units.push({ file });
197
- return units;
198
- }
199
-
200
- function stage(unit) {
201
- if (unit.file) {
202
- git(['add', '--', unit.file], { quiet: true });
203
- return;
204
- }
205
- const result = spawnSync('git', ['apply', '--cached', '--unidiff-zero', '--binary'], {
206
- input: unit.patch,
207
- encoding: 'utf8',
208
- });
209
- if (result.status !== 0) fail(`Could not stage a change: ${(result.stderr || '').trim()}`);
210
- }
211
-
212
- // Commits the changes as MAX_CHUNKS commits (fewer if there are fewer separate
213
- // changes), splitting the individual changes (hunks) as evenly as possible,
214
- // even within one file. afterCommit runs after each commit. Returns false when there was nothing to commit.
215
- function commitInChunks(message, afterCommit) {
216
- // Start from a clean index so each commit holds only its own chunk.
217
- git(['reset', '-q'], { quiet: true });
218
-
219
- const total = changeUnits().length;
220
- if (!total) return false;
221
-
222
- const count = Math.min(MAX_CHUNKS, total);
223
- console.log(cyan(`• Splitting ${total} change(s) into ${count} commit(s)`));
224
-
225
- const pool = [...messages];
226
- for (let i = 0; i < count; i++) {
227
- // The diff is read again after every commit, so line numbers stay right.
228
- const units = changeUnits();
229
- const take = Math.ceil(units.length / (count - i));
230
- units.slice(0, take).forEach(stage);
231
-
232
- let text;
233
- if (message) {
234
- text = `${message} (${i + 1}/${count})`;
235
- } else {
236
- // Draw without repeats so the log doesn't show the same message twice.
237
- text = pool.length ? pool.splice(Math.floor(Math.random() * pool.length), 1)[0] : randomMessage();
238
- }
239
- step(['commit', '-m', text]);
240
- if (afterCommit) afterCommit(i + 1, count);
241
- }
242
- return true;
243
- }
244
-
245
- // ---------- GitHub account picking (via gh CLI) ----------
246
- // Returns { owner, name } for a GitHub remote URL (HTTPS or SSH), or null.
247
- function githubRepo(url) {
248
- const match = url.match(
249
- /^(?:https?:\/\/(?:[^@/]+@)?github\.com\/|(?:ssh:\/\/)?git@github\.com[:/])([^/]+)\/([^/]+?)(?:\.git)?\/?$/i
250
- );
251
- return match ? { owner: match[1], name: match[2] } : null;
252
- }
253
-
254
- // Returns { accounts: [...logins], active: login } or null.
255
- function ghAccounts() {
256
- const json = run('gh', ['auth', 'status', '--hostname', 'github.com', '--json', 'hosts'], { quiet: true });
257
- if (json.error) return null; // gh is not installed
258
-
259
- try {
260
- const list = JSON.parse(json.stdout).hosts['github.com'] || [];
261
- if (list.length) {
262
- const active = list.find((a) => a.active) || list[0];
263
- return { accounts: list.map((a) => a.login), active: active.login };
264
- }
265
- return null;
266
- } catch (_) {
267
- // Older gh without --json: read the plain-text status instead.
268
- }
269
-
270
- const plain = run('gh', ['auth', 'status', '--hostname', 'github.com'], { quiet: true });
271
- const text = `${plain.stdout || ''}\n${plain.stderr || ''}`;
272
- const found = [...text.matchAll(/github\.com (?:account|as) ([A-Za-z0-9-]+)/g)];
273
- if (!found.length) return null;
274
-
275
- const accounts = found.map((m) => m[1]);
276
- let active = accounts[0];
277
- found.forEach((m, i) => {
278
- const block = text.slice(m.index, found[i + 1] ? found[i + 1].index : undefined);
279
- if (/Active account: true/.test(block)) active = m[1];
280
- });
281
- return { accounts, active };
282
- }
283
-
284
- function ghToken(login, isActive) {
285
- let result = run('gh', ['auth', 'token', '--hostname', 'github.com', '--user', login], { quiet: true });
286
- if (result.status !== 0 && isActive) {
287
- result = run('gh', ['auth', 'token', '--hostname', 'github.com'], { quiet: true });
288
- }
289
- return result.status === 0 ? result.stdout.trim() : null;
290
- }
291
-
292
- // Works out which gh account to push with and returns the extra git
293
- // arguments + env needed to use it. Returns null to use normal git login.
294
- function githubAuth(remoteUrl) {
295
- if (/^(ssh:\/\/)?git@github\.com[:/]/i.test(remoteUrl)) {
296
- console.log(dim('• SSH remote, using your SSH key.'));
297
- return null;
298
- }
299
-
300
- const repo = githubRepo(remoteUrl);
301
- if (!repo) return null; // not a GitHub https remote
302
- const owner = repo.owner;
303
-
304
- const gh = ghAccounts();
305
- if (!gh) {
306
- console.log(dim('• GitHub CLI not found or not logged in, using your normal git login.'));
307
- return null;
308
- }
309
-
310
- // GitHub usernames are case-insensitive (Gobibahu === GobiBahu).
311
- const match = gh.accounts.find((a) => a.toLowerCase() === owner.toLowerCase());
312
- const account = match || gh.active;
313
-
314
- if (match) {
315
- console.log(cyan(`• Using GitHub account "${account}" (owner of this repo)`));
316
- } else {
317
- console.log(cyan(`• No gh account for "${owner}", using last used account "${account}"`));
318
- }
319
-
320
- // Make it gh's active account, so it becomes the "last used" one.
321
- if (account !== gh.active) {
322
- const switched = run('gh', ['auth', 'switch', '--hostname', 'github.com', '--user', account], { quiet: true });
323
- if (switched.status !== 0) console.log(yellow(`⚠ Could not switch gh to "${account}", continuing anyway.`));
324
- }
325
-
326
- const token = ghToken(account, account === gh.active);
327
- if (!token) {
328
- console.log(yellow(`⚠ Could not get a token for "${account}", using your normal git login.`));
329
- return null;
330
- }
331
-
332
- // A one-off credential helper just for this push: it clears any saved
333
- // helpers (like Windows Credential Manager) and hands git the gh token.
334
- // The token travels in an env var, never on the command line.
335
- const helper =
336
- '!f() { if [ "$1" = get ]; then echo "username=$ACP_GH_USER"; echo "password=$ACP_GH_TOKEN"; fi; }; f';
337
-
338
- return {
339
- extraArgs: ['-c', 'credential.helper=', '-c', `credential.helper=${helper}`],
340
- env: { ACP_GH_USER: account, ACP_GH_TOKEN: token },
341
- hint:
342
- `⚠ GitHub account "${account}" may not have push access to this repo.\n` +
343
- ` Log in to an account that does with: gh auth login`,
344
- };
345
- }
346
-
347
- // ---------- pull requests (via gh CLI) ----------
348
- // Checks everything -u needs before anything is committed. Returns the
349
- // upstream repo ("owner/name") plus the owners of upstream and the fork.
350
- function pullRequestTarget(originUrl) {
351
- const upstreamUrl = git(['remote', 'get-url', 'upstream'], { quiet: true });
352
- if (upstreamUrl.status !== 0) {
353
- fail('Remote "upstream" does not exist. Add it with: git remote add upstream <url>');
354
- }
355
-
356
- const head = githubRepo(originUrl);
357
- const base = githubRepo(upstreamUrl.stdout.trim());
358
- if (!head || !base) fail('Pull requests need "origin" and "upstream" to both be GitHub repos.');
359
-
360
- if (run('gh', ['--version'], { quiet: true }).status !== 0) {
361
- fail('Pull requests need the GitHub CLI (gh). Install it from https://cli.github.com');
362
- }
363
-
364
- return { repo: `${base.owner}/${base.name}`, baseOwner: base.owner, headOwner: head.owner };
365
- }
366
-
367
- // True when the gh account behind `env` has write access to `repo`
368
- // (the write, maintain or admin role), which is what merging needs.
369
- function canPush(repo, env) {
370
- const result = run('gh', ['api', `repos/${repo}`], { quiet: true, env });
371
- try {
372
- return JSON.parse(result.stdout).permissions.push === true;
373
- } catch (_) {
374
- return false;
375
- }
376
- }
377
-
378
- function sleep(ms) {
379
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
380
- }
381
-
382
- // Opens a pull request from <branch> on the fork to upstream's default
383
- // branch, and merges it when `merge` is set.
384
- function pullRequest(target, branch, merge) {
385
- const gh = ghAccounts();
386
- const accountFor = (owner) => gh && gh.accounts.find((a) => a.toLowerCase() === owner.toLowerCase());
387
- // GH_TOKEN makes gh act as that account. Without it gh uses its active one.
388
- const envFor = (login) => {
389
- const token = login && ghToken(login, login === gh.active);
390
- return token ? { GH_TOKEN: token } : undefined;
391
- };
392
-
393
- const opener = accountFor(target.headOwner);
394
- const head = `${target.headOwner}:${branch}`;
395
- const title = git(['log', '-1', '--pretty=%s'], { quiet: true }).stdout.trim();
396
-
397
- console.log(cyan(`› gh pr create --repo ${target.repo} --head ${head}`));
398
- const created = run(
399
- 'gh',
400
- ['pr', 'create', '--repo', target.repo, '--head', head, '--title', title, '--body', ''],
401
- { quiet: true, env: envFor(opener) }
402
- );
403
- // gh prints the new PR's URL, or the open one's when it already exists.
404
- const output = `${created.stdout || ''}\n${created.stderr || ''}`;
405
- const found = output.match(/https:\/\/github\.com\/\S+\/pull\/\d+/);
406
- if (!found || (created.status !== 0 && !/already exists/i.test(output))) {
407
- if (created.stderr) process.stderr.write(created.stderr);
408
- fail(`"gh pr create" failed (exit code ${created.status}).`);
409
- }
410
-
411
- const url = found[0];
412
- if (created.status === 0) {
413
- console.log(green(`✔ Pull request opened: ${url}`));
414
- } else {
415
- console.log(yellow(`• Pull request already open, updated by this push: ${url}`));
416
- }
417
- if (!merge) return;
418
-
419
- // Only merge with write access to upstream (write, maintain or admin).
420
- // The fork's owner often doesn't have it, so the gh account that owns
421
- // upstream is tried first when there is one.
422
- const owner = accountFor(target.baseOwner);
423
- let merger = owner || opener;
424
- let env = envFor(merger);
425
- let allowed = canPush(target.repo, env);
426
- if (!allowed && merger !== opener) {
427
- merger = opener;
428
- env = envFor(merger);
429
- allowed = canPush(target.repo, env);
430
- }
431
- if (!allowed) {
432
- console.log(yellow(`• No write access to ${target.repo}, so the pull request stays open for a maintainer to merge.`));
433
- return;
434
- }
435
- if (merger && merger !== opener) {
436
- console.log(cyan(`• Merging with GitHub account "${merger}" (owner of upstream)`));
437
- }
438
-
439
- console.log(cyan(`› gh pr merge ${url} --merge`));
440
- let merged;
441
- for (let attempt = 1; attempt <= 3; attempt++) {
442
- merged = run('gh', ['pr', 'merge', url, '--merge'], { quiet: true, env });
443
- // GitHub needs a moment to work out whether a brand new PR can be merged.
444
- if (merged.status === 0 || !/GraphQL: .*not mergeable/i.test(merged.stderr || '')) break;
445
- if (attempt < 3) sleep(2000);
446
- }
447
- if (merged.status !== 0) {
448
- if (merged.stderr) process.stderr.write(merged.stderr);
449
- console.error(yellow(`⚠ The pull request is still open: ${url}`));
450
- fail(`"gh pr merge" failed (exit code ${merged.status}).`);
451
- }
452
- console.log(green(`✔ Merged into ${target.repo}`));
453
- }
454
-
455
- // ---------- git-multi-commit ----------
456
- // Projects set up with git-multi-commit keep this file in the repo root
457
- // (the same place git-multi-commit looks for it). For those, acp runs
458
- // git-multi-commit instead of git push.
459
- const MULTI_COMMIT_CONFIG = '.git-multi-commit.json';
460
-
461
- function usesMultiCommit() {
462
- const root = git(['rev-parse', '--show-toplevel'], { quiet: true }).stdout.trim();
463
- return fs.existsSync(path.join(root, MULTI_COMMIT_CONFIG));
464
- }
465
-
466
- function multiCommit() {
467
- const notInstalled = 'git-multi-commit is not installed. Install it with: npm install -g git-multi-commit';
468
- // npm installs global CLIs as .cmd shims on Windows, which only start
469
- // through a shell. No arguments are passed, so no user input reaches it.
470
- // cmd.exe's "not found" exit code isn't reliable, so look it up first.
471
- const isWindows = process.platform === 'win32';
472
- if (isWindows && run('where', ['git-multi-commit'], { quiet: true }).status !== 0) fail(notInstalled);
473
-
474
- console.log(cyan('› git-multi-commit'));
475
- const result = run('git-multi-commit', [], { shell: isWindows });
476
- if (result.error) fail(result.error.code === 'ENOENT' ? notInstalled : result.error.message);
477
- if (result.status !== 0) fail(`"git-multi-commit" failed (exit code ${result.status}).`);
478
- }
479
-
480
- // ---------- main ----------
481
- function main() {
482
- const { branch, message, pr, merge, chunks } = parseArgs(process.argv.slice(2));
483
- const remote = 'origin';
484
-
485
- if (git(['rev-parse', '--is-inside-work-tree'], { quiet: true }).status !== 0) {
486
- fail('Not inside a git repository.');
487
- }
488
-
489
- const multi = usesMultiCommit();
490
- let remoteUrl;
491
- let target;
492
- if (multi) {
493
- console.log(cyan(`• Found ${MULTI_COMMIT_CONFIG}, pushing with git-multi-commit instead of git push.`));
494
- if (pr || branch !== 'main') console.log(yellow('⚠ -u, -ua and -b are ignored for git-multi-commit.'));
495
- } else {
496
- remoteUrl = git(['remote', 'get-url', remote], { quiet: true });
497
- if (remoteUrl.status !== 0) {
498
- fail(`Remote "${remote}" does not exist. Add it with: git remote add ${remote} <url>`);
499
- }
500
- if (pr) target = pullRequestTarget(remoteUrl.stdout.trim());
501
- }
502
-
503
- if (multi && chunks) console.log(yellow('⚠ -c is ignored for git-multi-commit.'));
504
-
505
- const auth = multi ? null : githubAuth(remoteUrl.stdout.trim()) || {};
506
-
507
- // "HEAD:<branch>" pushes whatever branch you're on (main, master, anything)
508
- // to <branch> on the remote, so the default always lands on "main".
509
- const push = () => {
510
- step(['push', remote, `HEAD:${branch}`], auth);
511
- console.log(green(`✔ Pushed to ${remote}/${branch}`));
512
- };
513
-
514
- // With -c and -u/-ua, every chunk is pushed and gets its own pull request
515
- // (merged right away with -ua), instead of one push at the end.
516
- let pushedPerChunk = false;
517
-
518
- if (chunks && !multi) {
519
- const afterCommit = pr
520
- ? (n, count) => {
521
- console.log(cyan(`• Chunk ${n}/${count}`));
522
- push();
523
- pullRequest(target, branch, merge);
524
- }
525
- : undefined;
526
- const done = commitInChunks(message, afterCommit);
527
- pushedPerChunk = done && pr;
528
- if (!done) console.log(yellow('• Nothing new to commit, pushing existing commits.'));
529
- } else {
530
- step(['add', '.']);
531
-
532
- // "git diff --cached --quiet" exits 0 when nothing is staged.
533
- if (git(['diff', '--cached', '--quiet'], { quiet: true }).status === 0) {
534
- console.log(yellow('• Nothing new to commit, pushing existing commits.'));
535
- } else {
536
- step(['commit', '-m', message || randomMessage()]);
537
- }
538
- }
539
-
540
- if (multi) {
541
- multiCommit();
542
- console.log(green('✔ Pushed with git-multi-commit'));
543
- return;
544
- }
545
-
546
- if (pushedPerChunk) return;
547
-
548
- push();
549
- if (pr) pullRequest(target, branch, merge);
550
- }
551
-
552
- main();
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const { spawnSync } = require('child_process');
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const messages = require('../lib/messages');
8
+ const pkg = require('../package.json');
9
+
10
+ // ---------- output helpers ----------
11
+ const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
12
+ const paint = (code) => (text) => (useColor ? `\x1b[${code}m${text}\x1b[0m` : text);
13
+ const red = paint('31');
14
+ const green = paint('32');
15
+ const yellow = paint('33');
16
+ const cyan = paint('36');
17
+ const dim = paint('2');
18
+
19
+ const HELP = `
20
+ ${cyan('acp')} — git add, commit and push in one go
21
+
22
+ Usage: acp [options]
23
+
24
+ Options:
25
+ -u, --upstream Push to origin, then open a pull request to "upstream"
26
+ -ua, --upstream-allow Same as -u, then merge it if you have write access
27
+ (--upstream-merge works too)
28
+ -b, --branch <name> Push to <name> instead of "main"
29
+ -m, --message <text> Use your own commit message instead of a random one
30
+ -c, --chunks Split your changes into 10 smaller commits. With -u or
31
+ -ua, each commit is pushed with its own pull request
32
+ -h, --help Show this help
33
+ -v, --version Show the version
34
+
35
+ GitHub accounts:
36
+ If the GitHub CLI (gh) is installed, acp picks the gh account that matches
37
+ the repo owner (github.com/<owner>/...). If none matches, it uses the
38
+ account you used last. Log in to each account once with: gh auth login
39
+
40
+ Pull requests:
41
+ -u and -ua need the GitHub CLI (gh) and a remote called "upstream". The
42
+ pull request goes from <branch> on origin (your fork) to the default
43
+ branch of upstream. If one is already open, the push just updates it.
44
+ -ua only merges if your account can write to upstream (write, maintain
45
+ or admin role). Otherwise the pull request is left open.
46
+ Without an "origin" remote, acp pushes the branch straight to upstream
47
+ and opens the pull request from there. The branch is your current one,
48
+ -b <name>, or a new acp-<date> branch when you are on upstream's default.
49
+
50
+ git-multi-commit:
51
+ If the repo root has a .git-multi-commit.json file, acp still adds and
52
+ commits locally, then runs git-multi-commit instead of git push.
53
+ With -u or -ua and an "upstream" remote, acp also pushes <branch> (to
54
+ origin, or straight to upstream when there is no origin) and opens (and
55
+ with -ua merges) the pull request. Without "upstream" it warns and skips
56
+ that part. -b only applies when the pull request step runs.
57
+
58
+ Examples:
59
+ acp ${dim('# push to origin/main')}
60
+ acp -u ${dim('# push to origin/main, open a PR to upstream')}
61
+ acp -ua ${dim('# same, then merge the PR if you can')}
62
+ acp -b dev ${dim('# push to origin/dev')}
63
+ acp -u --branch fix ${dim('# push to origin/fix, open a PR to upstream')}
64
+ acp -m "Fix login bug" ${dim('# custom message, push to origin/main')}
65
+ acp -c ${dim('# commit in 10 chunks, then push')}
66
+ acp -c -ua ${dim('# each chunk: push, open a PR, merge it')}
67
+ acp -ua ${dim('# only "upstream" set: push a branch there, PR + merge')}
68
+ `;
69
+
70
+ function fail(message) {
71
+ console.error(red(`✖ ${message}`));
72
+ process.exit(1);
73
+ }
74
+
75
+ // ---------- argument parsing ----------
76
+ function parseArgs(argv) {
77
+ const options = { branch: 'main', branchGiven: false, message: null, pr: false, merge: false, chunks: false };
78
+
79
+ for (let i = 0; i < argv.length; i++) {
80
+ let flag = argv[i];
81
+ let inlineValue;
82
+
83
+ // Support --branch=dev and --message="text"
84
+ if (flag.startsWith('--') && flag.includes('=')) {
85
+ inlineValue = flag.slice(flag.indexOf('=') + 1);
86
+ flag = flag.slice(0, flag.indexOf('='));
87
+ }
88
+
89
+ const takeValue = () => {
90
+ if (inlineValue !== undefined) {
91
+ if (!inlineValue) fail(`${flag} needs a value`);
92
+ return inlineValue;
93
+ }
94
+ const next = argv[i + 1];
95
+ if (next === undefined || next.startsWith('-')) fail(`${flag} needs a value`);
96
+ i++;
97
+ return next;
98
+ };
99
+
100
+ switch (flag) {
101
+ case '-u':
102
+ case '--upstream':
103
+ options.pr = true;
104
+ break;
105
+ case '-ua':
106
+ case '--upstream-allow':
107
+ case '--upstream-merge':
108
+ options.pr = true;
109
+ options.merge = true;
110
+ break;
111
+ case '-b':
112
+ case '--branch':
113
+ options.branch = takeValue();
114
+ options.branchGiven = true;
115
+ break;
116
+ case '-m':
117
+ case '--message':
118
+ options.message = takeValue();
119
+ break;
120
+ case '-c':
121
+ case '--chunks':
122
+ options.chunks = true;
123
+ break;
124
+ case '-h':
125
+ case '--help':
126
+ console.log(HELP);
127
+ process.exit(0);
128
+ break;
129
+ case '-v':
130
+ case '--version':
131
+ console.log(pkg.version);
132
+ process.exit(0);
133
+ break;
134
+ default:
135
+ fail(`Unknown option "${flag}". Run "acp --help" to see all options.`);
136
+ }
137
+ }
138
+
139
+ return options;
140
+ }
141
+
142
+ // ---------- process helpers ----------
143
+ // Arguments are passed as an array (no shell), so commit messages with
144
+ // quotes, spaces or special characters are always safe. Only pass
145
+ // `shell: true` for commands that take no user input.
146
+ function run(cmd, args, { quiet = false, env, stdio, shell = false } = {}) {
147
+ return spawnSync(cmd, args, {
148
+ stdio: stdio || (quiet ? 'pipe' : 'inherit'),
149
+ encoding: 'utf8',
150
+ env: env ? { ...process.env, ...env } : process.env,
151
+ shell,
152
+ });
153
+ }
154
+
155
+ function git(args, options) {
156
+ const result = run('git', args, options);
157
+ if (result.error) {
158
+ if (result.error.code === 'ENOENT') fail('git is not installed or not on your PATH.');
159
+ fail(result.error.message);
160
+ }
161
+ return result;
162
+ }
163
+
164
+ function step(args, { extraArgs = [], env, hint } = {}) {
165
+ const shown = args.map((a) => (/[\s"']/.test(a) ? JSON.stringify(a) : a)).join(' ');
166
+ console.log(cyan(`› git ${shown}`));
167
+ // When a hint is set, capture git's error output so we can tell whether
168
+ // the push failed because of permissions (403, denied, auth failed).
169
+ const result = git([...extraArgs, ...args], {
170
+ env,
171
+ stdio: hint ? ['inherit', 'inherit', 'pipe'] : undefined,
172
+ });
173
+ if (hint && result.stderr) process.stderr.write(result.stderr);
174
+ if (result.status !== 0) {
175
+ const authError = /\b403\b|permission|denied|authentication failed|could not read username|repository not found/i;
176
+ if (hint && authError.test(result.stderr || '')) console.error(yellow(hint));
177
+ fail(`"git ${args[0]}" failed (exit code ${result.status}).`);
178
+ }
179
+ }
180
+
181
+ function randomMessage() {
182
+ return messages[Math.floor(Math.random() * messages.length)];
183
+ }
184
+
185
+ // ---------- chunked commits ----------
186
+ const MAX_CHUNKS = 10;
187
+
188
+ // The changes that are still uncommitted, as a list of units: each hunk of
189
+ // a tracked file's diff, any change without hunks (binary, mode change), and
190
+ // each untracked file as a whole. Units of one file stay in file order.
191
+ function changeUnits() {
192
+ const diff = git(['diff', '--no-color', '--no-renames', '--binary', '-U0'], { quiet: true }).stdout;
193
+ const units = [];
194
+
195
+ for (const section of diff.split(/^(?=diff --git )/m).filter(Boolean)) {
196
+ const at = section.search(/^@@ /m);
197
+ if (at === -1) {
198
+ units.push({ patch: section });
199
+ continue;
200
+ }
201
+ const header = section.slice(0, at);
202
+ for (const hunk of section.slice(at).split(/^(?=@@ )/m)) units.push({ patch: header + hunk });
203
+ }
204
+
205
+ const untracked = git(['ls-files', '-o', '--exclude-standard', '-z'], { quiet: true }).stdout;
206
+ for (const file of untracked.split('\0').filter(Boolean)) units.push({ file });
207
+ return units;
208
+ }
209
+
210
+ function stage(unit) {
211
+ if (unit.file) {
212
+ git(['add', '--', unit.file], { quiet: true });
213
+ return;
214
+ }
215
+ const result = spawnSync('git', ['apply', '--cached', '--unidiff-zero', '--binary'], {
216
+ input: unit.patch,
217
+ encoding: 'utf8',
218
+ });
219
+ if (result.status !== 0) fail(`Could not stage a change: ${(result.stderr || '').trim()}`);
220
+ }
221
+
222
+ // Commits the changes as MAX_CHUNKS commits (fewer if there are fewer separate
223
+ // changes), splitting the individual changes (hunks) as evenly as possible,
224
+ // even within one file. afterCommit runs after each commit. Returns false when there was nothing to commit.
225
+ function commitInChunks(message, afterCommit) {
226
+ // Start from a clean index so each commit holds only its own chunk.
227
+ git(['reset', '-q'], { quiet: true });
228
+
229
+ const total = changeUnits().length;
230
+ if (!total) return false;
231
+
232
+ const count = Math.min(MAX_CHUNKS, total);
233
+ console.log(cyan(`• Splitting ${total} change(s) into ${count} commit(s)`));
234
+
235
+ const pool = [...messages];
236
+ for (let i = 0; i < count; i++) {
237
+ // The diff is read again after every commit, so line numbers stay right.
238
+ const units = changeUnits();
239
+ const take = Math.ceil(units.length / (count - i));
240
+ units.slice(0, take).forEach(stage);
241
+
242
+ let text;
243
+ if (message) {
244
+ text = `${message} (${i + 1}/${count})`;
245
+ } else {
246
+ // Draw without repeats so the log doesn't show the same message twice.
247
+ text = pool.length ? pool.splice(Math.floor(Math.random() * pool.length), 1)[0] : randomMessage();
248
+ }
249
+ step(['commit', '-m', text]);
250
+ if (afterCommit) afterCommit(i + 1, count);
251
+ }
252
+ return true;
253
+ }
254
+
255
+ // ---------- GitHub account picking (via gh CLI) ----------
256
+ // Returns { owner, name } for a GitHub remote URL (HTTPS or SSH), or null.
257
+ function githubRepo(url) {
258
+ const match = url.match(
259
+ /^(?:https?:\/\/(?:[^@/]+@)?github\.com\/|(?:ssh:\/\/)?git@github\.com[:/])([^/]+)\/([^/]+?)(?:\.git)?\/?$/i
260
+ );
261
+ return match ? { owner: match[1], name: match[2] } : null;
262
+ }
263
+
264
+ // Returns { accounts: [...logins], active: login } or null.
265
+ function ghAccounts() {
266
+ const json = run('gh', ['auth', 'status', '--hostname', 'github.com', '--json', 'hosts'], { quiet: true });
267
+ if (json.error) return null; // gh is not installed
268
+
269
+ try {
270
+ const list = JSON.parse(json.stdout).hosts['github.com'] || [];
271
+ if (list.length) {
272
+ const active = list.find((a) => a.active) || list[0];
273
+ return { accounts: list.map((a) => a.login), active: active.login };
274
+ }
275
+ return null;
276
+ } catch (_) {
277
+ // Older gh without --json: read the plain-text status instead.
278
+ }
279
+
280
+ const plain = run('gh', ['auth', 'status', '--hostname', 'github.com'], { quiet: true });
281
+ const text = `${plain.stdout || ''}\n${plain.stderr || ''}`;
282
+ const found = [...text.matchAll(/github\.com (?:account|as) ([A-Za-z0-9-]+)/g)];
283
+ if (!found.length) return null;
284
+
285
+ const accounts = found.map((m) => m[1]);
286
+ let active = accounts[0];
287
+ found.forEach((m, i) => {
288
+ const block = text.slice(m.index, found[i + 1] ? found[i + 1].index : undefined);
289
+ if (/Active account: true/.test(block)) active = m[1];
290
+ });
291
+ return { accounts, active };
292
+ }
293
+
294
+ function ghToken(login, isActive) {
295
+ let result = run('gh', ['auth', 'token', '--hostname', 'github.com', '--user', login], { quiet: true });
296
+ if (result.status !== 0 && isActive) {
297
+ result = run('gh', ['auth', 'token', '--hostname', 'github.com'], { quiet: true });
298
+ }
299
+ return result.status === 0 ? result.stdout.trim() : null;
300
+ }
301
+
302
+ // Works out which gh account to push with and returns the extra git
303
+ // arguments + env needed to use it. Returns null to use normal git login.
304
+ // With `writeRepo` ("owner/name"), an account that can push to that repo is
305
+ // preferred, because the owner's account may not exist (an organisation).
306
+ function githubAuth(remoteUrl, writeRepo) {
307
+ if (/^(ssh:\/\/)?git@github\.com[:/]/i.test(remoteUrl)) {
308
+ console.log(dim('• SSH remote, using your SSH key.'));
309
+ return null;
310
+ }
311
+
312
+ const repo = githubRepo(remoteUrl);
313
+ if (!repo) return null; // not a GitHub https remote
314
+ const owner = repo.owner;
315
+
316
+ const gh = ghAccounts();
317
+ if (!gh) {
318
+ console.log(dim('• GitHub CLI not found or not logged in, using your normal git login.'));
319
+ return null;
320
+ }
321
+
322
+ // GitHub usernames are case-insensitive (Gobibahu === GobiBahu).
323
+ const match = gh.accounts.find((a) => a.toLowerCase() === owner.toLowerCase());
324
+ let account = match || gh.active;
325
+ let writer = null;
326
+
327
+ if (writeRepo) {
328
+ const candidates = [match, gh.active, ...gh.accounts].filter(Boolean);
329
+ writer = candidates.find((a) => {
330
+ const token = ghToken(a, a === gh.active);
331
+ return token && canPush(writeRepo, { GH_TOKEN: token });
332
+ });
333
+ if (writer) account = writer;
334
+ }
335
+
336
+ if (match && account === match) {
337
+ console.log(cyan(`• Using GitHub account "${account}" (owner of this repo)`));
338
+ } else if (writer) {
339
+ console.log(cyan(`• Using GitHub account "${account}" (has write access to ${writeRepo})`));
340
+ } else {
341
+ console.log(cyan(`• No gh account for "${owner}", using last used account "${account}"`));
342
+ }
343
+
344
+ // Make it gh's active account, so it becomes the "last used" one.
345
+ if (account !== gh.active) {
346
+ const switched = run('gh', ['auth', 'switch', '--hostname', 'github.com', '--user', account], { quiet: true });
347
+ if (switched.status !== 0) console.log(yellow(`⚠ Could not switch gh to "${account}", continuing anyway.`));
348
+ }
349
+
350
+ const token = ghToken(account, account === gh.active);
351
+ if (!token) {
352
+ console.log(yellow(`⚠ Could not get a token for "${account}", using your normal git login.`));
353
+ return null;
354
+ }
355
+
356
+ // A one-off credential helper just for this push: it clears any saved
357
+ // helpers (like Windows Credential Manager) and hands git the gh token.
358
+ // The token travels in an env var, never on the command line.
359
+ const helper =
360
+ '!f() { if [ "$1" = get ]; then echo "username=$ACP_GH_USER"; echo "password=$ACP_GH_TOKEN"; fi; }; f';
361
+
362
+ return {
363
+ extraArgs: ['-c', 'credential.helper=', '-c', `credential.helper=${helper}`],
364
+ env: { ACP_GH_USER: account, ACP_GH_TOKEN: token },
365
+ hint:
366
+ `⚠ GitHub account "${account}" may not have push access to this repo.\n` +
367
+ ` Log in to an account that does with: gh auth login`,
368
+ };
369
+ }
370
+
371
+ // ---------- pull requests (via gh CLI) ----------
372
+ // Checks everything -u needs before anything is committed. Returns the
373
+ // upstream repo ("owner/name") plus the owners of upstream and the fork.
374
+ // With no originUrl there is no fork: the branch goes straight to upstream
375
+ // (`direct`), so the pull request's head and base are the same repo.
376
+ function pullRequestTarget(originUrl) {
377
+ const upstreamUrl = git(['remote', 'get-url', 'upstream'], { quiet: true });
378
+ if (upstreamUrl.status !== 0) {
379
+ fail('Remote "upstream" does not exist. Add it with: git remote add upstream <url>');
380
+ }
381
+
382
+ const head = originUrl ? githubRepo(originUrl) : null;
383
+ const base = githubRepo(upstreamUrl.stdout.trim());
384
+ if (!base || (originUrl && !head)) {
385
+ fail(
386
+ originUrl
387
+ ? 'Pull requests need "origin" and "upstream" to both be GitHub repos.'
388
+ : 'Pull requests need "upstream" to be a GitHub repo.'
389
+ );
390
+ }
391
+
392
+ if (run('gh', ['--version'], { quiet: true }).status !== 0) {
393
+ fail('Pull requests need the GitHub CLI (gh). Install it from https://cli.github.com');
394
+ }
395
+
396
+ return {
397
+ repo: `${base.owner}/${base.name}`,
398
+ baseOwner: base.owner,
399
+ headOwner: head ? head.owner : base.owner,
400
+ direct: !originUrl,
401
+ };
402
+ }
403
+
404
+ // The branch to push to upstream when there is no fork: -b if given, else the
405
+ // branch you are on, else a new acp-<date> one (a pull request can't go from
406
+ // upstream's default branch into itself).
407
+ function directBranch(target, requested) {
408
+ const result = run('gh', ['api', `repos/${target.repo}`, '--jq', '.default_branch'], { quiet: true });
409
+ const base = result.status === 0 ? result.stdout.trim() : '';
410
+ if (!base) fail(`Could not read the default branch of ${target.repo} with gh. Is gh logged in?`);
411
+
412
+ if (requested) {
413
+ if (requested === base) fail(`-b ${requested} is the default branch of ${target.repo}, a pull request needs another one.`);
414
+ return requested;
415
+ }
416
+
417
+ const current = git(['rev-parse', '--abbrev-ref', 'HEAD'], { quiet: true }).stdout.trim();
418
+ if (current && current !== 'HEAD' && current !== base) return current;
419
+
420
+ const stamp = new Date().toISOString().replace(/\D/g, '').slice(0, 14);
421
+ return `acp-${stamp}`;
422
+ }
423
+
424
+ // True when the gh account behind `env` has write access to `repo`
425
+ // (the write, maintain or admin role), which is what merging needs.
426
+ function canPush(repo, env) {
427
+ const result = run('gh', ['api', `repos/${repo}`], { quiet: true, env });
428
+ try {
429
+ return JSON.parse(result.stdout).permissions.push === true;
430
+ } catch (_) {
431
+ return false;
432
+ }
433
+ }
434
+
435
+ function sleep(ms) {
436
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
437
+ }
438
+
439
+ // Opens a pull request from <branch> on the fork to upstream's default
440
+ // branch, and merges it when `merge` is set.
441
+ function pullRequest(target, branch, merge) {
442
+ const gh = ghAccounts();
443
+ const accountFor = (owner) => gh && gh.accounts.find((a) => a.toLowerCase() === owner.toLowerCase());
444
+ // GH_TOKEN makes gh act as that account. Without it gh uses its active one.
445
+ const envFor = (login) => {
446
+ const token = login && ghToken(login, login === gh.active);
447
+ return token ? { GH_TOKEN: token } : undefined;
448
+ };
449
+
450
+ const opener = target.opener || accountFor(target.headOwner);
451
+ const head = `${target.headOwner}:${branch}`;
452
+ const title = git(['log', '-1', '--pretty=%s'], { quiet: true }).stdout.trim();
453
+
454
+ console.log(cyan(`› gh pr create --repo ${target.repo} --head ${head}`));
455
+ const created = run(
456
+ 'gh',
457
+ ['pr', 'create', '--repo', target.repo, '--head', head, '--title', title, '--body', ''],
458
+ { quiet: true, env: envFor(opener) }
459
+ );
460
+ // gh prints the new PR's URL, or the open one's when it already exists.
461
+ const output = `${created.stdout || ''}\n${created.stderr || ''}`;
462
+ const found = output.match(/https:\/\/github\.com\/\S+\/pull\/\d+/);
463
+ if (!found || (created.status !== 0 && !/already exists/i.test(output))) {
464
+ if (created.stderr) process.stderr.write(created.stderr);
465
+ fail(`"gh pr create" failed (exit code ${created.status}).`);
466
+ }
467
+
468
+ const url = found[0];
469
+ if (created.status === 0) {
470
+ console.log(green(`✔ Pull request opened: ${url}`));
471
+ } else {
472
+ console.log(yellow(`• Pull request already open, updated by this push: ${url}`));
473
+ }
474
+ if (!merge) return;
475
+
476
+ // Only merge with write access to upstream (write, maintain or admin).
477
+ // The fork's owner often doesn't have it, so the gh account that owns
478
+ // upstream is tried first when there is one.
479
+ const owner = accountFor(target.baseOwner);
480
+ let merger = owner || opener;
481
+ let env = envFor(merger);
482
+ let allowed = canPush(target.repo, env);
483
+ if (!allowed && merger !== opener) {
484
+ merger = opener;
485
+ env = envFor(merger);
486
+ allowed = canPush(target.repo, env);
487
+ }
488
+ if (!allowed) {
489
+ console.log(yellow(`• No write access to ${target.repo}, so the pull request stays open for a maintainer to merge.`));
490
+ return;
491
+ }
492
+ if (merger && merger !== opener) {
493
+ console.log(cyan(`• Merging with GitHub account "${merger}" (owner of upstream)`));
494
+ }
495
+
496
+ console.log(cyan(`› gh pr merge ${url} --merge`));
497
+ let merged;
498
+ for (let attempt = 1; attempt <= 3; attempt++) {
499
+ merged = run('gh', ['pr', 'merge', url, '--merge'], { quiet: true, env });
500
+ // GitHub needs a moment to work out whether a brand new PR can be merged.
501
+ if (merged.status === 0 || !/GraphQL: .*not mergeable/i.test(merged.stderr || '')) break;
502
+ if (attempt < 3) sleep(2000);
503
+ }
504
+ if (merged.status !== 0) {
505
+ if (merged.stderr) process.stderr.write(merged.stderr);
506
+ console.error(yellow(`⚠ The pull request is still open: ${url}`));
507
+ fail(`"gh pr merge" failed (exit code ${merged.status}).`);
508
+ }
509
+ console.log(green(`✔ Merged into ${target.repo}`));
510
+ }
511
+
512
+ // ---------- git-multi-commit ----------
513
+ // Projects set up with git-multi-commit keep this file in the repo root
514
+ // (the same place git-multi-commit looks for it). For those, acp runs
515
+ // git-multi-commit instead of git push.
516
+ const MULTI_COMMIT_CONFIG = '.git-multi-commit.json';
517
+
518
+ function usesMultiCommit() {
519
+ const root = git(['rev-parse', '--show-toplevel'], { quiet: true }).stdout.trim();
520
+ return fs.existsSync(path.join(root, MULTI_COMMIT_CONFIG));
521
+ }
522
+
523
+ function multiCommit() {
524
+ const notInstalled = 'git-multi-commit is not installed. Install it with: npm install -g git-multi-commit';
525
+ // npm installs global CLIs as .cmd shims on Windows, which only start
526
+ // through a shell. No arguments are passed, so no user input reaches it.
527
+ // cmd.exe's "not found" exit code isn't reliable, so look it up first.
528
+ const isWindows = process.platform === 'win32';
529
+ if (isWindows && run('where', ['git-multi-commit'], { quiet: true }).status !== 0) fail(notInstalled);
530
+
531
+ console.log(cyan('› git-multi-commit'));
532
+ const result = run('git-multi-commit', [], { shell: isWindows });
533
+ if (result.error) fail(result.error.code === 'ENOENT' ? notInstalled : result.error.message);
534
+ if (result.status !== 0) fail(`"git-multi-commit" failed (exit code ${result.status}).`);
535
+ }
536
+
537
+ // ---------- main ----------
538
+ function main() {
539
+ const { branch: requestedBranch, branchGiven, message, pr, merge, chunks } = parseArgs(process.argv.slice(2));
540
+ let branch = requestedBranch;
541
+ let remote = 'origin';
542
+
543
+ if (git(['rev-parse', '--is-inside-work-tree'], { quiet: true }).status !== 0) {
544
+ fail('Not inside a git repository.');
545
+ }
546
+
547
+ const remoteUrlOf = (name) => git(['remote', 'get-url', name], { quiet: true });
548
+ const multi = usesMultiCommit();
549
+ let remoteUrl;
550
+ let target;
551
+ if (multi) {
552
+ console.log(cyan(`• Found ${MULTI_COMMIT_CONFIG}, pushing with git-multi-commit instead of git push.`));
553
+ if (pr) {
554
+ // git-multi-commit pushes to its own repos, so -u/-ua only apply when
555
+ // "upstream" exists. Without "origin" the branch goes straight to it.
556
+ const hasOrigin = remoteUrlOf('origin');
557
+ const hasUpstream = remoteUrlOf('upstream');
558
+ if (hasUpstream.status === 0) {
559
+ if (hasOrigin.status !== 0) remote = 'upstream';
560
+ remoteUrl = hasOrigin.status === 0 ? hasOrigin : hasUpstream;
561
+ target = pullRequestTarget(hasOrigin.status === 0 ? remoteUrl.stdout.trim() : null);
562
+ console.log(cyan(`• Found remote "upstream", will also push to ${remote} and open a pull request.`));
563
+ } else {
564
+ console.log(yellow('⚠ Remote "upstream" does not exist, skipping -u/-ua (git-multi-commit only).'));
565
+ }
566
+ }
567
+ if (!target && branch !== 'main') console.log(yellow('⚠ -b is ignored for git-multi-commit.'));
568
+ } else {
569
+ remoteUrl = remoteUrlOf('origin');
570
+ if (remoteUrl.status !== 0) {
571
+ const upstream = pr ? remoteUrlOf('upstream') : null;
572
+ if (!upstream || upstream.status !== 0) {
573
+ fail(`Remote "${remote}" does not exist. Add it with: git remote add ${remote} <url>`);
574
+ }
575
+ console.log(cyan('• No "origin" remote, pushing a branch straight to "upstream".'));
576
+ remote = 'upstream';
577
+ remoteUrl = upstream;
578
+ target = pullRequestTarget(null);
579
+ } else if (pr) {
580
+ target = pullRequestTarget(remoteUrl.stdout.trim());
581
+ }
582
+ }
583
+
584
+ if (target && target.direct) branch = directBranch(target, branchGiven ? requestedBranch : null);
585
+
586
+ if (multi && chunks) console.log(yellow('⚠ -c is ignored for git-multi-commit.'));
587
+
588
+ const auth = remoteUrl ? githubAuth(remoteUrl.stdout.trim(), target && target.direct ? target.repo : null) || {} : null;
589
+ // Without a fork, the account that pushed the branch also opens the pull request.
590
+ if (target && target.direct && auth && auth.env) target.opener = auth.env.ACP_GH_USER;
591
+
592
+ // "HEAD:<branch>" pushes whatever branch you're on (main, master, anything)
593
+ // to <branch> on the remote, so the default always lands on "main".
594
+ const push = () => {
595
+ step(['push', remote, `HEAD:${branch}`], auth);
596
+ console.log(green(`✔ Pushed to ${remote}/${branch}`));
597
+ };
598
+
599
+ // With -c and -u/-ua, every chunk is pushed and gets its own pull request
600
+ // (merged right away with -ua), instead of one push at the end.
601
+ let pushedPerChunk = false;
602
+
603
+ if (chunks && !multi) {
604
+ const afterCommit = pr
605
+ ? (n, count) => {
606
+ console.log(cyan(`• Chunk ${n}/${count}`));
607
+ push();
608
+ pullRequest(target, branch, merge);
609
+ }
610
+ : undefined;
611
+ const done = commitInChunks(message, afterCommit);
612
+ pushedPerChunk = done && pr;
613
+ if (!done) console.log(yellow('• Nothing new to commit, pushing existing commits.'));
614
+ } else {
615
+ step(['add', '.']);
616
+
617
+ // "git diff --cached --quiet" exits 0 when nothing is staged.
618
+ if (git(['diff', '--cached', '--quiet'], { quiet: true }).status === 0) {
619
+ console.log(yellow('• Nothing new to commit, pushing existing commits.'));
620
+ } else {
621
+ step(['commit', '-m', message || randomMessage()]);
622
+ }
623
+ }
624
+
625
+ if (multi) {
626
+ multiCommit();
627
+ console.log(green('✔ Pushed with git-multi-commit'));
628
+ if (target) {
629
+ push();
630
+ pullRequest(target, branch, merge);
631
+ }
632
+ return;
633
+ }
634
+
635
+ if (pushedPerChunk) return;
636
+
637
+ push();
638
+ if (pr) pullRequest(target, branch, merge);
639
+ }
640
+
641
+ main();