use super::Cmd; use crate::unistd; use clap::{Arg, ArgAction, ArgMatches, Command}; use std::{error::Error, io}; #[derive(Debug, Default)] pub struct Hostname; impl Cmd for Hostname { fn cli(&self) -> clap::Command { Command::new("hostname") .author("Nathan Fisher") .about("Prints the name of the current host. The super-user can set the host name by supplying an argument.") .args([ Arg::new("NAME") .help("name to set"), Arg::new("STRIP") .help("Removes any domain information from the printed name.") .short('s') .long("strip") .action(ArgAction::SetTrue) ]) } fn run(&self, matches: &ArgMatches) -> Result<(), Box> { if let Some(name) = matches.get_one::("NAME") { unistd::sethostname(name)?; Ok(()) } else { let hostname = unistd::gethostname()?; if matches.get_flag("STRIP") { println!( "{}", if let Some(s) = hostname.split('.').next() { s } else { return Err(io::Error::new( io::ErrorKind::Other, "hostname: missing operand", ) .into()); } ); } else { println!("{hostname}"); } Ok(()) } } fn path(&self) -> Option { Some(crate::Path::Bin) } }