如何在构建过程中包含文件夹?

rog*_*cro 5 rust

我有这个文件结构:

\n\n
myProject\n|\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 FolderToInclude\n|          |\n|          \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 somebatfile.bat\n|\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 src\n|    |\n|    \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 main.rs\n|\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 target\n       |\n       \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 debug\n             |\n             \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 myProject.exe // and other stuff\n
Run Code Online (Sandbox Code Playgroud)\n\n

rust 是否可以在构建目录中包含一个文件夹?\n我想最终得到以下文件结构:

\n\n
myProject\n|\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 FolderToInclude\n|          |\n|          \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 somebatfile.bat\n|\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 src\n|    |\n|    \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 main.rs\n|\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 target\n       |\n       \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 debug\n             |\n             \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 myProject.exe // and other stuff\n             |\n             \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 FolderToInclude\n                       |\n                       \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 somebatfile.bat\n
Run Code Online (Sandbox Code Playgroud)\n

Tri*_*yPR 4

当 Cargo 编译项目时,它会检查构建脚本,该脚本只是纯 Rust。您可以使用它来整理 C 代码或捆绑资源。该脚本可以使用许多有用的环境变量。以下build.rs文件应该适用于您的用例:

use std::{
    env, fs,
    path::{Path, PathBuf},
};

const COPY_DIR: &'static str = "FolderToInclude";

/// A helper function for recursively copying a directory.
fn copy_dir<P, Q>(from: P, to: Q)
where
    P: AsRef<Path>,
    Q: AsRef<Path>,
{
    let to = to.as_ref().to_path_buf();

    for path in fs::read_dir(from).unwrap() {
        let path = path.unwrap().path();
        let to = to.clone().join(path.file_name().unwrap());

        if path.is_file() {
            fs::copy(&path, to).unwrap();
        } else if path.is_dir() {
            if !to.exists() {
                fs::create_dir(&to).unwrap();
            }

            copy_dir(&path, to);
        } else { /* Skip other content */
        }
    }
}

fn main() {
    // Request the output directory
    let out = env::var("PROFILE").unwrap();
    let out = PathBuf::from(format!("target/{}/{}", out, COPY_DIR));

    // If it is already in the output directory, delete it and start over
    if out.exists() {
        fs::remove_dir_all(&out).unwrap();
    }

    // Create the out directory
    fs::create_dir(&out).unwrap();

    // Copy the directory
    copy_dir(COPY_DIR, &out);
}
Run Code Online (Sandbox Code Playgroud)