From 4f11ef54c336146222e40274a15bc4cd4715f540 Mon Sep 17 00:00:00 2001 From: t-mangoe Date: Sat, 5 Dec 2020 20:25:48 +0900 Subject: [PATCH] feat(nodejs): check node engines version in package.json (#1847) * check node engines version in package.json * fix code, following review. --- Cargo.lock | 23 ++++++++++-- Cargo.toml | 3 +- docs/config/README.md | 1 + src/configs/nodejs.rs | 2 ++ src/modules/nodejs.rs | 84 ++++++++++++++++++++++++++++++++++++++++++- 5 files changed, 109 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2eba19b57459e..e253b431c7915 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -921,9 +921,9 @@ dependencies = [ [[package]] name = "quick-xml" -version = "0.20.0" +version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26aab6b48e2590e4a64d1ed808749ba06257882b461d01ca71baeb747074a6dd" +checksum = "b3d72d5477478f85bd00b6521780dfba1ec6cdaadcf90b8b181c36d7de561f9b" dependencies = [ "memchr", ] @@ -1120,6 +1120,24 @@ dependencies = [ "libc", ] +[[package]] +name = "semver" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f301af10236f6df4160f7c3f04eec6dbc70ace82d23326abad5edee88801c6b6" +dependencies = [ + "semver-parser", +] + +[[package]] +name = "semver-parser" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42ef146c2ad5e5f4b037cd6ce2ebb775401729b19a82040c1beac9d36c7d1428" +dependencies = [ + "pest", +] + [[package]] name = "serde" version = "1.0.117" @@ -1210,6 +1228,7 @@ dependencies = [ "rayon", "regex", "rust-ini", + "semver", "serde", "serde_json", "shell-words", diff --git a/Cargo.toml b/Cargo.toml index a61359de7d9a7..1453ba69dbca4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -57,11 +57,12 @@ urlencoding = "1.1.1" open = "1.4.0" unicode-width = "0.1.8" term_size = "0.3.2" -quick-xml = "0.20.0" +quick-xml = "0.19.0" rand = "0.7.3" serde = { version = "1.0.117", features = ["derive"] } indexmap = "1.6.0" notify-rust = { version = "4.0.0", optional = true } +semver = "0.11.0" # Optional/http: attohttpc = { version = "0.16.0", optional = true, default-features = false, features = ["tls", "form"] } diff --git a/docs/config/README.md b/docs/config/README.md index d5d8b44f1c860..77e11176cabc0 100644 --- a/docs/config/README.md +++ b/docs/config/README.md @@ -1727,6 +1727,7 @@ The module will be shown if any of the following conditions are met: | `symbol` | `"⬢ "` | A format string representing the symbol of NodeJS. | | `style` | `"bold green"` | The style for the module. | | `disabled` | `false` | Disables the `nodejs` module. | +| `not_capable_style` | `bold red` | The style for the module when an engines property in Packages.json does not match the NodeJS version. | ### Variables diff --git a/src/configs/nodejs.rs b/src/configs/nodejs.rs index 355e2ff187934..2867d535ad26d 100644 --- a/src/configs/nodejs.rs +++ b/src/configs/nodejs.rs @@ -8,6 +8,7 @@ pub struct NodejsConfig<'a> { pub symbol: &'a str, pub style: &'a str, pub disabled: bool, + pub not_capable_style: &'a str, } impl<'a> RootModuleConfig<'a> for NodejsConfig<'a> { @@ -17,6 +18,7 @@ impl<'a> RootModuleConfig<'a> for NodejsConfig<'a> { symbol: "⬢ ", style: "bold green", disabled: false, + not_capable_style: "bold red", } } } diff --git a/src/modules/nodejs.rs b/src/modules/nodejs.rs index 1a3d087be75fd..7c5c1302695de 100644 --- a/src/modules/nodejs.rs +++ b/src/modules/nodejs.rs @@ -4,6 +4,12 @@ use crate::configs::nodejs::NodejsConfig; use crate::formatter::StringFormatter; use crate::utils; +use regex::Regex; +use semver::Version; +use semver::VersionReq; +use serde_json as json; +use std::path::PathBuf; + /// Creates a module with the current Node.js version /// /// Will display the Node.js version if any of the following criteria are met: @@ -31,6 +37,8 @@ pub fn module<'a>(context: &'a Context) -> Option> { let mut module = context.new_module("nodejs"); let config = NodejsConfig::try_load(module.config); let nodejs_version = utils::exec_cmd("node", &["--version"])?.stdout; + let engines_version = get_engines_version(&context.current_dir); + let in_engines_range = check_engines_version(&nodejs_version, engines_version); let parsed = StringFormatter::new(config.format).and_then(|formatter| { formatter .map_meta(|var, _| match var { @@ -38,7 +46,13 @@ pub fn module<'a>(context: &'a Context) -> Option> { _ => None, }) .map_style(|variable| match variable { - "style" => Some(Ok(config.style)), + "style" => { + if in_engines_range { + Some(Ok(config.style)) + } else { + Some(Ok(config.not_capable_style)) + } + } _ => None, }) .map(|variable| match variable { @@ -59,12 +73,42 @@ pub fn module<'a>(context: &'a Context) -> Option> { Some(module) } +fn get_engines_version(base_dir: &PathBuf) -> Option { + let json_str = utils::read_file(base_dir.join("package.json")).ok()?; + let package_json: json::Value = json::from_str(&json_str).ok()?; + let raw_version = package_json.get("engines")?.get("node")?.as_str()?; + Some(raw_version.to_string()) +} + +fn check_engines_version(nodejs_version: &str, engines_version: Option) -> bool { + if engines_version.is_none() { + return true; + } + let r = match VersionReq::parse(&engines_version.unwrap()) { + Ok(r) => r, + Err(_e) => return true, + }; + let re = Regex::new(r"\d+\.\d+\.\d+").unwrap(); + let version = re + .captures(nodejs_version) + .unwrap() + .get(0) + .unwrap() + .as_str(); + let v = match Version::parse(version) { + Ok(v) => v, + Err(_e) => return true, + }; + r.matches(&v) +} + #[cfg(test)] mod tests { use crate::test::ModuleRenderer; use ansi_term::Color; use std::fs::{self, File}; use std::io; + use std::io::Write; #[test] fn folder_without_node_files() -> io::Result<()> { @@ -165,4 +209,42 @@ mod tests { assert_eq!(expected, actual); dir.close() } + + #[test] + fn engines_node_version_match() -> io::Result<()> { + let dir = tempfile::tempdir()?; + let mut file = File::create(dir.path().join("package.json"))?; + file.write_all( + b"{ + \"engines\":{ + \"node\":\">=12.0.0\" + } + }", + )?; + file.sync_all()?; + + let actual = ModuleRenderer::new("nodejs").path(dir.path()).collect(); + let expected = Some(format!("via {} ", Color::Green.bold().paint("⬢ v12.0.0"))); + assert_eq!(expected, actual); + dir.close() + } + + #[test] + fn engines_node_version_not_match() -> io::Result<()> { + let dir = tempfile::tempdir()?; + let mut file = File::create(dir.path().join("package.json"))?; + file.write_all( + b"{ + \"engines\":{ + \"node\":\"<12.0.0\" + } + }", + )?; + file.sync_all()?; + + let actual = ModuleRenderer::new("nodejs").path(dir.path()).collect(); + let expected = Some(format!("via {} ", Color::Red.bold().paint("⬢ v12.0.0"))); + assert_eq!(expected, actual); + dir.close() + } }