Skip to content

Commit

Permalink
feat(nodejs): check node engines version in package.json (starship#1847)
Browse files Browse the repository at this point in the history
* check node engines version in package.json

* fix code, following review.
  • Loading branch information
t-mangoe authored and chipbuster committed Jan 14, 2021
1 parent ff862fa commit 4f11ef5
Show file tree
Hide file tree
Showing 5 changed files with 109 additions and 4 deletions.
23 changes: 21 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
Expand Down
1 change: 1 addition & 0 deletions docs/config/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 2 additions & 0 deletions src/configs/nodejs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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> {
Expand All @@ -17,6 +18,7 @@ impl<'a> RootModuleConfig<'a> for NodejsConfig<'a> {
symbol: "⬢ ",
style: "bold green",
disabled: false,
not_capable_style: "bold red",
}
}
}
84 changes: 83 additions & 1 deletion src/modules/nodejs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -31,14 +37,22 @@ 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 {
"symbol" => Some(config.symbol),
_ => 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 {
Expand All @@ -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<()> {
Expand Down Expand Up @@ -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()
}
}

0 comments on commit 4f11ef5

Please sign in to comment.