-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathlocalGitProvider.ts
6501 lines (5553 loc) · 187 KB
/
localGitProvider.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 { exec } from 'child_process';
import { promises as fs, readdir, realpath } from 'fs';
import { homedir, hostname, tmpdir, userInfo } from 'os';
import path, { resolve as resolvePath } from 'path';
import { env as process_env } from 'process';
import { md5 } from '@env/crypto';
import { fetch, getProxyAgent } from '@env/fetch';
import { hrtime } from '@env/hrtime';
import { isLinux, isWindows } from '@env/platform';
import type { CancellationToken, Event, TextDocument, WorkspaceFolder } from 'vscode';
import { Disposable, env, EventEmitter, extensions, FileType, Range, Uri, window, workspace } from 'vscode';
import type { GitExtension, API as ScmGitApi } from '../../../@types/vscode.git';
import { getCachedAvatarUri } from '../../../avatars';
import type { GitConfigKeys } from '../../../constants';
import { GlyphChars, Schemes } from '../../../constants';
import type { SearchQuery } from '../../../constants.search';
import type { Container } from '../../../container';
import { emojify } from '../../../emojis';
import { CancellationError } from '../../../errors';
import { Features } from '../../../features';
import { GitErrorHandling } from '../../../git/commandOptions';
import {
ApplyPatchCommitError,
ApplyPatchCommitErrorReason,
BlameIgnoreRevsFileBadRevisionError,
BlameIgnoreRevsFileError,
CherryPickError,
CherryPickErrorReason,
FetchError,
GitSearchError,
PullError,
PushError,
PushErrorReason,
StashApplyError,
StashApplyErrorReason,
StashPushError,
TagError,
WorktreeCreateError,
WorktreeCreateErrorReason,
WorktreeDeleteError,
WorktreeDeleteErrorReason,
} from '../../../git/errors';
import type {
BranchContributorOverview,
GitCaches,
GitDir,
GitProvider,
GitProviderDescriptor,
LeftRightCommitCountResult,
NextComparisonUrisResult,
PagedResult,
PagingOptions,
PreviousComparisonUrisResult,
PreviousLineComparisonUrisResult,
RepositoryCloseEvent,
RepositoryInitWatcher,
RepositoryOpenEvent,
RepositoryVisibility,
RevisionUriData,
ScmRepository,
} from '../../../git/gitProvider';
import { GitUri, isGitUri } from '../../../git/gitUri';
import { encodeGitLensRevisionUriAuthority } from '../../../git/gitUri.authority';
import type { GitBlame, GitBlameAuthor, GitBlameLine } from '../../../git/models/blame';
import type { BranchSortOptions } from '../../../git/models/branch';
import {
getBranchId,
getBranchNameAndRemote,
getBranchNameWithoutRemote,
getRemoteNameFromBranchName,
GitBranch,
isDetachedHead,
sortBranches,
} from '../../../git/models/branch';
import type { GitStashCommit } from '../../../git/models/commit';
import { GitCommit, GitCommitIdentity } from '../../../git/models/commit';
import { deletedOrMissing, uncommitted, uncommittedStaged } from '../../../git/models/constants';
import type { GitContributorStats } from '../../../git/models/contributor';
import { GitContributor, sortContributors } from '../../../git/models/contributor';
import type {
GitDiff,
GitDiffFile,
GitDiffFiles,
GitDiffFilter,
GitDiffLine,
GitDiffShortStat,
} from '../../../git/models/diff';
import type { GitFile, GitFileStatus } from '../../../git/models/file';
import { GitFileChange, GitFileWorkingTreeStatus, mapFilesWithStats } from '../../../git/models/file';
import type {
GitGraph,
GitGraphRow,
GitGraphRowContexts,
GitGraphRowHead,
GitGraphRowRemoteHead,
GitGraphRowsStats,
GitGraphRowStats,
GitGraphRowTag,
} from '../../../git/models/graph';
import type { GitLog } from '../../../git/models/log';
import type { GitMergeStatus } from '../../../git/models/merge';
import type { GitRebaseStatus } from '../../../git/models/rebase';
import type {
GitBranchReference,
GitReference,
GitRevisionRange,
GitTagReference,
} from '../../../git/models/reference';
import {
createReference,
createRevisionRange,
getBranchTrackingWithoutRemote,
getReferenceFromBranch,
isBranchReference,
isRevisionRange,
isSha,
isShaLike,
isUncommitted,
isUncommittedStaged,
shortenRevision,
} from '../../../git/models/reference';
import type { GitReflog } from '../../../git/models/reflog';
import type { GitRemote } from '../../../git/models/remote';
import { getRemoteIconUri, getVisibilityCacheKey, sortRemotes } from '../../../git/models/remote';
import { RemoteResourceType } from '../../../git/models/remoteResource';
import type { RepositoryChangeEvent } from '../../../git/models/repository';
import { Repository, RepositoryChange, RepositoryChangeComparisonMode } from '../../../git/models/repository';
import type { GitStash } from '../../../git/models/stash';
import type { GitStatusFile } from '../../../git/models/status';
import { GitStatus } from '../../../git/models/status';
import type { GitTag, TagSortOptions } from '../../../git/models/tag';
import { getTagId, sortTags } from '../../../git/models/tag';
import type { GitTreeEntry } from '../../../git/models/tree';
import type { GitUser } from '../../../git/models/user';
import { isUserMatch } from '../../../git/models/user';
import type { GitWorktree } from '../../../git/models/worktree';
import { getWorktreeId, groupWorktreesByBranch } from '../../../git/models/worktree';
import { parseGitBlame } from '../../../git/parsers/blameParser';
import { parseGitBranches } from '../../../git/parsers/branchParser';
import {
parseGitApplyFiles,
parseGitDiffNameStatusFiles,
parseGitDiffShortStat,
parseGitFileDiff,
} from '../../../git/parsers/diffParser';
import type { ParserWithFilesAndMaybeStats } from '../../../git/parsers/logParser';
import {
createLogParserSingle,
createLogParserWithFiles,
createLogParserWithFilesAndStats,
getContributorsParser,
getGraphParser,
getGraphStatsParser,
getRefAndDateParser,
getRefParser,
LogType,
parseGitLog,
parseGitLogAllFormat,
parseGitLogDefaultFormat,
parseGitLogSimple,
parseGitLogSimpleFormat,
parseGitLogSimpleRenamed,
} from '../../../git/parsers/logParser';
import { parseGitRefLog, parseGitRefLogDefaultFormat } from '../../../git/parsers/reflogParser';
import { parseGitRemotes } from '../../../git/parsers/remoteParser';
import { parseGitStatus } from '../../../git/parsers/statusParser';
import { parseGitTags, parseGitTagsDefaultFormat } from '../../../git/parsers/tagParser';
import { parseGitLsFiles, parseGitTree } from '../../../git/parsers/treeParser';
import { parseGitWorktrees } from '../../../git/parsers/worktreeParser';
import { getRemoteProviderMatcher, loadRemoteProviders } from '../../../git/remotes/remoteProviders';
import type { GitSearch, GitSearchResultData, GitSearchResults } from '../../../git/search';
import { getGitArgsFromSearchQuery, getSearchQueryComparisonKey } from '../../../git/search';
import {
showBlameInvalidIgnoreRevsFileWarningMessage,
showGenericErrorMessage,
showGitDisabledErrorMessage,
showGitInvalidConfigErrorMessage,
showGitMissingErrorMessage,
showGitVersionUnsupportedErrorMessage,
} from '../../../messages';
import type {
GraphBranchContextValue,
GraphItemContext,
GraphItemRefContext,
GraphItemRefGroupContext,
GraphTagContextValue,
} from '../../../plus/webviews/graph/protocol';
import { asRepoComparisonKey } from '../../../repositories';
import { countStringLength, filterMap } from '../../../system/array';
import { gate } from '../../../system/decorators/gate';
import { debug, log } from '../../../system/decorators/log';
import { debounce } from '../../../system/function';
import {
filterMap as filterMapIterable,
find,
first,
join,
last,
map,
min,
skip,
some,
} from '../../../system/iterable';
import { Logger } from '../../../system/logger';
import type { LogScope } from '../../../system/logger.scope';
import { getLogScope, setLogScopeExit } from '../../../system/logger.scope';
import {
commonBaseIndex,
dirname,
isAbsolute,
isFolderGlob,
joinPaths,
maybeUri,
normalizePath,
pathEquals,
} from '../../../system/path';
import type { PromiseOrValue } from '../../../system/promise';
import { any, asSettled, getSettledValue } from '../../../system/promise';
import { equalsIgnoreCase, getDurationMilliseconds, interpolate, splitSingle } from '../../../system/string';
import { PathTrie } from '../../../system/trie';
import { compare, fromString } from '../../../system/version';
import { TimedCancellationSource } from '../../../system/vscode/cancellation';
import { configuration } from '../../../system/vscode/configuration';
import { getBestPath, relative, splitPath } from '../../../system/vscode/path';
import { serializeWebviewItemContext } from '../../../system/webview';
import type { CachedBlame, CachedDiff, CachedLog, TrackedGitDocument } from '../../../trackers/trackedDocument';
import { GitDocumentState } from '../../../trackers/trackedDocument';
import { registerCommitMessageProvider } from './commitMessageProvider';
import type { Git, PushForceOptions } from './git';
import {
getShaInLogRegex,
GitErrors,
gitLogDefaultConfigs,
gitLogDefaultConfigsWithFiles,
maxGitCliLength,
} from './git';
import type { GitLocation } from './locator';
import { findGitPath, InvalidGitConfigError, UnableToFindGitError } from './locator';
import { CancelledRunError, fsExists, RunError } from './shell';
const emptyArray = Object.freeze([]) as unknown as any[];
const emptyPromise: Promise<GitBlame | GitDiffFile | GitLog | undefined> = Promise.resolve(undefined);
const emptyPagedResult: PagedResult<any> = Object.freeze({ values: [] });
const slash = 47;
const RepoSearchWarnings = {
doesNotExist: /no such file or directory/i,
};
const driveLetterRegex = /(?<=^\/?)([a-zA-Z])(?=:\/)/;
const userConfigRegex = /^user\.(name|email) (.*)$/gm;
const mappedAuthorRegex = /(.+)\s<(.+)>/;
const stashSummaryRegex =
// eslint-disable-next-line no-control-regex
/(?:(?:(?<wip>WIP) on|On) (?<onref>[^/](?!.*\/\.)(?!.*\.\.)(?!.*\/\/)(?!.*@\{)[^\x00-\x1F\x7F ~^:?*[\\]+[^./]):\s*)?(?<summary>.*)$/s;
const reflogCommands = ['merge', 'pull'];
interface RepositoryInfo {
gitDir?: GitDir;
user?: GitUser | null;
}
export class LocalGitProvider implements GitProvider, Disposable {
readonly descriptor: GitProviderDescriptor = { id: 'git', name: 'Git', virtual: false };
readonly supportedSchemes = new Set<string>([
Schemes.File,
Schemes.Git,
Schemes.GitLens,
Schemes.PRs,
// DocumentSchemes.Vsls,
]);
private _onDidChange = new EventEmitter<void>();
get onDidChange(): Event<void> {
return this._onDidChange.event;
}
private _onDidChangeRepository = new EventEmitter<RepositoryChangeEvent>();
get onDidChangeRepository(): Event<RepositoryChangeEvent> {
return this._onDidChangeRepository.event;
}
private _onDidCloseRepository = new EventEmitter<RepositoryCloseEvent>();
get onDidCloseRepository(): Event<RepositoryCloseEvent> {
return this._onDidCloseRepository.event;
}
private _onDidOpenRepository = new EventEmitter<RepositoryOpenEvent>();
get onDidOpenRepository(): Event<RepositoryOpenEvent> {
return this._onDidOpenRepository.event;
}
private readonly _branchCache = new Map<string, Promise<GitBranch | undefined>>();
private readonly _branchesCache = new Map<string, Promise<PagedResult<GitBranch>>>();
private readonly _contributorsCache = new Map<string, Map<string, Promise<GitContributor[]>>>();
private readonly _mergeStatusCache = new Map<string, Promise<GitMergeStatus | undefined>>();
private readonly _rebaseStatusCache = new Map<string, Promise<GitRebaseStatus | undefined>>();
private readonly _remotesCache = new Map<string, Promise<GitRemote[]>>();
private readonly _repoInfoCache = new Map<string, RepositoryInfo>();
private readonly _stashesCache = new Map<string, GitStash | null>();
private readonly _tagsCache = new Map<string, Promise<PagedResult<GitTag>>>();
private readonly _trackedPaths = new PathTrie<PromiseOrValue<[string, string] | undefined>>();
private readonly _worktreesCache = new Map<string, Promise<GitWorktree[]>>();
private _disposables: Disposable[] = [];
constructor(
protected readonly container: Container,
protected readonly git: Git,
) {
this.git.setLocator(this.ensureGit.bind(this));
this._disposables.push(
configuration.onDidChange(e => {
if (configuration.changed(e, 'remotes')) {
this.resetCaches(undefined, 'remotes');
}
}, this),
this.container.events.on('git:cache:reset', e =>
this.resetCaches(e.data.repoPath, ...(e.data.caches ?? emptyArray)),
),
);
}
dispose() {
Disposable.from(...this._disposables).dispose();
}
private get useCaching() {
return configuration.get('advanced.caching.enabled');
}
private onRepositoryChanged(repo: Repository, e: RepositoryChangeEvent) {
if (e.changed(RepositoryChange.Config, RepositoryChangeComparisonMode.Any)) {
this._repoInfoCache.delete(repo.path);
}
if (e.changed(RepositoryChange.Heads, RepositoryChange.Remotes, RepositoryChangeComparisonMode.Any)) {
this._branchCache.delete(repo.path);
this._branchesCache.delete(repo.path);
this._contributorsCache.delete(repo.path);
this._worktreesCache.delete(repo.path);
}
if (e.changed(RepositoryChange.Remotes, RepositoryChange.RemoteProviders, RepositoryChangeComparisonMode.Any)) {
this._remotesCache.delete(repo.path);
}
if (e.changed(RepositoryChange.Index, RepositoryChange.Unknown, RepositoryChangeComparisonMode.Any)) {
this._trackedPaths.clear();
}
if (e.changed(RepositoryChange.Merge, RepositoryChangeComparisonMode.Any)) {
this._branchCache.delete(repo.path);
this._mergeStatusCache.delete(repo.path);
}
if (e.changed(RepositoryChange.Rebase, RepositoryChangeComparisonMode.Any)) {
this._branchCache.delete(repo.path);
this._rebaseStatusCache.delete(repo.path);
}
if (e.changed(RepositoryChange.Stash, RepositoryChangeComparisonMode.Any)) {
this._stashesCache.delete(repo.path);
}
if (e.changed(RepositoryChange.Tags, RepositoryChangeComparisonMode.Any)) {
this._tagsCache.delete(repo.path);
}
if (e.changed(RepositoryChange.Worktrees, RepositoryChangeComparisonMode.Any)) {
this._worktreesCache.delete(repo.path);
}
this._onDidChangeRepository.fire(e);
}
private _gitLocator: Promise<GitLocation> | undefined;
private async ensureGit(): Promise<GitLocation> {
if (this._gitLocator == null) {
this._gitLocator = this.findGit();
}
return this._gitLocator;
}
@log()
private async findGit(): Promise<GitLocation> {
const scope = getLogScope();
if (!configuration.getCore('git.enabled', null, true)) {
Logger.log(scope, 'Built-in Git is disabled ("git.enabled": false)');
void showGitDisabledErrorMessage();
throw new UnableToFindGitError();
}
const scmGitPromise = this.getScmGitApi();
async function subscribeToScmOpenCloseRepository(this: LocalGitProvider) {
const scmGit = await scmGitPromise;
if (scmGit == null) return;
registerCommitMessageProvider(this.container, scmGit);
// Find env to pass to Git
for (const v of Object.values(scmGit.git)) {
if (v != null && typeof v === 'object' && 'git' in v) {
for (const vv of Object.values(v.git)) {
if (vv != null && typeof vv === 'object' && 'GIT_ASKPASS' in vv) {
Logger.debug(scope, 'Found built-in Git env');
this.git.setEnv(vv);
break;
}
}
}
}
const closing = new Set<Uri>();
const fireRepositoryClosed = debounce(() => {
if (this.container.deactivating) return;
for (const uri of closing) {
this._onDidCloseRepository.fire({ uri: uri });
}
closing.clear();
}, 1000);
this._disposables.push(
// Since we will get "close" events for repos when vscode is shutting down, debounce the event so ensure we aren't shutting down
scmGit.onDidCloseRepository(e => {
if (this.container.deactivating) return;
closing.add(e.rootUri);
fireRepositoryClosed();
}),
scmGit.onDidOpenRepository(e => this._onDidOpenRepository.fire({ uri: e.rootUri })),
);
for (const scmRepository of scmGit.repositories) {
this._onDidOpenRepository.fire({ uri: scmRepository.rootUri });
}
}
void subscribeToScmOpenCloseRepository.call(this);
const canCacheGitPath = configuration.get('advanced.caching.gitPath');
const potentialGitPaths =
configuration.getCore('git.path') ??
(canCacheGitPath ? this.container.storage.getWorkspace('gitPath') : undefined);
const start = hrtime();
const findGitPromise = findGitPath(potentialGitPaths);
// Try to use the same git as the built-in vscode git extension, but don't wait for it if we find something faster
const findGitFromSCMPromise = scmGitPromise.then(gitApi => {
const path = gitApi?.git.path;
if (!path) return findGitPromise;
if (potentialGitPaths != null) {
if (typeof potentialGitPaths === 'string') {
if (path === potentialGitPaths) return findGitPromise;
} else if (potentialGitPaths.includes(path)) {
return findGitPromise;
}
}
return findGitPath(path, false);
});
const location = await any<GitLocation>(findGitPromise, findGitFromSCMPromise);
// Save the found git path, but let things settle first to not impact startup performance
setTimeout(
() =>
void this.container.storage
.storeWorkspace('gitPath', canCacheGitPath ? location.path : undefined)
.catch(),
1000,
);
if (scope != null) {
setLogScopeExit(
scope,
` ${GlyphChars.Dot} Git (${location.version}) found in ${
location.path === 'git' ? 'PATH' : location.path
}`,
);
} else {
Logger.log(
scope,
`Git (${location.version}) found in ${
location.path === 'git' ? 'PATH' : location.path
} [${getDurationMilliseconds(start)}ms]`,
);
}
// Warn if git is less than v2.7.2
if (compare(fromString(location.version), fromString('2.7.2')) === -1) {
Logger.log(scope, `Git version (${location.version}) is outdated`);
void showGitVersionUnsupportedErrorMessage(location.version, '2.7.2');
}
return location;
}
@debug({ exit: true })
async discoverRepositories(
uri: Uri,
options?: { cancellation?: CancellationToken; depth?: number; silent?: boolean },
): Promise<Repository[]> {
if (uri.scheme !== Schemes.File) return [];
try {
const autoRepositoryDetection = configuration.getCore('git.autoRepositoryDetection') ?? true;
const folder = workspace.getWorkspaceFolder(uri);
if (folder == null && !options?.silent) return [];
void (await this.ensureGit());
if (options?.cancellation?.isCancellationRequested) return [];
const repositories = await this.repositorySearch(
folder ?? uri,
options?.depth ??
(autoRepositoryDetection === false || autoRepositoryDetection === 'openEditors' ? 0 : undefined),
options?.cancellation,
options?.silent,
);
if (!options?.silent && (autoRepositoryDetection === true || autoRepositoryDetection === 'subFolders')) {
for (const repository of repositories) {
void this.getOrOpenScmRepository(repository.uri);
}
}
if (!options?.silent && repositories.length > 0) {
this._trackedPaths.clear();
}
return repositories;
} catch (ex) {
if (ex instanceof InvalidGitConfigError) {
void showGitInvalidConfigErrorMessage();
} else if (ex instanceof UnableToFindGitError) {
void showGitMissingErrorMessage();
} else {
const msg: string = ex?.message ?? '';
if (msg && !options?.silent) {
void window.showErrorMessage(`Unable to initialize Git; ${msg}`);
}
}
throw ex;
}
}
@debug({ exit: true })
openRepository(
folder: WorkspaceFolder | undefined,
uri: Uri,
root: boolean,
suspended?: boolean,
closed?: boolean,
): Repository[] {
if (!closed) {
void this.getOrOpenScmRepository(uri);
}
const opened = [
new Repository(
this.container,
this.onRepositoryChanged.bind(this),
this.descriptor,
folder ?? workspace.getWorkspaceFolder(uri),
uri,
root,
suspended ?? !window.state.focused,
closed,
),
];
// Add a closed (hidden) repository for the canonical version if not already opened
const canonicalUri = this.toCanonicalMap.get(getBestPath(uri));
if (canonicalUri != null && this.container.git.getRepository(canonicalUri) == null) {
opened.push(
new Repository(
this.container,
this.onRepositoryChanged.bind(this),
this.descriptor,
folder ?? workspace.getWorkspaceFolder(canonicalUri),
canonicalUri,
root,
suspended ?? !window.state.focused,
true,
),
);
}
return opened;
}
@debug({ singleLine: true })
openRepositoryInitWatcher(): RepositoryInitWatcher {
const watcher = workspace.createFileSystemWatcher('**/.git', false, true, true);
return {
onDidCreate: watcher.onDidCreate,
dispose: () => void watcher.dispose(),
};
}
private _supportedFeatures = new Map<Features, boolean>();
async supports(feature: Features): Promise<boolean> {
let supported = this._supportedFeatures.get(feature);
if (supported != null) return supported;
switch (feature) {
case Features.Worktrees:
supported = await this.git.isAtLeastVersion('2.17.0');
this._supportedFeatures.set(feature, supported);
return supported;
case Features.StashOnlyStaged:
supported = await this.git.isAtLeastVersion('2.35.0');
this._supportedFeatures.set(feature, supported);
return supported;
case Features.ForceIfIncludes:
supported = await this.git.isAtLeastVersion('2.30.0');
this._supportedFeatures.set(feature, supported);
return supported;
default:
return true;
}
}
@debug<LocalGitProvider['visibility']>({ exit: r => `returned ${r[0]}` })
async visibility(repoPath: string): Promise<[visibility: RepositoryVisibility, cacheKey: string | undefined]> {
const remotes = await this.getRemotes(repoPath, { sort: true });
if (remotes.length === 0) return ['local', undefined];
let local = true;
for await (const result of asSettled(remotes.map(r => this.getRemoteVisibility(r)))) {
if (result.status !== 'fulfilled') continue;
if (result.value[0] === 'public') {
return ['public', getVisibilityCacheKey(result.value[1])];
}
if (result.value[0] !== 'local') {
local = false;
}
}
return local ? ['local', undefined] : ['private', getVisibilityCacheKey(remotes)];
}
private _pendingRemoteVisibility = new Map<string, ReturnType<typeof fetch>>();
@debug<LocalGitProvider['getRemoteVisibility']>({ args: { 0: r => r.url }, exit: r => `returned ${r[0]}` })
private async getRemoteVisibility(
remote: GitRemote,
): Promise<[visibility: RepositoryVisibility, remote: GitRemote]> {
const scope = getLogScope();
let url;
switch (remote.provider?.id) {
case 'github':
case 'gitlab':
case 'bitbucket':
case 'azure-devops':
case 'gitea':
case 'gerrit':
case 'google-source':
url = remote.provider.url({ type: RemoteResourceType.Repo });
if (url == null) return ['private', remote];
break;
default: {
url = remote.url;
if (!url.includes('git@')) {
return maybeUri(url) ? ['private', remote] : ['local', remote];
}
const [host, repo] = url.split('@')[1].split(':');
if (!host || !repo) return ['private', remote];
url = `https://${host}/${repo}`;
}
}
// Check if the url returns a 200 status code
let promise = this._pendingRemoteVisibility.get(url);
if (promise == null) {
const aborter = new AbortController();
const timer = setTimeout(() => aborter.abort(), 30000);
promise = fetch(url, { method: 'HEAD', agent: getProxyAgent(), signal: aborter.signal });
void promise.finally(() => clearTimeout(timer));
this._pendingRemoteVisibility.set(url, promise);
}
try {
const rsp = await promise;
if (rsp.ok) return ['public', remote];
Logger.debug(scope, `Response=${rsp.status}`);
} catch (ex) {
debugger;
Logger.error(ex, scope);
} finally {
this._pendingRemoteVisibility.delete(url);
}
return ['private', remote];
}
@log<LocalGitProvider['repositorySearch']>({
args: false,
singleLine: true,
prefix: (context, folder) => `${context.prefix}(${(folder instanceof Uri ? folder : folder.uri).fsPath})`,
exit: r => `returned ${r.length} repositories ${r.length !== 0 ? Logger.toLoggable(r) : ''}`,
})
private async repositorySearch(
folderOrUri: Uri | WorkspaceFolder,
depth?: number,
cancellation?: CancellationToken,
silent?: boolean | undefined,
): Promise<Repository[]> {
const scope = getLogScope();
let folder;
let rootUri;
if (folderOrUri instanceof Uri) {
rootUri = folderOrUri;
folder = workspace.getWorkspaceFolder(rootUri);
} else {
rootUri = folderOrUri.uri;
}
depth =
depth ??
configuration.get('advanced.repositorySearchDepth', rootUri) ??
configuration.getCore('git.repositoryScanMaxDepth', rootUri, 1);
Logger.log(scope, `searching (depth=${depth})...`);
const repositories: Repository[] = [];
let rootPath;
let canonicalRootPath;
function maybeAddRepo(this: LocalGitProvider, uri: Uri, folder: WorkspaceFolder | undefined, root: boolean) {
const comparisonId = asRepoComparisonKey(uri);
if (repositories.some(r => r.id === comparisonId)) {
Logger.log(scope, `found ${root ? 'root ' : ''}repository in '${uri.fsPath}'; skipping - duplicate`);
return;
}
const repo = this.container.git.getRepository(uri);
if (repo != null) {
if (repo.closed && silent === false) {
repo.closed = false;
}
Logger.log(scope, `found ${root ? 'root ' : ''}repository in '${uri.fsPath}'; skipping - already open`);
return;
}
Logger.log(scope, `found ${root ? 'root ' : ''}repository in '${uri.fsPath}'`);
repositories.push(...this.openRepository(folder, uri, root, undefined, silent));
}
const uri = await this.findRepositoryUri(rootUri, true);
if (uri != null) {
rootPath = normalizePath(uri.fsPath);
const canonicalUri = this.toCanonicalMap.get(getBestPath(uri));
if (canonicalUri != null) {
canonicalRootPath = normalizePath(canonicalUri.fsPath);
}
maybeAddRepo.call(this, uri, folder, true);
}
if (depth <= 0 || cancellation?.isCancellationRequested) return repositories;
// Get any specified excludes -- this is a total hack, but works for some simple cases and something is better than nothing :)
const excludes = new Set<string>(configuration.getCore('git.repositoryScanIgnoredFolders', rootUri, []));
for (let [key, value] of Object.entries({
...configuration.getCore('files.exclude', rootUri, {}),
...configuration.getCore('search.exclude', rootUri, {}),
})) {
if (!value) continue;
if (key.includes('*.')) continue;
if (key.startsWith('**/')) {
key = key.substring(3);
}
excludes.add(key);
}
let repoPaths;
try {
repoPaths = await this.repositorySearchCore(rootUri.fsPath, depth, excludes, cancellation);
} catch (ex) {
const msg: string = ex?.toString() ?? '';
if (RepoSearchWarnings.doesNotExist.test(msg)) {
Logger.log(scope, `FAILED${msg ? ` Error: ${msg}` : ''}`);
} else {
Logger.error(ex, scope, 'FAILED');
}
return repositories;
}
for (let p of repoPaths) {
p = dirname(p);
const normalized = normalizePath(p);
// If we are the same as the root, skip it
if (
(isLinux &&
(normalized === rootPath || (canonicalRootPath != null && normalized === canonicalRootPath))) ||
equalsIgnoreCase(normalized, rootPath) ||
(canonicalRootPath != null && equalsIgnoreCase(normalized, canonicalRootPath))
) {
continue;
}
Logger.log(scope, `searching in '${p}'...`);
Logger.debug(
scope,
`normalizedRepoPath=${normalized}, rootPath=${rootPath}, canonicalRootPath=${canonicalRootPath}`,
);
const rp = await this.findRepositoryUri(Uri.file(p), true);
if (rp == null) continue;
maybeAddRepo.call(this, rp, folder, false);
}
return repositories;
}
@debug<LocalGitProvider['repositorySearchCore']>({ args: { 2: false, 3: false }, exit: true })
private repositorySearchCore(
root: string,
depth: number,
excludes: Set<string>,
cancellation?: CancellationToken,
repositories: string[] = [],
): Promise<string[]> {
const scope = getLogScope();
if (cancellation?.isCancellationRequested) return Promise.resolve(repositories);
return new Promise<string[]>((resolve, reject) => {
readdir(root, { withFileTypes: true }, async (err, files) => {
if (err != null) {
reject(err);
return;
}
if (files.length === 0) {
resolve(repositories);
return;
}
depth--;
let f;
for (f of files) {
if (cancellation?.isCancellationRequested) break;
if (f.name === '.git') {
repositories.push(resolvePath(root, f.name));
} else if (depth >= 0 && f.isDirectory() && !excludes.has(f.name)) {
try {
await this.repositorySearchCore(
resolvePath(root, f.name),
depth,
excludes,
cancellation,
repositories,
);
} catch (ex) {
Logger.error(ex, scope, 'FAILED');
}
}
}
resolve(repositories);
});
});
}
canHandlePathOrUri(scheme: string, pathOrUri: string | Uri): string | undefined {
if (!this.supportedSchemes.has(scheme)) return undefined;
return getBestPath(pathOrUri);
}
getAbsoluteUri(pathOrUri: string | Uri, base: string | Uri): Uri {
// Convert the base to a Uri if it isn't one
if (typeof base === 'string') {
// If it looks like a Uri parse it
if (maybeUri(base)) {
base = Uri.parse(base, true);
} else {
if (!isAbsolute(base)) {
debugger;
void window.showErrorMessage(
`Unable to get absolute uri between ${
typeof pathOrUri === 'string' ? pathOrUri : pathOrUri.toString(true)
} and ${base}; Base path '${base}' must be an absolute path`,
);
throw new Error(`Base path '${base}' must be an absolute path`);
}
base = Uri.file(base);
}
}
// Short-circuit if the path is relative
if (typeof pathOrUri === 'string') {
const normalized = normalizePath(pathOrUri);
if (!isAbsolute(normalized)) return Uri.joinPath(base, normalized);
}
const relativePath = this.getRelativePath(pathOrUri, base);
return Uri.joinPath(base, relativePath);
}
@log({ exit: true })
async getBestRevisionUri(repoPath: string, path: string, ref: string | undefined): Promise<Uri | undefined> {
if (ref === deletedOrMissing) return undefined;
// TODO@eamodio Align this with isTrackedCore?
if (!ref || (isUncommitted(ref) && !isUncommittedStaged(ref))) {
// Make sure the file exists in the repo
let data = await this.git.ls_files(repoPath, path);
if (data != null) return this.getAbsoluteUri(path, repoPath);
// Check if the file exists untracked
data = await this.git.ls_files(repoPath, path, { untracked: true });
if (data != null) return this.getAbsoluteUri(path, repoPath);
return undefined;
}
// If the ref is the index, then try to create a Uri using the Git extension, but if we can't find a repo for it, then generate our own Uri
if (isUncommittedStaged(ref)) {
let scmRepo = await this.getScmRepository(repoPath);
if (scmRepo == null) {
// If the repoPath is a canonical path, then we need to remap it to the real path, because the vscode.git extension always uses the real path
const realUri = this.fromCanonicalMap.get(repoPath);
if (realUri != null) {
scmRepo = await this.getScmRepository(realUri.fsPath);
}
}
if (scmRepo != null) {
return this.getScmGitUri(path, repoPath);
}
}
return this.getRevisionUri(repoPath, path, ref);
}
getRelativePath(pathOrUri: string | Uri, base: string | Uri): string {
// Convert the base to a Uri if it isn't one
if (typeof base === 'string') {
// If it looks like a Uri parse it
if (maybeUri(base)) {
base = Uri.parse(base, true);
} else {
if (!isAbsolute(base)) {
debugger;
void window.showErrorMessage(
`Unable to get relative path between ${
typeof pathOrUri === 'string' ? pathOrUri : pathOrUri.toString(true)
} and ${base}; Base path '${base}' must be an absolute path`,
);
throw new Error(`Base path '${base}' must be an absolute path`);
}
base = Uri.file(base);
}
}
// Convert the path to a Uri if it isn't one
if (typeof pathOrUri === 'string') {
if (maybeUri(pathOrUri)) {
pathOrUri = Uri.parse(pathOrUri, true);
} else {
if (!isAbsolute(pathOrUri)) return normalizePath(pathOrUri);
pathOrUri = Uri.file(pathOrUri);
}
}
const relativePath = relative(base.fsPath, pathOrUri.fsPath);
return normalizePath(relativePath);
}