Skip to content

Commit f2c46ba

Browse files
fix: Nickel strings stay literal; a manifest lookup error is not an absent manifest (#303)
## Summary This follows up the two CodeRabbit findings on #302, which landed after #302 merged. I checked both against nickel 1.18.0 and Rust std before fixing them. ### 1. Nickel string escaping (`src/report/formatter.rs`) `nickel_escape_string` used JSON quoting, which is wrong for Nickel in two ways: | Input | Old output | `nickel export` result | |---|---|---| | `/tmp/%{true}` | `"/tmp/%{true}"` | `"/tmp/true"`: interpolated | | `a\u{1f}b` | `"a\u001fb"` | `invalid escape sequence` | | `a\u{8}b` | `"a\bb"` | `invalid escape sequence` | The escaper now writes: - `\%` for every `%` (Nickel reads it back as `%`); - `\"`, `\\`, `\n`, `\r` and `\t`; - `\u{XX}` for any other control character. The manifest export (`src/a2ml`) and the assault-report writer share this escaper, so both are fixed. ### 2. Manifest lookup (`src/a2ml/mod.rs`) `Manifest::default_path` and `load_if_exists` used `Path::exists()`. That turns every metadata error (a self-referential symlink, a permission error) into `false`, so the CLI quietly fell back to the defaults. Both now use `try_exists()`: - only a definite absence gives the defaults; - a path whose existence can't be determined is an error, which the startup warning reports. ## Tests - `nickel_strings_stay_literal`: five tricky strings make the round trip through `nickel export` unchanged, and three exact-output assertions pass. - `load_if_exists_reports_a_symlink_loop_instead_of_defaulting` (unix): a self-referential `0-AI-MANIFEST.deed` is an error, not the defaults. ## Checks run locally - `cargo build`: 0 warnings. The `serde_json` import in `formatter.rs` was unused after the rewrite and is gone. - `cargo test`: 818 passed, 0 failed. - `cargo test --features http`: 885 passed, 0 failed. - `cargo clippy --locked --all-targets --features http,sarif,signing -- -D warnings`: clean. - `cargo fmt --check`: exit 0. - `git diff --summary`: no mode changes. --- _Generated by [Claude Code](https://claude.ai/code/session_0136P7ZoBy5xGnGDLk7wQ8jC)_ Co-authored-by: Claude <noreply@anthropic.com>
1 parent c5fc2c6 commit f2c46ba

3 files changed

Lines changed: 96 additions & 11 deletions

File tree

‎src/a2ml/mod.rs‎

Lines changed: 33 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -177,27 +177,35 @@ impl Default for Manifest {
177177
impl Manifest {
178178
/// The manifest path in the current directory: the first of
179179
/// [`MANIFEST_CANDIDATES`] that exists, else the deed name (so a missing
180-
/// manifest is reported under the name it should have).
180+
/// manifest is reported under the name it should have). A candidate whose
181+
/// existence cannot be determined (a symlink loop, a permission error) is
182+
/// chosen too, so that loading it reports the error instead of skipping it.
181183
pub fn default_path() -> PathBuf {
182184
MANIFEST_CANDIDATES
183185
.iter()
184186
.map(PathBuf::from)
185-
.find(|path| path.exists())
187+
.find(|path| !matches!(path.try_exists(), Ok(false)))
186188
.unwrap_or_else(|| PathBuf::from(MANIFEST_CANDIDATES[0]))
187189
}
188190

189191
pub fn load_default() -> Result<Self> {
190192
Self::load(&Self::default_path())
191193
}
192194

193-
/// Load `path` if it exists, else the built-in defaults. A file that
194-
/// exists but does not load (a malformed or misheaded deed, an unreadable
195-
/// file) is an error, never the defaults.
195+
/// Load `path` if it exists, else the built-in defaults. Only a path that
196+
/// is definitely absent gives the defaults. A file that exists but does not
197+
/// load (a malformed or misheaded deed, an unreadable file), or a path whose
198+
/// existence cannot be determined (a symlink loop, a permission error), is
199+
/// an error, never the defaults.
196200
pub fn load_if_exists(path: &Path) -> Result<Self> {
197-
if path.exists() {
198-
Self::load(path)
199-
} else {
200-
Ok(Self::default())
201+
match path.try_exists() {
202+
Ok(true) => Self::load(path),
203+
Ok(false) => Ok(Self::default()),
204+
Err(e) => Err(anyhow!(
205+
"{}: cannot tell whether it exists: {}",
206+
path.display(),
207+
e
208+
)),
201209
}
202210
}
203211

@@ -1804,6 +1812,22 @@ mod tests {
18041812
);
18051813
}
18061814

1815+
#[cfg(unix)]
1816+
#[test]
1817+
fn load_if_exists_reports_a_symlink_loop_instead_of_defaulting() {
1818+
// Path::exists() turns the ELOOP of a self-referential link into
1819+
// `false`; the loader must not treat that as an absent manifest.
1820+
let dir = TempDir::new().expect("tempdir");
1821+
let path = dir.path().join("0-AI-MANIFEST.deed");
1822+
std::os::unix::fs::symlink(&path, &path).expect("self-referential symlink");
1823+
assert!(!path.exists(), "precondition: exists() hides the loop");
1824+
let err = Manifest::load_if_exists(&path).expect_err("a symlink loop is an error");
1825+
assert!(
1826+
err.to_string().contains("cannot tell whether it exists"),
1827+
"{err}"
1828+
);
1829+
}
1830+
18071831
#[test]
18081832
fn legacy_a2ml_manifest_still_reads_report_settings() {
18091833
let dir = TempDir::new().expect("tempdir");

‎src/report/formatter.rs‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ use crate::types::*;
77
use anyhow::Result;
88
use clap::ValueEnum;
99
use colored::*;
10-
use serde_json;
1110
use std::collections::HashMap;
1211
use std::fs;
1312
use std::path::Path;
@@ -496,8 +495,31 @@ impl ReportFormatter {
496495
}
497496
}
498497

498+
/// A Nickel string literal that evaluates to exactly `value`.
499+
///
500+
/// JSON quoting is not Nickel quoting:
501+
/// - Nickel interpolates `%{…}` inside a string, so every `%` is written `\%`
502+
/// (which Nickel reads back as `%`), and a path such as `/tmp/%{true}` stays
503+
/// literal;
504+
/// - Nickel has no `\b`, `\f` or `\uXXXX` escapes, so other control
505+
/// characters are written `\u{XX}`.
499506
pub(crate) fn nickel_escape_string(value: &str) -> String {
500-
serde_json::to_string(value).unwrap_or_else(|_| format!("\"{}\"", value))
507+
let mut out = String::with_capacity(value.len() + 2);
508+
out.push('"');
509+
for ch in value.chars() {
510+
match ch {
511+
'"' => out.push_str("\\\""),
512+
'\\' => out.push_str("\\\\"),
513+
'%' => out.push_str("\\%"),
514+
'\n' => out.push_str("\\n"),
515+
'\r' => out.push_str("\\r"),
516+
'\t' => out.push_str("\\t"),
517+
c if c.is_control() => out.push_str(&format!("\\u{{{:x}}}", c as u32)),
518+
c => out.push(c),
519+
}
520+
}
521+
out.push('"');
522+
out
501523
}
502524

503525
struct AccordionSection {

‎src/report/output.rs‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,45 @@ mod tests {
281281
}
282282
}
283283

284+
#[test]
285+
fn nickel_strings_stay_literal() {
286+
// `%{…}` is interpolation in Nickel and JSON quoting leaves it alone;
287+
// JSON's `\b`, `\f` and `\u001f` are not Nickel escapes at all.
288+
let tricky = [
289+
"/tmp/%{true}/x",
290+
"100% sure",
291+
"a\u{8}b\u{c}c\u{1f}d",
292+
"tab\tline\nret\r\"q\" back\\slash",
293+
"plain ünïcode ✓",
294+
];
295+
assert_eq!(nickel_escape_string("/tmp/%{true}"), "\"/tmp/\\%{true}\"");
296+
assert_eq!(nickel_escape_string("a\u{1f}"), "\"a\\u{1f}\"");
297+
assert!(!nickel_escape_string("a\u{8}").contains("\\b"));
298+
299+
let dir = TempDir::new().expect("tempdir");
300+
let file = dir.path().join("strings.ncl");
301+
let body = tricky
302+
.iter()
303+
.map(|s| nickel_escape_string(s))
304+
.collect::<Vec<_>>()
305+
.join(", ");
306+
fs::write(&file, format!("[{body}]")).expect("write");
307+
if let Ok(out) = std::process::Command::new("nickel")
308+
.args(["export", "--format", "json"])
309+
.arg(&file)
310+
.output()
311+
{
312+
assert!(
313+
out.status.success(),
314+
"{}",
315+
String::from_utf8_lossy(&out.stderr)
316+
);
317+
let back: Vec<String> =
318+
serde_json::from_slice(&out.stdout).expect("nickel export emits a JSON array");
319+
assert_eq!(back, tricky);
320+
}
321+
}
322+
284323
#[test]
285324
fn non_finite_numbers_become_null() {
286325
assert_eq!(nickel_number(f64::NAN, Some(1)), "null");

0 commit comments

Comments
 (0)