Skip to content

Commit 7a72ef5

Browse files
committed
feat: 优化格式化输出
1 parent 8a5bd7a commit 7a72ef5

11 files changed

Lines changed: 131 additions & 26 deletions

File tree

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ napi-derive = "2.12.2"
1313
serde_json = "1.0"
1414
jsonschema = "0.17"
1515
emojis = "0.6.0"
16+
console = "0.15.7"
1617

1718
[build-dependencies]
1819
napi-build = "2.0.1"

index.d.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@
66
export function validateConfig(configStr: string): void
77
export function validatePackage(appPath: string, nodeModulesPath: string, cliVersion: string): void
88
export function validateEnv(): void
9+
export function validateRecommend(appPath: string, nodeModulesPath: string): void

index.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,8 +252,9 @@ if (!nativeBinding) {
252252
throw new Error(`Failed to load native binding`)
253253
}
254254

255-
const { validateConfig, validatePackage, validateEnv } = nativeBinding
255+
const { validateConfig, validatePackage, validateEnv, validateRecommend } = nativeBinding
256256

257257
module.exports.validateConfig = validateConfig
258258
module.exports.validatePackage = validatePackage
259259
module.exports.validateEnv = validateEnv
260+
module.exports.validateRecommend = validateRecommend

src/lib.rs

Lines changed: 39 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ mod validators;
44

55
use std::{ fs, error::Error, path::PathBuf, env };
66

7-
use validators::env::EnvValidator;
7+
use validators::{env::EnvValidator, Recommend::RecommendValidator};
88

99
use crate::validators::{ message::{ Message, self }, package::{ PackageValidator }, config::ConfigValidator, common::{ Validator } };
1010

@@ -15,30 +15,39 @@ extern crate napi_derive;
1515
pub fn validate_config(config_str: String) {
1616
let result = validate_config_core(config_str);
1717
if let Err(e) = result {
18-
println!("{}", Message { kind: message::MessageKind::Error, content: e.to_string() });
18+
println!("{}", Message { kind: message::MessageKind::Error, content: e.to_string(), solution: None });
1919
}
2020
}
2121

2222
#[napi]
2323
pub fn validate_package(app_path: String, node_modules_path: String, cli_version: String) {
2424
let result = validate_package_core(app_path, node_modules_path, cli_version);
2525
if let Err(e) = result {
26-
println!("{}", Message { kind: message::MessageKind::Error, content: e.to_string() });
26+
println!("{}", Message { kind: message::MessageKind::Error, content: e.to_string(), solution: None });
2727
}
2828
}
2929

3030
#[napi]
3131
pub fn validate_env() {
3232
let result = validate_env_core();
3333
if let Err(e) = result {
34-
println!("{}", Message { kind: message::MessageKind::Error, content: e.to_string() });
34+
println!("{}", Message { kind: message::MessageKind::Error, content: e.to_string(), solution: None });
35+
}
36+
}
37+
38+
#[napi]
39+
pub fn validate_recommend(app_path: String, node_modules_path: String) {
40+
let result = validate_recommend_core(app_path, node_modules_path);
41+
if let Err(e) = result {
42+
println!("{}", Message { kind: message::MessageKind::Error, content: e.to_string(), solution: None });
3543
}
3644
}
3745

3846
fn validate_config_core(config_str: String) -> Result<(), Box<dyn Error>> {
3947
let tip = Message {
4048
kind: validators::message::MessageKind::Info,
41-
content: String::from("开始进行项目配置验证!")
49+
content: String::from("开始进行项目配置验证!"),
50+
solution: None
4251
};
4352
println!("{}", tip);
4453
let current_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
@@ -55,7 +64,8 @@ fn validate_config_core(config_str: String) -> Result<(), Box<dyn Error>> {
5564
Err(e) => vec![
5665
Message {
5766
kind: validators::message::MessageKind::Error,
58-
content: e.to_string()
67+
content: e.to_string(),
68+
solution: None
5969
}
6070
]
6171
};
@@ -64,15 +74,16 @@ fn validate_config_core(config_str: String) -> Result<(), Box<dyn Error>> {
6474
println!("{}", message);
6575
}
6676
} else {
67-
println!("{}", Message { kind: message::MessageKind::Success, content: "项目配置正确!".to_string() });
77+
println!("{}", Message { kind: message::MessageKind::Success, content: "项目配置正确!".to_string(), solution: None });
6878
}
6979
Ok(())
7080
}
7181

