-
Notifications
You must be signed in to change notification settings - Fork 30.1k
/
Copy pathcommands.ts
2688 lines (2134 loc) · 86.1 KB
/
commands.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 { lstat, Stats } from 'fs';
import * as os from 'os';
import * as path from 'path';
import { commands, Disposable, LineChange, MessageOptions, OutputChannel, Position, ProgressLocation, QuickPickItem, Range, SourceControlResourceState, TextDocumentShowOptions, TextEditor, Uri, ViewColumn, window, workspace, WorkspaceEdit, WorkspaceFolder, TimelineItem, env, QuickPick } from 'vscode';
import TelemetryReporter from 'vscode-extension-telemetry';
import * as nls from 'vscode-nls';
import { Branch, GitErrorCodes, Ref, RefType, Status, CommitOptions, RemoteSourceProvider, RemoteSource } from './api/git';
import { ForcePushMode, Git, Stash } from './git';
import { Model } from './model';
import { Repository, Resource, ResourceGroupType } from './repository';
import { applyLineChanges, getModifiedRange, intersectDiffWithRange, invertLineChange, toLineRanges } from './staging';
import { fromGitUri, toGitUri, isGitUri } from './uri';
import { grep, isDescendant, pathEquals } from './util';
import { Log, LogLevel } from './log';
import { GitTimelineItem } from './timelineProvider';
import { throttle, debounce } from './decorators';
const localize = nls.loadMessageBundle();
class CheckoutItem implements QuickPickItem {
protected get shortCommit(): string { return (this.ref.commit || '').substr(0, 8); }
get label(): string { return this.ref.name || this.shortCommit; }
get description(): string { return this.shortCommit; }
constructor(protected ref: Ref) { }
async run(repository: Repository): Promise<void> {
const ref = this.ref.name;
if (!ref) {
return;
}
await repository.checkout(ref);
}
}
class CheckoutTagItem extends CheckoutItem {
get description(): string {
return localize('tag at', "Tag at {0}", this.shortCommit);
}
}
class CheckoutRemoteHeadItem extends CheckoutItem {
get description(): string {
return localize('remote branch at', "Remote branch at {0}", this.shortCommit);
}
async run(repository: Repository): Promise<void> {
if (!this.ref.name) {
return;
}
const branches = await repository.findTrackingBranches(this.ref.name);
if (branches.length > 0) {
await repository.checkout(branches[0].name!);
} else {
await repository.checkoutTracking(this.ref.name);
}
}
}
class BranchDeleteItem implements QuickPickItem {
private get shortCommit(): string { return (this.ref.commit || '').substr(0, 8); }
get branchName(): string | undefined { return this.ref.name; }
get label(): string { return this.branchName || ''; }
get description(): string { return this.shortCommit; }
constructor(private ref: Ref) { }
async run(repository: Repository, force?: boolean): Promise<void> {
if (!this.branchName) {
return;
}
await repository.deleteBranch(this.branchName, force);
}
}
class MergeItem implements QuickPickItem {
get label(): string { return this.ref.name || ''; }
get description(): string { return this.ref.name || ''; }
constructor(protected ref: Ref) { }
async run(repository: Repository): Promise<void> {
await repository.merge(this.ref.name! || this.ref.commit!);
}
}
class CreateBranchItem implements QuickPickItem {
constructor(private cc: CommandCenter) { }
get label(): string { return '$(plus) ' + localize('create branch', 'Create new branch...'); }
get description(): string { return ''; }
get alwaysShow(): boolean { return true; }
async run(repository: Repository): Promise<void> {
await this.cc.branch(repository);
}
}
class CreateBranchFromItem implements QuickPickItem {
constructor(private cc: CommandCenter) { }
get label(): string { return '$(plus) ' + localize('create branch from', 'Create new branch from...'); }
get description(): string { return ''; }
get alwaysShow(): boolean { return true; }
async run(repository: Repository): Promise<void> {
await this.cc.branch(repository);
}
}
class HEADItem implements QuickPickItem {
constructor(private repository: Repository) { }
get label(): string { return 'HEAD'; }
get description(): string { return (this.repository.HEAD && this.repository.HEAD.commit || '').substr(0, 8); }
get alwaysShow(): boolean { return true; }
}
class AddRemoteItem implements QuickPickItem {
constructor(private cc: CommandCenter) { }
get label(): string { return '$(plus) ' + localize('add remote', 'Add a new remote...'); }
get description(): string { return ''; }
get alwaysShow(): boolean { return true; }
async run(repository: Repository): Promise<void> {
await this.cc.addRemote(repository);
}
}
interface CommandOptions {
repository?: boolean;
diff?: boolean;
}
interface Command {
commandId: string;
key: string;
method: Function;
options: CommandOptions;
}
const Commands: Command[] = [];
function command(commandId: string, options: CommandOptions = {}): Function {
return (_target: any, key: string, descriptor: any) => {
if (!(typeof descriptor.value === 'function')) {
throw new Error('not supported');
}
Commands.push({ commandId, key, method: descriptor.value, options });
};
}
// const ImageMimetypes = [
// 'image/png',
// 'image/gif',
// 'image/jpeg',
// 'image/webp',
// 'image/tiff',
// 'image/bmp'
// ];
async function categorizeResourceByResolution(resources: Resource[]): Promise<{ merge: Resource[], resolved: Resource[], unresolved: Resource[], deletionConflicts: Resource[] }> {
const selection = resources.filter(s => s instanceof Resource) as Resource[];
const merge = selection.filter(s => s.resourceGroupType === ResourceGroupType.Merge);
const isBothAddedOrModified = (s: Resource) => s.type === Status.BOTH_MODIFIED || s.type === Status.BOTH_ADDED;
const isAnyDeleted = (s: Resource) => s.type === Status.DELETED_BY_THEM || s.type === Status.DELETED_BY_US;
const possibleUnresolved = merge.filter(isBothAddedOrModified);
const promises = possibleUnresolved.map(s => grep(s.resourceUri.fsPath, /^<{7}|^={7}|^>{7}/));
const unresolvedBothModified = await Promise.all<boolean>(promises);
const resolved = possibleUnresolved.filter((_s, i) => !unresolvedBothModified[i]);
const deletionConflicts = merge.filter(s => isAnyDeleted(s));
const unresolved = [
...merge.filter(s => !isBothAddedOrModified(s) && !isAnyDeleted(s)),
...possibleUnresolved.filter((_s, i) => unresolvedBothModified[i])
];
return { merge, resolved, unresolved, deletionConflicts };
}
function createCheckoutItems(repository: Repository): CheckoutItem[] {
const config = workspace.getConfiguration('git');
const checkoutType = config.get<string>('checkoutType') || 'all';
const includeTags = checkoutType === 'all' || checkoutType === 'tags';
const includeRemotes = checkoutType === 'all' || checkoutType === 'remote';
const heads = repository.refs.filter(ref => ref.type === RefType.Head)
.map(ref => new CheckoutItem(ref));
const tags = (includeTags ? repository.refs.filter(ref => ref.type === RefType.Tag) : [])
.map(ref => new CheckoutTagItem(ref));
const remoteHeads = (includeRemotes ? repository.refs.filter(ref => ref.type === RefType.RemoteHead) : [])
.map(ref => new CheckoutRemoteHeadItem(ref));
return [...heads, ...tags, ...remoteHeads];
}
class TagItem implements QuickPickItem {
get label(): string { return this.ref.name ?? ''; }
get description(): string { return this.ref.commit?.substr(0, 8) ?? ''; }
constructor(readonly ref: Ref) { }
}
enum PushType {
Push,
PushTo,
PushFollowTags,
}
interface PushOptions {
pushType: PushType;
forcePush?: boolean;
silent?: boolean;
}
async function getQuickPickResult<T extends QuickPickItem>(quickpick: QuickPick<T>): Promise<T | undefined> {
const result = await new Promise<T | undefined>(c => {
quickpick.onDidAccept(() => c(quickpick.selectedItems[0]));
quickpick.onDidHide(() => c(undefined));
quickpick.show();
});
quickpick.hide();
return result;
}
class RemoteSourceProviderQuickPick {
private quickpick: QuickPick<QuickPickItem & { remoteSource?: RemoteSource }>;
constructor(private provider: RemoteSourceProvider) {
this.quickpick = window.createQuickPick();
this.quickpick.ignoreFocusOut = true;
if (provider.supportsQuery) {
this.quickpick.placeholder = localize('type to search', "Repository name (type to search)");
this.quickpick.onDidChangeValue(this.onDidChangeValue, this);
} else {
this.quickpick.placeholder = localize('type to filter', "Repository name");
}
}
@debounce(300)
onDidChangeValue(): void {
this.query();
}
@throttle
async query(): Promise<void> {
this.quickpick.busy = true;
try {
const remoteSources = await this.provider.getRemoteSources(this.quickpick.value) || [];
if (remoteSources.length === 0) {
this.quickpick.items = [{
label: localize('none found', "No remote repositories found."),
alwaysShow: true
}];
} else {
this.quickpick.items = remoteSources.map(remoteSource => ({
label: remoteSource.name,
description: remoteSource.description || (typeof remoteSource.url === 'string' ? remoteSource.url : remoteSource.url[0]),
remoteSource
}));
}
} catch (err) {
this.quickpick.items = [{ label: localize('error', "$(error) Error: {0}", err.message), alwaysShow: true }];
} finally {
this.quickpick.busy = false;
}
}
async pick(): Promise<RemoteSource | undefined> {
this.query();
const result = await getQuickPickResult(this.quickpick);
return result?.remoteSource;
}
}
export class CommandCenter {
private disposables: Disposable[];
constructor(
private git: Git,
private model: Model,
private outputChannel: OutputChannel,
private telemetryReporter: TelemetryReporter
) {
this.disposables = Commands.map(({ commandId, key, method, options }) => {
const command = this.createCommand(commandId, key, method, options);
if (options.diff) {
return commands.registerDiffInformationCommand(commandId, command);
} else {
return commands.registerCommand(commandId, command);
}
});
}
@command('git.setLogLevel')
async setLogLevel(): Promise<void> {
const createItem = (logLevel: LogLevel) => ({
label: LogLevel[logLevel],
logLevel,
description: Log.logLevel === logLevel ? localize('current', "Current") : undefined
});
const items = [
createItem(LogLevel.Trace),
createItem(LogLevel.Debug),
createItem(LogLevel.Info),
createItem(LogLevel.Warning),
createItem(LogLevel.Error),
createItem(LogLevel.Critical),
createItem(LogLevel.Off)
];
const choice = await window.showQuickPick(items, {
placeHolder: localize('select log level', "Select log level")
});
if (!choice) {
return;
}
Log.logLevel = choice.logLevel;
this.outputChannel.appendLine(localize('changed', "Log level changed to: {0}", LogLevel[Log.logLevel]));
}
@command('git.refresh', { repository: true })
async refresh(repository: Repository): Promise<void> {
await repository.status();
}
@command('git.openResource')
async openResource(resource: Resource, preserveFocus: boolean): Promise<void> {
const repository = this.model.getRepository(resource.resourceUri);
if (!repository) {
return;
}
const config = workspace.getConfiguration('git', Uri.file(repository.root));
const openDiffOnClick = config.get<boolean>('openDiffOnClick');
if (openDiffOnClick) {
await this._openResource(resource, undefined, preserveFocus, false);
} else {
await this.openFile(resource);
}
}
private async _openResource(resource: Resource, preview?: boolean, preserveFocus?: boolean, preserveSelection?: boolean): Promise<void> {
let stat: Stats | undefined;
try {
stat = await new Promise<Stats>((c, e) => lstat(resource.resourceUri.fsPath, (err, stat) => err ? e(err) : c(stat)));
} catch (err) {
// noop
}
let left: Uri | undefined;
let right: Uri | undefined;
if (stat && stat.isDirectory()) {
const repository = this.model.getRepositoryForSubmodule(resource.resourceUri);
if (repository) {
right = toGitUri(resource.resourceUri, resource.resourceGroupType === ResourceGroupType.Index ? 'index' : 'wt', { submoduleOf: repository.root });
}
} else {
if (resource.type !== Status.DELETED_BY_THEM) {
left = this.getLeftResource(resource);
}
right = this.getRightResource(resource);
}
const title = this.getTitle(resource);
if (!right) {
// TODO
console.error('oh no');
return;
}
const opts: TextDocumentShowOptions = {
preserveFocus,
preview,
viewColumn: ViewColumn.Active
};
const activeTextEditor = window.activeTextEditor;
// Check if active text editor has same path as other editor. we cannot compare via
// URI.toString() here because the schemas can be different. Instead we just go by path.
if (preserveSelection && activeTextEditor && activeTextEditor.document.uri.path === right.path) {
opts.selection = activeTextEditor.selection;
}
if (!left) {
await commands.executeCommand<void>('vscode.open', right, opts, title);
} else {
await commands.executeCommand<void>('vscode.diff', left, right, title, opts);
}
}
private getLeftResource(resource: Resource): Uri | undefined {
switch (resource.type) {
case Status.INDEX_MODIFIED:
case Status.INDEX_RENAMED:
case Status.INDEX_ADDED:
return toGitUri(resource.original, 'HEAD');
case Status.MODIFIED:
case Status.UNTRACKED:
return toGitUri(resource.resourceUri, '~');
case Status.DELETED_BY_THEM:
return toGitUri(resource.resourceUri, '');
}
return undefined;
}
private getRightResource(resource: Resource): Uri | undefined {
switch (resource.type) {
case Status.INDEX_MODIFIED:
case Status.INDEX_ADDED:
case Status.INDEX_COPIED:
case Status.INDEX_RENAMED:
return toGitUri(resource.resourceUri, '');
case Status.INDEX_DELETED:
case Status.DELETED:
return toGitUri(resource.resourceUri, 'HEAD');
case Status.DELETED_BY_US:
return toGitUri(resource.resourceUri, '~3');
case Status.DELETED_BY_THEM:
return toGitUri(resource.resourceUri, '~2');
case Status.MODIFIED:
case Status.UNTRACKED:
case Status.IGNORED:
case Status.INTENT_TO_ADD:
const repository = this.model.getRepository(resource.resourceUri);
if (!repository) {
return;
}
const uriString = resource.resourceUri.toString();
const [indexStatus] = repository.indexGroup.resourceStates.filter(r => r.resourceUri.toString() === uriString);
if (indexStatus && indexStatus.renameResourceUri) {
return indexStatus.renameResourceUri;
}
return resource.resourceUri;
case Status.BOTH_ADDED:
case Status.BOTH_MODIFIED:
return resource.resourceUri;
}
return undefined;
}
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 localize('git.title.index', '{0} (Index)', basename);
case Status.MODIFIED:
case Status.BOTH_ADDED:
case Status.BOTH_MODIFIED:
return localize('git.title.workingTree', '{0} (Working Tree)', basename);
case Status.DELETED_BY_US:
return localize('git.title.theirs', '{0} (Theirs)', basename);
case Status.DELETED_BY_THEM:
return localize('git.title.ours', '{0} (Ours)', basename);
case Status.UNTRACKED:
return localize('git.title.untracked', '{0} (Untracked)', basename);
default:
return '';
}
}
@command('git.clone')
async clone(url?: string, parentPath?: string): Promise<void> {
if (!url) {
const quickpick = window.createQuickPick<(QuickPickItem & { provider?: RemoteSourceProvider, url?: string })>();
quickpick.ignoreFocusOut = true;
const providers = this.model.getRemoteProviders()
.map(provider => ({ label: (provider.icon ? `$(${provider.icon}) ` : '') + localize('clonefrom', "Clone from {0}", provider.name), alwaysShow: true, provider }));
quickpick.placeholder = providers.length === 0
? localize('provide url', "Provide repository URL.")
: localize('provide url or pick', "Provide repository URL or pick a repository source.");
const updatePicks = (value?: string) => {
if (value) {
quickpick.items = [{
label: localize('repourl', "Clone from URL"),
description: value,
alwaysShow: true,
url: value
},
...providers];
} else {
quickpick.items = providers;
}
};
quickpick.onDidChangeValue(updatePicks);
updatePicks();
const result = await getQuickPickResult(quickpick);
if (result) {
if (result.url) {
url = result.url;
} else if (result.provider) {
const quickpick = new RemoteSourceProviderQuickPick(result.provider);
const remote = await quickpick.pick();
if (remote) {
if (typeof remote.url === 'string') {
url = remote.url;
} else if (remote.url.length > 0) {
url = await window.showQuickPick(remote.url, { ignoreFocusOut: true, placeHolder: localize('pick url', "Choose a URL to clone from.") });
}
}
}
}
}
if (!url) {
/* __GDPR__
"clone" : {
"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'no_URL' });
return;
}
url = url.trim().replace(/^git\s+clone\s+/, '');
if (!parentPath) {
const config = workspace.getConfiguration('git');
let defaultCloneDirectory = config.get<string>('defaultCloneDirectory') || os.homedir();
defaultCloneDirectory = defaultCloneDirectory.replace(/^~/, os.homedir());
const uris = await window.showOpenDialog({
canSelectFiles: false,
canSelectFolders: true,
canSelectMany: false,
defaultUri: Uri.file(defaultCloneDirectory),
openLabel: localize('selectFolder', "Select Repository Location")
});
if (!uris || uris.length === 0) {
/* __GDPR__
"clone" : {
"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'no_directory' });
return;
}
const uri = uris[0];
parentPath = uri.fsPath;
}
try {
const opts = {
location: ProgressLocation.Notification,
title: localize('cloning', "Cloning git repository '{0}'...", url),
cancellable: true
};
const repositoryPath = await window.withProgress(
opts,
(progress, token) => this.git.clone(url!, parentPath!, progress, token)
);
let message = localize('proposeopen', "Would you like to open the cloned repository?");
const open = localize('openrepo', "Open");
const openNewWindow = localize('openreponew', "Open in New Window");
const choices = [open, openNewWindow];
const addToWorkspace = localize('add', "Add to Workspace");
if (workspace.workspaceFolders) {
message = localize('proposeopen2', "Would you like to open the cloned repository, or add it to the current workspace?");
choices.push(addToWorkspace);
}
const result = await window.showInformationMessage(message, ...choices);
const openFolder = result === open;
/* __GDPR__
"clone" : {
"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"openFolder": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true }
}
*/
this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'success' }, { openFolder: openFolder ? 1 : 0 });
const uri = Uri.file(repositoryPath);
if (openFolder) {
commands.executeCommand('vscode.openFolder', uri);
} else if (result === addToWorkspace) {
workspace.updateWorkspaceFolders(workspace.workspaceFolders!.length, 0, { uri });
} else if (result === openNewWindow) {
commands.executeCommand('vscode.openFolder', uri, true);
}
} catch (err) {
if (/already exists and is not an empty directory/.test(err && err.stderr || '')) {
/* __GDPR__
"clone" : {
"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'directory_not_empty' });
} else if (/Cancelled/i.test(err && (err.message || err.stderr || ''))) {
return;
} else {
/* __GDPR__
"clone" : {
"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'error' });
}
throw err;
}
}
@command('git.init')
async init(skipFolderPrompt = false): Promise<void> {
let repositoryPath: string | undefined = undefined;
let askToOpen = true;
if (workspace.workspaceFolders) {
if (skipFolderPrompt && workspace.workspaceFolders.length === 1) {
repositoryPath = workspace.workspaceFolders[0].uri.fsPath;
askToOpen = false;
} else {
const placeHolder = localize('init', "Pick workspace folder to initialize git repo in");
const pick = { label: localize('choose', "Choose Folder...") };
const items: { label: string, folder?: WorkspaceFolder }[] = [
...workspace.workspaceFolders.map(folder => ({ label: folder.name, description: folder.uri.fsPath, folder })),
pick
];
const item = await window.showQuickPick(items, { placeHolder, ignoreFocusOut: true });
if (!item) {
return;
} else if (item.folder) {
repositoryPath = item.folder.uri.fsPath;
askToOpen = false;
}
}
}
if (!repositoryPath) {
const homeUri = Uri.file(os.homedir());
const defaultUri = workspace.workspaceFolders && workspace.workspaceFolders.length > 0
? Uri.file(workspace.workspaceFolders[0].uri.fsPath)
: homeUri;
const result = await window.showOpenDialog({
canSelectFiles: false,
canSelectFolders: true,
canSelectMany: false,
defaultUri,
openLabel: localize('init repo', "Initialize Repository")
});
if (!result || result.length === 0) {
return;
}
const uri = result[0];
if (homeUri.toString().startsWith(uri.toString())) {
const yes = localize('create repo', "Initialize Repository");
const answer = await window.showWarningMessage(localize('are you sure', "This will create a Git repository in '{0}'. Are you sure you want to continue?", uri.fsPath), yes);
if (answer !== yes) {
return;
}
}
repositoryPath = uri.fsPath;
if (workspace.workspaceFolders && workspace.workspaceFolders.some(w => w.uri.toString() === uri.toString())) {
askToOpen = false;
}
}
await this.git.init(repositoryPath);
let message = localize('proposeopen init', "Would you like to open the initialized repository?");
const open = localize('openrepo', "Open");
const openNewWindow = localize('openreponew', "Open in New Window");
const choices = [open, openNewWindow];
if (!askToOpen) {
return;
}
const addToWorkspace = localize('add', "Add to Workspace");
if (workspace.workspaceFolders) {
message = localize('proposeopen2 init', "Would you like to open the initialized repository, or add it to the current workspace?");
choices.push(addToWorkspace);
}
const result = await window.showInformationMessage(message, ...choices);
const uri = Uri.file(repositoryPath);
if (result === open) {
commands.executeCommand('vscode.openFolder', uri);
} else if (result === addToWorkspace) {
workspace.updateWorkspaceFolders(workspace.workspaceFolders!.length, 0, { uri });
} else if (result === openNewWindow) {
commands.executeCommand('vscode.openFolder', uri, true);
} else {
await this.model.openRepository(repositoryPath);
}
}
@command('git.openRepository', { repository: false })
async openRepository(path?: string): Promise<void> {
if (!path) {
const result = await window.showOpenDialog({
canSelectFiles: false,
canSelectFolders: true,
canSelectMany: false,
defaultUri: Uri.file(os.homedir()),
openLabel: localize('open repo', "Open Repository")
});
if (!result || result.length === 0) {
return;
}
path = result[0].fsPath;
}
await this.model.openRepository(path);
}
@command('git.close', { repository: true })
async close(repository: Repository): Promise<void> {
this.model.close(repository);
}
@command('git.openFile')
async openFile(arg?: Resource | Uri, ...resourceStates: SourceControlResourceState[]): Promise<void> {
const preserveFocus = arg instanceof Resource;
let uris: Uri[] | undefined;
if (arg instanceof Uri) {
if (isGitUri(arg)) {
uris = [Uri.file(fromGitUri(arg).path)];
} else if (arg.scheme === 'file') {
uris = [arg];
}
} else {
let resource = arg;
if (!(resource instanceof Resource)) {
// can happen when called from a keybinding
resource = this.getSCMResource();
}
if (resource) {
uris = ([resource, ...resourceStates] as Resource[])
.filter(r => r.type !== Status.DELETED && r.type !== Status.INDEX_DELETED)
.map(r => r.resourceUri);
} else if (window.activeTextEditor) {
uris = [window.activeTextEditor.document.uri];
}
}
if (!uris) {
return;
}
const activeTextEditor = window.activeTextEditor;
for (const uri of uris) {
const opts: TextDocumentShowOptions = {
preserveFocus,
preview: false,
viewColumn: ViewColumn.Active
};
let document;
try {
document = await workspace.openTextDocument(uri);
} catch (error) {
await commands.executeCommand<void>('vscode.open', uri, opts);
continue;
}
// Check if active text editor has same path as other editor. we cannot compare via
// URI.toString() here because the schemas can be different. Instead we just go by path.
if (activeTextEditor && activeTextEditor.document.uri.path === uri.path) {
// preserve not only selection but also visible range
opts.selection = activeTextEditor.selection;
const previousVisibleRanges = activeTextEditor.visibleRanges;
const editor = await window.showTextDocument(document, opts);
editor.revealRange(previousVisibleRanges[0]);
} else {
await window.showTextDocument(document, opts);
}
}
}
@command('git.openFile2')
async openFile2(arg?: Resource | Uri, ...resourceStates: SourceControlResourceState[]): Promise<void> {
this.openFile(arg, ...resourceStates);
}
@command('git.openHEADFile')
async openHEADFile(arg?: Resource | Uri): Promise<void> {
let resource: Resource | undefined = undefined;
const preview = !(arg instanceof Resource);
if (arg instanceof Resource) {
resource = arg;
} else if (arg instanceof Uri) {
resource = this.getSCMResource(arg);
} else {
resource = this.getSCMResource();
}
if (!resource) {
return;
}
const HEAD = this.getLeftResource(resource);
const basename = path.basename(resource.resourceUri.fsPath);
const title = `${basename} (HEAD)`;
if (!HEAD) {
window.showWarningMessage(localize('HEAD not available', "HEAD version of '{0}' is not available.", path.basename(resource.resourceUri.fsPath)));
return;
}
const opts: TextDocumentShowOptions = {
preview
};
return await commands.executeCommand<void>('vscode.open', HEAD, opts, title);
}
@command('git.openChange')
async openChange(arg?: Resource | Uri, ...resourceStates: SourceControlResourceState[]): Promise<void> {
const preserveFocus = arg instanceof Resource;
const preview = !(arg instanceof Resource);
const preserveSelection = arg instanceof Uri || !arg;
let resources: Resource[] | undefined = undefined;
if (arg instanceof Uri) {
const resource = this.getSCMResource(arg);
if (resource !== undefined) {
resources = [resource];
}
} else {
let resource: Resource | undefined = undefined;
if (arg instanceof Resource) {
resource = arg;
} else {
resource = this.getSCMResource();
}
if (resource) {
resources = [...resourceStates as Resource[], resource];
}
}
if (!resources) {
return;
}
for (const resource of resources) {
await this._openResource(resource, preview, preserveFocus, preserveSelection);
}
}
@command('git.stage')
async stage(...resourceStates: SourceControlResourceState[]): Promise<void> {
this.outputChannel.appendLine(`git.stage ${resourceStates.length}`);
resourceStates = resourceStates.filter(s => !!s);
if (resourceStates.length === 0 || (resourceStates[0] && !(resourceStates[0].resourceUri instanceof Uri))) {
const resource = this.getSCMResource();
this.outputChannel.appendLine(`git.stage.getSCMResource ${resource ? resource.resourceUri.toString() : null}`);
if (!resource) {
return;
}
resourceStates = [resource];
}
const selection = resourceStates.filter(s => s instanceof Resource) as Resource[];
const { resolved, unresolved, deletionConflicts } = await categorizeResourceByResolution(selection);
if (unresolved.length > 0) {
const message = unresolved.length > 1
? localize('confirm stage files with merge conflicts', "Are you sure you want to stage {0} files with merge conflicts?", unresolved.length)
: localize('confirm stage file with merge conflicts', "Are you sure you want to stage {0} with merge conflicts?", path.basename(unresolved[0].resourceUri.fsPath));
const yes = localize('yes', "Yes");
const pick = await window.showWarningMessage(message, { modal: true }, yes);
if (pick !== yes) {
return;
}
}
try {
await this.runByRepository(deletionConflicts.map(r => r.resourceUri), async (repository, resources) => {
for (const resource of resources) {
await this._stageDeletionConflict(repository, resource);
}
});
} catch (err) {
if (/Cancelled/.test(err.message)) {
return;
}
throw err;
}
const workingTree = selection.filter(s => s.resourceGroupType === ResourceGroupType.WorkingTree);
const untracked = selection.filter(s => s.resourceGroupType === ResourceGroupType.Untracked);
const scmResources = [...workingTree, ...untracked, ...resolved, ...unresolved];
this.outputChannel.appendLine(`git.stage.scmResources ${scmResources.length}`);
if (!scmResources.length) {
return;
}
const resources = scmResources.map(r => r.resourceUri);
await this.runByRepository(resources, async (repository, resources) => repository.add(resources));
}
@command('git.stageAll', { repository: true })
async stageAll(repository: Repository): Promise<void> {
const resources = repository.mergeGroup.resourceStates.filter(s => s instanceof Resource) as Resource[];
const { merge, unresolved, deletionConflicts } = await categorizeResourceByResolution(resources);
try {
for (const deletionConflict of deletionConflicts) {