1
0
mirror of https://github.com/Llewellynvdm/starship.git synced 2024-11-10 15:20:55 +00:00

feat(nodejs): check node engines version in package.json (#1847)

* check node engines version in package.json

* fix code, following review.
This commit is contained in:
t-mangoe 2020-12-05 20:25:48 +09:00 committed by GitHub
parent 749245bda7
commit 89588a7391
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 109 additions and 4 deletions

23
Cargo.lock generated
View File

@ -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",

View File

@ -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"] }

View File

@ -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

View File

@ -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",
}
}
}

View File

@ -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<Module<'a>> {
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<Module<'a>> {
_ => 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<Module<'a>> {
Some(module)
}
fn get_engines_version(base_dir: &PathBuf) -> Option<String> {
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<String>) -> 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()
}
}