import vscode from "vscode"; import fs from "fs/promises"; import path from "path"; import semver from "semver"; import * as zigUtil from "./zigUtil"; import * as zvm from "./zvm"; import { ZigProvider } from "./zigProvider"; let statusItem: vscode.StatusBarItem; let languageStatusItem: vscode.LanguageStatusItem; export let zigProvider: ZigProvider; /** Versions whose install prompt has already been shown, so a workspace asks only once. */ const promptedVersions = new Set(); function getWorkspaceFolder(): vscode.WorkspaceFolder | null { // Supporting multiple workspaces is significantly more complex so we just look for the first workspace. if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0) { return vscode.workspace.workspaceFolders[0]; } return null; } interface BuildZigZonMetadata { /** The `build.zig.zon` document. */ document: vscode.TextDocument; minimumZigVersion: semver.SemVer; /** `.minimum_zig_version = "0.13.0"` */ minimumZigVersionSourceRange: vscode.Range; } /** * Look for a `build.zig.zon` in the current workspace and return the `minimum_zig_version` in it. */ async function parseBuildZigZon(): Promise { const workspace = getWorkspaceFolder(); if (!workspace) return null; const manifestUri = vscode.Uri.joinPath(workspace.uri, "build.zig.zon"); let manifest; try { manifest = await vscode.workspace.openTextDocument(manifestUri); } catch { return null; } // Not perfect, but good enough const regex = /\n\s*\.minimum_zig_version\s=\s\"(.*)\"/; const matches = regex.exec(manifest.getText()); if (!matches) return null; const versionString = matches[1]; const version = semver.parse(versionString); if (!version) return null; const startPosition = manifest.positionAt(matches.index + matches[0].length - versionString.length - 1); const endPosition = startPosition.translate(0, versionString.length); return { document: manifest, minimumZigVersion: version, minimumZigVersionSourceRange: new vscode.Range(startPosition, endPosition), }; } /** The order of these enums defines the default order in which these sources are executed. */ enum WantedZigVersionSource { /** `.zigversion` */ workspaceZigVersionFile = ".zigversion", /** The `minimum_zig_version` in `build.zig.zon` */ workspaceBuildZigZon = "build.zig.zon", /** `zig.version` */ zigVersionConfigOption = "zig.version", } /** Try to resolve the (workspace-specific) Zig version. */ async function getWantedZigVersion( /** List of "sources" that are applied in the given order to resolve the wanted Zig version */ sources: WantedZigVersionSource[], ): Promise<{ version: semver.SemVer; source: WantedZigVersionSource; } | null> { const workspace = getWorkspaceFolder(); for (const source of sources) { let result: semver.SemVer | null = null; try { switch (source) { case WantedZigVersionSource.workspaceZigVersionFile: if (workspace) { const zigVersionString = await vscode.workspace.fs.readFile( vscode.Uri.joinPath(workspace.uri, ".zigversion"), ); result = semver.parse(zigVersionString.toString().trim()); } break; case WantedZigVersionSource.workspaceBuildZigZon: const metadata = await parseBuildZigZon(); if (metadata?.minimumZigVersion) { result = metadata.minimumZigVersion; } break; case WantedZigVersionSource.zigVersionConfigOption: const versionString = vscode.workspace.getConfiguration("zig").get("version"); if (versionString) { result = semver.parse(versionString); if (!result) { void vscode.window.showErrorMessage( `Invalid 'zig.version' config option. '${versionString}' is not a valid Zig version`, ); } } break; } } catch {} if (!result) continue; return { version: result, source: source, }; } return null; } /** The highest installed version that satisfies `minimum`, or `null`. */ function findInstalledSatisfying(installed: string[], minimum: semver.SemVer): string | null { let best: { name: string; version: semver.SemVer } | null = null; for (const name of installed) { const version = semver.parse(name); if (!version) continue; if (semver.lt(version, minimum)) continue; if (best === null || semver.gt(version, best.version)) best = { name, version }; } return best?.name ?? null; } /** Points the extension at a Zig installation that zvm manages. */ function useVersion(version: string): boolean { const result = zigUtil.resolveExePathAndVersion(zvm.zigExecutable(version), "version"); if ("message" in result) { void vscode.window.showErrorMessage( `The Zig version '${version}' managed by zvm cannot be used: ${result.message}`, ); return false; } zigProvider.set(result); return true; } /** Runs `zvm install` for a version that zvm does not manage yet. */ async function installWithZvm(version: string): Promise { const result = await vscode.window.withProgress( { location: vscode.ProgressLocation.Notification, title: `Installing Zig ${version} with zvm`, cancellable: false, }, () => zvm.install(version, { zls: true }), ); if (!result.ok) { void vscode.window.showErrorMessage(`zvm failed to install Zig ${version}: ${result.message}`); return false; } return useVersion(version); } async function offerInstall(version: string): Promise { if (promptedVersions.has(version)) return false; promptedVersions.add(version); const response = await vscode.window.showInformationMessage( `Zig ${version} is not installed. Install it with zvm?`, "Install", "Select Version", ); switch (response) { case "Install": return installWithZvm(version); case "Select Version": await vscode.commands.executeCommand("zig.install"); return false; default: return false; } } /** Resolves the Zig executable from `zig.path`, the workspace version, or PATH. */ async function resolveZig(): Promise { if (vscode.workspace.getConfiguration("zig").get("path")) { // `ZigProvider` resolves the configured path when it is constructed. return; } const wanted = await getWantedZigVersion(Object.values(WantedZigVersionSource) as WantedZigVersionSource[]); const installed = await zvm.installedVersions(); if (wanted) { const version = wanted.source === WantedZigVersionSource.workspaceBuildZigZon ? findInstalledSatisfying(installed, wanted.version) ?? wanted.version.raw : wanted.version.raw; if (installed.includes(version)) { useVersion(version); return; } if (await offerInstall(version)) return; } // No workspace version, or the chosen one was not installed: use whichever Zig PATH has. const inPath = zigUtil.resolveExePathAndVersion("zig", "version"); if ("exe" in inPath) { zigProvider.set(inPath); return; } zigProvider.set(null); } async function showUpdateWorkspaceVersionDialog(version: string, source?: WantedZigVersionSource): Promise { const workspace = getWorkspaceFolder(); if (workspace !== null) { let buttonName; switch (source) { case WantedZigVersionSource.workspaceZigVersionFile: buttonName = "update .zigversion"; break; case WantedZigVersionSource.workspaceBuildZigZon: buttonName = "update build.zig.zon"; break; case WantedZigVersionSource.zigVersionConfigOption: buttonName = "update workspace settings"; break; case undefined: buttonName = "create .zigversion"; break; } const response = await vscode.window.showInformationMessage( `Would you like to save Zig ${version} in this workspace?`, buttonName, ); if (!response) return; } source ??= workspace ? WantedZigVersionSource.workspaceZigVersionFile : WantedZigVersionSource.zigVersionConfigOption; switch (source) { case WantedZigVersionSource.workspaceZigVersionFile: { if (!workspace) throw new Error("failed to resolve workspace folder"); const edit = new vscode.WorkspaceEdit(); edit.createFile(vscode.Uri.joinPath(workspace.uri, ".zigversion"), { overwrite: true, contents: new Uint8Array(Buffer.from(version)), }); await vscode.workspace.applyEdit(edit); break; } case WantedZigVersionSource.workspaceBuildZigZon: { const metadata = await parseBuildZigZon(); if (!metadata) throw new Error("failed to parse build.zig.zon"); const edit = new vscode.WorkspaceEdit(); edit.replace(metadata.document.uri, metadata.minimumZigVersionSourceRange, version); await vscode.workspace.applyEdit(edit); break; } case WantedZigVersionSource.zigVersionConfigOption: { await vscode.workspace.getConfiguration("zig").update("version", version, !workspace); break; } } } async function selectVersion() { const installed = await zvm.installedVersions(); const workspaceZig = await getWantedZigVersion([ WantedZigVersionSource.workspaceZigVersionFile, WantedZigVersionSource.workspaceBuildZigZon, WantedZigVersionSource.zigVersionConfigOption, ]); const items: vscode.QuickPickItem[] = []; if (workspaceZig !== null) { items.push({ label: "Use Workspace Version", detail: workspaceZig.version.raw, }); } const zigInPath = zigUtil.resolveExePathAndVersion("zig", "version"); if (!("message" in zigInPath)) { items.push({ label: "Use Zig in PATH", description: zigInPath.exe, detail: zigInPath.version.raw, }); } items.push( { label: "Manually Specify Path", }, { label: "", kind: vscode.QuickPickItemKind.Separator, }, ); const currentPath = zigProvider.getZigPath(); for (const version of installed) { const inUse = currentPath !== null && path.resolve(currentPath) === path.resolve(zvm.zigExecutable(version)); items.push({ label: version, description: inUse ? "in use" : "zvm", }); } items.push( { label: "", kind: vscode.QuickPickItemKind.Separator, }, { label: "Install a Version with zvm…", }, ); const selection = await vscode.window.showQuickPick(items, { title: "Select Zig version", canPickMany: false, placeHolder: zigProvider.getZigVersion()?.raw, }); if (selection === undefined) return; switch (selection.label) { case "Use Workspace Version": await resolveZig(); break; case "Use Zig in PATH": { const zigConfig = vscode.workspace.getConfiguration("zig"); await zigUtil.workspaceConfigUpdateNoThrow(zigConfig, "path", "zig", true); break; } case "Manually Specify Path": { const uris = await vscode.window.showOpenDialog({ canSelectFiles: true, canSelectFolders: false, canSelectMany: false, title: "Select Zig executable", }); if (!uris) return; await zigProvider.setAndSave(uris[0].fsPath); break; } case "Install a Version with zvm…": { const version = await vscode.window.showInputBox({ title: "Zig version to install with zvm", placeHolder: "0.15.2", prompt: "Runs `zvm install --zls`. Run `zvm ls-remote` in a terminal to list versions.", }); if (!version) return; if (!(await installWithZvm(version.trim()))) return; await showUpdateWorkspaceVersionDialog(version.trim(), workspaceZig?.source); break; } default: { if (!useVersion(selection.label)) return; await showUpdateWorkspaceVersionDialog(selection.label, workspaceZig?.source); break; } } } function updateStatusItem(item: vscode.StatusBarItem, version: semver.SemVer | null) { item.name = "Zig Version"; item.text = version?.toString() ?? "not installed"; item.tooltip = "Select Zig Version"; item.command = { title: "Select Version", command: "zig.install", }; if (version) { item.backgroundColor = undefined; } else { item.backgroundColor = new vscode.ThemeColor("statusBarItem.errorBackground"); } } function updateLanguageStatusItem(item: vscode.LanguageStatusItem, version: semver.SemVer | null) { item.name = "Zig"; if (version) { item.text = `Zig ${version.toString()}`; item.detail = "Zig Version"; item.severity = vscode.LanguageStatusSeverity.Information; } else { item.text = "Zig not installed"; item.severity = vscode.LanguageStatusSeverity.Error; } item.command = { title: "Select Version", command: "zig.install", }; } function updateZigEnvironmentVariableCollection(context: vscode.ExtensionContext, zigExePath: string | null) { if (zigExePath) { const envValue = path.dirname(zigExePath) + path.delimiter; // This will take priority over a user-defined PATH values. context.environmentVariableCollection.prepend("PATH", envValue); } else { context.environmentVariableCollection.delete("PATH"); } } /** * Should be called when one of the following events happen: * - The Zig executable has been modified * - A workspace configuration file has been modified (e.g. `.zigversion`, `build.zig.zon`) */ async function updateStatus(context: vscode.ExtensionContext): Promise { const zigVersion = zigProvider.getZigVersion(); const zigPath = zigProvider.getZigPath(); updateStatusItem(statusItem, zigVersion); updateLanguageStatusItem(languageStatusItem, zigVersion); updateZigEnvironmentVariableCollection(context, zigPath); // Try to check whether the Zig version satifies the `minimum_zig_version` in `build.zig.zon` if (!zigVersion || !zigPath) return; const buildZigZonMetadata = await parseBuildZigZon(); if (!buildZigZonMetadata) return; if (semver.gte(zigVersion, buildZigZonMetadata.minimumZigVersion)) return; statusItem.backgroundColor = new vscode.ThemeColor("statusBarItem.warningBackground"); void vscode.window .showWarningMessage( `Your Zig version '${zigVersion.toString()}' does not satisfy the minimum Zig version '${buildZigZonMetadata.minimumZigVersion.toString()}' of your project.`, "select Zig version", "open build.zig.zon", ) .then(async (response) => { switch (response) { case undefined: break; case "select Zig version": { await vscode.commands.executeCommand("zig.install"); break; } case "open build.zig.zon": { void vscode.window.showTextDocument(buildZigZonMetadata.document, { selection: buildZigZonMetadata.minimumZigVersionSourceRange, }); break; } } }); } export async function setupZig(context: vscode.ExtensionContext) { const zigConfig = vscode.workspace.getConfiguration("zig"); { // convert `zig.buildOnSave` to `zig.buildOnSaveProvider` { const inspect = zigConfig.inspect("buildOnSave"); if (inspect?.globalValue !== undefined) { await zigUtil.workspaceConfigUpdateNoThrow(zigConfig, "buildOnSaveProvider", inspect.globalValue, true); await zigUtil.workspaceConfigUpdateNoThrow(zigConfig, "buildOnSave", undefined, true); } if (inspect?.workspaceValue !== undefined) { await zigUtil.workspaceConfigUpdateNoThrow( zigConfig, "buildOnSaveProvider", inspect.workspaceValue, false, ); await zigUtil.workspaceConfigUpdateNoThrow(zigConfig, "buildOnSave", undefined, false); } } // convert `zig.buildArgs` to `zig.buildOnSaveArgs` { const inspect = zigConfig.inspect("buildArgs"); if (inspect?.globalValue) { await zigUtil.workspaceConfigUpdateNoThrow(zigConfig, "buildOnSaveArgs", inspect.globalValue, true); await zigUtil.workspaceConfigUpdateNoThrow(zigConfig, "buildArgs", undefined, true); } if (inspect?.workspaceValue) { await zigUtil.workspaceConfigUpdateNoThrow(zigConfig, "buildOnSaveArgs", inspect.workspaceValue, false); await zigUtil.workspaceConfigUpdateNoThrow(zigConfig, "buildArgs", undefined, false); } } } /// Workaround https://github.com/ziglang/zig/issues/21905 switch (process.platform) { case "darwin": case "freebsd": case "openbsd": case "netbsd": case "haiku": vscode.workspace.onDidSaveTextDocument(async (document) => { if (document.languageId !== "zig") return; if (document.uri.scheme !== "file") return; const zigVersion = zigProvider.getZigVersion(); if (!zigVersion) return; if (semver.gte(zigVersion, "0.15.0-dev.1372+abf179533")) return; const fsPath = document.uri.fsPath; try { await fs.copyFile(fsPath, fsPath + ".tmp", fs.constants.COPYFILE_EXCL); await fs.rename(fsPath + ".tmp", fsPath); } catch {} }, context.subscriptions); break; case "aix": case "android": case "linux": case "sunos": case "win32": case "cygwin": break; } zigProvider = new ZigProvider(); /** There two status items because there doesn't seem to be a way to pin a language status item by default. */ statusItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, -1); languageStatusItem = vscode.languages.createLanguageStatusItem("zig.status", { language: "zig" }); context.environmentVariableCollection.description = "Add Zig to PATH"; const watcher1 = vscode.workspace.createFileSystemWatcher("**/.zigversion"); const watcher2 = vscode.workspace.createFileSystemWatcher("**/build.zig.zon"); const refreshZigInstallation = zigUtil.asyncDebounce(async () => { if (!vscode.workspace.getConfiguration("zig").get("path")) { await resolveZig(); } await updateStatus(context); }, 200); await resolveZig(); await updateStatus(context); const onDidChangeActiveTextEditor = (editor: vscode.TextEditor | undefined) => { if (editor?.document.languageId === "zig") { statusItem.show(); } else { statusItem.hide(); } }; onDidChangeActiveTextEditor(vscode.window.activeTextEditor); context.subscriptions.push( statusItem, languageStatusItem, vscode.commands.registerCommand("zig.install", async () => { await selectVersion(); }), vscode.workspace.onDidChangeConfiguration((change) => { if (change.affectsConfiguration("zig.version")) { void refreshZigInstallation(); } if (change.affectsConfiguration("zig.path")) { const result = zigProvider.resolveZigPathConfigOption(); if (result === undefined) return; // error message already reported if (result !== null) { zigProvider.set(result); } void refreshZigInstallation(); } }), vscode.window.onDidChangeActiveTextEditor(onDidChangeActiveTextEditor), zigProvider.onChange.event(() => { void updateStatus(context); }), watcher1.onDidCreate(refreshZigInstallation), watcher1.onDidChange(refreshZigInstallation), watcher1.onDidDelete(refreshZigInstallation), watcher1, watcher2.onDidCreate(refreshZigInstallation), watcher2.onDidChange(refreshZigInstallation), watcher2.onDidDelete(refreshZigInstallation), watcher2, ); }