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!("sh -c '{zed_path} --printenv >&{ENV_OUTPUT_FD}';"));
42 command.args(["-i", "-c", &command_string]);
43 super::set_pre_exec_to_start_new_session(&mut command);
44
45 let (env_output, process_output) = spawn_and_read_fd(command, ENV_OUTPUT_FD)?;
46 let env_output = String::from_utf8_lossy(&env_output);
47
48 anyhow::ensure!(
49 process_output.status.success(),
50 "login shell exited with {}. stdout: {:?}, stderr: {:?}",
51 process_output.status,
52 String::from_utf8_lossy(&process_output.stdout),
53 String::from_utf8_lossy(&process_output.stderr),
54 );
55
56 // Parse the JSON output from zed --printenv
57 let env_map: collections::HashMap<String, String> = serde_json::from_str(&env_output)
58 .with_context(|| "Failed to deserialize environment variables from json")?;
59 Ok(env_map)
60}
61
62#[cfg(unix)]
63fn spawn_and_read_fd(
64 mut command: std::process::Command,
65 child_fd: std::os::fd::RawFd,
66) -> anyhow::Result<(Vec<u8>, std::process::Output)> {
67 use command_fds::{CommandFdExt, FdMapping};
68 use std::io::Read;
69
70 let (mut reader, writer) = std::io::pipe()?;
71
72 command.fd_mappings(vec![FdMapping {
73 parent_fd: writer.into(),
74 child_fd,
75 }])?;
76
77 let process = command.spawn()?;
78 drop(command);
79
80 let mut buffer = Vec::new();
81 reader.read_to_end(&mut buffer)?;
82
83 Ok((buffer, process.wait_with_output()?))
84}
85
86pub fn print_env() {
87 let env_vars: HashMap<String, String> = std::env::vars().collect();
88 let json = serde_json::to_string_pretty(&env_vars).unwrap_or_else(|err| {
89 eprintln!("Error serializing environment variables: {}", err);
90 std::process::exit(1);
91 });
92 println!("{}", json);
93 std::process::exit(0);
94}