Files
starship/src/modules/nodejs.rs
T

58 lines
1.9 KiB
Rust
Raw Normal View History

2019-04-10 09:22:11 -04:00
use super::Segment;
use ansi_term::{Color, Style};
use clap::ArgMatches;
2019-04-12 13:07:41 -04:00
use rayon::prelude::*;
2019-04-11 19:31:30 -04:00
use std::env;
use std::fs::{self, DirEntry};
use std::process::Command;
2019-04-10 09:22:11 -04:00
/// Creates a segment with the current Node.js version
2019-04-12 13:07:41 -04:00
///
2019-04-11 20:04:04 -04:00
/// Will display the Node.js version if any of the following criteria are met:
/// - Current directory contains a `.js` file
/// - Current directory contains a `node_modules` directory
/// - Current directory contains a `package.json` file
2019-04-11 19:31:30 -04:00
pub fn segment(_: &ArgMatches) -> Segment {
2019-04-11 20:04:04 -04:00
const NODE_CHAR: &str = "";
2019-04-10 09:22:11 -04:00
const SECTION_COLOR: Color = Color::Green;
2019-04-11 19:31:30 -04:00
let current_path = env::current_dir().expect("Unable to identify current directory");
2019-04-12 13:07:41 -04:00
let files = fs::read_dir(&current_path)
.unwrap()
.filter_map(Result::ok)
.collect::<Vec<DirEntry>>();
2019-04-11 19:31:30 -04:00
2019-04-11 20:04:04 -04:00
// Early return if there are no JS project files
2019-04-12 13:07:41 -04:00
let is_js_project = files.par_iter().any(has_js_files);
2019-04-11 20:04:04 -04:00
if !is_js_project {
2019-04-11 19:31:30 -04:00
return Segment::default();
}
2019-04-10 09:22:11 -04:00
let version = match Command::new("node").arg("--version").output() {
2019-04-11 19:31:30 -04:00
Ok(output) => String::from_utf8(output.stdout).unwrap().trim().to_string(),
Err(_) => {
2019-04-10 09:22:11 -04:00
return Segment::default();
}
};
Segment {
2019-04-11 20:04:04 -04:00
value: format!("{} {}", NODE_CHAR, version),
2019-04-10 09:22:11 -04:00
style: Style::from(SECTION_COLOR),
..Default::default()
}
}
2019-04-12 13:07:41 -04:00
fn has_js_files(dir_entry: &DirEntry) -> bool {
2019-04-11 20:04:04 -04:00
let is_js_file = |d: &DirEntry| -> bool {
d.path().is_file() && d.path().extension().unwrap_or_default() == "js"
};
let is_node_modules = |d: &DirEntry| -> bool {
2019-04-11 19:31:30 -04:00
d.path().is_dir() && d.path().file_name().unwrap_or_default() == "node_modules"
};
2019-04-11 20:04:04 -04:00
let is_package_json = |d: &DirEntry| -> bool {
2019-04-11 19:31:30 -04:00
d.path().is_file() && d.path().file_name().unwrap_or_default() == "package.json"
};
2019-04-12 13:07:41 -04:00
is_js_file(dir_entry) || is_node_modules(dir_entry) || is_package_json(dir_entry)
2019-04-11 19:31:30 -04:00
}