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