-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
git-stacked-rebase.ts
executable file
·1668 lines (1419 loc) · 52.4 KB
/
git-stacked-rebase.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env ts-node-dev
/* eslint-disable indent */
/* eslint-disable @typescript-eslint/camelcase */
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import Git from "nodegit";
import fs from "fs";
import path from "path";
import assert from "assert";
import { bullets } from "nice-comment";
import open from "open";
/**
* separate package (soon)
*/
import { setupPostRewriteHookFor } from "./git-reconcile-rewritten-list/postRewriteHook";
import { Argv, createArgParse, Maybe, maybe, last, MaybeArg } from "./argparse/argparse";
import { filenames } from "./filenames";
import { ConfigValues, configKeys, loadGitConfig } from "./config";
import {
getDefaultResolvedOptions, //
ResolvedGitStackedRebaseOptions,
parseInitialBranch,
resolveOptions,
SpecifiableGitStackedRebaseOptions,
} from "./options";
import { apply, applyIfNeedsToApply, askYesNoAlways, markThatNeedsToApply } from "./apply";
import { forcePush } from "./forcePush";
import { BehaviorOfGetBranchBoundaries, branchSequencer } from "./branchSequencer";
import { autosquash } from "./autosquash";
import { askQuestion__internal, editor__internal, EitherEditor } from "./internal";
import { generateListOfURLsToCreateStackedPRs } from "./pullRequestStack";
import { repair } from "./repair";
import { createExecSyncInRepo } from "./util/execSyncInRepo";
import { noop } from "./util/noop";
import { uniq } from "./util/uniq";
import { parseTodoOfStackedRebase } from "./parse-todo-of-stacked-rebase/parseTodoOfStackedRebase";
import { Termination } from "./util/error";
import { assertNever } from "./util/assertNever";
import { Single, Tuple } from "./util/tuple";
import { isDirEmptySync } from "./util/fs";
import { AskQuestion, Questions, question } from "./util/createQuestion";
import { delay } from "./util/delay";
import { log, GSR_LOGDIR } from "./util/log";
import {
getParseTargetsCtxFromLine,
GoodCommand,
GoodCommandRegular,
GoodCommandStacked, //
namesOfRebaseCommandsThatMakeRebaseExitToPause,
regularRebaseCommands,
RegularRebaseEitherCommandOrAlias,
StackedRebaseCommand,
StackedRebaseCommandAlias,
stackedRebaseCommands,
Targets,
} from "./parse-todo-of-stacked-rebase/validator";
export * from "./options";
export async function gitStackedRebase(
specifiedOptions: SpecifiableGitStackedRebaseOptions = {}
): Promise<void> {
try {
const { repoRootDir, execSyncInRepo } = parsePrereqs(specifiedOptions);
const repo: Git.Repository = await Git.Repository.open(repoRootDir);
const config: Git.Config = await loadGitConfig(repo, specifiedOptions);
const dotGitDirPath: string = repo.path();
const options: ResolvedGitStackedRebaseOptions = await resolveOptions(specifiedOptions, { config, dotGitDirPath });
log({ options, repoRootDir });
const pathToRegularRebaseDirInsideDotGit = path.join(dotGitDirPath, "rebase-merge");
const pathToStackedRebaseDirInsideDotGit = path.join(dotGitDirPath, "stacked-rebase");
const pathToRegularRebaseTodoFile = path.join(pathToRegularRebaseDirInsideDotGit, filenames.gitRebaseTodo);
const pathToStackedRebaseTodoFile = path.join(pathToStackedRebaseDirInsideDotGit, filenames.gitRebaseTodo);
const initialBranch: Git.Reference = await parseInitialBranch(repo, options.initialBranch);
const currentBranch: Git.Reference = await repo.getCurrentBranch();
const checkIsRegularRebaseStillInProgress = (): boolean => fs.existsSync(pathToRegularRebaseDirInsideDotGit);
const askQuestion: AskQuestion = askQuestion__internal in options ? options[askQuestion__internal]! : question;
if (fs.existsSync(path.join(pathToStackedRebaseDirInsideDotGit, filenames.willNeedToApply))) {
markThatNeedsToApply(pathToStackedRebaseDirInsideDotGit);
}
if (options.apply) {
return await apply({
repo,
pathToStackedRebaseTodoFile,
pathToStackedRebaseDirInsideDotGit, //
rootLevelCommandName: "--apply",
gitCmd: options.gitCmd,
initialBranch,
currentBranch,
});
}
if (options.continue) {
execSyncInRepo(`${options.gitCmd} rebase --continue`);
if (checkIsRegularRebaseStillInProgress()) {
/**
* still not done - further `--continue`s will be needed.
*/
return;
}
log("after --continue, rebase done. trying to --apply");
/**
* rebase has finished. we can try to --apply now
* so that the partial branches do not get out of sync.
*/
await applyIfNeedsToApply({
isMandatoryIfMarkedAsNeeded: false,
repo,
pathToStackedRebaseTodoFile,
pathToStackedRebaseDirInsideDotGit, //
rootLevelCommandName: "--apply (automatically after --continue)",
gitCmd: options.gitCmd,
autoApplyIfNeeded: options.autoApplyIfNeeded,
config,
initialBranch,
currentBranch,
askQuestion,
});
return;
}
await applyIfNeedsToApply({
/**
* at this point, if an `--apply` has been marked as needed, we must perform it.
*
* we either a) already know that the user allows it, via options.autoApplyIfNeeded,
* or b) if not -- we must ask the user directly if the apply can be performed.
*
* if user does not allow us to perform the apply -- we cannot continue, and will terminate.
*/
isMandatoryIfMarkedAsNeeded: true,
repo,
pathToStackedRebaseTodoFile,
pathToStackedRebaseDirInsideDotGit, //
rootLevelCommandName: "--apply",
gitCmd: options.gitCmd,
autoApplyIfNeeded: options.autoApplyIfNeeded,
config,
initialBranch,
currentBranch,
askQuestion,
});
if (options.push) {
if (!options.forcePush) {
throw new Termination("\npush without --force will fail (since git rebase overrides history).\n\n");
}
return await forcePush({
repo, //
pathToStackedRebaseTodoFile,
pathToStackedRebaseDirInsideDotGit,
rootLevelCommandName: "--push --force",
gitCmd: options.gitCmd,
initialBranch,
currentBranch,
});
}
if (options.pullRequest) {
const githubFrontendURLsForUserToCreatePRs: string[] = await generateListOfURLsToCreateStackedPRs({
repo, //
initialBranch,
currentBranch,
ignoredBranches: options.ignoredBranches,
askQuestion,
});
const out = "\n" + githubFrontendURLsForUserToCreatePRs.join("\n") + "\n";
process.stdout.write(out);
const shouldOpenURLsInWebBrowser: boolean = await askYesNoAlways({
questionToAsk: Questions.open_urls_in_web_browser, //
askQuestion,
onAllowAlways: async () => {
const always: ConfigValues["autoOpenPRUrlsInBrowser"] = "always";
await config.setString(configKeys.autoOpenPRUrlsInBrowser, always);
},
});
if (shouldOpenURLsInWebBrowser) {
for (const url of githubFrontendURLsForUserToCreatePRs) {
await open(url);
await delay(10);
}
}
return;
}
if (options.branchSequencer) {
if (options.branchSequencerExec) {
const toExec: string = options.branchSequencerExec;
return branchSequencer({
gitCmd: options.gitCmd,
repo,
rootLevelCommandName: "--branch-sequencer --exec",
actionInsideEachCheckedOutBranch: ({ execSyncInRepo: execS }) => (execS(toExec), void 0),
pathToStackedRebaseDirInsideDotGit,
pathToStackedRebaseTodoFile,
initialBranch,
currentBranch,
behaviorOfGetBranchBoundaries:
BehaviorOfGetBranchBoundaries[
"if-stacked-rebase-in-progress-then-parse-not-applied-state-otherwise-simple-branch-traverse"
],
reverseCheckoutOrder: false,
});
} else {
/**
* we'll likely end up adding more sub-commands
* to branchSequencer later.
*/
throw new Termination("\n--branch-sequencer (without --exec) - nothing to do?\n\n");
}
}
const wasRegularRebaseInProgress: boolean = checkIsRegularRebaseStillInProgress();
// const
log({ wasRegularRebaseInProgress });
if (wasRegularRebaseInProgress) {
throw new Termination("regular rebase already in progress");
}
/**
* only create the dir now, when it's needed.
* otherwise, other commands can incorrectly infer
* that our own stacked rebase is in progress,
* when it's not, up until now.
*/
fs.mkdirSync(pathToStackedRebaseDirInsideDotGit, { recursive: true });
//
await createInitialEditTodoOfGitStackedRebase(
repo, //
initialBranch,
currentBranch,
// __default__pathToStackedRebaseTodoFile
pathToStackedRebaseTodoFile,
options.autoSquash,
options.repair,
askQuestion,
// () =>
// getWantedCommitsWithBranchBoundariesUsingNativeGitRebase({
// gitCmd: options.gitCmd,
// repo,
// initialBranch,
// currentBranch,
// dotGitDirPath,
// pathToRegularRebaseTodoFile,
// pathToStackedRebaseTodoFile,
// pathToRegularRebaseDirInsideDotGit,
// })
);
if (!wasRegularRebaseInProgress) {
try {
const editor: EitherEditor =
editor__internal in options
? options[editor__internal]!
: "editor" in options
? options.editor
: assertNever(options);
if (editor instanceof Function) {
await editor({ filePath: pathToStackedRebaseTodoFile });
} else {
process.stdout.write("hint: Waiting for your editor to close the file... ");
execSyncInRepo(`${editor} ${pathToStackedRebaseTodoFile}`);
}
} catch (_e) {
/**
* cleanup
*/
fs.unlinkSync(pathToStackedRebaseTodoFile);
if (isDirEmptySync(pathToStackedRebaseDirInsideDotGit)) {
fs.rmdirSync(pathToStackedRebaseDirInsideDotGit, { recursive: true });
}
throw new Termination(`error: There was a problem with the editor '${options.editor}'.\n`);
}
}
const regularRebaseTodoLines: string[] = [];
/**
* part 1 of "the different ways to launch git rebase"
*/
regularRebaseTodoLines.push("break");
const goodCommands: GoodCommand[] = parseTodoOfStackedRebase(pathToStackedRebaseTodoFile);
// eslint-disable-next-line no-inner-declarations
async function createBranchForCommand(
cmd: GoodCommand & { commandName: StackedRebaseCommand & "branch-end-new" }
): Promise<void> {
const newBranchName: string = cmd.targets![0];
const force: number = 0;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const targetCommitSHA: string = cmd.commitSHAThatBranchPointsTo!;
const targetCommit: Git.Commit = await Git.Commit.lookup(repo, targetCommitSHA);
await Git.Branch.create(repo, newBranchName, targetCommit, force);
}
/**
* TODO should probably go into `validator`
*/
const oldLatestBranchCmdIndex: number = goodCommands.findIndex((cmd) => cmd.commandName === "branch-end-last");
// if (indexOfLatestBranch === -1) // TODO verify in validator
const isThereANewLatestBranch: boolean = oldLatestBranchCmdIndex !== goodCommands.length - 1;
if (isThereANewLatestBranch) {
let newLatestBranchCmdIndex: number | null = null;
let userOnlyReorderedWithoutCreatingNew: boolean = false;
for (let i = goodCommands.length - 1; i >= 0; i--) {
const cmd = goodCommands[i];
if (cmd.commandName === "branch-end-new") {
newLatestBranchCmdIndex = i;
break;
}
}
if (newLatestBranchCmdIndex === null || newLatestBranchCmdIndex <= oldLatestBranchCmdIndex) {
/**
* check if wanted to re-order w/o creating a new branch
*/
const hasExistingBranchAsLatest: boolean =
goodCommands[goodCommands.length - 1].commandName === "branch-end";
if (newLatestBranchCmdIndex === null && hasExistingBranchAsLatest) {
newLatestBranchCmdIndex = goodCommands.length - 1;
userOnlyReorderedWithoutCreatingNew = true;
} else {
// TODO validator
const when =
newLatestBranchCmdIndex === null
? "at all"
: newLatestBranchCmdIndex <= oldLatestBranchCmdIndex
? "after the branch-end-latest command"
: ""; // assertNever(newLatestBranchCmdIndex);
throw new Termination(
"\n" +
`apparently a new latest branch was attempted (by adding commands _after_ the "branch-end-last")` +
`\nbut there was no "branch-end-new" command (${when})`
);
}
}
/**
* strategy:
*
* 1. create the "branch-end-new" at the appropriate position
*
* now, both the new & the old "latest" branches are pointing to the same commit
*
* 2. reset the old "latest" branch to the newly provided, earlier position
*
* 3. update the command names of the 2 branches
* 3.1 in "goodCommands"
* 3.2 in our "git-rebase-todo" file?
*
*
* strategy v2:
* 1. same
* 2.
*
*
* note 1:
* in general, idk if this is the best approach.
* though, it requries the least amount of effort from the user, afaik.
*
* if we instead made the user manually move the "branch-end-latest" to an earlier position (normal / same as here),
* but the also rename it to "branch-end" (extra work),
* and then create a new "branch-end-latest" in the very end (normal / similar to here (just "-latest" instead of "-new")),
*
* it's more steps, and idk if it conveys the picture well,
* because we no longer say "branch-end-new" explicitly,
* nor is it explicit that the "branch-end-last" has been moved.
*
* so then yes, the alternative sucks,
* & this (branch-end-last being not the latest command) is good.
*
* note 2:
* TODO will most likely need to do extra handling for the `rebaseChangedLocalHistory`,
* because even tho we won't change local history _of the commits_,
* the branches do indeed change, and here it's not simply adding a branch in the middle
* (though does that also need extra handling?),
* we're changing the latest branch, so it matters a lot
* and would need to run the `--apply`
* (currently `rebaseChangedLocalHistory` would prevent `--apply` from running).
*
* note 2.1:
* TODO need to support a use-case where the new latest branch
* is not new, i.e. user has had already created it,
* and now has simply moved it after the "branch-end-last".
*
* note 3:
* this logic implies that we should always be doing `--apply`,
* TODO thus consider.
*
* note 2.2 / 3.1:
* oh, we actually should be doing the `--apply` in a lot more cases,
* e.g. when a local branch is moved (currently we don't!)
*
*/
const oldLatestBranchCmd: GoodCommandStacked = goodCommands[oldLatestBranchCmdIndex] as GoodCommandStacked; // TODO TS
const newLatestBranchCmd: GoodCommandStacked = goodCommands[newLatestBranchCmdIndex] as GoodCommandStacked; // TODO TS
if (!userOnlyReorderedWithoutCreatingNew) {
/**
* create the new "latest branch"
*/
await createBranchForCommand(newLatestBranchCmd as any); // TODO TS
}
/**
* move the old "latest branch" earlier to it's target
*/
const oldTarget: string = oldLatestBranchCmd.targets![0].replace(removeLocalRegex, "");
execSyncInRepo(`${options.gitCmd} checkout ${oldTarget}`);
const commit: Git.Commit = await Git.Commit.lookup(repo, oldLatestBranchCmd.commitSHAThatBranchPointsTo!);
// await Git.Reset.reset(repo, commit, Git.Reset.TYPE.HARD, {});
execSyncInRepo(`${options.gitCmd} reset --hard ${commit.sha()}`);
/**
* go to the new "latest branch".
*/
const newTarget: string = newLatestBranchCmd.targets![0].replace(removeLocalRegex, "");
execSyncInRepo(`${options.gitCmd} checkout ${newTarget}`);
/**
* TODO FIXME don't do this so hackishly lmao
*/
const editedRebaseTodo: string = fs.readFileSync(pathToStackedRebaseTodoFile, { encoding: "utf-8" });
const linesOfEditedRebaseTodo: string[] = editedRebaseTodo.split("\n");
replaceCommandInText(oldLatestBranchCmd, ["branch-end-last"], "branch-end");
replaceCommandInText(
newLatestBranchCmd, //
userOnlyReorderedWithoutCreatingNew ? ["branch-end", "be"] : ["branch-end-new", "ben"],
"branch-end-last"
);
// eslint-disable-next-line no-inner-declarations
function replaceCommandInText(
cmd: GoodCommandStacked, //
allowedOldName: Single<StackedRebaseCommand> | Tuple<StackedRebaseCommand, StackedRebaseCommandAlias>,
newName: StackedRebaseCommand
): void {
const words = linesOfEditedRebaseTodo[cmd.lineNumber].split(" ");
assert(
allowedOldName.some((n) => n === words[0]),
`invalid old name of command in git-rebase-todo file. got "${words[0]}", expected one of "${allowedOldName}".`
);
words[0] = newName;
log({ before: linesOfEditedRebaseTodo[cmd.lineNumber] });
linesOfEditedRebaseTodo[cmd.lineNumber] = words.join(" ");
log({ after: linesOfEditedRebaseTodo[cmd.lineNumber] });
}
fs.writeFileSync(pathToStackedRebaseTodoFile, linesOfEditedRebaseTodo.join("\n"), { encoding: "utf-8" });
/**
* TODO RE-PARSE ALL COMMANDS FROM THE FILE INSTEAD
*/
oldLatestBranchCmd.commandName = "branch-end";
oldLatestBranchCmd.commandOrAliasName = "branch-end";
newLatestBranchCmd.commandName = "branch-end-last";
newLatestBranchCmd.commandOrAliasName = "branch-end-last";
/**
* it's fine if the new "latest branch" does not have
* a remote set yet, because `--push` handles that,
* and we regardless wouldn't want to mess anything
* in the remote until `--push` is used.
*/
}
const branchesWhoNeedLocalCheckout: BranchWhoNeedsLocalCheckout[] = [];
for (const cmd of goodCommands) {
if (cmd.rebaseKind === "regular") {
regularRebaseTodoLines.push(cmd.fullLine);
} else if (cmd.rebaseKind === "stacked") {
if (cmd.commandName === "branch-end-new") {
await createBranchForCommand(cmd as any); // TODO TS
} else if (cmd.commandName === "branch-end-new-from-remote") {
const b = parseBranchWhichNeedsLocalCheckout(cmd.targets!); // TODO TS NARROWER TYPES
branchesWhoNeedLocalCheckout.push(b);
}
} else {
assertNever(cmd);
}
}
checkoutRemotePartialBranchesLocally(
repo, //
currentBranch,
branchesWhoNeedLocalCheckout
);
setupPostRewriteHookFor("git-stacked-rebase", {
dotGitDirPathForInstallingTheHook: dotGitDirPath,
rewrittenListOutputDirPathThatWillBeInsideDotGitDir: path.basename(pathToStackedRebaseDirInsideDotGit),
});
/**
* libgit2's git rebase is sadly not very powerful
* and quite outdated...
* (checked C version too - same story).
*
*/
const regularRebaseTodo: string = regularRebaseTodoLines.join("\n") + "\n";
log({
regularRebaseTodo,
pathToRegularRebaseTodoFile,
});
const getCurrentCommit = (): Promise<string> => repo.getHeadCommit().then((c) => c.sha());
const commitShaOfCurrentCommit: string = await getCurrentCommit();
// /**
// * too bad libgit2 is limited. oh well, i've seen worse.
// *
// * this passes it off to the user.
// *
// * they'll come back to us once they're done,
// * with --apply or whatever.
// *
// */
// execSyncInRepo(`${options.gitCmd} rebase --continue`);
const preparedRegularRebaseTodoFile = path.join(
pathToStackedRebaseDirInsideDotGit,
filenames.gitRebaseTodo + ".ready"
);
fs.writeFileSync(preparedRegularRebaseTodoFile, regularRebaseTodo);
const editorScript = `\
#!/usr/bin/env bash
mv -f "${preparedRegularRebaseTodoFile}" "${pathToRegularRebaseTodoFile}"
`;
const editorScriptPath: string = path.join(dotGitDirPath, "editorScript.doActualRebase.sh");
fs.writeFileSync(editorScriptPath, editorScript, { mode: "777" });
const commitOfInitialBranch: Git.Oid = await referenceToOid(initialBranch); // bb
const commitOfCurrentBranch: Git.Oid = await referenceToOid(currentBranch);
// https://stackoverflow.com/a/1549155/9285308
const latestCommitOfOursThatInitialBranchAlreadyHas: Git.Oid = await Git.Merge.base(
repo, //
commitOfInitialBranch,
commitOfCurrentBranch
);
execSyncInRepo(
[
options.gitCmd, //
"rebase",
"--interactive",
latestCommitOfOursThatInitialBranchAlreadyHas.tostrS(),
"--onto",
initialBranch.name(),
options.gpgSign ? "--gpg-sign" : "",
].join(" "),
{
env: {
// https://git-scm.com/docs/git-rebase#Documentation/git-rebase.txt-sequenceeditor
GIT_SEQUENCE_EDITOR: editorScriptPath,
},
}
);
/**
* will need to apply, unless proven otherwise
*/
fs.writeFileSync(path.join(pathToStackedRebaseDirInsideDotGit, filenames.willNeedToApply), "");
/**
* part 2 of "the different ways to launch git rebase"
*/
execSyncInRepo(`${options.gitCmd} rebase --continue`);
/**
* if the rebase finishes and ONLY THEN EXITS,
* it's fine and we continue.
*
* otherwise, there was some commands that made the git rebase exit
* in order to allow the user to perform actions
* (i.e. break, edit),
* and thus the `execSync` command will exit and if we ran,
* we'd run without the actual rebase having finished,
*
* so the information would be incomplete
* and we'd cause other actions that will further f it up.
*
* thus, to avoid this, we exit ourselves if the regular rebase
* is still in progress.
*
* ---
*
* note: we would not have to deal with this if we implemented git rebase ourselves here,
* but that'd be a lot of work + maintainability,
* + also we'd need to
*
* edit: wait nvm, we'd fall into the same issues in the same exact scenarios
* (because we are interactive, but break off as soon as need manual input from user
* and cannot get it without exiting),
* so no, this is a given then.
*
*/
// taken from "part 1" from "canAndShouldBeApplying" from below,
// though using the actual (regular) rebase folder instead of ours
const isRegularRebaseStillInProgress: boolean = fs.existsSync(
path.join(pathToRegularRebaseDirInsideDotGit, filenames.rewrittenList)
);
if (isRegularRebaseStillInProgress) {
log("regular git rebase process exited, but rebase is not finished yet - exiting outselves.");
return;
} else {
log("regular git rebase process exited, and rebase is finished - continuing our execution.");
}
// await repo.continueRebase(undefined as any, () => {
// //
// });
// await repo.continueRebase(Git.Signature.create(Git.CredUsername.name(), (await Git));
// const rebase: Git.Rebase = await Git.Rebase.open(repo);
// console.log({ rebase });
// let i = 0;
// while (++i < 30) {
// const gitOp: Git.RebaseOperation = await rebase.next();
// noop(gitOp);
// }
// const rebase = await Git.Rebase.init()
const commitShaOfNewCurrentCommit = await getCurrentCommit();
const rebaseChangedLocalHistory: boolean = commitShaOfCurrentCommit !== commitShaOfNewCurrentCommit;
log({
rebaseChangedLocalHistory, //
commitShaOfOldCurrentCommit: commitShaOfCurrentCommit,
commitShaOfNewCurrentCommit,
});
fs.unlinkSync(path.join(pathToStackedRebaseDirInsideDotGit, filenames.willNeedToApply));
if (rebaseChangedLocalHistory) {
markThatNeedsToApply(pathToStackedRebaseDirInsideDotGit);
} else {
// /**
// * TODO `unmarkThatNeedsToApply` (NOT the same as `markThatApplied`!)
// */
// // unmarkThatNeedsToApply();
}
/**
* since we're invoking `git rebase --continue` directly (above),
* we do not have the control over it.
*
* meaning that in case it's the very first rebase,
* the `rewritten-list` in `.git/rebase-merge/`
* (the actual git-rebase, not ours)
* file is not generated yet,
*
* and since we depend on the `git rebase --continue` (the regular rebase)
* to generate the `rewritten-list` file,
* we explode trying to read the file if we try to --apply below.
*
* ---
*
* edit: oh wait nvm, it's potentially any rebase that has
* `break` or `edit` or similar right??
*
* because if the git-rebase-todo file has `break` or `edit`
* or similar commands that make `git rebase --continue` exit
* before it's fully completed, (my theory now is that) our code here proceeds
* and tries to --apply, but again the rewritten-list file
* doesn't exist yet, so we blow up.
*
* ---
*
* let's try to account for only the 1st scenario first.
* TODO implement directly in `--apply`
* (e.g. if user calls `gitStackedRebase` again, while still in a rebase)
*
* upd: ok let's also do the 2nd one because it's useless otherwise
*
*/
const canAndShouldBeApplying: boolean =
/** part 1 */ fs.existsSync(path.join(pathToStackedRebaseDirInsideDotGit, filenames.rewrittenList)) &&
/** part 2 (incomplete?) */ !fs.existsSync(pathToRegularRebaseDirInsideDotGit) &&
/** part 2 (complete?) (is this even needed?) */ goodCommands.every(
(cmd) => !namesOfRebaseCommandsThatMakeRebaseExitToPause.includes(cmd.commandName)
);
if (canAndShouldBeApplying) {
await applyIfNeedsToApply({
isMandatoryIfMarkedAsNeeded: false,
repo,
pathToStackedRebaseTodoFile,
pathToStackedRebaseDirInsideDotGit, //
rootLevelCommandName: "--apply",
gitCmd: options.gitCmd,
autoApplyIfNeeded: options.autoApplyIfNeeded,
config,
initialBranch,
currentBranch,
askQuestion,
});
}
/**
* execute the post-stacked-rebase hook if exists.
* will only happen if the rebase went thru, and in our control.
*/
const postStackedRebaseHook: string = path.join(dotGitDirPath, "hooks", filenames.postStackedRebaseHook);
if (fs.existsSync(postStackedRebaseHook)) {
execSyncInRepo(postStackedRebaseHook);
}
return;
} catch (e) {
throw e; // TODO FIXME - no try/catch at all?
}
}
export function parsePrereqs(specifiedOptions: SpecifiableGitStackedRebaseOptions) {
const potentialRepoPath = specifiedOptions.gitDir || getDefaultResolvedOptions().gitDir;
const gitCmd = specifiedOptions.gitCmd || getDefaultResolvedOptions().gitCmd;
const execSyncInRepo = createExecSyncInRepo(potentialRepoPath);
const repoRootDir: string = execSyncInRepo(`${gitCmd} rev-parse --show-toplevel`, { encoding: "utf-8", stdio: "pipe" }).toString().trim();
return {
repoRootDir,
execSyncInRepo,
}
}
export function referenceToOid(ref: Git.Reference): Promise<Git.Oid> {
return ref.peel(Git.Object.TYPE.COMMIT).then((x) => x.id());
}
export async function createInitialEditTodoOfGitStackedRebase(
repo: Git.Repository, //
initialBranch: Git.Reference,
currentBranch: Git.Reference,
pathToRebaseTodoFile: string,
autoSquash: boolean,
repairFlag: boolean,
askQuestion: AskQuestion,
getCommitsWithBranchBoundaries: () => Promise<CommitAndBranchBoundary[]> = () =>
getWantedCommitsWithBranchBoundariesOurCustomImpl(
repo, //
initialBranch,
currentBranch
)
): Promise<void> {
// .catch(logErr);
// if (!bb) {
// console.error();
// return;
// }
let commitsWithBranchBoundaries: CommitAndBranchBoundary[] = await getCommitsWithBranchBoundaries();
// /**
// * TODO: FIXME HACK for nodegit rebase
// */
// const p = path.join(repo.path(), "rebase-merge");
// fs.mkdirSync(p, { recursive: true });
// commitsWithBranchBoundaries.map((c, i) => {
// const f = path.join(p, `cmt.${i + 2}`);
// fs.writeFileSync(f, c.commit.sha() + "\n");
// });
// const last = commitsWithBranchBoundaries.length - 1;
// const ff = path.join(p, `cmt.${last + 2}`);
// fs.writeFileSync(ff, `${commitsWithBranchBoundaries[last].commit.sha()}`);
noop(commitsWithBranchBoundaries);
if (autoSquash && repairFlag) {
/**
* TODO: if autoSquash, but if explicit, instead of implicit via config,
* then throw
*
* or just verify when parsing opts
*/
// throw new Termination(`\nincompatible options: autoSquash and repair.\n\n`);
}
if (autoSquash) {
commitsWithBranchBoundaries = await autosquash(repo, commitsWithBranchBoundaries);
}
if (repairFlag) {
await repair({ initialBranch, currentBranch, askQuestion, commitsWithBranchBoundaries, repo });
}
const rebaseTodo = commitsWithBranchBoundaries
.map(({ commit, commitCommand, branchEnd }, i) => {
if (i === 0) {
assert(!!branchEnd?.length, `very first commit has a branch (${commit.sha()}).`);
assert.strictEqual(branchEnd.length, 1, "must be only a single initial branch");
// return [];
return [
// `pick ${commit.sha()} ${commit.summary()}`,
/**
* TODO refs/REMOTES/* instead of refs/HEADS/*
*/
`branch-end-initial ${branchEnd[0].name()}`, //
];
}
if (i === commitsWithBranchBoundaries.length - 1) {
assert(!!branchEnd?.length, `very last commit has a branch. sha = ${commit.sha()}`);
return [
`${commitCommand} ${commit.sha()} ${commit.summary()}`,
`branch-end-last ${currentBranch.name()}`, //
];
}
if (branchEnd?.length) {
return [
`${commitCommand} ${commit.sha()} ${commit.summary()}`,
...branchEnd.map((branch) => {
/**
* TODO handle if multiple remotes exist & have the same branch
* in such a case, ask the user which remote to use
* (by default for all branches, and/or allow customizing for each one? tho rare)
*
* here's a hint that git gives in this situation (& exits w/ 1 so good that errors)
*
* ```
* hint: If you meant to check out a remote tracking branch on, e.g. 'origin',
* hint: you can do so by fully qualifying the name with the --track option:
* hint:
* hint: git checkout --track origin/<name>
* hint:
* hint: If you'd like to always have checkouts of an ambiguous <name> prefer
* hint: one remote, e.g. the 'origin' remote, consider setting
* hint: checkout.defaultRemote=origin in your config.
* fatal: 'fork' matched multiple (2) remote tracking branches
* ```
*
*
* OR, do not do anything, because the user can edit the remote
* in the git-rebase-todo file when the editor opens.
*
* so maybe instead have some option for choosing the default remote,
* but otherwise everything's fine already.
*
* probably can respect the `checkout.defaultRemote` config var
* (see man git-checkout)
*
*
*/
if (branch.isRemote() || branch.name().startsWith("refs/remotes/")) {
const wantedLocalBranchName: string = branch
.name()
.replace(removeRemoteRegex, "");
const remoteName: string = branch.name().match(removeRemoteRegex)![1];
return encodeCmdToLine({
wantedLocalBranchName,
remoteName,
fullNameOfBranchWithRemote: getFullNameOfBranchWithRemote({ wantedLocalBranchName, remoteName })
})
} else {
return `branch-end ${branch.name()}`;
}
}), //
];
}
return [
`${commitCommand} ${commit.sha()} ${commit.summary()}`, //
];
})
.filter((xs) => xs.length)
.flat();
fs.writeFileSync(pathToRebaseTodoFile, rebaseTodo.join("\n"));
return;
}
export type BranchBoundaryWithCommits = {
commits: [Git.Commit, RegularRebaseEitherCommandOrAlias][];
branchEnds: Git.Reference[];
};
export function groupByBranchBoundaries(commitsWithBranchBoundaries: CommitAndBranchBoundary[]): BranchBoundaryWithCommits[] {
const grouped: BranchBoundaryWithCommits[] = [];
let commitsForBranch: BranchBoundaryWithCommits["commits"] = []
for (let i = 0; i < commitsWithBranchBoundaries.length; i++) {
const curr = commitsWithBranchBoundaries[i]
if (curr.branchEnd?.length) {
grouped.push({
commits: commitsForBranch,
branchEnds: curr.branchEnd,
})
commitsForBranch = []
} else {
commitsForBranch.push([curr.commit, curr.commitCommand])
}
}
return grouped;
};
export type BranchWhoNeedsLocalCheckout = {
wantedLocalBranchName: string; //
remoteName: string;
fullNameOfBranchWithRemote: string;
};
/**
* expects targets from the format of "branch-end-new-from-remote"
* TODO TS NARROWER TYPES (specific targets for each type of cmd)
*/
export function parseBranchWhichNeedsLocalCheckout(targets: NonNullable<Targets>): BranchWhoNeedsLocalCheckout {
const wantedLocalBranchName: string = targets[0];
const remoteAndRemoteBranchName: string = targets[1];
const remoteName: string = remoteAndRemoteBranchName.split("/")[0];
const fullNameOfBranchWithRemote: string = getFullNameOfBranchWithRemote({ fullNameOfBranchWithRemote: remoteAndRemoteBranchName });
return {
wantedLocalBranchName,
remoteName,
fullNameOfBranchWithRemote,
}
}
function getFullNameOfBranchWithRemote(b: Pick<BranchWhoNeedsLocalCheckout, "fullNameOfBranchWithRemote"> | Pick<BranchWhoNeedsLocalCheckout, "wantedLocalBranchName" | "remoteName">): string {
return (
"fullNameOfBranchWithRemote" in b
? b.fullNameOfBranchWithRemote
: b.remoteName + "/" + b.wantedLocalBranchName
);
}
// TODO RENAME
export function encodeCmdToLine(b: BranchWhoNeedsLocalCheckout) {
return `branch-end-new-from-remote ${b.wantedLocalBranchName} ${b.fullNameOfBranchWithRemote}`;
}
// TODO RENAME
export function decodeLineToCmd(line: string): BranchWhoNeedsLocalCheckout {
// TODO TS NARROWER TYPES
const targets: NonNullable<Targets> = stackedRebaseCommands["branch-end-new-from-remote"].parseTargets(getParseTargetsCtxFromLine(line))!
return parseBranchWhichNeedsLocalCheckout(targets);
}
function checkoutRemotePartialBranchesLocally(
repo: Git.Repository, //
currentBranch: Git.Reference,
branchesWhoNeedLocalCheckout: BranchWhoNeedsLocalCheckout[]