Skip to content

Commit 2fcc07b

Browse files
committed
better error message
1 parent dee0af9 commit 2fcc07b

File tree

10 files changed

+60
-78
lines changed

10 files changed

+60
-78
lines changed

.vscode/settings.json

+1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
"crossterm",
1616
"dialoguer",
1717
"flate",
18+
"fmtln",
1819
"hasher",
1920
"indicatif",
2021
"outpath",

crates/snm_download_builder/src/lib.rs

+4-12
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use colored::*;
22
use futures_util::StreamExt;
33
use indicatif::{ProgressBar, ProgressDrawTarget};
4-
use reqwest::{Client, StatusCode};
4+
use reqwest::Client;
55
use snm_utils::snm_error::SnmError;
66
use std::path::Path;
77
use std::time::Duration;
@@ -50,12 +50,6 @@ impl DownloadBuilder {
5050
download_url: &str,
5151
abs_path: P,
5252
) -> Result<P, SnmError> {
53-
// let response = Client::new().head(download_url).send().await?;
54-
55-
// if response.status() == StatusCode::NOT_FOUND {
56-
// return Err(SnmError::NotFoundResourceError(download_url.to_string()));
57-
// }
58-
5953
let mut attempts = 0;
6054

6155
while attempts < (self.retries + 1) {
@@ -91,7 +85,9 @@ impl DownloadBuilder {
9185
if abs_path_ref.exists() {
9286
match self.write_strategy {
9387
WriteStrategy::Error => {
94-
return Err(SnmError::FileAlreadyExists(abs_path_ref.to_path_buf()));
88+
return Err(SnmError::FileAlreadyExists {
89+
file_path: abs_path_ref.to_path_buf(),
90+
});
9591
}
9692
WriteStrategy::WriteAfterDelete => {
9793
std::fs::remove_file(&abs_path_ref)?;
@@ -113,10 +109,6 @@ impl DownloadBuilder {
113109
.send()
114110
.await?;
115111

116-
if response.status() == StatusCode::NOT_FOUND {
117-
return Err(SnmError::NotFoundResourceError(download_url.to_string()));
118-
}
119-
120112
if !response.status().is_success() {
121113
return Err(SnmError::HttpStatusCodeUnOk);
122114
}

crates/snm_package_json/src/package_json.rs

+3-5
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use std::{collections::HashMap, fs::File, io::BufReader, ops::Not, path::PathBuf
22

33
use regex::{Match, Regex};
44
use serde::Deserialize;
5-
use snm_utils::snm_error::SnmError;
5+
use snm_utils::{constant::PACKAGE_MANAGER, snm_error::SnmError};
66

77
use crate::{
88
package_manager_meta::{PackageManager, PackageManagerDownloadHash},
@@ -107,13 +107,11 @@ fn parse_package_manager(raw_package_manager: &str) -> Result<Option<PackageMana
107107
raw_package_manager: raw_package_manager.to_string(),
108108
})?;
109109

110-
let package_manager_vec = vec!["pnpm", "yarn", "npm"];
111-
112-
if package_manager_vec.contains(&name.as_str()).not() {
110+
if PACKAGE_MANAGER.contains(&name.as_str()).not() {
113111
return Err(SnmError::UnsupportedPackageManagerError {
114112
name: name.to_string(),
115113
raw: raw_package_manager.to_string(),
116-
supported: package_manager_vec.iter().map(|s| s.to_string()).collect(),
114+
supported: PACKAGE_MANAGER.iter().map(|s| s.to_string()).collect(),
117115
});
118116
}
119117

crates/snm_shim/src/get_node_bin_dir.rs

-3
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ use tracing::{instrument, Level};
99
#[instrument(level = Level::TRACE, ret)]
1010
pub async fn get_node_bin_dir() -> Result<String, SnmError> {
1111
let dir = current_dir()?;
12-
1312
let snm_config = parse_snm_config(&dir)?;
1413

1514
let snm_node = NodeAtom::new(snm_config.clone());
@@ -83,7 +82,5 @@ pub async fn get_node_bin_dir() -> Result<String, SnmError> {
8382
}
8483
let binary = snm_node.get_runtime_binary_dir_string(version.as_str())?;
8584

86-
// let binary_dir_string = ensure_binary_path(&snm_node, &version).await?;
87-
8885
Ok(binary)
8986
}

crates/snm_shim/src/package_manager_shim.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use std::{
88
use snm_atom::{atom::AtomTrait as _, package_manager_atom::PackageManagerAtom};
99
use snm_config::parse_snm_config;
1010
use snm_download_builder::{DownloadBuilder, WriteStrategy};
11-
use snm_utils::{exec::exec_cli, snm_error::SnmError};
11+
use snm_utils::{constant::RESTRICTED_LIST, exec::exec_cli, snm_error::SnmError};
1212

1313
use crate::get_node_bin_dir::get_node_bin_dir;
1414

@@ -31,8 +31,6 @@ pub async fn package_manager(prefix: &str, bin_name: &str) -> Result<(), SnmErro
3131

3232
let snm_package_manage = PackageManagerAtom::new(prefix, snm_config.clone());
3333

34-
let restricted_list = vec!["install", "i", "run"];
35-
3634
let bin_dirs = if let Some(package_manager) = snm_config.get_runtime_package_manager() {
3735
tracing::trace!(
3836
"There is a package manager in the entry process that is currently in use."
@@ -74,7 +72,7 @@ pub async fn package_manager(prefix: &str, bin_name: &str) -> Result<(), SnmErro
7472
let binary = snm_package_manage.get_runtime_binary_dir_string(version.as_str())?;
7573

7674
vec![node_dir.clone(), binary]
77-
} else if restricted_list.contains(&command.as_str()) {
75+
} else if RESTRICTED_LIST.contains(&command.as_str()) {
7876
return Err(SnmError::NotMatchPackageManagerError {
7977
raw_command: args_all.join(" ").to_string(),
8078
expect: package_manager.name,

crates/snm_utils/src/constant.rs

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
pub const PACKAGE_MANAGER: [&str; 3] = ["npm", "pnpm", "yarn"];
2+
3+
pub const RESTRICTED_LIST: [&str; 3] = ["install", "i", "run"];

crates/snm_utils/src/exec.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use std::{
22
env,
33
ffi::OsStr,
4-
process::{Command, Stdio},
4+
process::{exit, Command, Stdio},
55
};
66

77
use crate::snm_error::SnmError;
@@ -32,6 +32,8 @@ where
3232
return Err(SnmError::SNMBinaryProxyFail {
3333
stderr: String::from_utf8_lossy(&output.stderr).to_string(),
3434
});
35+
// TODO
36+
// exit(1);
3537
}
3638

3739
print!("{}", String::from_utf8_lossy(&output.stdout).to_string());

crates/snm_utils/src/fmtln.rs

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
#[macro_export]
2+
macro_rules! fmtln {
3+
($fmt:expr, $($arg:tt)*) => {
4+
format!($fmt, $($arg)*) + r#"
5+
"#
6+
};
7+
}

crates/snm_utils/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
pub mod constant;
12
pub mod exec;
3+
pub mod fmtln;
24
pub mod snm_error;
35
pub mod to_ok;

crates/snm_utils/src/snm_error.rs

+35-53
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ use colored::*;
22
use std::{path::PathBuf, process::exit};
33
use thiserror::Error;
44

5+
use crate::fmtln;
6+
57
#[derive(Error, Debug)]
68
pub enum SnmError {
79
#[error("Build config error: {0}")]
@@ -25,9 +27,6 @@ pub enum SnmError {
2527
#[error("Deserialize error: {0}")]
2628
DeserializeError(#[from] serde_json::Error),
2729

28-
#[error("Not found: {0}")]
29-
NotFoundResourceError(String),
30-
3130
#[error("Http status code not ok")]
3231
HttpStatusCodeUnOk,
3332

@@ -37,14 +36,11 @@ pub enum SnmError {
3736
#[error("Get workspace dir error")]
3837
GetWorkspaceError,
3938

40-
#[error("Not found valid version")]
41-
NotFoundValidNodeVersionDeclaration,
42-
4339
#[error("No default node binary")]
4440
NoDefaultNodeBinary,
4541

46-
#[error("File already exists {0}")]
47-
FileAlreadyExists(PathBuf),
42+
#[error("File already exists {file_path}")]
43+
FileAlreadyExists { file_path: PathBuf },
4844

4945
#[error("Exceeded maximum retry attempts: {0}")]
5046
ExceededMaxRetries(String),
@@ -97,7 +93,7 @@ pub fn create_error_message(message: String, descriptions: Vec<String>) -> Strin
9793
.iter()
9894
.map(|value| format!("{:<4}{}", "", value))
9995
.collect::<Vec<String>>()
100-
.join("\r\n".repeat(2).as_str());
96+
.join("\r\n".repeat(1).as_str());
10197

10298
format!(
10399
r##"
@@ -106,13 +102,26 @@ pub fn create_error_message(message: String, descriptions: Vec<String>) -> Strin
106102
{:<3}{}
107103
108104
{}
109-
"##,
105+
"##,
110106
"👹", message, "📋", "Explain", description
111107
)
112108
}
113109

114110
pub fn friendly_error_message(error: SnmError) {
115111
match error {
112+
SnmError::SNMBinaryProxyFail { stderr } => {
113+
eprintln!(
114+
r##"
115+
👹 SNM proxy error info:
116+
117+
{}
118+
"##,
119+
stderr
120+
)
121+
}
122+
SnmError::NoDefaultNodeBinary => {
123+
eprintln!(r##"[error]: No default node binary"##);
124+
}
116125
SnmError::ParsePackageManagerError {
117126
raw_package_manager,
118127
} => {
@@ -135,23 +144,14 @@ pub fn friendly_error_message(error: SnmError) {
135144
SnmError::ExceededMaxRetries(url) => {
136145
let message = create_error_message(
137146
"Exceeded max retries".to_string(),
138-
vec![format!(
139-
"The download failed after {} retries.",
140-
url.to_string().bold().red()
141-
)],
147+
vec![
148+
fmtln!("URL {}", url.to_string().bold().red()),
149+
fmtln!("The download failed after 3 retries.",),
150+
fmtln!("Please check the network connection and the download URL",),
151+
],
142152
);
143153
eprintln!("{}", message);
144154
}
145-
SnmError::NotFoundResourceError(url) => {
146-
eprintln!(
147-
r##"
148-
👹 Not found resource
149-
150-
The resource {} was not found.
151-
"##,
152-
url.to_string().bold().red()
153-
);
154-
}
155155
SnmError::GetHomeDirError => {
156156
eprintln!(
157157
r##"
@@ -181,22 +181,17 @@ pub fn friendly_error_message(error: SnmError) {
181181
"##
182182
);
183183
}
184-
SnmError::FileAlreadyExists(path_buf) => {
185-
eprintln!(
186-
r##"
187-
👹 File already exists
188-
189-
The file {} already exists.
190-
"##,
191-
path_buf.to_string_lossy().bold().red()
184+
SnmError::FileAlreadyExists { file_path } => {
185+
let message = create_error_message(
186+
"File already exists".to_string(),
187+
vec![format!(
188+
"The file {} already exists.",
189+
file_path.to_string_lossy().bold().red()
190+
)],
192191
);
192+
eprintln!("{}", message);
193193
}
194-
SnmError::NotFoundValidNodeVersionDeclaration => {
195-
eprintln!(r##"[error]: Not found valid node version declaration"##);
196-
}
197-
SnmError::NoDefaultNodeBinary => {
198-
eprintln!(r##"[error]: No default node binary"##);
199-
}
194+
200195
SnmError::NotFoundCommandError { bin_name } => {
201196
let message = create_error_message(
202197
format!("Not found command {}", bin_name.bold().red()),
@@ -222,16 +217,6 @@ pub fn friendly_error_message(error: SnmError) {
222217
);
223218
eprintln!("{}", message);
224219
}
225-
SnmError::SNMBinaryProxyFail { stderr } => {
226-
eprintln!(
227-
r##"
228-
👹 SNM proxy error info:
229-
230-
{}
231-
"##,
232-
stderr
233-
)
234-
}
235220
SnmError::ShasumError {
236221
file_path,
237222
expect,
@@ -272,7 +257,7 @@ pub fn friendly_error_message(error: SnmError) {
272257
let message = create_error_message(
273258
format!("Unsupported node {}", version.bold().bright_red()),
274259
vec![
275-
vec!["Only the following list is supported:".to_string()],
260+
vec![fmtln!("{}", "Only the following list is supported:")],
276261
node_white_list
277262
.iter()
278263
.map(|item| format!("- {}", item).to_string())
@@ -291,10 +276,7 @@ pub fn friendly_error_message(error: SnmError) {
291276
format!("Unsupported packageManager {}", name.bold().bright_red()),
292277
vec![
293278
vec![
294-
format!(
295-
"The raw package manager configuration is {}, Only the following list is supported:",
296-
raw.bold().bright_red()
297-
),
279+
fmtln!("The raw package manager configuration is {}, Only the following list is supported:", raw.bold().bright_red()),
298280
],
299281
supported
300282
.iter()

0 commit comments

Comments
 (0)