From e34000877486d1673f3121922ab53db33fd88af9 Mon Sep 17 00:00:00 2001 From: Chrison Simtian Date: Mon, 16 Nov 2026 12:41:15 +1300 Subject: [PATCH 1/3] Offer to migrate a NUKE build from the command palette MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add Fallout: Migrate from NUKE… to run fallout-migrate in the terminal, dry run first. Detect an unmigrated NUKE repo, show a one-time prompt and a welcome link in the empty Build views, and offer to install the tool when it is missing. --- AGENTS.md | 1 + README.md | 4 ++ package.json | 19 ++++++++- src/extension.ts | 18 ++++++++ src/migrate.ts | 105 +++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 146 insertions(+), 1 deletion(-) create mode 100644 src/migrate.ts diff --git a/AGENTS.md b/AGENTS.md index 90a55f5..4f4873c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -68,6 +68,7 @@ Compilation is delegated to the project's own npm scripts rather than reimplemen - **[`src/model.ts`](src/model.ts)** — the logic layer, near-free of UI: graph discovery (`findGraphFile` probes `.fallout/temp` then `.nuke/temp` across workspace folders), parsing, `checkCompatibility`, and `toMermaid`. The schema `version` is a **hard gate**; the extension-vs-framework `major.minor` comparison is a **soft warning**, deduplicated via a module-level `warned` set. - **[`src/extension.ts`](src/extension.ts)** — tree data provider plus command registration. Relations (`dependsOn`, `after`, `triggeredBy`, `triggers`) render as recursively expandable children. A `**/build-graph.json` watcher refreshes both tree and panel; parse failures during refresh are swallowed deliberately, because the build may be mid-write and the next watcher event re-reads it. +- **[`src/migrate.ts`](src/migrate.ts)** — NUKE detection (`.nuke/` or `Nuke.*` in `build/_build.csproj`, and no `.fallout/`), the `Fallout: Migrate from NUKE…` command, and the one-time prompt. Drives the `fallout-migrate` global tool in a terminal; preview (`--dry-run`) always comes before the real run. - **[`src/goToTarget.ts`](src/goToTarget.ts)** — C# workspace symbol provider first (precise, needs Roslyn warmed up), regex scan over `**/*.cs` as fallback. `declaredIn` from the graph disambiguates same-named targets declared across component interfaces. - **[`src/graphPanel.ts`](src/graphPanel.ts)** — singleton webview, CSP-locked with a nonce, `localResourceRoots` scoped to Mermaid's `dist`. Talks to the page via `ready` / `graph` / `run` messages. diff --git a/README.md b/README.md index 778a389..9e42350 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,10 @@ A form for the parameters and secrets your build takes: ![The Run Configuration view with a parameter and a secret](https://raw.githubusercontent.com/Fallout-build/Fallout.Extensions.VSCode/develop/.assets/screenshots/run-configuration.png) +### Migrate from NUKE + +Open a NUKE build and the extension offers to migrate it. **Fallout: Migrate from NUKE…** runs [`fallout-migrate`](https://github.com/Fallout-build/Fallout/blob/main/docs/Migration/from-nuke.md) in an integrated terminal: a dry run first, so you can read what would change, then the real run. If the tool is missing, the extension offers to install it (`dotnet tool install -g Fallout.Migrate`). + ### Go to definition Jump straight to the `Target X => …` C# declaration. Uses the C# language service when it's warmed up and falls back to a workspace scan, and disambiguates by declaring type when several components declare a target of the same name. diff --git a/package.json b/package.json index d23eba5..530bd9c 100644 --- a/package.json +++ b/package.json @@ -39,7 +39,9 @@ "onView:fallout.deployment", "onView:fallout.runConfig", "workspaceContains:**/.fallout/temp/build-graph.json", - "workspaceContains:**/.nuke/temp/build-graph.json" + "workspaceContains:**/.nuke/temp/build-graph.json", + "workspaceContains:**/.nuke/parameters.json", + "workspaceContains:**/.nuke/build.schema.json" ], "contributes": { "viewsContainers": { @@ -103,6 +105,16 @@ "view": "fallout.buildExplorer", "contents": "No Fallout build graph found in this workspace.\nRun the build once to generate `build-graph.json`, then refresh.\n[Plan build (dry run)](command:fallout.planTarget)" }, + { + "view": "fallout.build", + "contents": "This looks like a NUKE build. Fallout can migrate it for you.\n[Migrate from NUKE…](command:fallout.migrateFromNuke)", + "when": "fallout.nukeRepo" + }, + { + "view": "fallout.buildExplorer", + "contents": "This looks like a NUKE build. Fallout can migrate it for you.\n[Migrate from NUKE…](command:fallout.migrateFromNuke)", + "when": "fallout.nukeRepo" + }, { "view": "fallout.deployment", "contents": "No deployment graph yet.\nThe continuous-delivery model (channels → environments → targets) is emitted by a later Fallout build (ADR-0009). This view lights up once the framework writes a `deployment-graph.json`." @@ -144,6 +156,11 @@ "title": "Plan (dry run)", "category": "Fallout", "icon": "$(list-tree)" + }, + { + "command": "fallout.migrateFromNuke", + "title": "Migrate from NUKE…", + "category": "Fallout" } ], "menus": { diff --git a/src/extension.ts b/src/extension.ts index 8eb78fe..ac40e71 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -2,6 +2,7 @@ import * as vscode from 'vscode'; import { BuildGraph, GraphSource, RELATIONS, Relation, Target, checkCompatibility, findGraphFile, hasRelations, loadGraph, relatedTargets, sortTargets } from './model'; import { GraphPanel } from './graphPanel'; import { goToTarget } from './goToTarget'; +import { isNukeRepo, migrateFromNuke, promptIfNukeRepo } from './migrate'; import { RunConfigStore, RunConfigViewProvider } from './runConfig'; const RELATION_LABELS: Record = { @@ -216,6 +217,23 @@ export function activate(context: vscode.ExtensionContext): void { } }), ); + + // Drives the "migrate from NUKE" welcome content in the empty Build views. + const updateNukeContext = () => void vscode.commands.executeCommand( + 'setContext', 'fallout.nukeRepo', (vscode.workspace.workspaceFolders ?? []).some(f => isNukeRepo(f.uri.fsPath))); + updateNukeContext(); + + // The migrator renames .nuke/ to .fallout/ - re-evaluate the NUKE content when that lands. + const falloutDirWatcher = vscode.workspace.createFileSystemWatcher('**/.fallout'); + falloutDirWatcher.onDidCreate(() => { updateNukeContext(); provider.refresh(); }); + falloutDirWatcher.onDidDelete(() => { updateNukeContext(); provider.refresh(); }); + + context.subscriptions.push( + falloutDirWatcher, + vscode.commands.registerCommand('fallout.migrateFromNuke', () => migrateFromNuke(workspaceRoot())), + ); + + void promptIfNukeRepo(context, workspaceRoot()); } export function deactivate(): void {} diff --git a/src/migrate.ts b/src/migrate.ts new file mode 100644 index 0000000..cdbb99a --- /dev/null +++ b/src/migrate.ts @@ -0,0 +1,105 @@ +import * as vscode from 'vscode'; +import * as fs from 'fs'; +import * as path from 'path'; +import { execFile } from 'child_process'; + +const TOOL = 'fallout-migrate'; +const INSTALL = 'dotnet tool install -g Fallout.Migrate'; +const DISMISSED_KEY = 'fallout.migratePromptDismissed'; +const MIGRATION_GUIDE = 'https://github.com/Fallout-build/Fallout/blob/main/docs/Migration/from-nuke.md'; + +/** + * A NUKE build that has not been migrated: it still has a `.nuke/` directory (the migrator renames it + * to `.fallout/`), or its build project still references `Nuke.*`, and there is no `.fallout/` yet. + */ +export function isNukeRepo(root: string): boolean { + if (fs.existsSync(path.join(root, '.fallout'))) { + return false; + } + if (fs.existsSync(path.join(root, '.nuke'))) { + return true; + } + try { + return /Include="Nuke\./.test(fs.readFileSync(path.join(root, 'build', '_build.csproj'), 'utf8')); + } catch { + return false; + } +} + +/** Resolves whether the migrator is on PATH; it is a dotnet global tool, so a missing tool is ENOENT. */ +function isToolInstalled(): Promise { + return new Promise(resolve => { + execFile(TOOL, ['--help'], { timeout: 15000 }, error => { + resolve(!(error && (error as NodeJS.ErrnoException).code === 'ENOENT')); + }); + }); +} + +function runInMigrateTerminal(root: string, commandLine: string): void { + let terminal = vscode.window.terminals.find(t => t.name === 'Fallout Migrate'); + terminal ??= vscode.window.createTerminal({ name: 'Fallout Migrate', cwd: root }); + terminal.show(); + terminal.sendText(commandLine); +} + +/** + * `Fallout: Migrate from NUKE…` — preview with `--dry-run`, then migrate once the user confirms. + * Both run in the integrated terminal because the tool prompts before it changes anything. + */ +export async function migrateFromNuke(root: string | undefined): Promise { + if (!root) { + void vscode.window.showInformationMessage('Fallout: open the NUKE build\'s repository folder first.'); + return; + } + + if (!(await isToolInstalled())) { + const choice = await vscode.window.showInformationMessage( + `Fallout: the migration tool (${TOOL}) is not installed.`, + `Install and preview`, 'Open guide'); + if (choice === 'Open guide') { + void vscode.env.openExternal(vscode.Uri.parse(MIGRATION_GUIDE)); + } else if (choice) { + runInMigrateTerminal(root, `${INSTALL} && ${TOOL} --dry-run`); + await offerMigration(root); + } + return; + } + + const choice = await vscode.window.showInformationMessage( + 'Fallout: migrate this NUKE build to Fallout? A preview changes nothing.', + 'Preview (dry run)', 'Migrate now'); + if (choice === 'Preview (dry run)') { + runInMigrateTerminal(root, `${TOOL} --dry-run`); + await offerMigration(root); + } else if (choice === 'Migrate now') { + runInMigrateTerminal(root, TOOL); + } +} + +// The preview runs in a terminal we cannot await, so ask once the user has had a chance to read it. +async function offerMigration(root: string): Promise { + const choice = await vscode.window.showInformationMessage( + 'Fallout: preview is running in the "Fallout Migrate" terminal. Migrate when you have read it.', + 'Migrate now'); + if (choice === 'Migrate now') { + runInMigrateTerminal(root, TOOL); + } +} + +/** One-time prompt in an unmigrated NUKE repo; "Don't ask again" is remembered per workspace. */ +export async function promptIfNukeRepo( + context: vscode.ExtensionContext, + root: string | undefined, +): Promise { + if (!root || !isNukeRepo(root) || context.workspaceState.get(DISMISSED_KEY)) { + return; + } + const choice = await vscode.window.showInformationMessage( + 'This looks like a NUKE build. Migrate it to Fallout?', + 'Migrate…', 'Don\'t ask again'); + if (choice === 'Migrate…') { + await migrateFromNuke(root); + } else if (choice === 'Don\'t ask again') { + await context.workspaceState.update(DISMISSED_KEY, true); + } +} From 09a58de11e4f20261c5be60cacddcb9df32236df Mon Sep 17 00:00:00 2001 From: Chrison Simtian Date: Tue, 17 Nov 2026 09:11:25 +1300 Subject: [PATCH 2/3] Make the NUKE migration preview mandatory and harden the flow - Run the dry run first, wait for it, and only then offer the real run - Install with `dotnet tool update -g` and find the tool on disk, not PATH - Use a fresh terminal per run and a busy guard against overlapping runs - Pick the NUKE build across all workspace folders; prompt once per repo - Widen detection: quote styles, Update/Remove, nested repos, non-empty .nuke - Hide the generic welcome text in NUKE repos - Refresh the tree when the migration terminal closes --- package.json | 9 +- src/extension.ts | 21 ++-- src/migrate.ts | 250 +++++++++++++++++++++++++++++++++++------------ 3 files changed, 204 insertions(+), 76 deletions(-) diff --git a/package.json b/package.json index 530bd9c..e035f79 100644 --- a/package.json +++ b/package.json @@ -41,7 +41,8 @@ "workspaceContains:**/.fallout/temp/build-graph.json", "workspaceContains:**/.nuke/temp/build-graph.json", "workspaceContains:**/.nuke/parameters.json", - "workspaceContains:**/.nuke/build.schema.json" + "workspaceContains:**/.nuke/build.schema.json", + "workspaceContains:**/_build.csproj" ], "contributes": { "viewsContainers": { @@ -99,11 +100,13 @@ "viewsWelcome": [ { "view": "fallout.build", - "contents": "No Fallout build graph found in this workspace.\nRun the build once to generate `build-graph.json`, then refresh.\n[Plan build (dry run)](command:fallout.planTarget)" + "contents": "No Fallout build graph found in this workspace.\nRun the build once to generate `build-graph.json`, then refresh.\n[Plan build (dry run)](command:fallout.planTarget)", + "when": "!fallout.nukeRepo" }, { "view": "fallout.buildExplorer", - "contents": "No Fallout build graph found in this workspace.\nRun the build once to generate `build-graph.json`, then refresh.\n[Plan build (dry run)](command:fallout.planTarget)" + "contents": "No Fallout build graph found in this workspace.\nRun the build once to generate `build-graph.json`, then refresh.\n[Plan build (dry run)](command:fallout.planTarget)", + "when": "!fallout.nukeRepo" }, { "view": "fallout.build", diff --git a/src/extension.ts b/src/extension.ts index ac40e71..83e4a70 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -2,7 +2,7 @@ import * as vscode from 'vscode'; import { BuildGraph, GraphSource, RELATIONS, Relation, Target, checkCompatibility, findGraphFile, hasRelations, loadGraph, relatedTargets, sortTargets } from './model'; import { GraphPanel } from './graphPanel'; import { goToTarget } from './goToTarget'; -import { isNukeRepo, migrateFromNuke, promptIfNukeRepo } from './migrate'; +import { hasNukeRepo, migrateFromNuke, promptIfNukeRepo } from './migrate'; import { RunConfigStore, RunConfigViewProvider } from './runConfig'; const RELATION_LABELS: Record = { @@ -219,21 +219,26 @@ export function activate(context: vscode.ExtensionContext): void { ); // Drives the "migrate from NUKE" welcome content in the empty Build views. - const updateNukeContext = () => void vscode.commands.executeCommand( - 'setContext', 'fallout.nukeRepo', (vscode.workspace.workspaceFolders ?? []).some(f => isNukeRepo(f.uri.fsPath))); + const updateNukeContext = () => void vscode.commands.executeCommand('setContext', 'fallout.nukeRepo', hasNukeRepo()); + const afterMigration = () => { updateNukeContext(); provider.refresh(); }; updateNukeContext(); - // The migrator renames .nuke/ to .fallout/ - re-evaluate the NUKE content when that lands. + // The migrator renames .nuke/ to .fallout/. The terminal closing is the primary signal; the watchers + // also catch a rename done outside the extension. const falloutDirWatcher = vscode.workspace.createFileSystemWatcher('**/.fallout'); - falloutDirWatcher.onDidCreate(() => { updateNukeContext(); provider.refresh(); }); - falloutDirWatcher.onDidDelete(() => { updateNukeContext(); provider.refresh(); }); + falloutDirWatcher.onDidCreate(afterMigration); + falloutDirWatcher.onDidDelete(afterMigration); + const nukeDirWatcher = vscode.workspace.createFileSystemWatcher('**/.nuke'); + nukeDirWatcher.onDidCreate(afterMigration); + nukeDirWatcher.onDidDelete(afterMigration); context.subscriptions.push( falloutDirWatcher, - vscode.commands.registerCommand('fallout.migrateFromNuke', () => migrateFromNuke(workspaceRoot())), + nukeDirWatcher, + vscode.commands.registerCommand('fallout.migrateFromNuke', () => migrateFromNuke(afterMigration)), ); - void promptIfNukeRepo(context, workspaceRoot()); + void promptIfNukeRepo(context, afterMigration); } export function deactivate(): void {} diff --git a/src/migrate.ts b/src/migrate.ts index cdbb99a..4fae4d5 100644 --- a/src/migrate.ts +++ b/src/migrate.ts @@ -1,105 +1,225 @@ import * as vscode from 'vscode'; import * as fs from 'fs'; +import * as os from 'os'; import * as path from 'path'; -import { execFile } from 'child_process'; +import { spawn } from 'child_process'; const TOOL = 'fallout-migrate'; -const INSTALL = 'dotnet tool install -g Fallout.Migrate'; -const DISMISSED_KEY = 'fallout.migratePromptDismissed'; +const PACKAGE = 'Fallout.Migrate'; +const PROMPTED_KEY = 'fallout.migratePrompted'; const MIGRATION_GUIDE = 'https://github.com/Fallout-build/Fallout/blob/main/docs/Migration/from-nuke.md'; +const SKIP_DIRS = new Set(['node_modules', '.git', 'bin', 'obj', '.vs', 'out']); +const MAX_DEPTH = 3; +const NUKE_REFERENCE = /\b(?:Include|Update|Remove)\s*=\s*["']Nuke\./i; -/** - * A NUKE build that has not been migrated: it still has a `.nuke/` directory (the migrator renames it - * to `.fallout/`), or its build project still references `Nuke.*`, and there is no `.fallout/` yet. - */ -export function isNukeRepo(root: string): boolean { - if (fs.existsSync(path.join(root, '.fallout'))) { +let output: vscode.OutputChannel | undefined; +let busy = false; + +const channel = (): vscode.OutputChannel => (output ??= vscode.window.createOutputChannel('Fallout Migrate')); + +function isDirectory(p: string): boolean { + try { + return fs.statSync(p).isDirectory(); + } catch { return false; } - if (fs.existsSync(path.join(root, '.nuke'))) { - return true; +} + +/** The migrator renames a `.nuke/` directory; a legacy single file or an empty folder is not worth migrating. */ +function hasNukeDirectory(dir: string): boolean { + const nuke = path.join(dir, '.nuke'); + try { + return isDirectory(nuke) && fs.readdirSync(nuke).length > 0; + } catch { + return false; } +} + +function referencesNuke(csproj: string): boolean { try { - return /Include="Nuke\./.test(fs.readFileSync(path.join(root, 'build', '_build.csproj'), 'utf8')); + return NUKE_REFERENCE.test(fs.readFileSync(csproj, 'utf8')); } catch { return false; } } -/** Resolves whether the migrator is on PATH; it is a dotnet global tool, so a missing tool is ENOENT. */ -function isToolInstalled(): Promise { +/** + * Unmigrated NUKE repositories at or below `folder` (a few levels deep, for nested repos). + * A repository counts when it has a non-empty `.nuke/` directory, or a `_build.csproj` that still + * references `Nuke.*` (any quote style, `Include`/`Update`/`Remove`), and it has no `.fallout/` yet. + */ +export function findNukeRoots(folder: string): string[] { + const roots = new Set(); + const walk = (dir: string, depth: number): void => { + if (isDirectory(path.join(dir, '.fallout'))) { + return; + } + if (hasNukeDirectory(dir)) { + roots.add(dir); + } + let entries: fs.Dirent[]; + try { + entries = fs.readdirSync(dir, { withFileTypes: true }); + } catch { + return; + } + if (entries.some(e => e.isFile() && e.name === '_build.csproj') && referencesNuke(path.join(dir, '_build.csproj'))) { + roots.add(path.basename(dir) === 'build' ? path.dirname(dir) : dir); + } + if (depth >= MAX_DEPTH) { + return; + } + for (const e of entries) { + if (e.isDirectory() && !e.name.startsWith('.') && !SKIP_DIRS.has(e.name)) { + walk(path.join(dir, e.name), depth + 1); + } + } + }; + walk(folder, 0); + // A root that also lost its own .fallout/ check above may have been added from a child; drop migrated ones. + return [...roots].filter(r => !isDirectory(path.join(r, '.fallout'))); +} + +/** True when any workspace folder holds an unmigrated NUKE build. */ +export function hasNukeRepo(): boolean { + return (vscode.workspace.workspaceFolders ?? []).some(f => findNukeRoots(f.uri.fsPath).length > 0); +} + +function allNukeRoots(): string[] { + return (vscode.workspace.workspaceFolders ?? []).flatMap(f => findNukeRoots(f.uri.fsPath)); +} + +async function pickRoot(): Promise { + const roots = allNukeRoots(); + if (roots.length === 0) { + void vscode.window.showInformationMessage('Fallout: no NUKE build found in this workspace.'); + return undefined; + } + if (roots.length === 1) { + return roots[0]; + } + return vscode.window.showQuickPick(roots, { placeHolder: 'Which NUKE build do you want to migrate?' }); +} + +/** Absolute path first: a fresh global install is not on the PATH of an already-running VS Code. */ +function toolPathOnDisk(): string | undefined { + const home = process.env.DOTNET_CLI_HOME ?? os.homedir(); + const exe = path.join(home, '.dotnet', 'tools', process.platform === 'win32' ? `${TOOL}.exe` : TOOL); + return fs.existsSync(exe) ? exe : undefined; +} + +function run(command: string, args: string[]): Promise { return new Promise(resolve => { - execFile(TOOL, ['--help'], { timeout: 15000 }, error => { - resolve(!(error && (error as NodeJS.ErrnoException).code === 'ENOENT')); + const log = channel(); + log.appendLine(`> ${command} ${args.join(' ')}`); + const child = spawn(command, args, { windowsHide: true }); + child.stdout.on('data', d => log.append(String(d))); + child.stderr.on('data', d => log.append(String(d))); + child.on('error', e => { + log.appendLine(`error: ${e.message}`); + resolve(-1); }); + child.on('close', code => resolve(code ?? -1)); }); } -function runInMigrateTerminal(root: string, commandLine: string): void { - let terminal = vscode.window.terminals.find(t => t.name === 'Fallout Migrate'); - terminal ??= vscode.window.createTerminal({ name: 'Fallout Migrate', cwd: root }); - terminal.show(); - terminal.sendText(commandLine); +async function resolveTool(): Promise { + const onDisk = toolPathOnDisk(); + if (onDisk) { + return onDisk; + } + // Maybe on PATH somewhere else (custom tool path): ENOENT means it is not. + return (await run(TOOL, ['--help'])) === -1 ? undefined : TOOL; +} + +async function withProgress(title: string, task: () => Promise): Promise { + return vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title }, task); +} + +function openGuide(): void { + void vscode.env.openExternal(vscode.Uri.parse(MIGRATION_GUIDE)); } /** - * `Fallout: Migrate from NUKE…` — preview with `--dry-run`, then migrate once the user confirms. - * Both run in the integrated terminal because the tool prompts before it changes anything. + * `Fallout: Migrate from NUKE…`: install the tool if needed, run `--dry-run` and wait for it, + * and only then offer the real run. The preview is mandatory and always first. The real run goes + * in a fresh terminal because the tool asks "Continue?" itself. */ -export async function migrateFromNuke(root: string | undefined): Promise { - if (!root) { - void vscode.window.showInformationMessage('Fallout: open the NUKE build\'s repository folder first.'); +export async function migrateFromNuke(onFinished: () => void): Promise { + if (busy) { + void vscode.window.showInformationMessage('Fallout: a migration is already in progress.'); return; } + busy = true; + try { + const root = await pickRoot(); + if (!root) { + return; + } - if (!(await isToolInstalled())) { - const choice = await vscode.window.showInformationMessage( - `Fallout: the migration tool (${TOOL}) is not installed.`, - `Install and preview`, 'Open guide'); - if (choice === 'Open guide') { - void vscode.env.openExternal(vscode.Uri.parse(MIGRATION_GUIDE)); - } else if (choice) { - runInMigrateTerminal(root, `${INSTALL} && ${TOOL} --dry-run`); - await offerMigration(root); + let tool = await resolveTool(); + if (!tool) { + const choice = await vscode.window.showInformationMessage( + `Fallout: the migration tool (${TOOL}) is not installed.`, 'Install and preview', 'Open guide'); + if (choice === 'Open guide') { + openGuide(); + } + if (choice !== 'Install and preview') { + return; + } + // `update` installs when absent and upgrades when present, so it never fails on "already installed". + const code = await withProgress(`Installing ${PACKAGE}…`, () => run('dotnet', ['tool', 'update', '-g', PACKAGE])); + tool = code === 0 ? await resolveTool() : undefined; + if (!tool) { + channel().show(true); + void vscode.window.showErrorMessage( + code === 0 + ? `Fallout: ${PACKAGE} installed but ${TOOL} was not found. Restart VS Code and try again.` + : `Fallout: installing ${PACKAGE} failed. See the "Fallout Migrate" output.`); + return; + } } - return; - } - const choice = await vscode.window.showInformationMessage( - 'Fallout: migrate this NUKE build to Fallout? A preview changes nothing.', - 'Preview (dry run)', 'Migrate now'); - if (choice === 'Preview (dry run)') { - runInMigrateTerminal(root, `${TOOL} --dry-run`); - await offerMigration(root); - } else if (choice === 'Migrate now') { - runInMigrateTerminal(root, TOOL); - } -} + channel().clear(); + channel().show(true); + const previewCode = await withProgress('Previewing the NUKE migration…', () => run(tool, ['--dry-run', root])); + if (previewCode !== 0) { + void vscode.window.showErrorMessage('Fallout: the migration preview failed. See the "Fallout Migrate" output.'); + return; + } -// The preview runs in a terminal we cannot await, so ask once the user has had a chance to read it. -async function offerMigration(root: string): Promise { - const choice = await vscode.window.showInformationMessage( - 'Fallout: preview is running in the "Fallout Migrate" terminal. Migrate when you have read it.', - 'Migrate now'); - if (choice === 'Migrate now') { - runInMigrateTerminal(root, TOOL); + const choice = await vscode.window.showInformationMessage( + `Fallout: preview done, nothing changed (see the "Fallout Migrate" output). Migrate ${root}?`, + 'Migrate', 'Cancel'); + if (choice !== 'Migrate') { + return; + } + + // Fresh terminal, no shell: no quoting problems, no stray input into an earlier "Continue?" prompt. + const terminal = vscode.window.createTerminal({ name: 'Fallout Migrate', shellPath: tool, shellArgs: [root], cwd: root }); + const closed = vscode.window.onDidCloseTerminal(t => { + if (t === terminal) { + closed.dispose(); + onFinished(); + } + }); + terminal.show(); + } finally { + busy = false; } } -/** One-time prompt in an unmigrated NUKE repo; "Don't ask again" is remembered per workspace. */ -export async function promptIfNukeRepo( - context: vscode.ExtensionContext, - root: string | undefined, -): Promise { - if (!root || !isNukeRepo(root) || context.workspaceState.get(DISMISSED_KEY)) { +/** One-time prompt per NUKE repository, whatever the answer (closing the toast counts as "not now"). */ +export async function promptIfNukeRepo(context: vscode.ExtensionContext, onFinished: () => void): Promise { + const prompted = context.workspaceState.get(PROMPTED_KEY, []); + const roots = allNukeRoots().filter(r => !prompted.includes(r)); + if (roots.length === 0) { return; } + await context.workspaceState.update(PROMPTED_KEY, [...prompted, ...roots]); const choice = await vscode.window.showInformationMessage( - 'This looks like a NUKE build. Migrate it to Fallout?', - 'Migrate…', 'Don\'t ask again'); + 'This looks like a NUKE build. Migrate it to Fallout?', 'Migrate…', 'Not now'); if (choice === 'Migrate…') { - await migrateFromNuke(root); - } else if (choice === 'Don\'t ask again') { - await context.workspaceState.update(DISMISSED_KEY, true); + await migrateFromNuke(onFinished); } } From c37612f623d8200b0b8af4d039421361435b95fb Mon Sep 17 00:00:00 2001 From: Chrison Simtian Date: Tue, 17 Nov 2026 11:17:58 +1300 Subject: [PATCH 3/3] Test NUKE detection and the migration terminal - Move detection to a vscode-free src/nuke.ts and unit test it on temp repos - Extract openMigrationTerminal so an extension-host test can drive it with a stub tool - Fix the migration terminal never reporting it was done: it stays open after exit, so poll exitStatus as well as the close event --- AGENTS.md | 3 +- src/migrate.ts | 101 ++++++++----------------------- src/nuke.ts | 69 +++++++++++++++++++++ test/integration/migrate.test.ts | 62 +++++++++++++++++++ test/unit/nuke.test.ts | 91 ++++++++++++++++++++++++++++ 5 files changed, 250 insertions(+), 76 deletions(-) create mode 100644 src/nuke.ts create mode 100644 test/integration/migrate.test.ts create mode 100644 test/unit/nuke.test.ts diff --git a/AGENTS.md b/AGENTS.md index 4f4873c..7c425ec 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -68,7 +68,8 @@ Compilation is delegated to the project's own npm scripts rather than reimplemen - **[`src/model.ts`](src/model.ts)** — the logic layer, near-free of UI: graph discovery (`findGraphFile` probes `.fallout/temp` then `.nuke/temp` across workspace folders), parsing, `checkCompatibility`, and `toMermaid`. The schema `version` is a **hard gate**; the extension-vs-framework `major.minor` comparison is a **soft warning**, deduplicated via a module-level `warned` set. - **[`src/extension.ts`](src/extension.ts)** — tree data provider plus command registration. Relations (`dependsOn`, `after`, `triggeredBy`, `triggers`) render as recursively expandable children. A `**/build-graph.json` watcher refreshes both tree and panel; parse failures during refresh are swallowed deliberately, because the build may be mid-write and the next watcher event re-reads it. -- **[`src/migrate.ts`](src/migrate.ts)** — NUKE detection (`.nuke/` or `Nuke.*` in `build/_build.csproj`, and no `.fallout/`), the `Fallout: Migrate from NUKE…` command, and the one-time prompt. Drives the `fallout-migrate` global tool in a terminal; preview (`--dry-run`) always comes before the real run. +- **[`src/nuke.ts`](src/nuke.ts)** — vscode-free NUKE detection (`findNukeRoots`: a non-empty `.nuke/`, or a `_build.csproj` referencing `Nuke.*`, and no `.fallout/`; a few levels deep). +- **[`src/migrate.ts`](src/migrate.ts)** — the `Fallout: Migrate from NUKE…` command and the one-time prompt. Installs and drives the `fallout-migrate` global tool: the preview (`--dry-run`) runs first and is awaited, the real run goes in a fresh terminal (`openMigrationTerminal`). - **[`src/goToTarget.ts`](src/goToTarget.ts)** — C# workspace symbol provider first (precise, needs Roslyn warmed up), regex scan over `**/*.cs` as fallback. `declaredIn` from the graph disambiguates same-named targets declared across component interfaces. - **[`src/graphPanel.ts`](src/graphPanel.ts)** — singleton webview, CSP-locked with a nonce, `localResourceRoots` scoped to Mermaid's `dist`. Talks to the page via `ready` / `graph` / `run` messages. diff --git a/src/migrate.ts b/src/migrate.ts index 4fae4d5..c76ea8a 100644 --- a/src/migrate.ts +++ b/src/migrate.ts @@ -3,83 +3,18 @@ import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import { spawn } from 'child_process'; +import { findNukeRoots } from './nuke'; const TOOL = 'fallout-migrate'; const PACKAGE = 'Fallout.Migrate'; const PROMPTED_KEY = 'fallout.migratePrompted'; const MIGRATION_GUIDE = 'https://github.com/Fallout-build/Fallout/blob/main/docs/Migration/from-nuke.md'; -const SKIP_DIRS = new Set(['node_modules', '.git', 'bin', 'obj', '.vs', 'out']); -const MAX_DEPTH = 3; -const NUKE_REFERENCE = /\b(?:Include|Update|Remove)\s*=\s*["']Nuke\./i; let output: vscode.OutputChannel | undefined; let busy = false; const channel = (): vscode.OutputChannel => (output ??= vscode.window.createOutputChannel('Fallout Migrate')); -function isDirectory(p: string): boolean { - try { - return fs.statSync(p).isDirectory(); - } catch { - return false; - } -} - -/** The migrator renames a `.nuke/` directory; a legacy single file or an empty folder is not worth migrating. */ -function hasNukeDirectory(dir: string): boolean { - const nuke = path.join(dir, '.nuke'); - try { - return isDirectory(nuke) && fs.readdirSync(nuke).length > 0; - } catch { - return false; - } -} - -function referencesNuke(csproj: string): boolean { - try { - return NUKE_REFERENCE.test(fs.readFileSync(csproj, 'utf8')); - } catch { - return false; - } -} - -/** - * Unmigrated NUKE repositories at or below `folder` (a few levels deep, for nested repos). - * A repository counts when it has a non-empty `.nuke/` directory, or a `_build.csproj` that still - * references `Nuke.*` (any quote style, `Include`/`Update`/`Remove`), and it has no `.fallout/` yet. - */ -export function findNukeRoots(folder: string): string[] { - const roots = new Set(); - const walk = (dir: string, depth: number): void => { - if (isDirectory(path.join(dir, '.fallout'))) { - return; - } - if (hasNukeDirectory(dir)) { - roots.add(dir); - } - let entries: fs.Dirent[]; - try { - entries = fs.readdirSync(dir, { withFileTypes: true }); - } catch { - return; - } - if (entries.some(e => e.isFile() && e.name === '_build.csproj') && referencesNuke(path.join(dir, '_build.csproj'))) { - roots.add(path.basename(dir) === 'build' ? path.dirname(dir) : dir); - } - if (depth >= MAX_DEPTH) { - return; - } - for (const e of entries) { - if (e.isDirectory() && !e.name.startsWith('.') && !SKIP_DIRS.has(e.name)) { - walk(path.join(dir, e.name), depth + 1); - } - } - }; - walk(folder, 0); - // A root that also lost its own .fallout/ check above may have been added from a child; drop migrated ones. - return [...roots].filter(r => !isDirectory(path.join(r, '.fallout'))); -} - /** True when any workspace folder holds an unmigrated NUKE build. */ export function hasNukeRepo(): boolean { return (vscode.workspace.workspaceFolders ?? []).some(f => findNukeRoots(f.uri.fsPath).length > 0); @@ -140,6 +75,30 @@ function openGuide(): void { void vscode.env.openExternal(vscode.Uri.parse(MIGRATION_GUIDE)); } +/** + * Runs the migrator in a fresh terminal: no shell, so no quoting problems, and no stray input into an + * earlier "Continue?" prompt. `onFinished` fires once when the migrator exits. The terminal stays open + * after the process ends (it keeps the summary readable), so the close event alone is not enough: + * `exitStatus` is polled too, and whichever comes first wins. + */ +export function openMigrationTerminal(tool: string, args: string[], cwd: string, onFinished: () => void): vscode.Terminal { + const terminal = vscode.window.createTerminal({ name: 'Fallout Migrate', shellPath: tool, shellArgs: args, cwd }); + let done = false; + const finish = (): void => { + if (done) { + return; + } + done = true; + closed.dispose(); + clearInterval(poll); + onFinished(); + }; + const closed = vscode.window.onDidCloseTerminal(t => t === terminal && finish()); + const poll = setInterval(() => terminal.exitStatus !== undefined && finish(), 500); + terminal.show(); + return terminal; +} + /** * `Fallout: Migrate from NUKE…`: install the tool if needed, run `--dry-run` and wait for it, * and only then offer the real run. The preview is mandatory and always first. The real run goes @@ -195,15 +154,7 @@ export async function migrateFromNuke(onFinished: () => void): Promise { return; } - // Fresh terminal, no shell: no quoting problems, no stray input into an earlier "Continue?" prompt. - const terminal = vscode.window.createTerminal({ name: 'Fallout Migrate', shellPath: tool, shellArgs: [root], cwd: root }); - const closed = vscode.window.onDidCloseTerminal(t => { - if (t === terminal) { - closed.dispose(); - onFinished(); - } - }); - terminal.show(); + openMigrationTerminal(tool, [root], root, onFinished); } finally { busy = false; } diff --git a/src/nuke.ts b/src/nuke.ts new file mode 100644 index 0000000..5a95fdd --- /dev/null +++ b/src/nuke.ts @@ -0,0 +1,69 @@ +import * as fs from 'fs'; +import * as path from 'path'; + +const SKIP_DIRS = new Set(['node_modules', '.git', 'bin', 'obj', '.vs', 'out']); +const MAX_DEPTH = 3; +const NUKE_REFERENCE = /\b(?:Include|Update|Remove)\s*=\s*["']Nuke\./i; + +function isDirectory(p: string): boolean { + try { + return fs.statSync(p).isDirectory(); + } catch { + return false; + } +} + +/** The migrator renames a `.nuke/` directory; a legacy single file or an empty folder is not worth migrating. */ +function hasNukeDirectory(dir: string): boolean { + const nuke = path.join(dir, '.nuke'); + try { + return isDirectory(nuke) && fs.readdirSync(nuke).length > 0; + } catch { + return false; + } +} + +function referencesNuke(csproj: string): boolean { + try { + return NUKE_REFERENCE.test(fs.readFileSync(csproj, 'utf8')); + } catch { + return false; + } +} + +/** + * Unmigrated NUKE repositories at or below `folder` (a few levels deep, for nested repos). + * A repository counts when it has a non-empty `.nuke/` directory, or a `_build.csproj` that still + * references `Nuke.*` (any quote style, `Include`/`Update`/`Remove`), and it has no `.fallout/` yet. + */ +export function findNukeRoots(folder: string): string[] { + const roots = new Set(); + const walk = (dir: string, depth: number): void => { + if (isDirectory(path.join(dir, '.fallout'))) { + return; + } + if (hasNukeDirectory(dir)) { + roots.add(dir); + } + let entries: fs.Dirent[]; + try { + entries = fs.readdirSync(dir, { withFileTypes: true }); + } catch { + return; + } + if (entries.some(e => e.isFile() && e.name === '_build.csproj') && referencesNuke(path.join(dir, '_build.csproj'))) { + roots.add(path.basename(dir) === 'build' ? path.dirname(dir) : dir); + } + if (depth >= MAX_DEPTH) { + return; + } + for (const e of entries) { + if (e.isDirectory() && !e.name.startsWith('.') && !SKIP_DIRS.has(e.name)) { + walk(path.join(dir, e.name), depth + 1); + } + } + }; + walk(folder, 0); + // A csproj in a child maps to the parent root, which the walk above may not have checked for .fallout/. + return [...roots].filter(r => !isDirectory(path.join(r, '.fallout'))); +} diff --git a/test/integration/migrate.test.ts b/test/integration/migrate.test.ts new file mode 100644 index 0000000..76a475e --- /dev/null +++ b/test/integration/migrate.test.ts @@ -0,0 +1,62 @@ +import * as assert from 'assert'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import * as vscode from 'vscode'; +import { openMigrationTerminal } from '../../src/migrate'; + +// Inside the extension host process.execPath is VS Code itself, so find a real Node on PATH. +function findNode(): string { + const exe = process.platform === 'win32' ? 'node.exe' : 'node'; + for (const dir of (process.env.PATH ?? '').split(path.delimiter)) { + const candidate = path.join(dir, exe); + if (dir && fs.existsSync(candidate)) { + return candidate; + } + } + throw new Error('node not found on PATH'); +} +const NODE = findNode(); + +suite('migrate terminal', () => { + // The real run is a shell-less terminal around fallout-migrate. A stand-in script (run by Node) + // plays the tool: it renames .nuke to .fallout like the migrator and exits. + test('onFinished fires after the migrator exits, and the rename has happened by then', async () => { + const repo = fs.mkdtempSync(path.join(os.tmpdir(), 'fallout-migrate-')); + fs.mkdirSync(path.join(repo, '.nuke')); + fs.writeFileSync(path.join(repo, '.nuke', 'parameters.json'), '{}'); + const script = path.join(repo, 'fake-migrate.js'); + fs.writeFileSync(script, [ + "const fs = require('fs'), path = require('path');", + 'const root = process.argv[2];', + "console.log('fake migrate: ' + root);", + "fs.renameSync(path.join(root, '.nuke'), path.join(root, '.fallout'));", + ].join('\n')); + + let renamedWhenFinished: boolean | undefined; + let terminal: vscode.Terminal | undefined; + const finished = new Promise(resolve => { + terminal = openMigrationTerminal(NODE, [script, repo], repo, () => { + renamedWhenFinished = fs.existsSync(path.join(repo, '.fallout')) && !fs.existsSync(path.join(repo, '.nuke')); + resolve(); + }); + }); + + await Promise.race([ + finished, + new Promise((_, reject) => setTimeout(() => reject(new Error( + `onFinished never fired (exitStatus=${JSON.stringify(terminal?.exitStatus)}, .fallout exists=${fs.existsSync(path.join(repo, '.fallout'))}, terminals=${vscode.window.terminals.length})`)), 20000)), + ]); + assert.equal(renamedWhenFinished, true); + }); + + test('every call opens its own terminal', () => { + const before = vscode.window.terminals.length; + const a = openMigrationTerminal(NODE, ['-e', 'setTimeout(()=>{},60000)'], os.tmpdir(), () => undefined); + const b = openMigrationTerminal(NODE, ['-e', 'setTimeout(()=>{},60000)'], os.tmpdir(), () => undefined); + assert.notStrictEqual(a, b); + assert.equal(vscode.window.terminals.length, before + 2); + a.dispose(); + b.dispose(); + }); +}); diff --git a/test/unit/nuke.test.ts b/test/unit/nuke.test.ts new file mode 100644 index 0000000..602d9b7 --- /dev/null +++ b/test/unit/nuke.test.ts @@ -0,0 +1,91 @@ +import { test } from 'node:test'; +import * as assert from 'node:assert/strict'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { findNukeRoots } from '../../src/nuke'; + +/** Builds a throwaway repo from `{ 'relative/path': 'contents' }`; a path ending in `/` is an empty directory. */ +function repo(files: Record): string { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'fallout-nuke-')); + for (const [rel, text] of Object.entries(files)) { + const full = path.join(root, rel); + if (rel.endsWith('/')) { + fs.mkdirSync(full, { recursive: true }); + } else { + fs.mkdirSync(path.dirname(full), { recursive: true }); + fs.writeFileSync(full, text); + } + } + return root; +} + +const nukeCsproj = (attr: string) => ``; + +test('a non-empty .nuke directory marks the repo', () => { + const root = repo({ '.nuke/parameters.json': '{}' }); + assert.deepEqual(findNukeRoots(root), [root]); +}); + +for (const [name, attr] of [ + ['double quotes', 'Include="Nuke.Common"'], + ['single quotes', "Include='Nuke.Common'"], + ['Update=', 'Update="Nuke.Common"'], + ['spaces around =', 'Include = "Nuke.Common"'], +]) { + test(`build/_build.csproj with Nuke.* (${name}) marks the repo root`, () => { + const root = repo({ 'build/_build.csproj': nukeCsproj(attr) }); + assert.deepEqual(findNukeRoots(root), [root]); + }); +} + +test('_build.csproj outside a build/ folder marks its own directory', () => { + const root = repo({ 'tooling/_build.csproj': nukeCsproj('Include="Nuke.Common"') }); + assert.deepEqual(findNukeRoots(root), [path.join(root, 'tooling')]); +}); + +test('a build project that references Fallout.* is not NUKE', () => { + const root = repo({ 'build/_build.csproj': nukeCsproj('Include="Fallout.Common"') }); + assert.deepEqual(findNukeRoots(root), []); +}); + +test('an existing .fallout directory means already migrated', () => { + const root = repo({ '.nuke/parameters.json': '{}', '.fallout/parameters.json': '{}' }); + assert.deepEqual(findNukeRoots(root), []); +}); + +test('an empty .nuke directory and a legacy .nuke file do not count', () => { + assert.deepEqual(findNukeRoots(repo({ '.nuke/': '' })), []); + assert.deepEqual(findNukeRoots(repo({ '.nuke': 'legacy' })), []); +}); + +test('nested repositories are found, each with its own root', () => { + const root = repo({ + 'services/a/.nuke/parameters.json': '{}', + 'services/b/build/_build.csproj': nukeCsproj('Include="Nuke.Common"'), + }); + assert.deepEqual(findNukeRoots(root).sort(), [path.join(root, 'services/a'), path.join(root, 'services/b')].sort()); +}); + +test('a migrated repo nested in a NUKE repo is skipped, the outer one is kept', () => { + const root = repo({ '.nuke/parameters.json': '{}', 'inner/.nuke/x': '', 'inner/.fallout/x': '' }); + assert.deepEqual(findNukeRoots(root), [root]); +}); + +test('node_modules, bin, obj and dot-directories are not scanned', () => { + const root = repo({ + 'node_modules/pkg/.nuke/x': '', + 'src/bin/.nuke/x': '', + '.cache/.nuke/x': '', + }); + assert.deepEqual(findNukeRoots(root), []); +}); + +test('scanning stops below the depth limit', () => { + const root = repo({ 'a/b/c/d/.nuke/x': '' }); + assert.deepEqual(findNukeRoots(root), []); +}); + +test('a missing folder yields nothing instead of throwing', () => { + assert.deepEqual(findNukeRoots(path.join(os.tmpdir(), 'fallout-does-not-exist')), []); +});