🐞 fix: cmd error with gbk (#114)
* 🐞 fix: cmd error with gbk * 🎈 perf: try gbk only on windows
This commit is contained in:
@@ -164,6 +164,7 @@ windows-sys = { version = "0.52", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_System_IO",
|
||||
] }
|
||||
encoding = "0.2"
|
||||
|
||||
[build-dependencies]
|
||||
tonic-build = "0.10"
|
||||
|
||||
@@ -50,6 +50,8 @@ fn cidr_to_subnet_mask(prefix_length: u8) -> Ipv4Addr {
|
||||
|
||||
async fn run_shell_cmd(cmd: &str) -> Result<(), Error> {
|
||||
let cmd_out: std::process::Output;
|
||||
let stdout: String;
|
||||
let stderr: String;
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
const CREATE_NO_WINDOW: u32 = 0x08000000;
|
||||
@@ -58,22 +60,25 @@ async fn run_shell_cmd(cmd: &str) -> Result<(), Error> {
|
||||
.arg(cmd)
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.output()
|
||||
.await?
|
||||
.await?;
|
||||
stdout = crate::utils::utf8_or_gbk_to_string(cmd_out.stdout.as_slice());
|
||||
stderr = crate::utils::utf8_or_gbk_to_string(cmd_out.stderr.as_slice());
|
||||
};
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
{
|
||||
cmd_out = Command::new("sh").arg("-c").arg(cmd).output().await?
|
||||
cmd_out = Command::new("sh").arg("-c").arg(cmd).output().await?;
|
||||
stdout = String::from_utf8_lossy(cmd_out.stdout.as_slice()).to_string();
|
||||
stderr = String::from_utf8_lossy(cmd_out.stderr.as_slice()).to_string();
|
||||
};
|
||||
let stdout = String::from_utf8_lossy(cmd_out.stdout.as_slice());
|
||||
let stderr = String::from_utf8_lossy(cmd_out.stderr.as_slice());
|
||||
|
||||
let ec = cmd_out.status.code();
|
||||
let succ = cmd_out.status.success();
|
||||
tracing::info!(?cmd, ?ec, ?succ, ?stdout, ?stderr, "run shell cmd");
|
||||
|
||||
if !cmd_out.status.success() {
|
||||
return Err(Error::ShellCommandError(
|
||||
stdout.to_string() + &stderr.to_string(),
|
||||
stdout + &stderr,
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -225,6 +225,22 @@ pub fn init_logger(
|
||||
Ok(ret_sender)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
pub fn utf8_or_gbk_to_string(s: &[u8]) -> String {
|
||||
use encoding::{all::GBK, DecoderTrap, Encoding};
|
||||
if let Ok(utf8_str) = String::from_utf8(s.to_vec()) {
|
||||
utf8_str
|
||||
} else {
|
||||
// 如果解码失败,则尝试使用GBK解码
|
||||
if let Ok(gbk_str) = GBK.decode(&s, DecoderTrap::Strict) {
|
||||
gbk_str
|
||||
} else {
|
||||
String::from_utf8_lossy(s).to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::common::config::{self};
|
||||
|
||||
Reference in New Issue
Block a user