aboutsummaryrefslogtreecommitdiffstats
path: root/crates/config/src/import.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/config/src/import.rs')
-rw-r--r--crates/config/src/import.rs123
1 files changed, 102 insertions, 21 deletions
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<u8>),
}
-/// 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<usize> {
+/// 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<usize> {
let shell = text.starts_with("cmd:") || text.starts_with("cmd+");
let mut depth = 0usize;
let mut quote: Option<char> = None;
@@ -322,9 +340,9 @@ fn placeholder_end(text: &str) -> Option<usize> {
}
}
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<String> {
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<String> {
// 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<String> {
}
/// 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<Vec<Part<'_>>> {
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(),
+ "<in>"
+ );
+ 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);