Skip to content

Commit b55a1c5

Browse files
bors[bot]vlad20012
andauthored
Merge #11353
11353: Set current working directory for procedural macros r=vlad20012 a=vlad20012 Fixes #11079 Co-authored-by: vlad20012 <[email protected]>
2 parents 15d8f0c + 6051318 commit b55a1c5

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

crates/proc_macro_api/src/lib.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,12 +156,18 @@ impl ProcMacro {
156156
attr: Option<&Subtree>,
157157
env: Vec<(String, String)>,
158158
) -> Result<Result<Subtree, PanicMessage>, ServerError> {
159+
let current_dir = env
160+
.iter()
161+
.find(|(name, _)| name == "CARGO_MANIFEST_DIR")
162+
.map(|(_, value)| value.clone());
163+
159164
let task = ExpandMacro {
160165
macro_body: FlatTree::new(subtree),
161166
macro_name: self.name.to_string(),
162167
attributes: attr.map(FlatTree::new),
163168
lib: self.dylib_path.to_path_buf().into(),
164169
env,
170+
current_dir,
165171
};
166172

167173
let request = msg::Request::ExpandMacro(task);

crates/proc_macro_api/src/msg.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@ pub struct ExpandMacro {
4848

4949
/// Environment variables to set during macro expansion.
5050
pub env: Vec<(String, String)>,
51+
52+
pub current_dir: Option<String>,
5153
}
5254

5355
pub trait Message: Serialize + DeserializeOwned {
@@ -143,6 +145,7 @@ mod tests {
143145
attributes: None,
144146
lib: std::env::current_dir().unwrap(),
145147
env: Default::default(),
148+
current_dir: Default::default(),
146149
};
147150

148151
let json = serde_json::to_string(&task).unwrap();

crates/proc_macro_srv/src/lib.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,16 @@ impl ProcMacroSrv {
4343
prev_env.insert(k.as_str(), env::var_os(k));
4444
env::set_var(k, v);
4545
}
46+
let prev_working_dir = match task.current_dir {
47+
Some(dir) => {
48+
let prev_working_dir = std::env::current_dir().ok();
49+
if let Err(err) = std::env::set_current_dir(&dir) {
50+
eprintln!("Failed to set the current working dir to {}. Error: {:?}", dir, err)
51+
}
52+
prev_working_dir
53+
}
54+
None => None,
55+
};
4656

4757
let macro_body = task.macro_body.to_subtree();
4858
let attributes = task.attributes.map(|it| it.to_subtree());
@@ -56,6 +66,15 @@ impl ProcMacroSrv {
5666
None => env::remove_var(k),
5767
}
5868
}
69+
if let Some(dir) = prev_working_dir {
70+
if let Err(err) = std::env::set_current_dir(&dir) {
71+
eprintln!(
72+
"Failed to set the current working dir to {}. Error: {:?}",
73+
dir.display(),
74+
err
75+
)
76+
}
77+
}
5978

6079
result.map_err(PanicMessage)
6180
}

0 commit comments

Comments
 (0)