This repository was archived by the owner on Dec 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 402
/
Copy pathgit-shell-out-strategy.js
1176 lines (1022 loc) · 36.7 KB
/
git-shell-out-strategy.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
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
import path from 'path';
import os from 'os';
import childProcess from 'child_process';
import fs from 'fs-extra';
import util from 'util';
import {remote} from 'electron';
import {CompositeDisposable} from 'event-kit';
import {GitProcess} from 'dugite';
import {parse as parseDiff} from 'what-the-diff';
import {parse as parseStatus} from 'what-the-status';
import GitPromptServer from './git-prompt-server';
import GitTempDir from './git-temp-dir';
import AsyncQueue from './async-queue';
import {incrementCounter} from './reporter-proxy';
import {
getDugitePath, getSharedModulePath, getAtomHelperPath,
extractCoAuthorsAndRawCommitMessage, fileExists, isFileExecutable, isFileSymlink, isBinary,
normalizeGitHelperPath, toNativePathSep, toGitPathSep, LINE_ENDING_REGEX, CO_AUTHOR_REGEX,
} from './helpers';
import GitTimingsView from './views/git-timings-view';
import File from './models/patch/file';
import WorkerManager from './worker-manager';
import Author from './models/author';
const MAX_STATUS_OUTPUT_LENGTH = 1024 * 1024 * 10;
let headless = null;
let execPathPromise = null;
export class GitError extends Error {
constructor(message) {
super(message);
this.message = message;
this.stack = new Error().stack;
}
}
export class LargeRepoError extends Error {
constructor(message) {
super(message);
this.message = message;
this.stack = new Error().stack;
}
}
// ignored for the purposes of usage metrics tracking because they're noisy
const IGNORED_GIT_COMMANDS = ['cat-file', 'config', 'diff', 'for-each-ref', 'log', 'rev-parse', 'status'];
const DISABLE_COLOR_FLAGS = [
'branch', 'diff', 'showBranch', 'status', 'ui',
].reduce((acc, type) => {
acc.unshift('-c', `color.${type}=false`);
return acc;
}, []);
/**
* Expand config path name per
* https://git-scm.com/docs/git-config#git-config-pathname
* this regex attempts to get the specified user's home directory
* Ex: on Mac ~kuychaco/ is expanded to the specified user’s home directory (/Users/kuychaco)
* Regex translation:
* ^~ line starts with tilde
* ([^\\\\/]*)[\\\\/] captures non-slash characters before first slash
*/
const EXPAND_TILDE_REGEX = new RegExp('^~([^\\\\/]*)[\\\\/]');
export default class GitShellOutStrategy {
static defaultExecArgs = {
stdin: null,
useGitPromptServer: false,
useGpgWrapper: false,
useGpgAtomPrompt: false,
writeOperation: false,
}
constructor(workingDir, options = {}) {
this.workingDir = workingDir;
if (options.queue) {
this.commandQueue = options.queue;
} else {
const parallelism = options.parallelism || Math.max(3, os.cpus().length);
this.commandQueue = new AsyncQueue({parallelism});
}
this.prompt = options.prompt || (query => Promise.reject());
this.workerManager = options.workerManager;
if (headless === null) {
headless = !remote.getCurrentWindow().isVisible();
}
}
/*
* Provide an asynchronous callback to be used to request input from the user for git operations.
*
* `prompt` must be a callable that accepts a query object `{prompt, includeUsername}` and returns a Promise
* that either resolves with a result object `{[username], password}` or rejects on cancellation.
*/
setPromptCallback(prompt) {
this.prompt = prompt;
}
// Execute a command and read the output using the embedded Git environment
async exec(args, options = GitShellOutStrategy.defaultExecArgs) {
/* eslint-disable no-console,no-control-regex */
const {stdin, useGitPromptServer, useGpgWrapper, useGpgAtomPrompt, writeOperation} = options;
const commandName = args[0];
const subscriptions = new CompositeDisposable();
const diagnosticsEnabled = process.env.ATOM_GITHUB_GIT_DIAGNOSTICS || atom.config.get('github.gitDiagnostics');
const formattedArgs = `git ${args.join(' ')} in ${this.workingDir}`;
const timingMarker = GitTimingsView.generateMarker(`git ${args.join(' ')}`);
timingMarker.mark('queued');
args.unshift(...DISABLE_COLOR_FLAGS);
if (execPathPromise === null) {
// Attempt to collect the --exec-path from a native git installation.
execPathPromise = new Promise(resolve => {
childProcess.exec('git --exec-path', (error, stdout) => {
/* istanbul ignore if */
if (error) {
// Oh well
resolve(null);
return;
}
resolve(stdout.trim());
});
});
}
const execPath = await execPathPromise;
return this.commandQueue.push(async () => {
timingMarker.mark('prepare');
let gitPromptServer;
const pathParts = [];
if (process.env.PATH) {
pathParts.push(process.env.PATH);
}
if (execPath) {
pathParts.push(execPath);
}
const env = {
...process.env,
GIT_TERMINAL_PROMPT: '0',
GIT_OPTIONAL_LOCKS: '0',
PATH: pathParts.join(path.delimiter),
};
const gitTempDir = new GitTempDir();
if (useGpgWrapper) {
await gitTempDir.ensure();
args.unshift('-c', `gpg.program=${gitTempDir.getGpgWrapperSh()}`);
}
if (useGitPromptServer) {
gitPromptServer = new GitPromptServer(gitTempDir);
await gitPromptServer.start(this.prompt);
env.ATOM_GITHUB_TMP = gitTempDir.getRootPath();
env.ATOM_GITHUB_ASKPASS_PATH = normalizeGitHelperPath(gitTempDir.getAskPassJs());
env.ATOM_GITHUB_CREDENTIAL_PATH = normalizeGitHelperPath(gitTempDir.getCredentialHelperJs());
env.ATOM_GITHUB_ELECTRON_PATH = normalizeGitHelperPath(getAtomHelperPath());
env.ATOM_GITHUB_SOCK_ADDR = gitPromptServer.getAddress();
env.ATOM_GITHUB_WORKDIR_PATH = this.workingDir;
env.ATOM_GITHUB_DUGITE_PATH = getDugitePath();
env.ATOM_GITHUB_KEYTAR_STRATEGY_PATH = getSharedModulePath('keytar-strategy');
// "ssh" won't respect SSH_ASKPASS unless:
// (a) it's running without a tty
// (b) DISPLAY is set to something nonempty
// But, on a Mac, DISPLAY is unset. Ensure that it is so our SSH_ASKPASS is respected.
if (!process.env.DISPLAY || process.env.DISPLAY.length === 0) {
env.DISPLAY = 'atom-github-placeholder';
}
env.ATOM_GITHUB_ORIGINAL_PATH = process.env.PATH || '';
env.ATOM_GITHUB_ORIGINAL_GIT_ASKPASS = process.env.GIT_ASKPASS || '';
env.ATOM_GITHUB_ORIGINAL_SSH_ASKPASS = process.env.SSH_ASKPASS || '';
env.ATOM_GITHUB_ORIGINAL_GIT_SSH_COMMAND = process.env.GIT_SSH_COMMAND || '';
env.ATOM_GITHUB_SPEC_MODE = atom.inSpecMode() ? 'true' : 'false';
env.SSH_ASKPASS = normalizeGitHelperPath(gitTempDir.getAskPassSh());
env.GIT_ASKPASS = normalizeGitHelperPath(gitTempDir.getAskPassSh());
if (process.platform === 'linux') {
env.GIT_SSH_COMMAND = gitTempDir.getSshWrapperSh();
} else if (process.env.GIT_SSH_COMMAND) {
env.GIT_SSH_COMMAND = process.env.GIT_SSH_COMMAND;
} else {
env.GIT_SSH = process.env.GIT_SSH;
}
const credentialHelperSh = normalizeGitHelperPath(gitTempDir.getCredentialHelperSh());
args.unshift('-c', `credential.helper=${credentialHelperSh}`);
}
if (useGpgWrapper && useGitPromptServer && useGpgAtomPrompt) {
env.ATOM_GITHUB_GPG_PROMPT = 'true';
}
/* istanbul ignore if */
if (diagnosticsEnabled) {
env.GIT_TRACE = 'true';
env.GIT_TRACE_CURL = 'true';
}
let opts = {env};
if (stdin) {
opts.stdin = stdin;
opts.stdinEncoding = 'utf8';
}
/* istanbul ignore if */
if (process.env.PRINT_GIT_TIMES) {
console.time(`git:${formattedArgs}`);
}
return new Promise(async (resolve, reject) => {
if (options.beforeRun) {
const newArgsOpts = await options.beforeRun({args, opts});
args = newArgsOpts.args;
opts = newArgsOpts.opts;
}
const {promise, cancel} = this.executeGitCommand(args, opts, timingMarker);
let expectCancel = false;
if (gitPromptServer) {
subscriptions.add(gitPromptServer.onDidCancel(async ({handlerPid}) => {
expectCancel = true;
await cancel();
// On Windows, the SSH_ASKPASS handler is executed as a non-child process, so the bin\git-askpass-atom.sh
// process does not terminate when the git process is killed.
// Kill the handler process *after* the git process has been killed to ensure that git doesn't have a
// chance to fall back to GIT_ASKPASS from the credential handler.
await new Promise((resolveKill, rejectKill) => {
require('tree-kill')(handlerPid, 'SIGTERM', err => {
/* istanbul ignore if */
if (err) { rejectKill(err); } else { resolveKill(); }
});
});
}));
}
const {stdout, stderr, exitCode, signal, timing} = await promise.catch(err => {
if (err.signal) {
return {signal: err.signal};
}
reject(err);
return {};
});
if (timing) {
const {execTime, spawnTime, ipcTime} = timing;
const now = performance.now();
timingMarker.mark('nexttick', now - execTime - spawnTime - ipcTime);
timingMarker.mark('execute', now - execTime - ipcTime);
timingMarker.mark('ipc', now - ipcTime);
}
timingMarker.finalize();
/* istanbul ignore if */
if (process.env.PRINT_GIT_TIMES) {
console.timeEnd(`git:${formattedArgs}`);
}
if (gitPromptServer) {
gitPromptServer.terminate();
}
subscriptions.dispose();
/* istanbul ignore if */
if (diagnosticsEnabled) {
const exposeControlCharacters = raw => {
if (!raw) { return ''; }
return raw
.replace(/\u0000/ug, '<NUL>\n')
.replace(/\u001F/ug, '<SEP>');
};
if (headless) {
let summary = `git:${formattedArgs}\n`;
if (exitCode !== undefined) {
summary += `exit status: ${exitCode}\n`;
} else if (signal) {
summary += `exit signal: ${signal}\n`;
}
if (stdin && stdin.length !== 0) {
summary += `stdin:\n${exposeControlCharacters(stdin)}\n`;
}
summary += 'stdout:';
if (stdout.length === 0) {
summary += ' <empty>\n';
} else {
summary += `\n${exposeControlCharacters(stdout)}\n`;
}
summary += 'stderr:';
if (stderr.length === 0) {
summary += ' <empty>\n';
} else {
summary += `\n${exposeControlCharacters(stderr)}\n`;
}
console.log(summary);
} else {
const headerStyle = 'font-weight: bold; color: blue;';
console.groupCollapsed(`git:${formattedArgs}`);
if (exitCode !== undefined) {
console.log('%cexit status%c %d', headerStyle, 'font-weight: normal; color: black;', exitCode);
} else if (signal) {
console.log('%cexit signal%c %s', headerStyle, 'font-weight: normal; color: black;', signal);
}
console.log(
'%cfull arguments%c %s',
headerStyle, 'font-weight: normal; color: black;',
util.inspect(args, {breakLength: Infinity}),
);
if (stdin && stdin.length !== 0) {
console.log('%cstdin', headerStyle);
console.log(exposeControlCharacters(stdin));
}
console.log('%cstdout', headerStyle);
console.log(exposeControlCharacters(stdout));
console.log('%cstderr', headerStyle);
console.log(exposeControlCharacters(stderr));
console.groupEnd();
}
}
if (exitCode !== 0 && !expectCancel) {
const err = new GitError(
`${formattedArgs} exited with code ${exitCode}\nstdout: ${stdout}\nstderr: ${stderr}`,
);
err.code = exitCode;
err.stdErr = stderr;
err.stdOut = stdout;
err.command = formattedArgs;
reject(err);
}
if (!IGNORED_GIT_COMMANDS.includes(commandName)) {
incrementCounter(commandName);
}
resolve(stdout);
});
}, {parallel: !writeOperation});
/* eslint-enable no-console,no-control-regex */
}
async gpgExec(args, options) {
try {
return await this.exec(args.slice(), {
useGpgWrapper: true,
useGpgAtomPrompt: false,
...options,
});
} catch (e) {
if (/gpg failed/.test(e.stdErr)) {
return await this.exec(args, {
useGitPromptServer: true,
useGpgWrapper: true,
useGpgAtomPrompt: true,
...options,
});
} else {
throw e;
}
}
}
executeGitCommand(args, options, marker = null) {
if (process.env.ATOM_GITHUB_INLINE_GIT_EXEC || !WorkerManager.getInstance().isReady()) {
marker && marker.mark('nexttick');
let childPid;
options.processCallback = child => {
childPid = child.pid;
/* istanbul ignore next */
child.stdin.on('error', err => {
throw new Error(
`Error writing to stdin: git ${args.join(' ')} in ${this.workingDir}\n${options.stdin}\n${err}`);
});
};
const promise = GitProcess.exec(args, this.workingDir, options);
marker && marker.mark('execute');
return {
promise,
cancel: () => {
/* istanbul ignore if */
if (!childPid) {
return Promise.resolve();
}
return new Promise((resolve, reject) => {
require('tree-kill')(childPid, 'SIGTERM', err => {
/* istanbul ignore if */
if (err) { reject(err); } else { resolve(); }
});
});
},
};
} else {
const workerManager = this.workerManager || WorkerManager.getInstance();
return workerManager.request({
args,
workingDir: this.workingDir,
options,
});
}
}
async resolveDotGitDir() {
try {
await fs.stat(this.workingDir); // fails if folder doesn't exist
const output = await this.exec(['rev-parse', '--resolve-git-dir', path.join(this.workingDir, '.git')]);
const dotGitDir = output.trim();
return toNativePathSep(dotGitDir);
} catch (e) {
return null;
}
}
init() {
return this.exec(['init', this.workingDir]);
}
/**
* Staging/Unstaging files and patches and committing
*/
stageFiles(paths) {
if (paths.length === 0) { return Promise.resolve(null); }
const args = ['add'].concat(paths.map(toGitPathSep));
return this.exec(args, {writeOperation: true});
}
async fetchCommitMessageTemplate() {
let templatePath = await this.getConfig('commit.template');
if (!templatePath) {
return null;
}
const homeDir = os.homedir();
templatePath = templatePath.trim().replace(EXPAND_TILDE_REGEX, (_, user) => {
// if no user is specified, fall back to using the home directory.
return `${user ? path.join(path.dirname(homeDir), user) : homeDir}/`;
});
templatePath = toNativePathSep(templatePath);
if (!path.isAbsolute(templatePath)) {
templatePath = path.join(this.workingDir, templatePath);
}
if (!await fileExists(templatePath)) {
throw new Error(`Invalid commit template path set in Git config: ${templatePath}`);
}
return await fs.readFile(templatePath, {encoding: 'utf8'});
}
unstageFiles(paths, commit = 'HEAD') {
if (paths.length === 0) { return Promise.resolve(null); }
const args = ['reset', commit, '--'].concat(paths.map(toGitPathSep));
return this.exec(args, {writeOperation: true});
}
stageFileModeChange(filename, newMode) {
const indexReadPromise = this.exec(['ls-files', '-s', '--', filename]);
return this.exec(['update-index', '--cacheinfo', `${newMode},<OID_TBD>,${filename}`], {
writeOperation: true,
beforeRun: async function determineArgs({args, opts}) {
const index = await indexReadPromise;
const oid = index.substr(7, 40);
return {
opts,
args: ['update-index', '--cacheinfo', `${newMode},${oid},${filename}`],
};
},
});
}
stageFileSymlinkChange(filename) {
return this.exec(['rm', '--cached', filename], {writeOperation: true});
}
applyPatch(patch, {index} = {}) {
const args = ['apply', '-'];
if (index) { args.splice(1, 0, '--cached'); }
return this.exec(args, {stdin: patch, writeOperation: true});
}
async commit(rawMessage, {allowEmpty, amend, coAuthors, verbatim} = {}) {
const args = ['commit'];
let msg;
// if amending and no new message is passed, use last commit's message. Ensure that we don't
// mangle it in the process.
if (amend && rawMessage.length === 0) {
const {unbornRef, messageBody, messageSubject} = await this.getHeadCommit();
if (unbornRef) {
msg = rawMessage;
} else {
msg = `${messageSubject}\n\n${messageBody}`.trim();
verbatim = true;
}
} else {
msg = rawMessage;
}
// if commit template is used, strip commented lines from commit
// to be consistent with command line git.
const template = await this.fetchCommitMessageTemplate();
if (template) {
// respecting the comment character from user settings or fall back to # as default.
// https://git-scm.com/docs/git-config#git-config-corecommentChar
let commentChar = await this.getConfig('core.commentChar');
if (!commentChar) {
commentChar = '#';
}
msg = msg.split('\n').filter(line => !line.startsWith(commentChar)).join('\n');
}
// Determine the cleanup mode.
if (verbatim) {
args.push('--cleanup=verbatim');
} else {
const configured = await this.getConfig('commit.cleanup');
const mode = (configured && configured !== 'default') ? configured : 'strip';
args.push(`--cleanup=${mode}`);
}
// add co-author commit trailers if necessary
if (coAuthors && coAuthors.length > 0) {
msg = await this.addCoAuthorsToMessage(msg, coAuthors);
}
args.push('-m', msg.trim());
if (amend) { args.push('--amend'); }
if (allowEmpty) { args.push('--allow-empty'); }
return this.gpgExec(args, {writeOperation: true});
}
addCoAuthorsToMessage(message, coAuthors = []) {
const trailers = coAuthors.map(author => {
return {
token: 'Co-Authored-By',
value: `${author.name} <${author.email}>`,
};
});
// Ensure that message ends with newline for git-interpret trailers to work
const msg = `${message.trim()}\n`;
return trailers.length ? this.mergeTrailers(msg, trailers) : msg;
}
/**
* File Status and Diffs
*/
async getStatusBundle() {
const args = ['status', '--porcelain=v2', '--branch', '--untracked-files=all', '--ignore-submodules=dirty', '-z'];
const output = await this.exec(args);
if (output.length > MAX_STATUS_OUTPUT_LENGTH) {
throw new LargeRepoError();
}
const results = await parseStatus(output);
for (const entryType in results) {
if (Array.isArray(results[entryType])) {
this.updateNativePathSepForEntries(results[entryType]);
}
}
return results;
}
updateNativePathSepForEntries(entries) {
entries.forEach(entry => {
// Normally we would avoid mutating responses from other package's APIs, but we control
// the `what-the-status` module and know there are no side effects.
// This is a hot code path and by mutating we avoid creating new objects that will just be GC'ed
if (entry.filePath) {
entry.filePath = toNativePathSep(entry.filePath);
}
if (entry.origFilePath) {
entry.origFilePath = toNativePathSep(entry.origFilePath);
}
});
}
async diffFileStatus(options = {}) {
const args = ['diff', '--name-status', '--no-renames'];
if (options.staged) { args.push('--staged'); }
if (options.target) { args.push(options.target); }
const output = await this.exec(args);
const statusMap = {
A: 'added',
M: 'modified',
D: 'deleted',
U: 'unmerged',
};
const fileStatuses = {};
output && output.trim().split(LINE_ENDING_REGEX).forEach(line => {
const [status, rawFilePath] = line.split('\t');
const filePath = toNativePathSep(rawFilePath);
fileStatuses[filePath] = statusMap[status];
});
if (!options.staged) {
const untracked = await this.getUntrackedFiles();
untracked.forEach(filePath => { fileStatuses[filePath] = 'added'; });
}
return fileStatuses;
}
async getUntrackedFiles() {
const output = await this.exec(['ls-files', '--others', '--exclude-standard']);
if (output.trim() === '') { return []; }
return output.trim().split(LINE_ENDING_REGEX).map(toNativePathSep);
}
async getDiffsForFilePath(filePath, {staged, baseCommit} = {}) {
let args = ['diff', '--no-prefix', '--no-ext-diff', '--no-renames', '--diff-filter=u'];
if (staged) { args.push('--staged'); }
if (baseCommit) { args.push(baseCommit); }
args = args.concat(['--', toGitPathSep(filePath)]);
const output = await this.exec(args);
let rawDiffs = [];
if (output) {
rawDiffs = parseDiff(output)
.filter(rawDiff => rawDiff.status !== 'unmerged');
for (let i = 0; i < rawDiffs.length; i++) {
const rawDiff = rawDiffs[i];
if (rawDiff.oldPath) {
rawDiff.oldPath = toNativePathSep(rawDiff.oldPath);
}
if (rawDiff.newPath) {
rawDiff.newPath = toNativePathSep(rawDiff.newPath);
}
}
}
if (!staged && (await this.getUntrackedFiles()).includes(filePath)) {
// add untracked file
const absPath = path.join(this.workingDir, filePath);
const executable = await isFileExecutable(absPath);
const symlink = await isFileSymlink(absPath);
const contents = await fs.readFile(absPath, {encoding: 'utf8'});
const binary = isBinary(contents);
let mode;
let realpath;
if (executable) {
mode = File.modes.EXECUTABLE;
} else if (symlink) {
mode = File.modes.SYMLINK;
realpath = await fs.realpath(absPath);
} else {
mode = File.modes.NORMAL;
}
rawDiffs.push(buildAddedFilePatch(filePath, binary ? null : contents, mode, realpath));
}
if (rawDiffs.length > 2) {
throw new Error(`Expected between 0 and 2 diffs for ${filePath} but got ${rawDiffs.length}`);
}
return rawDiffs;
}
async getStagedChangesPatch() {
const output = await this.exec([
'diff', '--staged', '--no-prefix', '--no-ext-diff', '--no-renames', '--diff-filter=u',
]);
if (!output) {
return [];
}
const diffs = parseDiff(output);
for (const diff of diffs) {
if (diff.oldPath) { diff.oldPath = toNativePathSep(diff.oldPath); }
if (diff.newPath) { diff.newPath = toNativePathSep(diff.newPath); }
}
return diffs;
}
/**
* Miscellaneous getters
*/
async getCommit(ref) {
const [commit] = await this.getCommits({max: 1, ref, includeUnborn: true});
return commit;
}
async getHeadCommit() {
const [headCommit] = await this.getCommits({max: 1, ref: 'HEAD', includeUnborn: true});
return headCommit;
}
async getCommits(options = {}) {
const {max, ref, includeUnborn, includePatch} = {
max: 1,
ref: 'HEAD',
includeUnborn: false,
includePatch: false,
...options,
};
// https://git-scm.com/docs/git-log#_pretty_formats
// %x00 - null byte
// %H - commit SHA
// %ae - author email
// %an = author full name
// %at - timestamp, UNIX timestamp
// %s - subject
// %b - body
const args = [
'log',
'--pretty=format:%H%x00%ae%x00%an%x00%at%x00%s%x00%b%x00',
'--no-abbrev-commit',
'--no-prefix',
'--no-ext-diff',
'--no-renames',
'-z',
'-n',
max,
ref,
];
if (includePatch) {
args.push('--patch', '-m', '--first-parent');
}
const output = await this.exec(args.concat('--')).catch(err => {
if (/unknown revision/.test(err.stdErr) || /bad revision 'HEAD'/.test(err.stdErr)) {
return '';
} else {
throw err;
}
});
if (output === '') {
return includeUnborn ? [{sha: '', message: '', unbornRef: true}] : [];
}
const fields = output.trim().split('\0');
const commits = [];
for (let i = 0; i < fields.length; i += 7) {
const body = fields[i + 5].trim();
let patch = [];
if (includePatch) {
const diffs = fields[i + 6];
patch = parseDiff(diffs.trim());
}
const {message: messageBody, coAuthors} = extractCoAuthorsAndRawCommitMessage(body);
commits.push({
sha: fields[i] && fields[i].trim(),
author: new Author(fields[i + 1] && fields[i + 1].trim(), fields[i + 2] && fields[i + 2].trim()),
authorDate: parseInt(fields[i + 3], 10),
messageSubject: fields[i + 4],
messageBody,
coAuthors,
unbornRef: false,
patch,
});
}
return commits;
}
async getAuthors(options = {}) {
const {max, ref} = {max: 1, ref: 'HEAD', ...options};
// https://git-scm.com/docs/git-log#_pretty_formats
// %x1F - field separator byte
// %an - author name
// %ae - author email
// %cn - committer name
// %ce - committer email
// %(trailers:unfold,only) - the commit message trailers, separated
// by newlines and unfolded (i.e. properly
// formatted and one trailer per line).
const delimiter = '1F';
const delimiterString = String.fromCharCode(parseInt(delimiter, 16));
const fields = ['%an', '%ae', '%cn', '%ce', '%(trailers:unfold,only)'];
const format = fields.join(`%x${delimiter}`);
try {
const output = await this.exec([
'log', `--format=${format}`, '-z', '-n', max, ref, '--',
]);
return output.split('\0')
.reduce((acc, line) => {
if (line.length === 0) { return acc; }
const [an, ae, cn, ce, trailers] = line.split(delimiterString);
trailers
.split('\n')
.map(trailer => trailer.match(CO_AUTHOR_REGEX))
.filter(match => match !== null)
.forEach(([_, name, email]) => { acc[email] = name; });
acc[ae] = an;
acc[ce] = cn;
return acc;
}, {});
} catch (err) {
if (/unknown revision/.test(err.stdErr) || /bad revision 'HEAD'/.test(err.stdErr)) {
return [];
} else {
throw err;
}
}
}
mergeTrailers(commitMessage, trailers) {
const args = ['interpret-trailers'];
for (const trailer of trailers) {
args.push('--trailer', `${trailer.token}=${trailer.value}`);
}
return this.exec(args, {stdin: commitMessage});
}
readFileFromIndex(filePath) {
return this.exec(['show', `:${toGitPathSep(filePath)}`]);
}
/**
* Merge
*/
merge(branchName) {
return this.gpgExec(['merge', branchName], {writeOperation: true});
}
isMerging(dotGitDir) {
return fileExists(path.join(dotGitDir, 'MERGE_HEAD')).catch(() => false);
}
abortMerge() {
return this.exec(['merge', '--abort'], {writeOperation: true});
}
checkoutSide(side, paths) {
if (paths.length === 0) {
return Promise.resolve();
}
return this.exec(['checkout', `--${side}`, ...paths.map(toGitPathSep)]);
}
/**
* Rebase
*/
async isRebasing(dotGitDir) {
const results = await Promise.all([
fileExists(path.join(dotGitDir, 'rebase-merge')),
fileExists(path.join(dotGitDir, 'rebase-apply')),
]);
return results.some(r => r);
}
/**
* Remote interactions
*/
clone(remoteUrl, options = {}) {
const args = ['clone'];
if (options.noLocal) { args.push('--no-local'); }
if (options.bare) { args.push('--bare'); }
if (options.recursive) { args.push('--recursive'); }
if (options.sourceRemoteName) { args.push('--origin', options.remoteName); }
args.push(remoteUrl, this.workingDir);
return this.exec(args, {useGitPromptServer: true, writeOperation: true});
}
fetch(remoteName, branchName) {
return this.exec(['fetch', remoteName, branchName], {useGitPromptServer: true, writeOperation: true});
}
pull(remoteName, branchName, options = {}) {
const args = ['pull', remoteName, options.refSpec || branchName];
if (options.ffOnly) {
args.push('--ff-only');
}
return this.gpgExec(args, {useGitPromptServer: true, writeOperation: true});
}
push(remoteName, branchName, options = {}) {
const args = ['push', remoteName || 'origin', options.refSpec || `refs/heads/${branchName}`];
if (options.setUpstream) { args.push('--set-upstream'); }
if (options.force) { args.push('--force'); }
return this.exec(args, {useGitPromptServer: true, writeOperation: true});
}
/**
* Undo Operations
*/
reset(type, revision = 'HEAD') {
const validTypes = ['soft'];
if (!validTypes.includes(type)) {
throw new Error(`Invalid type ${type}. Must be one of: ${validTypes.join(', ')}`);
}
return this.exec(['reset', `--${type}`, revision]);
}
deleteRef(ref) {
return this.exec(['update-ref', '-d', ref]);
}
/**
* Branches
*/
checkout(branchName, options = {}) {
const args = ['checkout'];
if (options.createNew) {
args.push('-b');
}
args.push(branchName);
if (options.startPoint) {
if (options.track) { args.push('--track'); }
args.push(options.startPoint);
}
return this.exec(args, {writeOperation: true});
}
async getBranches() {
const format = [
'%(objectname)', '%(HEAD)', '%(refname:short)',
'%(upstream)', '%(upstream:remotename)', '%(upstream:remoteref)',
'%(push)', '%(push:remotename)', '%(push:remoteref)',
].join('%00');
const output = await this.exec(['for-each-ref', `--format=${format}`, 'refs/heads/**']);
return output.trim().split(LINE_ENDING_REGEX).map(line => {
const [
sha, head, name,
upstreamTrackingRef, upstreamRemoteName, upstreamRemoteRef,
pushTrackingRef, pushRemoteName, pushRemoteRef,
] = line.split('\0');
const branch = {name, sha, head: head === '*'};
if (upstreamTrackingRef || upstreamRemoteName || upstreamRemoteRef) {
branch.upstream = {
trackingRef: upstreamTrackingRef,
remoteName: upstreamRemoteName,
remoteRef: upstreamRemoteRef,
};
}
if (branch.upstream || pushTrackingRef || pushRemoteName || pushRemoteRef) {
branch.push = {
trackingRef: pushTrackingRef,
remoteName: pushRemoteName || (branch.upstream && branch.upstream.remoteName),
remoteRef: pushRemoteRef || (branch.upstream && branch.upstream.remoteRef),
};
}
return branch;
});
}
async getBranchesWithCommit(sha, option = {}) {
const args = ['branch', '--format=%(refname)', '--contains', sha];
if (option.showLocal && option.showRemote) {
args.splice(1, 0, '--all');
} else if (option.showRemote) {
args.splice(1, 0, '--remotes');
}
if (option.pattern) {
args.push(option.pattern);
}
return (await this.exec(args)).trim().split(LINE_ENDING_REGEX);
}
checkoutFiles(paths, revision) {
if (paths.length === 0) { return null; }
const args = ['checkout'];
if (revision) { args.push(revision); }
return this.exec(args.concat('--', paths.map(toGitPathSep)), {writeOperation: true});
}