aboutsummaryrefslogtreecommitdiffstats
path: root/crates/config/src
diff options
context:
space:
mode:
Diffstat (limited to 'crates/config/src')
-rw-r--r--crates/config/src/import.rs256
1 files changed, 234 insertions, 22 deletions
diff --git a/crates/config/src/import.rs b/crates/config/src/import.rs
index c5d058a..13885a3 100644
--- a/crates/config/src/import.rs
+++ b/crates/config/src/import.rs
@@ -44,6 +44,8 @@
//! `{ 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.
+//! In a table, one is used with several variables: `{ NAME = { host = "…", key = "…" } }`
+//! (`Source::Named`); one it never asks for is an error, as one it lacks is.
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt;
@@ -120,11 +122,13 @@ 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`.
+ /// A named importer (`Importers`), and the variables it is used with, as written:
+ /// each may hold placeholders. What follows its name (`NAME:REST`, `{ NAME =
+ /// "REST" }`) is its variable `name`; a table (`{ NAME = { key = "…" } }`) gives
+ /// several.
Named {
importer: String,
- name: String,
+ variables: std::collections::BTreeMap<String, String>,
},
/// Text with placeholders (`interpolated`).
Template(String),
@@ -171,7 +175,7 @@ pub fn parse_argument_in<'a>(raw: &'a str, importers: &Importers) -> Raw<'a> {
"cmd" => Source::Shell(rest.to_owned()),
named if importers.contains_key(named) => Source::Named {
importer: named.to_owned(),
- name: rest.to_owned(),
+ variables: [(NAME.to_owned(), rest.to_owned())].into(),
},
_ => return literal_or_interpolated(raw),
};
@@ -186,11 +190,7 @@ pub fn parse_argument_in<'a>(raw: &'a str, importers: &Importers) -> Raw<'a> {
/// 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 {
+ if !spelled(name) {
bail!("an importer's name is small letters, digits and `-`, a letter first: not {name:?}");
}
if RESERVED.contains(&name) {
@@ -325,7 +325,7 @@ pub fn parse_table_in(
} else if let Some(importer) = named.first() {
Source::Named {
importer: (*importer).clone(),
- name: text(importer)?,
+ variables: used_with(importer, &object[importer.as_str()])?,
}
} else {
match &object["command"] {
@@ -361,11 +361,41 @@ 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::Named {
+ importer,
+ variables,
+ } => match (variables.len(), variables.get(NAME)) {
+ (1, Some(name)) => format!("{importer}{format}:{name}"),
+ _ => format!("{importer}{format}({})", listed(variables)),
+ },
Source::Template(template) => template.clone(),
}
}
+ /// The variables it asks for by name (`var:NAME`), in what it names and in the
+ /// placeholders there, those of importers named among them: what a use may give
+ /// it. None where it computes a variable's name, and so may take any.
+ fn mentions(
+ &self,
+ importers: &Importers,
+ ) -> Result<Option<std::collections::BTreeSet<String>>> {
+ let texts: Vec<&str> = match &self.source {
+ Source::Env(name) => vec![name],
+ Source::File(path) => path.to_str().into_iter().collect(),
+ Source::Shell(command) => vec![command],
+ Source::Argv(argv) => argv.iter().map(String::as_str).collect(),
+ Source::Template(template) => vec![template],
+ Source::Named { variables, .. } => variables.values().map(String::as_str).collect(),
+ };
+ let mut mentioned = std::collections::BTreeSet::new();
+ for text in texts {
+ if !mentioned_in(text, importers, &mut mentioned)? {
+ return Ok(None);
+ }
+ }
+ Ok(Some(mentioned))
+ }
+
/// Whether this is text with placeholders (`interpolated`) rather than an importer
/// of the whole value: its result is shown, the importers' are not.
pub fn is_interpolation(&self) -> bool {
@@ -446,7 +476,10 @@ impl Importer {
run(process, dir, &self.describe())?
}
Source::Template(template) => expand_with(template, dir, given)?.into_bytes(),
- Source::Named { importer, name } => {
+ Source::Named {
+ importer,
+ variables: used,
+ } => {
let named = given
.importers
.get(importer)
@@ -454,13 +487,33 @@ impl Importer {
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.
+ // What it is used with that it never asks for: a misspelt variable, most
+ // likely.
+ if let Some(takes) = named.mentions(given.importers)?
+ && let Some(unknown) = used
+ .iter()
+ // Nothing after the name is no variable given.
+ .filter(|(name, value)| !(*name == NAME && value.is_empty()))
+ .map(|(name, _)| name)
+ .find(|name| !takes.contains(*name))
+ {
+ bail!(
+ "the importer named {importer:?} takes no variable {unknown:?}: it takes {}",
+ if takes.is_empty() {
+ "none".to_owned()
+ } else {
+ takes.into_iter().collect::<Vec<_>>().join(", ")
+ }
+ );
+ }
+ // The variables it is used with, beside the program's own.
let mut variables = given.variables.clone();
- variables.insert(
- NAME.to_owned(),
- filled(name, dir, raw, given)?.into_encoded_bytes(),
- );
+ for (name, value) in used {
+ variables.insert(
+ name.clone(),
+ filled(value, dir, raw, given)?.into_encoded_bytes(),
+ );
+ }
let mut named = named.clone();
named.format = Format::Raw;
let fetched = named
@@ -469,7 +522,9 @@ impl Importer {
importers: given.importers,
depth: given.depth + 1,
})
- .with_context(|| format!("the importer named {importer:?}"))?;
+ .with_context(|| {
+ format!("the importer named {importer:?} ({})", listed(used))
+ })?;
match fetched {
Imported::Raw(bytes) => bytes,
_ => unreachable!("a raw importer gives bytes"),
@@ -622,6 +677,81 @@ fn value(
}
}
+/// Adds the variables `text` asks for by name to `mentioned`, those in the
+/// placeholders inside its placeholders too. Whether it names them all: not where
+/// one's name is computed.
+fn mentioned_in(
+ text: &str,
+ importers: &Importers,
+ mentioned: &mut std::collections::BTreeSet<String>,
+) -> Result<bool> {
+ let mut all = true;
+ for part in parts_in(text, importers)? {
+ let Part::Placeholder(placeholder) = part else {
+ continue;
+ };
+ match variable(placeholder) {
+ Some((_, name)) if name.contains('$') => {
+ all = false;
+ mentioned_in(name, importers, mentioned)?;
+ }
+ Some((_, name)) => {
+ mentioned.insert(name.to_owned());
+ }
+ // What an importer in a placeholder names may ask for some in turn.
+ None => {
+ let inside = placeholder.split_once(':').map_or("", |(_, inside)| inside);
+ all &= mentioned_in(inside, importers, mentioned)?;
+ }
+ }
+ }
+ Ok(all)
+}
+
+/// Variables as written, for people: `host = web, key = tor`.
+fn listed(variables: &std::collections::BTreeMap<String, String>) -> String {
+ variables
+ .iter()
+ .map(|(name, value)| format!("{name} = {value}"))
+ .collect::<Vec<_>>()
+ .join(", ")
+}
+
+/// The variables the importer `importer` is used with in a table: text, its variable
+/// `name`; or a table of them, each text, named as importers are.
+fn used_with(
+ importer: &str,
+ value: &JsonValue,
+) -> Result<std::collections::BTreeMap<String, String>> {
+ match value {
+ JsonValue::String(name) => Ok([(NAME.to_owned(), name.clone())].into()),
+ JsonValue::Object(variables) => variables
+ .iter()
+ .map(|(name, value)| {
+ if !spelled(name) {
+ bail!(
+ "a variable's name is small letters, digits and `-`, a letter first: not {name:?} (of {importer})"
+ );
+ }
+ match value {
+ JsonValue::String(value) => Ok((name.clone(), value.clone())),
+ other => bail!("the variable {name} of {importer} must be text, not {other}"),
+ }
+ })
+ .collect(),
+ other => bail!("{importer} takes text, or a table of variables, not {other}"),
+ }
+}
+
+/// Whether `name` is spelled as an importer's, and a variable's given to one, is: small
+/// letters, digits and `-`, a letter first.
+fn spelled(name: &str) -> bool {
+ name.starts_with(|first: char| first.is_ascii_lowercase())
+ && name
+ .chars()
+ .all(|char| char.is_ascii_lowercase() || char.is_ascii_digit() || char == '-')
+}
+
/// 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, _)| {
@@ -1346,7 +1476,7 @@ mod tests {
}
// One named by another.
let nested = named_in_table(
- json!({ "outer": "cmd:printf '%s' $(show:x)" })
+ json!({ "outer": "cmd:printf '%s' $(show:$(var:name))" })
.as_object()
.unwrap(),
&scratch.0,
@@ -1357,10 +1487,10 @@ mod tests {
let Raw::Import(outer) = parse_argument_in("outer:y", &both) else {
panic!("no importer");
};
- assert_eq!(outer.fetch_in(&variables, &both).unwrap(), text("<x>"));
+ assert_eq!(outer.fetch_in(&variables, &both).unwrap(), text("<y>"));
// One defined through itself ends, and says so.
let looping = named_in_table(
- json!({ "again": "cmd:printf '%s' $(again:x)" })
+ json!({ "again": "cmd:printf '%s' $(again:$(var:name))" })
.as_object()
.unwrap(),
&scratch.0,
@@ -1386,6 +1516,88 @@ mod tests {
assert!(named_by_argument("cmd", "cmd:true").is_err());
}
+ /// A named importer used with several variables, in a table; what it asks for and
+ /// isn't given, and what it is given and never asks for, is an error naming it.
+ #[test]
+ fn a_named_importer_used_with_several_variables() {
+ let scratch = Scratch::new("config-import-named-variables");
+ std::fs::write(scratch.0.join("web"), "a host\n").unwrap();
+ let named = named_in_table(
+ json!({
+ "secrets": { "command": ["printf", "%s/%s", "$(var:host)", "$(var:key)"] },
+ "plain": "cmd:printf plain",
+ "any": "cmd:printf '%s' $(var:$(env:CONFIG_TEST_UNSET_VARIABLE))",
+ })
+ .as_object()
+ .unwrap(),
+ &scratch.0,
+ )
+ .unwrap();
+ let variables = Variables::new();
+ let table = |value: JsonValue| {
+ parse_table_in(value.as_object().unwrap(), &scratch.0, &named)
+ .map(|importer| importer.expect("an importer"))
+ };
+ let text = |text: &str| Imported::Text(text.to_owned());
+
+ let used = table(json!({ "secrets": { "key": "tor", "host": "$(file:web)" } })).unwrap();
+ assert_eq!(
+ used.fetch_in(&variables, &named).unwrap(),
+ text("a host/tor")
+ );
+ // Shown as written, and told apart by who looks.
+ assert_eq!(used.describe(), "secrets(host = $(file:web), key = tor)");
+ assert!(matches!(
+ &used.source,
+ Source::Named { importer, variables }
+ if importer == "secrets" && variables.len() == 2 && variables["key"] == "tor"
+ ));
+ let raw = table(json!({ "secrets": { "key": "k", "host": "h" }, "format": "raw" }));
+ assert_eq!(raw.unwrap().describe(), "secrets+raw(host = h, key = k)");
+
+ // Not given what it asks for; given what it never asks for.
+ let why = |value: JsonValue| {
+ format!(
+ "{:#}",
+ table(value)
+ .and_then(|importer| importer.fetch_in(&variables, &named))
+ .unwrap_err()
+ )
+ };
+ let lacking = why(json!({ "secrets": { "key": "tor" } }));
+ assert!(lacking.contains("unknown variable \"host\""), "{lacking}");
+ assert!(lacking.contains("secrets"), "{lacking}");
+ let misspelt = why(json!({ "secrets": { "key": "tor", "hots": "web" } }));
+ assert!(
+ misspelt.contains("takes no variable \"hots\": it takes host, key"),
+ "{misspelt}"
+ );
+ // The short forms give `name`, which this one doesn't take.
+ let short = why(json!({ "secrets": "tor" }));
+ assert!(short.contains("takes no variable \"name\""), "{short}");
+ // One that takes none is used with nothing after its name.
+ assert_eq!(
+ table(json!({ "plain": "" }))
+ .unwrap()
+ .fetch_in(&variables, &named)
+ .unwrap(),
+ text("plain")
+ );
+ assert!(why(json!({ "plain": "x" })).contains("it takes none"));
+ // One that computes a variable's name may take any: none is refused unasked.
+ let any = why(json!({ "any": { "whatever": "x" } }));
+ assert!(!any.contains("takes no variable"), "{any}");
+
+ // What a use's table may hold.
+ for refused in [
+ json!({ "secrets": { "Key": "tor" } }),
+ json!({ "secrets": { "key": 1 } }),
+ json!({ "secrets": ["tor"] }),
+ ] {
+ assert!(table(refused.clone()).is_err(), "{refused}");
+ }
+ }
+
#[test]
fn commands_with_braces_and_quotes() {
let expanded = |template: &str| expand(template, None);