aboutsummaryrefslogtreecommitdiffstats
path: root/crates/config/src/import.rs
diff options
context:
space:
mode:
authortv <tv@krebsco.de>2026-12-02 16:24:19 +0000
committertv <tv@krebsco.de>2026-12-02 17:08:52 +0000
commit2be9ca2b75d099a9ca04078f2182acda074ed270 (patch)
treeacd772e1873e566e2022f068628179bbd53eb8e9 /crates/config/src/import.rs
parent1de11da61a106187748c4b79e1d7b63e3b9d172f (diff)
config: a configuration names importers of its own
[meta.importer] in a file, or --meta-importer-NAME IMPORTER, names an importer: NAME:REST, { NAME = "REST" } and a placeholder of that name are then that importer, with REST as its variable `name`. So what would be built in for one tool, pass:NAME, is written by who uses it, once: pass = { command = ["pass", "show", "$(var:name)"] }. A name counts in every file and argument, wherever it is given; of two of one name, the later source's. What follows the name goes in as every variable does, as data. One named may be defined through others, not through itself. `meta` at the top of a configuration file is what the configuration says about itself. The argument is spelled as every option's, the table's keys joined with `-`; as its name is the configuration's, it is taken off the command line before the command reads it.
Diffstat (limited to 'crates/config/src/import.rs')
-rw-r--r--crates/config/src/import.rs419
1 files changed, 387 insertions, 32 deletions
diff --git a/crates/config/src/import.rs b/crates/config/src/import.rs
index 7305b49..c5d058a 100644
--- a/crates/config/src/import.rs
+++ b/crates/config/src/import.rs
@@ -38,6 +38,12 @@
//! names it, and those given. So what differs from one use to the next is a variable,
//! and the importer is written once: `["secrets", "$(env:HOSTNAME)", "show",
//! "$(var:key)"]`.
+//!
+//! A configuration may name importers of its own (`Importers`; `[meta.importer]` in a
+//! file, `--meta-importer-NAME`, which `file` and `arguments` read): `NAME:REST`,
+//! `{ NAME = "REST" }` and `$(NAME:REST)` are then the importer of that name, with
+//! `REST` as its variable `name` (`fetch_in`). None is built in for a tool: `pass:NAME`
+//! is `pass = { command = ["pass", "show", "$(var:name)"] }`, written by who uses it.
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt;
@@ -51,6 +57,36 @@ use serde_json::{Map as JsonMap, Value as JsonValue};
/// (`Importer::fetch_with`): a `var:NAME` placeholder is replaced by it.
pub type Variables = std::collections::BTreeMap<String, Vec<u8>>;
+/// Importers a configuration names itself (`[meta.importer]`, `--meta-importer-NAME`), by
+/// name: `NAME:REST` is the importer of that name, with `REST` as its variable `name`.
+/// So what would be built in for one tool (`pass:NAME`) is written by who uses it:
+/// `pass = { command = ["pass", "show", "$(var:name)"] }`.
+pub type Importers = std::collections::BTreeMap<String, Importer>;
+
+/// What a program and its configuration give to importers: variables and named
+/// importers.
+#[derive(Clone, Copy)]
+struct Given<'a> {
+ variables: &'a Variables,
+ importers: &'a Importers,
+ /// How many named importers deep this is: one named by itself, directly or
+ /// through others, ends at `DEEPEST`.
+ depth: usize,
+}
+
+/// How many named importers one may be defined through.
+const DEEPEST: usize = 8;
+
+/// No named importers.
+static UNNAMED: Importers = Importers::new();
+
+/// What a named importer may not be called: the kinds built in, and what else a
+/// value or an importer table reads as its own.
+const RESERVED: [&str; 7] = ["env", "file", "cmd", "command", "var", "literal", "format"];
+
+/// The variable a named importer gets what follows its name as.
+pub const NAME: &str = "name";
+
/// No variables: what `Importer::fetch` gives.
static NONE: Variables = Variables::new();
@@ -84,6 +120,12 @@ pub enum Source {
Shell(String),
/// A program and its arguments, run without a shell.
Argv(Vec<String>),
+ /// A named importer (`Importers`), and what follows its name, which may hold
+ /// placeholders: its variable `name`.
+ Named {
+ importer: String,
+ name: String,
+ },
/// Text with placeholders (`interpolated`).
Template(String),
}
@@ -104,8 +146,13 @@ pub enum Raw<'a> {
Literal(&'a str),
}
-/// Reads a command-line value.
+/// Reads a command-line value, where no importers are named.
pub fn parse_argument(raw: &str) -> Raw<'_> {
+ parse_argument_in(raw, &UNNAMED)
+}
+
+/// Reads a command-line value: `NAME:REST` is the importer `NAME` of `importers`.
+pub fn parse_argument_in<'a>(raw: &'a str, importers: &Importers) -> Raw<'a> {
if let Some(rest) = raw.strip_prefix("literal:") {
return Raw::Literal(rest);
}
@@ -122,6 +169,10 @@ pub fn parse_argument(raw: &str) -> Raw<'_> {
"env" => Source::Env(rest.to_owned()),
"file" => Source::File(PathBuf::from(rest)),
"cmd" => Source::Shell(rest.to_owned()),
+ named if importers.contains_key(named) => Source::Named {
+ importer: named.to_owned(),
+ name: rest.to_owned(),
+ },
_ => return literal_or_interpolated(raw),
};
Raw::Import(Importer {
@@ -131,6 +182,77 @@ pub fn parse_argument(raw: &str) -> Raw<'_> {
})
}
+/// Whether `importer` may be named `name` (`Importers`): a name of small letters,
+/// digits and `-`, beginning with a letter, and none of the kinds built in; an importer
+/// built in, of no format of its own, as what names it says how its content is read.
+pub fn define(name: &str, importer: &Importer) -> Result<()> {
+ let spelled = name.starts_with(|first: char| first.is_ascii_lowercase())
+ && name
+ .chars()
+ .all(|char| char.is_ascii_lowercase() || char.is_ascii_digit() || char == '-');
+ if !spelled {
+ bail!("an importer's name is small letters, digits and `-`, a letter first: not {name:?}");
+ }
+ if RESERVED.contains(&name) {
+ bail!("an importer can't be named {name:?}: that is built in");
+ }
+ match importer.source {
+ Source::Template(_) => bail!(
+ "the importer named {name:?} must be env:, file: or a command, not text with \
+ placeholders"
+ ),
+ Source::Named { .. } => {
+ bail!(
+ "the importer named {name:?} must be env:, file: or a command, not another named one"
+ )
+ }
+ Source::Env(_) | Source::File(_) | Source::Shell(_) | Source::Argv(_) => {}
+ }
+ if importer.format != Format::Text {
+ bail!(
+ "the importer named {name:?} takes no format: what names it says so \
+ ({name}+raw:…, {name}+json:…)"
+ );
+ }
+ Ok(())
+}
+
+/// The importers a file in `dir` names (`[meta.importer]`): each an importer table, or
+/// an importer as arguments spell them (`cmd:pass show …`).
+pub fn named_in_table(table: &JsonMap<String, JsonValue>, dir: &Path) -> Result<Importers> {
+ let mut importers = Importers::new();
+ for (name, value) in table {
+ let importer = match value {
+ JsonValue::Object(object) => parse_table(object, dir)?.ok_or_else(|| {
+ anyhow!("the importer named {name:?} must be an importer (env, file or command)")
+ })?,
+ JsonValue::String(text) => match parse_argument(text) {
+ Raw::Import(mut importer) => {
+ importer.dir = Some(dir.to_owned());
+ importer
+ }
+ Raw::Literal(_) => {
+ bail!("the importer named {name:?} must be env:, file: or cmd:, not {text:?}")
+ }
+ },
+ other => bail!("the importer named {name:?} must be an importer, not {other}"),
+ };
+ define(name, &importer)?;
+ importers.insert(name.clone(), importer);
+ }
+ Ok(importers)
+}
+
+/// The importer an argument names `name` (`--meta-importer-NAME IMPORTER`), the importer
+/// as arguments spell them.
+pub fn named_by_argument(name: &str, importer: &str) -> Result<Importer> {
+ let Raw::Import(importer) = parse_argument(importer) else {
+ bail!("the importer named {name:?} must be env:, file: or cmd:, not {importer:?}");
+ };
+ define(name, &importer)?;
+ Ok(importer)
+}
+
fn literal_or_interpolated(raw: &str) -> Raw<'_> {
match interpolated(raw, None) {
Some(importer) => Raw::Import(importer),
@@ -148,22 +270,37 @@ pub fn interpolated(text: &str, dir: Option<&Path>) -> Option<Importer> {
})
}
-/// Reads an importer table from a file in `dir`; None if `object` isn't one.
+/// Reads an importer table from a file in `dir`, where no importers are named; None
+/// if `object` isn't one.
pub fn parse_table(object: &JsonMap<String, JsonValue>, dir: &Path) -> Result<Option<Importer>> {
+ parse_table_in(object, dir, &UNNAMED)
+}
+
+/// Reads an importer table from a file in `dir`: `{ NAME = "REST" }` is the importer
+/// `NAME` of `importers`. None if `object` isn't one.
+pub fn parse_table_in(
+ object: &JsonMap<String, JsonValue>,
+ dir: &Path,
+ importers: &Importers,
+) -> Result<Option<Importer>> {
+ let named: Vec<&String> = object
+ .keys()
+ .filter(|key| importers.contains_key(*key))
+ .collect();
let sources = ["env", "file", "command"]
.into_iter()
.filter(|key| object.contains_key(*key))
- .count();
+ .count()
+ + named.len();
if sources == 0 {
return Ok(None);
}
if sources > 1 {
- bail!("an importer takes exactly one of env, file and command");
+ bail!("an importer takes exactly one of env, file, command and those named");
}
- if let Some(unknown) = object
- .keys()
- .find(|key| !["env", "file", "command", "format"].contains(&key.as_str()))
- {
+ if let Some(unknown) = object.keys().find(|key| {
+ !["env", "file", "command", "format"].contains(&key.as_str()) && !named.contains(key)
+ }) {
bail!("unknown importer key {unknown:?}");
}
let format = match object.get("format") {
@@ -185,6 +322,11 @@ pub fn parse_table(object: &JsonMap<String, JsonValue>, dir: &Path) -> Result<Op
Source::Env(text("env")?)
} else if object.contains_key("file") {
Source::File(PathBuf::from(text("file")?))
+ } else if let Some(importer) = named.first() {
+ Source::Named {
+ importer: (*importer).clone(),
+ name: text(importer)?,
+ }
} else {
match &object["command"] {
JsonValue::String(command) => Source::Shell(command.clone()),
@@ -219,6 +361,7 @@ impl Importer {
Source::File(path) => format!("file{format}:{}", self.in_dir(path).display()),
Source::Shell(command) => format!("cmd{format}:{command}"),
Source::Argv(argv) => format!("cmd{format}:{}", argv.join(" ")),
+ Source::Named { importer, name } => format!("{importer}{format}:{name}"),
Source::Template(template) => template.clone(),
}
}
@@ -246,12 +389,30 @@ impl Importer {
/// The imported content: text, JSON, or bytes; its `var:` placeholders, and those
/// of the placeholders in it, replaced by what `variables` gives.
pub fn fetch_with(&self, variables: &Variables) -> Result<Imported> {
+ self.fetch_given(Given {
+ variables,
+ importers: &UNNAMED,
+ depth: 0,
+ })
+ }
+
+ /// The imported content, as `fetch_with`; and where it, or a placeholder in it,
+ /// is one of `importers` by name, what that one gives.
+ pub fn fetch_in(&self, variables: &Variables, importers: &Importers) -> Result<Imported> {
+ self.fetch_given(Given {
+ variables,
+ importers,
+ depth: 0,
+ })
+ }
+
+ fn fetch_given(&self, given: Given<'_>) -> Result<Imported> {
let dir = self.dir.as_deref();
// Its placeholders may give bytes where it does.
let raw = self.format == Format::Raw;
let bytes = match &self.source {
Source::Env(name) => {
- let name = filled(name, dir, raw, variables)?;
+ let name = filled(name, dir, raw, given)?;
std::env::var_os(&name)
.ok_or_else(|| {
anyhow!("environment variable {} is not set", name.to_string_lossy())
@@ -260,13 +421,13 @@ impl Importer {
}
Source::File(path) => {
let path = match path.to_str() {
- Some(text) => self.in_dir(Path::new(&filled(text, dir, raw, variables)?)),
+ Some(text) => self.in_dir(Path::new(&filled(text, dir, raw, given)?)),
None => self.in_dir(path),
};
std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?
}
Source::Shell(command) => {
- let (script, values) = shell(command, dir, raw, variables)?;
+ let (script, values) = shell(command, dir, raw, given)?;
let mut process = Command::new("sh");
process.arg("-c").arg(script);
if !values.is_empty() {
@@ -278,13 +439,42 @@ impl Importer {
Source::Argv(argv) => {
let argv = argv
.iter()
- .map(|argument| filled(argument, dir, raw, variables))
+ .map(|argument| filled(argument, dir, raw, given))
.collect::<Result<Vec<_>>>()?;
let mut process = Command::new(&argv[0]);
process.args(&argv[1..]);
run(process, dir, &self.describe())?
}
- Source::Template(template) => expand_with(template, dir, variables)?.into_bytes(),
+ Source::Template(template) => expand_with(template, dir, given)?.into_bytes(),
+ Source::Named { importer, name } => {
+ let named = given
+ .importers
+ .get(importer)
+ .ok_or_else(|| anyhow!("no importer is named {importer:?} here"))?;
+ if given.depth >= DEEPEST {
+ bail!("the importer named {importer:?} is defined through itself");
+ }
+ // What follows the name is its variable `name`, beside the program's
+ // own.
+ let mut variables = given.variables.clone();
+ variables.insert(
+ NAME.to_owned(),
+ filled(name, dir, raw, given)?.into_encoded_bytes(),
+ );
+ let mut named = named.clone();
+ named.format = Format::Raw;
+ let fetched = named
+ .fetch_given(Given {
+ variables: &variables,
+ importers: given.importers,
+ depth: given.depth + 1,
+ })
+ .with_context(|| format!("the importer named {importer:?}"))?;
+ match fetched {
+ Imported::Raw(bytes) => bytes,
+ _ => unreachable!("a raw importer gives bytes"),
+ }
+ }
};
if self.format == Format::Raw {
return Ok(Imported::Raw(bytes));
@@ -378,14 +568,14 @@ fn value(
within: &str,
dir: Option<&Path>,
raw: bool,
- variables: &Variables,
+ given: Given<'_>,
) -> Result<Vec<u8>> {
if let Some((bytes, name)) = variable(placeholder) {
// Its name may hold placeholders, as an environment variable's.
- let name = filled(name, dir, false, variables)?;
+ let name = filled(name, dir, false, given)?;
let name = name.to_string_lossy();
- let Some(value) = variables.get(name.as_ref()) else {
- let given: Vec<&str> = variables.keys().map(String::as_str).collect();
+ let Some(value) = given.variables.get(name.as_ref()) else {
+ let given: Vec<&str> = given.variables.keys().map(String::as_str).collect();
bail!(
"unknown variable {name:?} in {within:?}: {}",
if given.is_empty() {
@@ -409,7 +599,7 @@ fn value(
),
};
}
- let mut importer = match parse_argument(placeholder) {
+ let mut importer = match parse_argument_in(placeholder, given.importers) {
Raw::Import(importer) if !importer.is_interpolation() => importer,
_ => bail!("placeholder {placeholder:?} in {within:?} isn't env:, file:, cmd: or var:"),
};
@@ -425,13 +615,20 @@ fn value(
),
}
importer.dir = dir.map(Path::to_owned);
- match importer.fetch_with(variables)? {
+ match importer.fetch_given(given)? {
Imported::Text(text) => Ok(text.into_bytes()),
Imported::Raw(bytes) => Ok(bytes),
Imported::Json(_) => unreachable!("no +json importer"),
}
}
+/// Whether `text` begins with the name of one of `importers`, and `:` or `+raw:`.
+fn names(text: &str, importers: &Importers) -> bool {
+ text.split_once(':').is_some_and(|(prefix, _)| {
+ importers.contains_key(prefix.strip_suffix("+raw").unwrap_or(prefix))
+ })
+}
+
/// The name in a placeholder that is a variable's, `var:NAME` or `var+raw:NAME`, and
/// whether it is `+raw`.
fn variable(placeholder: &str) -> Option<(bool, &str)> {
@@ -447,11 +644,19 @@ fn variable(placeholder: &str) -> Option<(bool, &str)> {
/// Text with its placeholders replaced by their content, without variables.
#[cfg(test)]
fn expand(template: &str, dir: Option<&Path>) -> Result<String> {
- expand_with(template, dir, &NONE)
+ expand_with(
+ template,
+ dir,
+ Given {
+ variables: &NONE,
+ importers: &UNNAMED,
+ depth: 0,
+ },
+ )
}
/// Text with its placeholders replaced by their content.
-fn expand_with(template: &str, dir: Option<&Path>, variables: &Variables) -> Result<String> {
+fn expand_with(template: &str, dir: Option<&Path>, given: Given<'_>) -> Result<String> {
let mut out = String::new();
let mut rest = template;
while let Some(at) = rest.find('$') {
@@ -463,7 +668,7 @@ fn expand_with(template: &str, dir: Option<&Path>, variables: &Variables) -> Res
} else if let Some((after, close)) = opened(after) {
let end = placeholder_end(after, opener(close), close)
.ok_or_else(|| anyhow!("unterminated placeholder in template {template:?}"))?;
- let text = value(&after[..end], template, dir, false, variables)?;
+ let text = value(&after[..end], template, dir, false, given)?;
out.push_str(&String::from_utf8(text).expect("a text importer gives text"));
rest = &after[end + 1..];
} else {
@@ -502,7 +707,13 @@ const NESTED: [&str; 8] = [
/// The parts of what an importer names (a name, a path, a command, an argument): only
/// `${env:`, `${file:`, `${cmd:` and `${var:` begin a placeholder, `$${` is a `${`, and
/// every other `$` stays as it is.
+#[cfg(test)]
fn parts(text: &str) -> Result<Vec<Part<'_>>> {
+ parts_in(text, &UNNAMED)
+}
+
+/// `parts`, where `NAME:` of `importers` begins a placeholder too.
+fn parts_in<'a>(text: &'a str, importers: &Importers) -> Result<Vec<Part<'a>>> {
let mut parts = Vec::new();
let mut plain = String::new();
let mut rest = text;
@@ -512,9 +723,9 @@ fn parts(text: &str) -> Result<Vec<Part<'_>>> {
if from.starts_with("$${") || from.starts_with("$$(") {
plain.push('$');
rest = &from[2..];
- } else if let Some((after, close)) = opened(&from[1..])
- .filter(|(after, _)| NESTED.iter().any(|prefix| after.starts_with(prefix)))
- {
+ } else if let Some((after, close)) = opened(&from[1..]).filter(|(after, _)| {
+ NESTED.iter().any(|prefix| after.starts_with(prefix)) || names(after, importers)
+ }) {
let end = placeholder_end(after, opener(close), close)
.ok_or_else(|| anyhow!("unterminated placeholder in {text:?}"))?;
if !plain.is_empty() {
@@ -536,13 +747,13 @@ fn parts(text: &str) -> Result<Vec<Part<'_>>> {
/// What an importer names, its placeholders replaced by their content, as it is: a
/// name, a path, or one argument, which stays one whatever a placeholder gives.
-fn filled(text: &str, dir: Option<&Path>, raw: bool, variables: &Variables) -> Result<OsString> {
+fn filled(text: &str, dir: Option<&Path>, raw: bool, given: Given<'_>) -> Result<OsString> {
let mut out = Vec::new();
- for part in parts(text)? {
+ for part in parts_in(text, given.importers)? {
match part {
Part::Text(plain) => out.extend(plain.into_bytes()),
Part::Placeholder(placeholder) => {
- out.extend(value(placeholder, text, dir, raw, variables)?)
+ out.extend(value(placeholder, text, dir, raw, given)?)
}
}
}
@@ -558,12 +769,12 @@ fn shell(
command: &str,
dir: Option<&Path>,
raw: bool,
- variables: &Variables,
+ given: Given<'_>,
) -> Result<(String, Vec<OsString>)> {
let mut script = String::new();
let mut values = Vec::new();
let mut at = Shell::default();
- for part in parts(command)? {
+ for part in parts_in(command, given.importers)? {
match part {
Part::Text(plain) => {
plain.chars().for_each(|char| at.read(char));
@@ -578,7 +789,7 @@ fn shell(
command,
dir,
raw,
- variables,
+ given,
)?));
script.push_str(&reference);
}
@@ -965,7 +1176,17 @@ mod tests {
.map(|(name, value)| (name.to_owned(), value.to_vec()))
.collect();
let dir = Some(scratch.0.as_path());
- let text = |template: &str| expand_with(template, dir, &variables);
+ let text = |template: &str| {
+ expand_with(
+ template,
+ dir,
+ Given {
+ variables: &variables,
+ importers: &UNNAMED,
+ depth: 0,
+ },
+ )
+ };
let fetch = |raw: &str| {
let Raw::Import(mut importer) = parse_argument(raw) else {
panic!("no importer: {raw}");
@@ -1031,6 +1252,140 @@ mod tests {
assert!(fetch("cmd:var=mine; printf '%s' \"${var:-x}\"").is_err());
}
+ /// An importer a configuration names is used as the kinds built in are: as a
+ /// value's importer, in a table, and as a placeholder; what follows its name is its
+ /// variable `name`, data to it, whatever it holds.
+ #[test]
+ fn importers_a_configuration_names() {
+ let scratch = Scratch::new("config-import-named");
+ std::fs::write(scratch.0.join("tor"), "a key\n").unwrap();
+ let named = named_in_table(
+ json!({
+ "show": { "command": ["printf", "<%s>", "$(var:name)"] },
+ "kept": "file:$(var:name)",
+ "shell": "cmd:printf '[%s]' $(var:name)",
+ })
+ .as_object()
+ .unwrap(),
+ &scratch.0,
+ )
+ .unwrap();
+ let variables = Variables::new();
+ let fetch = |raw: &str| {
+ let Raw::Import(mut importer) = parse_argument_in(raw, &named) else {
+ panic!("no importer: {raw}");
+ };
+ importer.dir = Some(scratch.0.clone());
+ importer.fetch_in(&variables, &named)
+ };
+ let text = |text: &str| Imported::Text(text.to_owned());
+
+ // As a value's importer, by argument and by table; shown as written.
+ assert_eq!(
+ fetch("show:continuum/tor").unwrap(),
+ text("<continuum/tor>")
+ );
+ assert_eq!(fetch("kept:tor").unwrap(), text("a key"));
+ assert_eq!(
+ fetch("kept+raw:tor").unwrap(),
+ Imported::Raw(b"a key\n".to_vec())
+ );
+ let table = parse_table_in(
+ json!({ "show": "x", "format": "raw" }).as_object().unwrap(),
+ &scratch.0,
+ &named,
+ )
+ .unwrap()
+ .unwrap();
+ assert_eq!(table.describe(), "show+raw:x");
+ assert_eq!(
+ table.fetch_in(&variables, &named).unwrap(),
+ Imported::Raw(b"<x>".to_vec())
+ );
+ // What follows the name is data: one argument, one word of a shell command.
+ assert_eq!(
+ fetch("show:a b; $(echo no)").unwrap(),
+ text("<a b; $(echo no)>")
+ );
+ assert_eq!(fetch("shell:a b; echo no").unwrap(), text("[a b; echo no]"));
+ // As a placeholder, in text and inside another importer; its name may hold some.
+ let template = interpolated("node-$(show:x)-${kept:tor}", Some(&scratch.0)).unwrap();
+ assert_eq!(
+ template.fetch_in(&variables, &named).unwrap(),
+ text("node-<x>-a key")
+ );
+ assert_eq!(
+ fetch("cmd:printf '%s' $(show:$(kept:tor))").unwrap(),
+ text("<a key>")
+ );
+ // Where it isn't named, it is none: text on the command line, an unknown key in
+ // a table, an unknown placeholder in text.
+ assert_eq!(parse_argument("show:x"), Raw::Literal("show:x"));
+ assert!(
+ parse_table(json!({ "show": "x" }).as_object().unwrap(), &scratch.0)
+ .unwrap()
+ .is_none()
+ );
+ assert!(expand("$(show:x)", None).is_err());
+
+ // What may be named, and how.
+ let define =
+ |value: JsonValue| named_in_table(value.as_object().unwrap(), &scratch.0).map(|_| ());
+ for refused in [
+ json!({ "env": "cmd:true" }),
+ json!({ "var": "cmd:true" }),
+ json!({ "Show": "cmd:true" }),
+ json!({ "a+b": "cmd:true" }),
+ json!({ "show": "plain" }),
+ json!({ "show": "node-$(env:X)" }),
+ json!({ "show": "cmd+raw:true" }),
+ json!({ "show": { "command": "true", "format": "json" } }),
+ json!({ "show": 1 }),
+ ] {
+ assert!(define(refused.clone()).is_err(), "{refused}");
+ }
+ // One named by another.
+ let nested = named_in_table(
+ json!({ "outer": "cmd:printf '%s' $(show:x)" })
+ .as_object()
+ .unwrap(),
+ &scratch.0,
+ )
+ .unwrap();
+ let mut both = named.clone();
+ both.extend(nested);
+ let Raw::Import(outer) = parse_argument_in("outer:y", &both) else {
+ panic!("no importer");
+ };
+ assert_eq!(outer.fetch_in(&variables, &both).unwrap(), text("<x>"));
+ // One defined through itself ends, and says so.
+ let looping = named_in_table(
+ json!({ "again": "cmd:printf '%s' $(again:x)" })
+ .as_object()
+ .unwrap(),
+ &scratch.0,
+ )
+ .unwrap();
+ let Raw::Import(again) = parse_argument_in("again:y", &looping) else {
+ panic!("no importer");
+ };
+ let why = format!("{:#}", again.fetch_in(&variables, &looping).unwrap_err());
+ assert!(why.contains("defined through itself"), "{why}");
+
+ // By argument.
+ let importer = named_by_argument("pass", "cmd:printf '%s' $(var:name)").unwrap();
+ let by_argument = Importers::from([("pass".to_owned(), importer)]);
+ let Raw::Import(pass) = parse_argument_in("pass:a/b", &by_argument) else {
+ panic!("no importer");
+ };
+ assert_eq!(
+ pass.fetch_in(&variables, &by_argument).unwrap(),
+ text("a/b")
+ );
+ assert!(named_by_argument("pass", "plain").is_err());
+ assert!(named_by_argument("cmd", "cmd:true").is_err());
+ }
+
#[test]
fn commands_with_braces_and_quotes() {
let expanded = |template: &str| expand(template, None);