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") | 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)?;
 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)]
 80fn 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 = command.spawn()?;
 95    drop(command);
 96
 97    let mut buffer = Vec::new();
 98    reader.read_to_end(&mut buffer)?;
 99
100    Ok((buffer, process.wait_with_output()?))
101}
102
103pub fn print_env() {
104    let env_vars: HashMap<String, String> = std::env::vars().collect();
105    let json = serde_json::to_string_pretty(&env_vars).unwrap_or_else(|err| {
106        eprintln!("Error serializing environment variables: {}", err);
107        std::process::exit(1);
108    });
109    println!("{}", json);
110    std::process::exit(0);
111}