aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--CHANGELOG.md7
-rw-r--r--crates/config/src/import.rs220
-rw-r--r--docs/configuration.md8
3 files changed, 211 insertions, 24 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ff27c0c..2000c11 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -36,6 +36,13 @@ it from the release before ([`docs/operations.md`](docs/operations.md),
([`docs/configuration.md`](docs/configuration.md),
[Importing values](docs/configuration.md#importing-values)).
+* The `config` crate takes variables of the program that uses it: `${var:NAME}`, or
+ `$(var:NAME)`, is replaced by the one of that name (`Variables`,
+ `Importer::fetch_with`), under the rules of every placeholder; an unknown one is an
+ error naming it. continuum gives none: a shell command in an importer that used a
+ variable of its own named `var` by `${var:…}` writes `$${var:…}`
+ ([`crates/config/src/import.rs`](crates/config/src/import.rs)).
+
* A placeholder may be written with parentheses, `$(env:NAME)`, `$(file:PATH)`,
`$(cmd:COMMAND)`, for a configuration written in a language with a `${…}` of its own
(Nix). A shell command in an importer that ran a program named `env:…`, `file:…` or
diff --git a/crates/config/src/import.rs b/crates/config/src/import.rs
index 61d162f..7305b49 100644
--- a/crates/config/src/import.rs
+++ b/crates/config/src/import.rs
@@ -25,12 +25,19 @@
//!
//! Placeholders nest: a name, a path, a command and each argument of an argument list
//! may hold placeholders of their own, `${cmd:secrets ${env:HOST} show x}`. There, only
-//! `${env:`, `${file:` and `${cmd:` begin one, or the same with `$(`, `$${` is a `${` and
-//! `$$(` a `$(`, and every other `$` stays as it is: a command's are its shell's. What a placeholder gives goes in as data, never
-//! as code: into a name, a path and an argument as it is, an argument staying one
+//! `${env:`, `${file:`, `${cmd:` and `${var:` begin one, or the same with `$(`, `$${` is
+//! a `${` and `$$(` a `$(`, and every other `$` stays as it is: a command's are its
+//! shell's. What a placeholder gives goes in as data, never as code: into a name, a path and an argument as it is, an argument staying one
//! argument; into a shell command as a positional parameter (`shell`), so the shell never
//! reads it as part of its script. In a `+raw` importer a placeholder may be `+raw` too
//! (`cmd+raw:sign ${file+raw:key}`), its bytes going in as they are; into text, none is.
+//!
+//! A program may give variables of its own (`Variables`, `Importer::fetch_with`):
+//! `${var:NAME}` is replaced by the one of that name, as the program gives it, under the
+//! same rules; `${var+raw:NAME}` where bytes go. One it doesn't give is an error that
+//! 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)"]`.
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt;
@@ -40,6 +47,13 @@ use std::process::Command;
use anyhow::{Context, Result, anyhow, bail};
use serde_json::{Map as JsonMap, Value as JsonValue};
+/// What the program that reads a configuration gives its importers, by name
+/// (`Importer::fetch_with`): a `var:NAME` placeholder is replaced by it.
+pub type Variables = std::collections::BTreeMap<String, Vec<u8>>;
+
+/// No variables: what `Importer::fetch` gives.
+static NONE: Variables = Variables::new();
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Format {
/// Text, its trailing line breaks removed.
@@ -223,14 +237,21 @@ impl Importer {
}
}
- /// The imported content: text, JSON, or bytes.
+ /// The imported content: text, JSON, or bytes. Of a program that gives no variables:
+ /// a `var:` placeholder is an error.
pub fn fetch(&self) -> Result<Imported> {
+ self.fetch_with(&NONE)
+ }
+
+ /// 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> {
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)?;
+ let name = filled(name, dir, raw, variables)?;
std::env::var_os(&name)
.ok_or_else(|| {
anyhow!("environment variable {} is not set", name.to_string_lossy())
@@ -239,13 +260,13 @@ impl Importer {
}
Source::File(path) => {
let path = match path.to_str() {
- Some(text) => self.in_dir(Path::new(&filled(text, dir, raw)?)),
+ Some(text) => self.in_dir(Path::new(&filled(text, dir, raw, variables)?)),
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)?;
+ let (script, values) = shell(command, dir, raw, variables)?;
let mut process = Command::new("sh");
process.arg("-c").arg(script);
if !values.is_empty() {
@@ -257,13 +278,13 @@ impl Importer {
Source::Argv(argv) => {
let argv = argv
.iter()
- .map(|argument| filled(argument, dir, raw))
+ .map(|argument| filled(argument, dir, raw, variables))
.collect::<Result<Vec<_>>>()?;
let mut process = Command::new(&argv[0]);
process.args(&argv[1..]);
run(process, dir, &self.describe())?
}
- Source::Template(template) => expand(template, dir)?.into_bytes(),
+ Source::Template(template) => expand_with(template, dir, variables)?.into_bytes(),
};
if self.format == Format::Raw {
return Ok(Imported::Raw(bytes));
@@ -352,10 +373,45 @@ fn placeholder_end(text: &str, open: char, close: char) -> Option<usize> {
/// What the placeholder `placeholder` (between its `${` and `}`) gives, read in `dir`: an
/// `env:`, a `file:` or a `cmd:`, as text; or, where what it goes into takes bytes (`raw`:
/// a `+raw` importer), with `+raw` as bytes. Never `+json`.
-fn value(placeholder: &str, within: &str, dir: Option<&Path>, raw: bool) -> Result<Vec<u8>> {
+fn value(
+ placeholder: &str,
+ within: &str,
+ dir: Option<&Path>,
+ raw: bool,
+ variables: &Variables,
+) -> 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 = name.to_string_lossy();
+ let Some(value) = variables.get(name.as_ref()) else {
+ let given: Vec<&str> = variables.keys().map(String::as_str).collect();
+ bail!(
+ "unknown variable {name:?} in {within:?}: {}",
+ if given.is_empty() {
+ "no variables are given here (a shell's own `${var:…}` is written `$${var:…}`)"
+ .to_owned()
+ } else {
+ format!("given are {}", given.join(", "))
+ }
+ );
+ };
+ return match (bytes, raw) {
+ (true, true) => Ok(value.clone()),
+ (true, false) => bail!(
+ "placeholder {placeholder:?} in {within:?} gives bytes as they are, and goes into \
+ text: a +raw placeholder is for a +raw importer"
+ ),
+ (false, _) if std::str::from_utf8(value).is_ok() => Ok(value.clone()),
+ (false, _) => bail!(
+ "variable {name:?} in {within:?} is not UTF-8: text is, and `var+raw:` in a \
+ `+raw` importer takes bytes as they are"
+ ),
+ };
+ }
let mut importer = match parse_argument(placeholder) {
Raw::Import(importer) if !importer.is_interpolation() => importer,
- _ => bail!("placeholder {placeholder:?} in {within:?} isn't env:, file: or cmd:"),
+ _ => bail!("placeholder {placeholder:?} in {within:?} isn't env:, file:, cmd: or var:"),
};
match importer.format {
Format::Text => {}
@@ -369,15 +425,33 @@ fn value(placeholder: &str, within: &str, dir: Option<&Path>, raw: bool) -> Resu
),
}
importer.dir = dir.map(Path::to_owned);
- match importer.fetch()? {
+ match importer.fetch_with(variables)? {
Imported::Text(text) => Ok(text.into_bytes()),
Imported::Raw(bytes) => Ok(bytes),
Imported::Json(_) => unreachable!("no +json importer"),
}
}
-/// Text with its placeholders replaced by their content.
+/// 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)> {
+ if let Some(name) = placeholder.strip_prefix("var:") {
+ Some((false, name))
+ } else {
+ placeholder
+ .strip_prefix("var+raw:")
+ .map(|name| (true, name))
+ }
+}
+
+/// 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)
+}
+
+/// Text with its placeholders replaced by their content.
+fn expand_with(template: &str, dir: Option<&Path>, variables: &Variables) -> Result<String> {
let mut out = String::new();
let mut rest = template;
while let Some(at) = rest.find('$') {
@@ -389,7 +463,7 @@ fn expand(template: &str, dir: Option<&Path>) -> Result<String> {
} 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)?;
+ let text = value(&after[..end], template, dir, false, variables)?;
out.push_str(&String::from_utf8(text).expect("a text importer gives text"));
rest = &after[end + 1..];
} else {
@@ -414,11 +488,20 @@ enum Part<'a> {
/// What begins a placeholder inside an importer, after its `${`: nothing else there is
/// one, as a command's `$` are its shell's.
-const NESTED: [&str; 6] = ["env:", "file:", "cmd:", "env+raw:", "file+raw:", "cmd+raw:"];
+const NESTED: [&str; 8] = [
+ "env:",
+ "file:",
+ "cmd:",
+ "var:",
+ "env+raw:",
+ "file+raw:",
+ "cmd+raw:",
+ "var+raw:",
+];
/// The parts of what an importer names (a name, a path, a command, an argument): only
-/// `${env:`, `${file:` and `${cmd:` begin a placeholder, `$${` is a `${`, and every other
-/// `$` stays as it is.
+/// `${env:`, `${file:`, `${cmd:` and `${var:` begin a placeholder, `$${` is a `${`, and
+/// every other `$` stays as it is.
fn parts(text: &str) -> Result<Vec<Part<'_>>> {
let mut parts = Vec::new();
let mut plain = String::new();
@@ -453,12 +536,14 @@ 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) -> Result<OsString> {
+fn filled(text: &str, dir: Option<&Path>, raw: bool, variables: &Variables) -> Result<OsString> {
let mut out = Vec::new();
for part in parts(text)? {
match part {
Part::Text(plain) => out.extend(plain.into_bytes()),
- Part::Placeholder(placeholder) => out.extend(value(placeholder, text, dir, raw)?),
+ Part::Placeholder(placeholder) => {
+ out.extend(value(placeholder, text, dir, raw, variables)?)
+ }
}
}
Ok(OsString::from_vec(out))
@@ -469,7 +554,12 @@ fn filled(text: &str, dir: Option<&Path>, raw: bool) -> Result<OsString> {
/// `"${1}"`, or `${1}` inside double quotes, so that what it gives is one word of the
/// command as it is, and the shell reads none of it as script, whatever it holds. Where
/// a reference can't be written so, the command is refused (`Shell::reference`).
-fn shell(command: &str, dir: Option<&Path>, raw: bool) -> Result<(String, Vec<OsString>)> {
+fn shell(
+ command: &str,
+ dir: Option<&Path>,
+ raw: bool,
+ variables: &Variables,
+) -> Result<(String, Vec<OsString>)> {
let mut script = String::new();
let mut values = Vec::new();
let mut at = Shell::default();
@@ -483,7 +573,13 @@ fn shell(command: &str, dir: Option<&Path>, raw: bool) -> Result<(String, Vec<Os
let reference = at.reference(values.len() + 1).map_err(|why| {
anyhow!("placeholder {placeholder:?} in the command {command:?} is {why}")
})?;
- values.push(OsString::from_vec(value(placeholder, command, dir, raw)?));
+ values.push(OsString::from_vec(value(
+ placeholder,
+ command,
+ dir,
+ raw,
+ variables,
+ )?));
script.push_str(&reference);
}
}
@@ -853,6 +949,88 @@ mod tests {
);
}
+ /// A `var:` placeholder is replaced by what the program gives under that name: in
+ /// text, in a name, a path, an argument and a shell command, as data; an unknown one
+ /// is an error naming it, and the shell's own `${var:…}` is written `$${var:…}`.
+ #[test]
+ fn variables_the_program_gives() {
+ let scratch = Scratch::new("config-import-variables");
+ std::fs::write(scratch.0.join("retiolum"), "a key\n").unwrap();
+ let variables: Variables = [
+ ("key", &b"retiolum"[..]),
+ ("code", b"$(echo no); echo no"),
+ ("bytes", b"\xff\n"),
+ ]
+ .into_iter()
+ .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 fetch = |raw: &str| {
+ let Raw::Import(mut importer) = parse_argument(raw) else {
+ panic!("no importer: {raw}");
+ };
+ importer.dir = Some(scratch.0.clone());
+ importer.fetch_with(&variables)
+ };
+
+ // In text, of either spelling.
+ assert_eq!(
+ text("<${var:key}|$(var:key)>").unwrap(),
+ "<retiolum|retiolum>"
+ );
+ // In a path, an argument, and a shell command: one word, never script.
+ assert_eq!(
+ fetch("file:${var:key}").unwrap(),
+ Imported::Text("a key".into())
+ );
+ assert_eq!(
+ fetch("cmd:printf '%s' $(var:code)").unwrap(),
+ Imported::Text("$(echo no); echo no".into())
+ );
+ let argv = parse_table(
+ json!({ "command": ["printf", "%s|%s", "$(var:key)", "$(var:code)"] })
+ .as_object()
+ .unwrap(),
+ &scratch.0,
+ )
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ argv.fetch_with(&variables).unwrap(),
+ Imported::Text("retiolum|$(echo no); echo no".into())
+ );
+ // Inside another placeholder, and naming a variable by one.
+ assert_eq!(text("${cmd:cat ${var:key}}").unwrap(), "a key");
+ assert_eq!(text("${var:${cmd:echo key}}").unwrap(), "retiolum");
+ // Bytes as they are go into a `+raw` importer only; text is UTF-8.
+ assert_eq!(
+ fetch("cmd+raw:printf '%s' ${var+raw:bytes}").unwrap(),
+ Imported::Raw(b"\xff\n".to_vec())
+ );
+ assert!(text("${var+raw:bytes}").is_err());
+ let not_text = text("${var:bytes}").unwrap_err().to_string();
+ assert!(not_text.contains("not UTF-8"), "{not_text}");
+
+ // An unknown one is an error that names it, and those given.
+ let unknown = text("${var:kye}").unwrap_err().to_string();
+ assert!(
+ unknown.contains("\"kye\"") && unknown.contains("bytes, code, key"),
+ "{unknown}"
+ );
+ let unknown = fetch("cmd:echo $(var:kye)").unwrap_err().to_string();
+ assert!(unknown.contains("\"kye\""), "{unknown}");
+ // Where the program gives none, each is unknown.
+ let none = expand("${var:key}", dir).unwrap_err().to_string();
+ assert!(none.contains("no variables are given"), "{none}");
+ // The shell's own.
+ assert_eq!(
+ fetch("cmd:var=mine; printf '%s' \"$${var:-x}\"").unwrap(),
+ Imported::Text("mine".into())
+ );
+ assert!(fetch("cmd:var=mine; printf '%s' \"${var:-x}\"").is_err());
+ }
+
#[test]
fn commands_with_braces_and_quotes() {
let expanded = |template: &str| expand(template, None);
diff --git a/docs/configuration.md b/docs/configuration.md
index e40d00e..41a4aff 100644
--- a/docs/configuration.md
+++ b/docs/configuration.md
@@ -229,10 +229,12 @@ tor-key = "${cmd:secrets ${env:HOSTNAME} show tor}"
alias = { command = ["hostname-of", "${env:SITE}"] }
```
-There, only `${env:`, `${file:` and `${cmd:` begin a placeholder, or the same with
-`$(`, and every other `$` stays as it is, a command's being its shell's (`$HOME`,
+There, only `${env:`, `${file:`, `${cmd:` and `${var:` begin a placeholder, or the same
+with `$(`, and every other `$` stays as it is, a command's being its shell's (`$HOME`,
`$(…)`, `${x:-y}`); `$${` and `$$(` give the shell a `${` or a `$(` that would begin
-one. What a placeholder gives goes in as it is, never
+one. `${var:NAME}` is a variable of the program that reads the configuration, where it
+gives any: continuum gives none, so one is an error, and a shell's own `${var:-x}` is
+written `$${var:-x}`. What a placeholder gives goes in as it is, never
as something to run:
* into a name, a path and an argument as text, an argument staying one argument;