timers/src/cli.rs

45 lines
1.4 KiB
Rust
Raw Normal View History

2023-07-28 19:52:23 +02:00
use crate::daemon::{Answer, Command as OtherCommand, AnswerErr};
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 {
Daemon,
Add { name: String, duration_seconds: u64 },
List,
Remove { name: String },
}
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!")?;
let answer: Result<Answer, AnswerErr> = serde_cbor::from_reader(&stream).context("Could not read answer!")?;
match answer {
Ok(answer) => println!("{}", answer),
Err(err) => println!("Error: {}", err),
}
Ok(())
}