roguemacro
roguemacro

Reputation: 319

How do I include a folder in the building process?

I have this file structure:

myProject
|
└── FolderToInclude
|          |
|          └── somebatfile.bat
|
└── src
|    |
|    └── main.rs
|
└── target
       |
       └── debug
             |
             └── myProject.exe // and other stuff

Is it possible in rust to include a folder in the build directory? I want to end up with this file structure:

myProject
|
└── FolderToInclude
|          |
|          └── somebatfile.bat
|
└── src
|    |
|    └── main.rs
|
└── target
       |
       └── debug
             |
             └── myProject.exe // and other stuff
             |
             └── FolderToInclude
                       |
                       └── somebatfile.bat

Upvotes: 6

Views: 2744

Answers (1)

TrickyPR
TrickyPR

Reputation: 178

When cargo is compiling a project, it checks for a build script, which is just pure Rust. You can use this to wrangle C code or bundle assets. A number of helpful environment variables are available to this script. The following build.rs file should work for your use case:

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);
}

Upvotes: 5

Related Questions