ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/salaryman/trunk/src/main.rs
Revision: 5
Committed: Sun Jun 1 04:59:07 2025 UTC (4 months, 1 week ago) by yuzu
File size: 2802 byte(s)
Log Message:
get config together

File Contents

# Content
1 use serde::{
2 Deserialize,
3 Serialize,
4 };
5 use clap::Parser;
6
7 use tokio::fs::read_to_string;
8
9 use std::{
10 fs::canonicalize,
11 io::Read,
12 process::{
13 Child,
14 Command,
15 Stdio
16 },
17 path::PathBuf,
18 net::IpAddr,
19 };
20
21 #[derive(Parser)]
22 #[command(version, about, long_about = None)]
23 struct Args {
24 #[arg(short, long, value_name = "FILE")]
25 config: Option<PathBuf>,
26 #[arg(short, long, value_name = "ADDR")]
27 address: Option<IpAddr>,
28 #[arg(short, long, value_name = "PORT")]
29 port: Option<u16>,
30 }
31
32 #[derive(Serialize, Deserialize)]
33 struct Service {
34 name: String,
35 command: String,
36 args: String,
37 directory: Option<PathBuf>,
38 }
39 impl Service {
40 fn new() -> Self {
41 Self {
42 name: String::new(),
43 command: String::new(),
44 args: String::new(),
45 directory: None,
46 }
47 }
48 }
49
50 #[derive(Serialize, Deserialize)]
51 struct Config {
52 address: Option<IpAddr>,
53 port: Option<u16>,
54 service: Vec<Service>,
55 }
56 impl Config {
57 fn new() -> Self {
58 Self {
59 address: None,
60 port: None,
61 service: Vec::new(),
62 }
63 }
64 }
65
66 fn exec(image: &str, args: Vec<&str>, dir: Option<PathBuf>) -> Result<Child, Box<dyn std::error::Error>> {
67 if let Some(cwd) = dir {
68 let child = Command::new(image)
69 .args(args)
70 .current_dir(canonicalize(cwd)?)
71 .stdin(Stdio::piped())
72 .stdout(Stdio::piped())
73 .stderr(Stdio::piped())
74 .spawn()?;
75 Ok(child)
76 } else {
77 let child = Command::new(image)
78 .args(args)
79 .stdin(Stdio::piped())
80 .stdout(Stdio::piped())
81 .stderr(Stdio::piped())
82 .spawn()?;
83 Ok(child)
84 }
85 }
86
87 async fn load_config(file: PathBuf) -> Result<Config, Box<dyn std::error::Error>> {
88 let config: Config = toml::from_str(read_to_string(file).await?.as_str())?;
89 Ok(config)
90 }
91
92 #[tokio::main]
93 async fn main() -> Result<(), Box<dyn std::error::Error>> {
94 let args = Args::parse();
95 let mut conf: Config = Config::new();
96 if let Some(file) = args.config.as_deref() {
97 conf = load_config(PathBuf::from(file)).await?;
98 } else {
99 conf = load_config(PathBuf::from("salaryman.toml")).await?;
100 }
101
102 let mut child = exec("java", vec!["-jar", "minecraft_server.jar"], None)?;
103 std::thread::sleep(std::time::Duration::from_secs(60));
104 let mut buf: [u8; 512] = [0; 512];
105 let mut ebuf: [u8; 512] = [0; 512];
106 child.stdout.as_mut().unwrap().read(&mut buf[..])?;
107 child.stderr.as_mut().unwrap().read(&mut ebuf[..])?;
108 println!("{}", String::from_utf8_lossy(&buf));
109 println!("{}", String::from_utf8_lossy(&ebuf));
110 child.kill()?;
111 Ok(())
112 }
113