guser/
lib.rs

1use inquire::{required, Text};
2use serde::{Deserialize, Serialize};
3use std::fs::File;
4use std::io::{self, Read};
5use std::path::Path;
6use std::path::PathBuf;
7use std::process::Command;
8
9#[derive(Debug, Serialize, Deserialize)]
10pub struct Config {
11    pub email: String,
12    pub name: String,
13    pub alias: String,
14}
15
16pub fn set_text(message: &str, default: Option<&str>) -> String {
17    let mut text = Text::new(message).with_validator(required!("This field is required"));
18
19    text = match default {
20        Some(value) => text.with_default(value),
21        None => text,
22    };
23
24    text.prompt().unwrap()
25}
26
27pub fn read_config() -> Option<String> {
28    // 检查文件是否存在
29    if Path::new(&get_config_path()).exists() {
30        // 如果文件存在,读取文件内容
31        let mut file = File::open(&get_config_path()).unwrap();
32        let mut content = String::new();
33        let _ = file.read_to_string(&mut content);
34        Some(content)
35    } else {
36        None
37    }
38}
39
40pub fn set_git_config(config: &Config) {
41    let command = "git";
42    exec_command(command, ["config", "user.name", config.name.as_str()]);
43    exec_command(command, ["config", "user.email", config.email.as_str()]);
44    println!("\n✅ config success");
45}
46
47fn exec_command(command: &str, args: [&str; 3]) {
48    let _ = Command::new(command)
49        .args(args)
50        .output()
51        .expect("❌ Failed to execute command");
52}
53
54pub fn handle_write(file_write: io::Result<()>) {
55    match file_write {
56        Ok(_) => println!("\n✅ add success"),
57        Err(_) => println!("\n❌ add failed"),
58    }
59}
60
61pub fn get_config_path() -> PathBuf {
62    #[cfg(target_os = "macos")]
63    {
64        let home_dir = std::env::var("HOME").expect("Could not find home directory");
65        let mut path = PathBuf::from(home_dir);
66        path.push(".guserc");
67        path
68    }
69
70    #[cfg(target_os = "windows")]
71    {
72        let mut path = PathBuf::from("C:\\");
73        path.push(".guserc");
74        path
75    }
76
77    #[cfg(target_os = "linux")]
78    {
79        let mut path = PathBuf::from("/var/");
80        path.push(".guserc");
81        path
82    }
83
84    #[cfg(target_os = "unix")]
85    {
86        let mut path = PathBuf::from("/var/");
87        path.push(".guserc");
88        path
89    }
90}