rsw/template/
mod.rs

1//! rsw template
2
3use std::path::Path;
4
5use crate::utils::load_file_contents;
6
7// config
8pub static RSW_TOML: &[u8] = include_bytes!("rsw.toml");
9
10// crate
11pub static CARGO_TOML: &[u8] = include_bytes!("rsw_cargo.toml");
12pub static LIB_RS: &[u8] = include_bytes!("rsw_lib.rs");
13pub static README: &[u8] = include_bytes!("rsw_readme.md");
14
15#[derive(Debug, PartialEq)]
16pub struct Template {
17    pub cargo: Vec<u8>,
18    pub readme: Vec<u8>,
19    pub lib: Vec<u8>,
20}
21
22impl Template {
23    pub fn new<P: AsRef<Path>>(template_dir: P) -> Self {
24        // Creates a `Template` from the given `template_dir`.
25        // If a file is found in the template dir, it will override the default version.
26        let template_dir = template_dir.as_ref();
27        let mut template = Template::default();
28
29        // If the theme directory doesn't exist there's no point continuing...
30        if !template_dir.exists() || !template_dir.is_dir() {
31            return template;
32        }
33
34        // Check for individual files, if they exist copy them across
35        {
36            let files = vec![
37                (template_dir.join("Cargo.tmol"), &mut template.cargo),
38                (template_dir.join("README.md"), &mut template.readme),
39                (template_dir.join("src/lib.rs"), &mut template.lib),
40            ];
41
42            let load_with_warn = |filename: &Path, dest| {
43                if !filename.exists() {
44                    // Don't warn if the file doesn't exist.
45                    return false;
46                }
47                if let Err(e) = load_file_contents(filename, dest) {
48                    println!("Couldn't load custom file, {}: {}", filename.display(), e);
49                    false
50                } else {
51                    true
52                }
53            };
54
55            for (filename, dest) in files {
56                load_with_warn(&filename, dest);
57            }
58        }
59
60        template
61    }
62}
63
64impl Default for Template {
65    fn default() -> Template {
66        Template {
67            cargo: CARGO_TOML.to_owned(),
68            readme: README.to_owned(),
69            lib: LIB_RS.to_owned(),
70        }
71    }
72}