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