7282
fn validate_package_core(app_path: String, node_modules_path: String, cli_version: String) -> Result<(), Box<dyn Error>> {
7383
let tip = Message {
7484
kind: validators::message::MessageKind::Info,
75-
content: String::from("开始进行项目依赖安装正确性验证!")
85+
content: String::from("开始进行项目依赖安装正确性验证!"),
86+
solution: None
7687
};
7788
println!("{}", tip);
7889
let mut path = PathBuf::new();
@@ -85,7 +96,8 @@ fn validate_package_core(app_path: String, node_modules_path: String, cli_versio
8596
Err(e) => vec![
8697
Message {
8798
kind: validators::message::MessageKind::Error,
88-
content: e.to_string()
99+
content: e.to_string(),
100+
solution: None
89101
}
90102
]
91103
};
@@ -103,3 +115,21 @@ fn validate_env_core() -> Result<(), Box<dyn Error>> {
103115
}
104116
Ok(())
105117
}
118+
119+
fn validate_recommend_core(app_path: String, node_modules_path: String) -> Result<(), Box<dyn Error>> {
120+
let recommend_validator_result = RecommendValidator::build(&app_path, &node_modules_path);
121+
let messages = match recommend_validator_result {
122+
Ok(recommend_validator) => recommend_validator.validate(),
123+
Err(e) => vec![
124+
Message {
125+
kind: validators::message::MessageKind::Error,
126+
content: e.to_string(),
127+
solution: None
128+
}
129+
]
130+
};
131+
for message in messages {
132+
println!("{}", message);
133+
}
134+
Ok(())
135+
}

src/validators/common.rs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ pub trait Validator {
1111
pub struct PackageInfo {
1212
pub name: String,
1313
pub version: String,
14+
pub json: Value,
1415
}
1516

1617
pub fn get_package_info(node_modules_path: &str, name: &str) -> Result<PackageInfo, Box<dyn Error>> {
@@ -30,14 +31,21 @@ pub fn get_package_info(node_modules_path: &str, name: &str) -> Result<PackageIn
3031
let package_json_re = from_str::<Value>(&package_str);
3132
match package_json_re {
3233
Ok(package_json) => {
33-
Ok(PackageInfo { name: name.to_string(), version: package_json.get("version").unwrap().as_str().unwrap().to_string() })
34+
Ok(
35+
PackageInfo {
36+
name: name.to_string(),
37+
version: package_json.get("version").unwrap().as_str().unwrap().to_string(),
38+
json: package_json
39+
}
40+
)
3441
},
3542
Err(e) => {
3643
Err(
3744
Box::new(
3845
Message {
3946
kind: MessageKind::Error,
40-
content: e.to_string()
47+
content: e.to_string(),
48+
solution: None
4149
}
4250
)
4351
)

src/validators/config.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -168,13 +168,14 @@ impl Validator for ConfigValidator {
168168
// })
169169
errors_result.push(Message {
170170
kind: MessageKind::Error,
171-
content: self.parse_error(error)
171+
content: self.parse_error(error),
172+
solution: None
172173
});
173174
}
174175
}
175176
}
176177
Err(error) => {
177-
errors_result.push(Message { kind: MessageKind::Error, content: self.parse_error(error) });
178+
errors_result.push(Message { kind: MessageKind::Error, content: self.parse_error(error), solution: None });
178179
},
179180
}
180181

src/validators/env.rs

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,31 +27,36 @@ impl Validator for EnvValidator {
2727
if ordering == Ordering::Greater || ordering == Ordering::Equal {
2828
Message {
2929
kind: MessageKind::Success,
30-
content: format!("安装的 Node 版本为 {}", version)
30+
content: format!("安装的 Node 版本为 {}", version),
31+
solution: None
3132
}
3233
} else {
3334
Message {
3435
kind: MessageKind::Error,
35-
content: format!("安装的 Node 版本为 {},小于最低要求 Node 版本 14.0.0,请安装正确的 Node 版本,推荐使用 nvm(https://github.com/nvm-sh/nvm) 来管理 Node 版本", version)
36+
content: format!("安装的 Node 版本为 {},小于最低要求 Node 版本 14.0.0", version),
37+
solution: Some("请安装正确的 Node 版本,推荐使用 nvm(https://github.com/nvm-sh/nvm) 来管理 Node 版本".to_string())
3638
}
3739
}
3840
} else {
3941
Message {
4042
kind: MessageKind::Success,
41-
content: format!("安装的 Node 版本为 {}", version)
43+
content: format!("安装的 Node 版本为 {}", version),
44+
solution: None
4245
}
4346
}
4447
} else {
4548
Message {
4649
kind: MessageKind::Error,
47-
content: format!("获取 Node 版本失败,请查看是否正确安装 Node")
50+
content: format!("获取 Node 版本失败,请查看是否正确安装 Node"),
51+
solution: Some("推荐使用 nvm(https://github.com/nvm-sh/nvm) 来管理 Node 版本".to_string())
4852
}
4953
}
5054
},
5155
Err(_) => {
5256
Message {
5357
kind: MessageKind::Error,
54-
content: format!("获取 Node 版本失败,请查看是否正确安装 Node")
58+
content: format!("获取 Node 版本失败,请查看是否正确安装 Node"),
59+
solution: Some("推荐使用 nvm(https://github.com/nvm-sh/nvm) 来管理 Node 版本".to_string())
5560
}
5661
}
5762
};

