Skip to content

Commit

Permalink
Add a --greedy-defaults option
Browse files Browse the repository at this point in the history
  • Loading branch information
stephenc committed Aug 28, 2019
1 parent 3839a66 commit 99f8357
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 2 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "envsub"
version = "0.1.0"
version = "0.1.1"
authors = ["Stephen Connolly <[email protected]>"]

[dependencies]
Expand Down
2 changes: 2 additions & 0 deletions README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ The program pipes stdin to stdout one line at a time applying the required subst
+
NOTE: If your suffix starts with `:` or `-` you will not have a good time as this will conflict with the default value separator that is internal to the pattern.

`-g`, `--greedy-defaults`:: Enables greedy replacement of unmatched default values. With this option if you have `${FOO}` and there is no corresponding variable `FOO` then that will remain untouched but `${FOO:-BAR}` or `${FOO-BAR}` will be replaced as `BAR` whereas without this option they would remain untouched.

`-v`, `--var`:: Only replace the named variable. _Can be specified multiple times_ if you want to replace multiple variables. If not specified then all variables from the environment can be substituted.

`-V`, `--version`:: Display the program version and exit.
Expand Down
22 changes: 22 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ fn create_options() -> Options {
let mut opts = Options::new();
opts.optflag("h", "help", "print this help menu and exit");
opts.optflag("V", "version", "print the version and exit");
opts.optflag("g", "greedy-defaults", "allow expansion of undefined variable defaults");
opts.optmulti(
"v",
"variable",
Expand Down Expand Up @@ -84,6 +85,20 @@ fn main() {
Some(v) => v,
None => "}".to_string(),
};
let greedy = match matches.opt_present("g") {
true => Some(
Regex::new(
format!(
r#"{}[a-zA-Z_][a-zA-Z0-9_]*:?-(.*?){}"#,
regex::escape(prefix.clone().as_str()),
regex::escape(suffix.clone().as_str())
)
.as_str(),
)
.unwrap()
),
false => None,
};
let vars = match matches.opt_present("v") {
true => {
let mut vars = HashMap::new();
Expand Down Expand Up @@ -178,6 +193,13 @@ fn main() {
})
.to_string();
}
out = match greedy.clone() {
Some(regex) => regex.replace_all(
out.as_str(),
|caps: &Captures| caps.get(1).map_or("", |m| m.as_str())
).to_string(),
None => out,
};
writer.write(out.as_bytes()).unwrap();
writer.write("\n".as_bytes()).unwrap();
writer.flush().unwrap();
Expand Down

0 comments on commit 99f8357

Please sign in to comment.