Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

devenv: escape shell vars in task exports #1477

Merged
merged 1 commit into from
Sep 26, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion devenv/src/tasks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,11 @@ impl TaskState {
for (env_key, env_value) in env_obj {
if let Some(env_str) = env_value.as_str() {
command.env(env_key, env_str);
devenv_env.push_str(&format!("export {}={}\n", env_key, env_str));
devenv_env.push_str(&format!(
"export {}={}\n",
env_key,
shell_escape(env_str)
));
}
}
}
Expand Down Expand Up @@ -836,6 +840,21 @@ impl TasksUi {
}
}

/// Escape a shell variable by wrapping it in single quotes.
/// Any single quotes within the variable are escaped.
fn shell_escape(s: &str) -> String {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if we should instead use some library like https://docs.rs/shell-quote/latest/shell_quote/ not to maintain this code which is tricky to get right

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, maybe. The above is what nix develop does, which felt like a safe choice without getting into the weeds.

let mut escaped = String::with_capacity(s.len() + 2);
escaped.push('\'');
for c in s.chars() {
match c {
'\'' => escaped.push_str("'\\''"),
_ => escaped.push(c),
}
}
escaped.push('\'');
escaped
}

#[cfg(test)]
mod test {
use super::*;
Expand All @@ -846,6 +865,13 @@ mod test {
use std::io::Write;
use std::os::unix::fs::PermissionsExt;

#[test]
fn test_shell_escape() {
let escaped = shell_escape("foo'bar");
eprintln!("{escaped}");
assert_eq!(escaped, "'foo'\\''bar'");
}

#[tokio::test]
async fn test_task_name() -> Result<(), Error> {
let invalid_names = vec![
Expand Down
Loading