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
42 changes: 33 additions & 9 deletions src/a2ml/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,27 +177,35 @@ impl Default for Manifest {
impl Manifest {
/// The manifest path in the current directory: the first of
/// [`MANIFEST_CANDIDATES`] that exists, else the deed name (so a missing
/// manifest is reported under the name it should have).
/// manifest is reported under the name it should have). A candidate whose
/// existence cannot be determined (a symlink loop, a permission error) is
/// chosen too, so that loading it reports the error instead of skipping it.
pub fn default_path() -> PathBuf {
MANIFEST_CANDIDATES
.iter()
.map(PathBuf::from)
.find(|path| path.exists())
.find(|path| !matches!(path.try_exists(), Ok(false)))
.unwrap_or_else(|| PathBuf::from(MANIFEST_CANDIDATES[0]))
}

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

/// Load `path` if it exists, else the built-in defaults. A file that
/// exists but does not load (a malformed or misheaded deed, an unreadable
/// file) is an error, never the defaults.
/// Load `path` if it exists, else the built-in defaults. Only a path that
/// is definitely absent gives the defaults. A file that exists but does not
/// load (a malformed or misheaded deed, an unreadable file), or a path whose
/// existence cannot be determined (a symlink loop, a permission error), is
/// an error, never the defaults.
pub fn load_if_exists(path: &Path) -> Result<Self> {
if path.exists() {
Self::load(path)
} else {
Ok(Self::default())
match path.try_exists() {
Ok(true) => Self::load(path),
Ok(false) => Ok(Self::default()),
Err(e) => Err(anyhow!(
"{}: cannot tell whether it exists: {}",
path.display(),
e
)),
}
}

Expand Down Expand Up @@ -1804,6 +1812,22 @@ mod tests {
);
}

#[cfg(unix)]
#[test]
fn load_if_exists_reports_a_symlink_loop_instead_of_defaulting() {
// Path::exists() turns the ELOOP of a self-referential link into
// `false`; the loader must not treat that as an absent manifest.
let dir = TempDir::new().expect("tempdir");
let path = dir.path().join("0-AI-MANIFEST.deed");
std::os::unix::fs::symlink(&path, &path).expect("self-referential symlink");
assert!(!path.exists(), "precondition: exists() hides the loop");
let err = Manifest::load_if_exists(&path).expect_err("a symlink loop is an error");
assert!(
err.to_string().contains("cannot tell whether it exists"),
"{err}"
);
}

#[test]
fn legacy_a2ml_manifest_still_reads_report_settings() {
let dir = TempDir::new().expect("tempdir");
Expand Down
26 changes: 24 additions & 2 deletions src/report/formatter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use crate::types::*;
use anyhow::Result;
use clap::ValueEnum;
use colored::*;
use serde_json;
use std::collections::HashMap;
use std::fs;
use std::path::Path;
Expand Down Expand Up @@ -496,8 +495,31 @@ impl ReportFormatter {
}
}

/// A Nickel string literal that evaluates to exactly `value`.
///
/// JSON quoting is not Nickel quoting:
/// - Nickel interpolates `%{…}` inside a string, so every `%` is written `\%`
/// (which Nickel reads back as `%`), and a path such as `/tmp/%{true}` stays
/// literal;
/// - Nickel has no `\b`, `\f` or `\uXXXX` escapes, so other control
/// characters are written `\u{XX}`.
pub(crate) fn nickel_escape_string(value: &str) -> String {
serde_json::to_string(value).unwrap_or_else(|_| format!("\"{}\"", value))
let mut out = String::with_capacity(value.len() + 2);
out.push('"');
for ch in value.chars() {
match ch {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'%' => out.push_str("\\%"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if c.is_control() => out.push_str(&format!("\\u{{{:x}}}", c as u32)),
c => out.push(c),
}
}
out.push('"');
out
}

struct AccordionSection {
Expand Down
39 changes: 39 additions & 0 deletions src/report/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,45 @@ mod tests {
}
}

#[test]
fn nickel_strings_stay_literal() {
// `%{…}` is interpolation in Nickel and JSON quoting leaves it alone;
// JSON's `\b`, `\f` and `\u001f` are not Nickel escapes at all.
let tricky = [
"/tmp/%{true}/x",
"100% sure",
"a\u{8}b\u{c}c\u{1f}d",
"tab\tline\nret\r\"q\" back\\slash",
"plain ünïcode ✓",
];
assert_eq!(nickel_escape_string("/tmp/%{true}"), "\"/tmp/\\%{true}\"");
assert_eq!(nickel_escape_string("a\u{1f}"), "\"a\\u{1f}\"");
assert!(!nickel_escape_string("a\u{8}").contains("\\b"));

let dir = TempDir::new().expect("tempdir");
let file = dir.path().join("strings.ncl");
let body = tricky
.iter()
.map(|s| nickel_escape_string(s))
.collect::<Vec<_>>()
.join(", ");
fs::write(&file, format!("[{body}]")).expect("write");
if let Ok(out) = std::process::Command::new("nickel")
.args(["export", "--format", "json"])
.arg(&file)
.output()
{
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
let back: Vec<String> =
serde_json::from_slice(&out.stdout).expect("nickel export emits a JSON array");
assert_eq!(back, tricky);
}
}

#[test]
fn non_finite_numbers_become_null() {
assert_eq!(nickel_number(f64::NAN, Some(1)), "null");
Expand Down
Loading