Copy files to the target directory after build

2020-08-16 12:15发布

问题:

Let's assume I have a game with the following directory structure:

/src
/resources
Cargo.toml

I would like cargo build to copy the files in the resources directory and paste them in the same directory as the executable file.

I know it is possible to do this using a custom build script, but this seems to be a common case that deserves special treatment. So the question is: does cargo provide a standard way of copying files to the target directory (using just Cargo.toml)?

回答1:

No, it doesn't.

You can move files around with build scripts, but these are run before your crate is built because their sole purpose is to prepare the environment (e.g. compile C libraries and shims).

If you think this is an important feature, you can open a feature request in Cargo issue tracker.

Alternatively, you can write a makefile or a shell script which would forward all arguments to cargo and then copy the directory manually:

#!/bin/bash

DIR="$(dirname "$0")"

if cargo "$@"; then
    [ -d "$DIR/target/debug" ] && cp -r "$DIR/resources" "$DIR/target/debug/resources"
    [ -d "$DIR/target/release" ] && cp -r "$DIR/resources" "$DIR/target/release/resources"
fi

Now you can run cargo like

% ./make.sh build