Search code examples
rustrust-cargorust-crates

Can we download something & set environment variable during crate installation?


As a Rust driver crate developer, I would like to perform below steps during my crate installation/download when used by any other Rust program:

  1. Check the platform i.e. Windows or UNIX or macOS.
  2. Download the corresponding platform-specific binary from an external website.
  3. Set an environment variable pointing to the download location.

I know this is possible in Node or Python or R but not sure if this is possible in Rust.


Solution

  • You can use Build script to achieve that (but it is not what you should do, please see note below).

    The script will be compiled and executed before cargo start building your library.

    1. Inside the script you can use cfg attribute to check platform.
    2. There is a bunch of libraries to download something via HTTP, for example reqwest
    3. You can set environment variable via cargo:rustc-env=VAR=VALUE

    IMPORTANT NOTE

    Most of Rust users doesn't expect that kind of behavior from build script. There may be dozen of problems with the approach. Just few of them from the top of my head:

    • First of all there may be security issues.
    • The approach will break builds at client side.

    I believe it's better to upload all binaries you need as a part of the crate. You can use include_bytes! for that.