Skip to content
Merged
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
97 changes: 97 additions & 0 deletions packages/core/src/cli/commands/carve-bridge.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { describe, test, expect } from "vitest";
import { mkdtempSync, writeFileSync, rmSync, readFileSync, existsSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
import { carveBridge, formatCarveBridge } from "./carve-bridge";
import { loadHcl2json } from "../../terraform/parse";

let parserAvailable = false;
try {
await loadHcl2json();
parserAvailable = true;
} catch {
parserAvailable = false;
}

const BUCKET_TF = `resource "aws_s3_bucket" "assets" {
bucket = "myapp-assets-prod"
}
`;
const API_TF = `resource "aws_lambda_function" "api" {
function_name = "myapp-api"
environment {
variables = {
ASSETS_BUCKET = aws_s3_bucket.assets.bucket
ASSETS_ARN = aws_s3_bucket.assets.arn
}
}
}
`;

async function withEstate<T>(fn: (dir: string) => Promise<T>): Promise<T> {
const dir = mkdtempSync(join(tmpdir(), "chant-bridge-"));
try {
writeFileSync(join(dir, "bucket.tf"), BUCKET_TF);
writeFileSync(join(dir, "api.tf"), API_TF);
return await fn(dir);
} finally {
rmSync(dir, { recursive: true, force: true });
}
}

describe("carveBridge", () => {
test("requires --from and --select", async () => {
expect((await carveBridge({})).error).toContain("--from");
expect((await carveBridge({ from: "/x" })).error).toContain("--select");
});

test("dry-run: writes runbook + data sources + proposed survivor, touches no .tf in place", async () => {
if (!parserAvailable) return;
await withEstate(async (dir) => {
const out = join(dir, "carveout");
const res = await carveBridge({ from: dir, select: "aws_s3_bucket.assets", output: out });
expect(res.ok).toBe(true);
expect(res.appliedInPlace).toBeFalsy();

// Runbook + data sources + proposed api.tf were written to the output dir.
expect(existsSync(join(out, "aws_s3_bucket-assets-runbook.md"))).toBe(true);
const ds = readFileSync(join(out, "aws_s3_bucket-assets-datasources.tf"), "utf-8");
expect(ds).toContain('data "aws_s3_bucket" "assets"');
const proposed = readFileSync(join(out, "api.tf"), "utf-8");
expect(proposed).toContain("data.aws_s3_bucket.assets.bucket");

// The ORIGINAL api.tf in the estate is untouched.
expect(readFileSync(join(dir, "api.tf"), "utf-8")).toBe(API_TF);
});
});

test("--apply-rewrites edits the survivor .tf in place", async () => {
if (!parserAvailable) return;
await withEstate(async (dir) => {
const res = await carveBridge({
from: dir,
select: "aws_s3_bucket.assets",
output: join(dir, "carveout"),
applyRewrites: true,
});
expect(res.ok).toBe(true);
expect(res.appliedInPlace).toBe(true);

// api.tf rewritten in place; bucket.tf (the carved declaration) untouched.
const api = readFileSync(join(dir, "api.tf"), "utf-8");
expect(api).toContain("data.aws_s3_bucket.assets.bucket");
expect(readFileSync(join(dir, "bucket.tf"), "utf-8")).toBe(BUCKET_TF);
});
});

test("formatCarveBridge summarizes data sources, rewires, and safety", async () => {
if (!parserAvailable) return;
await withEstate(async (dir) => {
const res = await carveBridge({ from: dir, select: "aws_s3_bucket.assets", output: join(dir, "carveout") });
const text = formatCarveBridge(res);
expect(text).toContain("data.aws_s3_bucket.assets");
expect(text).toContain("Nothing in your Terraform changed");
expect(text).toContain("runbook");
});
});
});
134 changes: 134 additions & 0 deletions packages/core/src/cli/commands/carve-bridge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/**
* `chant carve bridge` — the boundary-bridging step of the strangler-fig carve
* (#197). Generates the edits to the surviving Terraform (data sources +
* rewired references), records the deferred deploy-time inputs, and writes a
* reversible handoff runbook.
*
* Safe by default: writes proposed files to an output directory for review.
* `--apply-rewrites` writes the rewritten survivor `.tf` back in place — an
* opt-in mutation of your Terraform, never the default.
*/

import { existsSync, statSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "fs";
import { join, basename } from "path";
import { parseTerraformDir, Hcl2JsonNotInstalled } from "../../terraform/parse";
import { boundaryReport } from "../../terraform/carve";
import { generateBridge, type BridgePlan, type CarvedIdentity } from "../../terraform/bridge";
import { IDENTITY_ATTR } from "../../terraform/tier-map";

export interface CarveBridgeOptions {
from?: string;
select?: string;
statePath?: string;
/** Output directory for proposed files (default `<from>/carveout`). */
output?: string;
/** Write rewritten survivor `.tf` back in place instead of to the output dir. */
applyRewrites?: boolean;
}

export interface CarveBridgeResult {
ok: boolean;
error?: string;
plan?: BridgePlan;
/** Absolute paths written. */
written?: string[];
/** True if survivor files were edited in place. */
appliedInPlace?: boolean;
}

function listTfFiles(dir: string): string[] {
return readdirSync(dir)
.filter((f) => f.endsWith(".tf"))
.map((f) => join(dir, f))
.sort();
}

export async function carveBridge(opts: CarveBridgeOptions): Promise<CarveBridgeResult> {
if (!opts.from) return { ok: false, error: "chant carve bridge requires --from <terraform-dir>" };
if (!opts.select) return { ok: false, error: "chant carve bridge requires --select <tf-address>" };
if (!existsSync(opts.from) || !statSync(opts.from).isDirectory()) {
return { ok: false, error: `Not a directory: ${opts.from}` };
}

let plan: BridgePlan;
try {
const graph = await parseTerraformDir(opts.from, { statePath: opts.statePath });
const report = boundaryReport(graph, opts.select);
if (!report) return { ok: false, error: `${opts.select} not found in ${opts.from}` };

// Physical identities for the carved resources, for the data sources.
const identities = new Map<string, CarvedIdentity>();
for (const node of graph.nodes) {
if (node.type && node.identity) {
identities.set(node.address, { attr: IDENTITY_ATTR[node.type], value: node.identity });
}
}

const files = listTfFiles(opts.from).map((path) => ({ path, content: readFileSync(path, "utf-8") }));
plan = generateBridge(report, files, identities);
} catch (err) {
if (err instanceof Hcl2JsonNotInstalled) return { ok: false, error: err.message };
return { ok: false, error: `Failed to build the bridge: ${err instanceof Error ? err.message : String(err)}` };
}

const slug = opts.select.replace(/[^A-Za-z0-9_]+/g, "-");
const outDir = opts.output ?? join(opts.from, "carveout");
mkdirSync(outDir, { recursive: true });
const written: string[] = [];

// Runbook.
const runbookPath = join(outDir, `${slug}-runbook.md`);
writeFileSync(runbookPath, plan.runbook + "\n");
written.push(runbookPath);

// Data sources for the survivors to read.
if (plan.dataSources.length) {
const dsPath = join(outDir, `${slug}-datasources.tf`);
writeFileSync(dsPath, plan.dataSources.map((d) => d.hcl).join("\n\n") + "\n");
written.push(dsPath);
}

// Rewritten survivors: in place (opt-in) or proposed into the output dir.
const changed = plan.rewrites.filter((r) => r.changed);
for (const r of changed) {
if (opts.applyRewrites) {
writeFileSync(r.path, r.rewritten);
written.push(r.path);
} else {
const proposed = join(outDir, basename(r.path));
writeFileSync(proposed, r.rewritten);
written.push(proposed);
}
}

return { ok: true, plan, written, appliedInPlace: opts.applyRewrites && changed.length > 0 };
}

export function formatCarveBridge(result: CarveBridgeResult): string {
if (!result.ok || !result.plan) return result.error ?? "carve bridge failed";
const p = result.plan;
const L: string[] = [];
L.push(`Boundary bridge for ${p.target}:`);
if (p.dataSources.length) {
L.push(` ${p.dataSources.length} data source(s) for survivors to read:`);
for (const d of p.dataSources) L.push(` data.${d.type}.${d.name} (was ${d.address})`);
} else {
L.push(" no inbound edges — no survivor patch needed.");
}
const changed = p.rewrites.filter((r) => r.changed);
if (changed.length) {
L.push(` ${changed.length} survivor file(s) rewired: ${changed.map((r) => basename(r.path)).join(", ")}`);
}
if (p.deferredInputs.length) {
L.push(` ${p.deferredInputs.length} deferred deploy-time input(s) (wired at apply):`);
for (const d of p.deferredInputs) L.push(` - ${d.note}`);
}
L.push("");
if (result.appliedInPlace) {
L.push("Rewritten survivor Terraform in place. Review with `git diff`, then `terraform plan`.");
} else {
L.push(`Wrote proposals to ${result.written?.[0] ? result.written[0].replace(/[^/]+$/, "") : "the output dir"} — review, then apply. Nothing in your Terraform changed.`);
}
L.push("See the runbook for the reversible, observe-first handoff steps.");
return L.join("\n");
}
33 changes: 33 additions & 0 deletions packages/core/src/cli/handlers/carve-bridge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { carveBridge, formatCarveBridge } from "../commands/carve-bridge";
import { formatError } from "../format";
import type { CommandContext } from "../registry";

/**
* `chant carve bridge --from <tf-dir> --select <address> [--output <dir>] [--apply-rewrites]`
*
* Read-only by default: writes proposed survivor patches + a runbook to an
* output dir. `--apply-rewrites` edits the surviving `.tf` in place. Loads no
* lexicon plugins — pure Terraform-side analysis.
*/
export async function runCarveBridge(ctx: CommandContext): Promise<number> {
const { args } = ctx;

const result = await carveBridge({
from: args.migrateFrom, // `--from <terraform-dir>`
select: args.selectAddress, // `--select <tf-address>`
statePath: args.statePath,
output: args.output,
applyRewrites: args.applyRewrites,
});

if (!result.ok) {
console.error(formatError({
message: result.error ?? "carve bridge failed",
hint: "chant carve bridge --from ./tf --select aws_s3_bucket.assets",
}));
return 1;
}

console.log(formatCarveBridge(result));
return 0;
}
11 changes: 11 additions & 0 deletions packages/core/src/cli/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { runVendor } from "./handlers/vendor";
import { runMigrate } from "./handlers/migrate";
import { runCarveAdvise, runCarveUnknown } from "./handlers/carve";
import { runCarveEmit } from "./handlers/carve-emit";
import { runCarveBridge } from "./handlers/carve-bridge";
import { runLifecycleSnapshot, runLifecycleShow, runLifecycleDiff, runLifecycleRollback, runLifecyclePlan, runLifecycleAffected, runLifecycleLog, runLifecycleUnknown } from "./handlers/lifecycle";
import { runComponentsStatus, runComponentsReleaseRecord, runComponentsUnknown } from "./handlers/components";
import { runGraph } from "./handlers/graph";
Expand Down Expand Up @@ -122,6 +123,8 @@ export function parseArgs(args: string[]): ParsedArgs {
result.statePath = args[++i];
} else if (arg === "--select") {
result.selectAddress = args[++i];
} else if (arg === "--apply-rewrites") {
result.applyRewrites = true;
} else if (arg === "--to") {
result.migrateTo = args[++i];
} else if (arg === "--emit") {
Expand Down Expand Up @@ -259,6 +262,10 @@ Commands:
--from <tf-dir> import (cloud→code) and report its boundary.
--select <addr> Observe position, reversible; patches nothing.
--env <env> (next: carve bridge patches the surviving TF)
carve bridge Generate the surviving-TF patch (data sources + rewired
--from <tf-dir> refs) + deferred inputs + reversible runbook.
--select <addr> Writes proposals for review; --apply-rewrites
edits the .tf in place.

Ops:
run <name> Start an Op workflow (spawns worker + submits to Temporal)
Expand Down Expand Up @@ -448,6 +455,10 @@ const registry: CommandDef[] = [
// Emit step (#197): adopt a selected TF resource into chant source via live
// import. Needs the target lexicon's plugins for the cloud→code export.
{ name: "carve emit", requiresPlugins: true, handler: runCarveEmit },
// Boundary bridging (#197): patch the surviving TF (data sources + rewired
// refs) + runbook. No plugins; Terraform-side only. Read-only unless
// --apply-rewrites.
{ name: "carve bridge", handler: runCarveBridge },
{ name: "init", handler: runInit },
{ name: "init lexicon", handler: runInitLexicon },
{ name: "update", handler: runUpdate },
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/cli/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ export interface ParsedArgs {
statePath?: string;
/** `chant carve emit --select <tf-address>` — the Terraform resource to carve */
selectAddress?: string;
/** `chant carve bridge --apply-rewrites` — write rewritten survivor .tf in place */
applyRewrites?: boolean;
/** `chant migrate --to <name>` (default "gitlab") */
migrateTo?: string;
/** `chant migrate --emit yaml|ts` */
Expand Down
Loading