Skip to content

Commit

Permalink
fix: better handle utf8 paths in CmdExe and Powershell (#561)
Browse files Browse the repository at this point in the history
Adds a function to force a shell to handle utf8 encoding. An
implementation is provided for cmdexe through the use of the `chcp
65001` command and something similar for Powershell.
  • Loading branch information
baszalmstra authored Mar 8, 2024
1 parent cef23f8 commit c80ee27
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
2 changes: 2 additions & 0 deletions crates/rattler_shell/src/activation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,8 @@ impl<T: Shell + Clone> Activator<T> {
// activation script followed by again emitting all environment variables. Any changes
// should then become visible.
let mut activation_detection_script = String::new();
self.shell_type
.force_utf8(&mut activation_detection_script)?;
self.shell_type.env(&mut activation_detection_script)?;
self.shell_type
.echo(&mut activation_detection_script, ENV_START_SEPERATOR)?;
Expand Down
19 changes: 19 additions & 0 deletions crates/rattler_shell/src/shell/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ use thiserror::Error;
/// ```
#[enum_dispatch(ShellEnum)]
pub trait Shell {
/// Write a command to the script that forces the usage of UTF8-encoding for the shell script.
fn force_utf8(&self, _f: &mut impl Write) -> std::fmt::Result {
Ok(())
}

/// Set an env var by `export`-ing it.
fn set_env_var(&self, f: &mut impl Write, env_var: &str, value: &str) -> std::fmt::Result;

Expand Down Expand Up @@ -321,6 +326,10 @@ impl Shell for Xonsh {
pub struct CmdExe;

impl Shell for CmdExe {
fn force_utf8(&self, f: &mut impl Write) -> std::fmt::Result {
writeln!(f, "@chcp 65001")
}

fn set_env_var(&self, f: &mut impl Write, env_var: &str, value: &str) -> std::fmt::Result {
writeln!(f, "@SET \"{env_var}={value}\"")
}
Expand Down Expand Up @@ -385,6 +394,16 @@ pub struct PowerShell {
}

impl Shell for PowerShell {
fn force_utf8(&self, f: &mut impl Write) -> std::fmt::Result {
// Taken from https://stackoverflow.com/questions/51933189/character-encoding-utf-8-in-powershell-session
writeln!(f, "$OutputEncoding = [System.Text.Encoding]::UTF8")?;
writeln!(
f,
"[Console]::OutputEncoding = [System.Text.Encoding]::UTF8"
)?;
writeln!(f, "chcp 65001")
}

fn set_env_var(&self, f: &mut impl Write, env_var: &str, value: &str) -> std::fmt::Result {
writeln!(f, "${{Env:{env_var}}} = \"{value}\"")
}
Expand Down

0 comments on commit c80ee27

Please sign in to comment.