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
//! Where the original is and what it is, when the repository does not say it:
//! `rust/obligations-source.toml`. A port kept in a Rust workspace often holds the original out
//! of sight (an ignored `reference/` folder, an executable with no extension), and the language
//! detected from the files left is the wrong one.
//!
//! ```toml
//! lang = "python"
//! entry = ["reference/src/src"]
//! commands = ["status", "commit"]
//! flags = ["--verbose", "commit --message"]
//! ```
//!
//! - `lang` forces the language, for `obligations`, `obligations --check` and `app lift` alike.
//! - `entry` lists the original's executables, from the root: each is read for its commands,
//! flags, environment and error paths even when it is ignored or has no extension, and the
//! application counts as a CLI. Its functions are not exports: nobody calls them from outside.
//! - `commands` and `flags` list what the detectors cannot see (a dispatch table, `getattr`): a
//! flag is written alone (global) or after its command. They are obligations like the
//! detected ones; the family still needs a person's attestation.
//!
//! The file is read strictly, and every fault is reported at once: a wrong entry would make the
//! registry read nothing and call it empty.
use std::path::Path;
use anyhow::{Result, bail};
use toml_edit::{DocumentMut, Item};
use super::evidence::sources::{Opened, open};
use crate::lang::Lang;
/// Where the file lives, from the root of the repository.
pub const SOURCE_FILE: &str = "rust/obligations-source.toml";
const KEYS: [&str; 4] = ["lang", "entry", "commands", "flags"];
/// What `rust/obligations-source.toml` says. A missing file says nothing.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Source {
pub lang: Option<Lang>,
pub entries: Vec<String>,
pub commands: Vec<String>,
/// `(command, flag)`; `None` for a global flag.
pub flags: Vec<(Option<String>, String)>,
}
/// Reads `rust/obligations-source.toml` of `root`.
pub fn read(root: &Path) -> Result<Source> {
match open(root, SOURCE_FILE) {
Opened::Absent => Ok(Source::default()),
Opened::Refused(why) => bail!("{SOURCE_FILE} is not opened: {why}"),
Opened::Text(text) => parse(root, &text),
}
}
fn parse(root: &Path, text: &str) -> Result<Source> {
let doc: DocumentMut = match text.parse() {
Ok(doc) => doc,
Err(e) => bail!("invalid {SOURCE_FILE}: {e}"),
};
let mut faults: Vec<String> = Vec::new();
for (key, _) in doc.iter() {
if !KEYS.contains(&key) {
faults.push(format!("unknown key `{key}` (one of {})", KEYS.join(", ")));
}
}
let mut source = Source::default();
match doc.get("lang") {
None => {}
Some(item) => match item.as_str() {
Some(name) => match <Lang as clap::ValueEnum>::from_str(name, true) {
Ok(lang) => source.lang = Some(lang),
Err(_) => {
let names: Vec<String> = <Lang as clap::ValueEnum>::value_variants()
.iter()
.filter_map(clap::ValueEnum::to_possible_value)
.map(|v| v.get_name().to_string())
.collect();
faults.push(format!(
"`lang = \"{name}\"` is not a language (one of {})",
names.join(", ")
));
}
},
None => faults.push("`lang` must be a string".to_string()),
},
}
for entry in strings(&doc, "entry", &mut faults) {
match entry_fault(root, &entry) {
Some(fault) => faults.push(fault),
None if source.entries.contains(&entry) => {
faults.push(format!("entry `{entry}` is listed twice"));
}
None => source.entries.push(entry),
}
}
for command in strings(&doc, "commands", &mut faults) {
if command.is_empty() || command.starts_with('-') || command.contains(char::is_whitespace) {
faults.push(format!(
"command `{command}` must be one word that does not start with `-`"
));
} else if !source.commands.contains(&command) {
source.commands.push(command);
}
}
for flag in strings(&doc, "flags", &mut faults) {
let words: Vec<&str> = flag.split_whitespace().collect();
let parsed = match words.as_slice() {
[name] if is_flag(name) => Some((None, (*name).to_string())),
[command, name] if !command.starts_with('-') && is_flag(name) => {
Some((Some((*command).to_string()), (*name).to_string()))
}
_ => None,
};
match parsed {
Some(f) if !source.flags.contains(&f) => source.flags.push(f),
Some(_) => {}
None => faults.push(format!(
"flag `{flag}` must be `--name`, `-n` or `<command> --name`"
)),
}
}
if faults.is_empty() {
return Ok(source);
}
let list: String = faults.iter().map(|f| format!("\n - {f}")).collect();
bail!("invalid {SOURCE_FILE}:{list}")
}
fn is_flag(word: &str) -> bool {
word.len() > 1 && word.starts_with('-') && word != "--"
}
/// The strings of the array `key`; a value that is not one is a fault.
fn strings(doc: &DocumentMut, key: &str, faults: &mut Vec<String>) -> Vec<String> {
let Some(item) = doc.get(key) else {
return Vec::new();
};
let Some(array) = item.as_array().or_else(|| match item {
Item::Value(v) => v.as_array(),
_ => None,
}) else {
faults.push(format!("`{key}` must be an array of strings"));
return Vec::new();
};
let mut out = Vec::new();
for value in array {
match value.as_str() {
Some(s) => out.push(s.trim().to_string()),
None => faults.push(format!("`{key}` holds a value that is not a string")),
}
}
out
}
/// Why `entry` cannot be read as a file of the repository, if it cannot.
fn entry_fault(root: &Path, entry: &str) -> Option<String> {
let path = Path::new(entry);
if entry.is_empty()
|| path.is_absolute()
|| entry.contains('\\')
|| path
.components()
.any(|c| !matches!(c, std::path::Component::Normal(_)))
{
return Some(format!(
"entry `{entry}` must be a path from the root of the repository, with `/` and no `..`"
));
}
match open(root, entry) {
Opened::Text(_) => None,
Opened::Absent => Some(format!("entry `{entry}` does not exist")),
Opened::Refused(why) => Some(format!("entry `{entry}` is not opened: {why}")),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn repo(tag: &str, files: &[(&str, &str)]) -> std::path::PathBuf {
let dir =
std::env::temp_dir().join(format!("rust-anything-source-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
for (path, text) in files {
let full = dir.join(path);
std::fs::create_dir_all(full.parent().unwrap()).unwrap();
std::fs::write(full, text).unwrap();
}
dir
}
#[test]
fn a_missing_file_says_nothing() {
let dir = repo("missing", &[]);
assert_eq!(read(&dir).unwrap(), Source::default());
}
#[test]
fn reads_the_language_the_entries_and_the_declared_surface() {
let dir = repo(
"reads",
&[
("reference/src/src", "#!/usr/bin/env python3\n"),
(
SOURCE_FILE,
"lang = \"python\"\nentry = [\"reference/src/src\"]\n\
commands = [\"status\", \"commit\"]\nflags = [\"--verbose\", \"commit --message\"]\n",
),
],
);
let source = read(&dir).unwrap();
assert_eq!(source.lang, Some(Lang::Python));
assert_eq!(source.entries, ["reference/src/src"]);
assert_eq!(source.commands, ["status", "commit"]);
assert_eq!(
source.flags,
[
(None, "--verbose".to_string()),
(Some("commit".to_string()), "--message".to_string())
]
);
}
#[test]
fn every_fault_is_reported_at_once() {
let dir = repo(
"faults",
&[(
SOURCE_FILE,
"lang = \"cobol\"\nentry = [\"missing\", \"../outside\"]\n\
commands = [\"-x\"]\nflags = [\"verbose\"]\nextra = 1\n",
)],
);
let err = read(&dir).unwrap_err().to_string();
for needle in [
"`lang = \"cobol\"` is not a language",
"entry `missing` does not exist",
"entry `../outside` must be a path from the root",
"command `-x` must be one word",
"flag `verbose` must be",
"unknown key `extra`",
] {
assert!(err.contains(needle), "{needle} missing from {err}");
}
}
}