-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathgit.ts
2260 lines (1953 loc) · 65.2 KB
/
git.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
import type { ChildProcess, SpawnOptions } from 'child_process';
import { spawn } from 'child_process';
import { accessSync } from 'fs';
import { join as joinPath } from 'path';
import * as process from 'process';
import { hrtime } from '@env/hrtime';
import type { CancellationToken, OutputChannel } from 'vscode';
import { env, Uri, window, workspace } from 'vscode';
import { GlyphChars } from '../../../constants';
import type { GitCommandOptions, GitSpawnOptions } from '../../../git/commandOptions';
import { GitErrorHandling } from '../../../git/commandOptions';
import {
BlameIgnoreRevsFileBadRevisionError,
BlameIgnoreRevsFileError,
CherryPickError,
CherryPickErrorReason,
FetchError,
FetchErrorReason,
PullError,
PullErrorReason,
PushError,
PushErrorReason,
StashPushError,
StashPushErrorReason,
TagError,
TagErrorReason,
WorkspaceUntrustedError,
} from '../../../git/errors';
import type { GitDir } from '../../../git/gitProvider';
import type { GitDiffFilter } from '../../../git/models/diff';
import type { GitRevisionRange } from '../../../git/models/reference';
import { isUncommitted, isUncommittedStaged, shortenRevision } from '../../../git/models/reference';
import type { GitUser } from '../../../git/models/user';
import { parseGitBranchesDefaultFormat } from '../../../git/parsers/branchParser';
import { parseGitLogAllFormat, parseGitLogDefaultFormat } from '../../../git/parsers/logParser';
import { parseGitRemoteUrl } from '../../../git/parsers/remoteParser';
import { splitAt } from '../../../system/array';
import { log } from '../../../system/decorators/log';
import { join } from '../../../system/iterable';
import { Logger } from '../../../system/logger';
import { slowCallWarningThreshold } from '../../../system/logger.constants';
import { getLoggableScopeBlockOverride, getLogScope } from '../../../system/logger.scope';
import { dirname, isAbsolute, isFolderGlob, joinPaths, normalizePath } from '../../../system/path';
import { getDurationMilliseconds } from '../../../system/string';
import { compare, fromString } from '../../../system/version';
import { configuration } from '../../../system/vscode/configuration';
import { splitPath } from '../../../system/vscode/path';
import { getEditorCommand } from '../../../system/vscode/utils';
import { ensureGitTerminal } from '../../../terminal';
import type { GitLocation } from './locator';
import type { RunOptions } from './shell';
import { fsExists, isWindows, run, RunError } from './shell';
const emptyArray = Object.freeze([]) as unknown as any[];
const emptyObj = Object.freeze({});
const gitBranchDefaultConfigs = Object.freeze(['-c', 'color.branch=false']);
const gitDiffDefaultConfigs = Object.freeze(['-c', 'color.diff=false']);
export const gitLogDefaultConfigs = Object.freeze(['-c', 'log.showSignature=false']);
export const gitLogDefaultConfigsWithFiles = Object.freeze([
'-c',
'log.showSignature=false',
'-c',
'diff.renameLimit=0',
]);
const gitStatusDefaultConfigs = Object.freeze(['-c', 'color.status=false']);
export const maxGitCliLength = 30000;
const textDecoder = new TextDecoder('utf8');
// This is a root sha of all git repo's if using sha1
const rootSha = '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
export const GitErrors = {
badRevision: /bad revision '(.*?)'/i,
cantLockRef: /cannot lock ref|unable to update local ref/i,
changesWouldBeOverwritten: /Your local changes to the following files would be overwritten/i,
commitChangesFirst: /Please, commit your changes before you can/i,
conflict: /^CONFLICT \([^)]+\): \b/m,
failedToDeleteDirectoryNotEmpty: /failed to delete '(.*?)': Directory not empty/i,
invalidObjectName: /invalid object name: (.*)\s/i,
invalidObjectNameList: /could not open object name list: (.*)\s/i,
noFastForward: /\(non-fast-forward\)/i,
noMergeBase: /no merge base/i,
noRemoteRepositorySpecified: /No remote repository specified\./i,
notAValidObjectName: /Not a valid object name/i,
notAWorkingTree: /'(.*?)' is not a working tree/i,
noUserNameConfigured: /Please tell me who you are\./i,
invalidLineCount: /file .+? has only \d+ lines/i,
uncommittedChanges: /contains modified or untracked files/i,
alreadyExists: /already exists/i,
alreadyCheckedOut: /already checked out/i,
mainWorkingTree: /is a main working tree/i,
noUpstream: /^fatal: The current branch .* has no upstream branch/i,
permissionDenied: /Permission.*denied/i,
pushRejected: /^error: failed to push some refs to\b/m,
rebaseMultipleBranches: /cannot rebase onto multiple branches/i,
remoteAhead: /rejected because the remote contains work/i,
remoteConnection: /Could not read from remote repository/i,
tagConflict: /! \[rejected\].*\(would clobber existing tag\)/m,
unmergedFiles: /is not possible because you have unmerged files/i,
unstagedChanges: /You have unstaged changes/i,
tagAlreadyExists: /tag .* already exists/i,
tagNotFound: /tag .* not found/i,
invalidTagName: /invalid tag name/i,
remoteRejected: /rejected because the remote contains work/i,
};
const GitWarnings = {
notARepository: /Not a git repository/i,
outsideRepository: /is outside repository/i,
noPath: /no such path/i,
noCommits: /does not have any commits/i,
notFound: /Path '.*?' does not exist in/i,
foundButNotInRevision: /Path '.*?' exists on disk, but not in/i,
headNotABranch: /HEAD does not point to a branch/i,
noUpstream: /no upstream configured for branch '(.*?)'/i,
unknownRevision:
/ambiguous argument '.*?': unknown revision or path not in the working tree|not stored as a remote-tracking branch/i,
mustRunInWorkTree: /this operation must be run in a work tree/i,
patchWithConflicts: /Applied patch to '.*?' with conflicts/i,
noRemoteRepositorySpecified: /No remote repository specified\./i,
remoteConnectionError: /Could not read from remote repository/i,
notAGitCommand: /'.+' is not a git command/i,
tipBehind: /tip of your current branch is behind/i,
};
function defaultExceptionHandler(ex: Error, cwd: string | undefined, start?: [number, number]): string {
const msg = ex.message || ex.toString();
if (msg != null && msg.length !== 0) {
for (const warning of Object.values(GitWarnings)) {
if (warning.test(msg)) {
const duration = start !== undefined ? ` [${getDurationMilliseconds(start)}ms]` : '';
Logger.warn(
`[${cwd}] Git ${msg
.trim()
.replace(/fatal: /g, '')
.replace(/\r?\n|\r/g, ` ${GlyphChars.Dot} `)}${duration}`,
);
return '';
}
}
const match = GitErrors.badRevision.exec(msg);
if (match != null) {
const [, ref] = match;
// Since looking up a ref with ^3 (e.g. looking for untracked files in a stash) can error on some versions of git just ignore it
if (ref?.endsWith('^3')) return '';
}
}
throw ex;
}
let _uniqueCounterForStdin = 0;
function getStdinUniqueKey(): number {
if (_uniqueCounterForStdin === Number.MAX_SAFE_INTEGER) {
_uniqueCounterForStdin = 0;
}
return _uniqueCounterForStdin++;
}
type ExitCodeOnlyGitCommandOptions = GitCommandOptions & { exitCodeOnly: true };
export type PushForceOptions = { withLease: true; ifIncludes?: boolean } | { withLease: false; ifIncludes?: never };
const tagErrorAndReason: [RegExp, TagErrorReason][] = [
[GitErrors.tagAlreadyExists, TagErrorReason.TagAlreadyExists],
[GitErrors.tagNotFound, TagErrorReason.TagNotFound],
[GitErrors.invalidTagName, TagErrorReason.InvalidTagName],
[GitErrors.permissionDenied, TagErrorReason.PermissionDenied],
[GitErrors.remoteRejected, TagErrorReason.RemoteRejected],
];
export class Git {
/** Map of running git commands -- avoids running duplicate overlaping commands */
private readonly pendingCommands = new Map<string, Promise<string | Buffer>>();
async git(options: ExitCodeOnlyGitCommandOptions, ...args: any[]): Promise<number>;
async git<T extends string | Buffer>(options: GitCommandOptions, ...args: any[]): Promise<T>;
async git<T extends string | Buffer>(options: GitCommandOptions, ...args: any[]): Promise<T> {
if (!workspace.isTrusted) throw new WorkspaceUntrustedError();
const start = hrtime();
const { configs, correlationKey, errors: errorHandling, encoding, ...opts } = options;
const runOpts: RunOptions = {
...opts,
encoding: (encoding ?? 'utf8') === 'utf8' ? 'utf8' : 'buffer',
// Adds GCM environment variables to avoid any possible credential issues -- from https://github.com/Microsoft/vscode/issues/26573#issuecomment-338686581
// Shouldn't *really* be needed but better safe than sorry
env: {
...process.env,
...this._gitEnv,
...(options.env ?? emptyObj),
GCM_INTERACTIVE: 'NEVER',
GCM_PRESERVE_CREDS: 'TRUE',
LC_ALL: 'C',
},
};
const gitCommand = `[${runOpts.cwd}] git ${args.join(' ')}`;
const command = `${correlationKey !== undefined ? `${correlationKey}:` : ''}${
options?.stdin != null ? `${getStdinUniqueKey()}:` : ''
}${gitCommand}`;
let waiting;
let promise = this.pendingCommands.get(command);
if (promise === undefined) {
waiting = false;
// Fixes https://github.com/gitkraken/vscode-gitlens/issues/73 & https://github.com/gitkraken/vscode-gitlens/issues/161
// See https://stackoverflow.com/questions/4144417/how-to-handle-asian-characters-in-file-names-in-git-on-os-x
args.unshift(
'-c',
'core.quotepath=false',
'-c',
'color.ui=false',
...(configs != null ? configs : emptyArray),
);
if (process.platform === 'win32') {
args.unshift('-c', 'core.longpaths=true');
}
promise = run<T>(await this.path(), args, encoding ?? 'utf8', runOpts);
this.pendingCommands.set(command, promise);
} else {
waiting = true;
Logger.debug(`${getLoggableScopeBlockOverride('GIT')} ${gitCommand} ${GlyphChars.Dot} waiting...`);
}
let exception: Error | undefined;
try {
return (await promise) as T;
} catch (ex) {
exception = ex;
switch (errorHandling) {
case GitErrorHandling.Ignore:
exception = undefined;
return '' as T;
case GitErrorHandling.Throw:
throw ex;
default: {
const result = defaultExceptionHandler(ex, options.cwd, start);
exception = undefined;
return result as T;
}
}
} finally {
this.pendingCommands.delete(command);
this.logGitCommand(gitCommand, exception, getDurationMilliseconds(start), waiting);
}
}
async gitSpawn(options: GitSpawnOptions, ...args: any[]): Promise<ChildProcess> {
if (!workspace.isTrusted) throw new WorkspaceUntrustedError();
const start = hrtime();
const { cancellation, configs, stdin, stdinEncoding, ...opts } = options;
const spawnOpts: SpawnOptions = {
// Unless provided, ignore stdin and leave default streams for stdout and stderr
stdio: [stdin ? 'pipe' : 'ignore', null, null],
...opts,
// Adds GCM environment variables to avoid any possible credential issues -- from https://github.com/Microsoft/vscode/issues/26573#issuecomment-338686581
// Shouldn't *really* be needed but better safe than sorry
env: {
...process.env,
...this._gitEnv,
...(options.env ?? emptyObj),
GCM_INTERACTIVE: 'NEVER',
GCM_PRESERVE_CREDS: 'TRUE',
LC_ALL: 'C',
},
};
const gitCommand = `(spawn) [${spawnOpts.cwd as string}] git ${args.join(' ')}`;
// Fixes https://github.com/gitkraken/vscode-gitlens/issues/73 & https://github.com/gitkraken/vscode-gitlens/issues/161
// See https://stackoverflow.com/questions/4144417/how-to-handle-asian-characters-in-file-names-in-git-on-os-x
args.unshift(
'-c',
'core.quotepath=false',
'-c',
'color.ui=false',
...(configs !== undefined ? configs : emptyArray),
);
if (process.platform === 'win32') {
args.unshift('-c', 'core.longpaths=true');
}
if (cancellation) {
const aborter = new AbortController();
spawnOpts.signal = aborter.signal;
cancellation.onCancellationRequested(() => aborter.abort());
}
const proc = spawn(await this.path(), args, spawnOpts);
if (stdin) {
proc.stdin?.end(stdin, (stdinEncoding ?? 'utf8') as BufferEncoding);
}
let exception: Error | undefined;
proc.once('error', e => (exception = e));
proc.once('exit', () => this.logGitCommand(gitCommand, exception, getDurationMilliseconds(start), false));
return proc;
}
private _gitLocation: GitLocation | undefined;
private _gitLocationPromise: Promise<GitLocation> | undefined;
private async getLocation(): Promise<GitLocation> {
if (this._gitLocation == null) {
if (this._gitLocationPromise == null) {
this._gitLocationPromise = this._gitLocator();
}
this._gitLocation = await this._gitLocationPromise;
}
return this._gitLocation;
}
private _gitLocator!: () => Promise<GitLocation>;
setLocator(locator: () => Promise<GitLocation>): void {
this._gitLocator = locator;
this._gitLocationPromise = undefined;
this._gitLocation = undefined;
}
private _gitEnv: Record<string, unknown> | undefined;
setEnv(env: Record<string, unknown> | undefined): void {
this._gitEnv = env;
}
async path(): Promise<string> {
return (await this.getLocation()).path;
}
async version(): Promise<string> {
return (await this.getLocation()).version;
}
async isAtLeastVersion(minimum: string): Promise<boolean> {
const result = compare(fromString(await this.version()), fromString(minimum));
return result !== -1;
}
maybeIsAtLeastVersion(minimum: string): boolean | undefined {
return this._gitLocation != null
? compare(fromString(this._gitLocation.version), fromString(minimum)) !== -1
: undefined;
}
// Git commands
add(repoPath: string | undefined, pathspecs: string[], ...args: string[]) {
return this.git<string>({ cwd: repoPath }, 'add', ...args, '--', ...pathspecs);
}
apply(repoPath: string | undefined, patch: string, options: { allowConflicts?: boolean } = {}) {
const params = ['apply', '--whitespace=warn'];
if (options.allowConflicts) {
params.push('-3');
}
return this.git<string>({ cwd: repoPath, stdin: patch }, ...params);
}
async apply2(
repoPath: string,
options?: {
cancellation?: CancellationToken;
configs?: readonly string[];
errors?: GitErrorHandling;
env?: Record<string, unknown>;
stdin?: string;
},
...args: string[]
) {
return this.git<string>(
{
cwd: repoPath,
cancellation: options?.cancellation,
configs: options?.configs ?? gitLogDefaultConfigs,
env: options?.env,
errors: options?.errors,
stdin: options?.stdin,
},
'apply',
...args,
...(options?.stdin ? ['-'] : emptyArray),
);
}
private readonly ignoreRevsFileMap = new Map<string, boolean>();
async blame(
repoPath: string | undefined,
fileName: string,
options?: ({ ref: string | undefined; contents?: never } | { contents: string; ref?: never }) & {
args?: string[] | null;
correlationKey?: string;
ignoreWhitespace?: boolean;
startLine?: number;
endLine?: number;
},
) {
const [file, root] = splitPath(fileName, repoPath, true);
const params = ['blame', '--root', '--incremental'];
if (options?.ignoreWhitespace) {
params.push('-w');
}
if (options?.startLine != null && options.endLine != null) {
params.push(`-L ${options.startLine},${options.endLine}`);
}
if (options?.args != null) {
// See if the args contains a value like: `--ignore-revs-file <file>` or `--ignore-revs-file=<file>` to account for user error
// If so split it up into two args
const argIndex = options.args.findIndex(
arg => arg !== '--ignore-revs-file' && arg.startsWith('--ignore-revs-file'),
);
if (argIndex !== -1) {
const match = /^--ignore-revs-file\s*=?\s*(.*)$/.exec(options.args[argIndex]);
if (match != null) {
options.args.splice(argIndex, 1, '--ignore-revs-file', match[1]);
}
}
params.push(...options.args);
}
// Ensure the version of Git supports the --ignore-revs-file flag, otherwise the blame will fail
let supportsIgnoreRevsFile = this.maybeIsAtLeastVersion('2.23');
if (supportsIgnoreRevsFile === undefined) {
supportsIgnoreRevsFile = await this.isAtLeastVersion('2.23');
}
const ignoreRevsIndex = params.indexOf('--ignore-revs-file');
if (supportsIgnoreRevsFile) {
let ignoreRevsFile;
if (ignoreRevsIndex !== -1) {
ignoreRevsFile = params[ignoreRevsIndex + 1];
if (!isAbsolute(ignoreRevsFile)) {
ignoreRevsFile = joinPaths(root, ignoreRevsFile);
}
} else {
ignoreRevsFile = joinPaths(root, '.git-blame-ignore-revs');
}
const exists = this.ignoreRevsFileMap.get(ignoreRevsFile);
if (exists !== undefined) {
supportsIgnoreRevsFile = exists;
} else {
// Ensure the specified --ignore-revs-file exists, otherwise the blame will fail
try {
supportsIgnoreRevsFile = await fsExists(ignoreRevsFile);
} catch {
supportsIgnoreRevsFile = false;
}
this.ignoreRevsFileMap.set(ignoreRevsFile, supportsIgnoreRevsFile);
}
}
if (!supportsIgnoreRevsFile && ignoreRevsIndex !== -1) {
params.splice(ignoreRevsIndex, 2);
} else if (supportsIgnoreRevsFile && ignoreRevsIndex === -1) {
params.push('--ignore-revs-file', '.git-blame-ignore-revs');
}
let stdin;
if (options?.contents != null) {
// Pipe the blame contents to stdin
params.push('--contents', '-');
stdin = options.contents;
} else if (options?.ref) {
if (isUncommittedStaged(options.ref)) {
// Pipe the blame contents to stdin
params.push('--contents', '-');
// Get the file contents for the staged version using `:`
stdin = await this.show__content<string>(repoPath, fileName, ':');
} else {
params.push(options.ref);
}
}
try {
const blame = await this.git<string>(
{ cwd: root, stdin: stdin, correlationKey: options?.correlationKey },
...params,
'--',
file,
);
return blame;
} catch (ex) {
// Since `-c blame.ignoreRevsFile=` doesn't seem to work (unlike as the docs suggest), try to detect the error and throw a more helpful one
let match = GitErrors.invalidObjectNameList.exec(ex.message);
if (match != null) {
throw new BlameIgnoreRevsFileError(match[1], ex);
}
match = GitErrors.invalidObjectName.exec(ex.message);
if (match != null) {
throw new BlameIgnoreRevsFileBadRevisionError(match[1], ex);
}
throw ex;
}
}
branch(repoPath: string, ...args: string[]) {
return this.git<string>({ cwd: repoPath }, 'branch', ...args);
}
branch__set_upstream(repoPath: string, branch: string, remote: string, remoteBranch: string) {
return this.git<string>({ cwd: repoPath }, 'branch', '--set-upstream-to', `${remote}/${remoteBranch}`, branch);
}
branchOrTag__containsOrPointsAt(
repoPath: string,
refs: string[],
options?: {
type?: 'branch' | 'tag';
all?: boolean;
mode?: 'contains' | 'pointsAt';
name?: string;
remotes?: boolean;
},
) {
const params: string[] = [options?.type ?? 'branch'];
if (options?.all) {
params.push('-a');
} else if (options?.remotes) {
params.push('-r');
}
params.push('--format=%(refname:short)');
for (const ref of refs) {
params.push(options?.mode === 'pointsAt' ? `--points-at=${ref}` : `--contains=${ref}`);
}
if (options?.name != null) {
params.push(options.name);
}
return this.git<string>(
{ cwd: repoPath, configs: gitBranchDefaultConfigs, errors: GitErrorHandling.Ignore },
...params,
);
}
async cat_file__size(repoPath: string, oid: string): Promise<number> {
const data = await this.git<string>({ cwd: repoPath }, 'cat-file', '-s', oid);
return data.length ? parseInt(data.trim(), 10) : 0;
}
check_ignore(repoPath: string, ...files: string[]) {
return this.git<string>(
{ cwd: repoPath, errors: GitErrorHandling.Ignore, stdin: files.join('\0') },
'check-ignore',
'-z',
'--stdin',
);
}
check_mailmap(repoPath: string, author: string) {
return this.git<string>({ cwd: repoPath, errors: GitErrorHandling.Ignore }, 'check-mailmap', author);
}
async check_ref_format(ref: string, repoPath?: string, options: { branch?: boolean } = { branch: true }) {
const params = ['check-ref-format'];
if (options.branch) {
params.push('--branch');
} else {
params.push('--normalize');
}
try {
const data = await this.git<string>(
{ cwd: repoPath ?? '', errors: GitErrorHandling.Throw },
...params,
ref,
);
return Boolean(data.trim());
} catch {
return false;
}
}
checkout(repoPath: string, ref: string, { createBranch, path }: { createBranch?: string; path?: string } = {}) {
const params = ['checkout'];
if (createBranch) {
params.push('-b', createBranch, ref, '--');
} else {
params.push(ref, '--');
if (path) {
[path, repoPath] = splitPath(path, repoPath, true);
params.push(path);
}
}
return this.git<string>({ cwd: repoPath }, ...params);
}
async cherrypick(repoPath: string, sha: string, options: { noCommit?: boolean; errors?: GitErrorHandling } = {}) {
const params = ['cherry-pick'];
if (options?.noCommit) {
params.push('-n');
}
params.push(sha);
try {
await this.git<string>({ cwd: repoPath, errors: options?.errors }, ...params);
} catch (ex) {
const msg: string = ex?.toString() ?? '';
let reason: CherryPickErrorReason = CherryPickErrorReason.Other;
if (
GitErrors.changesWouldBeOverwritten.test(msg) ||
GitErrors.changesWouldBeOverwritten.test(ex.stderr ?? '')
) {
reason = CherryPickErrorReason.AbortedWouldOverwrite;
} else if (GitErrors.conflict.test(msg) || GitErrors.conflict.test(ex.stdout ?? '')) {
reason = CherryPickErrorReason.Conflicts;
}
throw new CherryPickError(reason, ex, sha);
}
}
// TODO: Expand to include options and other params
async clone(url: string, parentPath: string): Promise<string | undefined> {
let count = 0;
const [, , remotePath] = parseGitRemoteUrl(url);
const remoteName = remotePath.split('/').pop();
if (!remoteName) return undefined;
let folderPath = joinPath(parentPath, remoteName);
while ((await fsExists(folderPath)) && count < 20) {
count++;
folderPath = joinPath(parentPath, `${remotePath}-${count}`);
}
await this.git<string>({ cwd: parentPath }, 'clone', url, folderPath);
return folderPath;
}
async config__get(key: string, repoPath?: string, options?: { local?: boolean }) {
const data = await this.git<string>(
{ cwd: repoPath ?? '', errors: GitErrorHandling.Ignore, local: options?.local },
'config',
'--get',
key,
);
return data.length === 0 ? undefined : data.trim();
}
async config__get_regex(pattern: string, repoPath?: string, options?: { local?: boolean }) {
const data = await this.git<string>(
{ cwd: repoPath ?? '', errors: GitErrorHandling.Ignore, local: options?.local },
'config',
'--get-regex',
pattern,
);
return data.length === 0 ? undefined : data.trim();
}
async config__set(key: string, value: string | undefined, repoPath?: string) {
const params = ['config', '--local'];
if (value == null) {
params.push('--unset', key);
} else {
params.push(key, value);
}
await this.git<string>({ cwd: repoPath ?? '', local: true }, ...params);
}
async diff(
repoPath: string,
fileName: string,
ref1?: string,
ref2?: string,
options: {
encoding?: string;
filters?: GitDiffFilter[];
linesOfContext?: number;
renames?: boolean;
similarityThreshold?: number | null;
} = {},
): Promise<string> {
const params = ['diff', '--no-ext-diff', '--minimal'];
if (options.linesOfContext != null) {
params.push(`-U${options.linesOfContext}`);
}
if (options.renames) {
params.push(`-M${options.similarityThreshold == null ? '' : `${options.similarityThreshold}%`}`);
}
if (options.filters != null && options.filters.length !== 0) {
params.push(`--diff-filter=${options.filters.join('')}`);
}
if (ref1) {
// <sha>^3 signals an untracked file in a stash and if we are trying to find its parent, use the root sha
if (ref1.endsWith('^3^')) {
ref1 = rootSha;
}
params.push(isUncommittedStaged(ref1) ? '--staged' : ref1);
}
if (ref2) {
params.push(isUncommittedStaged(ref2) ? '--staged' : ref2);
}
try {
return await this.git<string>(
{
cwd: repoPath,
configs: gitDiffDefaultConfigs,
encoding: options.encoding,
},
...params,
'--',
fileName,
);
} catch (ex) {
const match = GitErrors.badRevision.exec(ex.message);
if (match !== null) {
const [, ref] = match;
// If the bad ref is trying to find a parent ref, assume we hit to the last commit, so try again using the root sha
if (ref === ref1 && ref?.endsWith('^')) {
return this.diff(repoPath, fileName, rootSha, ref2, options);
}
}
throw ex;
}
}
async diff2(
repoPath: string,
options?: {
cancellation?: CancellationToken;
configs?: readonly string[];
errors?: GitErrorHandling;
stdin?: string;
},
...args: string[]
) {
return this.git<string>(
{
cwd: repoPath,
cancellation: options?.cancellation,
configs: options?.configs ?? gitLogDefaultConfigs,
errors: options?.errors,
stdin: options?.stdin,
},
'diff',
...(options?.stdin ? ['--stdin'] : emptyArray),
...args,
...(!args.includes('--') ? ['--'] : emptyArray),
);
}
async diff__contents(
repoPath: string,
fileName: string,
ref: string,
contents: string,
options: { encoding?: string; filters?: GitDiffFilter[]; similarityThreshold?: number | null } = {},
): Promise<string> {
const params = [
'diff',
`-M${options.similarityThreshold == null ? '' : `${options.similarityThreshold}%`}`,
'--no-ext-diff',
'-U0',
'--minimal',
];
if (options.filters != null && options.filters.length !== 0) {
params.push(`--diff-filter=${options.filters.join('')}`);
}
// // <sha>^3 signals an untracked file in a stash and if we are trying to find its parent, use the root sha
// if (ref.endsWith('^3^')) {
// ref = rootSha;
// }
// params.push(isUncommittedStaged(ref) ? '--staged' : ref);
params.push('--no-index');
try {
return await this.git<string>(
{
cwd: repoPath,
configs: gitDiffDefaultConfigs,
encoding: options.encoding,
stdin: contents,
},
...params,
'--',
fileName,
// Pipe the contents to stdin
'-',
);
} catch (ex) {
if (ex instanceof RunError && ex.stdout) {
return ex.stdout;
}
const match = GitErrors.badRevision.exec(ex.message);
if (match !== null) {
const [, matchedRef] = match;
// If the bad ref is trying to find a parent ref, assume we hit to the last commit, so try again using the root sha
if (matchedRef === ref && matchedRef?.endsWith('^')) {
return this.diff__contents(repoPath, fileName, rootSha, contents, options);
}
}
throw ex;
}
}
diff__name_status(
repoPath: string,
ref1?: string,
ref2?: string,
options?: { filters?: GitDiffFilter[]; path?: string; similarityThreshold?: number },
) {
const params = [
'diff',
'--name-status',
`-M${options?.similarityThreshold == null ? '' : `${options?.similarityThreshold}%`}`,
'--no-ext-diff',
'-z',
];
if (options?.filters?.length) {
params.push(`--diff-filter=${options.filters.join('')}`);
}
if (ref1) {
params.push(ref1);
}
if (ref2) {
params.push(ref2);
}
params.push('--');
if (options?.path) {
params.push(options.path);
}
return this.git<string>({ cwd: repoPath, configs: gitDiffDefaultConfigs }, ...params);
}
async diff__shortstat(repoPath: string, ref?: string) {
const params = ['diff', '--shortstat', '--no-ext-diff'];
if (ref) {
params.push(ref);
}
try {
return await this.git<string>({ cwd: repoPath, configs: gitDiffDefaultConfigs }, ...params, '--');
} catch (ex) {
const msg: string = ex?.toString() ?? '';
if (GitErrors.noMergeBase.test(msg)) {
return undefined;
}
throw ex;
}
}
difftool(
repoPath: string,
fileName: string,
tool: string,
options: { ref1?: string; ref2?: string; staged?: boolean } = {},
) {
const params = ['difftool', '--no-prompt', `--tool=${tool}`];
if (options.staged) {
params.push('--staged');
}
if (options.ref1) {
params.push(options.ref1);
}
if (options.ref2) {
params.push(options.ref2);
}
return this.git<string>({ cwd: repoPath }, ...params, '--', fileName);
}
difftool__dir_diff(repoPath: string, tool: string, ref1: string, ref2?: string) {
const params = ['difftool', '--dir-diff', `--tool=${tool}`, ref1];
if (ref2) {
params.push(ref2);
}
return this.git<string>({ cwd: repoPath }, ...params);
}
async fetch(
repoPath: string,
options:
| { all?: boolean; branch?: undefined; prune?: boolean; pull?: boolean; remote?: string }
| {
all?: undefined;
branch: string;
prune?: undefined;
pull?: boolean;
remote: string;
upstream: string;
} = {},
): Promise<void> {
const params = ['fetch'];
if (options.prune) {
params.push('--prune');
}
if (options.branch && options.remote) {
if (options.upstream && options.pull) {
params.push('-u', options.remote, `${options.upstream}:${options.branch}`);
} else {
params.push(options.remote, options.upstream || options.branch);
}
} else if (options.remote) {
params.push(options.remote);
} else if (options.all) {
params.push('--all');
}
try {
void (await this.git<string>({ cwd: repoPath }, ...params));
} catch (ex) {
const msg: string = ex?.toString() ?? '';
let reason: FetchErrorReason = FetchErrorReason.Other;
if (GitErrors.noFastForward.test(msg) || GitErrors.noFastForward.test(ex.stderr ?? '')) {
reason = FetchErrorReason.NoFastForward;
} else if (
GitErrors.noRemoteRepositorySpecified.test(msg) ||
GitErrors.noRemoteRepositorySpecified.test(ex.stderr ?? '')
) {
reason = FetchErrorReason.NoRemote;
} else if (GitErrors.remoteConnection.test(msg) || GitErrors.remoteConnection.test(ex.stderr ?? '')) {
reason = FetchErrorReason.RemoteConnection;
}
throw new FetchError(reason, ex, options?.branch, options?.remote);
}
}
async push(
repoPath: string,
options: {
branch?: string;
force?: PushForceOptions;
publish?: boolean;
remote?: string;
upstream?: string;
},
): Promise<void> {
const params = ['push'];
if (options.force != null) {
if (options.force.withLease) {
params.push('--force-with-lease');
if (options.force.ifIncludes) {
if (await this.isAtLeastVersion('2.30.0')) {
params.push('--force-if-includes');
}
}
} else {
params.push('--force');
}
}
if (options.branch && options.remote) {
if (options.upstream) {
params.push('-u', options.remote, `${options.branch}:${options.upstream}`);
} else if (options.publish) {
params.push('--set-upstream', options.remote, options.branch);