Include directory in proc macro

I wrote a proc macro like this:

include_dir!(path/to/folder);

that finds a directory, reads all the files, and does something with them.

I have 2 questions about a macro like this:

  1. Is it possible to use the relative path (like in include_str!) instead of the absolute path from cargo.toml?

  2. Is there a way to make sure rust recompiles this macro after something changes in the folder? Currently only changes in the source code trigger recompilation.

Off the shelf:

It's not possible on stable. It's not possible to get the source filepath, and the working directory of the proc macro is technically unspecified as well[1], so you should grab $env:CARGO_MANIFEST_DIR instead of relying on cwd.

For files that actually get included, you can emit a const _: &str = include_str!("path"); to get the included file included in change detection. But on stable, there's no other way to track a path to rerun the proc macro like there is for buildscripts. But the buildscript tracked path functionality has actually supported watching a full directory for any contained changes for a while now. (It used to instead only watch the folder metadata for changes, thus ignoring changes within the folder, which isn't very useful.)


  1. I think it's been both the directory cargo was invoked from and the manifest directory of the currently compiled crate. But also, looking at the docs, the initial cwd might be documented to be the manifest directory now. â†Šī¸Ž

1 Like

Currently cargo invokes rustc in the workspace directory.

It's a bit funnier: when you compile the code it's manifest directory for the workspace, but when doctests are collected it's manifest directory for the crate. CARGO_MANIFEST_DIR is consistent even if workspaces are used.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.