-
Notifications
You must be signed in to change notification settings - Fork 627
/
Copy pathrepository.ts
2830 lines (2309 loc) · 101 KB
/
repository.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import TelemetryReporter from '@vscode/extension-telemetry';
import * as fs from 'fs';
import * as path from 'path';
import picomatch from 'picomatch';
import { CancellationError, CancellationToken, CancellationTokenSource, Command, commands, Disposable, Event, EventEmitter, FileDecoration, l10n, LogLevel, LogOutputChannel, Memento, ProgressLocation, ProgressOptions, QuickDiffProvider, RelativePattern, scm, SourceControl, SourceControlInputBox, SourceControlInputBoxValidation, SourceControlInputBoxValidationType, SourceControlResourceDecorations, SourceControlResourceGroup, SourceControlResourceState, TabInputNotebookDiff, TabInputTextDiff, TabInputTextMultiDiff, ThemeColor, Uri, window, workspace, WorkspaceEdit } from 'vscode';
import { ActionButton } from './actionButton';
import { ApiRepository } from './api/api1';
import { Branch, BranchQuery, Change, CommitOptions, FetchOptions, ForcePushMode, GitErrorCodes, LogOptions, Ref, RefQuery, RefType, Remote, Status } from './api/git';
import { AutoFetcher } from './autofetch';
import { GitBranchProtectionProvider, IBranchProtectionProviderRegistry } from './branchProtection';
import { debounce, memoize, throttle } from './decorators';
import { Repository as BaseRepository, BlameInformation, Commit, GitError, LogFileOptions, LsTreeElement, PullOptions, Stash, Submodule } from './git';
import { GitHistoryProvider } from './historyProvider';
import { Operation, OperationKind, OperationManager, OperationResult } from './operation';
import { CommitCommandsCenter, IPostCommitCommandsProviderRegistry } from './postCommitCommands';
import { IPushErrorHandlerRegistry } from './pushError';
import { IRemoteSourcePublisherRegistry } from './remotePublisher';
import { StatusBarCommands } from './statusbar';
import { toGitUri } from './uri';
import { anyEvent, combinedDisposable, debounceEvent, dispose, EmptyDisposable, eventToPromise, filterEvent, find, getCommitShortHash, IDisposable, isDescendant, isLinuxSnap, isRemote, Limiter, onceEvent, pathEquals, relativePath } from './util';
import { IFileWatcher, watch } from './watch';
import { ISourceControlHistoryItemDetailsProviderRegistry } from './historyItemDetailsProvider';
const timeout = (millis: number) => new Promise(c => setTimeout(c, millis));
const iconsRootPath = path.join(path.dirname(__dirname), 'resources', 'icons');
function getIconUri(iconName: string, theme: string): Uri {
return Uri.file(path.join(iconsRootPath, theme, `${iconName}.svg`));
}
export const enum RepositoryState {
Idle,
Disposed
}
export const enum ResourceGroupType {
Merge,
Index,
WorkingTree,
Untracked
}
export class Resource implements SourceControlResourceState {
static getStatusLetter(type: Status): string {
switch (type) {
case Status.INDEX_MODIFIED:
case Status.MODIFIED:
return 'M';
case Status.INDEX_ADDED:
case Status.INTENT_TO_ADD:
return 'A';
case Status.INDEX_DELETED:
case Status.DELETED:
return 'D';
case Status.INDEX_RENAMED:
case Status.INTENT_TO_RENAME:
return 'R';
case Status.TYPE_CHANGED:
return 'T';
case Status.UNTRACKED:
return 'U';
case Status.IGNORED:
return 'I';
case Status.DELETED_BY_THEM:
return 'D';
case Status.DELETED_BY_US:
return 'D';
case Status.INDEX_COPIED:
return 'C';
case Status.BOTH_DELETED:
case Status.ADDED_BY_US:
case Status.ADDED_BY_THEM:
case Status.BOTH_ADDED:
case Status.BOTH_MODIFIED:
return '!'; // Using ! instead of ⚠, because the latter looks really bad on windows
default:
throw new Error('Unknown git status: ' + type);
}
}
static getStatusText(type: Status) {
switch (type) {
case Status.INDEX_MODIFIED: return l10n.t('Index Modified');
case Status.MODIFIED: return l10n.t('Modified');
case Status.INDEX_ADDED: return l10n.t('Index Added');
case Status.INDEX_DELETED: return l10n.t('Index Deleted');
case Status.DELETED: return l10n.t('Deleted');
case Status.INDEX_RENAMED: return l10n.t('Index Renamed');
case Status.INDEX_COPIED: return l10n.t('Index Copied');
case Status.UNTRACKED: return l10n.t('Untracked');
case Status.IGNORED: return l10n.t('Ignored');
case Status.INTENT_TO_ADD: return l10n.t('Intent to Add');
case Status.INTENT_TO_RENAME: return l10n.t('Intent to Rename');
case Status.TYPE_CHANGED: return l10n.t('Type Changed');
case Status.BOTH_DELETED: return l10n.t('Conflict: Both Deleted');
case Status.ADDED_BY_US: return l10n.t('Conflict: Added By Us');
case Status.DELETED_BY_THEM: return l10n.t('Conflict: Deleted By Them');
case Status.ADDED_BY_THEM: return l10n.t('Conflict: Added By Them');
case Status.DELETED_BY_US: return l10n.t('Conflict: Deleted By Us');
case Status.BOTH_ADDED: return l10n.t('Conflict: Both Added');
case Status.BOTH_MODIFIED: return l10n.t('Conflict: Both Modified');
default: return '';
}
}
static getStatusColor(type: Status): ThemeColor {
switch (type) {
case Status.INDEX_MODIFIED:
return new ThemeColor('gitDecoration.stageModifiedResourceForeground');
case Status.MODIFIED:
case Status.TYPE_CHANGED:
return new ThemeColor('gitDecoration.modifiedResourceForeground');
case Status.INDEX_DELETED:
return new ThemeColor('gitDecoration.stageDeletedResourceForeground');
case Status.DELETED:
return new ThemeColor('gitDecoration.deletedResourceForeground');
case Status.INDEX_ADDED:
case Status.INTENT_TO_ADD:
return new ThemeColor('gitDecoration.addedResourceForeground');
case Status.INDEX_COPIED:
case Status.INDEX_RENAMED:
case Status.INTENT_TO_RENAME:
return new ThemeColor('gitDecoration.renamedResourceForeground');
case Status.UNTRACKED:
return new ThemeColor('gitDecoration.untrackedResourceForeground');
case Status.IGNORED:
return new ThemeColor('gitDecoration.ignoredResourceForeground');
case Status.BOTH_DELETED:
case Status.ADDED_BY_US:
case Status.DELETED_BY_THEM:
case Status.ADDED_BY_THEM:
case Status.DELETED_BY_US:
case Status.BOTH_ADDED:
case Status.BOTH_MODIFIED:
return new ThemeColor('gitDecoration.conflictingResourceForeground');
default:
throw new Error('Unknown git status: ' + type);
}
}
@memoize
get resourceUri(): Uri {
if (this.renameResourceUri && (this._type === Status.MODIFIED || this._type === Status.DELETED || this._type === Status.INDEX_RENAMED || this._type === Status.INDEX_COPIED || this._type === Status.INTENT_TO_RENAME)) {
return this.renameResourceUri;
}
return this._resourceUri;
}
get leftUri(): Uri | undefined {
return this.resources.left;
}
get rightUri(): Uri | undefined {
return this.resources.right;
}
get multiDiffEditorOriginalUri(): Uri | undefined {
return this.resources.original;
}
get multiFileDiffEditorModifiedUri(): Uri | undefined {
return this.resources.modified;
}
@memoize
get command(): Command {
return this._commandResolver.resolveDefaultCommand(this);
}
@memoize
private get resources(): { left: Uri | undefined; right: Uri | undefined; original: Uri | undefined; modified: Uri | undefined } {
return this._commandResolver.getResources(this);
}
get resourceGroupType(): ResourceGroupType { return this._resourceGroupType; }
get type(): Status { return this._type; }
get original(): Uri { return this._resourceUri; }
get renameResourceUri(): Uri | undefined { return this._renameResourceUri; }
private static Icons: any = {
light: {
Modified: getIconUri('status-modified', 'light'),
Added: getIconUri('status-added', 'light'),
Deleted: getIconUri('status-deleted', 'light'),
Renamed: getIconUri('status-renamed', 'light'),
Copied: getIconUri('status-copied', 'light'),
Untracked: getIconUri('status-untracked', 'light'),
Ignored: getIconUri('status-ignored', 'light'),
Conflict: getIconUri('status-conflict', 'light'),
TypeChanged: getIconUri('status-type-changed', 'light')
},
dark: {
Modified: getIconUri('status-modified', 'dark'),
Added: getIconUri('status-added', 'dark'),
Deleted: getIconUri('status-deleted', 'dark'),
Renamed: getIconUri('status-renamed', 'dark'),
Copied: getIconUri('status-copied', 'dark'),
Untracked: getIconUri('status-untracked', 'dark'),
Ignored: getIconUri('status-ignored', 'dark'),
Conflict: getIconUri('status-conflict', 'dark'),
TypeChanged: getIconUri('status-type-changed', 'dark')
}
};
private getIconPath(theme: string): Uri {
switch (this.type) {
case Status.INDEX_MODIFIED: return Resource.Icons[theme].Modified;
case Status.MODIFIED: return Resource.Icons[theme].Modified;
case Status.INDEX_ADDED: return Resource.Icons[theme].Added;
case Status.INDEX_DELETED: return Resource.Icons[theme].Deleted;
case Status.DELETED: return Resource.Icons[theme].Deleted;
case Status.INDEX_RENAMED: return Resource.Icons[theme].Renamed;
case Status.INDEX_COPIED: return Resource.Icons[theme].Copied;
case Status.UNTRACKED: return Resource.Icons[theme].Untracked;
case Status.IGNORED: return Resource.Icons[theme].Ignored;
case Status.INTENT_TO_ADD: return Resource.Icons[theme].Added;
case Status.INTENT_TO_RENAME: return Resource.Icons[theme].Renamed;
case Status.TYPE_CHANGED: return Resource.Icons[theme].TypeChanged;
case Status.BOTH_DELETED: return Resource.Icons[theme].Conflict;
case Status.ADDED_BY_US: return Resource.Icons[theme].Conflict;
case Status.DELETED_BY_THEM: return Resource.Icons[theme].Conflict;
case Status.ADDED_BY_THEM: return Resource.Icons[theme].Conflict;
case Status.DELETED_BY_US: return Resource.Icons[theme].Conflict;
case Status.BOTH_ADDED: return Resource.Icons[theme].Conflict;
case Status.BOTH_MODIFIED: return Resource.Icons[theme].Conflict;
default: throw new Error('Unknown git status: ' + this.type);
}
}
private get tooltip(): string {
return Resource.getStatusText(this.type);
}
private get strikeThrough(): boolean {
switch (this.type) {
case Status.DELETED:
case Status.BOTH_DELETED:
case Status.DELETED_BY_THEM:
case Status.DELETED_BY_US:
case Status.INDEX_DELETED:
return true;
default:
return false;
}
}
@memoize
private get faded(): boolean {
// TODO@joao
return false;
// const workspaceRootPath = this.workspaceRoot.fsPath;
// return this.resourceUri.fsPath.substr(0, workspaceRootPath.length) !== workspaceRootPath;
}
get decorations(): SourceControlResourceDecorations {
const light = this._useIcons ? { iconPath: this.getIconPath('light') } : undefined;
const dark = this._useIcons ? { iconPath: this.getIconPath('dark') } : undefined;
const tooltip = this.tooltip;
const strikeThrough = this.strikeThrough;
const faded = this.faded;
return { strikeThrough, faded, tooltip, light, dark };
}
get letter(): string {
return Resource.getStatusLetter(this.type);
}
get color(): ThemeColor {
return Resource.getStatusColor(this.type);
}
get priority(): number {
switch (this.type) {
case Status.INDEX_MODIFIED:
case Status.MODIFIED:
case Status.INDEX_COPIED:
case Status.TYPE_CHANGED:
return 2;
case Status.IGNORED:
return 3;
case Status.BOTH_DELETED:
case Status.ADDED_BY_US:
case Status.DELETED_BY_THEM:
case Status.ADDED_BY_THEM:
case Status.DELETED_BY_US:
case Status.BOTH_ADDED:
case Status.BOTH_MODIFIED:
return 4;
default:
return 1;
}
}
get resourceDecoration(): FileDecoration {
const res = new FileDecoration(this.letter, this.tooltip, this.color);
res.propagate = this.type !== Status.DELETED && this.type !== Status.INDEX_DELETED;
return res;
}
constructor(
private _commandResolver: ResourceCommandResolver,
private _resourceGroupType: ResourceGroupType,
private _resourceUri: Uri,
private _type: Status,
private _useIcons: boolean,
private _renameResourceUri?: Uri,
) { }
async open(): Promise<void> {
const command = this.command;
await commands.executeCommand<void>(command.command, ...(command.arguments || []));
}
async openFile(): Promise<void> {
const command = this._commandResolver.resolveFileCommand(this);
await commands.executeCommand<void>(command.command, ...(command.arguments || []));
}
async openChange(): Promise<void> {
const command = this._commandResolver.resolveChangeCommand(this);
await commands.executeCommand<void>(command.command, ...(command.arguments || []));
}
clone(resourceGroupType?: ResourceGroupType) {
return new Resource(this._commandResolver, resourceGroupType ?? this._resourceGroupType, this._resourceUri, this._type, this._useIcons, this._renameResourceUri);
}
}
export interface GitResourceGroup extends SourceControlResourceGroup {
resourceStates: Resource[];
}
interface GitResourceGroups {
indexGroup?: Resource[];
mergeGroup?: Resource[];
untrackedGroup?: Resource[];
workingTreeGroup?: Resource[];
}
class ProgressManager {
private enabled = false;
private disposable: IDisposable = EmptyDisposable;
constructor(private repository: Repository) {
const onDidChange = filterEvent(workspace.onDidChangeConfiguration, e => e.affectsConfiguration('git', Uri.file(this.repository.root)));
onDidChange(_ => this.updateEnablement());
this.updateEnablement();
this.repository.onDidChangeOperations(() => {
// Disable input box when the commit operation is running
this.repository.sourceControl.inputBox.enabled = !this.repository.operations.isRunning(OperationKind.Commit);
});
}
private updateEnablement(): void {
const config = workspace.getConfiguration('git', Uri.file(this.repository.root));
if (config.get<boolean>('showProgress')) {
this.enable();
} else {
this.disable();
}
}
private enable(): void {
if (this.enabled) {
return;
}
const start = onceEvent(filterEvent(this.repository.onDidChangeOperations, () => this.repository.operations.shouldShowProgress()));
const end = onceEvent(filterEvent(debounceEvent(this.repository.onDidChangeOperations, 300), () => !this.repository.operations.shouldShowProgress()));
const setup = () => {
this.disposable = start(() => {
const promise = eventToPromise(end).then(() => setup());
window.withProgress({ location: ProgressLocation.SourceControl }, () => promise);
});
};
setup();
this.enabled = true;
}
private disable(): void {
if (!this.enabled) {
return;
}
this.disposable.dispose();
this.disposable = EmptyDisposable;
this.enabled = false;
}
dispose(): void {
this.disable();
}
}
class FileEventLogger {
private eventDisposable: IDisposable = EmptyDisposable;
private logLevelDisposable: IDisposable = EmptyDisposable;
constructor(
private onWorkspaceWorkingTreeFileChange: Event<Uri>,
private onDotGitFileChange: Event<Uri>,
private logger: LogOutputChannel
) {
this.logLevelDisposable = logger.onDidChangeLogLevel(this.onDidChangeLogLevel, this);
this.onDidChangeLogLevel(logger.logLevel);
}
private onDidChangeLogLevel(logLevel: LogLevel): void {
this.eventDisposable.dispose();
if (logLevel > LogLevel.Debug) {
return;
}
this.eventDisposable = combinedDisposable([
this.onWorkspaceWorkingTreeFileChange(uri => this.logger.debug(`[FileEventLogger][onWorkspaceWorkingTreeFileChange] ${uri.fsPath}`)),
this.onDotGitFileChange(uri => this.logger.debug(`[FileEventLogger][onDotGitFileChange] ${uri.fsPath}`))
]);
}
dispose(): void {
this.eventDisposable.dispose();
this.logLevelDisposable.dispose();
}
}
class DotGitWatcher implements IFileWatcher {
readonly event: Event<Uri>;
private emitter = new EventEmitter<Uri>();
private transientDisposables: IDisposable[] = [];
private disposables: IDisposable[] = [];
constructor(
private repository: Repository,
private logger: LogOutputChannel
) {
const rootWatcher = watch(repository.dotGit.path);
this.disposables.push(rootWatcher);
// Ignore changes to the "index.lock" file, and watchman fsmonitor hook (https://git-scm.com/docs/githooks#_fsmonitor_watchman) cookie files.
// Watchman creates a cookie file inside the git directory whenever a query is run (https://facebook.github.io/watchman/docs/cookies.html).
const filteredRootWatcher = filterEvent(rootWatcher.event, uri => uri.scheme === 'file' && !/\/\.git(\/index\.lock)?$|\/\.watchman-cookie-/.test(uri.path));
this.event = anyEvent(filteredRootWatcher, this.emitter.event);
repository.onDidRunGitStatus(this.updateTransientWatchers, this, this.disposables);
this.updateTransientWatchers();
}
private updateTransientWatchers() {
this.transientDisposables = dispose(this.transientDisposables);
if (!this.repository.HEAD || !this.repository.HEAD.upstream) {
return;
}
this.transientDisposables = dispose(this.transientDisposables);
const { name, remote } = this.repository.HEAD.upstream;
const upstreamPath = path.join(this.repository.dotGit.commonPath ?? this.repository.dotGit.path, 'refs', 'remotes', remote, name);
try {
const upstreamWatcher = watch(upstreamPath);
this.transientDisposables.push(upstreamWatcher);
upstreamWatcher.event(this.emitter.fire, this.emitter, this.transientDisposables);
} catch (err) {
this.logger.warn(`[DotGitWatcher][updateTransientWatchers] Failed to watch ref '${upstreamPath}', is most likely packed.`);
}
}
dispose() {
this.emitter.dispose();
this.transientDisposables = dispose(this.transientDisposables);
this.disposables = dispose(this.disposables);
}
}
class ResourceCommandResolver {
constructor(private repository: Repository) { }
resolveDefaultCommand(resource: Resource): Command {
const config = workspace.getConfiguration('git', Uri.file(this.repository.root));
const openDiffOnClick = config.get<boolean>('openDiffOnClick', true);
return openDiffOnClick ? this.resolveChangeCommand(resource) : this.resolveFileCommand(resource);
}
resolveFileCommand(resource: Resource): Command {
return {
command: 'vscode.open',
title: l10n.t('Open'),
arguments: [resource.resourceUri]
};
}
resolveChangeCommand(resource: Resource): Command {
const title = this.getTitle(resource);
if (!resource.leftUri) {
const bothModified = resource.type === Status.BOTH_MODIFIED;
if (resource.rightUri && workspace.getConfiguration('git').get<boolean>('mergeEditor', false) && (bothModified || resource.type === Status.BOTH_ADDED)) {
return {
command: 'git.openMergeEditor',
title: l10n.t('Open Merge'),
arguments: [resource.rightUri]
};
} else {
return {
command: 'vscode.open',
title: l10n.t('Open'),
arguments: [resource.rightUri, { override: bothModified ? false : undefined }, title]
};
}
} else {
return {
command: 'vscode.diff',
title: l10n.t('Open'),
arguments: [resource.leftUri, resource.rightUri, title]
};
}
}
getResources(resource: Resource): { left: Uri | undefined; right: Uri | undefined; original: Uri | undefined; modified: Uri | undefined } {
for (const submodule of this.repository.submodules) {
if (path.join(this.repository.root, submodule.path) === resource.resourceUri.fsPath) {
const original = undefined;
const modified = toGitUri(resource.resourceUri, resource.resourceGroupType === ResourceGroupType.Index ? 'index' : 'wt', { submoduleOf: this.repository.root });
return { left: original, right: modified, original, modified };
}
}
const left = this.getLeftResource(resource);
const right = this.getRightResource(resource);
return {
left: left.original ?? left.modified,
right: right.original ?? right.modified,
original: left.original ?? right.original,
modified: left.modified ?? right.modified,
};
}
private getLeftResource(resource: Resource): ModifiedOrOriginal {
switch (resource.type) {
case Status.INDEX_MODIFIED:
case Status.INDEX_RENAMED:
case Status.INTENT_TO_RENAME:
case Status.TYPE_CHANGED:
return { original: toGitUri(resource.original, 'HEAD') };
case Status.MODIFIED:
return { original: toGitUri(resource.resourceUri, '~') };
case Status.DELETED_BY_US:
case Status.DELETED_BY_THEM:
return { original: toGitUri(resource.resourceUri, '~1') };
}
return {};
}
private getRightResource(resource: Resource): ModifiedOrOriginal {
switch (resource.type) {
case Status.INDEX_MODIFIED:
case Status.INDEX_ADDED:
case Status.INDEX_COPIED:
case Status.INDEX_RENAMED:
return { modified: toGitUri(resource.resourceUri, '') };
case Status.INDEX_DELETED:
case Status.DELETED:
return { original: toGitUri(resource.resourceUri, 'HEAD') };
case Status.DELETED_BY_US:
return { original: toGitUri(resource.resourceUri, '~3') };
case Status.DELETED_BY_THEM:
return { original: toGitUri(resource.resourceUri, '~2') };
case Status.MODIFIED:
case Status.UNTRACKED:
case Status.IGNORED:
case Status.INTENT_TO_ADD:
case Status.INTENT_TO_RENAME:
case Status.TYPE_CHANGED: {
const uriString = resource.resourceUri.toString();
const [indexStatus] = this.repository.indexGroup.resourceStates.filter(r => r.resourceUri.toString() === uriString);
if (indexStatus && indexStatus.renameResourceUri) {
return { modified: indexStatus.renameResourceUri };
}
return { modified: resource.resourceUri };
}
case Status.BOTH_ADDED:
case Status.BOTH_MODIFIED:
return { modified: resource.resourceUri };
}
return {};
}
private getTitle(resource: Resource): string {
const basename = path.basename(resource.resourceUri.fsPath);
switch (resource.type) {
case Status.INDEX_MODIFIED:
case Status.INDEX_RENAMED:
case Status.INDEX_ADDED:
return l10n.t('{0} (Index)', basename);
case Status.MODIFIED:
case Status.BOTH_ADDED:
case Status.BOTH_MODIFIED:
return l10n.t('{0} (Working Tree)', basename);
case Status.INDEX_DELETED:
case Status.DELETED:
return l10n.t('{0} (Deleted)', basename);
case Status.DELETED_BY_US:
return l10n.t('{0} (Theirs)', basename);
case Status.DELETED_BY_THEM:
return l10n.t('{0} (Ours)', basename);
case Status.UNTRACKED:
return l10n.t('{0} (Untracked)', basename);
case Status.INTENT_TO_ADD:
case Status.INTENT_TO_RENAME:
return l10n.t('{0} (Intent to add)', basename);
case Status.TYPE_CHANGED:
return l10n.t('{0} (Type changed)', basename);
default:
return '';
}
}
}
interface ModifiedOrOriginal {
modified?: Uri | undefined;
original?: Uri | undefined;
}
interface BranchProtectionMatcher {
include?: picomatch.Matcher;
exclude?: picomatch.Matcher;
}
export interface IRepositoryResolver {
getRepository(sourceControl: SourceControl): Repository | undefined;
getRepository(resourceGroup: SourceControlResourceGroup): Repository | undefined;
getRepository(path: string): Repository | undefined;
getRepository(resource: Uri): Repository | undefined;
getRepository(hint: any): Repository | undefined;
}
export class Repository implements Disposable {
private _onDidChangeRepository = new EventEmitter<Uri>();
readonly onDidChangeRepository: Event<Uri> = this._onDidChangeRepository.event;
private _onDidChangeState = new EventEmitter<RepositoryState>();
readonly onDidChangeState: Event<RepositoryState> = this._onDidChangeState.event;
private _onDidChangeStatus = new EventEmitter<void>();
readonly onDidRunGitStatus: Event<void> = this._onDidChangeStatus.event;
private _onDidChangeOriginalResource = new EventEmitter<Uri>();
readonly onDidChangeOriginalResource: Event<Uri> = this._onDidChangeOriginalResource.event;
private _onRunOperation = new EventEmitter<OperationKind>();
readonly onRunOperation: Event<OperationKind> = this._onRunOperation.event;
private _onDidRunOperation = new EventEmitter<OperationResult>();
readonly onDidRunOperation: Event<OperationResult> = this._onDidRunOperation.event;
private _onDidChangeBranchProtection = new EventEmitter<void>();
readonly onDidChangeBranchProtection: Event<void> = this._onDidChangeBranchProtection.event;
@memoize
get onDidChangeOperations(): Event<void> {
return anyEvent(this.onRunOperation as Event<any>, this.onDidRunOperation as Event<any>);
}
private _sourceControl: SourceControl;
get sourceControl(): SourceControl { return this._sourceControl; }
get inputBox(): SourceControlInputBox { return this._sourceControl.inputBox; }
private _mergeGroup: SourceControlResourceGroup;
get mergeGroup(): GitResourceGroup { return this._mergeGroup as GitResourceGroup; }
private _indexGroup: SourceControlResourceGroup;
get indexGroup(): GitResourceGroup { return this._indexGroup as GitResourceGroup; }
private _workingTreeGroup: SourceControlResourceGroup;
get workingTreeGroup(): GitResourceGroup { return this._workingTreeGroup as GitResourceGroup; }
private _untrackedGroup: SourceControlResourceGroup;
get untrackedGroup(): GitResourceGroup { return this._untrackedGroup as GitResourceGroup; }
private _EMPTY_TREE: string | undefined;
private _HEAD: Branch | undefined;
get HEAD(): Branch | undefined {
return this._HEAD;
}
private _refs: Ref[] = [];
get refs(): Ref[] {
return this._refs;
}
get headShortName(): string | undefined {
if (!this.HEAD) {
return;
}
const HEAD = this.HEAD;
if (HEAD.name) {
return HEAD.name;
}
return (HEAD.commit || '').substr(0, 8);
}
private _remotes: Remote[] = [];
get remotes(): Remote[] {
return this._remotes;
}
private _submodules: Submodule[] = [];
get submodules(): Submodule[] {
return this._submodules;
}
private _rebaseCommit: Commit | undefined = undefined;
set rebaseCommit(rebaseCommit: Commit | undefined) {
if (this._rebaseCommit && !rebaseCommit) {
this.inputBox.value = '';
} else if (rebaseCommit && (!this._rebaseCommit || this._rebaseCommit.hash !== rebaseCommit.hash)) {
this.inputBox.value = rebaseCommit.message;
}
const shouldUpdateContext = !!this._rebaseCommit !== !!rebaseCommit;
this._rebaseCommit = rebaseCommit;
if (shouldUpdateContext) {
commands.executeCommand('setContext', 'gitRebaseInProgress', !!this._rebaseCommit);
}
}
get rebaseCommit(): Commit | undefined {
return this._rebaseCommit;
}
private _mergeInProgress: boolean = false;
set mergeInProgress(value: boolean) {
if (this._mergeInProgress === value) {
return;
}
this._mergeInProgress = value;
commands.executeCommand('setContext', 'gitMergeInProgress', value);
}
get mergeInProgress() {
return this._mergeInProgress;
}
private _cherryPickInProgress: boolean = false;
set cherryPickInProgress(value: boolean) {
if (this._cherryPickInProgress === value) {
return;
}
this._cherryPickInProgress = value;
commands.executeCommand('setContext', 'gitCherryPickInProgress', value);
}
get cherryPickInProgress() {
return this._cherryPickInProgress;
}
private _operations = new OperationManager(this.logger);
get operations(): OperationManager { return this._operations; }
private _state = RepositoryState.Idle;
get state(): RepositoryState { return this._state; }
set state(state: RepositoryState) {
this._state = state;
this._onDidChangeState.fire(state);
this._HEAD = undefined;
this._remotes = [];
this.mergeGroup.resourceStates = [];
this.indexGroup.resourceStates = [];
this.workingTreeGroup.resourceStates = [];
this.untrackedGroup.resourceStates = [];
this._sourceControl.count = 0;
}
get root(): string {
return this.repository.root;
}
get rootRealPath(): string | undefined {
return this.repository.rootRealPath;
}
get dotGit(): { path: string; commonPath?: string } {
return this.repository.dotGit;
}
private _historyProvider: GitHistoryProvider;
get historyProvider(): GitHistoryProvider { return this._historyProvider; }
private isRepositoryHuge: false | { limit: number } = false;
private didWarnAboutLimit = false;
private unpublishedCommits: Set<string> | undefined = undefined;
private branchProtection = new Map<string, BranchProtectionMatcher[]>();
private commitCommandCenter: CommitCommandsCenter;
private resourceCommandResolver = new ResourceCommandResolver(this);
private updateModelStateCancellationTokenSource: CancellationTokenSource | undefined;
private disposables: Disposable[] = [];
constructor(
private readonly repository: BaseRepository,
private readonly repositoryResolver: IRepositoryResolver,
private pushErrorHandlerRegistry: IPushErrorHandlerRegistry,
remoteSourcePublisherRegistry: IRemoteSourcePublisherRegistry,
postCommitCommandsProviderRegistry: IPostCommitCommandsProviderRegistry,
private readonly branchProtectionProviderRegistry: IBranchProtectionProviderRegistry,
historyItemDetailProviderRegistry: ISourceControlHistoryItemDetailsProviderRegistry,
globalState: Memento,
private readonly logger: LogOutputChannel,
private telemetryReporter: TelemetryReporter
) {
const repositoryWatcher = workspace.createFileSystemWatcher(new RelativePattern(Uri.file(repository.root), '**'));
this.disposables.push(repositoryWatcher);
const onRepositoryFileChange = anyEvent(repositoryWatcher.onDidChange, repositoryWatcher.onDidCreate, repositoryWatcher.onDidDelete);
const onRepositoryWorkingTreeFileChange = filterEvent(onRepositoryFileChange, uri => !/\.git($|\\|\/)/.test(relativePath(repository.root, uri.fsPath)));
let onRepositoryDotGitFileChange: Event<Uri>;
try {
const dotGitFileWatcher = new DotGitWatcher(this, logger);
onRepositoryDotGitFileChange = dotGitFileWatcher.event;
this.disposables.push(dotGitFileWatcher);
} catch (err) {
logger.error(`Failed to watch path:'${this.dotGit.path}' or commonPath:'${this.dotGit.commonPath}', reverting to legacy API file watched. Some events might be lost.\n${err.stack || err}`);
onRepositoryDotGitFileChange = filterEvent(onRepositoryFileChange, uri => /\.git($|\\|\/)/.test(uri.path));
}
// FS changes should trigger `git status`:
// - any change inside the repository working tree
// - any change whithin the first level of the `.git` folder, except the folder itself and `index.lock`
const onFileChange = anyEvent(onRepositoryWorkingTreeFileChange, onRepositoryDotGitFileChange);
onFileChange(this.onFileChange, this, this.disposables);
// Relevate repository changes should trigger virtual document change events
onRepositoryDotGitFileChange(this._onDidChangeRepository.fire, this._onDidChangeRepository, this.disposables);
this.disposables.push(new FileEventLogger(onRepositoryWorkingTreeFileChange, onRepositoryDotGitFileChange, logger));
const root = Uri.file(repository.root);
this._sourceControl = scm.createSourceControl('git', 'Git', root);
this._sourceControl.quickDiffProvider = this;
this._historyProvider = new GitHistoryProvider(historyItemDetailProviderRegistry, this, logger);
this._sourceControl.historyProvider = this._historyProvider;
this.disposables.push(this._historyProvider);
this._sourceControl.acceptInputCommand = { command: 'git.commit', title: l10n.t('Commit'), arguments: [this._sourceControl] };
this._sourceControl.inputBox.validateInput = this.validateInput.bind(this);
this.disposables.push(this._sourceControl);
this.updateInputBoxPlaceholder();
this.disposables.push(this.onDidRunGitStatus(() => this.updateInputBoxPlaceholder()));
this._mergeGroup = this._sourceControl.createResourceGroup('merge', l10n.t('Merge Changes'));
this._indexGroup = this._sourceControl.createResourceGroup('index', l10n.t('Staged Changes'), { multiDiffEditorEnableViewChanges: true });
this._workingTreeGroup = this._sourceControl.createResourceGroup('workingTree', l10n.t('Changes'), { multiDiffEditorEnableViewChanges: true });
this._untrackedGroup = this._sourceControl.createResourceGroup('untracked', l10n.t('Untracked Changes'), { multiDiffEditorEnableViewChanges: true });
const updateIndexGroupVisibility = () => {
const config = workspace.getConfiguration('git', root);
this.indexGroup.hideWhenEmpty = !config.get<boolean>('alwaysShowStagedChangesResourceGroup');
};
const onConfigListener = filterEvent(workspace.onDidChangeConfiguration, e => e.affectsConfiguration('git.alwaysShowStagedChangesResourceGroup', root));
onConfigListener(updateIndexGroupVisibility, this, this.disposables);
updateIndexGroupVisibility();
workspace.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('git.mergeEditor')) {
this.mergeGroup.resourceStates = this.mergeGroup.resourceStates.map(r => r.clone());
}
}, undefined, this.disposables);
filterEvent(workspace.onDidChangeConfiguration, e =>
e.affectsConfiguration('git.branchSortOrder', root)
|| e.affectsConfiguration('git.untrackedChanges', root)
|| e.affectsConfiguration('git.ignoreSubmodules', root)
|| e.affectsConfiguration('git.openDiffOnClick', root)
|| e.affectsConfiguration('git.showActionButton', root)
|| e.affectsConfiguration('git.similarityThreshold', root)
)(() => this.updateModelState(), this, this.disposables);
const updateInputBoxVisibility = () => {
const config = workspace.getConfiguration('git', root);
this._sourceControl.inputBox.visible = config.get<boolean>('showCommitInput', true);
};
const onConfigListenerForInputBoxVisibility = filterEvent(workspace.onDidChangeConfiguration, e => e.affectsConfiguration('git.showCommitInput', root));
onConfigListenerForInputBoxVisibility(updateInputBoxVisibility, this, this.disposables);
updateInputBoxVisibility();
this.mergeGroup.hideWhenEmpty = true;
this.untrackedGroup.hideWhenEmpty = true;
this.disposables.push(this.mergeGroup);
this.disposables.push(this.indexGroup);
this.disposables.push(this.workingTreeGroup);
this.disposables.push(this.untrackedGroup);
// Don't allow auto-fetch in untrusted workspaces
if (workspace.isTrusted) {
this.disposables.push(new AutoFetcher(this, globalState));
} else {
const trustDisposable = workspace.onDidGrantWorkspaceTrust(() => {
trustDisposable.dispose();
this.disposables.push(new AutoFetcher(this, globalState));
});
this.disposables.push(trustDisposable);
}
// https://github.com/microsoft/vscode/issues/39039
const onSuccessfulPush = filterEvent(this.onDidRunOperation, e => e.operation.kind === OperationKind.Push && !e.error);
onSuccessfulPush(() => {
const gitConfig = workspace.getConfiguration('git');
if (gitConfig.get<boolean>('showPushSuccessNotification')) {
window.showInformationMessage(l10n.t('Successfully pushed.'));
}
}, null, this.disposables);
// Default branch protection provider
const onBranchProtectionProviderChanged = filterEvent(this.branchProtectionProviderRegistry.onDidChangeBranchProtectionProviders, e => pathEquals(e.fsPath, root.fsPath));
this.disposables.push(onBranchProtectionProviderChanged(root => this.updateBranchProtectionMatchers(root)));
this.disposables.push(this.branchProtectionProviderRegistry.registerBranchProtectionProvider(root, new GitBranchProtectionProvider(root)));
const statusBar = new StatusBarCommands(this, remoteSourcePublisherRegistry);
this.disposables.push(statusBar);
statusBar.onDidChange(() => this._sourceControl.statusBarCommands = statusBar.commands, null, this.disposables);
this._sourceControl.statusBarCommands = statusBar.commands;
this.commitCommandCenter = new CommitCommandsCenter(globalState, this, postCommitCommandsProviderRegistry);
this.disposables.push(this.commitCommandCenter);
const actionButton = new ActionButton(this, this.commitCommandCenter, this.logger);
this.disposables.push(actionButton);
actionButton.onDidChange(() => this._sourceControl.actionButton = actionButton.button, this, this.disposables);
this._sourceControl.actionButton = actionButton.button;
const progressManager = new ProgressManager(this);
this.disposables.push(progressManager);
const onDidChangeCountBadge = filterEvent(workspace.onDidChangeConfiguration, e => e.affectsConfiguration('git.countBadge', root));
onDidChangeCountBadge(this.setCountBadge, this, this.disposables);
this.setCountBadge();
}