-
Notifications
You must be signed in to change notification settings - Fork 42
/
main.ts
732 lines (660 loc) · 24.7 KB
/
main.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
/* eslint-disable max-len */
import * as fse from 'fs-extra';
import * as readline from 'readline';
import {
isAbsolute, join, resolve, relative, normalize,
} from './src/path';
import { Index } from './src/index';
import { Commit } from './src/commit';
import { Reference } from './src/reference';
import {
StatusEntry, FILTER, Repository, RESET, COMMIT_ORDER, REFERENCE_TYPE,
} from './src/repository';
import { TreeDir, TreeEntry, TreeFile } from './src/treedir';
import { IoContext } from './src/io_context';
const program = require('commander');
const chalk = require('chalk');
const drivelist = require('drivelist');
const AggregateError = require('es-aggregate-error');
const versionString = '0.9.3';
function fileMatch(relFilepath: string, relCwd: string, pathPattern: string): boolean {
return pathPattern === '*' || (pathPattern === '.' && relFilepath.startsWith(relCwd)) || pathPattern === relative(relCwd, relFilepath);
}
/**
* Helper function to get an existing or creating a new index.
* @param index Either null/defined, or 'create' or an existing index;
*/
function getIndex(repo: Repository, index: string | null | undefined) {
if (index === 'create') {
const i = repo.createIndex();
console.log(`Created new index: [${i.id}]`);
return i;
}
if (index) {
const i = repo.getIndex(index);
if (!i) {
throw new Error(`unknown index: ${index}`);
}
return i;
}
return repo.ensureMainIndex();
}
/**
* Helper function for additional parsing options. Some CLI commands support passing information
* through stdin or a text-file (e.g. --user-data for commits). If the passed options object
* contains 'input', the options can be loaded from a stdin, otherwise the value is treated as
* a filepath. The content is extracted from the source and applied on top of the 'opts' object.
*
* Example:
* --cmd-arg1: can,be,multiple\nlines\r\n\r\n\r\n\r\n
* --cmd-arg2: random-value
*
* '\r\n\r\n\r\n\r\n' is the delimiter between the passed arguments.
* The payload of the argument must not contain the delimiter, otherwise an error will occur.
*
* @param opts Options passed from the commander.
* @return New options object.
*/
async function parseOptions(opts: any) {
let tmp: string;
if (opts.input) {
if (opts.input === 'stdin') {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
let res: string;
rl.question('', (answer: string) => {
res = answer;
rl.close();
});
tmp = await new Promise<string>((resolve) => {
rl.on('close', () => {
resolve(res);
});
});
} else { // else assumes it is a file-path
const buf: Buffer = fse.readFileSync(opts.input);
tmp = buf.toString();
}
} else {
// no --input set, simply use the options from the command-line
return opts;
}
const splitOpts: string[] = tmp.split('\r\n\r\n\r\n\r\n');
for (const splitOpt of splitOpts) {
if (!splitOpt.startsWith('--')) {
throw new Error("option must start with '--', e.g. --option: value");
}
// '--option:'
const parsed = splitOpt.match(/--([\w-]+):/g);
if (!parsed) {
throw new Error(`option '${parsed}' is invalid`);
}
// '--foo-bar:' ==> 'fooBar'
const parsedOption = parsed[0].substr(2, parsed[0].length - 3)
.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
opts[parsedOption] = splitOpt.substring(parsed[0].length, splitOpt.length)
.replace(/^[\n|\s]*/, '')
.replace(/[\n|\s]*$/, '');
}
return opts;
}
program
.version(versionString)
.description('SnowFS - a fast, scalable version control file storage for graphic files.');
program
.command('init [path] [commondir]')
.option('--debug', 'add more debug information on errors')
.description('initialize a SnowFS repository')
.action(async (path: string, commondir?: string, opts?: any) => {
const repoPath: string = path ?? '.';
try {
await Repository.initExt(repoPath, {
commondir,
additionalConfig: {
creator: 'snowfs-cli',
version: versionString,
},
});
} catch (error) {
if (opts.debug) {
throw error;
} else {
if (error instanceof AggregateError) {
process.stderr.write(`fatal: ${error.errors.map((e) => e.message).join('\n')}`);
} else {
process.stderr.write(`fatal: ${error.message}\n`);
}
process.exit(-1);
}
}
console.log(`Initialized empty SnowFS repository at ${resolve(repoPath)}`);
});
program
.command('rm [path]')
.option('--index [id]', 'use a custom index id')
.option('--debug', 'add more debug information on errors')
.description('Remove files from the working tree and from the index')
.action(async (path: string, opts?: any) => {
try {
const repo = await Repository.open(normalize(process.cwd()));
const filepathAbs: string = isAbsolute(path) ? path : join(repo.workdir(), path);
// important! this fails and throw an error
// if the file is not there! (expected by a unit-test in 9.cli.test)
fse.statSync(filepathAbs);
await IoContext.putToTrash(filepathAbs);
const index: Index = getIndex(repo, opts.index);
index.deleteFiles([path]);
await index.writeFiles();
} catch (error) {
if (opts.debug) {
throw error;
} else {
if (error instanceof AggregateError) {
process.stderr.write(`fatal: ${error.errors.map((e) => e.message).join('\n')}`);
} else {
process.stderr.write(`fatal: ${error.message}\n`);
}
process.exit(-1);
}
}
});
program
.command('add <path>')
.option('--index [id]', 'use a custom index id')
.option('--debug', 'add more debug information on errors')
.description('add file contents to the index')
.action(async (pathPattern: string, opts?: any) => {
try {
const repo = await Repository.open(normalize(process.cwd()));
const statusFiles: StatusEntry[] = await repo.getStatus(FILTER.INCLUDE_MODIFIED | FILTER.INCLUDE_DELETED | FILTER.INCLUDE_UNTRACKED);
const relCwd = relative(repo.workdir(), normalize(process.cwd()));
const index: Index = getIndex(repo, opts.index);
for (const file of statusFiles) {
if (file.isNew() || file.isModified()) {
if (fileMatch(file.path, relCwd, pathPattern)) {
index.addFiles([file.path]);
}
}
}
for (const file of statusFiles) {
if (file.isDeleted()) {
if (fileMatch(file.path, relCwd, pathPattern)) {
index.deleteFiles([file.path]);
}
}
}
await index.writeFiles();
} catch (error) {
if (opts.debug) {
throw error;
} else {
if (error instanceof AggregateError) {
process.stderr.write(`fatal: ${error.errors.map((e) => e.message).join('\n')}`);
} else {
process.stderr.write(`fatal: ${error.message}\n`);
}
process.exit(-1);
}
}
});
program
.command('branch [branch-name] [start-point]')
.option('--debug', 'add more debug information on errors')
.option('--delete', 'delete a branch')
.option('--no-color')
.option('--user-data', 'open standard input to apply user data for commit')
.option('--input <type>', "type can be 'stdin' or {filepath}")
.description('create a new branch')
.action(async (branchName: string, startPoint: string, opts: any) => {
if (opts.noColor) {
chalk.level = 0;
}
try {
opts = await parseOptions(opts);
const repo = await Repository.open(normalize(process.cwd()));
if (opts.delete) {
if (startPoint) {
throw new Error('start-point must be empty');
}
const oldTarget = await repo.deleteReference(REFERENCE_TYPE.BRANCH, branchName);
console.log(`Deleted branch '${branchName}' (was ${oldTarget})`);
} else {
let data = {};
if (opts.userData) {
try {
data = JSON.parse(opts.userData);
} catch (e) {
throw new Error(`invalid user-data: ${e}`);
}
}
await repo.createNewReference(REFERENCE_TYPE.BRANCH, branchName, startPoint, data);
console.log(`A branch '${branchName}' got created.`);
}
} catch (error) {
if (opts.debug) {
throw error;
} else {
if (error instanceof AggregateError) {
process.stderr.write(`fatal: ${error.errors.map((e) => e.message).join('\n')}`);
} else {
process.stderr.write(`fatal: ${error.message}\n`);
}
process.exit(-1);
}
}
});
program
.command('checkout [target]')
.option('--discard-changes', 'force switch and discard changes in workdir')
.option('-k, --keep-changes', "don't reset files in the workdir")
.option('--debug', 'add more debug information on errors')
.option('--no-color')
.option('--user-data', 'open standard input to apply user data for commit')
.option('--input <type>', "type can be 'stdin' or {filepath}")
.description('checkout a commit')
.action(async (target: string | undefined, opts: any) => {
if (opts.noColor) {
chalk.level = 0;
}
try {
opts = await parseOptions(opts);
const repo = await Repository.open(normalize(process.cwd()));
const targetCommit = repo.findCommitByHash(target);
if (!targetCommit) {
if (repo.findCommitByReferenceName(REFERENCE_TYPE.BRANCH, target)) {
throw new Error(`target ${target} seems to be a branch and must be checked out via 'snow switch'`);
}
throw new Error(`cannot find commit '${target}'`);
}
if (target) {
if (opts.discardChanges && opts.keepChanges) {
throw new Error('either --discard-changes or --keep-changes can be used, not both');
} else if (!opts.discardChanges && !opts.keepChanges) {
const statusFiles: StatusEntry[] = await repo.getStatus(FILTER.INCLUDE_UNTRACKED | FILTER.INCLUDE_MODIFIED);
let criticalChanges = 0;
for (const statusFile of statusFiles) {
// new or modified files will abort the checkout to prevent data loss
if (statusFile.isModified()) {
process.stdout.write(`M ${statusFile.path}\n`);
criticalChanges++;
} else if (statusFile.isNew()) {
process.stdout.write(`A ${statusFile.path}\n`);
criticalChanges++;
}
// 'Ignored' or 'Deleted' files can also be ignored, since they could be restored
}
if (criticalChanges > 0) {
throw new Error(`You have local changes to '${target}'; not switching branches.`);
}
}
let reset: RESET = RESET.DETACH; // checkout always results in a detached HEAD
if (!opts.keepChanges) {
reset |= RESET.RESTORE_MODIFIED_ITEMS | RESET.DELETE_NEW_ITEMS | RESET.RESTORE_DELETED_ITEMS;
}
await repo.checkout(target, reset);
}
} catch (error) {
if (opts.debug) {
throw error;
} else {
if (error instanceof AggregateError) {
process.stderr.write(`fatal: ${error.errors.map((e) => e.message).join('\n')}`);
} else {
process.stderr.write(`fatal: ${error.message}\n`);
}
process.exit(-1);
}
}
});
program
.command('index [command]')
.action(async (command: any, opts: any) => {
try {
const repo = await Repository.open(normalize(process.cwd()));
if (command === 'create') {
const index = repo.createIndex();
// the user explicitely asked for an index
// so we must dump the empty index to disk
await index.writeFiles();
console.log(`Created new index: [${index.id}]`);
}
} catch (error) {
if (opts.debug) {
throw error;
} else {
if (error instanceof AggregateError) {
process.stderr.write(`fatal: ${error.errors.map((e) => e.message).join('\n')}`);
} else {
process.stderr.write(`fatal: ${error.message}\n`);
}
process.exit(-1);
}
}
});
program
.command('status')
.option('--no-color')
.option('--output [format]', "currently supported output formats 'json', 'json-pretty'")
.option('--index [id]', 'use a custom index id')
.option('--debug', 'add more debug information on errors')
.description('show the working tree status')
.action(async (opts: any) => {
if (opts.noColor) {
chalk.level = 0;
}
try {
const repo = await Repository.open(normalize(process.cwd()));
const statuses: StatusEntry[] = await repo.getStatus(FILTER.INCLUDE_MODIFIED | FILTER.INCLUDE_DELETED | FILTER.INCLUDE_UNTRACKED | FILTER.INCLUDE_DIRECTORIES);
const newe: StatusEntry[] = [];
const modified: StatusEntry[] = [];
const deleted: StatusEntry[] = [];
for (const status of statuses) {
if (status.isNew()) {
newe.push(status);
} else if (status.isModified()) {
modified.push(status);
} else if (status.isDeleted()) {
deleted.push(status);
}
}
const index: Index = getIndex(repo, opts.index);
if (opts.output === 'json' || opts.output === 'json-pretty') {
const o = { new: newe, modified, deleted };
process.stdout.write(JSON.stringify(o, (key, value) => {
if (value instanceof StatusEntry) {
return {
path: value.path, isdir: value.isdir,
};
}
return value;
}, opts.output === 'json-pretty' ? ' ' : ''));
} else {
console.log(`On branch ${repo.getHead().getName()}`);
console.log('Changes not staged for commit:');
console.log('use "snow add <rel-path>..." to update what will be committed');
for (const modifiedFile of modified) {
console.log(modifiedFile.path);
}
process.stdout.write('\n');
if (deleted.length > 0) {
console.log('Deleted:');
for (const del of deleted) {
console.log(del.path);
}
} else {
console.log('no deleted changes added to commit (use "snow rm")');
}
process.stdout.write('\n');
if (newe.length > 0) {
console.log('New:');
for (const n of newe) {
if (index.addRelPaths.has(n.path)) {
process.stdout.write(chalk.red('+ '));
}
console.log(n.path);
}
} else {
console.log('no changes added to commit (use "snow add"');
}
}
} catch (error) {
if (opts.debug) {
throw error;
} else {
if (error instanceof AggregateError) {
process.stderr.write(`fatal: ${error.errors.map((e) => e.message).join('\n')}`);
} else {
process.stderr.write(`fatal: ${error.message}\n`);
}
process.exit(-1);
}
}
// process.exit(0);
});
program
.command('commit')
.option('-m, --message [message]', 'input file')
.option('--allow-empty', 'allow an empty commit without any changes, not set by default')
.option('--debug', 'add more debug information on errors')
.option('--user-data', 'open standard input to apply user data for commit')
.option('--tags [collection]', 'add user defined tags to commit')
.option('--input <type>', "type can be 'stdin' or {filepath}")
.option('--index [id]', 'use a custom index id')
.description('complete the commit')
.action(async (opts: any) => {
try {
opts = await parseOptions(opts);
const repo = await Repository.open(normalize(process.cwd()));
const index: Index = getIndex(repo, opts.index);
let data = {};
let tags: string[];
if (opts.tags && opts.tags.length > 0) {
tags = String(opts.tags).split(',');
}
if (opts.userData) {
try {
data = JSON.parse(opts.userData);
} catch (e) {
throw new Error(`invalid user-data: ${e}`);
}
}
const newCommit: Commit = await repo.createCommit(index, opts.message, opts, tags, data);
console.log(`[${repo.getHead().getName()} (root-commit) ${newCommit.hash.substr(0, 6)}]`);
} catch (error) {
if (opts.debug) {
throw error;
} else {
if (error instanceof AggregateError) {
process.stderr.write(`fatal: ${error.errors.map((e) => e.message).join('\n')}`);
} else {
process.stderr.write(`fatal: ${error.message}\n`);
}
process.exit(-1);
}
}
});
program
.command('log')
.option('--no-color')
.option('-v, --verbose', 'verbose')
.option('--output [format]', "currently supported output formats 'json', 'json-pretty'")
.option('--debug', 'add more debug information on errors')
.description('print the log to the console')
.action(async (opts: any) => {
if (opts.noColor) {
chalk.level = 0;
}
try {
const repo = await Repository.open(normalize(process.cwd()));
const commits: Commit[] = repo.getAllCommits(COMMIT_ORDER.NEWEST_FIRST);
const refs: Reference[] = repo.getAllReferences();
const headHash: string = repo.getHead().hash;
const headName: string = repo.getHead().getName();
if (opts.output === 'json' || opts.output === 'json-pretty') {
const o = { commits, refs, head: repo.getHead().isDetached() ? headHash : headName };
process.stdout.write(JSON.stringify(o, (key, value) => {
if (value instanceof Commit) {
return {
hash: value.hash,
message: value.message,
date: value.date.getTime() / 1000.0,
root: opts.verbose ? value.root : undefined,
tags: value.tags,
userData: value.userData ? JSON.parse(JSON.stringify(value.userData)) : {},
};
}
if (value instanceof TreeDir) {
return { path: value.path, hash: value.hash, children: value.children };
}
if (value instanceof TreeFile) {
return {
path: value.path,
hash: value.hash,
ctime: value.stats.ctime,
mtime: value.stats.mtime,
size: value.stats.size,
};
}
if (value instanceof Reference) {
return {
name: value.getName(),
hash: value.hash,
start: value.startHash,
userData: value.userData ? JSON.parse(JSON.stringify(value.userData)) : {},
};
}
return value;
}, opts.output === 'json-pretty' ? ' ' : ''));
} else {
for (const commit of commits) {
process.stdout.write(chalk.magenta.bold(`commit: ${commit.hash}`));
const branchRefs: Reference[] = refs.filter((ref: Reference) => ref.hash === commit.hash);
if (repo.getHead().isDetached() && commit.hash === headHash) {
branchRefs.unshift(repo.getHead());
}
if (branchRefs.length > 0) {
process.stdout.write(' (');
process.stdout.write(`${branchRefs.map((ref) => {
if (ref.hash === commit.hash) {
if (ref.getName() === headName) {
if (headName === 'HEAD') {
return chalk.blue.bold(ref.getName());
}
return chalk.blue.bold(`HEAD -> ${ref.getName()}`);
}
return chalk.rgb(255, 165, 0)(ref.getName());
}
return null;
}).filter((x) => !!x).join(', ')}`);
process.stdout.write(')');
}
process.stdout.write('\n');
process.stdout.write(`Date: ${commit.date}\n`);
if (commit.tags && commit.tags.length > 0) {
process.stdout.write('Tags:');
let seperator = ' ';
commit.tags.forEach((tag) => {
process.stdout.write(`${seperator}${tag}`);
seperator = ', ';
});
process.stdout.write('\n');
}
if (Object.keys(commit.userData).length > 0) {
process.stdout.write('User Data:');
let seperator = ' ';
// eslint-disable-next-line guard-for-in
for (const key in commit.userData) {
if ({}.hasOwnProperty.call(commit.userData, key)) {
process.stdout.write(`${seperator}${key}=${commit.userData[key]}`);
}
seperator = ', ';
}
process.stdout.write('\n');
}
process.stdout.write(`\n ${commit.message}\n\n\n`);
if (opts.verbose) {
const files = commit.root.getAllTreeFiles({ entireHierarchy: true, includeDirs: true });
files.forEach((value: TreeEntry) => {
if (value.isDirectory()) {
process.stdout.write(` [${value.hash}] ${value.path}\n`);
} else if (value instanceof TreeFile) {
process.stdout.write(` [${value.hash}] ${value.path} (${value.stats.size}B)\n`);
}
});
if (files.size > 0) {
process.stdout.write('\n');
}
}
}
}
} catch (error) {
if (opts.debug) {
throw error;
} else {
if (error instanceof AggregateError) {
process.stderr.write(`fatal: ${error.errors.map((e) => e.message).join('\n')}`);
} else {
process.stderr.write(`fatal: ${error.message}\n`);
}
process.exit(-1);
}
}
});
program
.command('driveinfo')
.option('--output [format=json-pretty]', "currently supported output formats 'json', 'json-pretty'")
.description('List all connected drives in your computer, in all major operating systems')
.action(async (opts: any) => {
const drives = await drivelist.list();
console.log(JSON.stringify(drives, null, opts.output === 'json' ? '' : ' '));
});
program
.command('switch [branch-name]')
.option('--discard-changes', 'force switch and discard changes in workdir')
.option('-k, --keep-changes', "don't reset files in the workdir")
.option('-d, --detach', 'detach the branch')
.option('--debug', 'add more debug information on errors')
.option('--no-color')
.option('--user-data', 'open standard input to apply user data for commit')
.option('--input <type>', "type can be 'stdin' or {filepath}")
.description('switch a commit')
.action(async (branchName: string | undefined, opts: any) => {
if (opts.noColor) {
chalk.level = 0;
}
try {
opts = await parseOptions(opts);
const repo = await Repository.open(normalize(process.cwd()));
if (branchName) {
const targetCommit = repo.findCommitByReferenceName(REFERENCE_TYPE.BRANCH, branchName);
if (!targetCommit) {
if (repo.findCommitByHash(branchName)) {
throw new Error(`target ${branchName} seems to be a commit and must be checked out via 'snow checkout'`);
}
throw new Error(`cannot find branch '${branchName}'`);
}
if (opts.discardChanges && opts.keepChanges) {
throw new Error('either --discard-changes or --keep-changes can be used, not both');
} else if (!opts.discardChanges && !opts.keepChanges) {
const statusFiles: StatusEntry[] = await repo.getStatus(FILTER.INCLUDE_UNTRACKED | FILTER.INCLUDE_MODIFIED);
let criticalChanges = 0;
for (const statusFile of statusFiles) {
// new or modified files will abort the checkout to prevent data loss
if (statusFile.isModified()) {
process.stdout.write(`M ${statusFile.path}\n`);
criticalChanges++;
} else if (statusFile.isNew()) {
process.stdout.write(`A ${statusFile.path}\n`);
criticalChanges++;
}
// 'Ignored' or 'Deleted' files can also be ignored, since they could be restored
}
if (criticalChanges > 0) {
throw new Error(`You have local changes to '${branchName}'; not switching branches.`);
}
}
let reset: RESET = RESET.NONE;
if (!opts.keepChanges) {
reset |= RESET.RESTORE_MODIFIED_ITEMS | RESET.DELETE_NEW_ITEMS | RESET.RESTORE_DELETED_ITEMS;
}
if (opts.detach) {
reset |= RESET.DETACH;
}
await repo.checkout(branchName, reset);
}
} catch (error) {
if (opts.debug) {
throw error;
} else {
if (error instanceof AggregateError) {
process.stderr.write(`fatal: ${error.errors.map((e) => e.message).join('\n')}`);
} else {
process.stderr.write(`fatal: ${error.message}\n`);
}
process.exit(-1);
}
}
});
program.parse(process.argv.filter((x) => x !== '--'));