next_web_dev/util/
command_util.rs

1use std::collections::HashMap;
2
3/**
4*struct:    CommandUtil
5*desc:      命令工具类 适用于 linux shell 命令
6*author:    Listening
7*email:     yuenxillar@163.com
8*date:      2024/10/02
9*/
10
11pub struct CommandUtil;
12
13/// 运行命令工具类
14impl CommandUtil {
15    //! 运行命令 例如 linux shell 命令
16    pub fn run_command(program: &str, args: Vec<&str>) -> Result<String, std::io::Error> {
17        // run the ls command
18
19        let output = std::process::Command::new(program).args(args).output()?;
20
21        if !output.status.success() {
22            return Err(std::io::Error::new(
23                std::io::ErrorKind::Other,
24                String::from_utf8_lossy(output.stdout.as_slice()),
25            ));
26        }
27
28        Ok(String::from_utf8_lossy(&output.stdout).into_owned())
29    }
30
31    pub fn handle_args(args: Vec<String>) -> HashMap<String, String> {
32        let mut data: HashMap<String, String> = HashMap::new();
33        // 解析命令行参数
34        // 格式:--key=value 或者 -key2=value2
35        for arg in args {
36            if !arg.starts_with("--") || !arg.starts_with("-") {
37                continue;
38            }
39            if !arg.contains("=") {
40                continue;
41            }
42
43            let mut split_arg = arg.split('=');
44            let key = split_arg.next().unwrap().to_string();
45            let value = split_arg.next().unwrap().to_string();
46            data.insert(key, value);
47        }
48        return data;
49    }
50}