1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//! traduki translation assets management toolkit

mod env;
mod key;
mod parser;
mod section;

pub(crate) use {key::Key, section::Section};

use std::{
    fs::{self, File},
    io::Write,
    path::{Path, PathBuf},
};

fn out_dir() -> PathBuf {
    let env_var = std::env::var("OUT_DIR");
    Path::new(env_var.as_ref().unwrap()).into()
}

fn asset_dir<S: Into<String>>(s: S) -> PathBuf {
    let s = s.into();
    println!("cargo:rerun-if-changed={}", s);
    Path::new(&s).into()
}

fn wrap_string(s: String) -> String {
    format!(r#"pub(crate) mod traduki {{ {} }}"#, s)
}

pub fn bootstrap<S: Into<String>>(assets: S) {
    let out = out_dir();
    let assets = asset_dir(assets);

    // Clear the previous codegen
    let _ = fs::remove_dir_all(&out);
    fs::create_dir_all(&out).expect("Write error: failed to create $OUT directory scaffold!");

    // Create a new file for translations
    let mut f = File::create(out.join("traduki.rs")).expect("Write error: Failed to create file");
    let parse_output = parser::handle_root(&assets)
        .expect("Write error: failed to read asset directory tree.  Do you have permissions?")
        .into_iter()
        .fold(String::new(), |prev, section| {
            format!("{}\n{}", prev, section.generate())
        });

    f.write_all(wrap_string(parse_output).as_bytes())
        .expect("Write error: failed to write generated translations file!");
}