Disable building lib.rs for bins that don't use it

Our lib.rs is mostly just a directory listing of all the other .rs files in the project. When we add a new file we need to add it to the lib.rs and its a very mundane task.

I wrote a script to automate it and put it in src/bin/rebuild_lib.rs. I developed it as a separate project and it built and ran fine, however, once I moved it into the project I want to use it in it no longer works. When I try to run it with cargo run --bin rebuild_lib.rs -- --out src/lib.rs cargo tries to compile the lib.rs as dependency which fails because lib.rs is out of date.

This is a catch 22 situation now; rebuild_lib.rs is fully self contained (with the exception of the regex crate) so it doesn't need lib.rs or any of the other code in the project, but cargo refuses to build it until the rest of the project also compiles.

How can I tell cargo to build / run the script without trying to build the rest of the project? Or am I barking up the wrong tree here and should be trying some other way to automate generating the lib file? (e.g. installing ts-node in our dev environment and using the original version of the script I wrote in typescript?)

1 Like

Sounds like something that could be a stand-alone binary. Or perhaps a build script.

1 Like

I considered using a build script, but I believe that lib.rs would need to be updated before then so the rust-analyzer can do its job while I'm still writing code. In any case I will try moving it into build.rs as this is how prost currently works.

The documentation does say that build scripts should not modify any files outside of OUT_DIR, so using it to update src/lib.rs would not work.

You shouldn't put files outside of OUT_DIR, but you can import those into your lib.rs. There's an example here. That one uses include!, which operates as if you replaced the macro with the contents of the file.

If all you're doing is adding modules, there's automod.

1 Like

Sounds like you just made a cargo plugin! :slight_smile:

If you have a binary that does what you need to without depending on lib.rs, name it cargo-something and you have a cargo plugin usable by you and anyone else who installs it.

This also reminds me of cargo-xtask. It's basically a cargo plugin to easily run project specific "tasks"...

Such as adding new modules to lib.rs :slight_smile:

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.