shitbox/src/cmd/sleep/mod.rs
Nathan Fisher fb389fd309 Simplify subcommand parsing:
- one match statement to return a `Box<dyn Cmd>`
- one array containing all command names
Only two places to register new commands (besides their module), both in
crate::cmd::mod.rs. Also removes `once_cell` crate dependency.

Replace `base64` crate dependency with `data_encoding::BASE64` so that
both base32 and base64 commands use the same crate.
2023-01-06 23:41:02 -05:00

61 lines
1.8 KiB
Rust

use super::Cmd;
use crate::Path;
use clap::{value_parser, Arg, ArgAction, ArgMatches, Command};
use std::{env, error::Error, thread, time::Duration};
#[derive(Debug)]
pub struct Sleep {
name: &'static str,
path: Option<Path>,
}
impl Default for Sleep {
fn default() -> Self {
Self {
name: "sleep",
path: Some(crate::Path::Bin),
}
}
}
impl Cmd for Sleep {
fn name(&self) -> &str {
self.name
}
fn cli(&self) -> clap::Command {
Command::new(self.name)
.about("Suspend execution for an interval of time")
.long_about(
"The sleep utility suspends execution for a minimum of the specified number of seconds.\n\
This number must be positive and may contain a decimal fraction.\n\
sleep is commonly used to schedule the execution of other commands"
)
.author(env!("CARGO_PKG_AUTHORS"))
.arg(
Arg::new("seconds")
.help("The number of seconds to sleep")
.num_args(1)
.allow_negative_numbers(false)
.value_parser(value_parser!(f64))
.required(true)
.action(ArgAction::Set)
)
}
#[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
fn run(&self, matches: Option<&ArgMatches>) -> Result<(), Box<dyn Error>> {
if let Some(raw) = matches.unwrap().get_one::<f64>("seconds") {
let seconds = *raw as u64;
let nanos = ((raw % 1.0) * 10e-9) as u32;
let s = Duration::new(seconds, nanos);
thread::sleep(s);
}
Ok(())
}
fn path(&self) -> Option<Path> {
self.path
}
}