Skip to content

Add command to generate launch configurations #1577

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,11 @@
}
],
"commands": [
{
"command": "swift.generateLaunchConfigurations",
"title": "Generate Launch Configurations",
"category": "Swift"
},
{
"command": "swift.previewDocumentation",
"title": "Preview Documentation",
Expand Down Expand Up @@ -886,6 +891,10 @@
}
],
"commandPalette": [
{
"command": "swift.generateLaunchConfigurations",
"when": "swift.hasPackage"
},
{
"command": "swift.previewDocumentation",
"when": "swift.supportsDocumentationLivePreview"
Expand Down
4 changes: 2 additions & 2 deletions src/WorkspaceContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ export class WorkspaceContext implements vscode.Disposable {
.then(async selected => {
if (selected === "Update") {
this.folders.forEach(ctx =>
makeDebugConfigurations(ctx, undefined, true)
makeDebugConfigurations(ctx, { yes: true })
);
}
});
Expand All @@ -120,7 +120,7 @@ export class WorkspaceContext implements vscode.Disposable {
.then(selected => {
if (selected === "Update") {
this.folders.forEach(ctx =>
makeDebugConfigurations(ctx, undefined, true)
makeDebugConfigurations(ctx, { yes: true })
);
}
});
Expand Down
4 changes: 4 additions & 0 deletions src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import { TestKind } from "./TestExplorer/TestKind";
import { pickProcess } from "./commands/pickProcess";
import { openDocumentation } from "./commands/openDocumentation";
import restartLSPServer from "./commands/restartLSPServer";
import { generateLaunchConfigurations } from "./commands/generateLaunchConfigurations";

/**
* References:
Expand Down Expand Up @@ -105,6 +106,9 @@ export enum Commands {
*/
export function register(ctx: WorkspaceContext): vscode.Disposable[] {
return [
vscode.commands.registerCommand("swift.generateLaunchConfigurations", () =>
generateLaunchConfigurations(ctx)
),
vscode.commands.registerCommand("swift.newFile", uri => newSwiftFile(uri)),
vscode.commands.registerCommand(Commands.RESOLVE_DEPENDENCIES, () =>
resolveDependencies(ctx)
Expand Down
70 changes: 70 additions & 0 deletions src/commands/generateLaunchConfigurations.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the VS Code Swift open source project
//
// Copyright (c) 2025 the VS Code Swift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of VS Code Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

import { makeDebugConfigurations } from "../debugger/launch";
import { FolderContext } from "../FolderContext";
import { WorkspaceContext } from "../WorkspaceContext";
import * as vscode from "vscode";

export async function generateLaunchConfigurations(ctx: WorkspaceContext): Promise<boolean> {
if (ctx.folders.length === 0) {
return false;
}

if (ctx.folders.length === 1) {
return await makeDebugConfigurations(ctx.folders[0], { force: true, yes: true });
}

const quickPickItems: SelectFolderQuickPick[] = ctx.folders.map(folder => ({
type: "folder",
folder,
label: folder.name,
detail: folder.workspaceFolder.uri.fsPath,
}));
quickPickItems.push({ type: "all", label: "Generate For All Folders" });
const selection = await vscode.window.showQuickPick(quickPickItems, {
matchOnDetail: true,
placeHolder: "Select a folder to generate launch configurations for",
});

if (!selection) {
return false;
}

const foldersToUpdate: FolderContext[] = [];
if (selection.type === "all") {
foldersToUpdate.push(...ctx.folders);
} else {
foldersToUpdate.push(selection.folder);
}

return (
await Promise.all(
foldersToUpdate.map(folder =>
makeDebugConfigurations(folder, { force: true, yes: true })
)
)
).reduceRight((prev, curr) => prev || curr);
}

type SelectFolderQuickPick = AllQuickPickItem | FolderQuickPickItem;

interface AllQuickPickItem extends vscode.QuickPickItem {
type: "all";
}

interface FolderQuickPickItem extends vscode.QuickPickItem {
type: "folder";
folder: FolderContext;
}
16 changes: 13 additions & 3 deletions src/debugger/debugAdapterFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ import { registerLoggingDebugAdapterTracker } from "./logTracker";
import { SwiftToolchain } from "../toolchain/toolchain";
import { SwiftOutputChannel } from "../ui/SwiftOutputChannel";
import { fileExists } from "../utilities/filesystem";
import { getLLDBLibPath } from "./lldb";
import { getErrorDescription } from "../utilities/utilities";
import { CI_DISABLE_ASLR, getLLDBLibPath } from "./lldb";
import { getErrorDescription, swiftRuntimeEnv } from "../utilities/utilities";
import configuration from "../configuration";

/**
Expand Down Expand Up @@ -137,6 +137,13 @@ export class LLDBDebugConfigurationProvider implements vscode.DebugConfiguration
launchConfig.pid = pid;
}

// Merge in the Swift runtime environment variables
const runtimeEnv = swiftRuntimeEnv(true);
if (runtimeEnv) {
const existingEnv = launchConfig.env ?? {};
launchConfig.env = { ...runtimeEnv, existingEnv };
}

// Delegate to the appropriate debug adapter extension
launchConfig.type = DebugAdapter.getLaunchConfigType(toolchain.swiftVersion);
if (launchConfig.type === LaunchConfigType.CODE_LLDB) {
Expand Down Expand Up @@ -164,7 +171,10 @@ export class LLDBDebugConfigurationProvider implements vscode.DebugConfiguration
launchConfig.debugAdapterExecutable = lldbDapPath;
}

return launchConfig;
return {
...launchConfig,
...CI_DISABLE_ASLR,
};
}

private async promptToInstallCodeLLDB(): Promise<boolean> {
Expand Down
160 changes: 74 additions & 86 deletions src/debugger/launch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,94 +14,105 @@

import * as path from "path";
import * as vscode from "vscode";
import { isDeepStrictEqual } from "util";
import { FolderContext } from "../FolderContext";
import { BuildFlags } from "../toolchain/BuildFlags";
import { stringArrayInEnglish, swiftLibraryPathKey, swiftRuntimeEnv } from "../utilities/utilities";
import { stringArrayInEnglish } from "../utilities/utilities";
import { SWIFT_LAUNCH_CONFIG_TYPE } from "./debugAdapter";
import { getFolderAndNameSuffix } from "./buildConfig";
import configuration from "../configuration";
import { CI_DISABLE_ASLR } from "./lldb";

/** Options used to configure {@link makeDebugConfigurations}. */
export interface WriteLaunchConfigurationsOptions {
/** Force the generation of launch configurations regardless of user settings. */
force?: boolean;

/** Automatically answer yes to update dialogs. */
yes?: boolean;
}

/**
* Edit launch.json based on contents of Swift Package.
* Adds launch configurations based on the executables in Package.swift.
*
* @param ctx folder context to create launch configurations for
* @param yes automatically answer yes to dialogs
* @param options the options used to configure behavior of this function
* @returns a boolean indicating whether or not launch configurations were actually updated
*/
export async function makeDebugConfigurations(
ctx: FolderContext,
message?: string,
yes = false
options: WriteLaunchConfigurationsOptions = {}
): Promise<boolean> {
if (!configuration.folder(ctx.workspaceFolder).autoGenerateLaunchConfigurations) {
if (
!options.force &&
!configuration.folder(ctx.workspaceFolder).autoGenerateLaunchConfigurations
) {
return false;
}

const wsLaunchSection = vscode.workspace.getConfiguration("launch", ctx.folder);
const launchConfigs = wsLaunchSection.get<vscode.DebugConfiguration[]>("configurations") || [];
// list of keys that can be updated in config merge
const keysToUpdate = [
"program",
"cwd",
"preLaunchTask",
"type",
"disableASLR",
"initCommands",
`env.${swiftLibraryPathKey()}`,
];
const configUpdates: { index: number; config: vscode.DebugConfiguration }[] = [];

const configs = await createExecutableConfigurations(ctx);
let edited = false;
for (const config of configs) {
const index = launchConfigs.findIndex(c => c.name === config.name);
if (index !== -1) {
// deep clone config and update with keys from calculated config
const newConfig: vscode.DebugConfiguration = JSON.parse(
JSON.stringify(launchConfigs[index])
);
updateConfigWithNewKeys(newConfig, config, keysToUpdate);

// if original config is different from new config
if (JSON.stringify(launchConfigs[index]) !== JSON.stringify(newConfig)) {
configUpdates.push({ index: index, config: newConfig });
}
} else {
launchConfigs.push(config);
edited = true;
// Determine which launch configurations need updating/creating
const configsToCreate: vscode.DebugConfiguration[] = [];
const configsToUpdate: { index: number; config: vscode.DebugConfiguration }[] = [];
for (const generatedConfig of await createExecutableConfigurations(ctx)) {
const index = launchConfigs.findIndex(c => c.name === generatedConfig.name);
if (index === -1) {
configsToCreate.push(generatedConfig);
continue;
}

// deep clone the existing config and update with keys from generated config
const config = structuredClone(launchConfigs[index]);
updateConfigWithNewKeys(config, generatedConfig, [
"program",
"cwd",
"preLaunchTask",
"type",
]);

// Check to see if the config has changed
if (!isDeepStrictEqual(launchConfigs[index], config)) {
configsToUpdate.push({ index, config });
}
}

if (configUpdates.length > 0) {
if (!yes) {
// Create/Update launch configurations if necessary
let needsUpdate = false;
if (configsToCreate.length > 0) {
launchConfigs.push(...configsToCreate);
needsUpdate = true;
}
if (configsToUpdate.length > 0) {
let answer: "Update" | "Cancel" | undefined = options.yes ? "Update" : undefined;
if (!answer) {
const configUpdateNames = stringArrayInEnglish(
configUpdates.map(update => update.config.name)
configsToUpdate.map(update => update.config.name)
);
const warningMessage =
message ??
`The Swift extension would like to update launch configurations '${configUpdateNames}'.`;
const answer = await vscode.window.showWarningMessage(
const warningMessage = `The Swift extension would like to update launch configurations '${configUpdateNames}'.`;
answer = await vscode.window.showWarningMessage(
`${ctx.name}: ${warningMessage} Do you want to update?`,
"Update",
"Cancel"
);
if (answer === "Update") {
yes = true;
}
}
if (yes) {
configUpdates.forEach(update => (launchConfigs[update.index] = update.config));
edited = true;

if (answer === "Update") {
configsToUpdate.forEach(update => (launchConfigs[update.index] = update.config));
needsUpdate = true;
}
}

if (edited) {
await wsLaunchSection.update(
"configurations",
launchConfigs,
vscode.ConfigurationTarget.WorkspaceFolder
);
if (!needsUpdate) {
return false;
}

await wsLaunchSection.update(
"configurations",
launchConfigs,
vscode.ConfigurationTarget.WorkspaceFolder
);
return true;
}

Expand Down Expand Up @@ -142,8 +153,6 @@ async function createExecutableConfigurations(
request: "launch",
args: [],
cwd: folder,
env: swiftRuntimeEnv(true),
...CI_DISABLE_ASLR,
};
return [
{
Expand Down Expand Up @@ -182,9 +191,7 @@ export function createSnippetConfiguration(
program: path.posix.join(buildDirectory, "debug", snippetName),
args: [],
cwd: folder,
env: swiftRuntimeEnv(true),
runType: "snippet",
...CI_DISABLE_ASLR,
};
}

Expand Down Expand Up @@ -218,36 +225,17 @@ export async function debugLaunchConfig(
});
}

/** Return the base configuration with (nested) keys updated with the new one. */
/** Update the provided debug configuration with keys from a newly generated configuration. */
function updateConfigWithNewKeys(
baseConfiguration: vscode.DebugConfiguration,
newConfiguration: vscode.DebugConfiguration,
oldConfig: vscode.DebugConfiguration,
newConfig: vscode.DebugConfiguration,
keys: string[]
) {
keys.forEach(key => {
// We're manually handling `undefined`s during nested update, so even if the depth
// is restricted to 2, the implementation still looks a bit messy.
if (key.includes(".")) {
const [mainKey, subKey] = key.split(".", 2);
if (baseConfiguration[mainKey] === undefined) {
// { mainKey: unknown | undefined } -> { mainKey: undefined }
baseConfiguration[mainKey] = newConfiguration[mainKey];
} else if (newConfiguration[mainKey] === undefined) {
const subKeys = Object.keys(baseConfiguration[mainKey]);
if (subKeys.length === 1 && subKeys[0] === subKey) {
// { mainKey: undefined } -> { mainKey: { subKey: unknown } }
baseConfiguration[mainKey] = undefined;
} else {
// { mainKey: undefined } -> { mainKey: { subKey: unknown | undefined, ... } }
baseConfiguration[mainKey][subKey] = undefined;
}
} else {
// { mainKey: { subKey: unknown | undefined } } -> { mainKey: { subKey: unknown | undefined, ... } }
baseConfiguration[mainKey][subKey] = newConfiguration[mainKey][subKey];
}
} else {
// { key: unknown | undefined } -> { key: unknown | undefined, ... }
baseConfiguration[key] = newConfiguration[key];
for (const key of keys) {
if (newConfig[key] === undefined) {
delete oldConfig[key];
continue;
}
});
oldConfig[key] = newConfig[key];
}
}
Loading