Skip to content

Set current working directory for procedural macros #11353

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 27, 2022
Merged
Show file tree
Hide file tree
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
6 changes: 6 additions & 0 deletions crates/proc_macro_api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,12 +156,18 @@ impl ProcMacro {
attr: Option<&Subtree>,
env: Vec<(String, String)>,
) -> Result<Result<Subtree, PanicMessage>, ServerError> {
let current_dir = env
.iter()
.find(|(name, _)| name == "CARGO_MANIFEST_DIR")
.map(|(_, value)| value.clone());

let task = ExpandMacro {
macro_body: FlatTree::new(subtree),
macro_name: self.name.to_string(),
attributes: attr.map(FlatTree::new),
lib: self.dylib_path.to_path_buf().into(),
env,
current_dir,
};

let request = msg::Request::ExpandMacro(task);
Expand Down
3 changes: 3 additions & 0 deletions crates/proc_macro_api/src/msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ pub struct ExpandMacro {

/// Environment variables to set during macro expansion.
pub env: Vec<(String, String)>,

pub current_dir: Option<String>,
}

pub trait Message: Serialize + DeserializeOwned {
Expand Down Expand Up @@ -143,6 +145,7 @@ mod tests {
attributes: None,
lib: std::env::current_dir().unwrap(),
env: Default::default(),
current_dir: Default::default(),
};

let json = serde_json::to_string(&task).unwrap();
Expand Down
19 changes: 19 additions & 0 deletions crates/proc_macro_srv/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,16 @@ impl ProcMacroSrv {
prev_env.insert(k.as_str(), env::var_os(k));
env::set_var(k, v);
}
let prev_working_dir = match task.current_dir {
Some(dir) => {
let prev_working_dir = std::env::current_dir().ok();
if let Err(err) = std::env::set_current_dir(&dir) {
eprintln!("Failed to set the current working dir to {}. Error: {:?}", dir, err)
}
prev_working_dir
}
None => None,
};

let macro_body = task.macro_body.to_subtree();
let attributes = task.attributes.map(|it| it.to_subtree());
Expand All @@ -56,6 +66,15 @@ impl ProcMacroSrv {
None => env::remove_var(k),
}
}
if let Some(dir) = prev_working_dir {
if let Err(err) = std::env::set_current_dir(&dir) {
eprintln!(
"Failed to set the current working dir to {}. Error: {:?}",
dir.display(),
err
)
}
}

result.map_err(PanicMessage)
}
Expand Down