acp-push 2.2.0 → 2.3.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 +27 -4
  2. package/bin/acp.js +207 -18
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -29,7 +29,8 @@ npm install -g acp-push
29
29
  | `-u`, `--upstream` | Push to `origin`, then open a pull request to `upstream` |
30
30
  | `-ua`, `--upstream-allow` (or `--upstream-merge`) | Same as `-u`, then merge the pull request if you have write access to `upstream` |
31
31
  | `-bpa`, `--branch-pr-auto` | Push to a new branch on `origin`, open a pull request into the default branch, merge it, then delete the branch |
32
- | `-b`, `--branch <name>` | Push to `<name>` instead of `main` |
32
+ | `-bopa`, `--branch-origin-pr-auto` | Same as `-bpa` |
33
+ | `-b`, `--branch <name>` | Push to `<name>` instead of `main` (`-b-<name>` works too, e.g. `-b-nida`) |
33
34
  | `-m`, `--message <text>` | Use your own commit message instead of a random one |
34
35
  | `-c`, `--chunks` | Split your changes into 10 smaller commits (by change, not by file), then push |
35
36
  | `-h`, `--help` | Show help |
@@ -42,8 +43,11 @@ acp # git push origin main
42
43
  acp -u # git push origin main, then open a PR to upstream
43
44
  acp -ua # same, then merge the PR if you have write access
44
45
  acp -bpa # new branch, PR into main, merge, delete the branch
46
+ acp -bopa # same as -bpa
45
47
  acp -b dev # git push origin dev
46
48
  acp --branch=dev # same as above
49
+ acp -b-nida # same as -b nida, git push origin nida
50
+ acp -c -b-nida # commit in 10 chunks, then push to origin nida
47
51
  acp -u -b fix # git push origin fix, then open a PR to upstream
48
52
  acp -m "Fix login bug" # custom message
49
53
  acp -c # 10 smaller commits, then push
