Skip to content

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.

fix: obligations source file, Python code points and whole-command wiring (#1504)

erKame52212156226
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b6eb593f..2feac540 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,26 @@
## Unreleased
+- `app wire` and `app lift` say that a CLI unit is reached through whole commands: `app wire`
+ refuses a `rust/app/src/main.rs` that never calls `units::dispatch` (a command answered in Rust
+ before it would never reach the unit), its "name the commands" error and lift's "no unit is
+ wired" blocker explain that a unit's helpers are called from the glue of a wired command, and
+ `docs/whole-apps.md` describes moving that Rust code into the glue (#1477, reported by
+ @alfa-reza).
+- Python: a `str` where a high surrogate code point comes right before a low one
+ (`chr(0xDC00) + chr(0xD800) + chr(0xDC00)`) now crosses the PyO3 bindings and the recordings as
+ `{"$codepoints": [...]}`, so it no longer becomes the same `{"$utf16": [...]}` as
+ `"\udc00\U00010000"` and a replay that confuses the two fails. Other strings with lone
+ surrogates keep `$utf16`, so existing recordings stay valid. A `record --inputs` line that fails
+ to parse (a JSON escape of a lone surrogate) names both markers (#1477, reported by @alfa-reza).
+- `obligations` reads `rust/obligations-source.toml` when the repository does not show the
+ original: `lang` forces the language, `entry` names its executables (read even when ignored or
+ without an extension, so the app counts as a CLI and its error paths count, but not its
+ functions as exports), and `commands` and `flags` list what no detector can see (a dispatch
+ table, `getattr`). `obligations --check` and `app lift` read the same file; `--check --lang`
+ is accepted when it matches the file and otherwise says to write it there, instead of being
+ refused. An entry where no command or flag was detected is reported as a site on that family,
+ never as a library (#1477, reported by @alfa-reza).
- C: `putc`, `fputc`, `dprintf`, `vprintf` and `vfprintf` count as printing, as `printf` does,
so `bridge` keeps a function that calls one in C with the reason ``prints (`putc`)``. Before, a
port that dropped the output passed `diff`. A member call such as `ops->putc(c)` is still not a
diff --git a/directory/skills/rust-anything/languages/python.md b/directory/skills/rust-anything/languages/python.md
index b1da6d3d..ab80c6b0 100644
--- a/directory/skills/rust-anything/languages/python.md
+++ b/directory/skills/rust-anything/languages/python.md
@@ -49,7 +49,9 @@ else `serde_json::Value`. `*args`, `**kwargs` and generators keep a function in
hold`, and `diff` shows the case as a mismatch where the original returned. To carry such
strings, leave the parameter unhinted or make it `serde_json::Value` in `port.rs` and run
`refresh`: the string arrives as `{"$utf16": [code units]}`, and returning that marker hands
- Python back the same string.
+ Python back the same string. A string where a high surrogate code point comes right before a
+ low one (`chr(0xD800) + chr(0xDC00)`, not `"\U00010000"`) would read back from its units as
+ another string, so it arrives as `{"$codepoints": [...]}` instead, in recordings too.
- **Letters**: `str.isalpha` takes letters only, where Rust's `char::is_alphanumeric` also takes
digits and more. Match the original's rule by general category.
- **numpy**: `record` cannot generate `np.ndarray` arguments. Record the app instead, or port the
diff --git a/directory/skills/rust-anything/whole-app.md b/directory/skills/rust-anything/whole-app.md
index 5b111990..5c095862 100644
--- a/directory/skills/rust-anything/whole-app.md
+++ b/directory/skills/rust-anything/whole-app.md
@@ -139,7 +139,12 @@ Then list what the original offers and what no case exercises yet:
`rust-anything obligations <repo> --evidence`. Every obligation without a case comes with a
candidate input: write the entries (lines for `--inputs`) and record again. A family listed as
`enumerated` or `none-found` (commands, flags, routes, environment variables, error paths) is not
-proven complete: the detectors list what they recognise, and the user attests the rest.
+proven complete: the detectors list what they recognise, and the user attests the rest. When
+the original is out of sight (an ignored `reference/` folder, an executable with no extension) or
+its language is detected wrong, write `rust/obligations-source.toml` with `lang = "python"` and
+`entry = ["reference/tool"]`: `obligations`, `--check` and `app lift` all read it. Commands and
+flags behind a dispatch the detectors cannot follow (a table of handlers, `getattr`) go under
+`commands` and `flags` in the same file, read from the original's source.
## 4. Build the front door
@@ -177,7 +182,10 @@ of SKILL.md with `--end-state scaffold` (the lift deletes its bindings), then:
`--route 'GET /users/{id}'` (axum syntax; `/path` for any method, `*` for every route no
other unit answers). Write the glue in `rust/app/src/units/<unit>.rs` (read the arguments or
the request, call `<crate>::port`, answer what the original answers: output and exit code, or
- status, headers and body), then run `app wire <repo> <unit>` again. For a library,
+ status, headers and body), then run `app wire <repo> <unit>` again. A CLI unit is reached
+ through whole commands only: for a unit of helpers (an escaping function, a parser), wire the
+ commands that call them and write those commands' Rust code in the glue; never answer a
+ command in `rust/app/src/main.rs` before `units::dispatch`. For a library,
`app wire <repo> <unit crate>` with no command or route: the unit's exports become a module of
`rust/app`, and `wire` writes the unit's shadow; change the original package to import the
shadow in place of the unit, so its callers reach the Rust.
diff --git a/docs/whole-apps.md b/docs/whole-apps.md
index 90fe8bc8..de7fcce6 100644
--- a/docs/whole-apps.md
+++ b/docs/whole-apps.md
@@ -187,6 +187,13 @@ rust-anything app wire . textkit # 100% again, lower fa
Wire the app's own name as a command (`--command mytool`) for argv that names no command: no
arguments, unknown commands, usage errors.
+`app wire` routes whole commands, never single call sites. A unit can hold only helpers (an
+escaping function, a parser) that several commands call: wire those commands to it, and write each
+command's Rust code in the unit's glue, which calls as many `<crate>::port` functions as it needs.
+Rust code that answers a command in `rust/app/src/main.rs` before `units::dispatch` never reaches
+a wired unit, so `app wire` refuses a `main.rs` that does not call `units::dispatch`, and `app
+lift` counts a helper as ported only through a wired command.
+
When replay passes with fallback rate 0 and every unit passes gate, make it a pure Rust app:
```sh
diff --git a/plugin/skills/rust-anything/languages/python.md b/plugin/skills/rust-anything/languages/python.md
index b1da6d3d..ab80c6b0 100644
--- a/plugin/skills/rust-anything/languages/python.md
+++ b/plugin/skills/rust-anything/languages/python.md
@@ -49,7 +49,9 @@ else `serde_json::Value`. `*args`, `**kwargs` and generators keep a function in
hold`, and `diff` shows the case as a mismatch where the original returned. To carry such
strings, leave the parameter unhinted or make it `serde_json::Value` in `port.rs` and run
`refresh`: the string arrives as `{"$utf16": [code units]}`, and returning that marker hands
- Python back the same string.
+ Python back the same string. A string where a high surrogate code point comes right before a
+ low one (`chr(0xD800) + chr(0xDC00)`, not `"\U00010000"`) would read back from its units as
+ another string, so it arrives as `{"$codepoints": [...]}` instead, in recordings too.
- **Letters**: `str.isalpha` takes letters only, where Rust's `char::is_alphanumeric` also takes
digits and more. Match the original's rule by general category.
- **numpy**: `record` cannot generate `np.ndarray` arguments. Record the app instead, or port the
diff --git a/plugin/skills/rust-anything/whole-app.md b/plugin/skills/rust-anything/whole-app.md
index 5b111990..5c095862 100644
--- a/plugin/skills/rust-anything/whole-app.md
+++ b/plugin/skills/rust-anything/whole-app.md
@@ -139,7 +139,12 @@ Then list what the original offers and what no case exercises yet:
`rust-anything obligations <repo> --evidence`. Every obligation without a case comes with a
candidate input: write the entries (lines for `--inputs`) and record again. A family listed as
`enumerated` or `none-found` (commands, flags, routes, environment variables, error paths) is not
-proven complete: the detectors list what they recognise, and the user attests the rest.
+proven complete: the detectors list what they recognise, and the user attests the rest. When
+the original is out of sight (an ignored `reference/` folder, an executable with no extension) or
+its language is detected wrong, write `rust/obligations-source.toml` with `lang = "python"` and
+`entry = ["reference/tool"]`: `obligations`, `--check` and `app lift` all read it. Commands and
+flags behind a dispatch the detectors cannot follow (a table of handlers, `getattr`) go under
+`commands` and `flags` in the same file, read from the original's source.
## 4. Build the front door
@@ -177,7 +182,10 @@ of SKILL.md with `--end-state scaffold` (the lift deletes its bindings), then:
`--route 'GET /users/{id}'` (axum syntax; `/path` for any method, `*` for every route no
other unit answers). Write the glue in `rust/app/src/units/<unit>.rs` (read the arguments or
the request, call `<crate>::port`, answer what the original answers: output and exit code, or
- status, headers and body), then run `app wire <repo> <unit>` again. For a library,
+ status, headers and body), then run `app wire <repo> <unit>` again. A CLI unit is reached
+ through whole commands only: for a unit of helpers (an escaping function, a parser), wire the
+ commands that call them and write those commands' Rust code in the glue; never answer a
+ command in `rust/app/src/main.rs` before `units::dispatch`. For a library,
`app wire <repo> <unit crate>` with no command or route: the unit's exports become a module of
`rust/app`, and `wire` writes the unit's shadow; change the original package to import the
shadow in place of the unit, so its callers reach the Rust.
diff --git a/skills/rust-anything/languages/python.md b/skills/rust-anything/languages/python.md
index b1da6d3d..ab80c6b0 100644
--- a/skills/rust-anything/languages/python.md
+++ b/skills/rust-anything/languages/python.md
@@ -49,7 +49,9 @@ else `serde_json::Value`. `*args`, `**kwargs` and generators keep a function in
hold`, and `diff` shows the case as a mismatch where the original returned. To carry such
strings, leave the parameter unhinted or make it `serde_json::Value` in `port.rs` and run
`refresh`: the string arrives as `{"$utf16": [code units]}`, and returning that marker hands
- Python back the same string.
+ Python back the same string. A string where a high surrogate code point comes right before a
+ low one (`chr(0xD800) + chr(0xDC00)`, not `"\U00010000"`) would read back from its units as
+ another string, so it arrives as `{"$codepoints": [...]}` instead, in recordings too.
- **Letters**: `str.isalpha` takes letters only, where Rust's `char::is_alphanumeric` also takes
digits and more. Match the original's rule by general category.
- **numpy**: `record` cannot generate `np.ndarray` arguments. Record the app instead, or port the
diff --git a/skills/rust-anything/whole-app.md b/skills/rust-anything/whole-app.md
index 5b111990..5c095862 100644
--- a/skills/rust-anything/whole-app.md
+++ b/skills/rust-anything/whole-app.md
@@ -139,7 +139,12 @@ Then list what the original offers and what no case exercises yet:
`rust-anything obligations <repo> --evidence`. Every obligation without a case comes with a
candidate input: write the entries (lines for `--inputs`) and record again. A family listed as
`enumerated` or `none-found` (commands, flags, routes, environment variables, error paths) is not
-proven complete: the detectors list what they recognise, and the user attests the rest.
+proven complete: the detectors list what they recognise, and the user attests the rest. When
+the original is out of sight (an ignored `reference/` folder, an executable with no extension) or
+its language is detected wrong, write `rust/obligations-source.toml` with `lang = "python"` and
+`entry = ["reference/tool"]`: `obligations`, `--check` and `app lift` all read it. Commands and
+flags behind a dispatch the detectors cannot follow (a table of handlers, `getattr`) go under
+`commands` and `flags` in the same file, read from the original's source.
## 4. Build the front door
@@ -177,7 +182,10 @@ of SKILL.md with `--end-state scaffold` (the lift deletes its bindings), then:
`--route 'GET /users/{id}'` (axum syntax; `/path` for any method, `*` for every route no
other unit answers). Write the glue in `rust/app/src/units/<unit>.rs` (read the arguments or
the request, call `<crate>::port`, answer what the original answers: output and exit code, or
- status, headers and body), then run `app wire <repo> <unit>` again. For a library,
+ status, headers and body), then run `app wire <repo> <unit>` again. A CLI unit is reached
+ through whole commands only: for a unit of helpers (an escaping function, a parser), wire the
+ commands that call them and write those commands' Rust code in the glue; never answer a
+ command in `rust/app/src/main.rs` before `units::dispatch`. For a library,
`app wire <repo> <unit crate>` with no command or route: the unit's exports become a module of
`rust/app`, and `wire` writes the unit's shadow; change the original package to import the
shadow in place of the unit, so its callers reach the Rust.
diff --git a/src/codegen_py.rs b/src/codegen_py.rs
index 4ef13c77..c9bee92a 100644
--- a/src/codegen_py.rs
+++ b/src/codegen_py.rs
@@ -1159,7 +1159,8 @@ def _method(name, positions, names, json_result):
/// `src/pyconv.rs`: Python objects to `serde_json::Value` and back, in Rust, without JSON text.
/// Values the JSON model lacks use the same markers as recorded cases: `$tuple`, `$set`,
/// `$bytes`, `$path` (a `pathlib` path), `$int` (beyond i64), `$dict` (non-string keys), `$num`
-/// (NaN, infinities, -0), `$utf16` (strings with lone surrogates).
+/// (NaN, infinities, -0), `$utf16` (strings with lone surrogates), `$codepoints` (those whose
+/// UTF-16 units would read back as another string).
pub const PYCONV_RS: &str = r#"//! Python objects to `serde_json::Value` and back, in Rust. Generated by rust-anything.
#![forbid(unsafe_code)]
@@ -1192,7 +1193,9 @@ pub fn argument(name: &str, error: String) -> String {
fn holds_utf16(v: &Value) -> bool {
match v {
Value::Array(items) => items.iter().any(holds_utf16),
- Value::Object(o) => o.contains_key("$utf16") || o.values().any(holds_utf16),
+ Value::Object(o) => {
+ o.contains_key("$utf16") || o.contains_key("$codepoints") || o.values().any(holds_utf16)
+ }
_ => false,
}
}
@@ -1268,20 +1271,35 @@ fn py_string_value(obj: &Bound<'_, PyAny>) -> Result<Value, String> {
return Ok(Value::String(s));
}
// Lone surrogates (e.g. from `errors="surrogateescape"`) cannot become Rust UTF-8 `String`:
- // encode their UTF-16 code units with the same `$utf16` marker recordings use.
+ // encode their UTF-16 code units with the same `$utf16` marker recordings use. A high then a
+ // low surrogate code point would read back as one character, so a string with that pair keeps
+ // its code points instead (`$codepoints`), as the recorder does.
let encoded = obj
- .call_method1("encode", ("utf-16-le", "surrogatepass"))
+ .call_method1("encode", ("utf-32-le", "surrogatepass"))
.map_err(|e| e.to_string())?;
let bytes = encoded
.cast::<PyBytes>()
.map_err(|e| e.to_string())?
.as_bytes();
- let units: Vec<u16> = bytes
- .as_chunks::<2>()
+ let points: Vec<u32> = bytes
+ .as_chunks::<4>()
.0
.iter()
- .map(|c| u16::from_le_bytes(*c))
+ .map(|c| u32::from_le_bytes(*c))
.collect();
+ let paired = points
+ .windows(2)
+ .any(|w| (0xD800..0xDC00).contains(&w[0]) && (0xDC00..0xE000).contains(&w[1]));
+ if paired {
+ return Ok(json!({"$codepoints": points}));
+ }
+ let mut units: Vec<u16> = Vec::with_capacity(points.len());
+ for point in points {
+ match char::from_u32(point) {
+ Some(c) => units.extend(c.encode_utf16(&mut [0; 2]).iter()),
+ None => units.push(point as u16),
+ }
+ }
Ok(json!({"$utf16": units}))
}
@@ -1797,6 +1815,22 @@ fn entry(py: Python<'_>, key: &str, inner: &Value) -> PyResult<Py<PyAny>> {
dict.into_any().unbind()
}
},
+ "$codepoints" => match inner.as_array() {
+ Some(points) if points.iter().all(|c| c.as_u64().is_some_and(|c| c <= 0x10FFFF)) => {
+ let mut raw = Vec::with_capacity(points.len() * 4);
+ for point in points {
+ raw.extend_from_slice(&(point.as_u64().expect("checked") as u32).to_le_bytes());
+ }
+ PyBytes::new(py, &raw)
+ .call_method1("decode", ("utf-32-le", "surrogatepass"))?
+ .unbind()
+ }
+ _ => {
+ let dict = PyDict::new(py);
+ dict.set_item(key, to_py(py, inner)?)?;
+ dict.into_any().unbind()
+ }
+ },
_ => {
let dict = PyDict::new(py);
dict.set_item(key, to_py(py, inner)?)?;
diff --git a/src/front_door.rs b/src/front_door.rs
index 4d0656a5..b6eb2d67 100644
--- a/src/front_door.rs
+++ b/src/front_door.rs
@@ -20,6 +20,15 @@ pub const KILL_SWITCH_PREFIX: &str = "RUST_ANYTHING_UNIT_";
const SCHEMA: &str = "rust-anything/front-door@1";
const GLUE_MARKER: &str = "unimplemented!(\"glue for";
+/// How a unit is reached in a CLI, for the errors of `wire` and `lift`: whole commands, never
+/// call sites.
+pub(crate) const WHOLE_COMMANDS: &str = "`app wire` hands whole commands to a unit: \
+ `units::dispatch` in rust/app/src/main.rs routes each one to the unit's glue \
+ (rust/app/src/units/<unit>.rs), and the glue calls the unit's helpers in `<crate>::port`. A \
+ helper called from Rust code that answers a command before `units::dispatch` is not reached \
+ and cannot be wired on its own: wire that command to the unit and move its Rust code into the \
+ glue, which may call any number of the unit's functions";
+
/// The glue file still holds the stub `wire` wrote, however rustfmt wrapped it.
pub(crate) fn is_stub(glue: &str) -> bool {
let squash = |s: &str| s.split_whitespace().collect::<String>();
@@ -1246,6 +1255,16 @@ fn wire_unit(opts: &WireOptions) -> Result<WireOutcome> {
"the app is lifted: there is no fallback left to wire around; call the crate from src/units directly"
);
let app_dir = repo.join(APP_DIR);
+ if state.kind == AppKind::Cli {
+ let main = app_dir.join("src/main.rs");
+ let text = std::fs::read_to_string(&main)
+ .with_context(|| format!("reading {}", main.display()))?;
+ ensure!(
+ text.contains("units::dispatch("),
+ "{} never calls `units::dispatch`, so no command wired to a unit would reach it. {WHOLE_COMMANDS}",
+ main.display()
+ );
+ }
let crate_dir = find_unit(&repo, opts.unit)?;
let manifest_text = std::fs::read_to_string(crate_dir.join("Cargo.toml"))?;
let unit_doc: DocumentMut = manifest_text.parse()?;
@@ -1336,7 +1355,9 @@ fn wire_unit(opts: &WireOptions) -> Result<WireOutcome> {
} else if opts.commands.is_empty() {
previous
.map(|i| state.units[i].commands.clone())
- .with_context(|| format!("name the commands {name} answers with --command"))?
+ .with_context(|| {
+ format!("name the commands {name} answers with --command. {WHOLE_COMMANDS}")
+ })?
} else {
opts.commands.to_vec()
};
@@ -1646,6 +1667,7 @@ mod tests {
)
.unwrap();
std::fs::write(app.join("src/units/mod.rs"), "").unwrap();
+ std::fs::write(app.join("src/main.rs"), MAIN_RS).unwrap();
for name in crates {
let dir = repo.join("rust").join(name);
std::fs::create_dir_all(&dir).unwrap();
diff --git a/src/harness.rs b/src/harness.rs
index 38371888..c82e41e0 100644
--- a/src/harness.rs
+++ b/src/harness.rs
@@ -391,7 +391,9 @@ pub(crate) fn parse_inputs(
let mut case: Value = parse_deep(line).with_context(|| {
format!(
"{} (values use the record codec: {{\"$undefined\": true}}, {{\"$num\": \"NaN\"}}, \
- and {{\"$utf16\": [code units]}} for strings with lone surrogates)",
+ {{\"$utf16\": [code units]}} for strings with lone surrogates, and in Python \
+ {{\"$codepoints\": [code points]}} for those where a high surrogate comes right \
+ before a low one)",
at(i + 1)
)
})?;
diff --git a/src/harness_py.rs b/src/harness_py.rs
index e52e5cf0..dcb06849 100644
--- a/src/harness_py.rs
+++ b/src/harness_py.rs
@@ -352,6 +352,10 @@ def enc_str(v):
v.encode("utf-8")
except UnicodeEncodeError:
raw = v.encode("utf-16-le", "surrogatepass")
+ if raw.decode("utf-16-le", "surrogatepass") != v:
+ # A high then a low surrogate code point: their units read back as one character, so
+ # "\udc00\ud800\udc00" and "\udc00\U00010000" would record alike.
+ return {"$codepoints": [ord(c) for c in v]}
return {"$utf16": [int.from_bytes(raw[i:i + 2], "little") for i in range(0, len(raw), 2)]}
return v
@@ -415,6 +419,8 @@ def dec(v):
return {dec(k): dec(x) for k, x in inner}
if key == "$utf16" and isinstance(inner, list) and all(isinstance(u, int) and not isinstance(u, bool) and 0 <= u <= 0xFFFF for u in inner):
return b"".join(u.to_bytes(2, "little") for u in inner).decode("utf-16-le", "surrogatepass")
+ if key == "$codepoints" and isinstance(inner, list) and all(isinstance(c, int) and not isinstance(c, bool) and 0 <= c <= 0x10FFFF for c in inner):
+ return "".join(chr(c) for c in inner)
if set(v) == {"$object", "attrs"} and isinstance(v["attrs"], dict):
cls = dataclass_named(v["$object"])
if cls is not None:
@@ -1074,6 +1080,12 @@ out["surrogate_decodes"] = m.dec(encoded) == surr
out["surrogate_empty_utf16"] = m.dec({"$utf16": []}) == ""
out["surrogate_non_list_stays_dict"] = m.dec({"$utf16": "literal"}) == {"$utf16": "literal"}
surr_dict = m.enc({surr: surr})
+pair = chr(0xDC00) + chr(0xD800) + chr(0xDC00)
+astral = chr(0xDC00) + chr(0x10000)
+out["surrogate_pair_of_code_points_differs"] = m.enc(pair) != m.enc(astral)
+out["surrogate_pair_of_code_points_marker"] = m.enc(pair) == {"$codepoints": [0xDC00, 0xD800, 0xDC00]}
+out["surrogate_pair_of_code_points_decodes"] = m.dec(m.enc(pair)) == pair and m.dec(m.enc(astral)) == astral
+out["surrogate_codepoints_out_of_range_stays_dict"] = m.dec({"$codepoints": [0x110000]}) == {"$codepoints": [0x110000]}
out["surrogate_dict_key"] = surr_dict == {"$dict": [[encoded, encoded]]} and m.dec(surr_dict) == {surr: surr}
print(json.dumps(out))
"#;
diff --git a/src/lift.rs b/src/lift.rs
index b31e9925..67ce7764 100644
--- a/src/lift.rs
+++ b/src/lift.rs
@@ -1653,7 +1653,14 @@ fn lift_app_dir(opts: &LiftOptions) -> Result<LiftOutcome> {
.unwrap_or_else(|_| repo.join("rust"));
let mut blockers = Vec::new();
if state.units.is_empty() {
- blockers.push("no unit is wired yet: run `rust-anything app wire` first".to_string());
+ blockers.push(if state.kind == AppKind::Cli {
+ format!(
+ "no unit is wired yet: run `rust-anything app wire` first ({})",
+ front_door::WHOLE_COMMANDS
+ )
+ } else {
+ "no unit is wired yet: run `rust-anything app wire` first".to_string()
+ });
}
let mut units = Vec::new();
for unit in &state.units {
diff --git a/src/main.rs b/src/main.rs
index 174377be..59449e82 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -614,9 +614,12 @@ enum Cmd {
/// recorded case, no registry entry and no waiver covers. It is an error when rust/obligations-bindings.toml or
/// rust/obligations-decisions.toml is invalid. With `--json` it prints the standing
/// (schema `rust-anything/standing@1`).
- #[arg(long, conflicts_with_all = ["lang", "write", "evidence"])]
+ #[arg(long, conflicts_with_all = ["write", "evidence"])]
check: bool,
- /// Source language; detected from the repository when omitted.
+ /// Source language; rust/obligations-source.toml gives it when omitted, or it is detected
+ /// from the repository. With `--check` it must match that file, which `app lift` reads
+ /// too. The same file names the original's executables (`entry`, read even when ignored
+ /// or extensionless) and the commands and flags no detector can see.
#[arg(long, value_enum)]
lang: Option<rust_anything::lang::Lang>,
/// Write the ledger to rust/OBLIGATIONS.json in the repository instead of printing it.
@@ -2492,8 +2495,25 @@ fn run() -> Result<ExitCode> {
repo,
check: true,
json,
+ lang,
..
} => {
+ if let Some(lang) = lang {
+ let root = rust_anything::walk::resolve_root(&repo)?;
+ let declared = rust_anything::obligations::source::read(&root)?;
+ if declared.lang != Some(lang) {
+ anyhow::bail!(
+ "`--check` reads the language from {file}, as `app lift` does: write \
+ `lang = \"{name}\"` there (and `entry = [\"path/to/script\"]` for an \
+ executable that is ignored or has no extension), then run \
+ `rust-anything obligations --check` again",
+ file = rust_anything::obligations::source::SOURCE_FILE,
+ name = clap::ValueEnum::to_possible_value(&lang)
+ .map(|v| v.get_name().to_string())
+ .unwrap_or_default(),
+ );
+ }
+ }
let standing = rust_anything::obligations::standing::standing(&repo)?;
if json {
say!("{}", serde_json::to_string_pretty(&standing)?);
diff --git a/src/obligations/evidence/mod.rs b/src/obligations/evidence/mod.rs
index 381a1a0b..fc5ec53c 100644
--- a/src/obligations/evidence/mod.rs
+++ b/src/obligations/evidence/mod.rs
@@ -31,7 +31,7 @@ mod bindings;
mod cli;
mod lens;
mod routes;
-mod sources;
+pub(in crate::obligations) mod sources;
mod unit;
pub(crate) use lens::{CliProbe, Digest, HttpProbe, Lens};
diff --git a/src/obligations/mod.rs b/src/obligations/mod.rs
index 03b7175d..3d83d179 100644
--- a/src/obligations/mod.rs
+++ b/src/obligations/mod.rs
@@ -31,6 +31,7 @@ mod facts;
mod gaps;
mod py_file;
mod python;
+pub mod source;
pub mod standing;
pub mod surface;
mod ts;
@@ -325,8 +326,8 @@ fn package_of(lang: Lang, spec: &str) -> Option<&str> {
/// The surface detector of a file: `(path, text)`.
pub type Detector<'a> = &'a dyn Fn(&str, &str) -> Surface;
-/// The obligation registry of the repository `root`. `lang` forces the language; otherwise it is
-/// detected.
+/// The obligation registry of the repository `root`. `lang` forces the language; otherwise
+/// `rust/obligations-source.toml` does, or it is detected.
pub fn ledger(root: &Path, lang: Option<Lang>) -> Result<Ledger> {
build(root, lang, None)
}
@@ -339,10 +340,17 @@ pub fn ledger_with(root: &Path, lang: Option<Lang>, detector: Detector) -> Resul
fn build(root: &Path, lang: Option<Lang>, injected: Option<Detector>) -> Result<Ledger> {
let root = crate::walk::resolve_root(root)?;
+ let declared_source = source::read(&root)?;
+ let lang = lang.or(declared_source.lang);
// `analyze` recurses into the files: on the calling thread, a file with a chain of tens of
// thousands of links overflows the stack. So the analysis runs on a thread whose stack
// follows the biggest file of the repository; nothing is written before the end.
- let biggest = gaps::largest_file(&root, lang);
+ let biggest = declared_source
+ .entries
+ .iter()
+ .filter_map(|e| std::fs::metadata(root.join(e)).ok())
+ .map(|m| usize::try_from(m.len()).unwrap_or(usize::MAX))
+ .fold(gaps::largest_file(&root, lang), usize::max);
let (report, app) = facts::on_stack_of(biggest, &|| {
let report = match lang {
Some(lang) => crate::analyze::analyze_lang(&root, lang),
@@ -436,6 +444,14 @@ fn build(root: &Path, lang: Option<Lang>, injected: Option<Detector>) -> Result<
let mut read: HashSet<String> = inventoried.clone();
let mut queue: VecDeque<(String, Depth)> =
sources.iter().map(|s| (s.clone(), Depth::Whole)).collect();
+ for entry in &declared_source.entries {
+ if read.insert(entry.clone()) {
+ known.insert(entry.clone());
+ queue.push_back((entry.clone(), Depth::Entry));
+ } else if let Some(queued) = queue.iter_mut().find(|(p, _)| p == entry) {
+ queued.1 = Depth::Entry;
+ }
+ }
let mut configs_queued = false;
// The external packages unknown to the detectors, (package, file, line), and the packages
// with an import that is already an "is not followed" site.
@@ -503,14 +519,21 @@ fn build(root: &Path, lang: Option<Lang>, injected: Option<Detector>) -> Result<
inventory.add_gaps(gaps::find(&root, lang, &workspace, &inventoried, &read));
inventory.add_gaps(entries.gaps);
inventory.scan_lines(lang, &root, &units);
+ inventory.declared_source(&declared_source);
let has_cli = app.entry_points.iter().any(|e| e.kind == "cli")
|| (lang == Lang::Ts && gaps::declares_bin(&root, &workspace))
- || entries.cli;
+ || entries.cli
+ || !declared_source.entries.is_empty();
let has_server = app.entry_points.iter().any(|e| e.kind == "server");
+ let shape = if app.shape == "library" && !declared_source.entries.is_empty() {
+ "cli"
+ } else {
+ app.shape
+ };
let context = App {
lang,
- shape: app.shape.to_string(),
+ shape: shape.to_string(),
reader: detector.map(|_| surface_reader(lang)),
has_cli,
has_server,
@@ -580,6 +603,9 @@ enum Depth {
/// raises is a tool's configuration, not a function of the application; what it reads from
/// the environment counts.
Surface,
+ /// An executable named in `rust/obligations-source.toml`: its surface and its error paths.
+ /// Its functions are not exports: nobody calls them from outside the program.
+ Entry,
}
struct Reader<'a> {
@@ -634,8 +660,8 @@ impl Reader<'_> {
for (line, reason) in &facts.unreadable {
inv.site_at(depth, path, *line, reason);
}
- if depth == Depth::Whole {
- self.record(inv, path, unit, facts);
+ if depth != Depth::Surface {
+ self.record(inv, path, unit, facts, depth == Depth::Whole);
}
if let Some(detect) = self.detector {
self.surface(inv, path, unit, detect(path, &text));
@@ -674,24 +700,37 @@ impl Reader<'_> {
.collect()
}
- fn record(&self, inv: &mut Inventory, path: &str, unit: Option<&str>, facts: FileFacts) {
+ /// Records what the file offers; its exports only when `exports` (an executable's functions
+ /// are not called from outside, but their error paths count).
+ fn record(
+ &self,
+ inv: &mut Inventory,
+ path: &str,
+ unit: Option<&str>,
+ facts: FileFacts,
+ exports: bool,
+ ) {
let ast = ast_errors(self.lang);
for n in facts.named {
- inv.exports.push(draft(
- Family::Export,
- export_id(path, &n.name),
- &n.name,
- path,
- n.line,
- unit,
- n.detail.clone(),
- ));
+ if exports {
+ inv.exports.push(draft(
+ Family::Export,
+ export_id(path, &n.name),
+ &n.name,
+ path,
+ n.line,
+ unit,
+ n.detail.clone(),
+ ));
+ }
if !ast {
inv.raisers.push((n.name, path.to_string(), n.line));
}
}
- for (line, reason) in facts.unresolved {
- inv.site(Family::Export, path, line, &reason);
+ if exports {
+ for (line, reason) in facts.unresolved {
+ inv.site(Family::Export, path, line, &reason);
+ }
}
for (line, spec) in facts.relative_reexports {
inv.reexports.push((path.to_string(), line, spec));
@@ -822,6 +861,11 @@ impl Inventory {
fn site_at(&mut self, depth: Depth, file: &str, line: u32, reason: &str) {
match depth {
Depth::Whole => self.site_all(file, line, reason),
+ Depth::Entry => {
+ for family in SURFACE_FAMILIES.into_iter().chain([Family::ErrorPath]) {
+ self.site(family, file, line, reason);
+ }
+ }
Depth::Surface => {
for family in SURFACE_FAMILIES {
self.site(family, file, line, reason);
@@ -830,6 +874,73 @@ impl Inventory {
}
}
+ /// What `rust/obligations-source.toml` adds: a site on the commands and the flags of an entry
+ /// where no detector saw any, unless a person listed them; then the commands and the flags
+ /// that person listed, as obligations of the first entry (of the file itself without one).
+ fn declared_source(&mut self, declared: &source::Source) {
+ let from_file = |family: Family, file: &str, drafts: &[Draft], sites: &[Site]| {
+ drafts
+ .iter()
+ .any(|d| d.obligation.family == family && d.file == file)
+ || sites.iter().any(|s| s.family == family && s.file == file)
+ };
+ for entry in &declared.entries {
+ for (family, listed, key) in [
+ (Family::Command, !declared.commands.is_empty(), "commands"),
+ (Family::Flag, !declared.flags.is_empty(), "flags"),
+ ] {
+ if listed || from_file(family, entry, &self.surface, &self.sites) {
+ continue;
+ }
+ let reason = format!(
+ "no {} was detected in this entry point: a dispatch the detectors cannot \
+ follow (a table of handlers, getattr, argv read by hand) hides them; list \
+ them under `{key}` in {}, or attest the family if it has none",
+ family.noun(),
+ source::SOURCE_FILE
+ );
+ self.site(family, entry, 1, &reason);
+ }
+ }
+ let owner = declared
+ .entries
+ .first()
+ .map_or(source::SOURCE_FILE, String::as_str);
+ let detail = Some(format!("declared in {}", source::SOURCE_FILE));
+ let commands = declared.commands.iter().map(|c| Found {
+ family: Family::Command,
+ name: c.clone(),
+ line: 1,
+ scope: None,
+ detail: detail.clone(),
+ });
+ let flags = declared.flags.iter().map(|(scope, f)| Found {
+ family: Family::Flag,
+ name: f.clone(),
+ line: 1,
+ scope: scope.clone(),
+ detail: detail.clone(),
+ });
+ for found in commands.chain(flags) {
+ let Some(id) = surface_id(&found, owner) else {
+ continue;
+ };
+ if !self.surface.iter().any(|d| d.obligation.id == id) {
+ self.surface.push(draft(
+ found.family,
+ id,
+ &found.name,
+ owner,
+ found.line,
+ None,
+ found.detail.clone(),
+ ));
+ self.recognised
+ .insert((found.family, source::SOURCE_FILE.to_string()));
+ }
+ }
+ }
+
/// One site per unknown package and per surface family, at the first import in (path, line)
/// order. `foreign`: (package, file, line) of the unknown external packages; `unfollowed`:
/// the packages with an import that is already an "is not followed" site, which covers all
diff --git a/src/obligations/source.rs b/src/obligations/source.rs
new file mode 100644
index 00000000..2b3feaff
--- /dev/null
+++ b/src/obligations/source.rs
@@ -0,0 +1,248 @@
+//! 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}");
+ }
+ }
+}
diff --git a/tests/app.rs b/tests/app.rs
index 6dcb1658..6a700740 100644
--- a/tests/app.rs
+++ b/tests/app.rs
@@ -530,6 +530,86 @@ fn write_unit(repo: &Path, name: &str, port: &str) {
std::fs::write(unit.join("src/port.rs"), port).unwrap();
}
+/// Issue #1477: a front door that answers commands in Rust before `units::dispatch` never reaches a
+/// wired unit, and a helper cannot be wired on its own. `wire` and `lift` say so instead of
+/// wiring a unit nothing calls.
+#[test]
+fn wire_requires_whole_command_routing_and_says_so() {
+ let repo = fixture("python");
+ app::record(&RecordOptions {
+ repo: &repo,
+ run: &words("python3 tcli.py"),
+ inputs: None,
+ normalize: &[],
+ name: None,
+ traps: false,
+ timeout_secs: None,
+ http: None,
+ server_args: None,
+ fresh: None,
+ pace_ms: None,
+ port: None,
+ float_tolerance: None,
+ float_files: &[],
+ effects: None,
+ ready_secs: None,
+ ready_request: None,
+ sandbox: false,
+ })
+ .unwrap();
+ front_door::front_door(&FrontDoorOptions {
+ repo: &repo,
+ library: false,
+ check: false,
+ commands: &[],
+ })
+ .unwrap();
+ write_unit(&repo, "helpers-rs", WORDCOUNT_PORT);
+
+ let blocked = lift::lift(&LiftOptions { repo: &repo }).unwrap();
+ let blocker = blocked
+ .blockers
+ .iter()
+ .find(|b| b.contains("no unit is wired"))
+ .unwrap_or_else(|| panic!("{:?}", blocked.blockers));
+ assert!(
+ blocker.contains("whole commands") && blocker.contains("glue"),
+ "{blocker}"
+ );
+
+ let wire = |commands: &[&str]| {
+ front_door::wire(&WireOptions {
+ repo: &repo,
+ unit: "helpers",
+ commands: &commands.iter().map(|c| c.to_string()).collect::<Vec<_>>(),
+ routes: &[],
+ skip_gate: true,
+ check: false,
+ })
+ };
+ let unnamed = format!("{:#}", wire(&[]).unwrap_err());
+ assert!(
+ unnamed.contains("--command") && unnamed.contains("hands whole commands"),
+ "{unnamed}"
+ );
+
+ let main = repo.join("rust/app/src/main.rs");
+ std::fs::write(
+ &main,
+ "mod cli;\nmod original;\nmod units;\n\nfn main() -> std::process::ExitCode {\n \
+ let argv: Vec<std::ffi::OsString> = std::env::args_os().collect();\n \
+ original::run(&argv[1..])\n}\n",
+ )
+ .unwrap();
+ let native = format!("{:#}", wire(&["words"]).unwrap_err());
+ assert!(
+ native.contains("never calls `units::dispatch`")
+ && native.contains("move its Rust code into the glue"),
+ "{native}"
+ );
+ std::fs::remove_dir_all(&repo).unwrap();
+}
+
/// How the original counts and uppercases: a faithful port matches its own language.
struct Semantics {
count: &'static str,
diff --git a/tests/native.rs b/tests/native.rs
index 05fe89ce..d9ca7bd8 100644
--- a/tests/native.rs
+++ b/tests/native.rs
@@ -536,6 +536,142 @@ fn pyo3_lone_surrogates_round_trip_through_utf16_marker() {
std::fs::remove_dir_all(root).unwrap();
}
+#[test]
+fn pyo3_a_surrogate_pair_of_code_points_stays_apart_from_the_astral_character() {
+ // Issue #1477: "\udc00\ud800\udc00" (three code points) and "\udc00\U00010000" (two) have
+ // the same UTF-16 units, so `$utf16` recorded and bridged them alike.
+ let Some(python) = common::python() else {
+ return;
+ };
+ let root = project(
+ "pyo3-codepoints",
+ &[
+ (
+ "pyproject.toml",
+ "[project]\nname = \"pairkit\"\nversion = \"0.1.0\"\n",
+ ),
+ ("pairkit/__init__.py", "def echo(s):\n return s\n"),
+ ],
+ );
+ let dir = root.join("port");
+ bridge::bridge(&bridge::Options {
+ root: &root,
+ unit: "pairkit/",
+ kind: Some(Kind::Pyo3),
+ out: Some(dir.clone()),
+ name: None,
+ force: false,
+ keep: Vec::new(),
+ lang: None,
+ batch: Vec::new(),
+ as_json: Vec::new(),
+ allocator: Default::default(),
+ })
+ .unwrap();
+
+ let inputs = root.join("inputs.jsonl");
+ std::fs::write(
+ &inputs,
+ "{\"fn\": \"echo\", \"args\": [{\"$codepoints\": [56320, 55296, 56320]}]}\n\
+ {\"fn\": \"echo\", \"args\": [{\"$utf16\": [56320, 55296, 56320]}]}\n",
+ )
+ .unwrap();
+ let recorded = harness::record(&RecordOptions {
+ crate_dir: &dir,
+ count: 0,
+ inputs: Some(&inputs),
+ module: None,
+ resolve_from: None,
+ node_args: &[],
+ sandbox: false,
+ })
+ .unwrap();
+ assert_eq!(recorded.cases, 2, "{recorded:?}");
+ let cases = std::fs::read_to_string(dir.join("cases.jsonl")).unwrap();
+ assert!(
+ cases.contains(r#""ok": {"$codepoints": [56320, 55296, 56320]}"#),
+ "{cases}"
+ );
+ assert!(
+ cases.contains(r#""ok": {"$utf16": [56320, 55296, 56320]}"#),
+ "{cases}"
+ );
+
+ let port_path = dir.join("src/port.rs");
+ let original = std::fs::read_to_string(&port_path).unwrap();
+ let with_body = |body: &str| {
+ let start = original.find("pub fn echo(").unwrap();
+ let open = start + original[start..].find('{').unwrap();
+ let close = open + original[open..].find("\n}").unwrap();
+ format!("{}{{\n {body}{}", &original[..open], &original[close..])
+ };
+ let diff = || {
+ harness::build(&dir).unwrap();
+ harness::diff(&DiffOptions {
+ crate_dir: &dir,
+ module: None,
+ ignore_key_order: false,
+ node_args: &[],
+ float_tolerance: None,
+ })
+ .unwrap()
+ };
+
+ std::fs::write(&port_path, with_body("Ok(s)")).unwrap();
+ let outcome = diff();
+ assert_eq!(
+ (outcome.failed, outcome.passed),
+ (0, 2),
+ "{:#?}",
+ outcome.mismatches
+ );
+
+ let check = Command::new(python)
+ .env("PYTHONPATH", dir.join("python"))
+ .args([
+ "-c",
+ "import pairkit_rs as m\n\
+ pair = chr(0xDC00) + chr(0xD800) + chr(0xDC00)\n\
+ astral = chr(0xDC00) + chr(0x10000)\n\
+ assert [ord(c) for c in m.echo(pair)] == [0xDC00, 0xD800, 0xDC00], repr(m.echo(pair))\n\
+ assert [ord(c) for c in m.echo(astral)] == [0xDC00, 0x10000], repr(m.echo(astral))\n",
+ ])
+ .output()
+ .unwrap();
+ assert!(
+ check.status.success(),
+ "stdout: {}\nstderr: {}",
+ String::from_utf8_lossy(&check.stdout),
+ String::from_utf8_lossy(&check.stderr)
+ );
+
+ // A port that folds the code points into UTF-16 units, as the bridge used to, is not exact.
+ let folding = "Ok(match s.get(\"$codepoints\").and_then(|v| v.as_array()) {\n \
+ Some(points) => {\n \
+ let mut units: Vec<u64> = Vec::new();\n \
+ for p in points.iter().filter_map(|p| p.as_u64()) {\n \
+ if p > 0xFFFF {\n \
+ units.push(0xD800 + ((p - 0x10000) >> 10));\n \
+ units.push(0xDC00 + ((p - 0x10000) & 0x3FF));\n \
+ } else {\n \
+ units.push(p);\n \
+ }\n \
+ }\n \
+ serde_json::json!({ \"$utf16\": units })\n \
+ }\n \
+ None => s,\n \
+ })";
+ std::fs::write(&port_path, with_body(folding)).unwrap();
+ let outcome = diff();
+ assert_eq!(
+ (outcome.failed, outcome.passed),
+ (1, 1),
+ "{:#?}",
+ outcome.mismatches
+ );
+ std::fs::remove_dir_all(root).unwrap();
+}
+
#[test]
fn pyo3_lone_surrogate_in_a_string_parameter_is_refused_by_name() {
let Some(python) = common::python() else {
diff --git a/tests/obligations_blocking.rs b/tests/obligations_blocking.rs
index e604ba16..15eab2e5 100644
--- a/tests/obligations_blocking.rs
+++ b/tests/obligations_blocking.rs
@@ -1071,16 +1071,26 @@ fn check_json_has_a_schema_and_the_blocking_items() {
#[test]
fn check_is_refused_next_to_the_options_it_does_not_take() {
let root = repo("ts-cli", "cli-conflict");
- for extra in [["--lang", "ts"], ["--write", ""], ["--evidence", ""]] {
- let mut args = vec!["obligations", root.to_str().unwrap(), "--check"];
- args.push(extra[0]);
- if !extra[1].is_empty() {
- args.push(extra[1]);
- }
+ for extra in ["--write", "--evidence"] {
+ let args = ["obligations", root.to_str().unwrap(), "--check", extra];
let o = run(&args);
assert_eq!(o.status.code(), Some(2), "{args:?}: {}", out(&o));
assert!(out(&o).contains("cannot be used with"), "{}", out(&o));
}
+ // `--lang` that rust/obligations-source.toml does not give points there: `app lift` reads it.
+ let o = run(&[
+ "obligations",
+ root.to_str().unwrap(),
+ "--check",
+ "--lang",
+ "ts",
+ ]);
+ assert!(!o.status.success(), "{}", out(&o));
+ assert!(
+ out(&o).contains("rust/obligations-source.toml") && out(&o).contains("lang = \"ts\""),
+ "{}",
+ out(&o)
+ );
}
#[test]
diff --git a/tests/obligations_source.rs b/tests/obligations_source.rs
new file mode 100644
index 00000000..2375abea
--- /dev/null
+++ b/tests/obligations_source.rs
@@ -0,0 +1,234 @@
+//! `rust/obligations-source.toml`: the language and the executables of an original that the
+//! repository keeps out of sight (issue #1477, a Python CLI with no extension in an ignored
+//! `reference/` folder of a Rust workspace), and the commands and flags no detector can see.
+
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+use rust_anything::obligations::standing::standing;
+use rust_anything::obligations::{self, Completeness, Family, Ledger};
+
+const CLI: &str = env!("CARGO_BIN_EXE_rust-anything");
+
+const SCRIPT: &str = "\
+#!/usr/bin/env python3
+import cmd
+import os
+
+def htmlescape(s):
+ return s.replace('&', '&amp;')
+
+class Shell(cmd.Cmd):
+ def do_status(self, arg):
+ if os.environ.get('SRC_DEBUG'):
+ print('debug')
+
+ def do_commit(self, arg):
+ raise ValueError('nothing to commit')
+
+if __name__ == '__main__':
+ Shell().cmdloop()
+";
+
+/// A Rust workspace whose original sits in an ignored folder, with no extension.
+struct Repo(PathBuf);
+
+impl Repo {
+ fn new(tag: &str, source: Option<&str>) -> Self {
+ let dir = std::env::temp_dir().join(format!(
+ "rust-anything-obligations-source-{}-{tag}",
+ std::process::id()
+ ));
+ let _ = std::fs::remove_dir_all(&dir);
+ let mut files = vec![
+ (
+ "Cargo.toml",
+ "[package]\nname = \"srrc\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
+ ),
+ ("src/main.rs", "fn main() {}\n"),
+ (".gitignore", "reference/\n"),
+ ("reference/src/src", SCRIPT),
+ ];
+ if let Some(text) = source {
+ files.push(("rust/obligations-source.toml", text));
+ }
+ 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();
+ }
+ Self(dir)
+ }
+
+ fn path(&self) -> &Path {
+ &self.0
+ }
+
+ fn ledger(&self) -> Ledger {
+ obligations::ledger(&self.0, None).unwrap()
+ }
+}
+
+impl Drop for Repo {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_dir_all(&self.0);
+ }
+}
+
+const ENTRY: &str = "lang = \"python\"\nentry = [\"reference/src/src\"]\n";
+
+fn ids(ledger: &Ledger, family: Family) -> Vec<&str> {
+ let mut ids: Vec<&str> = ledger
+ .obligations
+ .iter()
+ .filter(|o| o.family == family)
+ .map(|o| o.id.as_str())
+ .collect();
+ ids.sort_unstable();
+ ids
+}
+
+fn state(ledger: &Ledger, family: Family) -> Completeness {
+ ledger
+ .families
+ .iter()
+ .find(|f| f.family == family)
+ .unwrap()
+ .completeness
+}
+
+#[test]
+fn an_ignored_extensionless_entry_is_read_as_the_python_cli_it_is() {
+ let repo = Repo::new("entry", Some(ENTRY));
+ let ledger = repo.ledger();
+ assert_eq!(ledger.language, rust_anything::lang::Lang::Python);
+ assert_eq!(ledger.shape, "cli");
+ assert_eq!(ids(&ledger, Family::Env), ["env:SRC_DEBUG"]);
+ assert_eq!(
+ ids(&ledger, Family::ErrorPath),
+ ["error:reference/src/src#Shell.do_commit:raise ValueError('nothing to commit')"]
+ );
+ assert!(
+ ids(&ledger, Family::Export).is_empty(),
+ "an executable's functions are not exports: {:?}",
+ ids(&ledger, Family::Export)
+ );
+}
+
+#[test]
+fn an_entry_whose_commands_no_detector_sees_says_so_instead_of_calling_it_a_library() {
+ let repo = Repo::new("undetected", Some(ENTRY));
+ let ledger = repo.ledger();
+ for family in [Family::Command, Family::Flag] {
+ assert_eq!(state(&ledger, family), Completeness::Unknown);
+ let site = ledger
+ .unresolved
+ .iter()
+ .find(|u| u.family == family)
+ .unwrap();
+ assert_eq!(site.site, "reference/src/src:1");
+ assert!(
+ site.reason.contains("was detected in this entry point")
+ && site.reason.contains("rust/obligations-source.toml"),
+ "{}",
+ site.reason
+ );
+ }
+}
+
+#[test]
+fn declared_commands_and_flags_become_obligations_and_close_the_site() {
+ let repo = Repo::new(
+ "declared",
+ Some(&format!(
+ "{ENTRY}commands = [\"status\", \"commit\"]\nflags = [\"--verbose\", \"commit --message\"]\n"
+ )),
+ );
+ let ledger = repo.ledger();
+ assert_eq!(
+ ids(&ledger, Family::Command),
+ [
+ "command:reference/src/src#commit",
+ "command:reference/src/src#status"
+ ]
+ );
+ assert_eq!(
+ ids(&ledger, Family::Flag),
+ [
+ "flag:reference/src/src#--verbose",
+ "flag:reference/src/src#commit/--message"
+ ]
+ );
+ assert!(
+ ledger
+ .unresolved
+ .iter()
+ .all(|u| u.family != Family::Command && u.family != Family::Flag),
+ "{:#?}",
+ ledger.unresolved
+ );
+ assert_eq!(state(&ledger, Family::Command), Completeness::Enumerated);
+ let family = ledger
+ .families
+ .iter()
+ .find(|f| f.family == Family::Command)
+ .unwrap();
+ assert!(
+ family
+ .detectors
+ .contains(&"rust/obligations-source.toml".to_string()),
+ "{:?}",
+ family.detectors
+ );
+}
+
+#[test]
+fn the_check_and_lift_read_the_same_language_as_the_ledger() {
+ let repo = Repo::new("standing", Some(ENTRY));
+ assert_eq!(
+ standing(repo.path()).unwrap().language,
+ rust_anything::lang::Lang::Python
+ );
+}
+
+#[test]
+fn check_with_lang_points_to_the_file_lift_reads() {
+ let repo = Repo::new("check-lang", None);
+ let path = repo.path().to_str().unwrap();
+ let refused = Command::new(CLI)
+ .args(["obligations", path, "--check", "--lang", "python"])
+ .output()
+ .unwrap();
+ let stderr = String::from_utf8_lossy(&refused.stderr);
+ assert!(!refused.status.success());
+ assert!(
+ stderr.contains("rust/obligations-source.toml") && stderr.contains("lang = \"python\""),
+ "{stderr}"
+ );
+
+ std::fs::create_dir_all(repo.path().join("rust")).unwrap();
+ std::fs::write(repo.path().join("rust/obligations-source.toml"), ENTRY).unwrap();
+ let checked = Command::new(CLI)
+ .args(["obligations", path, "--check", "--lang", "python", "--json"])
+ .output()
+ .unwrap();
+ let standing: serde_json::Value = serde_json::from_slice(&checked.stdout).unwrap_or_else(|e| {
+ panic!("{e}: {}", String::from_utf8_lossy(&checked.stderr));
+ });
+ assert_eq!(standing["language"], "python");
+}
+
+#[test]
+fn a_faulty_source_file_is_an_error_not_an_empty_ledger() {
+ let repo = Repo::new(
+ "faulty",
+ Some("lang = \"python\"\nentry = [\"reference/missing\"]\n"),
+ );
+ let err = obligations::ledger(repo.path(), None)
+ .unwrap_err()
+ .to_string();
+ assert!(
+ err.contains("entry `reference/missing` does not exist"),
+ "{err}"
+ );
+}