Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
26 changes: 23 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -144,6 +159,11 @@
"title": "Plan (dry run)",
"category": "Fallout",
"icon": "$(list-tree)"
},
{
"command": "fallout.migrateFromNuke",
"title": "Migrate from NUKE…",
"category": "Fallout"
}
],
"menus": {
Expand Down
23 changes: 23 additions & 0 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Relation, string> = {
Expand Down Expand Up @@ -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 {}
176 changes: 176 additions & 0 deletions src/migrate.ts
Original file line number Diff line number Diff line change
@@ -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<string | undefined> {
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<number> {
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<string | undefined> {
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<T>(title: string, task: () => Promise<T>): Promise<T> {
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<void> {
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<void> {
const prompted = context.workspaceState.get<string[]>(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);
}
}
69 changes: 69 additions & 0 deletions src/nuke.ts
Original file line number Diff line number Diff line change
@@ -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<string>();
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')));
}
Loading
Loading