shell_env.rs

  1#![cfg_attr(not(unix), allow(unused))]
  2
  3use anyhow::{Context as _, Result};
  4use collections::HashMap;
  5
  6/// Capture all environment variables from the login shell.
  7#[cfg(unix)]
  8pub async fn capture(directory: &std::path::Path) -> Result<collections::HashMap<String, String>> {
  9    use std::os::unix::process::CommandExt;
 10    use std::process::Stdio;
 11
 12    let zed_path = super::get_shell_safe_zed_path()?;
 13    let shell_path = std::env::var("SHELL").map(std::path::PathBuf::from)?;
 14    let shell_name = shell_path.file_name().and_then(std::ffi::OsStr::to_str);
 15
 16    let mut command_string = String::new();
 17    let mut command = std::process::Command::new(&shell_path);
 18    // In some shells, file descriptors greater than 2 cannot be used in interactive mode,
 19    // so file descriptor 0 (stdin) is used instead. This impacts zsh, old bash; perhaps others.
 20    // See: https://github.com/zed-industries/zed/pull/32136#issuecomment-2999645482
 21    const FD_STDIN: std::os::fd::RawFd = 0;
 22    const FD_STDOUT: std::os::fd::RawFd = 1;
 23
 24    let (fd_num, redir) = match shell_name {
 25        Some("rc") => (FD_STDIN, format!(">[1={}]", FD_STDIN)), // `[1=0]`
 26        Some("nu") | Some("tcsh") => (FD_STDOUT, "".to_string()),
 27        _ => (FD_STDIN, format!(">&{}", FD_STDIN)), // `>&0`
 28    };
 29    command.stdin(Stdio::null());
 30    command.stdout(Stdio::piped());
 31    command.stderr(Stdio::piped());
 32
 33    let mut command_prefix = String::new();
 34    match shell_name {
 35        Some("tcsh" | "csh") => {
 36            // For csh/tcsh, login shell requires passing `-` as 0th argument (instead of `-l`)
 37            command.arg0("-");
 38        }
 39        Some("fish") => {
 40            // in fish, asdf, direnv attach to the `fish_prompt` event
 41            command_string.push_str("emit fish_prompt;");
 42            command.arg("-l");
 43        }
 44        Some("nu") => {
 45            // nu needs special handling for -- options.
 46            command_prefix = String::from("^");
 47        }
 48        _ => {
 49            command.arg("-l");
 50        }
 51    }
 52    // cd into the directory, triggering directory specific side-effects (asdf, direnv, etc)
 53    command_string.push_str(&format!("cd '{}';", directory.display()));
 54    command_string.push_str(&format!(
 55        "{}{} --printenv {}",
 56        command_prefix, zed_path, redir
 57    ));
 58    command.args(["-i", "-c", &command_string]);
 59
 60    super::set_pre_exec_to_start_new_session(&mut command);
 61
 62    let (env_output, process_output) = spawn_and_read_fd(command, fd_num).await?;
 63    let env_output = String::from_utf8_lossy(&env_output);
 64
 65    anyhow::ensure!(
 66        process_output.status.success(),
 67        "login shell exited with {}. stdout: {:?}, stderr: {:?}",
 68        process_output.status,
 69        String::from_utf8_lossy(&process_output.stdout),
 70        String::from_utf8_lossy(&process_output.stderr),
 71    );
 72
 73    // Parse the JSON output from zed --printenv
 74    let env_map: collections::HashMap<String, String> = serde_json::from_str(&env_output)
 75        .with_context(|| "Failed to deserialize environment variables from json")?;
 76    Ok(env_map)
 77}
 78
 79#[cfg(unix)]
 80async fn spawn_and_read_fd(
 81    mut command: std::process::Command,
 82    child_fd: std::os::fd::RawFd,
 83) -> anyhow::Result<(Vec<u8>, std::process::Output)> {
 84    use command_fds::{CommandFdExt, FdMapping};
 85    use std::io::Read;
 86
 87    let (mut reader, writer) = std::io::pipe()?;
 88
 89    command.fd_mappings(vec![FdMapping {
 90        parent_fd: writer.into(),
 91        child_fd,
 92    }])?;
 93
 94    let process = smol::process::Command::from(command).spawn()?;
 95
 96    let mut buffer = Vec::new();
 97    reader.read_to_end(&mut buffer)?;
 98
 99    Ok((buffer, process.output().await?))
100}
101
102/// Capture all environment variables from the shell on Windows.
103#[cfg(windows)]
104pub async fn capture(directory: &std::path::Path) -> Result<collections::HashMap<String, String>> {
105    use std::process::Stdio;
106
107    let zed_path =
108        std::env::current_exe().context("Failed to determine current zed executable path.")?;
109
110    // Use PowerShell to get environment variables in the directory context
111    let output = crate::command::new_smol_command(crate::get_windows_system_shell())
112        .args([
113            "-NonInteractive",
114            "-NoProfile",
115            "-Command",
116            &format!(
117                "Set-Location '{}'; & '{}' --printenv",
118                directory.display(),
119                zed_path.display()
120            ),
121        ])
122        .stdin(Stdio::null())
123        .stdout(Stdio::piped())
124        .stderr(Stdio::piped())
125        .output()
126        .await?;
127
128    anyhow::ensure!(
129        output.status.success(),
130        "PowerShell command failed with {}. stdout: {:?}, stderr: {:?}",
131        output.status,
132        String::from_utf8_lossy(&output.stdout),
133        String::from_utf8_lossy(&output.stderr),
134    );
135
136    let env_output = String::from_utf8_lossy(&output.stdout);
137
138    // Parse the JSON output from zed --printenv
139    let env_map: collections::HashMap<String, String> = serde_json::from_str(&env_output)
140        .with_context(|| "Failed to deserialize environment variables from json")?;
141    Ok(env_map)
142}
143
144pub fn print_env() {
145    let env_vars: HashMap<String, String> = std::env::vars().collect();
146    let json = serde_json::to_string_pretty(&env_vars).unwrap_or_else(|err| {
147        eprintln!("Error serializing environment variables: {}", err);
148        std::process::exit(1);
149    });
150    println!("{}", json);
151    std::process::exit(0);
152}