Skip to content

internal: Rollback env vars changed by a proc macro #11356

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 30, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 32 additions & 9 deletions crates/proc_macro_srv/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ mod abis;

use std::{
collections::{hash_map::Entry, HashMap},
env, fs,
env,
ffi::OsString,
fs,
path::{Path, PathBuf},
time::SystemTime,
};
Expand All @@ -38,9 +40,8 @@ impl ProcMacroSrv {
PanicMessage(format!("failed to load macro: {}", err))
})?;

let mut prev_env = HashMap::new();
let prev_env = EnvSnapshot::new();
for (k, v) in &task.env {
prev_env.insert(k.as_str(), env::var_os(k));
env::set_var(k, v);
}
let prev_working_dir = match task.current_dir {
Expand All @@ -60,12 +61,8 @@ impl ProcMacroSrv {
.expand(&task.macro_name, &macro_body, attributes.as_ref())
.map(|it| FlatTree::new(&it));

for (k, _) in &task.env {
match &prev_env[k.as_str()] {
Some(v) => env::set_var(k, v),
None => env::remove_var(k),
}
}
prev_env.rollback();

if let Some(dir) = prev_working_dir {
if let Err(err) = std::env::set_current_dir(&dir) {
eprintln!(
Expand Down Expand Up @@ -101,6 +98,32 @@ impl ProcMacroSrv {
}
}

struct EnvSnapshot {
vars: HashMap<OsString, OsString>,
}

impl EnvSnapshot {
fn new() -> EnvSnapshot {
EnvSnapshot { vars: env::vars_os().collect() }
}

fn rollback(self) {
let mut old_vars = self.vars;
for (name, value) in env::vars_os() {
let old_value = old_vars.remove(&name);
if old_value != Some(value) {
match old_value {
None => env::remove_var(name),
Some(old_value) => env::set_var(name, old_value),
}
}
}
for (name, old_value) in old_vars {
env::set_var(name, old_value)
}
}
}

pub mod cli;

#[cfg(test)]
Expand Down