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

Escape trailing backslashes in build script env vars #714

Merged
merged 1 commit into from
Apr 29, 2021
Merged
Show file tree
Hide file tree
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
17 changes: 15 additions & 2 deletions cargo/cargo_build_script_runner/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ impl BuildScriptOutput {
v.iter()
.filter_map(|x| {
if let BuildScriptOutput::Env(env) = x {
Some(Self::redact_exec_root(env, exec_root))
Some(Self::escape_for_serializing(Self::redact_exec_root(env, exec_root)))
} else {
None
}
Expand All @@ -143,7 +143,7 @@ impl BuildScriptOutput {
Some(format!(
"{}{}",
prefix,
Self::redact_exec_root(env, exec_root)
Self::escape_for_serializing(Self::redact_exec_root(env, exec_root))
))
} else {
None
Expand Down Expand Up @@ -176,6 +176,19 @@ impl BuildScriptOutput {
fn redact_exec_root(value: &str, exec_root: &str) -> String {
value.replace(exec_root, "${pwd}")
}

// The process-wrapper treats trailing backslashes as escapes for following newlines.
// If the env var ends with a backslash (and accordingly doesn't have a following newline),
// escape it so that it doesn't get turned into a newline by the process-wrapper.
//
// Note that this code doesn't handle newlines in strings - that's because Cargo treats build
// script output as single-line-oriented, so stops processing at the end of a line regardless.
fn escape_for_serializing(mut value: String) -> String {
if value.ends_with('\\') {
value.push('\\');
}
value
}
}

#[cfg(test)]
Expand Down
1 change: 1 addition & 0 deletions test/build_env/src/build.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
fn main() {
println!("cargo:rustc-env=CARGO_PKG_NAME_FROM_BUILD_SCRIPT={}", env!("CARGO_PKG_NAME"));
println!("cargo:rustc-env=CARGO_CRATE_NAME_FROM_BUILD_SCRIPT={}", env!("CARGO_CRATE_NAME"));
println!("cargo:rustc-env=HAS_TRAILING_SLASH=foo\\");
}
1 change: 1 addition & 0 deletions test/build_env/tests/cargo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ fn cargo_env_vars() {
assert_eq!(env!("CARGO_CRATE_NAME"), "cargo_env_vars_test");
assert_eq!(env!("CARGO_PKG_NAME_FROM_BUILD_SCRIPT"), "cargo_build_script_env-vars");
assert_eq!(env!("CARGO_CRATE_NAME_FROM_BUILD_SCRIPT"), "cargo_build_script_env_vars");
assert_eq!(env!("HAS_TRAILING_SLASH"), "foo\\");
}