Skip to content

Install Toolchain #1780

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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
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
183 changes: 183 additions & 0 deletions src/toolchain/swiftly.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
import * as path from "path";
import { SwiftlyConfig } from "./ToolchainVersion";
import * as fs from "fs/promises";
import * as fsSync from "fs";
import * as os from "os";
import * as readline from "readline";
import { execFile, ExecFileError } from "../utilities/utilities";
import * as vscode from "vscode";
import { Version } from "../utilities/version";
Expand Down Expand Up @@ -51,6 +54,45 @@ const InUseVersionResult = z.object({
version: z.string(),
});

const ListAvailableResult = z.object({
toolchains: z.array(
z.object({
version: z.discriminatedUnion("type", [
z.object({
major: z.union([z.number(), z.undefined()]),
minor: z.union([z.number(), z.undefined()]),
patch: z.union([z.number(), z.undefined()]),
name: z.string(),
type: z.literal("stable"),
}),
z.object({
major: z.union([z.number(), z.undefined()]),
minor: z.union([z.number(), z.undefined()]),
branch: z.string(),
date: z.string(),
name: z.string(),
type: z.literal("snapshot"),
}),
]),
})
),
});

export interface AvailableToolchain {
name: string;
type: "stable" | "snapshot";
version: string;
isInstalled: boolean;
}

export interface SwiftlyProgressData {
step?: {
text?: string;
timestamp?: number;
percent?: number;
};
}

export class Swiftly {
/**
* Finds the version of Swiftly installed on the system.
Expand Down Expand Up @@ -219,6 +261,147 @@ export class Swiftly {
return undefined;
}

/**
* Lists all toolchains available for installation from swiftly
*
* @param logger Optional logger for error reporting
* @returns Array of available toolchains
*/
public static async listAvailable(logger?: SwiftLogger): Promise<AvailableToolchain[]> {
if (!this.isSupported()) {
return [];
}

const version = await Swiftly.version(logger);
if (!version) {
logger?.warn("Swiftly is not installed");
return [];
}

if (!(await Swiftly.supportsJsonOutput(logger))) {
logger?.warn("Swiftly version does not support JSON output for list-available");
return [];
}

try {
const { stdout: availableStdout } = await execFile("swiftly", [
"list-available",
"--format=json",
]);
const availableResponse = ListAvailableResult.parse(JSON.parse(availableStdout));

const { stdout: installedStdout } = await execFile("swiftly", [
"list",
"--format=json",
]);
const installedResponse = ListResult.parse(JSON.parse(installedStdout));
const installedNames = new Set(installedResponse.toolchains.map(t => t.version.name));

return availableResponse.toolchains.map(toolchain => ({
name: toolchain.version.name,
type: toolchain.version.type,
version: toolchain.version.name,
isInstalled: installedNames.has(toolchain.version.name),
}));
} catch (error) {
logger?.error(`Failed to retrieve available Swiftly toolchains: ${error}`);
return [];
}
}

/**
* Installs a toolchain via swiftly with optional progress tracking
*
* @param version The toolchain version to install
* @param progressCallback Optional callback that receives progress data as JSON objects
* @param logger Optional logger for error reporting
*/
public static async installToolchain(
version: string,
progressCallback?: (progressData: SwiftlyProgressData) => void,
logger?: SwiftLogger
): Promise<void> {
if (!this.isSupported()) {
throw new Error("Swiftly is not supported on this platform");
}

if (process.platform === "linux") {
logger?.info(
`Skipping toolchain installation on Linux as it requires PostInstall steps`
);
return;
}

logger?.info(`Installing toolchain ${version} via swiftly`);

const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "vscode-swift-"));
const postInstallFilePath = path.join(tmpDir, `post-install-${version}.sh`);

let progressPipePath: string | undefined;
let progressPromise: Promise<void> | undefined;

if (progressCallback) {
progressPipePath = path.join(tmpDir, `progress-${version}.pipe`);

await execFile("mkfifo", [progressPipePath]);

progressPromise = new Promise<void>((resolve, reject) => {
const rl = readline.createInterface({
input: fsSync.createReadStream(progressPipePath!),
crlfDelay: Infinity,
});

rl.on("line", (line: string) => {
try {
const progressData = JSON.parse(line.trim()) as SwiftlyProgressData;
progressCallback(progressData);
} catch (err) {
logger?.error(`Failed to parse progress line: ${err}`);
}
});

rl.on("close", () => {
resolve();
});

rl.on("error", err => {
reject(err);
});
});
}

const installArgs = [
"install",
version,
"--use",
"--assume-yes",
"--post-install-file",
postInstallFilePath,
];

if (progressPipePath) {
installArgs.push("--progress-file", progressPipePath);
}

