From 34434f7fd5a6bab1884a63c96679f48045f4bffd Mon Sep 17 00:00:00 2001 From: tv Date: Mon, 30 Nov 2026 21:06:06 +0000 Subject: config: placeholders in parentheses, for where braces are another language's A placeholder may be written $(env:NAME), $(file:PATH) or $(cmd:COMMAND), ending at the parenthesis matching its own: the same as with braces, nesting and all. A configuration written in Nix, or passed through a systemd unit, needs no escapes so. --- CHANGELOG.md | 7 +++ crates/config/src/import.rs | 123 ++++++++++++++++++++++++++++++++++++-------- docs/configuration.md | 20 +++++-- 3 files changed, 126 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f363c4..d5c6ac5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,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)). +* 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 + `cmd:…` by `$(…)` writes `$$(` + ([`docs/configuration.md`](docs/configuration.md), + [Importing values](docs/configuration.md#importing-values)). + * Placeholders nest: `${cmd:secrets ${env:HOSTNAME} show x}`, and in a name, a path, a command and each argument of an importer. What a placeholder gives is never run: an argument stays one argument, and a shell command gets it as a positional parameter. diff --git a/crates/config/src/import.rs b/crates/config/src/import.rs index 04d396f..61d162f 100644 --- a/crates/config/src/import.rs +++ b/crates/config/src/import.rs @@ -19,12 +19,14 @@ //! Any other text value may hold placeholders, `${env:NAME}`, `${file:PATH}` or //! `${cmd:COMMAND}`, each replaced by its content as text (`$$` is a `$`; a placeholder //! ends at the `}` matching its `{`), e.g. `node-${env:HOSTNAME}`. Relative paths are -//! relative to the file, and commands run in its directory, in placeholders too. +//! relative to the file, and commands run in its directory, in placeholders too. A +//! placeholder may be written `$(env:NAME)` instead, ending at the `)` matching its `(`: +//! the same, for where `${` is another language's (Nix, a systemd unit). //! //! 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, `$${` is a `${`, and every other `$` stays -//! as it is: a command's are its shell's. What a placeholder gives goes in as data, never +//! `${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 //! 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 @@ -292,11 +294,27 @@ pub enum Imported { Raw(Vec), } -/// Where the placeholder that `text` starts (after its `${`) ends: at the `}` that -/// matches its `{`. Braces inside balance, so a command may hold `{...}` (a jq object, a -/// shell group) and a placeholder others; in a command (`cmd:`), braces in shell quotes -/// (`'...'`, `"..."`) or escaped with a backslash don't count either. -fn placeholder_end(text: &str) -> Option { +/// What `text`, after a `$`, opens a placeholder with: the text after its `{` or `(`, +/// and what closes it. +fn opened(text: &str) -> Option<(&str, char)> { + if let Some(after) = text.strip_prefix('{') { + Some((after, '}')) + } else { + text.strip_prefix('(').map(|after| (after, ')')) + } +} + +/// What opens a placeholder that `close` closes. +fn opener(close: char) -> char { + if close == '}' { '{' } else { '(' } +} + +/// Where the placeholder that `text` starts (after its `${` or `$(`, its `open`) ends: +/// at the `close` that matches it. Those inside balance, so a command may hold `{...}` +/// (a jq object, a shell group) or `(...)` (a subshell, a `$(…)` of its shell's) and a +/// placeholder others; in a command (`cmd:`), those in shell quotes (`'...'`, `"..."`) +/// or escaped with a backslash don't count either. +fn placeholder_end(text: &str, open: char, close: char) -> Option { let shell = text.starts_with("cmd:") || text.starts_with("cmd+"); let mut depth = 0usize; let mut quote: Option = None; @@ -322,9 +340,9 @@ fn placeholder_end(text: &str) -> Option { } } match char { - '{' => depth += 1, - '}' if depth == 0 => return Some(at), - '}' => depth -= 1, + _ if char == open => depth += 1, + _ if char == close && depth == 0 => return Some(at), + _ if char == close => depth -= 1, _ => {} } } @@ -368,8 +386,8 @@ fn expand(template: &str, dir: Option<&Path>) -> Result { if let Some(after) = after.strip_prefix('$') { out.push('$'); rest = after; - } else if let Some(after) = after.strip_prefix('{') { - let end = placeholder_end(after) + } 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)?; out.push_str(&String::from_utf8(text).expect("a text importer gives text")); @@ -378,7 +396,7 @@ fn expand(template: &str, dir: Option<&Path>) -> Result { // Most likely a shell-style `$NAME` that would silently stay as it is. bail!( "a `$` in {template:?} that starts no placeholder: write `$$` for a `$`, or \ - e.g. `${{env:NAME}}` for a variable" + e.g. `${{env:NAME}}` or `$(env:NAME)` for a variable" ); } } @@ -387,7 +405,7 @@ fn expand(template: &str, dir: Option<&Path>) -> Result { } /// A part of what an importer names: text as it is, or a placeholder (between its `${` -/// and `}`). +/// and `}`, or its `$(` and `)`). #[derive(Debug, PartialEq, Eq)] enum Part<'a> { Text(String), @@ -408,14 +426,13 @@ fn parts(text: &str) -> Result>> { while let Some(at) = rest.find('$') { plain.push_str(&rest[..at]); let from = &rest[at..]; - if from.starts_with("$${") { + if from.starts_with("$${") || from.starts_with("$$(") { plain.push('$'); rest = &from[2..]; - } else if let Some(after) = from - .strip_prefix("${") - .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))) { - let end = placeholder_end(after) + let end = placeholder_end(after, opener(close), close) .ok_or_else(|| anyhow!("unterminated placeholder in {text:?}"))?; if !plain.is_empty() { parts.push(Part::Text(std::mem::take(&mut plain))); @@ -750,7 +767,7 @@ mod tests { #[test] fn placeholders_end_at_their_matching_brace() { fn end(text: &str) -> Option<&str> { - placeholder_end(text).map(|at| &text[..at]) + placeholder_end(text, '{', '}').map(|at| &text[..at]) } assert_eq!(end("env:HOST}-x"), Some("env:HOST")); // Balanced braces, as a jq object has them. @@ -772,6 +789,70 @@ mod tests { ); } + /// A placeholder spelled `$(…)`, which a language with `${…}` of its own (Nix) + /// leaves as it is: the same as `${…}`, ending at its matching parenthesis. + #[test] + fn placeholders_in_parentheses() { + fn end(text: &str) -> Option<&str> { + placeholder_end(text, '(', ')').map(|at| &text[..at]) + } + assert_eq!(end("env:HOST)-x"), Some("env:HOST")); + // Balanced parentheses: a subshell, the shell's own `$(…)` and `$((…))`. + assert_eq!(end("cmd:(cd /; pwd))x"), Some("cmd:(cd /; pwd)")); + assert_eq!( + end("cmd:echo $(date) $((1 + 1)))x"), + Some("cmd:echo $(date) $((1 + 1))") + ); + // In a command, those in quotes or escaped don't count; braces never do. + assert_eq!(end("cmd:printf ')'}{)x"), Some("cmd:printf ')'}{")); + assert_eq!(end(r"cmd:printf \))x"), Some(r"cmd:printf \)")); + assert_eq!(end("env:X"), None); + + let expanded = |template: &str| expand(template, None); + assert_eq!(expanded("a-$(cmd:echo b)-c $$5").unwrap(), "a-b-c $5"); + // Of both spellings, and one inside the other, either way. + assert_eq!( + expanded("$(cmd:printf one)${cmd:printf two}").unwrap(), + "onetwo" + ); + assert_eq!( + expanded("<$(cmd:printf '%s' ${cmd:printf '%s' $(cmd:echo in)})>").unwrap(), + "" + ); + assert_eq!( + expanded(r#"$(cmd:printf '%s' "$(echo '::1')" | tr -d '()')"#).unwrap(), + "::1" + ); + // A `$(` written out. + assert_eq!(expanded("$$(env:HOME)").unwrap(), "$(env:HOME)"); + assert!(expanded("$(cmd:echo b").is_err()); + assert!(expanded("$(plain)").is_err()); + assert!(expanded("$(env+json:X)").is_err()); + + // Inside an importer, only `$(env:`, `$(file:` and `$(cmd:` begin one; the + // shell's own stay, and `$$(` gives it a `$(` that would be a placeholder's. + let text = |text: &str| Part::Text(text.to_owned()); + assert_eq!( + parts("secrets $(env:HOST) show $(date) $(cmd+raw:x)").unwrap(), + [ + text("secrets "), + Part::Placeholder("env:HOST"), + text(" show $(date) "), + Part::Placeholder("cmd+raw:x"), + ] + ); + assert_eq!( + parts("echo $$(env:x) $$").unwrap(), + [text("echo $(env:x) $$")] + ); + assert!(parts("echo $(env:HOST").is_err()); + // What it gives is data to the shell, as with braces. + assert_eq!( + expanded("$(cmd:printf '%s' $(cmd:printf '%s' '$(echo no); echo no'))").unwrap(), + "$(echo no); echo no" + ); + } + #[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 27b73be..e40d00e 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -197,6 +197,19 @@ in shell quotes (`'...'`, `"..."`) or after a backslash don't count, so a comman hold `$`, quotes and braces of its own. `literal:` on the command line turns this off too. +A placeholder may be written with parentheses instead, `$(env:NAME)`, `$(file:PATH)`, +`$(cmd:COMMAND)`: the same, ending at the `)` that matches its `(`, parentheses +balancing and counting as braces do. So a configuration written in a language with a +`${…}` of its own, as Nix has, or passed through one (a systemd unit's `ExecStart=`), +needs no escapes there: + +```nix +{ alias = "$(env:SITE)-$(cmd:hostname -s)"; } +``` + +A command whose own parentheses don't balance outside quotes (a `case` pattern) is +written with braces. + ```sh continuum --alias 'node-${env:HOSTNAME}' ``` @@ -216,9 +229,10 @@ tor-key = "${cmd:secrets ${env:HOSTNAME} show tor}" alias = { command = ["hostname-of", "${env:SITE}"] } ``` -There, only `${env:`, `${file:` and `${cmd:` begin a placeholder, and every other `$` -stays as it is, a command's being its shell's (`$HOME`, `$(…)`, `${x:-y}`); `$${` gives -the shell a `${` that would begin one. What a placeholder gives goes in as it is, never +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`, +`$(…)`, `${x:-y}`); `$${` and `$$(` give the shell a `${` or a `$(` that would begin +one. 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; -- cgit v1.3.1