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
119 changes: 119 additions & 0 deletions scripts/ruby/rename.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
#!/usr/bin/env ruby
#
# Apply a rename plan to a Rails project tree.
# Stdin: { "renamePlan": [{"from":"Shop","to":"Clinic"}, ...], "root": "/abs/path" }
# Stdout: { "files_scanned": N, "files_changed": N, "substitutions": N, "files_renamed": N }
#
# Rewrites file content AND renames files/directories for every
# PascalCase / snake_case / plural variant of each rename pair.
# Word-boundary matching via Regexp; crude-but-sufficient English
# pluralization. Skips .git, node_modules, tmp/, log/, vendor/bundle/.

require "json"

input = JSON.parse($stdin.read)
plan = input.fetch("renamePlan")
root = input.fetch("root")

stats = { files_scanned: 0, files_changed: 0, substitutions: 0, files_renamed: 0 }

SKIP_DIR_SEGMENTS = %w[.git node_modules tmp log].freeze
SKIP_SUBPATHS = %w[vendor/bundle].freeze
TEXT_EXTS = %w[.rb .erb .yml .yaml .json .md .gemspec .rake .ru .txt .sample .example .conf .html .css .scss .js .mjs .tt .lock].freeze
TEXT_BASENAMES = %w[Gemfile Gemfile.lock Rakefile Procfile Procfile.dev .gitignore .env.sample .ruby-version .node-version config.ru Dockerfile].freeze

def pluralize(word)
if word.end_with?("y") && word.length > 1 && !%w[a e i o u].include?(word[-2])
word[0..-2] + "ies"
elsif word.end_with?("s", "sh", "ch", "x", "z")
word + "es"
else
word + "s"
end
end

def snake_case(pascal)
pascal.gsub(/([a-z\d])([A-Z])/, '\1_\2')
.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
.downcase
end

def build_patterns(from, to)
from_snake = snake_case(from)
to_snake = snake_case(to)

