Using Build.rs to inject build-time data to Web Assembly in Yew (OMR #2)
Tags: webdev, rust, webassembly
Published: 2023-03-23 18:45:31


This is part 2 of an ongoing series, in which we build in public an Online Manga Reader (OMR) with unique features such as instant loading, thumbnail preview, rotation, dual page and cinema mode using Rust and Yew. 

You can [grab the repo here](https://github.com/superjose/rust-online-manga-reader).

Read all of the posts [here](https://dev.to/superjose/building-a-revolutionary-online-manga-reader-from-scratch-using-yew-and-rust-introduction-1ieb).

## The Problem:
As I'm currently reading the chapters from the file system, I  need a way to automatically count the available chapters and the number of pages each chapter has.

Unfortunately, you can't read from the filesystem in Yew. 



## Solution:
We need to generate a rust file that can be consumed.

[We can achieve that using Rust's built-in build scripts.](https://doc.rust-lang.org/cargo/reference/build-scripts.html) 


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sqc98bfy1wrt554zt2i5.png)



## Full Code below:

```rust
//<root>/build.rs (NOT <root>/src/build.rs)
use std::{collections::HashMap, fs};

/**
 * Recreates a HashMap<i16, i8> that from the directory structure of the manga
 * that is consumed by the state.rs
 */
fn main() {
    println!("cargo:rerun-if-changed=build.rs");
    let out_dir = "./src/";

    let mut chapter_state: HashMap<i16, i8> = HashMap::new();

    let dir_path = "./src/assets/manga/one_piece"; // replace with your directory path

    let manga_folders = fs::read_dir(dir_path).expect("Failed to read directory");

    for read in manga_folders {
        let entry = match read {
            Err(_) => continue,
            Ok(e) => e,
        };

        if !entry.path().is_dir() {
            continue;
        }

        if let Some(folder_name) = entry.path().file_name().and_then(|n| n.to_str()) {
            if let Ok(folder_num) = folder_name.parse::<i16>() {
                let count = fs::read_dir(entry.path())
                    .expect("Failed to read directory")
                    .count() as i8;

                chapter_state.insert(folder_num, count);
            }
        }
    }

    let mut sorted_manga_folders: Vec<(i16, i8)> = chapter_state.into_iter().collect();
    sorted_manga_folders.sort_by_key(|&(chapter, _)| -chapter);

    let mut chapter_concat: String = "[".to_owned();
    for (index, (chapter, page)) in sorted_manga_folders.iter().enumerate() {
        let comma_suffix = if index == sorted_manga_folders.len() - 1 {
            ""
        } else {
            ","
        };
        chapter_concat.push_str(&format!("({}, {}){}", chapter, page, comma_suffix));
    }

    chapter_concat.push_str("]");

    println!("cargo:warning={:?}", &chapter_concat);

    let chapter_map_rs = format!(
        "
        // Automatically generated - see build.rs
        // Do not modify manually!

        use std::collections::HashMap;
        pub fn get_chapters() -> HashMap<i16, i8> {{
        let chapter_state: HashMap<i16, i8> = HashMap::from({});
            chapter_state
        }}
    
    ",
        chapter_concat
    );

    let dest_path = format!("{}/chapter_map.rs", out_dir);
    fs::write(&dest_path, chapter_map_rs).unwrap();
}
```

1. We create a `build.rs` file in the root directory. 

2. We use a special `println!` macro that instructs rust to only run `build.rs` if the file has changed.

3. The `out_dir` variable instructs Rust to send our file to the `src` folder so we can consume it later. 

4. We then iterate over the `/src/assets/one_piece` folder to create a HashMap with the number of the chapter as the key and the number of pages as the value. 

5. We then create a string that will serve as the content of the rust file. This is then generated to /src/chapter_map.rs with the following contents:

```rs

        // Automatically generated - see build.rs
        // Do not modify manually!

        use std::collections::HashMap;
        pub fn get_chapters() -> HashMap<i16, i8> {
        let chapter_state: HashMap<i16, i8> = HashMap::from([(1047, 20),(1046, 17),(1045, 20),(1044, 17),(1043, 17),(1042, 17)]);
            chapter_state
        }
    
    
```

Note, that this content will depend on whether you have your assets placed inside. 

6. You then need to make the `chapter_map.rs` file available in `main.rs` file in order for you to import it on your file.



## Follow me on other social media

I post regularly on:

    LinkedIn - https://linkedin.com/in/javiasilis
    Twitter - https://twitter.com/javiasilis

Feel free to connect with me there!