try {
const installPromise = execFile("swiftly", installArgs);

if (progressPromise) {
await Promise.all([installPromise, progressPromise]);
} else {
await installPromise;
}
} finally {
if (progressPipePath) {
try {
await fs.unlink(progressPipePath);
} catch {
// Ignore errors if the pipe file doesn't exist
}
}
}
}

/**
* Reads the Swiftly configuration file, if it exists.
*
Expand Down
96 changes: 84 additions & 12 deletions src/ui/ToolchainSelection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { showReloadExtensionNotification } from "./ReloadExtension";
import { SwiftToolchain } from "../toolchain/toolchain";
import configuration from "../configuration";
import { Commands } from "../commands";
import { Swiftly } from "../toolchain/swiftly";
import { Swiftly, SwiftlyProgressData } from "../toolchain/swiftly";
import { SwiftLogger } from "../logging/SwiftLogger";

/**
Expand Down Expand Up @@ -133,6 +133,12 @@ interface SwiftlyToolchainItem extends BaseSwiftToolchainItem {
version: string;
}

interface InstallableToolchainItem extends BaseSwiftToolchainItem {
category: "installable";
version: string;
toolchainType: "stable" | "snapshot";
}

/** A {@link vscode.QuickPickItem} that separates items in the UI */
class SeparatorItem implements vscode.QuickPickItem {
readonly type = "separator";
Expand All @@ -145,7 +151,11 @@ class SeparatorItem implements vscode.QuickPickItem {
}

/** The possible types of {@link vscode.QuickPickItem} in the toolchain selection dialog */
type SelectToolchainItem = SwiftToolchainItem | ActionItem | SeparatorItem;
type SelectToolchainItem =
| SwiftToolchainItem
| InstallableToolchainItem
| ActionItem
| SeparatorItem;

/**
* Retrieves all {@link SelectToolchainItem} that are available on the system.
Expand Down Expand Up @@ -223,7 +233,72 @@ async function getQuickPickItems(
}
},
}));
// Mark which toolchain is being actively used

const installableToolchains =
process.platform === "linux"
? []
: (await Swiftly.listAvailable(logger))
.filter(toolchain => !toolchain.isInstalled)
.reverse()
.map<InstallableToolchainItem>(toolchain => ({
type: "toolchain",
label: `$(cloud-download) ${toolchain.name} (${toolchain.type})`,
// detail: `Install ${toolchain.type} release`,
category: "installable",
version: toolchain.name,
toolchainType: toolchain.type,
onDidSelect: async () => {
try {
await vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: `Installing Swift ${toolchain.name}`,
cancellable: false,
},
async progress => {
progress.report({ message: "Starting installation..." });

let lastProgress = 0;

await Swiftly.installToolchain(
toolchain.name,
(progressData: SwiftlyProgressData) => {
if (
progressData.step?.percent !== undefined &&
progressData.step.percent > lastProgress
) {
const increment =
progressData.step.percent - lastProgress;
progress.report({
increment,
message:
progressData.step.text ||
`${progressData.step.percent}% complete`,
});
lastProgress = progressData.step.percent;
}
},
logger
);

progress.report({
increment: 100 - lastProgress,
message: "Installation complete",
});
}
);

void showReloadExtensionNotification(
`Swift ${toolchain.name} has been installed and activated. Visual Studio Code needs to be reloaded.`
);
} catch (error) {
logger?.error(`Failed to install Swift ${toolchain.name}: ${error}`);
void vscode.window.showErrorMessage(
`Failed to install Swift ${toolchain.name}: ${error}`
);
}
},
}));
if (activeToolchain) {
const currentSwiftlyVersion = activeToolchain.isSwiftlyManaged
? await Swiftly.inUseVersion("swiftly", cwd)
Expand Down Expand Up @@ -286,6 +361,9 @@ async function getQuickPickItems(
...(swiftlyToolchains.length > 0
? [new SeparatorItem("swiftly"), ...swiftlyToolchains]
: []),
...(installableToolchains.length > 0
? [new SeparatorItem("available for install"), ...installableToolchains]
: []),
new SeparatorItem("actions"),
...actionItems,
];
Expand Down Expand Up @@ -345,17 +423,11 @@ export async function showToolchainSelectionQuickPick(
// Update the toolchain path`
let swiftPath: string | undefined;

// Handle Swiftly toolchains specially
if (selected.category === "swiftly") {
try {
swiftPath = undefined;
} catch (error) {
void vscode.window.showErrorMessage(`Failed to switch Swiftly toolchain: ${error}`);
return;
}
if (selected.category === "swiftly" || selected.category === "installable") {
swiftPath = undefined;
} else {
// For non-Swiftly toolchains, use the swiftFolderPath
swiftPath = selected.swiftFolderPath;
swiftPath = (selected as PublicSwiftToolchainItem | XcodeToolchainItem).swiftFolderPath;
}

const isUpdated = await setToolchainPath(swiftPath, developerDir);
Expand Down
Loading