summaryrefslogtreecommitdiffstats
path: root/src/modules/nodejs.rs
blob: 180e143ff97d0c663ae31a58a1274d7f6dbae3f2 (plain)
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
use ansi_term::Color;
use std::process::Command;

use super::{Context, Module};

/// Creates a module with the current Node.js version
///
/// Will display the Node.js version if any of the following criteria are met:
///     - Current directory contains a `.js` file
///     - Current directory contains a `package.json` file
///     - Current directory contains a `node_modules` directory
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
    let is_js_project = context
        .new_scan_dir()
        .set_files(&["package.json"])
        .set_extensions(&["js"])
        .set_folders(&["node_modules"])
        .scan();

    if !is_js_project {
        return None;
    }

    match get_node_version() {
        Some(node_version) => {
            const NODE_CHAR: &str = "⬢ ";

            let mut module = context.new_module("nodejs");
            let module_style = module
                .config_value_style("style")
                .unwrap_or_else(|| Color::Green.bold());
            module.set_style(module_style);

            let formatted_version = node_version.trim();
            module.new_segment("symbol", NODE_CHAR);
            module.new_segment("version", formatted_version);

            Some(module)
        }
        None => None,
    }
}

fn get_node_version() -> Option<String> {
    match Command::new("node").arg("--version").output() {
        Ok(output) => Some(String::from_utf8(output.stdout).unwrap()),
        Err(_) => None,
    }
}