home ~ projects ~ socials

Load A Directory Of Static Files Into Rust

This is how I'm pulling in static files from a directory into Rust binaries.

---
[dependencies]
include_dir = { version = "0.7.4", features = ["glob"] }
---

use include_dir::{include_dir, Dir};

static INCLUDES_DIR: Dir<'_> = include_dir!("include_dir_tests");

fn main() {
    let glob = "*.txt";
    for entry in INCLUDES_DIR.find(glob).unwrap() {
        if let Some(file) = entry.as_file() {
            if let Some(contents) = file.contents_utf8() {
                println!("FILE:\n{}\n", entry.path().display());
                println!("CONTENTS:\n{}\n\n", contents);
            }
        }
    }
}
Output:
FILE:
2.txt

CONTENTS:
this is a second test file


FILE:
1.txt

CONTENTS:
this is a test file

Notes

  • The documentation says:

    When invoking the include_dir!() macro you should try to avoid using relative paths because rustc makes no guarantees about u the current directory when it is running a procedural macro.

    I haven't had problem with that yet.

-- end of line --

References