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
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
use anyhow::Result;
use regex::Regex;
use std::io::{Read, Write};
use std::{
    env,
    fs::{self, File},
    path::Path,
};
use toml::Value;

use crate::config;
use crate::core::RswErr;

// https://stackoverflow.com/questions/35045996/check-if-a-command-is-in-path-executable-as-process
pub fn check_env_cmd(program: &str) -> bool {
    if let Ok(path) = env::var("PATH") {
        for p in path.split(":") {
            let p_str = format!("{}/{}", p, program);
            if fs::metadata(p_str).is_ok() {
                return true;
            }
        }
    }
    false
}

// get fields from `Cargo.toml`
pub fn get_crate_metadata(name: &str) -> Value {
    let crate_root = env::current_dir().unwrap().join(name).join("Cargo.toml");
    let content = fs::read_to_string(crate_root).unwrap_or_else(|e| {
        // TODO: create crate
        print(RswErr::Crate(name.to_string(), e));
        std::process::exit(1);
    });
    let value = content.parse::<Value>().unwrap();
    value
}

pub fn path_exists(path: &Path) -> bool {
    fs::metadata(path).is_ok()
}

// https://docs.npmjs.com/creating-a-package-json-file#required-name-and-version-fields
pub fn get_pkg(name: &str) -> (String, String) {
    // example: @rsw/test | rsw-test | wasm123
    let re = Regex::new(r"(?x)(@([\w\d_-]+)/)?((?P<pkg_name>[\w\d_-]+))").unwrap();
    let caps = re.captures(name).unwrap();
    let mut scope = "".into();
    if caps.get(2) != None {
        scope = caps.get(2).unwrap().as_str().into();
    }

    (caps["pkg_name"].to_owned(), scope)
}

// Checks if a file exists, if so, the destination buffer will be filled with
// its contents.
pub fn load_file_contents<P: AsRef<Path>>(filename: P, dest: &mut Vec<u8>) -> Result<()> {
    let filename = filename.as_ref();

    let mut buffer = Vec::new();
    File::open(filename)?.read_to_end(&mut buffer)?;

    // We needed the buffer so we'd only overwrite the existing content if we
    // could successfully load the file into memory.
    dest.clear();
    dest.append(&mut buffer);

    Ok(())
}

// @see: https://github.com/rust-lang/mdBook/blob/2213312938/src/utils/fs.rs#L61-L72
// This function creates a file and returns it. But before creating the file
// it checks every directory in the path to see if it exists,
// and if it does not it will be created.
pub fn create_file(path: &Path) -> Result<File> {
    debug!("Creating {}", path.display());

    // Construct path
    if let Some(p) = path.parent() {
        trace!("Parent directory is: {:?}", p);

        fs::create_dir_all(p)?;
    }

    File::create(path).map_err(Into::into)
}

// @see: https://github.com/rust-lang/mdBook/blob/2213312938/src/utils/fs.rs#L16-L20
// Write the given data to a file, creating it first if necessary
pub fn write_file<P: AsRef<Path>>(build_dir: &Path, filename: P, content: &[u8]) -> Result<()> {
    let path = build_dir.join(filename);
    create_file(&path)?.write_all(content).map_err(Into::into)
}

// recursive copy folder
pub fn copy_dirs(source: impl AsRef<Path>, target: impl AsRef<Path>) -> std::io::Result<()> {
    fs::create_dir_all(&target)?;
    for entry in fs::read_dir(source)? {
        let entry = entry?;
        let entry_target = target.as_ref().join(entry.file_name());
        trace!(
            "Copy {} to {}",
            entry.path().display(),
            entry_target.display()
        );
        if entry.file_type()?.is_dir() {
            copy_dirs(entry.path(), entry_target)?;
        } else {
            fs::copy(entry.path(), entry_target)?;
        }
    }
    Ok(())
}

// rsw log
pub fn init_logger() {
    use colored::Colorize;
    use env_logger::Builder;
    use log::Level;
    use log::LevelFilter;

    let mut builder = Builder::new();

    builder.format(|formatter, record| {
        let level = record.level().as_str();
        let log_level = match record.level() {
            Level::Info => level.blue(),
            Level::Debug => level.magenta(),
            Level::Trace => level.green(),
            Level::Error => level.red(),
            Level::Warn => level.yellow(),
        };

        let log_target = match record.level() {
            Level::Info | Level::Error => format!(""),
            _ => format!(" {}", record.target().yellow()),
        };

        let rsw_log = format!("[rsw::{}]", log_level);
        writeln!(
            formatter,
            "{}{} {}",
            rsw_log.bold().on_black(),
            log_target,
            record.args()
        )
    });

    if let Ok(var) = env::var("RUST_LOG") {
        builder.parse_filters(&var);
    } else {
        // if no RUST_LOG provided, default to logging at the Info level
        builder.filter(None, LevelFilter::Info);
    }

    builder.init();
}

pub fn print<T: std::fmt::Display>(a: T) {
    println!("{}", a)
}

pub fn rsw_watch_file(content: &[u8]) -> Result<()> {
    let rsw_file = std::env::current_dir()
        .unwrap()
        .join(config::RSW_WATCH_FILE);
    if !path_exists(rsw_file.as_path()) {
        File::create(&rsw_file)?;
    }
    fs::write(rsw_file, content)?;
    Ok(())
}

#[cfg(test)]
mod pkg_name_tests {
    use super::*;

    #[test]
    fn pkg_word() {
        assert_eq!(get_pkg("@rsw/test".into()), ("test".into(), "rsw".into()));
    }

    #[test]
    fn pkg_word_num() {
        assert_eq!(get_pkg("wasm123".into()), ("wasm123".into(), "".into()));
    }

    #[test]
    fn pkg_word_num_line() {
        assert_eq!(
            get_pkg("@rsw-org/my_wasm".into()),
            ("my_wasm".into(), "rsw-org".into())
        );
    }
}