What is a suitable place to store procedural macro artifacts so that they are cleaned up by `cargo clean`?

久未见 提交于 2019-12-10 14:54:41

问题


I'm working on a procedural macro that needs a place to store state on the system where it is run. The state should be cleaned up when cargo clean is run.

In the past, I've assumed that the target directory is the proper place. However, my assumption is likely incorrect because:

  1. my files and directories may conflict with those of rustc and cargo.
  2. the location of the target directory can change from the default.

In an effort to avoid these issues, I've been attempting to determine a way to locate a location properly but haven't been successful. The closest I've found is the environment variable OUT_DIR that Cargo sets for build scripts which, unfortunately, isn't set for procedural macro runs.

Note that this question is not a duplicate of Is it possible to store state within Rust's procedural macros?. That question covers procedural macro state in general while this question is about determining a suitable location within a crate's file structure.


回答1:


It appears that the best place for storing temporary files (that both persist across compilation runs and also get cleaned up by Cargo) is to smuggle the location of the temporary directory Cargo sets up for build scripts (OUT_DIR) to the rest of your compilation environment.

One thing to keep in mind that the same directory will be used by any crate that uses your macros. Make sure to design your macro so that multiple concurrent instances of the macro can use the same directory at the same time without conflict.

Solution in steps:

  1. Place the following line in the build script of your procedural macro crate:

    println!("cargo:rustc-env=PROC_ARTIFACT_DIR={}", std::env::var("OUT_DIR").unwrap())
    
  2. Use env!("PROC_ARTIFACT_DIR") in your procedural macros to get the path to the state directory.

Note that this is only a workaround until Cargo provides native support for temp directories for procedural macro crates. Full credit for this method goes to @sven-marnach.



来源:https://stackoverflow.com/questions/56215463/what-is-a-suitable-place-to-store-procedural-macro-artifacts-so-that-they-are-cl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!