Skip to content

Commit

Permalink
feat(layout): Support environment variables in cwd (zellij-org#2288)
Browse files Browse the repository at this point in the history
* add `shellexpand` as dependency
* expand environment variable in kdl parser's `parse_cwd()`
  • Loading branch information
shahamran committed Mar 15, 2023
1 parent 09c1d79 commit 2a8ca06
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 1 deletion.
21 changes: 20 additions & 1 deletion Cargo.lock

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

1 change: 1 addition & 0 deletions zellij-utils/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ miette = { version = "3.3.0", features = ["fancy"] }
regex = "1.5.5"
tempfile = "3.2.0"
kdl = { version = "4.5.0", features = ["span"] }
shellexpand = "3.0.0"

#[cfg(not(target_family = "wasm"))]
[target.'cfg(not(target_family = "wasm"))'.dependencies]
Expand Down
32 changes: 32 additions & 0 deletions zellij-utils/src/input/unit/layout_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2031,3 +2031,35 @@ fn run_plugin_location_parsing() {
};
assert_eq!(layout, expected_layout);
}

fn get_cwd(layout: &Layout) -> Option<&PathBuf> {
match layout.template.as_ref()?.0.children.get(0)?.run.as_ref()? {
Run::Cwd(cwd) => Some(cwd),
_ => None,
}
}

#[test]
fn pane_cwd_valid_env_var() {
let kdl_layout = r#"
layout {
pane cwd="$ZELLIJ_FOO/foo"
}
"#;
std::env::set_var("ZELLIJ_FOO", "/test_cwd");
let layout = Layout::from_kdl(kdl_layout, "layout_file_name".into(), None, None).unwrap();
let cwd = get_cwd(&layout).unwrap();
assert_eq!(cwd.to_string_lossy(), "/test_cwd/foo");
}

#[test]
fn pane_cwd_invalid_env_var() {
let kdl_layout = r#"
layout {
pane cwd="$ZELLIJ_BAR/foo"
}
"#;
std::env::remove_var("ZELLIJ_BAR");
let layout = Layout::from_kdl(kdl_layout, "layout_file_name".into(), None, None).unwrap();
assert_eq!(get_cwd(&layout), None);
}
7 changes: 7 additions & 0 deletions zellij-utils/src/kdl/kdl_layout_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,13 @@ impl<'a> KdlLayoutParser<'a> {
fn parse_cwd(&self, kdl_node: &KdlNode) -> Result<Option<PathBuf>, ConfigError> {
Ok(
kdl_get_string_property_or_child_value_with_error!(kdl_node, "cwd")
.and_then(|cwd| match shellexpand::env(cwd) {
Ok(cwd) => Some(cwd.to_string()),
Err(e) => {
log::error!("when parsing `cwd`: {}", e);
None
},
})
.map(|cwd| PathBuf::from(cwd)),
)
}
Expand Down

0 comments on commit 2a8ca06

Please sign in to comment.