src/validators/message.rs

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,45 @@
11
use std::{fmt, error::Error};
22

3+
use console::{style};
4+
35
#[derive(Debug)]
46
pub enum MessageKind {
57
Info,
68
Error,
79
Success,
10+
Warning,
811
Manual
912
}
1013

1114
#[derive(Debug)]
1215
pub struct Message {
1316
pub kind: MessageKind,
1417
pub content: String,
18+
pub solution: Option<String>,
1519
}
1620

1721
impl fmt::Display for Message {
1822
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1923
match &self.kind {
2024
MessageKind::Error => {
21-
write!(f, "{} {}", emojis::get("❌").unwrap(), self.content)
25+
if let Some(solution) = &self.solution {
26+
write!(f, "{} {} {}", style("[✗] ").red(), style(&self.content).white(), style(solution).color256(246))
27+
} else {
28+
write!(f, "{} {}", style("[✗] ").red(), style(&self.content).white())
29+
}
2230
},
2331
MessageKind::Info => {
24-
write!(f, "{} {}", emojis::get("🎯").unwrap(), self.content)
32+
write!(f, "{} {}", emojis::get("🎯").unwrap(), style(&self.content).color256(248).bold())
2533
},
2634
MessageKind::Success => {
27-
write!(f, "{} {}", emojis::get("✅").unwrap(), self.content)
35+
write!(f, "{} {}", style("[✓] ").green(), style(&self.content).white())
36+
},
37+
MessageKind::Warning => {
38+
if let Some(solution) = &self.solution {
39+
write!(f, "{} {} {}", style("[!] ").yellow(), style(&self.content).white(), style(solution).color256(246))
40+
} else {
41+
write!(f, "{} {}", style("[!] ").yellow(), style(&self.content).white())
42+
}
2843
},
2944
MessageKind::Manual => {
3045
write!(f, "{}", self.content)

src/validators/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,4 @@ pub(crate) mod message;
33
pub(crate) mod common;
44
pub(crate) mod package;
55
pub(crate) mod env;
6+
pub(crate) mod Recommend;

src/validators/package.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -103,19 +103,19 @@ impl<'a> Validator for PackageValidator<'a> {
103103
fn validate(&self) -> Vec<Message> {
104104
let mut messages: Vec<Message> = vec![];
105105
let taro_packages = self.get_taro_packages();
106-
messages.push(Message { kind: MessageKind::Manual, content: "本地安装的 Taro 相关依赖版本信息如下:".to_string() });
106+
messages.push(Message { kind: MessageKind::Manual, content: "本地安装的 Taro 相关依赖版本信息如下:".to_string(), solution: None });
107107
let cli_version = self.cli_version;
108108
for p in taro_packages {
109109
let package_info = get_package_info(self.node_modules_path, p);
110110
match package_info {
111111
Ok(info) => {
112-
messages.push(Message { kind: MessageKind::Manual, content: format!("- {}: {}", info.name, info.version) });
112+
messages.push(Message { kind: MessageKind::Manual, content: format!("- {}: {}", info.name, info.version), solution: None });
113113
if UPDATE_PACKAGE_LIST.contains(&p.as_str()) && cli_version != info.version {
114-
messages.push(Message { kind: MessageKind::Error, content: format!("依赖 {} ({}) 与当前使用的 Taro CLI ({}) 版本不一致, 请更新为统一的版本", p, info.version, cli_version) });
114+
messages.push(Message { kind: MessageKind::Error, content: format!("依赖 {} ({}) 与当前使用的 Taro CLI ({}) 版本不一致, 请更新为统一的版本", p, info.version, cli_version), solution: None });
115115
}
116116
},
117117
Err(_) => {
118-
messages.push(Message { kind: MessageKind::Error, content: format!("请安装 Taro 依赖: {}", p) });
118+
messages.push(Message { kind: MessageKind::Error, content: format!("请安装 Taro 依赖: {}", p), solution: None });
119119
}
120120
}
121121
}

0 commit comments

Comments
 (0)