Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.
Rust agent-skillsclaude-codeclicode-migrationcodexffigolangjavajavascriptmcpmigrationnapiperformanceportingpyo3pythonrewriterubyrusttypescript
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail, ensure};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::app::{self, Failure, ReplayOptions};
use crate::gate::Check;
use crate::recording::Trend;
pub const CASES: &str = "spec/cases";
pub const SPEC: &str = "spec/SPEC.md";
pub const RULES: &str = "spec/RULES.md";
pub const APPROVED: &str = "spec/approved.json";
const HISTORY: &str = "target/rust-anything/spec-history.jsonl";
const CASE_FILES: [&str; 6] = ["toml", "stdin", "stdout", "stderr", "removed", "effects"];
pub fn is_new_app(root: &Path) -> bool {
root.join(CASES).join(app::CONFIG_FILE).is_file() && !root.join(app::CASES_DIR).is_dir()
}
fn ensure_new_app(dir: &Path) -> Result<PathBuf> {
let dir = crate::walk::resolve_root(dir)?;
ensure!(
is_new_app(&dir),
"{} has no {CASES}/{}: start the app with `rust-anything new`",
dir.display(),
app::CONFIG_FILE
);
Ok(dir)
}
#[derive(Debug, Serialize)]
pub struct NewOutcome {
pub dir: PathBuf,
pub name: String,
pub files: Vec<String>,
}
fn crate_name(name: &str) -> Result<String> {
let ok = name.chars().next().is_some_and(|c| c.is_ascii_alphabetic())
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
ensure!(
ok,
"`{name}` is not a crate name: use letters, digits, `-` and `_`, starting with a letter (pass --name)"
);
Ok(name.to_string())
}
pub fn new_app(dir: &Path, name: Option<&str>) -> Result<NewOutcome> {
if dir.exists() {
ensure!(dir.is_dir(), "{} is a file", dir.display());
let has_files = std::fs::read_dir(dir)
.with_context(|| format!("reading {}", dir.display()))?
.next()
.is_some();
ensure!(
!has_files,
"{} has files; `rust-anything new` only starts an app in an empty or new folder",
dir.display()
);
}
let name = match name {
Some(n) => crate_name(n)?,
None => crate_name(
&dir.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default(),
)?,
};
let config = serde_json::to_string_pretty(&app::Config::new(&name))? + "\n";
let files: Vec<(String, String)> = vec![
(
"Cargo.toml".into(),
format!(
"[package]\nname = \"{name}\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n[dependencies]\n"
),
),
(
"src/main.rs".into(),
format!(
"fn main() {{\n eprintln!(\"{name}: not written yet, see spec/SPEC.md\");\n std::process::exit(1);\n}}\n"
),
),
(".gitignore".into(), "/target\n".into()),
(SPEC.into(), spec_template(&name)),
(
RULES.into(),
"# Rules\n\nBehavior the app must keep, learned from corrections. Add one with \
`rust-anything rules --add`.\n\n"
.into(),
),
(format!("{CASES}/{}", app::CONFIG_FILE), config),
(
format!("{CASES}/hello.toml"),
format!(
"bin.name = \"{name}\"\nargs = [\"world\"]\nstatus.code = 0\nfs.sandbox = true\n"
),
),
(format!("{CASES}/hello.stdout"), "Hello, world!\n".into()),
];
for (path, text) in &files {
let path = dir.join(path);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)
.with_context(|| format!("creating {}", parent.display()))?;
}
std::fs::write(&path, text).with_context(|| format!("writing {}", path.display()))?;
}
Ok(NewOutcome {
dir: dir.to_path_buf(),
name,
files: files.into_iter().map(|(p, _)| p).collect(),
})
}
fn spec_template(name: &str) -> String {
format!(
"# {name}\n\n\
What {name} does, in a few sentences: who runs it, what goes in, what comes out.\n\n\
## Inputs\n\n\
Arguments, standard input and files it reads.\n\n\
## Outputs\n\n\
What it prints, the files it writes and its exit codes.\n\n\
## Errors\n\n\
What it does with bad input: the message, where it goes and the exit code.\n\n\
## Out of scope\n\n\
What it does not do.\n\n\
## Open questions\n\n\
One line per question the spec does not answer yet, as `- [ ] the question`. Once the user \
answers, write it as `- [x] the question: the answer`. `rust-anything spec check` does not \
call the app done while a question is open.\n"
)
}
#[derive(Debug, Default, Serialize, Deserialize)]
struct Approvals {
schema: String,
cases: BTreeMap<String, Approval>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
struct Approval {
hash: String,
at: String,
}
fn load_approvals(dir: &Path) -> Result<Approvals> {
let path = dir.join(APPROVED);
let Ok(text) = std::fs::read_to_string(&path) else {
return Ok(Approvals::default());
};
serde_json::from_str(&text).with_context(|| format!("parsing {}", path.display()))
}
fn files_in(dir: &Path, out: &mut Vec<PathBuf>) {
let Ok(rd) = std::fs::read_dir(dir) else {
return;
};
let mut entries: Vec<_> = rd.flatten().map(|e| e.path()).collect();
entries.sort();
for path in entries {
if path.is_dir() {
files_in(&path, out);
} else {
out.push(path);
}
}
}
fn case_hash(cases: &Path, name: &str) -> String {
let mut h = Sha256::new();
h.update(std::fs::read(cases.join(app::CONFIG_FILE)).unwrap_or_default());
let mut files: Vec<PathBuf> = CASE_FILES
.iter()
.map(|ext| cases.join(format!("{name}.{ext}")))
.filter(|p| p.is_file())
.collect();
for side in ["in", "out"] {
files_in(&cases.join(format!("{name}.{side}")), &mut files);
}
let base = std::fs::read_to_string(cases.join(format!("{name}.toml")))
.ok()
.and_then(|text| text.parse::<toml_edit::DocumentMut>().ok())
.and_then(|doc| {
doc.get("fs")
.and_then(|f| f.get("base"))
.and_then(toml_edit::Item::as_str)
.map(str::to_string)
});
if let Some(base) = base {
let mut inputs = Vec::new();
files_in(&cases.join(base), &mut inputs);
for file in inputs {
if !files.contains(&file) {
files.push(file);
}
}
}
for file in files {
let rel = file.strip_prefix(cases).unwrap_or(&file);
h.update([0]);
h.update(rel.to_string_lossy().replace('\\', "/").as_bytes());
h.update([0]);
h.update(std::fs::read(&file).unwrap_or_default());
}
h.finalize().iter().map(|b| format!("{b:02x}")).collect()
}
#[derive(Debug, Serialize)]
pub struct Shown {
pub name: String,
pub args: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub stdout: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct ApproveOutcome {
pub file: PathBuf,
pub approved: Vec<Shown>,
pub unchanged: Vec<String>,
pub forgotten: Vec<String>,
}
fn pick(names: &[String], wanted: &[String]) -> Result<Vec<String>> {
if wanted.is_empty() {
return Ok(names.to_vec());
}
for w in wanted {
ensure!(
names.contains(w),
"no case named {w}; the cases are: {}",
names.join(", ")
);
}
Ok(wanted.to_vec())
}
pub fn approve(dir: &Path, cases: &[String]) -> Result<ApproveOutcome> {
let dir = ensure_new_app(dir)?;
let cases_dir = dir.join(CASES);
let previews = app::case_previews(&cases_dir)?;
let names: Vec<String> = previews.iter().map(|p| p.name.clone()).collect();
if names.is_empty() {
bail!("no cases in {CASES} to approve");
}
let picked = pick(&names, cases)?;
let mut approvals = load_approvals(&dir)?;
approvals.schema = crate::state::schema("spec-approved");
let forgotten: Vec<String> = if cases.is_empty() {
let gone: Vec<String> = approvals
.cases
.keys()
.filter(|k| !names.contains(k))
.cloned()
.collect();
for k in &gone {
approvals.cases.remove(k);
}
gone
} else {
Vec::new()
};
let at = crate::state::now();
let mut approved = Vec::new();
let mut unchanged = Vec::new();
for app::CasePreview { name, args, stdout } in previews {
if !picked.contains(&name) {
continue;
}
let hash = case_hash(&cases_dir, &name);
if approvals.cases.get(&name).is_some_and(|a| a.hash == hash) {
unchanged.push(name);
continue;
}
approvals.cases.insert(
name.clone(),
Approval {
hash,
at: at.clone(),
},
);
approved.push(Shown {
name,
args,
stdout: stdout.map(|s| String::from_utf8_lossy(&s).into_owned()),
});
}
let file = dir.join(APPROVED);
std::fs::write(&file, serde_json::to_string_pretty(&approvals)? + "\n")
.with_context(|| format!("writing {}", file.display()))?;
Ok(ApproveOutcome {
file,
approved,
unchanged,
forgotten,
})
}
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Standing {
Approved,
Changed,
Draft,
}
#[derive(Debug, Serialize)]
pub struct CaseResult {
pub name: String,
pub standing: Standing,
pub passed: bool,
}
#[derive(Debug, Default, Serialize)]
pub struct Count {
pub passed: usize,
pub total: usize,
}
#[derive(Debug, Serialize)]
pub struct CheckOutcome {
pub schema: String,
pub at: String,
pub app: String,
pub done: bool,
pub approved: Count,
pub cases: Vec<CaseResult>,
pub removed: Vec<String>,
pub failures: Vec<Failure>,
pub open_questions: Vec<String>,
pub checks: Vec<Check>,
#[serde(skip_serializing_if = "Option::is_none")]
pub trend: Option<Trend>,
#[serde(skip_serializing_if = "Option::is_none")]
pub next: Option<String>,
}
pub fn open_questions(dir: &Path) -> Vec<String> {
let text = std::fs::read_to_string(dir.join(SPEC)).unwrap_or_default();
text.lines()
.filter_map(|l| l.trim_start().strip_prefix("- [ ]"))
.map(|q| q.trim().to_string())
.filter(|q| !q.is_empty())
.collect()
}
fn source_version(dir: &Path) -> String {
let mut files = vec![dir.join("Cargo.toml")];
files_in(&dir.join("src"), &mut files);
let mut h = Sha256::new();
for f in files {
h.update(
f.strip_prefix(dir)
.unwrap_or(&f)
.to_string_lossy()
.as_bytes(),
);
h.update([0]);
h.update(std::fs::read(&f).unwrap_or_default());
}
h.finalize()[..8]
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}
fn placeholders_check(dir: &Path) -> Check {
let mut files = Vec::new();
files_in(&dir.join("src"), &mut files);
let mut found = Vec::new();
for file in files
.iter()
.filter(|f| f.extension().is_some_and(|e| e == "rs"))
{
let text = std::fs::read_to_string(file).unwrap_or_default();
let rel = file.strip_prefix(dir).unwrap_or(file).to_string_lossy();
for (i, line) in text.lines().enumerate() {
let code = line.split("//").next().unwrap_or("");
if code.contains("todo!(") || code.contains("unimplemented!(") {
found.push(format!("{}:{}", rel.replace('\\', "/"), i + 1));
}
}
}
Check {
name: "placeholders",
passed: found.is_empty(),
detail: if found.is_empty() {
"no todo! or unimplemented!".into()
} else {
format!("todo! or unimplemented! at {}", found.join(", "))
},
fix: None,
}
}
fn first_line(text: &str) -> &str {
text.lines().find(|l| !l.trim().is_empty()).unwrap_or("")
}
fn tail(text: &str, n: usize) -> String {
let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
lines[lines.len().saturating_sub(n)..].join("\n")
}
pub fn check(dir: &Path, case: Option<&str>) -> Result<CheckOutcome> {
let shown = dir.display().to_string();
let dir = ensure_new_app(dir)?;
let cases_dir = dir.join(CASES);
let names: Vec<String> = app::case_previews(&cases_dir)?
.into_iter()
.map(|p| p.name)
.collect();
let names = match case {
Some(c) => pick(&names, &[c.to_string()])?,
None => names,
};
let target = dir.join("target");
let mut checks = Vec::new();
let mut failures = Vec::new();
let built = match crate::front_door::cargo_build(&dir, Some(&target)) {
Ok(_) if names.is_empty() => true,
Ok(exe) => {
let replay = app::replay_unwritten(&ReplayOptions {
repo: &dir,
build: Some(&app::shell_quote(&exe.to_string_lossy())),
timeout_secs: None,
port: None,
case,
})?;
failures = replay.failures;
true
}
Err(e) => {
checks.push(Check {
name: "build",
passed: false,
detail: tail(&format!("{e:#}"), 15),
fix: None,
});
false
}
};
let failing: BTreeSet<&str> = failures.iter().map(|f| f.case.as_str()).collect();
let approvals = load_approvals(&dir)?;
let cases: Vec<CaseResult> = names
.iter()
.map(|name| CaseResult {
name: name.clone(),
standing: match approvals.cases.get(name) {
Some(a) if a.hash == case_hash(&cases_dir, name) => Standing::Approved,
Some(_) => Standing::Changed,
None => Standing::Draft,
},
passed: built && !failing.contains(name.as_str()),
})
.collect();
let removed: Vec<String> = if case.is_none() {
approvals
.cases
.keys()
.filter(|k| !names.contains(k))
.cloned()
.collect()
} else {
Vec::new()
};
let approved_cases = cases.iter().filter(|c| c.standing != Standing::Draft);
let approved = Count {
passed: approved_cases
.clone()
.filter(|c| c.standing == Standing::Approved && c.passed)
.count(),
total: approved_cases.count(),
};
checks.extend(crate::gate::rust_checks(&dir, &target));
checks.push(placeholders_check(&dir));
let trend = (built && case.is_none() && approved.total > 0).then(|| {
crate::recording::track_in(
&dir.join(HISTORY),
&source_version(&dir),
approved.passed,
approved.total,
)
});
let open = open_questions(&dir);
let names_of = |standing: Standing| -> Vec<&str> {
cases
.iter()
.filter(|c| c.standing == standing)
.map(|c| c.name.as_str())
.collect()
};
let changed = names_of(Standing::Changed);
let drafts = names_of(Standing::Draft);
let failed_approved: Vec<&Failure> = failures
.iter()
.filter(|f| {
cases
.iter()
.any(|c| c.name == f.case && c.standing == Standing::Approved)
})
.collect();
let approve_cmd = format!("rust-anything spec approve {}", app::shell_quote(&shown));
let next = if !built {
Some("fix the build (see `build`)".to_string())
} else if !removed.is_empty() {
Some(format!(
"approved cases were removed: {}. Put them back, or ask the user to approve the spec without them (`{approve_cmd}`)",
removed.join(", ")
))
} else if !changed.is_empty() {
Some(format!(
"approved cases changed since the user approved them: {}. Undo the edit, or show the user the change and ask them to approve it (`{approve_cmd} --case {}`)",
changed.join(", "),
changed[0]
))
} else if names.is_empty() {
Some(format!(
"{CASES} has no cases: write the user's examples there as cases, then ask them to approve them"
))
} else if approved.total == 0 {
Some(format!(
"no case is approved yet: show the user the cases in {CASES} and ask them to run `{approve_cmd}`"
))
} else if let Some(f) = failed_approved.first() {
if trend.as_ref().is_some_and(|t| t.stalled) {
Some(format!(
"stalled: the last {} changes to src/ passed no more approved cases. Stop and show the user what still fails; they may know the rule you are missing",
crate::recording::STALL_AFTER
))
} else {
let why = f
.problems
.first()
.map(|p| format!(" ({}: {})", p.field, first_line(&p.detail)))
.unwrap_or_default();
Some(format!(
"make `{}` pass{why}; {} of {} approved cases fail",
f.case,
failed_approved.len(),
approved.total
))
}
} else if let Some(q) = open.first() {
Some(format!(
"ask the user: {q} Then write the answer in {SPEC} as `- [x] the question: the answer`"
))
} else if let Some(c) = checks.iter().find(|c| !c.passed) {
Some(
c.fix
.clone()
.unwrap_or_else(|| format!("{}: {}", c.name, first_line(&c.detail))),
)
} else if !drafts.is_empty() {
Some(format!(
"{} not approved: show the user and ask them to run `{approve_cmd}`, or delete the ones they reject",
drafts.join(", ")
))
} else if case.is_some() {
Some(format!(
"run `rust-anything spec check {}` without --case for the verdict",
app::shell_quote(&shown)
))
} else {
None
};
let app_name = app::Config::load(&dir)?.map_or_else(|| "app".to_string(), |c| c.name);
Ok(CheckOutcome {
schema: crate::state::schema("spec-check"),
at: crate::state::now(),
app: app_name,
done: next.is_none(),
approved,
cases,
removed,
failures,
open_questions: open,
checks,
trend,
next,
})
}
pub fn text(outcome: &CheckOutcome) -> String {
let mut out = format!(
"{}: {}\n",
outcome.app,
if outcome.done { "done" } else { "not done" }
);
out.push_str(&format!(
" approved cases: {} of {} pass\n",
outcome.approved.passed, outcome.approved.total
));
for (standing, label) in [
(Standing::Changed, "changed since approval"),
(Standing::Draft, "not approved"),
] {
let names: Vec<String> = outcome
.cases
.iter()
.filter(|c| c.standing == standing)
.map(|c| format!("{} ({})", c.name, if c.passed { "passes" } else { "fails" }))
.collect();
if !names.is_empty() {
out.push_str(&format!(" {label}: {}\n", names.join(", ")));
}
}
if !outcome.removed.is_empty() {
out.push_str(&format!(
" removed since approval: {}\n",
outcome.removed.join(", ")
));
}
for f in &outcome.failures {
let why: Vec<String> = f
.problems
.iter()
.map(|p| format!("{}: {}", p.field, first_line(&p.detail)))
.collect();
out.push_str(&format!(" failing {}: {}\n", f.case, why.join("; ")));
}
if !outcome.open_questions.is_empty() {
out.push_str(&format!(
" open questions ({SPEC}): {}\n",
outcome.open_questions.len()
));
for q in &outcome.open_questions {
out.push_str(&format!(" - {q}\n"));
}
}
for c in &outcome.checks {
let mark = if c.passed { "ok" } else { "FAIL" };
out.push_str(&format!(" {mark} {}: {}\n", c.name, first_line(&c.detail)));
if !c.passed {
for line in c.detail.lines().skip(1).take(14) {
out.push_str(&format!(" {line}\n"));
}
}
}
if let Some(next) = &outcome.next {
out.push_str(&format!("Next: {next}\n"));
}
out
}
pub fn approve_text(outcome: &ApproveOutcome) -> String {
let mut out = String::new();
for s in &outcome.approved {
out.push_str(&format!("Approved {}: {}\n", s.name, s.args.join(" ")));
if let Some(stdout) = &s.stdout {
for line in stdout.lines().take(3) {
out.push_str(&format!(" {line}\n"));
}
}
}
if !outcome.unchanged.is_empty() {
out.push_str(&format!(
"Already approved: {}\n",
outcome.unchanged.join(", ")
));
}
if !outcome.forgotten.is_empty() {
out.push_str(&format!(
"No longer in the spec: {}\n",
outcome.forgotten.join(", ")
));
}
out.push_str(&format!("Saved in {}\n", outcome.file.display()));
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_edited_input_folder_named_by_fs_base_needs_a_new_approval() {
let root = crate::app::temp_dir("spec-fs-base").unwrap();
let app = root.join("demo");
new_app(&app, Some("demo")).unwrap();
let cases = app.join(CASES);
std::fs::create_dir_all(cases.join("shared")).unwrap();
std::fs::write(cases.join("shared/input.txt"), "one\ntwo\nthree\n").unwrap();
std::fs::write(
cases.join("count.toml"),
"bin.name = \"demo\"\nargs = [\"input.txt\"]\nfs.base = \"shared\"\nfs.sandbox = true\n",
)
.unwrap();
std::fs::write(cases.join("count.stdout"), "3\n").unwrap();
let first = approve(&app, &[]).unwrap();
let same = approve(&app, &["count".to_string()]).unwrap();
std::fs::write(cases.join("shared/input.txt"), "a different input\n").unwrap();
let again = approve(&app, &["count".to_string()]).unwrap();
std::fs::remove_dir_all(&root).unwrap();
assert!(first.approved.iter().any(|s| s.name == "count"));
assert_eq!(same.unchanged, ["count"]);
assert!(
again.approved.iter().any(|s| s.name == "count"),
"the input changed, so the approval is new: {:?}",
again.unchanged
);
}
}