@@ -83,9 +87,9 @@ gh pr merge <pr> --merge
83
87
  - Of your logged-in `gh` accounts, `acp` uses one that can push to `upstream` (the owner's account first) for the push, the pull request and the merge.
84
88
  - The branch is not deleted after the merge.
85
89
 
86
- ## One repo: branch, PR, merge, delete (`-bpa`)
90
+ ## One repo: branch, PR, merge, delete (`-bpa` / `-bopa`)
87
91
 
88
- `acp -bpa` does the whole branch workflow in the repo you are in, with no fork or `upstream` needed:
92
+ `acp -bpa` (or `acp -bopa`) does the whole branch workflow in the repo you are in, with no fork or `upstream` needed:
89
93
 
90
94
  ```bash
91
95
  git add .
@@ -102,7 +106,7 @@ git pull --ff-only origin <default branch> # only if you are on the default br
102
106
  - The pull request goes into the default branch of `origin`. Its title is your last commit message.
103
107
  - If your account can't merge (no write access), the pull request stays open and the branch is **not** deleted.
104
108
  - If the branch was already deleted (for example by the repo's "automatically delete head branches" setting), `acp` just says so.
105
- - Works with `-c` (each chunk gets its own branch round trip). Not supported with git-multi-commit projects.
109
+ - Works with `-c` (each chunk gets its own branch round trip). With git-multi-commit projects, see [below](#git-multi-commit-projects).
106
110
 
107
111
  ## Multiple GitHub accounts
108
112
 
@@ -135,6 +139,25 @@ git-multi-commit
135
139
 
136
140
  No `origin` remote is needed in this case. With `-u` / `-ua`, `acp` looks for an `upstream` remote: if it exists, it also pushes the branch (to `origin`, or straight to `upstream` when there is no `origin`) and opens (and with `-ua`, merges) the pull request after `git-multi-commit` finishes. If `upstream` is missing, it prints a warning and skips that part. `-b` only applies when the pull request step runs. Install it with `npm install -g git-multi-commit`.
137
141
 
142
+ With `-bpa`, every repo in `.git-multi-commit.json` goes through the branch workflow instead of being pushed to directly:
143
+
144
+ ```bash
145
+ git add .
146
+ git commit -m "<one of 25 random messages>"
147
+ # for every repo in the config, using that pair's account:
148
+ gh api -X POST repos/<owner>/<repo>/git/refs # acp-<date>, from the default branch
149
+ git-multi-commit # pushes to acp-<date>
150
+ gh pr create --repo <owner>/<repo> --head <owner>:acp-<date>
151
+ gh pr merge <pr> --merge
152
+ gh api -X DELETE repos/<owner>/<repo>/git/refs/heads/acp-<date>
153
+ ```
154
+
155
+ - The pull request goes into each repo's default branch, even if the pair has another `branch` in its config.
156
+ - Every account must be logged in to `gh` and able to push to its repo, and every repo needs at least one commit. `acp` checks this before committing anything.
157
+ - A repo with nothing new gets no pull request, and its branch is removed. If one pair fails, the others still finish, and `acp` exits with an error at the end.
158
+ - `.git-multi-commit.json` is pointed at the branch while `git-multi-commit` runs, then put back exactly as it was.
159
+ - `-c` is ignored, as with any git-multi-commit run. Your local branch is not updated, because these repos have their own histories.
160
+
138
161
  ## Notes
139
162
 
140
163
  - 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
@@ -28,7 +28,10 @@ Options:
28
28
  -bpa, --branch-pr-auto Push to a new branch on origin, open a pull request into
29
29
  the default branch, merge it, then delete the branch
30
30
  (-b <name> picks the branch name)
31
+ -bopa, --branch-origin-pr-auto
32
+ Same as -bpa
31
33
  -b, --branch <name> Push to <name> instead of "main"
34
+ (-b-<name> works too, e.g. -b-nida)
32
35
  -m, --message <text> Use your own commit message instead of a random one
33
36
  -c, --chunks Split your changes into 10 smaller commits. With -u or
34
37
  -ua, each commit is pushed with its own pull request
@@ -50,7 +53,7 @@ Pull requests:
50
53
  and opens the pull request from there. The branch is your current one,
51
54
  -b <name>, or a new acp-<date> branch when you are on upstream's default.
52
55
 
53
- One repo (-bpa):
56
+ One repo (-bpa, -bopa):
54
57
  Needs the GitHub CLI (gh) and an "origin" remote on GitHub. The branch is
55
58
  named acp-<date> unless you give -b <name>. The merge needs write access to
56
59
  origin; without it the pull request stays open and the branch is kept.
@@ -63,14 +66,19 @@ git-multi-commit:
63
66
  origin, or straight to upstream when there is no origin) and opens (and
64
67
  with -ua merges) the pull request. Without "upstream" it warns and skips
65
68
  that part. -b only applies when the pull request step runs.
69
+ With -bpa, every repo in the config gets its own branch, pull request into
70
+ its default branch, merge and branch delete. -b <name> works here too.
66
71
 
67
72
  Examples:
68
73
  acp ${dim('# push to origin/main')}
69
74
  acp -u ${dim('# push to origin/main, open a PR to upstream')}
70
75
  acp -ua ${dim('# same, then merge the PR if you can')}
71
76
  acp -bpa ${dim('# push a new branch, PR into main, merge, delete the branch')}
77
+ acp -bopa ${dim('# same as -bpa')}
72
78
  acp -b dev ${dim('# push to origin/dev')}
73
- acp -u --branch fix ${dim('# push to origin/fix, open a PR to upstream')}
79
+ acp -b-nida ${dim('# same as -b nida: push to origin/nida')}
80
+ acp -c -b-nida ${dim('# commit in 10 chunks, then push to origin/nida')}
81
+ acp -u --branch fix ${dim('# push to origin/fix, open a PR to upstream')}
74
82
  acp -m "Fix login bug" ${dim('# custom message, push to origin/main')}
75
83
  acp -c ${dim('# commit in 10 chunks, then push')}
76
84
  acp -c -ua ${dim('# each chunk: push, open a PR, merge it')}
@@ -107,6 +115,14 @@ function parseArgs(argv) {
107
115
  return next;
108
116
  };
109
117
 
118
+ // Shorthand: -b-nida is the same as -b nida (the name may contain dashes).
119
+ if (flag.startsWith('-b-')) {
120
+ if (flag.length === 3) fail('-b- needs a branch name, like -b-nida');
121
+ options.branch = flag.slice(3);
122
+ options.branchGiven = true;
123
+ continue;
124
+ }
125
+
110
126
  switch (flag) {
111
127
  case '-u':
112
128
  case '--upstream':
@@ -120,6 +136,8 @@ function parseArgs(argv) {
120
136
  break;
121
137
  case '-bpa':
122
138
  case '--branch-pr-auto':
139
+ case '-bopa':
140
+ case '--branch-origin-pr-auto':
123
141
  options.bpa = true;
124
142
  options.pr = true;
125
143
  options.merge = true;
@@ -426,7 +444,7 @@ function pullRequestTarget(originUrl, baseRemote = 'upstream') {
426
444
  // because the branch is deleted after the merge.
427
445
  // Also stores the default branch as target.base.
428
446
  function directBranch(target, requested, fresh = false) {
429
- const result = run('gh', ['api', `repos/${target.repo}`, '--jq', '.default_branch'], { quiet: true });
447
+ const result = run('gh', ['api', `repos/${target.repo}`, '--jq', '.default_branch'], { quiet: true, env: target.env });
430
448
  const base = result.status === 0 ? result.stdout.trim() : '';
431
449
  if (!base) fail(`Could not read the default branch of ${target.repo} with gh. Is gh logged in?`);
432
450
  target.base = base;
@@ -568,23 +586,185 @@ function cleanUp(remote, branch, base, auth) {
568
586
  // git-multi-commit instead of git push.
569
587
  const MULTI_COMMIT_CONFIG = '.git-multi-commit.json';
570
588
 
571
- function usesMultiCommit() {
589
+ const MULTI_COMMIT_NOT_INSTALLED = 'git-multi-commit is not installed. Install it with: npm install -g git-multi-commit';
590
+ const isWindows = process.platform === 'win32';
591
+
592
+ function multiCommitConfigPath() {
572
593
  const root = git(['rev-parse', '--show-toplevel'], { quiet: true }).stdout.trim();
573
- return fs.existsSync(path.join(root, MULTI_COMMIT_CONFIG));
594
+ return path.join(root, MULTI_COMMIT_CONFIG);
574
595
  }
575
596
 
576
- function multiCommit() {
577
- const notInstalled = 'git-multi-commit is not installed. Install it with: npm install -g git-multi-commit';
578
- // npm installs global CLIs as .cmd shims on Windows, which only start
579
- // through a shell. No arguments are passed, so no user input reaches it.
580
- // cmd.exe's "not found" exit code isn't reliable, so look it up first.
581
- const isWindows = process.platform === 'win32';
582
- if (isWindows && run('where', ['git-multi-commit'], { quiet: true }).status !== 0) fail(notInstalled);
597
+ function usesMultiCommit() {
598
+ return fs.existsSync(multiCommitConfigPath());
599
+ }
583
600
 
601
+ // cmd.exe's "not found" exit code isn't reliable, so look it up first.
602
+ function requireMultiCommit() {
603
+ if (isWindows && run('where', ['git-multi-commit'], { quiet: true }).status !== 0) fail(MULTI_COMMIT_NOT_INSTALLED);
604
+ }
605
+
606
+ // npm installs global CLIs as .cmd shims on Windows, which only start
607
+ // through a shell. No arguments are passed, so no user input reaches it.
608
+ function runMultiCommit() {
584
609
  console.log(cyan('› git-multi-commit'));
585
- const result = run('git-multi-commit', [], { shell: isWindows });
586
- if (result.error) fail(result.error.code === 'ENOENT' ? notInstalled : result.error.message);
587
- if (result.status !== 0) fail(`"git-multi-commit" failed (exit code ${result.status}).`);
610
+ return run('git-multi-commit', [], { shell: isWindows });
611
+ }
612
+
613
+ // What went wrong with a git-multi-commit run, or null if nothing did.
614
+ function multiCommitProblem(result) {
615
+ if (result.error) return result.error.code === 'ENOENT' ? MULTI_COMMIT_NOT_INSTALLED : result.error.message;
616
+ return result.status === 0 ? null : `"git-multi-commit" failed (exit code ${result.status}).`;
617
+ }
618
+
619
+ function multiCommit() {
620
+ requireMultiCommit();
621
+ const problem = multiCommitProblem(runMultiCommit());
622
+ if (problem) fail(problem);
623
+ }
624
+
625
+ // ---------- -bpa with git-multi-commit ----------
626
+ // Each pair is its own repo with its own history, so every one gets its own
627
+ // branch, pull request and merge. Checks everything before anything is committed.
628
+ function pairTargets(requested) {
629
+ let config;
630
+ try {
631
+ config = JSON.parse(fs.readFileSync(multiCommitConfigPath(), 'utf8'));
632
+ } catch (error) {
633
+ fail(`Could not read ${MULTI_COMMIT_CONFIG}: ${error.message}`);
634
+ }
635
+ const pairs = (config && config.pairs) || [];
636
+ if (!pairs.length) fail(`${MULTI_COMMIT_CONFIG} has no pairs. Set them up with: git-multi-commit --config`);
637
+
638
+ const gh = ghAccounts();
639
+ if (!gh) fail('-bpa needs the GitHub CLI (gh), logged in. Install it from https://cli.github.com');
640
+
641
+ let branch = requested;
642
+ const targets = pairs.map((pair) => {
643
+ const repo = githubRepo(pair.repoUrl || '');
644
+ if (!repo) fail(`Pull requests need every pair to be a GitHub repo, "${pair.repoUrl}" is not.`);
645
+
646
+ const account = String(pair.account).toLowerCase();
647
+ const login = gh.accounts.find((a) => a.toLowerCase() === account);
648
+ const token = login && ghToken(login, login === gh.active);
649
+ if (!token) fail(`GitHub account "${pair.account}" is not logged in. Log in with: gh auth login`);
650
+
651
+ const target = {
652
+ repo: `${repo.owner}/${repo.name}`,
653
+ baseOwner: repo.owner,
654
+ headOwner: repo.owner,
655
+ direct: true,
656
+ opener: login,
657
+ env: { GH_TOKEN: token },
658
+ };
659
+ branch = directBranch(target, branch, true);
660
+ if (!canPush(target.repo, target.env)) fail(`GitHub account "${login}" can't push to ${target.repo}.`);
661
+
662
+ const tip = run('gh', ['api', `repos/${target.repo}/git/ref/heads/${target.base}`, '--jq', '.object.sha'], {
663
+ quiet: true,
664
+ env: target.env,
665
+ });
666
+ if (tip.status !== 0) fail(`Could not read ${target.base} of ${target.repo}. A pull request needs a repo with commits.`);
667
+ target.baseSha = tip.stdout.trim();
668
+ return target;
669
+ });
670
+ return { targets, branch };
671
+ }
672
+
673
+ // Creates <branch> from the default branch. Returns false when it failed.
674
+ // A branch that already exists is used as it is, and is not ours to delete.
675
+ function createPairBranch(target, branch) {
676
+ const created = run(
677
+ 'gh',
678
+ ['api', '-X', 'POST', `repos/${target.repo}/git/refs`, '-f', `ref=refs/heads/${branch}`, '-f', `sha=${target.baseSha}`],
679
+ { quiet: true, env: target.env }
680
+ );
681
+ target.createdBranch = created.status === 0;
682
+ if (created.status === 0 || /already exists/i.test(created.stderr || '')) return true;
683
+ if (created.stderr) process.stderr.write(created.stderr);
684
+ return false;
685
+ }
686
+
687
+ function deletePairBranch(target, branch) {
688
+ console.log(cyan(`› gh api -X DELETE repos/${target.repo}/git/refs/heads/${branch}`));
689
+ const deleted = run('gh', ['api', '-X', 'DELETE', `repos/${target.repo}/git/refs/heads/${branch}`], {
690
+ quiet: true,
691
+ env: target.env,
692
+ });
693
+ if (deleted.status === 0) {
694
+ console.log(green(`✔ Deleted ${target.repo}:${branch}`));
695
+ } else if (/reference does not exist/i.test(deleted.stderr || '')) {
696
+ console.log(dim(`• ${target.repo}:${branch} was already deleted.`));
697
+ } else {
698
+ if (deleted.stderr) process.stderr.write(deleted.stderr);
699
+ console.log(yellow(`⚠ Could not delete ${target.repo}:${branch}, delete it yourself.`));
700
+ }
701
+ }
702
+
703
+ // How many commits <branch> is ahead of the default branch, or null if unknown.
704
+ function commitsAhead(target, branch) {
705
+ const compared = run('gh', ['api', `repos/${target.repo}/compare/${target.base}...${branch}`, '--jq', '.ahead_by'], {
706
+ quiet: true,
707
+ env: target.env,
708
+ });
709
+ return compared.status === 0 ? Number(compared.stdout.trim()) : null;
710
+ }
711
+
712
+ // git-multi-commit has no branch option and only reads the branch from its
713
+ // config, so the config points at <branch> just for this one run. The branch
714
+ // has to exist first: on a missing branch git-multi-commit starts from nothing,
715
+ // and a pull request can't be opened between unrelated histories.
716
+ function runMultiCommitOnBranch(branch) {
717
+ const file = multiCommitConfigPath();
718
+ const original = fs.readFileSync(file, 'utf8');
719
+ const config = JSON.parse(original);
720
+ config.branch = branch;
721
+ config.pairs.forEach((pair) => {
722
+ pair.branch = branch;
723
+ });
724
+
725
+ // Ctrl+C must stop git-multi-commit but not acp, or the config stays changed.
726
+ const ignore = () => {};
727
+ process.on('SIGINT', ignore);
728
+ fs.writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`);
729
+ try {
730
+ return runMultiCommit();
731
+ } finally {
732
+ fs.writeFileSync(file, original);
733
+ process.removeListener('SIGINT', ignore);
734
+ }
735
+ }
736
+
737
+ function branchPrAutoPairs(targets, branch) {
738
+ for (const target of targets) {
739
+ if (createPairBranch(target, branch)) continue;
740
+ targets.filter((t) => t.createdBranch).forEach((t) => deletePairBranch(t, branch));
741
+ fail(`Could not create branch "${branch}" on ${target.repo}.`);
742
+ }
743
+
744
+ const result = runMultiCommitOnBranch(branch);
745
+
746
+ // 0xC000013A is how Windows reports a process stopped with Ctrl+C.
747
+ if (result.signal === 'SIGINT' || result.status === 130 || result.status === 0xc000013a) {
748
+ fail(`Interrupted, nothing was merged. Branch "${branch}" may be left on the repos.`);
749
+ }
750
+
751
+ // A pair with nothing new, or one that failed, has an empty branch. A failed
752
+ // pair doesn't stop the others, so the ones that were pushed still go through.
753
+ for (const target of targets) {
754
+ console.log(cyan(`• ${target.repo}`));
755
+ const ahead = commitsAhead(target, branch);
756
+ if (ahead === null) {
757
+ console.log(yellow(`⚠ Could not compare "${branch}" with ${target.base}, leaving it for you to check.`));
758
+ } else if (ahead === 0) {
759
+ console.log(dim('• No new commits, skipping the pull request.'));
760
+ if (target.createdBranch) deletePairBranch(target, branch);
761
+ } else if (pullRequest(target, branch, true)) {
762
+ deletePairBranch(target, branch);
763
+ }
764
+ }
765
+
766
+ const problem = multiCommitProblem(result);
767
+ if (problem) fail(problem);
588
768
  }
589
769
 
590
770
  // ---------- main ----------
@@ -601,10 +781,14 @@ function main() {
601
781
  const multi = usesMultiCommit();
602
782
  let remoteUrl;
603
783
  let target;
784
+ let pairs;
604
785
  if (multi) {
605
- if (bpa) fail('-bpa does not work with git-multi-commit.');
606
786
  console.log(cyan(`• Found ${MULTI_COMMIT_CONFIG}, pushing with git-multi-commit instead of git push.`));
607
- if (pr) {
787
+ if (bpa) {
788
+ requireMultiCommit();
789
+ ({ targets: pairs, branch } = pairTargets(branchGiven ? requestedBranch : null));
790
+ console.log(cyan(`• Using branch "${branch}" on ${pairs.length} repo(s)`));
791
+ } else if (pr) {
608
792
  // git-multi-commit pushes to its own repos, so -u/-ua only apply when
609
793
  // "upstream" exists. Without "origin" the branch goes straight to it.
610
794
  const hasOrigin = remoteUrlOf('origin');
@@ -618,7 +802,7 @@ function main() {
618
802
  console.log(yellow('⚠ Remote "upstream" does not exist, skipping -u/-ua (git-multi-commit only).'));
619
803
  }
620
804
  }
621
- if (!target && branch !== 'main') console.log(yellow('⚠ -b is ignored for git-multi-commit.'));
805
+ if (!target && !bpa && branch !== 'main') console.log(yellow('⚠ -b is ignored for git-multi-commit.'));
622
806
  } else {
623
807
  remoteUrl = remoteUrlOf('origin');
624
808
  if (remoteUrl.status !== 0) {
@@ -687,6 +871,11 @@ function main() {
687
871
  }
688
872
  }
689
873
 
874
+ if (pairs) {
875
+ branchPrAutoPairs(pairs, branch);
876
+ return;
877
+ }
878
+
690
879
  if (multi) {
691
880
  multiCommit();
692
881
  console.log(green('✔ Pushed with git-multi-commit'));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "acp-push",
3
- "version": "2.2.0",
3
+ "version": "2.3.0",
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"