# Ruby's \b treats `_` as a word char, so \bshop\b doesn't fire
# inside `shop_id` or `accounts_shopkeeper`. Use a letter-aware
# boundary instead: "no letter on either side of the match."
# Order matters: plural forms first so e.g. "Shops" isn't
# partially-matched as "Shop" + residual "s".
[
[/(?<![A-Za-z])#{Regexp.escape(pluralize(from))}(?![A-Za-z])/, pluralize(to)],
[/(?<![A-Za-z])#{Regexp.escape(from)}(?![A-Za-z])/, to],
[/(?<![A-Za-z])#{Regexp.escape(pluralize(from_snake))}(?![A-Za-z])/, pluralize(to_snake)],
[/(?<![A-Za-z])#{Regexp.escape(from_snake)}(?![A-Za-z])/, to_snake],
[/(?<![A-Za-z])#{Regexp.escape(from.upcase)}(?![A-Za-z])/, to.upcase],
]
end

all_patterns = plan.flat_map { |p| build_patterns(p.fetch("from"), p.fetch("to")) }

def skip?(path)
return true if SKIP_DIR_SEGMENTS.any? { |d| path.include?("/#{d}/") || path.end_with?("/#{d}") }
return true if SKIP_SUBPATHS.any? { |sp| path.include?("/#{sp}") }
false
end

def text_file?(path)
basename = File.basename(path)
return true if TEXT_BASENAMES.include?(basename)
return true if TEXT_EXTS.include?(File.extname(path))
false
end

# Pass 1 — rewrite file contents.
Dir.glob("#{root}/**/*", File::FNM_DOTMATCH).each do |path|
next unless File.file?(path)
next if skip?(path)
next unless text_file?(path)

stats[:files_scanned] += 1

begin
content = File.read(path, encoding: "UTF-8")
rescue StandardError
next
end

original = content.dup
local_subst = 0
all_patterns.each do |regex, replacement|
content = content.gsub(regex) { local_subst += 1; replacement }
end

next if content == original

File.write(path, content)
stats[:files_changed] += 1
stats[:substitutions] += local_subst
end

# Pass 2 — rename paths. Deepest-first so renaming a parent directory
# doesn't invalidate paths we haven't visited yet.
Dir.glob("#{root}/**/*", File::FNM_DOTMATCH).sort_by { |p| -p.length }.each do |path|
next if skip?(path)
next unless File.exist?(path)

old_name = File.basename(path)
new_name = old_name.dup
all_patterns.each { |regex, replacement| new_name = new_name.gsub(regex, replacement) }
next if new_name == old_name

new_path = File.join(File.dirname(path), new_name)
next if File.exist?(new_path)

File.rename(path, new_path)
stats[:files_renamed] += 1
end

puts JSON.generate(stats)
97 changes: 95 additions & 2 deletions src/agents/workers/rails.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,103 @@
import { cp, lstat, mkdir, rm, stat } from "node:fs/promises";
import { spawn } from "node:child_process";
import { resolve } from "node:path";
import { trace } from "../../trace.js";
import type { DomainSpec, WorkerResult } from "../types.js";
import { isStub } from "../../stub.js";
import { runRuby } from "../../ruby.js";
import type { DomainSpec, RenamePair, WorkerResult } from "../types.js";

const delay = (ms: number): Promise<void> => new Promise((r) => { setTimeout(r, ms); });
type RenameStats = {
files_scanned: number;
files_changed: number;
substitutions: number;
files_renamed: number;
};

const SKIP_RELATIVE_PATHS = ["/.git", "/node_modules", "/tmp", "/log", "/vendor/bundle"];

export async function runRailsWorker(domain: DomainSpec): Promise<WorkerResult> {
if (isStub("rails")) {
return runStubRailsWorker(domain);
}

const substrate = process.env['NATEMPLATE_API'];
if (!substrate) {
throw new Error("rails worker: NATEMPLATE_API env var is not set; see CLAUDE.md Substrate section");
}

const outDir = resolve(process.cwd(), "out", domain.slug, "rails");

trace("rails", `copying substrate from ${substrate} to ${outDir}`);
await prepareFresh(outDir);
await copyFiltered(substrate, outDir);

const plan = domain.renamePlan.map((p) => `${p.from}->${p.to}`).join(", ");
trace("rails", `running scripts/ruby/rename.rb: ${plan}`);

const renameStats = await runRuby<{ renamePlan: readonly RenamePair[]; root: string }, RenameStats>(
"rename.rb",
{ renamePlan: domain.renamePlan, root: outDir },
);

trace(
"rails",
`scanned ${renameStats.files_scanned} files, changed ${renameStats.files_changed}, ${renameStats.substitutions} substitutions, ${renameStats.files_renamed} file/dir renames`,
);

await initGit(outDir);
trace("rails", `done (out/${domain.slug}/rails)`);

return {
platform: "rails",
outDir: `./out/${domain.slug}/rails`,
filesTouched: renameStats.files_changed + renameStats.files_renamed,
};
}

async function prepareFresh(dir: string): Promise<void> {
try {
await stat(dir);
await rm(dir, { recursive: true, force: true });
} catch {
// dest doesn't exist — nothing to clean
}
await mkdir(dir, { recursive: true });
}

async function copyFiltered(src: string, dest: string): Promise<void> {
await cp(src, dest, {
recursive: true,
force: true,
filter: async (source: string) => {
const rel = source.slice(src.length);
if (SKIP_RELATIVE_PATHS.some((p) => rel === p || rel.startsWith(`${p}/`))) return false;
try {
const s = await lstat(source);
if (s.isSocket() || s.isFIFO() || s.isBlockDevice() || s.isCharacterDevice()) return false;
} catch {
return false;
}
return true;
},
});
}

async function initGit(dir: string): Promise<void> {
await new Promise<void>((resolvePromise, rejectPromise) => {
const child = spawn("git", ["init", "-q", "-b", "main"], { cwd: dir });
child.on("close", (code) => {
if (code === 0) resolvePromise();
else rejectPromise(new Error(`git init exited ${code}`));
});
child.on("error", rejectPromise);
});
}

const delay = (ms: number): Promise<void> => new Promise((r) => { setTimeout(r, ms); });

async function runStubRailsWorker(domain: DomainSpec): Promise<WorkerResult> {
const plan = domain.renamePlan.map((p) => `${p.from}->${p.to}`).join(", ");
trace("rails", "(stub mode)");
trace("rails", `copying substrate for ${domain.displayName}`);
await delay(200);
trace("rails", `renaming Ruby symbols: ${plan}`);
Expand Down
28 changes: 28 additions & 0 deletions src/ruby.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { spawn } from "node:child_process";
import { resolve } from "node:path";

export async function runRuby<TInput, TOutput>(
scriptName: string,
input: TInput,
): Promise<TOutput> {
const scriptPath = resolve(process.cwd(), "scripts/ruby", scriptName);
const child = spawn("ruby", [scriptPath]);

const stdoutChunks: Buffer[] = [];
const stderrChunks: Buffer[] = [];

child.stdout.on("data", (c: Buffer) => stdoutChunks.push(c));
child.stderr.on("data", (c: Buffer) => stderrChunks.push(c));

child.stdin.write(JSON.stringify(input));
child.stdin.end();

const code: number = await new Promise((r) => { child.on("close", r); });
if (code !== 0) {
const stderr = Buffer.concat(stderrChunks).toString("utf8");
throw new Error(`ruby script ${scriptName} exited ${code}: ${stderr}`);
}

const stdout = Buffer.concat(stdoutChunks).toString("utf8");
return JSON.parse(stdout) as TOutput;
}
Loading