Add Marqdo VS Code run/debug, diagnostics, and CLI auto-install.

Ship TextMate highlighting, Run/Problems/debug entry, GitHub release CLI+stdlib bootstrap, and packaging metadata for the published .vsix.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-08-05 16:57:49 +08:00
1 parent f4f798a4d0
commit 3887205ebb
15 files changed
+5184 -66

No files matched your search

+184
View File
@@ -0,0 +1,184 @@
import * as vscode from "vscode";
import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "child_process";
import type { ExtensionContext } from "vscode";
export interface CliResult {
code: number | null;
stdout: string;
stderr: string;
}
let resolveCli: (() => string) | undefined;
let resolveLib: (() => string | undefined) | undefined;
/** Wire install-aware path resolution from extension activate. */
export function configureCliResolution(
_context: ExtensionContext,
cli: () => string,
lib: () => string | undefined
): void {
resolveCli = cli;
resolveLib = lib;
}
function configuredPath(): string {
return (
vscode.workspace.getConfiguration("marqdo").get<string>("cliPath")?.trim() ||
"marqdo"
);
}
export function resolveMarqdoCli(): string {
if (resolveCli) {
return resolveCli();
}
return configuredPath();
}
function spawnEnv(): NodeJS.ProcessEnv {
const env = { ...process.env };
const lib = resolveLib?.();
if (lib) {
env.MARQDO_LIB = lib;
}
return env;
}
export function workspaceCwd(prefer?: vscode.Uri): string {
if (prefer) {
const folder = vscode.workspace.getWorkspaceFolder(prefer);
if (folder) {
return folder.uri.fsPath;
}
return vscode.Uri.joinPath(prefer, "..").fsPath;
}
return vscode.workspace.workspaceFolders?.[0]?.uri.fsPath ?? process.cwd();
}
export function runMarqdo(
args: string[],
options: { cwd: string; timeoutMs?: number }
): Promise<CliResult> {
const cli = resolveMarqdoCli();
return new Promise((resolve) => {
const child = spawn(cli, args, {
cwd: options.cwd,
shell: process.platform === "win32",
env: spawnEnv(),
});
let stdout = "";
let stderr = "";
let settled = false;
const finish = (code: number | null) => {
if (settled) {
return;
}
settled = true;
resolve({ code, stdout, stderr });
};
const timer =
options.timeoutMs && options.timeoutMs > 0
? setTimeout(() => {
child.kill();
finish(null);
}, options.timeoutMs)
: undefined;
child.stdout.on("data", (d: Buffer) => {
stdout += d.toString();
});
child.stderr.on("data", (d: Buffer) => {
stderr += d.toString();
});
child.on("error", (err) => {
if (timer) {
clearTimeout(timer);
}
stderr += err.message;
finish(1);
});
child.on("close", (code) => {
if (timer) {
clearTimeout(timer);
}
finish(code);
});
});
}
export function probeMarqdo(
cliOverride?: string
): { ok: boolean; version?: string; detail: string } {
const cli = cliOverride ?? resolveMarqdoCli();
try {
const r = spawnSync(cli, ["--version"], {
encoding: "utf8",
shell: process.platform === "win32",
timeout: 8000,
env: spawnEnv(),
});
const out = `${r.stdout ?? ""}${r.stderr ?? ""}`.trim();
if (r.error) {
return { ok: false, detail: r.error.message };
}
if (r.status !== 0) {
return { ok: false, detail: out || `exit ${r.status}` };
}
return { ok: true, version: out, detail: out };
} catch (e) {
return { ok: false, detail: e instanceof Error ? e.message : String(e) };
}
}
export class DebugServer {
private proc: ChildProcessWithoutNullStreams | null = null;
private output: vscode.OutputChannel;
constructor(output: vscode.OutputChannel) {
this.output = output;
}
get running(): boolean {
return this.proc !== null && this.proc.exitCode === null;
}
async start(targetPath: string, host: string, port: number): Promise<string> {
if (this.running) {
await this.stop();
}
const cli = resolveMarqdoCli();
const cwd = workspaceCwd(vscode.Uri.file(targetPath));
this.output.appendLine(`$ ${cli} debug ${targetPath} --host ${host} --port ${port} --no-open`);
this.proc = spawn(
cli,
["debug", targetPath, "--host", host, "--port", String(port), "--no-open"],
{
cwd,
shell: process.platform === "win32",
env: spawnEnv(),
}
);
const url = `http://${host}:${port}/`;
this.proc.stdout.on("data", (d: Buffer) => this.output.append(d.toString()));
this.proc.stderr.on("data", (d: Buffer) => this.output.append(d.toString()));
this.proc.on("exit", (code) => {
this.output.appendLine(`[debug] exited (${code})`);
this.proc = null;
});
this.proc.on("error", (err) => {
this.output.appendLine(`[debug] ${err.message}`);
this.proc = null;
});
await new Promise((r) => setTimeout(r, 600));
return url;
}
async stop(): Promise<void> {
if (!this.proc) {
return;
}
const p = this.proc;
this.proc = null;
p.kill();
await new Promise((r) => setTimeout(r, 200));
}
}
+141
View File
@@ -0,0 +1,141 @@
import * as vscode from "vscode";
import * as path from "path";
export function parseDiagnostics(
text: string,
fallbackUri: vscode.Uri,
cwd: string
): vscode.Diagnostic[] {
const out: vscode.Diagnostic[] = [];
for (const raw of text.split(/\r?\n/)) {
const line = raw.trim();
if (!line) {
continue;
}
const parsed = parseDiagLine(line);
if (!parsed) {
continue;
}
out.push(
makeDiag(parsed.file, parsed.line, parsed.col, parsed.message, fallbackUri, cwd)
);
}
return out;
}
function parseDiagLine(
line: string
): { file: string; line: number; col: number; message: string } | undefined {
// Windows: E:\path\to\file.mq.md:7:1: message
const win = /^([A-Za-z]:[\\/][^:]*):(\d+):(\d+):\s*(.+)$/.exec(line);
if (win) {
return {
file: win[1],
line: Number(win[2]),
col: Number(win[3]),
message: win[4],
};
}
// Unix / relative: path/file.mq.md:7:1: message
const normal = /^(.+):(\d+):(\d+):\s*(.+)$/.exec(line);
if (normal) {
return {
file: normal[1],
line: Number(normal[2]),
col: Number(normal[3]),
message: normal[4],
};
}
const spanOnly = /^(\d+):(\d+):\s*(.+)$/.exec(line);
if (spanOnly) {
return {
file: "",
line: Number(spanOnly[1]),
col: Number(spanOnly[2]),
message: spanOnly[3],
};
}
return undefined;
}
function makeDiag(
filePath: string,
line1: number,
col1: number,
message: string,
fallbackUri: vscode.Uri,
cwd: string
): vscode.Diagnostic {
const line = Math.max(0, line1 - 1);
const col = Math.max(0, col1 - 1);
const range = new vscode.Range(line, col, line, Math.max(col + 1, col));
const diag = new vscode.Diagnostic(range, message, vscode.DiagnosticSeverity.Error);
diag.source = "marqdo";
(diag as vscode.Diagnostic & { targetPath?: string }).targetPath = resolvePath(
filePath,
fallbackUri,
cwd
);
return diag;
}
function resolvePath(filePath: string, fallbackUri: vscode.Uri, cwd: string): string {
if (!filePath) {
return fallbackUri.fsPath;
}
if (path.isAbsolute(filePath)) {
return filePath;
}
return path.resolve(cwd, filePath);
}
export class DiagnosticBag {
private readonly collection: vscode.DiagnosticCollection;
constructor() {
this.collection = vscode.languages.createDiagnosticCollection("marqdo");
}
get disposable(): vscode.Disposable {
return this.collection;
}
clear(uri?: vscode.Uri): void {
if (uri) {
this.collection.delete(uri);
} else {
this.collection.clear();
}
}
setFromCli(text: string, fallbackUri: vscode.Uri, cwd: string): void {
const parsed = parseDiagnostics(text, fallbackUri, cwd);
const byFile = new Map<string, vscode.Diagnostic[]>();
for (const d of parsed) {
const target =
(d as vscode.Diagnostic & { targetPath?: string }).targetPath ?? fallbackUri.fsPath;
const list = byFile.get(target) ?? [];
list.push(d);
byFile.set(target, list);
}
if (byFile.size === 0) {
const trimmed = text.trim();
if (trimmed) {
const range = new vscode.Range(0, 0, 0, 1);
this.collection.set(fallbackUri, [
new vscode.Diagnostic(
range,
trimmed.split(/\r?\n/)[0],
vscode.DiagnosticSeverity.Error
),
]);
} else {
this.collection.delete(fallbackUri);
}
return;
}
for (const [file, diags] of byFile) {
this.collection.set(vscode.Uri.file(file), diags);
}
}
}
+237 -9
View File
@@ -1,13 +1,241 @@
import * as vscode from "vscode";
import { DebugServer, configureCliResolution, runMarqdo, workspaceCwd } from "./cli";
import { DiagnosticBag } from "./diagnostics";
import {
checkInstallStatus,
installFromGitHub,
promptIfNeeded,
resetSkipPrompt,
resolveCliPath,
resolveLibEnv,
} from "./install";
/**
* Marqdo VS Code extension entry.
* Keep this host thin: language contribution lives in package.json / TextMate;
* run / diagnostics / DAP come later via the marqdo CLI.
*/
export function activate(_context: vscode.ExtensionContext): void {
// P0: grammar + language id are declarative.
// P1+: register commands that spawn `marqdo`.
let output: vscode.OutputChannel;
let diagnostics: DiagnosticBag;
let debugServer: DebugServer;
let extContext: vscode.ExtensionContext;
export function activate(context: vscode.ExtensionContext): void {
extContext = context;
output = vscode.window.createOutputChannel("Marqdo");
diagnostics = new DiagnosticBag();
debugServer = new DebugServer(output);
configureCliResolution(
context,
() => resolveCliPath(context),
() => resolveLibEnv(context)
);
context.subscriptions.push(
output,
diagnostics.disposable,
vscode.commands.registerCommand("marqdo.run", () => runActiveFile()),
vscode.commands.registerCommand("marqdo.debug", () => startDebug()),
vscode.commands.registerCommand("marqdo.debug.stop", () => stopDebug()),
vscode.commands.registerCommand("marqdo.catalog", () => runCatalog()),
vscode.commands.registerCommand("marqdo.showOutput", () => output.show(true)),
vscode.commands.registerCommand("marqdo.installCli", () => installCli()),
vscode.commands.registerCommand("marqdo.checkCli", () => checkCli()),
vscode.workspace.onDidSaveTextDocument((doc) => {
if (doc.languageId === "marqdo" && autoDiagnose()) {
void diagnoseDocument(doc);
}
})
);
void promptIfNeeded(context, output);
}
export function deactivate(): void {}
export function deactivate(): void {
void debugServer?.stop();
}
function autoDiagnose(): boolean {
return vscode.workspace.getConfiguration("marqdo").get<boolean>("diagnoseOnSave") ?? false;
}
async function installCli(): Promise<void> {
await resetSkipPrompt(extContext);
const status = checkInstallStatus(extContext);
try {
if (status.cliOk && !status.libOk) {
await installFromGitHub(extContext, output, "stdlib");
} else {
await installFromGitHub(extContext, output, "bundle");
}
} catch (e) {
const err = e instanceof Error ? e.message : String(e);
output.appendLine(`[install] ${err}`);
const open = await vscode.window.showErrorMessage(`Marqdo install failed: ${err}`, "Open Releases");
if (open) {
await vscode.env.openExternal(vscode.Uri.parse("https://github.com/cflmy/marqdo/releases"));
}
}
}
async function checkCli(): Promise<void> {
const status = checkInstallStatus(extContext);
output.appendLine(`[check] ${status.detail}`);
if (status.cliOk && status.libOk) {
void vscode.window.showInformationMessage(`Marqdo ready: ${status.version}`);
return;
}
const choice = await vscode.window.showWarningMessage(
status.detail,
"Install / Repair",
"Open Releases"
);
if (choice === "Install / Repair") {
await installCli();
} else if (choice === "Open Releases") {
await vscode.env.openExternal(vscode.Uri.parse("https://github.com/cflmy/marqdo/releases"));
}
}
function activeMqDoc(): vscode.TextDocument | undefined {
const doc = vscode.window.activeTextEditor?.document;
if (!doc) {
return undefined;
}
if (doc.languageId === "marqdo" || doc.fileName.endsWith(".mq.md")) {
return doc;
}
return undefined;
}
async function ensureCliOrOfferInstall(): Promise<boolean> {
const status = checkInstallStatus(extContext);
if (status.cliOk) {
return true;
}
const choice = await vscode.window.showWarningMessage(
"Marqdo CLI not found. Install the official release (includes stdlib)?",
"Install",
"Cancel"
);
if (choice === "Install") {
await installCli();
return checkInstallStatus(extContext).cliOk;
}
return false;
}
async function runActiveFile(): Promise<void> {
if (!(await ensureCliOrOfferInstall())) {
return;
}
const doc = activeMqDoc();
if (!doc) {
void vscode.window.showWarningMessage("Open a .mq.md file to run.");
return;
}
if (doc.isDirty) {
await doc.save();
}
const cwd = workspaceCwd(doc.uri);
output.show(true);
output.appendLine(`$ marqdo run ${doc.uri.fsPath}`);
const result = await runMarqdo(["run", doc.uri.fsPath], {
cwd,
timeoutMs: vscode.workspace.getConfiguration("marqdo").get<number>("runTimeoutMs") ?? 60000,
});
if (result.stdout.trim()) {
output.appendLine(result.stdout.trimEnd());
}
if (result.stderr.trim()) {
output.appendLine(result.stderr.trimEnd());
}
if (result.code === 0) {
diagnostics.clear(doc.uri);
void vscode.window.setStatusBarMessage("Marqdo: run ok", 3000);
} else {
diagnostics.setFromCli(result.stderr || result.stdout, doc.uri, cwd);
void vscode.window.showErrorMessage("Marqdo: run failed (see Problems / Output)");
}
}
async function diagnoseDocument(doc: vscode.TextDocument): Promise<void> {
const cwd = workspaceCwd(doc.uri);
const result = await runMarqdo(["run", doc.uri.fsPath], {
cwd,
timeoutMs: vscode.workspace.getConfiguration("marqdo").get<number>("runTimeoutMs") ?? 60000,
});
if (result.code === 0) {
diagnostics.clear(doc.uri);
} else {
diagnostics.setFromCli(result.stderr || result.stdout, doc.uri, cwd);
}
}
async function startDebug(): Promise<void> {
if (!(await ensureCliOrOfferInstall())) {
return;
}
const doc = activeMqDoc();
const folder = vscode.workspace.workspaceFolders?.[0];
const target = doc?.uri.fsPath ?? folder?.uri.fsPath;
if (!target) {
void vscode.window.showWarningMessage("Open a folder or .mq.md file to debug.");
return;
}
const cfg = vscode.workspace.getConfiguration("marqdo");
const host = cfg.get<string>("debugHost") ?? "127.0.0.1";
const port = cfg.get<number>("debugPort") ?? 7430;
output.show(true);
try {
const url = await debugServer.start(target, host, port);
const open = cfg.get<string>("debugOpen") ?? "external";
if (open === "simpleBrowser") {
await vscode.commands.executeCommand("simpleBrowser.show", url);
} else {
await vscode.env.openExternal(vscode.Uri.parse(url));
}
void vscode.window.setStatusBarMessage(`Marqdo debug: ${url}`, 5000);
} catch (e) {
void vscode.window.showErrorMessage(
`Marqdo debug failed: ${e instanceof Error ? e.message : String(e)}`
);
}
}
async function stopDebug(): Promise<void> {
await debugServer.stop();
void vscode.window.setStatusBarMessage("Marqdo debug stopped", 3000);
}
async function runCatalog(): Promise<void> {
if (!(await ensureCliOrOfferInstall())) {
return;
}
const folder = vscode.workspace.workspaceFolders?.[0];
if (!folder) {
void vscode.window.showWarningMessage("Open a workspace folder for catalog.");
return;
}
const outDir =
vscode.workspace.getConfiguration("marqdo").get<string>("catalogOut") ?? ".marqdo";
output.show(true);
output.appendLine(`$ marqdo catalog ${folder.uri.fsPath} -o ${outDir}`);
const result = await runMarqdo(["catalog", folder.uri.fsPath, "-o", outDir], {
cwd: folder.uri.fsPath,
timeoutMs: 120000,
});
if (result.stdout.trim()) {
output.appendLine(result.stdout.trimEnd());
}
if (result.stderr.trim()) {
output.appendLine(result.stderr.trimEnd());
}
if (result.code === 0) {
const index = vscode.Uri.joinPath(folder.uri, outDir, "index.md");
try {
const doc = await vscode.workspace.openTextDocument(index);
await vscode.window.showTextDocument(doc, { preview: true });
} catch {
void vscode.window.showInformationMessage(`Marqdo catalog written to ${outDir}`);
}
} else {
void vscode.window.showErrorMessage("Marqdo catalog failed (see Output)");
}
}
+424
View File
@@ -0,0 +1,424 @@
import * as vscode from "vscode";
import * as fs from "fs";
import * as path from "path";
import * as os from "os";
import { spawnSync } from "child_process";
import { probeMarqdo } from "./cli";
const REPO = "cflmy/marqdo";
const SKIP_KEY = "marqdo.skipInstallPrompt";
const MANAGED_DIR = "cli";
export type InstallStatus = {
cliOk: boolean;
libOk: boolean;
version?: string;
cliPath?: string;
libRoot?: string;
detail: string;
};
type GhAsset = { name: string; browser_download_url: string };
type GhRelease = {
tag_name: string;
html_url: string;
assets: GhAsset[];
};
function cfg() {
return vscode.workspace.getConfiguration("marqdo");
}
export function managedRoot(context: vscode.ExtensionContext): string {
return path.join(context.globalStorageUri.fsPath, MANAGED_DIR);
}
export function managedExePath(context: vscode.ExtensionContext): string {
const name = process.platform === "win32" ? "marqdo.exe" : "marqdo";
return path.join(managedRoot(context), name);
}
export function managedLibRoot(context: vscode.ExtensionContext): string {
// Release zip layout: marqdo.exe + lib/… → MARQDO_LIB can be the dir that contains lib/, or lib itself.
// load.rs: root.join(remainder) and root.join("lib").join(remainder)
return managedRoot(context);
}
/** Prefer explicit setting, then managed install, then PATH. */
export function resolveCliPath(context?: vscode.ExtensionContext): string {
const setting = cfg().get<string>("cliPath")?.trim() || "marqdo";
if (setting !== "marqdo") {
return setting;
}
if (context) {
const managed = managedExePath(context);
if (fs.existsSync(managed)) {
return managed;
}
}
const stored = cfg().get<string>("managedCliPath")?.trim();
if (stored && fs.existsSync(stored)) {
return stored;
}
return "marqdo";
}
export function resolveLibEnv(context?: vscode.ExtensionContext): string | undefined {
const setting = cfg().get<string>("libPath")?.trim();
if (setting) {
return setting;
}
if (context) {
const root = managedLibRoot(context);
if (fs.existsSync(path.join(root, "lib")) || looksLikeLibRoot(root)) {
return root;
}
}
return undefined;
}
function looksLikeLibRoot(root: string): boolean {
return (
fs.existsSync(path.join(root, "math.mq.md")) ||
fs.existsSync(path.join(root, "text.mq.md")) ||
fs.existsSync(path.join(root, "lib", "math.mq.md"))
);
}
function findExeDir(cliPath: string): string | undefined {
if (cliPath.includes(path.sep) || cliPath.includes("/") || /\.exe$/i.test(cliPath)) {
if (fs.existsSync(cliPath)) {
return path.dirname(cliPath);
}
}
// Resolve via where/which
const cmd = process.platform === "win32" ? "where" : "which";
const r = spawnSync(cmd, [cliPath === "marqdo" && process.platform === "win32" ? "marqdo.exe" : cliPath], {
encoding: "utf8",
shell: true,
});
const first = (r.stdout || "")
.split(/\r?\n/)
.map((s) => s.trim())
.find((s) => s.length > 0);
if (first && fs.existsSync(first)) {
return path.dirname(first);
}
return undefined;
}
function stdlibPresent(cliPath: string, context?: vscode.ExtensionContext): { ok: boolean; root?: string } {
const envLib = process.env.MARQDO_LIB;
if (envLib && looksLikeLibRoot(envLib)) {
return { ok: true, root: envLib };
}
const configured = resolveLibEnv(context);
if (configured && looksLikeLibRoot(configured)) {
return { ok: true, root: configured };
}
const dir = findExeDir(cliPath);
if (dir) {
if (looksLikeLibRoot(dir) || looksLikeLibRoot(path.join(dir, "lib"))) {
return { ok: true, root: dir };
}
}
// Workspace ./lib
const ws = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
if (ws && looksLikeLibRoot(path.join(ws, "lib"))) {
return { ok: true, root: path.join(ws, "lib") };
}
return { ok: false };
}
export function checkInstallStatus(context: vscode.ExtensionContext): InstallStatus {
const cliPath = resolveCliPath(context);
const probe = probeMarqdo(cliPath);
if (!probe.ok) {
return {
cliOk: false,
libOk: false,
cliPath,
detail: probe.detail,
};
}
const lib = stdlibPresent(cliPath, context);
return {
cliOk: true,
libOk: lib.ok,
version: probe.version,
cliPath,
libRoot: lib.root,
detail: lib.ok
? `CLI ${probe.version}; stdlib at ${lib.root}`
: `CLI ${probe.version}; stdlib missing (no lib/ next to binary, no MARQDO_LIB)`,
};
}
function rustTargetTriple(): string | undefined {
const { platform, arch } = process;
if (platform === "win32" && arch === "x64") {
return "x86_64-pc-windows-msvc";
}
if (platform === "linux" && arch === "x64") {
return "x86_64-unknown-linux-gnu";
}
if (platform === "darwin" && arch === "arm64") {
return "aarch64-apple-darwin";
}
if (platform === "darwin" && arch === "x64") {
return "x86_64-apple-darwin";
}
return undefined;
}
async function fetchLatestRelease(): Promise<GhRelease> {
const res = await fetch(`https://api.github.com/repos/${REPO}/releases/latest`, {
headers: {
Accept: "application/vnd.github+json",
"User-Agent": "marqdo-vscode-extension",
},
});
if (!res.ok) {
throw new Error(`GitHub releases/latest HTTP ${res.status}`);
}
return (await res.json()) as GhRelease;
}
async function downloadToFile(url: string, dest: string, onProgress?: (msg: string) => void): Promise<void> {
onProgress?.(`Downloading ${path.basename(dest)}…`);
const res = await fetch(url, {
headers: { "User-Agent": "marqdo-vscode-extension", Accept: "application/octet-stream" },
redirect: "follow",
});
if (!res.ok) {
throw new Error(`Download failed HTTP ${res.status}: ${url}`);
}
const buf = Buffer.from(await res.arrayBuffer());
fs.mkdirSync(path.dirname(dest), { recursive: true });
fs.writeFileSync(dest, buf);
}
function extractZip(zipPath: string, destDir: string): void {
fs.mkdirSync(destDir, { recursive: true });
if (process.platform === "win32") {
const ps = `Expand-Archive -LiteralPath '${zipPath.replace(/'/g, "''")}' -DestinationPath '${destDir.replace(/'/g, "''")}' -Force`;
const r = spawnSync("powershell", ["-NoProfile", "-Command", ps], { encoding: "utf8" });
if (r.status !== 0) {
throw new Error(r.stderr || r.stdout || `Expand-Archive exit ${r.status}`);
}
return;
}
const r = spawnSync("unzip", ["-o", zipPath, "-d", destDir], { encoding: "utf8" });
if (r.status !== 0) {
throw new Error(r.stderr || r.stdout || `unzip exit ${r.status}`);
}
}
function pickBundleAsset(release: GhRelease, triple: string): GhAsset | undefined {
const zipName = `marqdo-${release.tag_name.replace(/^v/, "")}-${triple}.zip`;
return (
release.assets.find((a) => a.name === zipName) ||
release.assets.find(
(a) => a.name.endsWith(`-${triple}.zip`) && !a.name.includes("stdlib")
)
);
}
function pickStdlibAsset(release: GhRelease): GhAsset | undefined {
return release.assets.find((a) => a.name.includes("stdlib") && a.name.endsWith(".zip"));
}
async function applyManagedPaths(context: vscode.ExtensionContext, exe: string): Promise<void> {
await cfg().update("cliPath", exe, vscode.ConfigurationTarget.Global);
await cfg().update("managedCliPath", exe, vscode.ConfigurationTarget.Global);
await cfg().update("libPath", managedLibRoot(context), vscode.ConfigurationTarget.Global);
}
/**
* Download recommended release bundle (exe + lib/) into extension globalStorage.
*/
export async function installFromGitHub(
context: vscode.ExtensionContext,
output: vscode.OutputChannel,
mode: "bundle" | "stdlib" = "bundle"
): Promise<InstallStatus> {
const triple = rustTargetTriple();
output.show(true);
return vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: "Marqdo",
cancellable: false,
},
async (progress) => {
progress.report({ message: "Fetching latest release…" });
output.appendLine(`Fetching https://github.com/${REPO}/releases/latest`);
const release = await fetchLatestRelease();
output.appendLine(`Latest: ${release.tag_name}`);
const destRoot = managedRoot(context);
fs.mkdirSync(destRoot, { recursive: true });
const tmp = path.join(os.tmpdir(), `marqdo-ext-${Date.now()}`);
fs.mkdirSync(tmp, { recursive: true });
try {
if (mode === "bundle") {
if (!triple) {
throw new Error(
`No prebuilt bundle for ${process.platform}/${process.arch}. Open ${release.html_url} or build from source.`
);
}
const asset = pickBundleAsset(release, triple);
if (!asset) {
throw new Error(
`No asset for ${triple} in ${release.tag_name}. Available: ${release.assets
.map((a) => a.name)
.join(", ") || "(none)"}. See ${release.html_url}`
);
}
const zipPath = path.join(tmp, asset.name);
progress.report({ message: `Downloading ${asset.name}…` });
await downloadToFile(asset.browser_download_url, zipPath, (m) => output.appendLine(m));
progress.report({ message: "Extracting (CLI + stdlib)…" });
// Clear previous managed install
fs.rmSync(destRoot, { recursive: true, force: true });
fs.mkdirSync(destRoot, { recursive: true });
extractZip(zipPath, destRoot);
output.appendLine(`Extracted to ${destRoot}`);
} else {
const asset = pickStdlibAsset(release);
if (!asset) {
throw new Error(`No stdlib zip in ${release.tag_name}. See ${release.html_url}`);
}
const zipPath = path.join(tmp, asset.name);
progress.report({ message: `Downloading ${asset.name}…` });
await downloadToFile(asset.browser_download_url, zipPath, (m) => output.appendLine(m));
progress.report({ message: "Extracting stdlib…" });
extractZip(zipPath, destRoot);
output.appendLine(`Stdlib extracted to ${destRoot}`);
}
const exe = managedExePath(context);
if (mode === "bundle" && !fs.existsSync(exe)) {
// Some zips might nest a folder
const nested = findFileRecursive(destRoot, process.platform === "win32" ? "marqdo.exe" : "marqdo");
if (nested) {
// Flatten: move exe+lib up if needed is complex; just point cliPath at nested
await cfg().update("cliPath", nested, vscode.ConfigurationTarget.Global);
await cfg().update("managedCliPath", nested, vscode.ConfigurationTarget.Global);
const libCandidate = path.dirname(nested);
await cfg().update("libPath", libCandidate, vscode.ConfigurationTarget.Global);
} else {
throw new Error(`Extracted archive but ${exe} not found`);
}
} else if (mode === "bundle") {
await applyManagedPaths(context, exe);
} else {
await cfg().update("libPath", managedLibRoot(context), vscode.ConfigurationTarget.Global);
}
// chmod +x on unix
if (process.platform !== "win32" && fs.existsSync(exe)) {
fs.chmodSync(exe, 0o755);
}
const status = checkInstallStatus(context);
output.appendLine(status.detail);
if (status.cliOk && status.libOk) {
void vscode.window.showInformationMessage(
`Marqdo installed (${status.version}). Stdlib ready.`
);
} else if (status.cliOk && !status.libOk) {
void vscode.window.showWarningMessage(
`Marqdo CLI ok but stdlib still missing. Try “Marqdo: Install / Repair CLI”.`
);
}
return status;
} finally {
fs.rmSync(tmp, { recursive: true, force: true });
}
}
);
}
function findFileRecursive(root: string, name: string): string | undefined {
const stack = [root];
while (stack.length) {
const dir = stack.pop()!;
let entries: fs.Dirent[];
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
continue;
}
for (const e of entries) {
const p = path.join(dir, e.name);
if (e.isDirectory()) {
stack.push(p);
} else if (e.name === name) {
return p;
}
}
}
return undefined;
}
export async function promptIfNeeded(
context: vscode.ExtensionContext,
output: vscode.OutputChannel
): Promise<void> {
if (cfg().get<boolean>("autoInstall.checkOnStartup") === false) {
return;
}
if (context.globalState.get<boolean>(SKIP_KEY)) {
return;
}
const status = checkInstallStatus(context);
output.appendLine(`[install] ${status.detail}`);
if (status.cliOk && status.libOk) {
return;
}
let message: string;
let primary: string;
if (!status.cliOk) {
message =
"Marqdo CLI not found. Download the official release (includes standard library) into the extension?";
primary = "Install CLI + stdlib";
} else {
message =
"Marqdo CLI found, but the standard library (lib/) is missing. Download stdlib into the extension?";
primary = "Install stdlib";
}
const choice = await vscode.window.showWarningMessage(
message,
primary,
"Open Releases",
"Don't ask again"
);
if (choice === primary) {
try {
await installFromGitHub(context, output, status.cliOk ? "stdlib" : "bundle");
} catch (e) {
const err = e instanceof Error ? e.message : String(e);
output.appendLine(`[install] ${err}`);
const open = await vscode.window.showErrorMessage(`Marqdo install failed: ${err}`, "Open Releases");
if (open) {
await vscode.env.openExternal(vscode.Uri.parse(`https://github.com/${REPO}/releases`));
}
}
} else if (choice === "Open Releases") {
await vscode.env.openExternal(vscode.Uri.parse(`https://github.com/${REPO}/releases`));
} else if (choice === "Don't ask again") {
await context.globalState.update(SKIP_KEY, true);
}
}
export async function resetSkipPrompt(context: vscode.ExtensionContext): Promise<void> {
await context.globalState.update(SKIP_KEY, undefined);
}