-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathgitService.ts
2311 lines (1929 loc) · 80 KB
/
gitService.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
'use strict';
import * as fs from 'fs';
import * as paths from 'path';
import {
ConfigurationChangeEvent,
Disposable,
Event,
EventEmitter,
Extension,
extensions,
ProgressLocation,
Range,
TextEditor,
Uri,
window,
WindowState,
workspace,
WorkspaceFolder,
WorkspaceFoldersChangeEvent
} from 'vscode';
// eslint-disable-next-line import/no-unresolved
import { API as BuiltInGitApi, GitExtension } from '../@types/git';
import { configuration, RemotesConfig } from '../configuration';
import { CommandContext, DocumentSchemes, setCommandContext } from '../constants';
import { Container } from '../container';
import { LogCorrelationContext, Logger } from '../logger';
import { Messages } from '../messages';
import { gate, Iterables, log, Objects, Strings, TernarySearchTree, Versions } from '../system';
import { CachedBlame, CachedDiff, CachedLog, GitDocumentState, TrackedDocument } from '../trackers/gitDocumentTracker';
import { vslsUriPrefixRegex } from '../vsls/vsls';
import {
CommitFormatting,
Git,
GitAuthor,
GitBlame,
GitBlameCommit,
GitBlameLine,
GitBlameLines,
GitBlameParser,
GitBranch,
GitBranchParser,
GitCommit,
GitCommitType,
GitContributor,
GitDiff,
GitDiffHunkLine,
GitDiffParser,
GitDiffShortStat,
GitFile,
GitLog,
GitLogCommit,
GitLogParser,
GitRemote,
GitRemoteParser,
GitStash,
GitStashParser,
GitStatus,
GitStatusFile,
GitStatusParser,
GitTag,
GitTagParser,
GitTree,
GitTreeParser,
Repository,
RepositoryChange
} from './git';
import { GitUri } from './gitUri';
import { RemoteProviderFactory, RemoteProviders } from './remotes/factory';
import { GitShortLogParser } from './parsers/parsers';
export * from './gitUri';
export * from './models/models';
export * from './formatters/formatters';
export { getNameFromRemoteResource, RemoteProvider, RemoteResource, RemoteResourceType } from './remotes/provider';
export { RemoteProviderFactory } from './remotes/factory';
const emptyStr = '';
const slash = '/';
const RepoSearchWarnings = {
doesNotExist: /no such file or directory/i
};
const userConfigRegex = /^user\.(name|email) (.*)$/gm;
const mappedAuthorRegex = /(.+)\s<(.+)>/;
export enum GitRepoSearchBy {
Author = 'author',
ChangedLines = 'changed-lines',
Changes = 'changes',
Files = 'files',
Message = 'message',
Sha = 'sha'
}
export class GitService implements Disposable {
static emptyPromise: Promise<GitBlame | GitDiff | GitLog | undefined> = Promise.resolve(undefined);
static deletedOrMissingSha = Git.deletedOrMissingSha;
static stagedUncommittedSha = Git.stagedUncommittedSha;
static uncommittedSha = Git.uncommittedSha;
private _onDidChangeRepositories = new EventEmitter<void>();
get onDidChangeRepositories(): Event<void> {
return this._onDidChangeRepositories.event;
}
private readonly _disposable: Disposable;
private readonly _repositoryTree: TernarySearchTree<Repository>;
private _repositoriesLoadingPromise: Promise<void> | undefined;
private _suspended: boolean = false;
private readonly _branchesCache = new Map<string, GitBranch[]>();
private readonly _tagsCache = new Map<string, GitTag[]>();
private readonly _tagsWithRefsCache = new Map<string, GitTag[]>();
private readonly _trackedCache = new Map<string, boolean | Promise<boolean>>();
private readonly _userMapCache = new Map<string, { name?: string; email?: string } | null>();
constructor() {
this._repositoryTree = TernarySearchTree.forPaths();
this._disposable = Disposable.from(
window.onDidChangeWindowState(this.onWindowStateChanged, this),
workspace.onDidChangeWorkspaceFolders(this.onWorkspaceFoldersChanged, this),
configuration.onDidChange(this.onConfigurationChanged, this)
);
this.onConfigurationChanged(configuration.initializingChangeEvent);
this._repositoriesLoadingPromise = this.onWorkspaceFoldersChanged();
}
dispose() {
this._repositoryTree.forEach(r => r.dispose());
this._branchesCache.clear();
this._tagsCache.clear();
this._tagsWithRefsCache.clear();
this._trackedCache.clear();
this._userMapCache.clear();
this._disposable && this._disposable.dispose();
}
get useCaching() {
return Container.config.advanced.caching.enabled;
}
private onAnyRepositoryChanged(repo: Repository, reason: RepositoryChange) {
this._trackedCache.clear();
this._branchesCache.delete(repo.path);
this._tagsCache.delete(repo.path);
this._tagsWithRefsCache.clear();
if (reason === RepositoryChange.Config) {
this._userMapCache.delete(repo.path);
}
if (reason === RepositoryChange.Closed) {
// Send a notification that the repositories changed
setImmediate(async () => {
await this.updateContext(this._repositoryTree);
this.fireRepositoriesChanged();
});
}
}
private onConfigurationChanged(e: ConfigurationChangeEvent) {
if (
configuration.changed(e, configuration.name('defaultDateStyle').value) ||
configuration.changed(e, configuration.name('defaultDateFormat').value)
) {
CommitFormatting.reset();
}
}
private onWindowStateChanged(e: WindowState) {
if (e.focused) {
this._repositoryTree.forEach(r => r.resume());
}
else {
this._repositoryTree.forEach(r => r.suspend());
}
this._suspended = !e.focused;
}
private async onWorkspaceFoldersChanged(e?: WorkspaceFoldersChangeEvent) {
let initializing = false;
if (e === undefined) {
initializing = true;
e = {
added: workspace.workspaceFolders || [],
removed: []
};
Logger.log(`Starting repository search in ${e.added.length} folders`);
}
for (const f of e.added) {
const { scheme } = f.uri;
if (scheme !== DocumentSchemes.File && scheme !== DocumentSchemes.Vsls) continue;
if (scheme === DocumentSchemes.Vsls) {
if (Container.vsls.isMaybeGuest) {
const guest = await Container.vsls.guest();
if (guest !== undefined) {
const repositories = await guest.getRepositoriesInFolder(
f,
this.onAnyRepositoryChanged.bind(this)
);
for (const r of repositories) {
this._repositoryTree.set(r.path, r);
}
}
}
}
else {
// Search for and add all repositories (nested and/or submodules)
const repositories = await this.repositorySearch(f);
for (const r of repositories) {
this._repositoryTree.set(r.path, r);
}
}
}
for (const f of e.removed) {
const { fsPath, scheme } = f.uri;
if (scheme !== DocumentSchemes.File && scheme !== DocumentSchemes.Vsls) continue;
const repos = this._repositoryTree.findSuperstr(fsPath);
const reposToDelete =
repos !== undefined
? // Since the filtered tree will have keys that are relative to the fsPath, normalize to the full path
[...Iterables.map<Repository, [Repository, string]>(repos, r => [r, r.path])]
: [];
// const filteredTree = this._repositoryTree.findSuperstr(fsPath);
// const reposToDelete =
// filteredTree !== undefined
// ? // Since the filtered tree will have keys that are relative to the fsPath, normalize to the full path
// [
// ...Iterables.map<[Repository, string], [Repository, string]>(
// filteredTree.entries(),
// ([r, k]) => [r, path.join(fsPath, k)]
// )
// ]
// : [];
const repo = this._repositoryTree.get(fsPath);
if (repo !== undefined) {
reposToDelete.push([repo, fsPath]);
}
for (const [r, k] of reposToDelete) {
this._repositoryTree.delete(k);
r.dispose();
}
}
await this.updateContext(this._repositoryTree);
if (!initializing) {
// Defer the event trigger enough to let everything unwind
setImmediate(() => this.fireRepositoriesChanged());
}
}
@log<GitService['repositorySearch']>({
args: false,
singleLine: true,
prefix: (context, folder) => `${context.prefix}(${folder.uri.fsPath})`,
exit: result =>
`returned ${result.length} repositories${
result.length !== 0 ? ` (${result.map(r => r.path).join(', ')})` : emptyStr
}`
})
private async repositorySearch(folder: WorkspaceFolder): Promise<Repository[]> {
const cc = Logger.getCorrelationContext();
const { uri } = folder;
const depth = configuration.get<number>(configuration.name('advanced')('repositorySearchDepth').value, uri);
Logger.log(cc, `searching (depth=${depth})...`);
const repositories: Repository[] = [];
const anyRepoChangedFn = this.onAnyRepositoryChanged.bind(this);
const rootPath = await this.getRepoPathCore(uri.fsPath, true);
if (rootPath !== undefined) {
Logger.log(cc, `found root repository in '${rootPath}'`);
repositories.push(new Repository(folder, rootPath, true, anyRepoChangedFn, this._suspended));
}
if (depth <= 0) return repositories;
// Get any specified excludes -- this is a total hack, but works for some simple cases and something is better than nothing :)
let excludes = {
...workspace.getConfiguration('files', uri).get<{ [key: string]: boolean }>('exclude', {}),
...workspace.getConfiguration('search', uri).get<{ [key: string]: boolean }>('exclude', {})
};
const excludedPaths = [
...Iterables.filterMap(Objects.entries(excludes), ([key, value]) => {
if (!value) return undefined;
if (key.startsWith('**/')) return key.substring(3);
return key;
})
];
excludes = excludedPaths.reduce((accumulator, current) => {
accumulator[current] = true;
return accumulator;
}, Object.create(null));
let repoPaths;
try {
repoPaths = await this.repositorySearchCore(uri.fsPath, depth, excludes);
}
catch (ex) {
if (RepoSearchWarnings.doesNotExist.test(ex.message || emptyStr)) {
Logger.log(cc, `FAILED${ex.message ? ` Error: ${ex.message}` : emptyStr}`);
}
else {
Logger.error(ex, cc, 'FAILED');
}
return repositories;
}
for (let p of repoPaths) {
p = paths.dirname(p);
// If we are the same as the root, skip it
if (Strings.normalizePath(p) === rootPath) continue;
Logger.log(cc, `searching in '${p}'...`);
const rp = await this.getRepoPathCore(p, true);
if (rp === undefined) continue;
Logger.log(cc, `found repository in '${rp}'`);
repositories.push(new Repository(folder, rp, false, anyRepoChangedFn, this._suspended));
}
return repositories;
}
private repositorySearchCore(
root: string,
depth: number,
excludes: { [key: string]: boolean },
repositories: string[] = []
): Promise<string[]> {
return new Promise<string[]>((resolve, reject) => {
fs.readdir(root, async (err, files) => {
if (err != null) {
reject(err);
return;
}
if (files.length === 0) {
resolve(repositories);
return;
}
const folders: string[] = [];
const promises = files.map(file => {
const path = paths.resolve(root, file);
return new Promise<void>((resolve2, reject2) => {
fs.stat(path, (err, stat) => {
if (file === '.git') {
repositories.push(path);
}
else if (err == null && excludes[file] !== true && stat != null && stat.isDirectory()) {
folders.push(path);
}
resolve2();
});
});
});
await Promise.all(promises);
if (depth-- > 0) {
for (const folder of folders) {
await this.repositorySearchCore(folder, depth, excludes, repositories);
}
}
resolve(repositories);
});
});
}
private async updateContext(repositoryTree: TernarySearchTree<Repository>) {
const hasRepository = repositoryTree.any();
await setCommandContext(CommandContext.Enabled, hasRepository);
let hasRemotes = false;
if (hasRepository) {
for (const repo of repositoryTree.values()) {
hasRemotes = await repo.hasRemotes();
if (hasRemotes) break;
}
}
await setCommandContext(CommandContext.HasRemotes, hasRemotes);
// If we have no repositories setup a watcher in case one is initialized
if (!hasRepository) {
const watcher = workspace.createFileSystemWatcher('**/.git', false, true, true);
const disposable = Disposable.from(
watcher,
watcher.onDidCreate(async uri => {
const f = workspace.getWorkspaceFolder(uri);
if (f === undefined) return;
// Search for and add all repositories (nested and/or submodules)
const repositories = await this.repositorySearch(f);
if (repositories.length === 0) return;
disposable.dispose();
for (const r of repositories) {
this._repositoryTree.set(r.path, r);
}
await this.updateContext(this._repositoryTree);
// Defer the event trigger enough to let everything unwind
setImmediate(() => this.fireRepositoriesChanged());
}, this)
);
}
}
private fireRepositoriesChanged() {
this._onDidChangeRepositories.fire();
}
@log()
async applyChangesToWorkingFile(uri: GitUri, ref1?: string, ref2?: string) {
const cc = Logger.getCorrelationContext();
ref1 = ref1 || uri.sha;
if (ref1 === undefined || uri.repoPath === undefined) return;
if (ref2 === undefined) {
ref2 = ref1;
ref1 = `${ref1}^`;
}
let patch;
try {
patch = await Git.diff(uri.repoPath, uri.fsPath, ref1, ref2);
void (await Git.apply(uri.repoPath!, patch));
}
catch (ex) {
if (patch && /patch does not apply/i.test(ex.message)) {
const result = await window.showWarningMessage(
'Unable to apply changes cleanly. Retry and allow conflicts?',
{ title: 'Yes' },
{ title: 'No', isCloseAffordance: true }
);
if (result === undefined || result.title !== 'Yes') return;
if (result.title === 'Yes') {
try {
void (await Git.apply(uri.repoPath!, patch, { allowConflicts: true }));
return;
}
catch (e) {
// eslint-disable-next-line no-ex-assign
ex = e;
}
}
}
Logger.error(ex, cc);
void Messages.showGenericErrorMessage('Unable to apply changes');
}
}
@log()
checkout(repoPath: string, ref: string, fileName?: string) {
return Git.checkout(repoPath, ref, fileName);
}
@gate()
@log()
fetch(repoPath: string, remote?: string) {
return Git.fetch(repoPath, { remote: remote });
}
@gate()
@log()
async fetchAll() {
const repositories = await this.getOrderedRepositories();
if (repositories.length === 0) return;
await window.withProgress(
{
location: ProgressLocation.Notification,
title: 'Fetching repositories',
cancellable: true
},
async (progress, token) => {
const total = repositories.length;
for (const repo of repositories) {
progress.report({
message: `${repo.formattedName}...`,
increment: 100 / total
});
if (token.isCancellationRequested) break;
await repo.fetch({ progress: false });
}
}
);
}
@gate()
@log()
async pullAll() {
const repositories = await this.getOrderedRepositories();
if (repositories.length === 0) return;
await window.withProgress(
{
location: ProgressLocation.Notification,
title: 'Pulling repositories',
cancellable: true
},
async (progress, token) => {
const total = repositories.length;
for (const repo of repositories) {
progress.report({
message: `${repo.formattedName}...`,
increment: 100 / total
});
if (token.isCancellationRequested) break;
await repo.pull({ progress: false });
}
}
);
}
@gate()
@log()
async pushAll() {
const repositories = await this.getOrderedRepositories();
if (repositories.length === 0) return;
await window.withProgress(
{
location: ProgressLocation.Notification,
title: 'Pushing repositories',
cancellable: true
},
async (progress, token) => {
const total = repositories.length;
for (const repo of repositories) {
progress.report({
message: `${repo.formattedName}...`,
increment: 100 / total
});
if (token.isCancellationRequested) break;
await repo.push({ progress: false });
}
}
);
}
async fileExists(
repoPath: string,
fileName: string,
options: { ensureCase: boolean } = { ensureCase: false }
): Promise<boolean> {
if (Container.vsls.isMaybeGuest) {
const guest = await Container.vsls.guest();
if (guest !== undefined) {
return guest.fileExists(repoPath, fileName, options);
}
}
const path = paths.resolve(repoPath, fileName);
const exists = await new Promise<boolean>((resolve, reject) => fs.exists(path, resolve));
if (!options.ensureCase || !exists) return exists;
// Deal with renames in case only on case-insensative file systems
const normalizedRepoPath = paths.normalize(repoPath);
return this.fileExistsWithCase(path, normalizedRepoPath, normalizedRepoPath.length);
}
private async fileExistsWithCase(path: string, repoPath: string, repoPathLength: number): Promise<boolean> {
const dir = paths.dirname(path);
if (dir.length < repoPathLength) return false;
if (dir === repoPath) return true;
const filenames = await new Promise<string[]>((resolve, reject) =>
fs.readdir(dir, (err: NodeJS.ErrnoException, files: string[]) => {
if (err) {
reject(err);
}
else {
resolve(files);
}
})
);
if (filenames.indexOf(paths.basename(path)) === -1) {
return false;
}
return this.fileExistsWithCase(dir, repoPath, repoPathLength);
}
@log()
async findNextCommit(repoPath: string, fileName: string, ref?: string): Promise<GitLogCommit | undefined> {
let log = await this.getLogForFile(repoPath, fileName, { maxCount: 1, ref: ref, renames: true, reverse: true });
let commit = log && Iterables.first(log.commits.values());
if (commit) return commit;
const nextFileName = await this.findNextFileName(repoPath, fileName, ref);
if (nextFileName) {
log = await this.getLogForFile(repoPath, nextFileName, {
maxCount: 1,
ref: ref,
renames: true,
reverse: true
});
commit = log && Iterables.first(log.commits.values());
}
return commit;
}
@log()
async findNextFileName(repoPath: string | undefined, fileName: string, ref?: string): Promise<string | undefined> {
[fileName, repoPath] = Git.splitPath(fileName, repoPath);
return (await this.fileExists(repoPath, fileName, { ensureCase: true }))
? fileName
: this.findNextFileNameCore(repoPath, fileName, ref);
}
private async findNextFileNameCore(repoPath: string, fileName: string, ref?: string): Promise<string | undefined> {
if (ref === undefined) {
// Get the most recent commit for this file name
ref = await this.getRecentShaForFile(repoPath, fileName);
if (ref === undefined) return undefined;
}
// Get the full commit (so we can see if there are any matching renames in the files)
const log = await this.getLog(repoPath, { maxCount: 1, ref: ref });
if (log === undefined) return undefined;
const c = Iterables.first(log.commits.values());
const file = c.files.find(f => f.originalFileName === fileName);
if (file === undefined) return undefined;
return file.fileName;
}
async findWorkingFileName(commit: GitCommit): Promise<[string | undefined, string | undefined]>;
async findWorkingFileName(
fileName: string,
repoPath?: string,
ref?: string
): Promise<[string | undefined, string | undefined]>;
@log()
async findWorkingFileName(
commitOrFileName: GitCommit | string,
repoPath?: string,
ref?: string
): Promise<[string | undefined, string | undefined]> {
let fileName;
if (typeof commitOrFileName === 'string') {
fileName = commitOrFileName;
if (repoPath === undefined) {
repoPath = await this.getRepoPath(fileName, { ref: ref });
[fileName, repoPath] = Git.splitPath(fileName, repoPath);
}
else {
fileName = Strings.normalizePath(paths.relative(repoPath, fileName));
}
}
else {
const c = commitOrFileName;
repoPath = c.repoPath;
if (c.workingFileName && (await this.fileExists(repoPath, c.workingFileName, { ensureCase: true }))) {
return [c.workingFileName, repoPath];
}
fileName = c.fileName;
}
// Keep walking up to the most recent commit for a given filename, until it exists on disk
while (true) {
if (await this.fileExists(repoPath, fileName, { ensureCase: true })) return [fileName, repoPath];
fileName = await this.findNextFileNameCore(repoPath, fileName);
if (fileName === undefined) return [undefined, undefined];
}
}
@log({
args: {
0: (editor: TextEditor) =>
editor !== undefined ? `TextEditor(${Logger.toLoggable(editor.document.uri)})` : 'undefined'
}
})
async getActiveRepoPath(editor?: TextEditor): Promise<string | undefined> {
editor = editor || window.activeTextEditor;
let repoPath;
if (editor != null) {
const doc = await Container.tracker.getOrAdd(editor.document.uri);
if (doc !== undefined) {
repoPath = doc.uri.repoPath;
}
}
if (repoPath != null) return repoPath;
return this.getHighlanderRepoPath();
}
@log()
getHighlanderRepoPath(): string | undefined {
const entry = this._repositoryTree.highlander();
if (entry === undefined) return undefined;
const [repo] = entry;
return repo.path;
}
@log()
async getBlameForFile(uri: GitUri): Promise<GitBlame | undefined> {
const cc = Logger.getCorrelationContext();
let key = 'blame';
if (uri.sha !== undefined) {
key += `:${uri.sha}`;
}
const doc = await Container.tracker.getOrAdd(uri);
if (this.useCaching) {
if (doc.state !== undefined) {
const cachedBlame = doc.state.get<CachedBlame>(key);
if (cachedBlame !== undefined) {
Logger.debug(cc, `Cache hit: '${key}'`);
return cachedBlame.item;
}
}
Logger.debug(cc, `Cache miss: '${key}'`);
if (doc.state === undefined) {
doc.state = new GitDocumentState(doc.key);
}
}
const promise = this.getBlameForFileCore(uri, doc, key, cc);
if (doc.state !== undefined) {
Logger.debug(cc, `Cache add: '${key}'`);
const value: CachedBlame = {
item: promise as Promise<GitBlame>
};
doc.state.set<CachedBlame>(key, value);
}
return promise;
}
private async getBlameForFileCore(
uri: GitUri,
document: TrackedDocument<GitDocumentState>,
key: string,
cc: LogCorrelationContext | undefined
): Promise<GitBlame | undefined> {
if (!(await this.isTracked(uri))) {
Logger.log(cc, `Skipping blame; '${uri.fsPath}' is not tracked`);
return GitService.emptyPromise as Promise<GitBlame>;
}
const [file, root] = Git.splitPath(uri.fsPath, uri.repoPath, false);
try {
const data = await Git.blame(root, file, uri.sha, {
args: Container.config.advanced.blame.customArguments,
ignoreWhitespace: Container.config.blame.ignoreWhitespace
});
const blame = GitBlameParser.parse(data, root, file, await this.getCurrentUser(root));
return blame;
}
catch (ex) {
// Trap and cache expected blame errors
if (document.state !== undefined) {
const msg = ex && ex.toString();
Logger.debug(cc, `Cache replace (with empty promise): '${key}'`);
const value: CachedBlame = {
item: GitService.emptyPromise as Promise<GitBlame>,
errorMessage: msg
};
document.state.set<CachedBlame>(key, value);
document.setBlameFailure();
return GitService.emptyPromise as Promise<GitBlame>;
}
return undefined;
}
}
@log({
args: {
1: contents => '<contents>'
}
})
async getBlameForFileContents(uri: GitUri, contents: string): Promise<GitBlame | undefined> {
const cc = Logger.getCorrelationContext();
const key = `blame:${Strings.sha1(contents)}`;
const doc = await Container.tracker.getOrAdd(uri);
if (this.useCaching) {
if (doc.state !== undefined) {
const cachedBlame = doc.state.get<CachedBlame>(key);
if (cachedBlame !== undefined) {
Logger.debug(cc, `Cache hit: ${key}`);
return cachedBlame.item;
}
}
Logger.debug(cc, `Cache miss: ${key}`);
if (doc.state === undefined) {
doc.state = new GitDocumentState(doc.key);
}
}
const promise = this.getBlameForFileContentsCore(uri, contents, doc, key, cc);
if (doc.state !== undefined) {
Logger.debug(cc, `Cache add: '${key}'`);
const value: CachedBlame = {
item: promise as Promise<GitBlame>
};
doc.state.set<CachedBlame>(key, value);
}
return promise;
}
async getBlameForFileContentsCore(
uri: GitUri,
contents: string,
document: TrackedDocument<GitDocumentState>,
key: string,
cc: LogCorrelationContext | undefined
): Promise<GitBlame | undefined> {
if (!(await this.isTracked(uri))) {
Logger.log(cc, `Skipping blame; '${uri.fsPath}' is not tracked`);
return GitService.emptyPromise as Promise<GitBlame>;
}
const [file, root] = Git.splitPath(uri.fsPath, uri.repoPath, false);
try {
const data = await Git.blame_contents(root, file, contents, {
args: Container.config.advanced.blame.customArguments,
correlationKey: `:${key}`,
ignoreWhitespace: Container.config.blame.ignoreWhitespace
});
const blame = GitBlameParser.parse(data, root, file, await this.getCurrentUser(root));
return blame;
}
catch (ex) {
// Trap and cache expected blame errors
if (document.state !== undefined) {
const msg = ex && ex.toString();
Logger.debug(cc, `Cache replace (with empty promise): '${key}'`);
const value: CachedBlame = {
item: GitService.emptyPromise as Promise<GitBlame>,
errorMessage: msg
};
document.state.set<CachedBlame>(key, value);
document.setBlameFailure();
return GitService.emptyPromise as Promise<GitBlame>;
}
return undefined;
}
}
@log()
async getBlameForLine(
uri: GitUri,
editorLine: number, // editor lines are 0-based
options: { skipCache?: boolean } = {}
): Promise<GitBlameLine | undefined> {
if (!options.skipCache && this.useCaching) {
const blame = await this.getBlameForFile(uri);
if (blame === undefined) return undefined;
let blameLine = blame.lines[editorLine];
if (blameLine === undefined) {
if (blame.lines.length !== editorLine) return undefined;
blameLine = blame.lines[editorLine - 1];
}
const commit = blame.commits.get(blameLine.sha);
if (commit === undefined) return undefined;
const author = blame.authors.get(commit.author)!;
return {
author: { ...author, lineCount: commit.lines.length },
commit: commit,
line: blameLine
};
}
const lineToBlame = editorLine + 1;
const fileName = uri.fsPath;
try {
const data = await Git.blame(uri.repoPath, fileName, uri.sha, {
args: Container.config.advanced.blame.customArguments,
ignoreWhitespace: Container.config.blame.ignoreWhitespace,
startLine: lineToBlame,
endLine: lineToBlame
});
const blame = GitBlameParser.parse(data, uri.repoPath, fileName, await this.getCurrentUser(uri.repoPath!));
if (blame === undefined) return undefined;
return {
author: Iterables.first(blame.authors.values()),
commit: Iterables.first(blame.commits.values()),
line: blame.lines[editorLine]
};
}
catch {
return undefined;
}
}
@log({
args: {
2: contents => '<contents>'
}
})
async getBlameForLineContents(
uri: GitUri,
editorLine: number, // editor lines are 0-based
contents: string,
options: { skipCache?: boolean } = {}
): Promise<GitBlameLine | undefined> {
if (!options.skipCache && this.useCaching) {
const blame = await this.getBlameForFileContents(uri, contents);
if (blame === undefined) return undefined;
let blameLine = blame.lines[editorLine];
if (blameLine === undefined) {
if (blame.lines.length !== editorLine) return undefined;
blameLine = blame.lines[editorLine - 1];
}
const commit = blame.commits.get(blameLine.sha);
if (commit === undefined) return undefined;
const author = blame.authors.get(commit.author)!;
return {
author: { ...author, lineCount: commit.lines.length },
commit: commit,
line: blameLine
};
}
const lineToBlame = editorLine + 1;
const fileName = uri.fsPath;
try {
const data = await Git.blame_contents(uri.repoPath, fileName, contents, {
args: Container.config.advanced.blame.customArguments,
ignoreWhitespace: Container.config.blame.ignoreWhitespace,
startLine: lineToBlame,
endLine: lineToBlame
});