-
Notifications
You must be signed in to change notification settings - Fork 29k
/
commands.ts
4552 lines (3658 loc) · 147 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, SourceControlHistoryItem, SourceControl, InputBoxValidationMessage, Tab, TabInputNotebook, QuickInputButtonLocation, SourceControlHistoryItemRef } from 'vscode';
import TelemetryReporter from '@vscode/extension-telemetry';
import { uniqueNamesGenerator, adjectives, animals, colors, NumberDictionary } from '@joaomoreno/unique-names-generator';
import { ForcePushMode, GitErrorCodes, Ref, RefType, Status, CommitOptions, RemoteSourcePublisher, Remote } from './api/git';
import { Git, Stash } from './git';
import { Model } from './model';
import { GitResourceGroup, Repository, Resource, ResourceGroupType } from './repository';
import { DiffEditorSelectionHunkToolbarContext, applyLineChanges, getModifiedRange, intersectDiffWithRange, invertLineChange, toLineRanges } from './staging';
import { fromGitUri, toGitUri, isGitUri, toMergeUris, toMultiFileDiffEditorUris } from './uri';
import { dispose, grep, isDefined, 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';
abstract class CheckoutCommandItem implements QuickPickItem {
abstract get label(): string;
get description(): string { return ''; }
get alwaysShow(): boolean { return true; }
}
class CreateBranchItem extends CheckoutCommandItem {
get label(): string { return l10n.t('{0} Create new branch...', '$(plus)'); }
}
class CreateBranchFromItem extends CheckoutCommandItem {
get label(): string { return l10n.t('{0} Create new branch from...', '$(plus)'); }
}
class CheckoutDetachedItem extends CheckoutCommandItem {
get label(): string { return l10n.t('{0} Checkout detached...', '$(debug-disconnect)'); }
}
class RefItemSeparator implements QuickPickItem {
get kind(): QuickPickItemKind { return QuickPickItemKind.Separator; }
get label(): string {
switch (this.refType) {
case RefType.Head:
return l10n.t('branches');
case RefType.RemoteHead:
return l10n.t('remote branches');
case RefType.Tag:
return l10n.t('tags');
default:
return '';
}
}
constructor(private readonly refType: RefType) { }
}
class RefItem implements QuickPickItem {
get label(): string {
switch (this.ref.type) {
case RefType.Head:
return `$(git-branch) ${this.ref.name ?? this.shortCommit}`;
case RefType.RemoteHead:
return `$(cloud) ${this.ref.name ?? this.shortCommit}`;
case RefType.Tag:
return `$(tag) ${this.ref.name ?? this.shortCommit}`;
default:
return '';
}
}
get description(): string {
switch (this.ref.type) {
case RefType.Head:
return this.shortCommit;
case RefType.RemoteHead:
return l10n.t('Remote branch at {0}', this.shortCommit);
case RefType.Tag:
return l10n.t('Tag at {0}', this.shortCommit);
default:
return '';
}
}
get refName(): string | undefined { return this.ref.name; }
get refRemote(): string | undefined { return this.ref.remote; }
get shortCommit(): string { return (this.ref.commit || '').substr(0, 8); }
private _buttons?: QuickInputButton[];
get buttons(): QuickInputButton[] | undefined { return this._buttons; }
set buttons(newButtons: QuickInputButton[] | undefined) { this._buttons = newButtons; }
constructor(protected readonly ref: Ref) { }
}
class CheckoutItem extends RefItem {
async run(repository: Repository, opts?: { detached?: boolean }): Promise<void> {
if (!this.ref.name) {
return;
}
const config = workspace.getConfiguration('git', Uri.file(repository.root));
const pullBeforeCheckout = config.get<boolean>('pullBeforeCheckout', false) === true;
const treeish = opts?.detached ? this.ref.commit ?? this.ref.name : this.ref.name;
await repository.checkout(treeish, { ...opts, pullBeforeCheckout });
}
}
class CheckoutProtectedItem extends CheckoutItem {
override get label(): string {
return `$(lock) ${this.ref.name ?? this.shortCommit}`;
}
}
class CheckoutRemoteHeadItem extends RefItem {
async run(repository: Repository, opts?: { detached?: boolean }): Promise<void> {
if (!this.ref.name) {
return;
}
if (opts?.detached) {
await repository.checkout(this.ref.commit ?? this.ref.name, opts);
return;
}
const branches = await repository.findTrackingBranches(this.ref.name);
if (branches.length > 0) {
await repository.checkout(branches[0].name!, opts);
} else {
await repository.checkoutTracking(this.ref.name, opts);
}
}
}
class CheckoutTagItem extends RefItem {
async run(repository: Repository, opts?: { detached?: boolean }): Promise<void> {
if (!this.ref.name) {
return;
}
await repository.checkout(this.ref.name, opts);
}
}
class BranchDeleteItem extends RefItem {
async run(repository: Repository, force?: boolean): Promise<void> {
if (this.ref.name) {
await repository.deleteBranch(this.ref.name, force);
}
}
}
class TagDeleteItem extends RefItem {
async run(repository: Repository): Promise<void> {
if (this.ref.name) {
await repository.deleteTag(this.ref.name);
}
}
}
class RemoteTagDeleteItem extends RefItem {
override get description(): string {
return l10n.t('Remote tag at {0}', this.shortCommit);
}
async run(repository: Repository, remote: string): Promise<void> {
if (this.ref.name) {
await repository.deleteRemoteTag(remote, this.ref.name);
}
}
}
class MergeItem extends RefItem {
async run(repository: Repository): Promise<void> {
if (this.ref.name || this.ref.commit) {
await repository.merge(this.ref.name ?? this.ref.commit!);
}
}
}
class RebaseItem extends RefItem {
async run(repository: Repository): Promise<void> {
if (this.ref?.name) {
await repository.rebase(this.ref.name);
}
}
}
class RebaseUpstreamItem extends RebaseItem {
override get description(): string {
return '(upstream)';
}
}
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) { }
}
class StashItem implements QuickPickItem {
get label(): string { return `#${this.stash.index}: ${this.stash.description}`; }
get description(): string | undefined { return this.stash.branchName; }
constructor(readonly stash: Stash) { }
}
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<QuickPickItem[]> {
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 refProcessors = checkoutTypes.map(type => getCheckoutRefProcessor(repository, type))
.filter(p => !!p) as RefProcessor[];
const buttons = await getRemoteRefItemButtons(repository);
const itemsProcessor = new CheckoutItemsProcessor(refProcessors, repository, buttons, detached);
return itemsProcessor.processRefs(refs);
}
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 RefProcessor {
protected readonly refs: Ref[] = [];
get items(): QuickPickItem[] {
const items = this.refs.map(r => new this.ctor(r));
return items.length === 0 ? items : [new RefItemSeparator(this.type), ...items];
}
constructor(protected readonly type: RefType, protected readonly ctor: { new(ref: Ref): QuickPickItem } = RefItem) { }
processRef(ref: Ref): boolean {
if (!ref.name && !ref.commit) {
return false;
}
if (ref.type !== this.type) {
return false;
}
this.refs.push(ref);
return true;
}
}
class RefItemsProcessor {
constructor(protected readonly processors: RefProcessor[]) { }
processRefs(refs: Ref[]): QuickPickItem[] {
for (const ref of refs) {
for (const processor of this.processors) {
if (processor.processRef(ref)) {
break;
}
}
}
const result: QuickPickItem[] = [];
for (const processor of this.processors) {
result.push(...processor.items);
}
return result;
}
}
class RebaseItemsProcessors extends RefItemsProcessor {
private upstreamName: string | undefined;
constructor(private readonly repository: Repository) {
super([
new RefProcessor(RefType.Head, RebaseItem),
new RefProcessor(RefType.RemoteHead, RebaseItem)
]);
if (this.repository.HEAD?.upstream) {
this.upstreamName = `${this.repository.HEAD?.upstream.remote}/${this.repository.HEAD?.upstream.name}`;
}
}
override processRefs(refs: Ref[]): QuickPickItem[] {
const result: QuickPickItem[] = [];
for (const ref of refs) {
if (ref.name === this.repository.HEAD?.name) {
continue;
}
if (ref.name === this.upstreamName) {
result.push(new RebaseUpstreamItem(ref));
continue;
}
for (const processor of this.processors) {
if (processor.processRef(ref)) {
break;
}
}
}
for (const processor of this.processors) {
result.push(...processor.items);
}
return result;
}
}
class CheckoutRefProcessor extends RefProcessor {
override get items(): QuickPickItem[] {
const items = this.refs.map(ref => {
return this.repository.isBranchProtected(ref) ?
new CheckoutProtectedItem(ref) :
new CheckoutItem(ref);
});
return items.length === 0 ? items : [new RefItemSeparator(this.type), ...items];
}
constructor(private readonly repository: Repository) {
super(RefType.Head);
}
}
class CheckoutItemsProcessor extends RefItemsProcessor {
private defaultButtons: RemoteSourceActionButton[] | undefined;
constructor(
processors: RefProcessor[],
private readonly repository: Repository,
private readonly buttons: Map<string, RemoteSourceActionButton[]>,
private readonly detached = false) {
super(processors);
// Default button(s)
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) {
this.defaultButtons = buttons.get(remoteUrl);
}
}
override processRefs(refs: Ref[]): QuickPickItem[] {
for (const ref of refs) {
if (!this.detached && ref.name === 'origin/HEAD') {
continue;
}
for (const processor of this.processors) {
if (processor.processRef(ref)) {
break;
}
}
}
const result: QuickPickItem[] = [];
for (const processor of this.processors) {
for (const item of processor.items) {
if (!(item instanceof RefItem)) {
result.push(item);
continue;
}
// Button(s)
if (item.refRemote) {
const matchingRemote = this.repository.remotes.find((remote) => remote.name === item.refRemote);
const buttons = [];
if (matchingRemote?.pushUrl) {
buttons.push(...this.buttons.get(matchingRemote.pushUrl) ?? []);
}
if (matchingRemote?.fetchUrl && matchingRemote.fetchUrl !== matchingRemote.pushUrl) {
buttons.push(...this.buttons.get(matchingRemote.fetchUrl) ?? []);
}
if (buttons.length) {
item.buttons = buttons;
}
} else {
item.buttons = this.defaultButtons;
}
result.push(item);
}
}
return result;
}
}
function getCheckoutRefProcessor(repository: Repository, type: string): RefProcessor | undefined {
switch (type) {
case 'local':
return new CheckoutRefProcessor(repository);
case 'remote':
return new RefProcessor(RefType.RemoteHead, CheckoutRemoteHeadItem);
case 'tags':
return new RefProcessor(RefType.Tag, CheckoutTagItem);
default:
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, '-');
}
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.refresh();
}
@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, diffBetween] = await Promise.all([
repo.getCommit('HEAD'),
isRebasing ? repo.getCommit('REBASE_HEAD') : repo.getCommit('MERGE_HEAD'),
await repo.diffBetween(isRebasing ? 'REBASE_HEAD' : 'MERGE_HEAD', 'HEAD')
]);
const diffFile = diffBetween?.find(diff => diff.uri.fsPath === uri.fsPath);
// 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);
if (diffFile) {
incoming.uri = toGitUri(diffFile.originalUri, rebaseOrMergeHead.hash);
} else {
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;