timers/src/cli.rs

54 lines
1.5 KiB
Rust
Raw Normal View History

2023-07-29 10:41:56 +02:00
use crate::daemon::{Answer, AnswerErr, Command as OtherCommand};
2023-07-28 19:52:23 +02:00
use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use std::net::Shutdown;
use std::os::unix::net::UnixStream;
#[derive(Debug, Parser)]
#[command(name = "timers")]
#[command(about = "A advanced timer daemon/cli.", long_about = None)]
#[command(arg_required_else_help = true)]
pub struct Cli {
#[command(subcommand)]
pub command: Command,
#[arg(short, long)]
#[clap(default_value = "/tmp/timers.socket")]
pub socket: String,
}
#[derive(Debug, Subcommand)]
pub enum Command {
2023-07-29 10:41:56 +02:00
Daemon {
#[arg(short, long)]
notify: bool,
},
Add {
name: String,
duration_seconds: u64,
},
2023-07-28 19:52:23 +02:00
List,
2023-07-29 10:41:56 +02:00
Remove {
name: String,
},
2023-07-28 19:52:23 +02:00
}
fn get_stream(socket_path: &String) -> Result<UnixStream> {
UnixStream::connect(socket_path)
.context(format!("Could not connect to socket {}!", socket_path))
}
pub fn send_command(socket_path: &String, command: OtherCommand) -> Result<()> {
let stream = get_stream(socket_path)?;
serde_cbor::to_writer(&stream, &command).context("Could not write command!")?;
stream
.shutdown(Shutdown::Write)
.context("Could not shutdown write!")?;
2023-07-29 10:41:56 +02:00
let answer: Result<Answer, AnswerErr> =
serde_cbor::from_reader(&stream).context("Could not read answer!")?;
2023-07-28 19:52:23 +02:00
match answer {
Ok(answer) => println!("{}", answer),
Err(err) => println!("Error: {}", err),
}
Ok(())
}