-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathcommands.ts
1043 lines (974 loc) · 36.3 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
//===----------------------------------------------------------------------===//
//
// This source file is part of the VSCode Swift open source project
//
// Copyright (c) 2021-2023 the VSCode Swift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of VSCode Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import * as vscode from "vscode";
import * as fs from "fs/promises";
import * as path from "path";
import configuration from "./configuration";
import { FolderEvent, WorkspaceContext } from "./WorkspaceContext";
import { createSwiftTask, SwiftTaskProvider } from "./SwiftTaskProvider";
import { FolderContext } from "./FolderContext";
import { PackageNode } from "./ui/PackageDependencyProvider";
import { withQuickPick } from "./ui/QuickPick";
import { withDelayedProgress } from "./ui/withDelayedProgress";
import { execSwift, getErrorDescription } from "./utilities/utilities";
import { Version } from "./utilities/version";
import { DarwinCompatibleTarget, SwiftToolchain } from "./toolchain/toolchain";
import { debugSnippet, runSnippet } from "./SwiftSnippets";
import { debugLaunchConfig, getLaunchConfiguration } from "./debugger/launch";
import { execFile } from "./utilities/utilities";
import { SwiftExecOperation, TaskOperation } from "./TaskQueue";
import { SwiftProjectTemplate } from "./toolchain/toolchain";
/**
* References:
*
* - Contributing commands:
* https://code.visualstudio.com/api/references/contribution-points#contributes.commands
* - Implementing commands:
* https://code.visualstudio.com/api/extension-guides/command
*/
/**
* Executes a {@link vscode.Task task} to resolve this package's dependencies.
*/
export async function resolveDependencies(ctx: WorkspaceContext) {
const current = ctx.currentFolder;
if (!current) {
return;
}
await resolveFolderDependencies(current);
}
/**
* Run `swift package resolve` inside a folder
* @param folderContext folder to run resolve for
*/
export async function resolveFolderDependencies(
folderContext: FolderContext,
checkAlreadyRunning?: boolean
) {
const task = createSwiftTask(
["package", "resolve"],
SwiftTaskProvider.resolvePackageName,
{
cwd: folderContext.folder,
scope: folderContext.workspaceFolder,
prefix: folderContext.name,
presentationOptions: { reveal: vscode.TaskRevealKind.Silent },
},
folderContext.workspaceContext.toolchain
);
await executeTaskWithUI(
task,
"Resolving Dependencies",
folderContext,
false,
checkAlreadyRunning
).then(result => {
updateAfterError(result, folderContext);
});
}
/**
* Executes a {@link vscode.Task task} to update this package's dependencies.
*/
export async function updateDependencies(ctx: WorkspaceContext) {
const current = ctx.currentFolder;
if (!current) {
return;
}
await updateFolderDependencies(current);
}
/**
* Prompts the user to input project details and then executes `swift package init`
* to create the project.
*/
export async function createNewProject(ctx: WorkspaceContext): Promise<void> {
// The context key `swift.createNewProjectAvailable` only works if the extension has been
// activated. As such, we also have to allow this command to run when no workspace is
// active. Show an error to the user if the command is unavailable.
if (!ctx.toolchain.swiftVersion.isGreaterThanOrEqual(new Version(5, 8, 0))) {
vscode.window.showErrorMessage(
"Creating a new swift project is only available starting in swift version 5.8.0."
);
return;
}
// Prompt the user for the type of project they would like to create
const availableProjectTemplates = await ctx.toolchain.getProjectTemplates();
const selectedProjectTemplate = await vscode.window.showQuickPick<
vscode.QuickPickItem & { type: SwiftProjectTemplate }
>(
availableProjectTemplates.map(type => ({
label: type.name,
description: type.id,
detail: type.description,
type,
})),
{
placeHolder: "Select a swift project template",
}
);
if (!selectedProjectTemplate) {
return undefined;
}
const projectType = selectedProjectTemplate.type.id;
// Prompt the user for a location in which to create the new project
const selectedFolder = await vscode.window.showOpenDialog({
title: "Select a folder to create a new swift project in",
openLabel: "Select folder",
canSelectFiles: false,
canSelectFolders: true,
canSelectMany: false,
});
if (!selectedFolder || selectedFolder.length === 0) {
return undefined;
}
// Prompt the user for the project name
const existingNames = await fs.readdir(selectedFolder[0].fsPath, { encoding: "utf-8" });
let initialValue = `swift-${projectType}`;
for (let i = 1; ; i++) {
if (!existingNames.includes(initialValue)) {
break;
}
initialValue = `swift-${projectType}-${i}`;
}
const projectName = await vscode.window.showInputBox({
value: initialValue,
prompt: "Enter a name for your new swift project",
validateInput(value) {
// Swift Package Manager doesn't seem to do any validation on the name.
// So, we'll just check for obvious failure cases involving mkdir.
if (value.trim() === "") {
return "Project name cannot be empty.";
} else if (value.includes("/") || value.includes("\\")) {
return "Project name cannot contain '/' or '\\' characters.";
} else if (value === "." || value === "..") {
return "Project name cannot be '.' or '..'.";
}
// Ensure there are no name collisions
if (existingNames.includes(value)) {
return "A file/folder with this name already exists.";
}
return undefined;
},
});
if (projectName === undefined) {
return undefined;
}
// Create the folder that will store the new project
const projectUri = vscode.Uri.joinPath(selectedFolder[0], projectName);
await fs.mkdir(projectUri.fsPath);
// Use swift package manager to initialize the swift project
await withDelayedProgress(
{
location: vscode.ProgressLocation.Notification,
title: `Creating swift project ${projectName}`,
},
async () => {
await execSwift(
["package", "init", "--type", projectType, "--name", projectName],
ctx.toolchain,
{
cwd: projectUri.fsPath,
}
);
},
1000
);
// Prompt the user whether or not they want to open the newly created project
const isWorkspaceOpened = !!vscode.workspace.workspaceFolders;
const openAfterCreate = configuration.openAfterCreateNewProject;
let action: "open" | "openNewWindow" | "addToWorkspace" | undefined;
if (openAfterCreate === "always") {
action = "open";
} else if (openAfterCreate === "alwaysNewWindow") {
action = "openNewWindow";
} else if (openAfterCreate === "whenNoFolderOpen" && !isWorkspaceOpened) {
action = "open";
}
if (action === undefined) {
let message = `Would you like to open ${projectName}?`;
const open = "Open";
const openNewWindow = "Open in New Window";
const choices = [open, openNewWindow];
const addToWorkspace = "Add to Workspace";
if (isWorkspaceOpened) {
message = `Would you like to open ${projectName}, or add it to the current workspace?`;
choices.push(addToWorkspace);
}
const result = await vscode.window.showInformationMessage(
message,
{ modal: true, detail: "The default action can be configured in settings" },
...choices
);
if (result === open) {
action = "open";
} else if (result === openNewWindow) {
action = "openNewWindow";
} else if (result === addToWorkspace) {
action = "addToWorkspace";
}
}
if (action === "open") {
await vscode.commands.executeCommand("vscode.openFolder", projectUri, {
forceReuseWindow: true,
});
} else if (action === "openNewWindow") {
await vscode.commands.executeCommand("vscode.openFolder", projectUri, {
forceNewWindow: true,
});
} else if (action === "addToWorkspace") {
const index = vscode.workspace.workspaceFolders?.length ?? 0;
await vscode.workspace.updateWorkspaceFolders(index, 0, { uri: projectUri });
}
}
/**
* Prompts the user to input project details and then executes `swift package init`
* to create the project.
*/
export async function browsePackageIndex(ctx: WorkspaceContext): Promise<void> {
// The context key `swift.addPackageRefactoringAvailable` only works if the extension has been
// activated. As such, we also have to allow this command to run when no workspace is
// active. Show an error to the user if the command is unavailable.
if (!ctx.toolchain.swiftVersion.isGreaterThanOrEqual(new Version(6, 0, 0))) {
vscode.window.showErrorMessage(
"Browsing the package index is only available starting in swift version 6.0.0."
);
return;
}
const panel = vscode.window.createWebviewPanel(
"swiftPackageIndex",
"Swift Package Index",
vscode.ViewColumn.One,
{
retainContextWhenHidden: true,
enableScripts: true,
}
);
panel.webview.onDidReceiveMessage(
message => {
switch (message.command) {
case "addSwiftPackage":
addPackageDependency(ctx, message.url, message.version);
return;
default:
// Log message
vscode.window.showErrorMessage(`An error occurred when adding packages`);
return;
}
},
undefined,
ctx.subscriptions
);
panel.webview.html = `<html>
<iframe name="vscode_iframe" id="mainframe" src="http://localhost:8080/" style="position:fixed; top:0; left:0; bottom:0; right:0; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;">
Your browser doesn't support iframes
</iframe>
<script>
const vscode = acquireVsCodeApi();
window.addEventListener('message', e => {
action = e.data.action;
if (action === "addPackage") {
url = e.data.url
version = e.data.version
if (url && version) {
vscode.postMessage({
command: 'addSwiftPackage',
url: url,
version: version
})
} else {
console.log("Unknown message: " + e)
}
} else {
console.log("Unknown message: " + e)
}
}, false);
</script>
</html>`;
}
export async function addPackageDependency(
ctx: WorkspaceContext,
url?: string,
version?: string
): Promise<void> {
// The context key `swift.addPackageRefactoringAvailable` only works if the extension has been
// activated. As such, we also have to allow this command to run when no workspace is
// active. Show an error to the user if the command is unavailable.
if (!ctx.toolchain.swiftVersion.isGreaterThanOrEqual(new Version(6, 0, 0))) {
vscode.window.showErrorMessage(
"Adding a new swift package dependency is only available starting in swift version 6.0.0."
);
return;
}
if (!ctx.currentFolder) {
vscode.window.showErrorMessage("An error occurred when adding packages");
return;
}
const folderContext = ctx.currentFolder;
if (!url) {
url = await vscode.window.showInputBox({
prompt: "Enter the URL for the package",
validateInput(value) {
if (value.trim() === "") {
return "URL cannot be empty.";
}
return undefined;
},
});
if (!url) {
return;
}
}
if (!version) {
version = await vscode.window.showInputBox({
prompt: "Enter the version for the package",
validateInput(value) {
if (value.trim() === "") {
return "Version cannot be empty.";
}
return undefined;
},
});
if (!version) {
return;
}
}
const resolveTask = createSwiftTask(
["package", "add-dependency", url, "--branch", version],
"Adding Package Dependency",
{
cwd: folderContext.folder,
scope: folderContext.workspaceFolder,
prefix: folderContext.name,
presentationOptions: { reveal: vscode.TaskRevealKind.Silent },
},
folderContext.workspaceContext.toolchain
);
await executeTaskWithUI(resolveTask, "Adding Package Dependency", folderContext);
await openPackage(ctx);
}
/**
* Run `swift package update` inside a folder
* @param folderContext folder to run update inside
* @returns
*/
export async function updateFolderDependencies(folderContext: FolderContext) {
const task = createSwiftTask(
["package", "update"],
SwiftTaskProvider.updatePackageName,
{
cwd: folderContext.folder,
scope: folderContext.workspaceFolder,
prefix: folderContext.name,
presentationOptions: { reveal: vscode.TaskRevealKind.Silent },
},
folderContext.workspaceContext.toolchain
);
await executeTaskWithUI(task, "Updating Dependencies", folderContext).then(result => {
updateAfterError(result, folderContext);
});
}
/**
* Executes a {@link vscode.Task task} to run swift target.
*/
export async function runBuild(ctx: WorkspaceContext) {
await debugBuildWithOptions(ctx, { noDebug: true });
}
/**
* Executes a {@link vscode.Task task} to debug swift target.
*/
export async function debugBuild(ctx: WorkspaceContext) {
await debugBuildWithOptions(ctx, {});
}
/**
* Executes a {@link vscode.Task task} to debug swift target.
*/
async function debugBuildWithOptions(ctx: WorkspaceContext, options: vscode.DebugSessionOptions) {
const current = ctx.currentFolder;
if (!current) {
return;
}
const file = vscode.window.activeTextEditor?.document.fileName;
if (!file) {
return;
}
const target = current.swiftPackage.getTarget(file);
if (!target || target.type !== "executable") {
return;
}
const launchConfig = getLaunchConfiguration(target.name, current);
if (launchConfig) {
return debugLaunchConfig(current.workspaceFolder, launchConfig, options);
}
}
/**
* Executes a {@link vscode.Task task} to delete all build artifacts.
*/
export async function cleanBuild(ctx: WorkspaceContext) {
const current = ctx.currentFolder;
if (!current) {
return;
}
await folderCleanBuild(current);
}
/**
* Run `swift package clean` inside a folder
* @param folderContext folder to run update inside
*/
export async function folderCleanBuild(folderContext: FolderContext) {
const task = createSwiftTask(
["package", "clean"],
SwiftTaskProvider.cleanBuildName,
{
cwd: folderContext.folder,
scope: folderContext.workspaceFolder,
prefix: folderContext.name,
presentationOptions: { reveal: vscode.TaskRevealKind.Silent },
group: vscode.TaskGroup.Clean,
},
folderContext.workspaceContext.toolchain
);
await executeTaskWithUI(task, "Clean Build", folderContext);
}
/**
* Executes a {@link vscode.Task task} to reset the complete cache/build directory.
*/
export async function resetPackage(ctx: WorkspaceContext) {
const current = ctx.currentFolder;
if (!current) {
return;
}
await folderResetPackage(current);
}
/**
* Run `swift package reset` inside a folder
* @param folderContext folder to run update inside
*/
export async function folderResetPackage(folderContext: FolderContext) {
const task = createSwiftTask(
["package", "reset"],
"Reset Package Dependencies",
{
cwd: folderContext.folder,
scope: folderContext.workspaceFolder,
prefix: folderContext.name,
presentationOptions: { reveal: vscode.TaskRevealKind.Silent },
group: vscode.TaskGroup.Clean,
},
folderContext.workspaceContext.toolchain
);
await executeTaskWithUI(task, "Reset Package", folderContext).then(async success => {
if (!success) {
return;
}
const resolveTask = createSwiftTask(
["package", "resolve"],
SwiftTaskProvider.resolvePackageName,
{
cwd: folderContext.folder,
scope: folderContext.workspaceFolder,
prefix: folderContext.name,
presentationOptions: { reveal: vscode.TaskRevealKind.Silent },
},
folderContext.workspaceContext.toolchain
);
await executeTaskWithUI(resolveTask, "Resolving Dependencies", folderContext);
});
}
/**
* Run single Swift file through Swift REPL
*/
async function runSwiftScript(ctx: WorkspaceContext) {
const document = vscode.window.activeTextEditor?.document;
if (!document) {
return;
}
// Swift scripts require new swift driver to work on Windows. Swift driver is available
// from v5.7 of Windows Swift
if (
process.platform === "win32" &&
ctx.toolchain.swiftVersion.isLessThan(new Version(5, 7, 0))
) {
vscode.window.showErrorMessage(
"Run Swift Script is unavailable with the legacy driver on Windows."
);
return;
}
let filename = document.fileName;
let isTempFile = false;
if (document.isUntitled) {
// if document hasn't been saved, save it to a temporary file
isTempFile = true;
filename = ctx.tempFolder.filename(document.fileName, "swift");
const text = document.getText();
await fs.writeFile(filename, text);
} else {
// otherwise save document
await document.save();
}
const runTask = createSwiftTask(
[filename],
`Run ${filename}`,
{
scope: vscode.TaskScope.Global,
cwd: vscode.Uri.file(path.dirname(filename)),
presentationOptions: { reveal: vscode.TaskRevealKind.Always, clear: true },
},
ctx.toolchain
);
await ctx.tasks.executeTaskAndWait(runTask);
// delete file after running swift
if (isTempFile) {
await fs.rm(filename);
}
}
async function runPluginTask() {
vscode.commands.executeCommand("workbench.action.tasks.runTask", {
type: "swift-plugin",
});
}
/**
* Use local version of package dependency
*
* equivalent of `swift package edit --path <localpath> identifier
* @param identifier Identifier for dependency
* @param ctx workspace context
*/
async function useLocalDependency(identifier: string, ctx: WorkspaceContext) {
const currentFolder = ctx.currentFolder;
if (!currentFolder) {
return;
}
vscode.window
.showOpenDialog({
canSelectFiles: false,
canSelectFolders: true,
canSelectMany: false,
defaultUri: currentFolder.folder,
openLabel: "Select",
title: "Select folder",
})
.then(async value => {
if (!value) {
return;
}
const folder = value[0];
const task = createSwiftTask(
["package", "edit", "--path", folder.fsPath, identifier],
"Edit Package Dependency",
{
scope: currentFolder.workspaceFolder,
cwd: currentFolder.folder,
prefix: currentFolder.name,
},
ctx.toolchain
);
await executeTaskWithUI(
task,
`Use local version of ${identifier}`,
currentFolder,
true
).then(result => {
if (result) {
ctx.fireEvent(currentFolder, FolderEvent.resolvedUpdated);
}
});
});
}
/**
* Setup package dependency to be edited
* @param identifier Identifier of dependency we want to edit
* @param ctx workspace context
*/
async function editDependency(identifier: string, ctx: WorkspaceContext) {
const currentFolder = ctx.currentFolder;
if (!currentFolder) {
return;
}
const task = createSwiftTask(
["package", "edit", identifier],
"Edit Package Dependency",
{
scope: currentFolder.workspaceFolder,
cwd: currentFolder.folder,
prefix: currentFolder.name,
},
ctx.toolchain
);
await executeTaskWithUI(task, `edit locally ${identifier}`, currentFolder, true).then(
result => {
if (result) {
ctx.fireEvent(currentFolder, FolderEvent.resolvedUpdated);
// add folder to workspace
const index = vscode.workspace.workspaceFolders?.length ?? 0;
vscode.workspace.updateWorkspaceFolders(index, 0, {
uri: vscode.Uri.file(currentFolder.editedPackageFolder(identifier)),
name: identifier,
});
}
}
);
}
/**
* Stop local editing of package dependency
* @param identifier Identifier of dependency
* @param ctx workspace context
*/
async function uneditDependency(identifier: string, ctx: WorkspaceContext) {
const currentFolder = ctx.currentFolder;
if (!currentFolder) {
return;
}
ctx.outputChannel.log(`unedit dependency ${identifier}`, currentFolder.name);
const status = `Reverting edited dependency ${identifier} (${currentFolder.name})`;
ctx.statusItem.showStatusWhileRunning(status, async () => {
await uneditFolderDependency(currentFolder, identifier, ctx);
});
}
async function uneditFolderDependency(
folder: FolderContext,
identifier: string,
ctx: WorkspaceContext,
args: string[] = []
) {
try {
const uneditOperation = new SwiftExecOperation(
["package", "unedit", ...args, identifier],
folder,
`Finish editing ${identifier}`,
{ showStatusItem: true, checkAlreadyRunning: false, log: "Unedit" },
() => {
// do nothing. Just want to run the process on the Task queue to ensure it
// doesn't clash with another swifr process
}
);
await folder.taskQueue.queueOperation(uneditOperation);
ctx.fireEvent(folder, FolderEvent.resolvedUpdated);
// find workspace folder, and check folder still exists
const folderIndex = vscode.workspace.workspaceFolders?.findIndex(
item => item.name === identifier
);
if (folderIndex) {
try {
// check folder exists. if error thrown remove folder
await fs.stat(vscode.workspace.workspaceFolders![folderIndex].uri.fsPath);
} catch {
vscode.workspace.updateWorkspaceFolders(folderIndex, 1);
}
}
} catch (error) {
const execError = error as { stderr: string };
// if error contains "has uncommited changes" then ask if user wants to force the unedit
if (execError.stderr.match(/has uncommited changes/)) {
vscode.window
.showWarningMessage(
`${identifier} has uncommitted changes. Are you sure you want to continue?`,
"Yes",
"No"
)
.then(async result => {
if (result === "No") {
ctx.outputChannel.log(execError.stderr, folder.name);
return;
}
await uneditFolderDependency(folder, identifier, ctx, ["--force"]);
});
} else {
ctx.outputChannel.log(execError.stderr, folder.name);
vscode.window.showErrorMessage(`${execError.stderr}`);
}
}
}
/**
* Open local package in workspace
* @param packageNode PackageNode attached to dependency tree item
*/
async function openInWorkspace(packageNode: PackageNode) {
const index = vscode.workspace.workspaceFolders?.length ?? 0;
vscode.workspace.updateWorkspaceFolders(index, 0, {
uri: vscode.Uri.file(packageNode.path),
name: packageNode.name,
});
}
/**
* Open Package.swift for in focus project
* @param workspaceContext Workspace context, required to get current project
*/
async function openPackage(workspaceContext: WorkspaceContext) {
if (workspaceContext.currentFolder) {
const packagePath = vscode.Uri.joinPath(
workspaceContext.currentFolder.folder,
"Package.swift"
);
const document = await vscode.workspace.openTextDocument(packagePath);
vscode.window.showTextDocument(document);
}
}
function insertFunctionComment(workspaceContext: WorkspaceContext) {
const activeEditor = vscode.window.activeTextEditor;
if (!activeEditor) {
return;
}
const line = activeEditor.selection.active.line;
workspaceContext.commentCompletionProvider.insert(activeEditor, line);
}
/** Restart the SourceKit-LSP server */
function restartLSPServer(workspaceContext: WorkspaceContext) {
workspaceContext.languageClientManager.restart();
}
/** Execute task and show UI while running */
async function executeTaskWithUI(
task: vscode.Task,
description: string,
folderContext: FolderContext,
showErrors = false,
checkAlreadyRunning?: boolean
): Promise<boolean> {
try {
const exitCode = await folderContext.taskQueue.queueOperation(
new TaskOperation(task, {
showStatusItem: true,
checkAlreadyRunning: checkAlreadyRunning ?? false,
log: description,
})
);
if (exitCode === 0) {
return true;
} else {
if (showErrors) {
vscode.window.showErrorMessage(`${description} failed`);
}
return false;
}
} catch (error) {
if (showErrors) {
vscode.window.showErrorMessage(`${description} failed: ${error}`);
}
return false;
}
}
/**
*
* @param packageNode PackageNode attached to dependency tree item
*/
function openInExternalEditor(packageNode: PackageNode) {
try {
const uri = vscode.Uri.parse(packageNode.location, true);
vscode.env.openExternal(uri);
} catch {
// ignore error
}
}
/**
* Switches the target SDK to the platform selected in a QuickPick UI.
*/
async function switchPlatform() {
await withQuickPick(
"Select a new target",
[
{ value: undefined, label: "macOS" },
{ value: DarwinCompatibleTarget.iOS, label: "iOS" },
{ value: DarwinCompatibleTarget.tvOS, label: "tvOS" },
{ value: DarwinCompatibleTarget.watchOS, label: "watchOS" },
{ value: DarwinCompatibleTarget.visionOS, label: "visionOS" },
],
async picked => {
try {
const sdkForTarget = picked.value
? await SwiftToolchain.getSDKForTarget(picked.value)
: "";
if (sdkForTarget !== undefined) {
if (sdkForTarget !== "") {
configuration.sdk = sdkForTarget;
vscode.window.showWarningMessage(
`Selecting the ${picked.label} SDK will provide code editing support, but compiling with this SDK will have undefined results.`
);
} else {
configuration.sdk = undefined;
}
} else {
vscode.window.showErrorMessage("Unable to obtain requested SDK path");
}
} catch {
vscode.window.showErrorMessage("Unable to obtain requested SDK path");
}
}
);
}
/**
* Choose DEVELOPER_DIR
* @param workspaceContext
*/
async function selectXcodeDeveloperDir() {
const defaultXcode = await SwiftToolchain.getXcodeDeveloperDir();
const selectedXcode = configuration.swiftEnvironmentVariables.DEVELOPER_DIR;
const xcodes = await SwiftToolchain.getXcodeInstalls();
await withQuickPick(
selectedXcode ?? defaultXcode,
xcodes.map(xcode => {
const developerDir = `${xcode}/Contents/Developer`;
return {
label: developerDir === defaultXcode ? `${xcode} (default)` : xcode,
folder: developerDir === defaultXcode ? undefined : developerDir,
};
}),
async selected => {
let swiftEnv = configuration.swiftEnvironmentVariables;
const previousDeveloperDir = swiftEnv.DEVELOPER_DIR ?? defaultXcode;
if (selected.folder) {
swiftEnv.DEVELOPER_DIR = selected.folder;
} else if (swiftEnv.DEVELOPER_DIR) {
// if DEVELOPER_DIR was set and the new folder is the default then
// delete variable
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { DEVELOPER_DIR, ...rest } = swiftEnv;
swiftEnv = rest;
}
configuration.swiftEnvironmentVariables = swiftEnv;
// if SDK is inside previous DEVELOPER_DIR then move to new DEVELOPER_DIR
if (
configuration.sdk.length > 0 &&
configuration.sdk.startsWith(previousDeveloperDir)
) {
configuration.sdk = configuration.sdk.replace(
previousDeveloperDir,
selected.folder ?? defaultXcode
);
}
vscode.window
.showInformationMessage(
"Changing the Xcode Developer Directory requires the project be reloaded.",
"Ok"
)
.then(() => {
vscode.commands.executeCommand("workbench.action.reloadWindow");
});
}
);
}
export async function showTestCoverageReport(workspaceContext: WorkspaceContext) {
// show test coverage report
if (workspaceContext.currentFolder) {
workspaceContext.testCoverageDocumentProvider.show(workspaceContext.currentFolder);
}
}
function toggleTestCoverageDisplay(workspaceContext: WorkspaceContext) {
workspaceContext.toggleTestCoverageDisplay();
}
async function attachDebugger(workspaceContext: WorkspaceContext) {
// use LLDB to get list of processes
const lldb = workspaceContext.toolchain.getLLDB();
try {
const { stdout } = await execFile(lldb, [
"--batch",
"--no-lldbinit",
"--one-line",
"platform process list --show-args --all-users",
]);
const entries = stdout.split("\n");
const processPickItems = entries.flatMap(line => {
const match = /^(\d+)\s+\d+\s+\S+\s+\S+\s+(.+)$/.exec(line);
if (match) {
return [{ pid: parseInt(match[1]), label: `${match[1]}: ${match[2]}` }];
} else {
return [];
}
});
await withQuickPick("Select Process", processPickItems, async selected => {
const debugConfig: vscode.DebugConfiguration = {
type: "swift-lldb",
request: "attach",
name: "Attach",
pid: selected.pid,
};
await vscode.debug.startDebugging(undefined, debugConfig);
});
} catch (error) {
vscode.window.showErrorMessage(`Failed to run LLDB: ${getErrorDescription(error)}`);
}
}
function updateAfterError(result: boolean, folderContext: FolderContext) {
const triggerResolvedUpdatedEvent = folderContext.hasResolveErrors;
// set has resolve errors flag
folderContext.hasResolveErrors = !result;
// if previous folder state was with resolve errors, and now it is without then
// send Package.resolved updated event to trigger display of package dependencies
// view
if (triggerResolvedUpdatedEvent && !folderContext.hasResolveErrors) {
folderContext.fireEvent(FolderEvent.resolvedUpdated);
}
}
/**
* Registers this extension's commands in the given {@link vscode.ExtensionContext context}.
*/
export function register(ctx: WorkspaceContext) {
ctx.subscriptions.push(
vscode.commands.registerCommand("swift.createNewProject", () => createNewProject(ctx)),
vscode.commands.registerCommand("swift.browsePackageIndex", () => browsePackageIndex(ctx)),
vscode.commands.registerCommand("swift.addPackageDependency", (url, version) =>
addPackageDependency(ctx, url, version)
),
vscode.commands.registerCommand("swift.resolveDependencies", () =>
resolveDependencies(ctx)
),
vscode.commands.registerCommand("swift.updateDependencies", () => updateDependencies(ctx)),
vscode.commands.registerCommand("swift.run", () => runBuild(ctx)),
vscode.commands.registerCommand("swift.debug", () => debugBuild(ctx)),
vscode.commands.registerCommand("swift.cleanBuild", () => cleanBuild(ctx)),
// Note: This is only available on macOS (gated in `package.json`) because its the only OS that has the iOS SDK available.
vscode.commands.registerCommand("swift.switchPlatform", () => switchPlatform()),
vscode.commands.registerCommand("swift.resetPackage", () => resetPackage(ctx)),
vscode.commands.registerCommand("swift.runScript", () => runSwiftScript(ctx)),
vscode.commands.registerCommand("swift.openPackage", () => openPackage(ctx)),
vscode.commands.registerCommand("swift.runSnippet", () => runSnippet(ctx)),