Skip to content

Commit

Permalink
Escape Windows paths with spaces in venv activation command (#2223)
Browse files Browse the repository at this point in the history
## Summary

Ensure that we print `& "foo bar\Scripts\activate"` if necessary.
  • Loading branch information
charliermarsh authored Mar 5, 2024
1 parent 9f1bb4d commit 65518c9
Showing 1 changed file with 21 additions and 15 deletions.
36 changes: 21 additions & 15 deletions crates/uv/src/commands/venv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,29 +216,21 @@ async fn venv_impl(
None => None,
Some(Shell::Bash | Shell::Zsh) => Some(format!(
"source {}",
shlex(path.join("bin").join("activate"))
shlex_posix(path.join("bin").join("activate"))
)),
Some(Shell::Fish) => Some(format!(
"source {}",
shlex(path.join("bin").join("activate.fish"))
shlex_posix(path.join("bin").join("activate.fish"))
)),
Some(Shell::Nushell) => Some(format!(
"overlay use {}",
shlex(path.join("bin").join("activate.nu"))
shlex_posix(path.join("bin").join("activate.nu"))
)),
Some(Shell::Csh) => Some(format!(
"source {}",
shlex(path.join("bin").join("activate.csh"))
shlex_posix(path.join("bin").join("activate.csh"))
)),
Some(Shell::Powershell) => {
// No need to quote the path for PowerShell.
Some(
path.join("Scripts")
.join("activate")
.simplified_display()
.to_string(),
)
}
Some(Shell::Powershell) => Some(shlex_windows(path.join("Scripts").join("activate"))),
};
if let Some(act) = activation {
writeln!(printer, "Activate with: {}", act.green()).into_diagnostic()?;
Expand All @@ -247,8 +239,8 @@ async fn venv_impl(
Ok(ExitStatus::Success)
}

/// Quote a path, if necessary, for safe use in a shell command.
fn shlex(executable: impl AsRef<Path>) -> String {
/// Quote a path, if necessary, for safe use in a POSIX-compatible shell command.
fn shlex_posix(executable: impl AsRef<Path>) -> String {
// Convert to a display path.
let executable = executable.as_ref().simplified_display().to_string();

Expand All @@ -261,3 +253,17 @@ fn shlex(executable: impl AsRef<Path>) -> String {
executable
}
}

/// Quote a path, if necessary, for safe use in `PowerShell`.
fn shlex_windows(executable: impl AsRef<Path>) -> String {
// Convert to a display path.
let executable = executable.as_ref().simplified_display().to_string();

// Wrap the executable in quotes (and a `&` invocation) if it contains spaces.
// TODO(charlie): This won't work in `cmd.exe`.
if executable.contains(' ') {
format!("& \"{executable}\"")
} else {
executable
}
}

0 comments on commit 65518c9

Please sign in to comment.