2022-12-25 18:29:09 -05:00
|
|
|
use super::Cmd;
|
2022-12-20 18:35:45 -05:00
|
|
|
use clap::{Arg, ArgAction, ArgMatches, Command};
|
2022-12-25 18:29:09 -05:00
|
|
|
use std::{error::Error, io};
|
2022-12-20 12:05:21 -05:00
|
|
|
|
2023-01-13 01:08:32 -05:00
|
|
|
#[derive(Debug, Default)]
|
|
|
|
pub struct Hostname;
|
2022-12-25 18:29:09 -05:00
|
|
|
|
|
|
|
impl Cmd for Hostname {
|
|
|
|
fn cli(&self) -> clap::Command {
|
2023-01-13 01:08:32 -05:00
|
|
|
Command::new("hostname")
|
|
|
|
.author("Nathan Fisher")
|
2022-12-25 18:29:09 -05:00
|
|
|
.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: Option<&ArgMatches>) -> Result<(), Box<dyn Error>> {
|
|
|
|
let matches = matches.unwrap();
|
|
|
|
if let Some(name) = matches.get_one::<String>("NAME") {
|
|
|
|
hostname::set(name)?;
|
|
|
|
Ok(())
|
|
|
|
} else {
|
|
|
|
let hostname = hostname::get()?;
|
|
|
|
if matches.get_flag("STRIP") {
|
|
|
|
println!(
|
|
|
|
"{}",
|
|
|
|
if let Some(s) = hostname.to_string_lossy().split('.').next() {
|
|
|
|
s
|
|
|
|
} else {
|
|
|
|
return Err(io::Error::new(
|
|
|
|
io::ErrorKind::Other,
|
|
|
|
"hostname: missing operand",
|
|
|
|
)
|
|
|
|
.into());
|
|
|
|
}
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
println!("{}", hostname.to_string_lossy());
|
2022-12-20 12:05:21 -05:00
|
|
|
}
|
2022-12-25 18:29:09 -05:00
|
|
|
Ok(())
|
2022-12-20 12:05:21 -05:00
|
|
|
}
|
|
|
|
}
|
2022-12-25 18:29:09 -05:00
|
|
|
|
|
|
|
fn path(&self) -> Option<crate::Path> {
|
2023-01-13 01:08:32 -05:00
|
|
|
Some(crate::Path::Bin)
|
2022-12-25 18:29:09 -05:00
|
|
|
}
|
2022-12-20 12:05:21 -05:00
|
|
|
}
|