-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
apply.ts
293 lines (257 loc) · 9.01 KB
/
apply.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
import fs from "fs";
import path from "path";
import Git from "nodegit";
import { combineRewrittenLists } from "./git-reconcile-rewritten-list/combineRewrittenLists";
import { AskQuestion, question, Questions } from "./util/createQuestion";
import { isDirEmptySync } from "./util/fs";
import { Termination } from "./util/error";
import { log } from "./util/log";
import { filenames } from "./filenames";
import { configKeys } from "./config";
// eslint-disable-next-line import/no-cycle
import {
BranchSequencerBase, //
branchSequencer,
ActionInsideEachCheckedOutBranch,
BranchSequencerArgsBase,
BehaviorOfGetBranchBoundaries,
} from "./branchSequencer";
export const apply: BranchSequencerBase = (args) =>
branchSequencer({
...args,
actionInsideEachCheckedOutBranch: defaultApplyAction,
// callbackAfterDone: defaultApplyCallback,
delayMsBetweenCheckouts: 0,
behaviorOfGetBranchBoundaries: BehaviorOfGetBranchBoundaries["parse-from-not-yet-applied-state"],
reverseCheckoutOrder: false,
}).then(
(ret) => (markThatApplied(args.pathToStackedRebaseDirInsideDotGit), ret) //
);
const defaultApplyAction: ActionInsideEachCheckedOutBranch = async ({
repo, //
gitCmd,
// targetBranch,
targetCommitSHA,
isLatestBranch,
execSyncInRepo,
}) => {
const commit: Git.Commit = await Git.Commit.lookup(repo, targetCommitSHA);
log("will reset to commit", commit.sha(), "(" + commit.summary() + ")");
log({ isLatestBranch });
if (!isLatestBranch) {
/**
* we're not using libgit's `Git.Reset.reset` here, because even after updating
* to the latest version of nodegit (& they to libgit),
* it still chokes when a user has specified an option `merge.conflictStyle` as `zdiff3`
* (a newly added one in git, but it's been added like 4 months ago)
*/
// await Git.Reset.reset(repo, commit, Git.Reset.TYPE.HARD, {});
execSyncInRepo(`${gitCmd} reset --hard ${commit.sha()}`);
// if (previousTargetBranchName) {
// execSyncInRepo(`/usr/bin/env git rebase ${previousTargetBranchName}`);
// }
}
};
export const getBackupPathOfPreviousStackedRebase = (pathToStackedRebaseDirInsideDotGit: string): string =>
pathToStackedRebaseDirInsideDotGit + ".previous";
export async function applyIfNeedsToApply({
repo,
pathToStackedRebaseTodoFile,
pathToStackedRebaseDirInsideDotGit, //
autoApplyIfNeeded,
isMandatoryIfMarkedAsNeeded,
config,
askQuestion = question,
...rest
}: BranchSequencerArgsBase & {
/**
* i.e., sometimes a) we need the `--apply` to go thru,
* and sometimes b) it's "resumable" on the next run,
* i.e. we'd prefer to apply right now,
* but it's fine if user does not apply now,
* because `--apply` is resumable[1],
* and on the next run of stacked rebase, user will be forced to apply anyway.
*
* [1] resumable, unless user runs into some edge case where it no longer is.
* TODO: work out when this happens & handle better.
*/
isMandatoryIfMarkedAsNeeded: boolean;
autoApplyIfNeeded: boolean; //
config: Git.Config;
askQuestion: AskQuestion;
}): Promise<void> {
const needsToApply: boolean = doesNeedToApply(pathToStackedRebaseDirInsideDotGit);
if (!needsToApply) {
return;
}
if (isMandatoryIfMarkedAsNeeded) {
/**
* is marked as needed to apply,
* and is mandatory -- try to get a confirmation that it is ok to apply.
*/
const userAllowedToApply =
autoApplyIfNeeded ||
(await askYesNoAlways({
questionToAsk: Questions.need_to_apply_before_continuing, //
askQuestion,
onAllowAlways: async () => {
await config.setBool(configKeys.autoApplyIfNeeded, 1);
},
}));
if (!userAllowedToApply) {
const msg = "\ncannot continue without mandatory --apply. Exiting.\n";
throw new Termination(msg);
} else {
await apply({
repo,
pathToStackedRebaseTodoFile,
pathToStackedRebaseDirInsideDotGit, //
...rest,
});
return;
}
} else {
/**
* is marked as needed to apply,
* but performing the apply is NOT mandatory.
*
* thus, do NOT ask user if should apply -- only infer from config.
*/
if (autoApplyIfNeeded) {
await apply({
repo,
pathToStackedRebaseTodoFile,
pathToStackedRebaseDirInsideDotGit, //
...rest,
});
return;
} else {
/**
* not mandatory, thus do nothing.
*/
}
}
}
export type AskYesNoAlwaysCtx = {
questionToAsk: Parameters<AskQuestion>[0];
askQuestion: AskQuestion;
onAllowAlways?: () => void | Promise<void>;
};
export const askYesNoAlways = async ({
questionToAsk, //
askQuestion = question,
onAllowAlways = () => {},
}: AskYesNoAlwaysCtx): Promise<boolean> => {
const answer: string = await askQuestion(questionToAsk, { cb: (ans) => ans.trim().toLowerCase() });
const userAllowed: boolean = ["y", "yes", ""].includes(answer);
const userAllowedAlways: boolean = ["a", "always"].includes(answer);
if (userAllowedAlways) {
await onAllowAlways();
}
const allowed = userAllowed || userAllowedAlways;
return allowed;
};
const getPaths = (
pathToStackedRebaseDirInsideDotGit: string //
) =>
({
rewrittenListPath: path.join(pathToStackedRebaseDirInsideDotGit, filenames.rewrittenList),
needsToApplyPath: path.join(pathToStackedRebaseDirInsideDotGit, filenames.needsToApply),
appliedPath: path.join(pathToStackedRebaseDirInsideDotGit, filenames.applied),
gitRebaseTodoPath: path.join(pathToStackedRebaseDirInsideDotGit, filenames.gitRebaseTodo),
} as const);
export const markThatNeedsToApply = (
pathToStackedRebaseDirInsideDotGit: string //
): void =>
[getPaths(pathToStackedRebaseDirInsideDotGit)].map(
({ rewrittenListPath, needsToApplyPath, appliedPath }) => (
fs.existsSync(rewrittenListPath)
? fs.copyFileSync(rewrittenListPath, needsToApplyPath)
: fs.writeFileSync(needsToApplyPath, ""),
fs.existsSync(appliedPath) && fs.unlinkSync(appliedPath),
void 0
)
)[0];
export const isMarkedThatNeedsToApply = (pathToStackedRebaseDirInsideDotGit: string): boolean => {
const pathToMark: string = getPaths(pathToStackedRebaseDirInsideDotGit).needsToApplyPath;
return fs.existsSync(pathToMark);
};
export const markThatApplied = (pathToStackedRebaseDirInsideDotGit: string): void =>
[getPaths(pathToStackedRebaseDirInsideDotGit)].map(
({ rewrittenListPath, needsToApplyPath, gitRebaseTodoPath }) => (
fs.existsSync(needsToApplyPath) && fs.unlinkSync(needsToApplyPath), //
/**
* need to check if the `rewrittenListPath` exists,
* because even if it does not, then the "apply" can still go through
* and "apply", by using the already .applied file, i.e. do nothing.
*
* TODO just do not run "apply" if the file doesn't exist?
* or is there a case where it's useful still?
*
*/
// fs.existsSync(rewrittenListPath) && fs.renameSync(rewrittenListPath, appliedPath),
// // fs.existsSync(rewrittenListPath)
// // ? fs.renameSync(rewrittenListPath, appliedPath)
// // : !fs.existsSync(appliedPath) &&
// // (() => {
// // throw new Error("applying uselessly");
// // })(),
fs.existsSync(rewrittenListPath) && fs.unlinkSync(rewrittenListPath),
fs.existsSync(gitRebaseTodoPath) && fs.unlinkSync(gitRebaseTodoPath),
isDirEmptySync(pathToStackedRebaseDirInsideDotGit) &&
fs.rmdirSync(pathToStackedRebaseDirInsideDotGit, { recursive: true }),
void 0
)
)[0];
const doesNeedToApply = (pathToStackedRebaseDirInsideDotGit: string): boolean => {
const { rewrittenListPath, needsToApplyPath, appliedPath } = getPaths(pathToStackedRebaseDirInsideDotGit);
if (!fs.existsSync(rewrittenListPath)) {
/**
* nothing to apply
*/
return false;
}
const needsToApplyPart1: boolean = fs.existsSync(needsToApplyPath);
if (needsToApplyPart1) {
return true;
}
const needsToApplyPart2: boolean = fs.existsSync(appliedPath)
? /**
* check if has been applied, but that apply is outdated
*/
!fs.readFileSync(appliedPath).equals(fs.readFileSync(rewrittenListPath))
: false;
return needsToApplyPart2;
};
export function readRewrittenListNotAppliedOrAppliedOrError(repoPath: string): {
pathOfRewrittenList: string;
pathOfRewrittenListApplied: string;
rewrittenListRaw: string;
/**
* you probably want these:
*/
combinedRewrittenList: string;
combinedRewrittenListLines: string[];
} {
const pathOfRewrittenList: string = path.join(repoPath, "stacked-rebase", filenames.rewrittenList);
const pathOfRewrittenListApplied: string = path.join(repoPath, "stacked-rebase", filenames.applied);
/**
* not combined yet
*/
let rewrittenListRaw: string;
if (fs.existsSync(pathOfRewrittenList)) {
rewrittenListRaw = fs.readFileSync(pathOfRewrittenList, { encoding: "utf-8" });
} else if (fs.existsSync(pathOfRewrittenListApplied)) {
rewrittenListRaw = fs.readFileSync(pathOfRewrittenListApplied, { encoding: "utf-8" });
} else {
throw new Error(`rewritten-list not found neither in ${pathOfRewrittenList}, nor in ${pathOfRewrittenListApplied}`);
}
const { combinedRewrittenList } = combineRewrittenLists(rewrittenListRaw);
return {
pathOfRewrittenList,
pathOfRewrittenListApplied,
rewrittenListRaw,
combinedRewrittenList,
combinedRewrittenListLines: combinedRewrittenList.split("\n").filter((line) => !!line),
};
}