-
Notifications
You must be signed in to change notification settings - Fork 30.3k
/
Copy pathcommands.ts
3822 lines (3058 loc) · 124 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 * as os from 'os';
import * as path from 'path';
import { Command, commands, Disposable, LineChange, MessageOptions, Position, ProgressLocation, QuickPickItem, Range, SourceControlResourceState, TextDocumentShowOptions, TextEditor, Uri, ViewColumn, window, workspace, WorkspaceEdit, WorkspaceFolder, TimelineItem, env, Selection, TextDocumentContentProvider, InputBoxValidationSeverity, TabInputText, TabInputTextMerge, QuickPickItemKind, TextDocument, LogOutputChannel, l10n, Memento, UIKind, QuickInputButton, ThemeIcon } from 'vscode';
import TelemetryReporter from '@vscode/extension-telemetry';
import { uniqueNamesGenerator, adjectives, animals, colors, NumberDictionary } from '@joaomoreno/unique-names-generator';
import { Branch, ForcePushMode, GitErrorCodes, Ref, RefType, Status, CommitOptions, RemoteSourcePublisher, Remote } from './api/git';
import { 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, toMergeUris } from './uri';
import { grep, isDescendant, pathEquals, relativePath } from './util';
import { GitTimelineItem } from './timelineProvider';
import { ApiRepository } from './api/api1';
import { getRemoteSourceActions, pickRemoteSource } from './remoteSource';
import { RemoteSourceAction } from './api/git-base';
class CheckoutItem implements QuickPickItem {
protected get shortCommit(): string { return (this.ref.commit || '').substr(0, 8); }
get label(): string { return `${this.repository.isBranchProtected(this.ref) ? '$(lock)' : '$(git-branch)'} ${this.ref.name || this.shortCommit}`; }
get description(): string { return this.shortCommit; }
get refName(): string | undefined { return this.ref.name; }
get refRemote(): string | undefined { return this.ref.remote; }
get buttons(): QuickInputButton[] | undefined { return this._buttons; }
set buttons(newButtons: QuickInputButton[] | undefined) { this._buttons = newButtons; }
constructor(protected repository: Repository, protected ref: Ref, protected _buttons?: QuickInputButton[]) { }
async run(opts?: { detached?: boolean }): Promise<void> {
if (!this.ref.name) {
return;
}
const config = workspace.getConfiguration('git', Uri.file(this.repository.root));
const pullBeforeCheckout = config.get<boolean>('pullBeforeCheckout', false) === true;
const treeish = opts?.detached ? this.ref.commit ?? this.ref.name : this.ref.name;
await this.repository.checkout(treeish, { ...opts, pullBeforeCheckout });
}
}
class CheckoutTagItem extends CheckoutItem {
override get label(): string { return `$(tag) ${this.ref.name || this.shortCommit}`; }
override get description(): string {
return l10n.t('Tag at {0}', this.shortCommit);
}
override async run(opts?: { detached?: boolean }): Promise<void> {
if (!this.ref.name) {
return;
}
await this.repository.checkout(this.ref.name, opts);
}
}
class CheckoutRemoteHeadItem extends CheckoutItem {
override get label(): string { return `$(cloud) ${this.ref.name || this.shortCommit}`; }
override get description(): string {
return l10n.t('Remote branch at {0}', this.shortCommit);
}
override async run(opts?: { detached?: boolean }): Promise<void> {
if (!this.ref.name) {
return;
}
if (opts?.detached) {
await this.repository.checkout(this.ref.commit ?? this.ref.name, opts);
return;
}
const branches = await this.repository.findTrackingBranches(this.ref.name);
if (branches.length > 0) {
await this.repository.checkout(branches[0].name!, opts);
} else {
await this.repository.checkoutTracking(this.ref.name, opts);
}
}
}
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 RebaseItem implements QuickPickItem {
get label(): string { return this.ref.name || ''; }
description: string = '';
constructor(readonly ref: Ref) { }
async run(repository: Repository): Promise<void> {
if (this.ref?.name) {
await repository.rebase(this.ref.name);
}
}
}
class CreateBranchItem implements QuickPickItem {
get label(): string { return '$(plus) ' + l10n.t('Create new branch...'); }
get description(): string { return ''; }
get alwaysShow(): boolean { return true; }
}
class CreateBranchFromItem implements QuickPickItem {
get label(): string { return '$(plus) ' + l10n.t('Create new branch from...'); }
get description(): string { return ''; }
get alwaysShow(): boolean { return true; }
}
class CheckoutDetachedItem implements QuickPickItem {
get label(): string { return '$(debug-disconnect) ' + l10n.t('Checkout detached...'); }
get description(): string { return ''; }
get alwaysShow(): boolean { return true; }
}
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; }
get refName(): string { return 'HEAD'; }
}
class AddRemoteItem implements QuickPickItem {
constructor(private cc: CommandCenter) { }
get label(): string { return '$(plus) ' + l10n.t('Add a new remote...'); }
get description(): string { return ''; }
get alwaysShow(): boolean { return true; }
async run(repository: Repository): Promise<void> {
await this.cc.addRemote(repository);
}
}
class RemoteItem implements QuickPickItem {
get label() { return `$(cloud) ${this.remote.name}`; }
get description(): string | undefined { return this.remote.fetchUrl; }
get remoteName(): string { return this.remote.name; }
constructor(private readonly repository: Repository, private readonly remote: Remote) { }
async run(): Promise<void> {
await this.repository.fetch({ remote: this.remote.name });
}
}
class FetchAllRemotesItem implements QuickPickItem {
get label(): string { return l10n.t('{0} Fetch all remotes', '$(cloud-download)'); }
constructor(private readonly repository: Repository) { }
async run(): Promise<void> {
await this.repository.fetch({ all: true });
}
}
class RepositoryItem implements QuickPickItem {
get label(): string { return `$(repo) ${getRepositoryLabel(this.path)}`; }
get description(): string { return this.path; }
constructor(public readonly path: string) { }
}
interface ScmCommandOptions {
repository?: boolean;
diff?: boolean;
}
interface ScmCommand {
commandId: string;
key: string;
method: Function;
options: ScmCommandOptions;
}
const Commands: ScmCommand[] = [];
function command(commandId: string, options: ScmCommandOptions = {}): 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 };
}
async function createCheckoutItems(repository: Repository, detached = false): Promise<CheckoutItem[]> {
const config = workspace.getConfiguration('git');
const checkoutTypeConfig = config.get<string | string[]>('checkoutType');
let checkoutTypes: string[];
if (checkoutTypeConfig === 'all' || !checkoutTypeConfig || checkoutTypeConfig.length === 0) {
checkoutTypes = ['local', 'remote', 'tags'];
} else if (typeof checkoutTypeConfig === 'string') {
checkoutTypes = [checkoutTypeConfig];
} else {
checkoutTypes = checkoutTypeConfig;
}
if (detached) {
// Remove tags when in detached mode
checkoutTypes = checkoutTypes.filter(t => t !== 'tags');
}
const refs = await repository.getRefs();
const processors = checkoutTypes.map(type => getCheckoutProcessor(repository, type))
.filter(p => !!p) as CheckoutProcessor[];
for (const ref of refs) {
for (const processor of processors) {
processor.onRef(ref);
}
}
const buttons = await getRemoteRefItemButtons(repository);
let fallbackRemoteButtons: RemoteSourceActionButton[] | undefined = [];
const remote = repository.remotes.find(r => r.pushUrl === repository.HEAD?.remote || r.fetchUrl === repository.HEAD?.remote) ?? repository.remotes[0];
const remoteUrl = remote?.pushUrl ?? remote?.fetchUrl;
if (remoteUrl) {
fallbackRemoteButtons = buttons.get(remoteUrl);
}
return processors.reduce<CheckoutItem[]>((r, p) => r.concat(...p.items.map((item) => {
if (item.refRemote) {
const matchingRemote = repository.remotes.find((remote) => remote.name === item.refRemote);
const remoteUrl = matchingRemote?.pushUrl ?? matchingRemote?.fetchUrl;
if (remoteUrl) {
item.buttons = buttons.get(item.refRemote);
}
}
item.buttons = fallbackRemoteButtons;
return item;
})), []);
}
type RemoteSourceActionButton = {
iconPath: ThemeIcon;
tooltip: string;
actual: RemoteSourceAction;
};
async function getRemoteRefItemButtons(repository: Repository) {
// Compute actions for all known remotes
const remoteUrlsToActions = new Map<string, RemoteSourceActionButton[]>();
const getButtons = async (remoteUrl: string) => (await getRemoteSourceActions(remoteUrl)).map((action) => ({ iconPath: new ThemeIcon(action.icon), tooltip: action.label, actual: action }));
for (const remote of repository.remotes) {
if (remote.fetchUrl) {
const actions = remoteUrlsToActions.get(remote.fetchUrl) ?? [];
actions.push(...await getButtons(remote.fetchUrl));
remoteUrlsToActions.set(remote.fetchUrl, actions);
}
if (remote.pushUrl && remote.pushUrl !== remote.fetchUrl) {
const actions = remoteUrlsToActions.get(remote.pushUrl) ?? [];
actions.push(...await getButtons(remote.pushUrl));
remoteUrlsToActions.set(remote.pushUrl, actions);
}
}
return remoteUrlsToActions;
}
class CheckoutProcessor {
private refs: Ref[] = [];
get items(): CheckoutItem[] { return this.refs.map(r => new this.ctor(this.repository, r)); }
constructor(private repository: Repository, private type: RefType, private ctor: { new(repository: Repository, ref: Ref): CheckoutItem }) { }
onRef(ref: Ref): void {
if (ref.type === this.type) {
this.refs.push(ref);
}
}
}
function getCheckoutProcessor(repository: Repository, type: string): CheckoutProcessor | undefined {
switch (type) {
case 'local':
return new CheckoutProcessor(repository, RefType.Head, CheckoutItem);
case 'remote':
return new CheckoutProcessor(repository, RefType.RemoteHead, CheckoutRemoteHeadItem);
case 'tags':
return new CheckoutProcessor(repository, RefType.Tag, CheckoutTagItem);
}
return undefined;
}
function getRepositoryLabel(repositoryRoot: string): string {
const workspaceFolder = workspace.getWorkspaceFolder(Uri.file(repositoryRoot));
return workspaceFolder?.uri.toString() === repositoryRoot ? workspaceFolder.name : path.basename(repositoryRoot);
}
function compareRepositoryLabel(repositoryRoot1: string, repositoryRoot2: string): number {
return getRepositoryLabel(repositoryRoot1).localeCompare(getRepositoryLabel(repositoryRoot2));
}
function sanitizeBranchName(name: string, whitespaceChar: string): string {
return name ? name.trim().replace(/^-+/, '').replace(/^\.|\/\.|\.\.|~|\^|:|\/$|\.lock$|\.lock\/|\\|\*|\s|^\s*$|\.$|\[|\]$/g, whitespaceChar) : name;
}
function sanitizeRemoteName(name: string) {
name = name.trim();
return name && name.replace(/^\.|\/\.|\.\.|~|\^|:|\/$|\.lock$|\.lock\/|\\|\*|\s|^\s*$|\.$|\[|\]$/g, '-');
}
class TagItem implements QuickPickItem {
get label(): string { return `$(tag) ${this.ref.name ?? ''}`; }
get description(): string { return this.ref.commit?.substr(0, 8) ?? ''; }
constructor(readonly ref: Ref) { }
}
enum PushType {
Push,
PushTo,
PushFollowTags,
PushTags
}
interface PushOptions {
pushType: PushType;
forcePush?: boolean;
silent?: boolean;
pushTo?: {
remote?: string;
refspec?: string;
setUpstream?: boolean;
};
}
class CommandErrorOutputTextDocumentContentProvider implements TextDocumentContentProvider {
private items = new Map<string, string>();
set(uri: Uri, contents: string): void {
this.items.set(uri.path, contents);
}
delete(uri: Uri): void {
this.items.delete(uri.path);
}
provideTextDocumentContent(uri: Uri): string | undefined {
return this.items.get(uri.path);
}
}
export class CommandCenter {
private disposables: Disposable[];
private commandErrors = new CommandErrorOutputTextDocumentContentProvider();
constructor(
private git: Git,
private model: Model,
private globalState: Memento,
private logger: LogOutputChannel,
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);
}
});
this.disposables.push(workspace.registerTextDocumentContentProvider('git-output', this.commandErrors));
}
@command('git.showOutput')
showOutput(): void {
this.logger.show();
}
@command('git.refresh', { repository: true })
async refresh(repository: Repository): Promise<void> {
await repository.status();
}
@command('git.openResource')
async openResource(resource: Resource): Promise<void> {
const repository = this.model.getRepository(resource.resourceUri);
if (!repository) {
return;
}
await resource.open();
}
@command('git.openAllChanges', { repository: true })
async openChanges(repository: Repository): Promise<void> {
for (const resource of [...repository.workingTreeGroup.resourceStates, ...repository.untrackedGroup.resourceStates]) {
if (
resource.type === Status.DELETED || resource.type === Status.DELETED_BY_THEM ||
resource.type === Status.DELETED_BY_US || resource.type === Status.BOTH_DELETED
) {
continue;
}
void commands.executeCommand(
'vscode.open',
resource.resourceUri,
{ background: true, preview: false, }
);
}
}
@command('git.openMergeEditor')
async openMergeEditor(uri: unknown) {
if (uri === undefined) {
// fallback to active editor...
if (window.tabGroups.activeTabGroup.activeTab?.input instanceof TabInputText) {
uri = window.tabGroups.activeTabGroup.activeTab.input.uri;
}
}
if (!(uri instanceof Uri)) {
return;
}
const repo = this.model.getRepository(uri);
if (!repo) {
return;
}
const isRebasing = Boolean(repo.rebaseCommit);
type InputData = { uri: Uri; title?: string; detail?: string; description?: string };
const mergeUris = toMergeUris(uri);
let isStashConflict = false;
try {
// Look at the conflict markers to check if this is a stash conflict
const document = await workspace.openTextDocument(uri);
const firstConflictInfo = findFirstConflictMarker(document);
isStashConflict = firstConflictInfo?.incomingChangeLabel === 'Stashed changes';
} catch (error) {
console.error(error);
}
const current: InputData = { uri: mergeUris.ours, title: l10n.t('Current') };
const incoming: InputData = { uri: mergeUris.theirs, title: l10n.t('Incoming') };
if (isStashConflict) {
incoming.title = l10n.t('Stashed Changes');
}
try {
const [head, rebaseOrMergeHead] = await Promise.all([
repo.getCommit('HEAD'),
isRebasing ? repo.getCommit('REBASE_HEAD') : repo.getCommit('MERGE_HEAD')
]);
// ours (current branch and commit)
current.detail = head.refNames.map(s => s.replace(/^HEAD ->/, '')).join(', ');
current.description = '$(git-commit) ' + head.hash.substring(0, 7);
current.uri = toGitUri(uri, head.hash);
// theirs
incoming.detail = rebaseOrMergeHead.refNames.join(', ');
incoming.description = '$(git-commit) ' + rebaseOrMergeHead.hash.substring(0, 7);
incoming.uri = toGitUri(uri, rebaseOrMergeHead.hash);
} catch (error) {
// not so bad, can continue with just uris
console.error('FAILED to read HEAD, MERGE_HEAD commits');
console.error(error);
}
const options = {
base: mergeUris.base,
input1: isRebasing ? current : incoming,
input2: isRebasing ? incoming : current,
output: uri
};
await commands.executeCommand(
'_open.mergeEditor',
options
);
function findFirstConflictMarker(doc: TextDocument): { currentChangeLabel: string; incomingChangeLabel: string } | undefined {
const conflictMarkerStart = '<<<<<<<';
const conflictMarkerEnd = '>>>>>>>';
let inConflict = false;
let currentChangeLabel: string = '';
let incomingChangeLabel: string = '';
let hasConflict = false;
for (let lineIdx = 0; lineIdx < doc.lineCount; lineIdx++) {
const lineStr = doc.lineAt(lineIdx).text;
if (!inConflict) {
if (lineStr.startsWith(conflictMarkerStart)) {
currentChangeLabel = lineStr.substring(conflictMarkerStart.length).trim();
inConflict = true;
hasConflict = true;
}
} else {
if (lineStr.startsWith(conflictMarkerEnd)) {
incomingChangeLabel = lineStr.substring(conflictMarkerStart.length).trim();
inConflict = false;
break;
}
}
}
if (hasConflict) {
return {
currentChangeLabel,
incomingChangeLabel
};
}
return undefined;
}
}
async cloneRepository(url?: string, parentPath?: string, options: { recursive?: boolean; ref?: string } = {}): Promise<void> {
if (!url || typeof url !== 'string') {
url = await pickRemoteSource({
providerLabel: provider => l10n.t('Clone from {0}', provider.name),
urlLabel: l10n.t('Clone from URL')
});
}
if (!url) {
/* __GDPR__
"clone" : {
"owner": "lszomoru",
"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The outcome of the git operation" }
}
*/
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),
title: l10n.t('Choose a folder to clone {0} into', url),
openLabel: l10n.t('Select as Repository Destination')
});
if (!uris || uris.length === 0) {
/* __GDPR__
"clone" : {
"owner": "lszomoru",
"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The outcome of the git operation" }
}
*/
this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'no_directory' });
return;
}
const uri = uris[0];
parentPath = uri.fsPath;
}
try {
const opts = {
location: ProgressLocation.Notification,
title: l10n.t('Cloning git repository "{0}"...', url),
cancellable: true
};
const repositoryPath = await window.withProgress(
opts,
(progress, token) => this.git.clone(url!, { parentPath: parentPath!, progress, recursive: options.recursive, ref: options.ref }, token)
);
const config = workspace.getConfiguration('git');
const openAfterClone = config.get<'always' | 'alwaysNewWindow' | 'whenNoFolderOpen' | 'prompt'>('openAfterClone');
enum PostCloneAction { Open, OpenNewWindow, AddToWorkspace }
let action: PostCloneAction | undefined = undefined;
if (openAfterClone === 'always') {
action = PostCloneAction.Open;
} else if (openAfterClone === 'alwaysNewWindow') {
action = PostCloneAction.OpenNewWindow;
} else if (openAfterClone === 'whenNoFolderOpen' && !workspace.workspaceFolders) {
action = PostCloneAction.Open;
}
if (action === undefined) {
let message = l10n.t('Would you like to open the cloned repository?');
const open = l10n.t('Open');
const openNewWindow = l10n.t('Open in New Window');
const choices = [open, openNewWindow];
const addToWorkspace = l10n.t('Add to Workspace');
if (workspace.workspaceFolders) {
message = l10n.t('Would you like to open the cloned repository, or add it to the current workspace?');
choices.push(addToWorkspace);
}
const result = await window.showInformationMessage(message, { modal: true }, ...choices);
action = result === open ? PostCloneAction.Open
: result === openNewWindow ? PostCloneAction.OpenNewWindow
: result === addToWorkspace ? PostCloneAction.AddToWorkspace : undefined;
}
/* __GDPR__
"clone" : {
"owner": "lszomoru",
"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The outcome of the git operation" },
"openFolder": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true, "comment": "Indicates whether the folder is opened following the clone operation" }
}
*/
this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'success' }, { openFolder: action === PostCloneAction.Open || action === PostCloneAction.OpenNewWindow ? 1 : 0 });
const uri = Uri.file(repositoryPath);
if (action === PostCloneAction.Open) {
commands.executeCommand('vscode.openFolder', uri, { forceReuseWindow: true });
} else if (action === PostCloneAction.AddToWorkspace) {
workspace.updateWorkspaceFolders(workspace.workspaceFolders!.length, 0, { uri });
} else if (action === PostCloneAction.OpenNewWindow) {
commands.executeCommand('vscode.openFolder', uri, { forceNewWindow: true });
}
} catch (err) {
if (/already exists and is not an empty directory/.test(err && err.stderr || '')) {
/* __GDPR__
"clone" : {
"owner": "lszomoru",
"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The outcome of the git operation" }
}
*/
this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'directory_not_empty' });
} else if (/Cancelled/i.test(err && (err.message || err.stderr || ''))) {
return;
} else {
/* __GDPR__
"clone" : {
"owner": "lszomoru",
"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The outcome of the git operation" }
}
*/
this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'error' });
}
throw err;
}
}
@command('git.continueInLocalClone')
async continueInLocalClone(): Promise<Uri | void> {
if (this.model.repositories.length === 0) { return; }
// Pick a single repository to continue working on in a local clone if there's more than one
const items = this.model.repositories.reduce<(QuickPickItem & { repository: Repository })[]>((items, repository) => {
const remote = repository.remotes.find((r) => r.name === repository.HEAD?.upstream?.remote);
if (remote?.pushUrl) {
items.push({ repository: repository, label: remote.pushUrl });
}
return items;
}, []);
let selection = items[0];
if (items.length > 1) {
const pick = await window.showQuickPick(items, { canPickMany: false, placeHolder: l10n.t('Choose which repository to clone') });
if (pick === undefined) { return; }
selection = pick;
}
const uri = selection.label;
const ref = selection.repository.HEAD?.upstream?.name;
if (uri !== undefined) {
let target = `${env.uriScheme}://vscode.git/clone?url=${encodeURIComponent(uri)}`;
const isWeb = env.uiKind === UIKind.Web;
const isRemote = env.remoteName !== undefined;
if (isWeb || isRemote) {
if (ref !== undefined) {
target += `&ref=${encodeURIComponent(ref)}`;
}
if (isWeb) {
// Launch desktop client if currently in web
return Uri.parse(target);
}
if (isRemote) {
// If already in desktop client but in a remote window, we need to force a new window
// so that the git extension can access the local filesystem for cloning
target += `&windowId=_blank`;
return Uri.parse(target);
}
}
// Otherwise, directly clone
void this.clone(uri, undefined, { ref: ref });
}
}
@command('git.clone')
async clone(url?: string, parentPath?: string, options?: { ref?: string }): Promise<void> {
await this.cloneRepository(url, parentPath, options);
}
@command('git.cloneRecursive')
async cloneRecursive(url?: string, parentPath?: string): Promise<void> {
await this.cloneRepository(url, parentPath, { recursive: true });
}
@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 = l10n.t('Pick workspace folder to initialize git repo in');
const pick = { label: l10n.t('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: l10n.t('Initialize Repository')
});
if (!result || result.length === 0) {
return;
}
const uri = result[0];
if (homeUri.toString().startsWith(uri.toString())) {
const yes = l10n.t('Initialize Repository');
const answer = await window.showWarningMessage(l10n.t('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;
}
}
const config = workspace.getConfiguration('git');
const defaultBranchName = config.get<string>('defaultBranchName', 'main');
const branchWhitespaceChar = config.get<string>('branchWhitespaceChar', '-');
await this.git.init(repositoryPath, { defaultBranch: sanitizeBranchName(defaultBranchName, branchWhitespaceChar) });
let message = l10n.t('Would you like to open the initialized repository?');
const open = l10n.t('Open');
const openNewWindow = l10n.t('Open in New Window');
const choices = [open, openNewWindow];
if (!askToOpen) {
return;
}
const addToWorkspace = l10n.t('Add to Workspace');
if (workspace.workspaceFolders) {
message = l10n.t('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: l10n.t('Open Repository')
});
if (!result || result.length === 0) {
return;
}
path = result[0].fsPath;
}
await this.model.openRepository(path, true);
}
@command('git.reopenClosedRepositories', { repository: false })
async reopenClosedRepositories(): Promise<void> {
if (this.model.closedRepositories.length === 0) {
return;
}
const closedRepositories: string[] = [];
const title = l10n.t('Reopen Closed Repositories');
const placeHolder = l10n.t('Pick a repository to reopen');
const allRepositoriesLabel = l10n.t('All Repositories');
const allRepositoriesQuickPickItem: QuickPickItem = { label: allRepositoriesLabel };
const repositoriesQuickPickItems: QuickPickItem[] = this.model.closedRepositories
.sort(compareRepositoryLabel).map(r => new RepositoryItem(r));
const items = this.model.closedRepositories.length === 1 ? [...repositoriesQuickPickItems] :
[...repositoriesQuickPickItems, { label: '', kind: QuickPickItemKind.Separator }, allRepositoriesQuickPickItem];
const repositoryItem = await window.showQuickPick(items, { title, placeHolder });
if (!repositoryItem) {
return;
}
if (repositoryItem === allRepositoriesQuickPickItem) {
// All Repositories
closedRepositories.push(...this.model.closedRepositories.values());
} else {
// One Repository
closedRepositories.push((repositoryItem as RepositoryItem).path);
}
for (const repository of closedRepositories) {
await this.model.openRepository(repository, true);
}
}
@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;
// Must extract these now because opening a new document will change the activeTextEditor reference
const previousVisibleRange = activeTextEditor?.visibleRanges[0];
const previousURI = activeTextEditor?.document.uri;
const previousSelection = activeTextEditor?.selection;
for (const uri of uris) {
const opts: TextDocumentShowOptions = {
preserveFocus,
preview: false,
viewColumn: ViewColumn.Active
};
await commands.executeCommand('vscode.open', uri, {
...opts,
override: arg instanceof Resource && arg.type === Status.BOTH_MODIFIED ? false : undefined
});