Skip to content
This repository has been archived by the owner on Jul 9, 2023. It is now read-only.

Attribute macro for conditional compilation options #44

Closed
dtolnay opened this issue Nov 2, 2019 · 3 comments
Closed

Attribute macro for conditional compilation options #44

dtolnay opened this issue Nov 2, 2019 · 3 comments

Comments

@dtolnay
Copy link
Owner

dtolnay commented Nov 2, 2019

Similar idea to what https://github.com/dtolnay/rustversion does for compiler version selection, but for lots of other things people want to be conditional on.


Environment variables

Conditional compilation based on whether an environment variable is defined at build time.

For example you could use this to disable or enable specific code when building in CI:
https://docs.travis-ci.com/user/environment-variables/#default-environment-variables

#[condition::env("TRAVIS")]
fn run() {...}

#[condition::not(env("TRAVIS"))]
fn run() {...}

PATH

Conditional compilation based on whether some binary is available on the system's PATH.

For example you could conditionally ignore a test case that requires some specific binary.

#[condition::attr(not(cmd("cargo-expand")), ignore)]
fn my_test() {...}

^ This expands to #[ignore] if there is no cargo-expand on the PATH. Ignored tests are logged by the test runner and is friendlier than considering the test failed or silently passing it.


More...

Potentially other ideas.

@mtkennerly
Copy link

mtkennerly commented Jul 12, 2020

@dtolnay Hi! I just published a crate called Realia that implements these:

#[realia::env("NAME")]
#[realia::env("NAME", "value")]
#[realia::cmd("name")]

Let me know what you think :D

I really wanted to implement checks for dependencies as well (installed, exact version, version since, version before, source from registry/git/path), but I don't think it's possible for Realia's proc macros to discover the dependencies of a crate using Realia. If I check the crate metadata in Realia's build.rs, then it only sees Realia's dependencies, and if I check the crate metadata in the parent crate's build.rs, then there's no way to reference it in the proc macro because of hygiene.

@dtolnay
Copy link
Owner Author

dtolnay commented Jul 12, 2020

Awesome! I will add a link from the readme here. Thanks for putting this together.

I don't know a way to inspect the downstream crate's dependencies either.

@mtkennerly
Copy link

Follow-up: Thanks to a suggestion I received, I was able to figure out a way to add checks for dependencies as well! More info here.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants