/
githubGitProvider.ts
3184 lines (2712 loc) · 90.2 KB
/
githubGitProvider.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
/* eslint-disable @typescript-eslint/require-await */
import type {
AuthenticationSession,
AuthenticationSessionsChangeEvent,
CancellationToken,
Disposable,
Event,
Range,
TextDocument,
WorkspaceFolder,
} from 'vscode';
import { authentication, EventEmitter, FileType, Uri, window, workspace } from 'vscode';
import { encodeUtf8Hex } from '@env/hex';
import { configuration } from '../../configuration';
import { CharCode, ContextKeys, Schemes } from '../../constants';
import type { Container } from '../../container';
import { setContext } from '../../context';
import { emojify } from '../../emojis';
import {
AuthenticationError,
AuthenticationErrorReason,
ExtensionNotFoundError,
OpenVirtualRepositoryError,
OpenVirtualRepositoryErrorReason,
} from '../../errors';
import { Features } from '../../features';
import { GitSearchError } from '../../git/errors';
import type {
GitProvider,
NextComparisonUrisResult,
PagedResult,
PreviousComparisonUrisResult,
PreviousLineComparisonUrisResult,
RepositoryCloseEvent,
RepositoryOpenEvent,
ScmRepository,
} from '../../git/gitProvider';
import { GitProviderId, RepositoryVisibility } from '../../git/gitProvider';
import { GitUri } from '../../git/gitUri';
import type { GitBlame, GitBlameAuthor, GitBlameLine, GitBlameLines } from '../../git/models/blame';
import type { BranchSortOptions } from '../../git/models/branch';
import { getBranchId, GitBranch, sortBranches } from '../../git/models/branch';
import type { GitCommitLine } from '../../git/models/commit';
import { GitCommit, GitCommitIdentity } from '../../git/models/commit';
import { GitContributor } from '../../git/models/contributor';
import type { GitDiff, GitDiffFilter, GitDiffHunkLine, GitDiffShortStat } from '../../git/models/diff';
import type { GitFile } from '../../git/models/file';
import { GitFileChange, GitFileIndexStatus } from '../../git/models/file';
import type {
GitGraph,
GitGraphRow,
GitGraphRowContexts,
GitGraphRowHead,
GitGraphRowRemoteHead,
GitGraphRowTag,
} from '../../git/models/graph';
import { GitGraphRowType } 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 } from '../../git/models/reference';
import { GitReference, GitRevision } from '../../git/models/reference';
import type { GitReflog } from '../../git/models/reflog';
import { getRemoteIconUri, GitRemote, GitRemoteType } from '../../git/models/remote';
import type { RepositoryChangeEvent } from '../../git/models/repository';
import { Repository } from '../../git/models/repository';
import type { GitStash } from '../../git/models/stash';
import type { GitStatus, GitStatusFile } from '../../git/models/status';
import type { TagSortOptions } from '../../git/models/tag';
import { GitTag, 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 { RemoteProvider } from '../../git/remotes/remoteProvider';
import type { RemoteProviders } from '../../git/remotes/remoteProviders';
import { getRemoteProviderMatcher, loadRemoteProviders } from '../../git/remotes/remoteProviders';
import type { RichRemoteProvider } from '../../git/remotes/richRemoteProvider';
import type { GitSearch, GitSearchResultData, GitSearchResults, SearchQuery } from '../../git/search';
import { getSearchQueryComparisonKey, parseSearchQuery } from '../../git/search';
import type { LogScope } from '../../logger';
import { Logger } from '../../logger';
import { gate } from '../../system/decorators/gate';
import { debug, getLogScope, log } from '../../system/decorators/log';
import { filterMap, first, last, some } from '../../system/iterable';
import { isAbsolute, isFolderGlob, maybeUri, normalizePath, relative } from '../../system/path';
import { getSettledValue } from '../../system/promise';
import { serializeWebviewItemContext } from '../../system/webview';
import type { CachedBlame, CachedLog } from '../../trackers/gitDocumentTracker';
import { GitDocumentState } from '../../trackers/gitDocumentTracker';
import type { TrackedDocument } from '../../trackers/trackedDocument';
import type { GitHubAuthorityMetadata, Metadata, RemoteHubApi } from '../remotehub';
import { getRemoteHubApi } from '../remotehub';
import type { GraphItemContext, GraphItemRefContext } from '../webviews/graph/graphWebview';
import type { GitHubApi } from './github';
import { fromCommitFileStatus } from './models';
const doubleQuoteRegex = /"/g;
const emptyPagedResult: PagedResult<any> = Object.freeze({ values: [] });
const emptyPromise: Promise<GitBlame | GitDiff | GitLog | undefined> = Promise.resolve(undefined);
const githubAuthenticationScopes = ['repo', 'read:user', 'user:email'];
// Since negative lookbehind isn't supported in all browsers, this leaves out the negative lookbehind condition `(?<!\.lock)` to ensure the branch name doesn't end with `.lock`
const validBranchOrTagRegex = /^[^/](?!.*\/\.)(?!.*\.\.)(?!.*\/\/)(?!.*@\{)[^\000-\037\177 ~^:?*[\\]+[^./]$/;
interface RepositoryInfo {
user?: GitUser | null;
}
export class GitHubGitProvider implements GitProvider, Disposable {
descriptor = { id: GitProviderId.GitHub, name: 'GitHub', virtual: true };
readonly supportedSchemes: Set<string> = new Set([Schemes.Virtual, Schemes.GitHub, Schemes.PRs]);
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 _branchesCache = new Map<string, Promise<PagedResult<GitBranch>>>();
private readonly _repoInfoCache = new Map<string, RepositoryInfo>();
private readonly _tagsCache = new Map<string, Promise<PagedResult<GitTag>>>();
private readonly _disposables: Disposable[] = [];
constructor(private readonly container: Container) {
this._disposables.push(authentication.onDidChangeSessions(this.onAuthenticationSessionsChanged, this));
}
dispose() {
this._disposables.forEach(d => void d.dispose());
}
private onAuthenticationSessionsChanged(e: AuthenticationSessionsChangeEvent) {
if (e.provider.id === 'github') {
this._sessionPromise = undefined;
void this.ensureSession(false, true);
}
}
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._branchesCache.delete(repo.path);
// }
this._branchesCache.delete(repo.path);
this._tagsCache.delete(repo.path);
this._repoInfoCache.delete(repo.path);
this._onDidChangeRepository.fire(e);
}
async discoverRepositories(uri: Uri): Promise<Repository[]> {
if (!this.supportedSchemes.has(uri.scheme)) return [];
try {
const { remotehub } = await this.ensureRepositoryContext(uri.toString(), true);
const workspaceUri = remotehub.getVirtualWorkspaceUri(uri);
if (workspaceUri == null) return [];
return this.openRepository(undefined, workspaceUri, true);
} catch {
return [];
}
}
updateContext(): void {
void setContext(ContextKeys.HasVirtualFolders, this.container.git.hasOpenRepositories(this.descriptor.id));
}
openRepository(
folder: WorkspaceFolder | undefined,
uri: Uri,
root: boolean,
suspended?: boolean,
closed?: boolean,
): Repository[] {
return [
new Repository(
this.container,
this.onRepositoryChanged.bind(this),
this.descriptor,
folder,
uri,
root,
suspended ?? !window.state.focused,
closed,
),
];
}
// private _supportedFeatures = new Map<Features, boolean>();
async supports(feature: Features): Promise<boolean> {
// const supported = this._supportedFeatures.get(feature);
// if (supported != null) return supported;
switch (feature) {
case Features.Stashes:
case Features.Worktrees:
return false;
default:
return true;
}
}
async visibility(repoPath: string): Promise<RepositoryVisibility> {
const remotes = await this.getRemotes(repoPath);
if (remotes.length === 0) return RepositoryVisibility.Local;
const origin = remotes.find(r => r.name === 'origin');
if (origin != null) {
return this.getRemoteVisibility(origin);
}
return RepositoryVisibility.Private;
}
private async getRemoteVisibility(
remote: GitRemote<RemoteProvider | RichRemoteProvider | undefined>,
): Promise<RepositoryVisibility> {
switch (remote.provider?.id) {
case 'github': {
const { github, metadata, session } = await this.ensureRepositoryContext(remote.repoPath);
const visibility = await github.getRepositoryVisibility(
session.accessToken,
metadata.repo.owner,
metadata.repo.name,
);
return visibility ?? RepositoryVisibility.Private;
}
default:
return RepositoryVisibility.Private;
}
}
async getOpenScmRepositories(): Promise<ScmRepository[]> {
return [];
}
async getScmRepository(_repoPath: string): Promise<ScmRepository | undefined> {
return undefined;
}
async getOrOpenScmRepository(_repoPath: string): Promise<ScmRepository | undefined> {
return undefined;
}
canHandlePathOrUri(scheme: string, pathOrUri: string | Uri): string | undefined {
if (!this.supportedSchemes.has(scheme)) return undefined;
return typeof pathOrUri === 'string' ? pathOrUri : pathOrUri.toString();
}
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, otherwise throw
if (maybeUri(base)) {
base = Uri.parse(base, true);
} else {
debugger;
void window.showErrorMessage(
`Unable to get absolute uri between ${
typeof pathOrUri === 'string' ? pathOrUri : pathOrUri.toString(true)
} and ${base}; Base path '${base}' must be a uri`,
);
throw new Error(`Base path '${base}' must be a uri`);
}
}
if (typeof pathOrUri === 'string' && !maybeUri(pathOrUri) && !isAbsolute(pathOrUri)) {
return Uri.joinPath(base, normalizePath(pathOrUri));
}
const relativePath = this.getRelativePath(pathOrUri, base);
return Uri.joinPath(base, relativePath);
}
@log()
async getBestRevisionUri(repoPath: string, path: string, ref: string | undefined): Promise<Uri | undefined> {
return ref ? this.createProviderUri(repoPath, ref, path) : this.createVirtualUri(repoPath, ref, path);
}
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, otherwise throw
if (maybeUri(base)) {
base = Uri.parse(base, true);
} else {
debugger;
void window.showErrorMessage(
`Unable to get relative path between ${
typeof pathOrUri === 'string' ? pathOrUri : pathOrUri.toString(true)
} and ${base}; Base path '${base}' must be a uri`,
);
throw new Error(`Base path '${base}' must be a uri`);
}
}
let relativePath;
// Convert the path to a Uri if it isn't one
if (typeof pathOrUri === 'string') {
if (maybeUri(pathOrUri)) {
pathOrUri = Uri.parse(pathOrUri, true);
} else {
pathOrUri = normalizePath(pathOrUri);
relativePath =
isAbsolute(pathOrUri) && pathOrUri.startsWith(base.path)
? pathOrUri.slice(base.path.length)
: pathOrUri;
if (relativePath.charCodeAt(0) === CharCode.Slash) {
relativePath = relativePath.slice(1);
}
return relativePath;
}
}
relativePath = normalizePath(relative(base.path.slice(1), pathOrUri.path.slice(1)));
return relativePath;
}
getRevisionUri(repoPath: string, path: string, ref: string): Uri {
const uri = this.createProviderUri(repoPath, ref, path);
return ref === GitRevision.deletedOrMissing ? uri.with({ query: '~' }) : uri;
}
@log()
async getWorkingUri(repoPath: string, uri: Uri) {
return this.createVirtualUri(repoPath, undefined, uri.path);
}
@log()
async addRemote(_repoPath: string, _name: string, _url: string): Promise<void> {}
@log()
async pruneRemote(_repoPath: string, _remoteName: string): Promise<void> {}
@log()
async applyChangesToWorkingFile(_uri: GitUri, _ref1?: string, _ref2?: string): Promise<void> {}
@log()
async branchContainsCommit(_repoPath: string, _name: string, _ref: string): Promise<boolean> {
return false;
}
@log()
async checkout(
_repoPath: string,
_ref: string,
_options?: { createBranch?: string } | { path?: string },
): Promise<void> {}
@log()
resetCaches(
...affects: ('branches' | 'contributors' | 'providers' | 'remotes' | 'stashes' | 'status' | 'tags')[]
): void {
if (affects.length === 0 || affects.includes('branches')) {
this._branchesCache.clear();
}
if (affects.length === 0 || affects.includes('tags')) {
this._tagsCache.clear();
}
if (affects.length === 0) {
this._repoInfoCache.clear();
}
}
@log<GitHubGitProvider['excludeIgnoredUris']>({ args: { 1: uris => uris.length } })
async excludeIgnoredUris(_repoPath: string, uris: Uri[]): Promise<Uri[]> {
return uris;
}
// @gate()
@log()
async fetch(
_repoPath: string,
_options?: { all?: boolean; branch?: GitBranchReference; prune?: boolean; pull?: boolean; remote?: string },
): Promise<void> {}
@gate()
@debug()
async findRepositoryUri(uri: Uri, _isDirectory?: boolean): Promise<Uri | undefined> {
const scope = getLogScope();
try {
const remotehub = await this.ensureRemoteHubApi();
const rootUri = remotehub.getProviderRootUri(uri).with({ scheme: Schemes.Virtual });
return rootUri;
} catch (ex) {
if (!(ex instanceof ExtensionNotFoundError)) {
debugger;
}
Logger.error(ex, scope);
return undefined;
}
}
@log<GitHubGitProvider['getAheadBehindCommitCount']>({ args: { 1: refs => refs.join(',') } })
async getAheadBehindCommitCount(
_repoPath: string,
_refs: string[],
): Promise<{ ahead: number; behind: number } | undefined> {
return undefined;
}
@gate<GitHubGitProvider['getBlame']>((u, d) => `${u.toString()}|${d?.isDirty}`)
@log<GitHubGitProvider['getBlame']>({ args: { 1: d => d?.isDirty } })
async getBlame(uri: GitUri, document?: TextDocument | undefined): Promise<GitBlame | undefined> {
const scope = getLogScope();
// TODO@eamodio we need to figure out when to do this, since dirty isn't enough, we need to know if there are any uncommitted changes
if (document?.isDirty) return undefined; //this.getBlameContents(uri, document.getText());
let key = 'blame';
if (uri.sha != null) {
key += `:${uri.sha}`;
}
const doc = await this.container.tracker.getOrAdd(uri);
if (doc.state != null) {
const cachedBlame = doc.state.getBlame(key);
if (cachedBlame != null) {
Logger.debug(scope, `Cache hit: '${key}'`);
return cachedBlame.item;
}
}
Logger.debug(scope, `Cache miss: '${key}'`);
if (doc.state == null) {
doc.state = new GitDocumentState();
}
const promise = this.getBlameCore(uri, doc, key, scope);
if (doc.state != null) {
Logger.debug(scope, `Cache add: '${key}'`);
const value: CachedBlame = {
item: promise as Promise<GitBlame>,
};
doc.state.setBlame(key, value);
}
return promise;
}
private async getBlameCore(
uri: GitUri,
document: TrackedDocument<GitDocumentState>,
key: string,
scope: LogScope | undefined,
): Promise<GitBlame | undefined> {
try {
const context = await this.ensureRepositoryContext(uri.repoPath!);
if (context == null) return undefined;
const { metadata, github, remotehub, session } = context;
const root = remotehub.getVirtualUri(remotehub.getProviderRootUri(uri));
const relativePath = this.getRelativePath(uri, root);
if (uri.scheme === Schemes.Virtual) {
const [working, committed] = await Promise.allSettled([
workspace.fs.stat(uri),
workspace.fs.stat(uri.with({ scheme: Schemes.GitHub })),
]);
if (
working.status !== 'fulfilled' ||
committed.status !== 'fulfilled' ||
working.value.mtime !== committed.value.mtime
) {
return undefined;
}
}
const ref = !uri.sha || uri.sha === 'HEAD' ? (await metadata.getRevision()).revision : uri.sha;
const blame = await github.getBlame(
session.accessToken,
metadata.repo.owner,
metadata.repo.name,
ref,
relativePath,
);
const authors = new Map<string, GitBlameAuthor>();
const commits = new Map<string, GitCommit>();
const lines: GitCommitLine[] = [];
for (const range of blame.ranges) {
const c = range.commit;
const { viewer = session.account.label } = blame;
const authorName = viewer != null && c.author.name === viewer ? 'You' : c.author.name;
const committerName = viewer != null && c.committer.name === viewer ? 'You' : c.committer.name;
let author = authors.get(authorName);
if (author == null) {
author = {
name: authorName,
lineCount: 0,
};
authors.set(authorName, author);
}
author.lineCount += range.endingLine - range.startingLine + 1;
let commit = commits.get(c.oid);
if (commit == null) {
commit = new GitCommit(
this.container,
uri.repoPath!,
c.oid,
new GitCommitIdentity(authorName, c.author.email, new Date(c.author.date), c.author.avatarUrl),
new GitCommitIdentity(committerName, c.committer.email, new Date(c.author.date)),
c.message.split('\n', 1)[0],
c.parents.nodes[0]?.oid ? [c.parents.nodes[0]?.oid] : [],
c.message,
new GitFileChange(root.toString(), relativePath, GitFileIndexStatus.Modified),
{ changedFiles: c.changedFiles ?? 0, additions: c.additions ?? 0, deletions: c.deletions ?? 0 },
[],
);
commits.set(c.oid, commit);
}
for (let i = range.startingLine; i <= range.endingLine; i++) {
// GitHub doesn't currently support returning the original line number, so we are just using the current one
const line: GitCommitLine = { sha: c.oid, originalLine: i, line: i };
commit.lines.push(line);
lines[i - 1] = line;
}
}
const sortedAuthors = new Map([...authors.entries()].sort((a, b) => b[1].lineCount - a[1].lineCount));
return {
repoPath: uri.repoPath!,
authors: sortedAuthors,
commits: commits,
lines: lines,
};
} catch (ex) {
debugger;
// Trap and cache expected blame errors
if (document.state != null && !String(ex).includes('No provider registered with')) {
const msg = ex?.toString() ?? '';
Logger.debug(scope, `Cache replace (with empty promise): '${key}'`);
const value: CachedBlame = {
item: emptyPromise as Promise<GitBlame>,
errorMessage: msg,
};
document.state.setBlame(key, value);
document.setBlameFailure();
return emptyPromise as Promise<GitBlame>;
}
return undefined;
}
}
@log<GitHubGitProvider['getBlameContents']>({ args: { 1: '<contents>' } })
async getBlameContents(_uri: GitUri, _contents: string): Promise<GitBlame | undefined> {
// TODO@eamodio figure out how to actually generate a blame given the contents (need to generate a diff)
return undefined; //this.getBlame(uri);
}
@gate<GitHubGitProvider['getBlameForLine']>(
(u, l, d, o) => `${u.toString()}|${l}|${d?.isDirty}|${o?.forceSingleLine}`,
)
@log<GitHubGitProvider['getBlameForLine']>({ args: { 2: d => d?.isDirty } })
async getBlameForLine(
uri: GitUri,
editorLine: number, // 0-based, Git is 1-based
document?: TextDocument | undefined,
options?: { forceSingleLine?: boolean },
): Promise<GitBlameLine | undefined> {
const scope = getLogScope();
// TODO@eamodio we need to figure out when to do this, since dirty isn't enough, we need to know if there are any uncommitted changes
if (document?.isDirty) return undefined; //this.getBlameForLineContents(uri, editorLine, document.getText(), options);
if (!options?.forceSingleLine) {
const blame = await this.getBlame(uri);
if (blame == null) return undefined;
let blameLine = blame.lines[editorLine];
if (blameLine == null) {
if (blame.lines.length !== editorLine) return undefined;
blameLine = blame.lines[editorLine - 1];
}
const commit = blame.commits.get(blameLine.sha);
if (commit == null) return undefined;
const author = blame.authors.get(commit.author.name)!;
return {
author: { ...author, lineCount: commit.lines.length },
commit: commit,
line: blameLine,
};
}
try {
const context = await this.ensureRepositoryContext(uri.repoPath!);
if (context == null) return undefined;
const { metadata, github, remotehub, session } = context;
const root = remotehub.getVirtualUri(remotehub.getProviderRootUri(uri));
const relativePath = this.getRelativePath(uri, root);
const ref = !uri.sha || uri.sha === 'HEAD' ? (await metadata.getRevision()).revision : uri.sha;
const blame = await github.getBlame(
session.accessToken,
metadata.repo.owner,
metadata.repo.name,
ref,
relativePath,
);
const startingLine = editorLine + 1;
const range = blame.ranges.find(r => r.startingLine === startingLine);
if (range == null) return undefined;
const c = range.commit;
const { viewer = session.account.label } = blame;
const authorName = viewer != null && c.author.name === viewer ? 'You' : c.author.name;
const committerName = viewer != null && c.committer.name === viewer ? 'You' : c.committer.name;
const commit = new GitCommit(
this.container,
uri.repoPath!,
c.oid,
new GitCommitIdentity(authorName, c.author.email, new Date(c.author.date), c.author.avatarUrl),
new GitCommitIdentity(committerName, c.committer.email, new Date(c.author.date)),
c.message.split('\n', 1)[0],
c.parents.nodes[0]?.oid ? [c.parents.nodes[0]?.oid] : [],
c.message,
new GitFileChange(root.toString(), relativePath, GitFileIndexStatus.Modified),
{ changedFiles: c.changedFiles ?? 0, additions: c.additions ?? 0, deletions: c.deletions ?? 0 },
[],
);
for (let i = range.startingLine; i <= range.endingLine; i++) {
// GitHub doesn't currently support returning the original line number, so we are just using the current one
const line: GitCommitLine = { sha: c.oid, originalLine: i, line: i };
commit.lines.push(line);
}
return {
author: {
name: authorName,
lineCount: range.endingLine - range.startingLine + 1,
},
commit: commit,
// GitHub doesn't currently support returning the original line number, so we are just using the current one
line: { sha: c.oid, originalLine: range.startingLine, line: range.startingLine },
};
} catch (ex) {
debugger;
Logger.error(scope, ex);
return undefined;
}
}
@log<GitHubGitProvider['getBlameForLineContents']>({ args: { 2: '<contents>' } })
async getBlameForLineContents(
_uri: GitUri,
_editorLine: number, // 0-based, Git is 1-based
_contents: string,
_options?: { forceSingleLine?: boolean },
): Promise<GitBlameLine | undefined> {
// TODO@eamodio figure out how to actually generate a blame given the contents (need to generate a diff)
return undefined; //this.getBlameForLine(uri, editorLine);
}
@log()
async getBlameForRange(uri: GitUri, range: Range): Promise<GitBlameLines | undefined> {
const blame = await this.getBlame(uri);
if (blame == null) return undefined;
return this.getBlameRange(blame, uri, range);
}
@log<GitHubGitProvider['getBlameForRangeContents']>({ args: { 2: '<contents>' } })
async getBlameForRangeContents(uri: GitUri, range: Range, contents: string): Promise<GitBlameLines | undefined> {
const blame = await this.getBlameContents(uri, contents);
if (blame == null) return undefined;
return this.getBlameRange(blame, uri, range);
}
@log<GitHubGitProvider['getBlameRange']>({ args: { 0: '<blame>' } })
getBlameRange(blame: GitBlame, uri: GitUri, range: Range): GitBlameLines | undefined {
if (blame.lines.length === 0) return { allLines: blame.lines, ...blame };
if (range.start.line === 0 && range.end.line === blame.lines.length - 1) {
return { allLines: blame.lines, ...blame };
}
const lines = blame.lines.slice(range.start.line, range.end.line + 1);
const shas = new Set(lines.map(l => l.sha));
// ranges are 0-based
const startLine = range.start.line + 1;
const endLine = range.end.line + 1;
const authors = new Map<string, GitBlameAuthor>();
const commits = new Map<string, GitCommit>();
for (const c of blame.commits.values()) {
if (!shas.has(c.sha)) continue;
const commit = c.with({
lines: c.lines.filter(l => l.line >= startLine && l.line <= endLine),
});
commits.set(c.sha, commit);
let author = authors.get(commit.author.name);
if (author == null) {
author = {
name: commit.author.name,
lineCount: 0,
};
authors.set(author.name, author);
}
author.lineCount += commit.lines.length;
}
const sortedAuthors = new Map([...authors.entries()].sort((a, b) => b[1].lineCount - a[1].lineCount));
return {
repoPath: uri.repoPath!,
authors: sortedAuthors,
commits: commits,
lines: lines,
allLines: blame.lines,
};
}
@log()
async getBranch(repoPath: string | undefined): Promise<GitBranch | undefined> {
const {
values: [branch],
} = await this.getBranches(repoPath, { filter: b => b.current });
return branch;
}
@log({ args: { 1: false } })
async getBranches(
repoPath: string | undefined,
options?: {
cursor?: string;
filter?: (b: GitBranch) => boolean;
sort?: boolean | BranchSortOptions;
},
): Promise<PagedResult<GitBranch>> {
if (repoPath == null) return emptyPagedResult;
const scope = getLogScope();
let branchesPromise = options?.cursor ? undefined : this._branchesCache.get(repoPath);
if (branchesPromise == null) {
async function load(this: GitHubGitProvider): Promise<PagedResult<GitBranch>> {
try {
const { metadata, github, session } = await this.ensureRepositoryContext(repoPath!);
const revision = await metadata.getRevision();
const current = revision.type === 0 /* HeadType.Branch */ ? revision.name : undefined;
const branches: GitBranch[] = [];
let cursor = options?.cursor;
const loadAll = cursor == null;
while (true) {
const result = await github.getBranches(
session.accessToken,
metadata.repo.owner,
metadata.repo.name,
{ cursor: cursor },
);
for (const branch of result.values) {
const date = new Date(
configuration.get('advanced.commitOrdering') === 'author-date'
? branch.target.authoredDate
: branch.target.committedDate,
);
const ref = branch.target.oid;
branches.push(
new GitBranch(repoPath!, branch.name, false, branch.name === current, date, ref, {
name: `origin/${branch.name}`,
missing: false,
}),
new GitBranch(repoPath!, `origin/${branch.name}`, true, false, date, ref),
);
}
if (!result.paging?.more || !loadAll) return { ...result, values: branches };
cursor = result.paging.cursor;
}
} catch (ex) {
Logger.error(ex, scope);
debugger;
this._branchesCache.delete(repoPath!);
return emptyPagedResult;
}
}
branchesPromise = load.call(this);
if (options?.cursor == null) {
this._branchesCache.set(repoPath, branchesPromise);
}
}
let result = await branchesPromise;
if (options?.filter != null) {
result = {
...result,
values: result.values.filter(options.filter),
};
}
if (options?.sort != null) {
sortBranches(result.values, typeof options.sort === 'boolean' ? undefined : options.sort);
}
return result;
}
@log()
async getChangedFilesCount(repoPath: string, ref?: string): Promise<GitDiffShortStat | undefined> {
// TODO@eamodio if there is no ref we can't return anything, until we can get at the change store from RemoteHub
if (!ref) return undefined;
const commit = await this.getCommit(repoPath, ref);
if (commit?.stats == null) return undefined;
const { stats } = commit;
const changedFiles =
typeof stats.changedFiles === 'number'
? stats.changedFiles
: stats.changedFiles.added + stats.changedFiles.changed + stats.changedFiles.deleted;
return { additions: stats.additions, deletions: stats.deletions, changedFiles: changedFiles };
}
@log()
async getCommit(repoPath: string, ref: string): Promise<GitCommit | undefined> {
if (repoPath == null) return undefined;
const scope = getLogScope();
try {
const { metadata, github, session } = await this.ensureRepositoryContext(repoPath);
const commit = await github.getCommit(session.accessToken, metadata.repo.owner, metadata.repo.name, ref);
if (commit == null) return undefined;
const { viewer = session.account.label } = commit;
const authorName = viewer != null && commit.author.name === viewer ? 'You' : commit.author.name;
const committerName = viewer != null && commit.committer.name === viewer ? 'You' : commit.committer.name;
return new GitCommit(
this.container,
repoPath,
commit.oid,
new GitCommitIdentity(
authorName,
commit.author.email,
new Date(commit.author.date),
commit.author.avatarUrl,
),
new GitCommitIdentity(committerName, commit.committer.email, new Date(commit.committer.date)),
commit.message.split('\n', 1)[0],
commit.parents.nodes.map(p => p.oid),
commit.message,
commit.files?.map(
f =>
new GitFileChange(
repoPath,
f.filename ?? '',
fromCommitFileStatus(f.status) ?? GitFileIndexStatus.Modified,
f.previous_filename,
undefined,
{ additions: f.additions ?? 0, deletions: f.deletions ?? 0, changes: f.changes ?? 0 },
),
) ?? [],
{
changedFiles: commit.changedFiles ?? 0,
additions: commit.additions ?? 0,
deletions: commit.deletions ?? 0,
},
[],
);
} catch (ex) {
Logger.error(ex, scope);
debugger;
return undefined;
}
}
@log()
async getCommitBranches(
repoPath: string,
ref: string,
options?: { branch?: string; commitDate?: Date; mode?: 'contains' | 'pointsAt'; remotes?: boolean },
): Promise<string[]> {
if (repoPath == null || options?.commitDate == null) return [];
const scope = getLogScope();
try {
const { metadata, github, session } = await this.ensureRepositoryContext(repoPath);
let branches;
if (options?.branch) {
branches = await github.getCommitOnBranch(
session.accessToken,
metadata.repo.owner,
metadata.repo.name,
options?.branch,
ref,
options?.commitDate,
);
} else {
branches = await github.getCommitBranches(
session.accessToken,
metadata.repo.owner,
metadata.repo.name,
ref,
options?.commitDate,
);
}
return branches;
} catch (ex) {
Logger.error(ex, scope);
debugger;
return [];
}
}
@log()
async getCommitCount(repoPath: string, ref: string): Promise<number | undefined> {
if (repoPath == null) return undefined;
const scope = getLogScope();
try {
const { metadata, github, session } = await this.ensureRepositoryContext(repoPath);
const count = await github.getCommitCount(
session?.accessToken,
metadata.repo.owner,
metadata.repo.name,
ref,
);
return count;
} catch (ex) {
Logger.error(ex, scope);
debugger;
return undefined;
}
}
@log()
async getCommitForFile(
repoPath: string | undefined,
uri: Uri,
options?: { ref?: string; firstIfNotFound?: boolean; range?: Range },