dtolnay / request-for-implementation

Crates that don't exist, but should
610 stars 6 forks source link

Attribute macro for conditional compilation options #44

Closed dtolnay closed 4 years ago

dtolnay commented 4 years ago

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 commented 4 years ago

@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 commented 4 years ago

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 commented 4 years ago

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.