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 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") => (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    match shell_name {
 34        Some("tcsh" | "csh") => {
 35            // For csh/tcsh, login shell requires passing `-` as 0th argument (instead of `-l`)
 36            command.arg0("-");
 37        }
 38        Some("fish") => {
 39            // in fish, asdf, direnv attach to the `fish_prompt` event
 40            command_string.push_str("emit fish_prompt;");
 41            command.arg("-l");
 42        }
 43        _ => {
 44            command.arg("-l");
 45        }
 46    }
 47    // cd into the directory, triggering directory specific side-effects (asdf, direnv, etc)
 48    command_string.push_str(&format!("cd '{}';", directory.display()));
 49    command_string.push_str(&format!("{} --printenv {}", zed_path, redir));
 50    command.args(["-i", "-c", &command_string]);
 51
 52    super::set_pre_exec_to_start_new_session(&mut command);
 53
 54    let (env_output, process_output) = spawn_and_read_fd(command, fd_num)?;
 55    let env_output = String::from_utf8_lossy(&env_output);
 56
 57    anyhow::ensure!(
 58        process_output.status.success(),
 59        "login shell exited with {}. stdout: {:?}, stderr: {:?}",
 60        process_output.status,
 61        String::from_utf8_lossy(&process_output.stdout),
 62        String::from_utf8_lossy(&process_output.stderr),
 63    );
 64
 65    // Parse the JSON output from zed --printenv
 66    let env_map: collections::HashMap<String, String> = serde_json::from_str(&env_output)
 67        .with_context(|| "Failed to deserialize environment variables from json")?;
 68    Ok(env_map)
 69}
 70
 71#[cfg(unix)]
 72fn spawn_and_read_fd(
 73    mut command: std::process::Command,
 74    child_fd: std::os::fd::RawFd,
 75) -> anyhow::Result<(Vec<u8>, std::process::Output)> {
 76    use command_fds::{CommandFdExt, FdMapping};
 77    use std::io::Read;
 78
 79    let (mut reader, writer) = std::io::pipe()?;
 80
 81    command.fd_mappings(vec![FdMapping {
 82        parent_fd: writer.into(),
 83        child_fd,
 84    }])?;
 85
 86    let process = command.spawn()?;
 87    drop(command);
 88
 89    let mut buffer = Vec::new();
 90    reader.read_to_end(&mut buffer)?;
 91
 92    Ok((buffer, process.wait_with_output()?))
 93}
 94
 95pub fn print_env() {
 96    let env_vars: HashMap<String, String> = std::env::vars().collect();
 97    let json = serde_json::to_string_pretty(&env_vars).unwrap_or_else(|err| {
 98        eprintln!("Error serializing environment variables: {}", err);
 99        std::process::exit(1);
100    });
101    println!("{}", json);
102    std::process::exit(0);
103}