-
Notifications
You must be signed in to change notification settings - Fork 114
/
Copy pathsession.js
419 lines (358 loc) · 10.3 KB
/
session.js
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
import path from 'node:path';
import fs from 'node:fs';
import { getMergedConfig, getNcuDir } from './config.js';
import { readJson, writeJson, readFile, writeFile } from './file.js';
import {
runAsync, runSync, forceRunAsync
} from './run.js';
import {
shortSha
} from './utils.js';
const APPLYING = 'APPLYING';
const STARTED = 'STARTED';
const AMENDING = 'AMENDING';
export default class Session {
constructor(cli, dir, prid, argv, warnForMissing = true) {
this.cli = cli;
this.dir = dir;
this.prid = prid;
this.config = { ...getMergedConfig(this.dir), ...argv };
if (warnForMissing) {
const { upstream, owner, repo } = this;
if (this.warnForMissing()) {
throw new Error('Failed to create new session');
}
const upstreamHref = runSync('git', [
'config', '--get',
`remote.${upstream}.url`]).trim();
if (!new RegExp(`${owner}/${repo}(?:.git)?$`).test(upstreamHref)) {
cli.warn('Remote repository URL does not point to the expected ' +
`repository ${owner}/${repo}`);
cli.setExitCode(1);
}
}
}
get session() {
return readJson(this.sessionPath);
}
get gitDir() {
return path.join(this.dir, '.git');
}
get ncuDir() {
return getNcuDir(this.dir);
}
get argv() {
// TODO(joyeecheung): remove this and make argv an object
return {
owner: this.owner,
repo: this.repo,
upstream: this.upstream,
branch: this.branch,
readme: this.readme,
waitTimeSingleApproval: this.waitTimeSingleApproval,
waitTimeMultiApproval: this.waitTimeMultiApproval,
updateDeprecations: this.updateDeprecations,
ciType: this.ciType,
prid: this.prid,
checkCI: this.checkCI
};
}
get sessionPath() {
return path.join(this.ncuDir, 'land');
}
get owner() {
return this.config.owner || 'nodejs';
}
get repo() {
return this.config.repo || 'node';
}
get upstream() {
return this.config.upstream;
}
get branch() {
return this.config.branch;
}
get username() {
return this.config.username;
}
get readme() {
return this.config.readme;
}
get waitTimeSingleApproval() {
return this.config.waitTimeSingleApproval;
}
get waitTimeMultiApproval() {
return this.config.waitTimeMultiApproval;
}
get ciType() {
return this.config.ciType || 'nodejs';
}
get pullName() {
return `${this.owner}/${this.repo}/pulls/${this.prid}`;
}
get pullDir() {
return path.join(this.ncuDir, `${this.prid}`);
}
get updateDeprecations() {
return this.config.updateDeprecations || 'yes';
}
startLanding() {
writeJson(this.sessionPath, {
state: STARTED,
prid: this.prid,
config: this.config
});
}
// TODO(joyeecheung): more states
// - STARTED (fetching metadata)
// - DOWNLOADING (downloading the patch)
// - PATCHING (git am)
// - AMENDING (git rebase or just amending messages)
// - DONE
startApplying() {
this.updateSession({
state: APPLYING
});
}
startAmending() {
this.updateSession({
state: AMENDING
});
}
cleanFiles() {
let sess;
try {
sess = this.session;
} catch (err) {
return fs.rmSync(this.sessionPath, { recursive: true, force: true });
}
if (sess.prid && sess.prid === this.prid) {
fs.rmSync(this.pullDir, { recursive: true, force: true });
}
fs.rmSync(this.sessionPath, { recursive: true, force: true });
}
get statusPath() {
return path.join(this.pullDir, 'status');
}
get status() {
return readJson(this.statusPath);
}
get metadataPath() {
return path.join(this.pullDir, 'metadata');
}
get metadata() {
return readFile(this.metadataPath);
}
get commitInfoPath() {
return path.join(this.pullDir, 'commit-info');
}
get commitInfo() {
return readJson(this.commitInfoPath);
}
getMessagePath(rev) {
return path.join(this.pullDir, `${shortSha(rev)}.COMMIT_EDITMSG`);
}
updateSession(update) {
const old = this.session;
writeJson(this.sessionPath, Object.assign(old, update));
}
saveStatus(status) {
writeJson(this.statusPath, status);
}
saveMetadata(status) {
writeFile(this.metadataPath, status.metadata);
}
saveCommitInfo(commitInfo) {
writeJson(this.commitInfoPath, commitInfo);
}
saveMessage(rev, message) {
const file = this.getMessagePath(rev);
writeFile(file, message);
return file;
}
hasStarted() {
return !!this.session.prid && this.session.prid === this.prid;
}
isApplying() {
return this.session.state === APPLYING;
}
readyToAmend() {
if (this.session.state === AMENDING) {
return true;
} else if (this.isApplying()) {
return !this.cherryPickInProgress();
} else {
return false;
}
}
readyToFinal() {
if (this.amInProgress() || this.cherryPickInProgress()) {
return false; // git am/rebase in progress
}
return this.session.state === AMENDING;
}
// Refs: https://github.com/git/git/blob/99de064/git-rebase.sh#L208-L228
// XXX: This may be unused at this point?
amInProgress() {
const amPath = path.join(this.gitDir, 'rebase-apply', 'applying');
return fs.existsSync(amPath);
}
rebaseInProgress() {
if (this.amInProgress()) {
return false;
}
const normalRebasePath = path.join(this.gitDir, 'rebase-apply');
const mergeRebasePath = path.join(this.gitDir, 'rebase-merge');
return fs.existsSync(normalRebasePath) || fs.existsSync(mergeRebasePath);
}
cherryPickInProgress() {
const cpPath = path.join(this.gitDir, 'CHERRY_PICK_HEAD');
return fs.existsSync(cpPath);
}
restore() {
const sess = this.session;
if (sess.prid) {
this.prid = sess.prid;
this.config = sess.config;
}
return this;
}
async tryAbortAm() {
const { cli } = this;
if (!this.amInProgress()) {
return cli.ok('No git am in progress');
}
const shouldAbortAm = await cli.prompt(
'Abort previous git am sessions?');
if (shouldAbortAm) {
await forceRunAsync('git', ['am', '--abort']);
cli.ok('Aborted previous git am sessions');
}
}
async tryAbortCherryPick() {
const { cli } = this;
if (!this.cherryPickInProgress()) {
return cli.ok('No git cherry-pick in progress');
}
const shouldAbortCherryPick = await cli.prompt(
'Abort previous git cherry-pick sessions?');
if (shouldAbortCherryPick) {
await forceRunAsync('git', ['cherry-pick', '--abort']);
cli.ok('Aborted previous git cherry-pick sessions');
}
}
async tryAbortRebase() {
const { cli } = this;
if (!this.rebaseInProgress()) {
return cli.ok('No git rebase in progress');
}
const shouldAbortRebase = await cli.prompt(
'Abort previous git rebase sessions?');
if (shouldAbortRebase) {
await forceRunAsync('git', ['rebase', '--abort']);
cli.ok('Aborted previous git rebase sessions');
}
}
async tryResetBranch() {
const { cli, upstream, branch } = this;
await this.tryAbortCherryPick();
await this.tryAbortAm();
await this.tryAbortRebase();
const branchName = `${upstream}/${branch}`;
const shouldResetHead = await cli.prompt(
`Do you want to try reset the local ${branch} branch to ${branchName}?`);
if (shouldResetHead) {
await this.tryResetHead();
}
}
getCurrentRev() {
return runSync('git', ['rev-parse', 'HEAD']).trim();
}
getCurrentBranch() {
return runSync('git', ['rev-parse', '--abbrev-ref', 'HEAD']).trim();
}
getUpstreamHead() {
const { upstream, branch } = this;
return runSync('git', ['rev-parse', `${upstream}/${branch}`]).trim();
}
getStrayCommits(verbose) {
const { upstream, branch } = this;
const ref = `${upstream}/${branch}...HEAD`;
const gitCmd = verbose
? ['log', '--oneline', '--reverse', ref]
: ['rev-list', '--reverse', ref];
const revs = runSync('git', gitCmd).trim();
return revs ? revs.split('\n') : [];
}
async tryResetHead() {
const { cli, upstream, branch } = this;
const branchName = `${upstream}/${branch}`;
cli.startSpinner(`Bringing ${branchName} up to date...`);
await runAsync('git', ['fetch', upstream, branch]);
cli.stopSpinner(`${branchName} is now up-to-date`);
const stray = this.getStrayCommits(true);
if (!stray.length) {
return;
}
cli.log(`${branch} is out of sync with ${branchName}. ` +
'Mismatched commits:\n' +
` - ${stray.join('\n - ')}`);
const shouldReset = await cli.prompt(`Reset to ${branchName}?`);
if (shouldReset) {
await runAsync('git', ['reset', '--hard', branchName]);
cli.ok(`Reset to ${branchName}`);
}
}
warnForMissing() {
const { upstream, branch, cli } = this;
const missing = !upstream || !branch;
if (!branch) {
cli.warn('You have not told git-node what branch you are trying' +
' to land commits on.');
cli.separator();
cli.info(
'For example, if your want to land commits on the ' +
'`main` branch, you can run:\n\n' +
' $ ncu-config set branch main');
cli.separator();
cli.setExitCode(1);
}
if (!upstream) {
cli.warn('You have not told git-node the remote you want to sync with.');
cli.separator();
cli.info(
'For example, if your remote pointing to nodejs/node is' +
' `remote-upstream`, you can run:\n\n' +
' $ ncu-config set upstream remote-upstream');
cli.separator();
cli.setExitCode(1);
}
return missing;
}
warnForWrongBranch() {
const { branch, cli } = this;
const rev = this.getCurrentBranch();
if (rev === 'HEAD') {
cli.warn(
'You are in detached HEAD state. Please run git-node on a valid ' +
'branch');
cli.setExitCode(1);
return true;
}
if (rev === branch) {
return false;
}
cli.warn(
`You are running git-node-land on \`${rev}\`,\n but you have` +
` configured \`${branch}\` to be the branch to land commits.`);
cli.separator();
cli.info(
`You can switch to \`${branch}\` with \`git checkout ${branch}\`, or\n` +
' reconfigure the target branch with:\n\n' +
` $ ncu-config set branch ${rev}`);
cli.separator();
cli.setExitCode(1);
return true;
// TODO warn if backporting onto master branch
}
}