Created
February 1, 2023 19:41
-
-
Save ms747/bb98cb83d86c79e63f3f58a92f606e52 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// build.rs | |
use std::env; | |
use std::fs; | |
use std::path::Path; | |
fn main() { | |
let out_dir = env::var("OUT_DIR").unwrap(); | |
let dest_path = Path::new(&out_dir).join("routes.rs"); | |
let src_path = Path::new("src/pages"); | |
let mut routes = String::new(); | |
for entry in fs::read_dir(src_path).unwrap() { | |
let entry = entry.unwrap(); | |
let path = entry.path(); | |
if path.is_file() { | |
let file_name = path.file_stem().unwrap().to_str().unwrap(); | |
let route = format!("\"/{}\": \"{}\"", file_name, path.display()); | |
routes.push_str(&route); | |
routes.push_str(",\n"); | |
} | |
} | |
let contents = format!("pub const ROUTES: &str = {{\n{}\n}};\n", routes); | |
std::fs::write(dest_path, contents).unwrap(); | |
println!("cargo:rerun-if-changed=src/pages"); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
include!(concat!(env!("OUT_DIR"), "/routes.rs")); | |
// use the routes in your code | |
for route in ROUTES.iter() { | |
println!("{}", route); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment