Skip to content

Commit

Permalink
Set current working directory for procedural macros
Browse files Browse the repository at this point in the history
  • Loading branch information
vlad20012 committed Jan 27, 2022
1 parent e149a15 commit 6051318
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
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

0 comments on commit 6051318

Please sign in to comment.