diff --git a/AGENTS.md b/AGENTS.md index 90a55f5..7c425ec 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -68,6 +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/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/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..e035f79 100644 --- a/package.json +++ b/package.json @@ -39,7 +39,10 @@ "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", + "workspaceContains:**/_build.csproj" ], "contributes": { "viewsContainers": { @@ -97,11 +100,23 @@ "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", + "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", @@ -144,6 +159,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..83e4a70 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 { hasNukeRepo, migrateFromNuke, promptIfNukeRepo } from './migrate'; import { RunConfigStore, RunConfigViewProvider } from './runConfig'; const RELATION_LABELS: Record = { @@ -216,6 +217,28 @@ 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', hasNukeRepo()); + const afterMigration = () => { updateNukeContext(); provider.refresh(); }; + updateNukeContext(); + + // 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(afterMigration); + falloutDirWatcher.onDidDelete(afterMigration); + const nukeDirWatcher = vscode.workspace.createFileSystemWatcher('**/.nuke'); + nukeDirWatcher.onDidCreate(afterMigration); + nukeDirWatcher.onDidDelete(afterMigration); + + context.subscriptions.push( + falloutDirWatcher, + nukeDirWatcher, + vscode.commands.registerCommand('fallout.migrateFromNuke', () => migrateFromNuke(afterMigration)), + ); + + void promptIfNukeRepo(context, afterMigration); } export function deactivate(): void {} diff --git a/src/migrate.ts b/src/migrate.ts new file mode 100644 index 0000000..c76ea8a --- /dev/null +++ b/src/migrate.ts @@ -0,0 +1,176 @@ +import * as vscode from 'vscode'; +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'; + +let output: vscode.OutputChannel | undefined; +let busy = false; + +const channel = (): vscode.OutputChannel => (output ??= vscode.window.createOutputChannel('Fallout Migrate')); + +/** 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 => { + 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)); + }); +} + +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)); +} + +/** + * 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 + * in a fresh terminal because the tool asks "Continue?" itself. + */ +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; + } + + 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; + } + } + + 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; + } + + const choice = await vscode.window.showInformationMessage( + `Fallout: preview done, nothing changed (see the "Fallout Migrate" output). Migrate ${root}?`, + 'Migrate', 'Cancel'); + if (choice !== 'Migrate') { + return; + } + + openMigrationTerminal(tool, [root], root, onFinished); + } finally { + busy = false; + } +} + +/** 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…', 'Not now'); + if (choice === 'Migrate…') { + await migrateFromNuke(onFinished); + } +} 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')), []); +});