shitbox/corebox/commands/hostname/mod.rs

54 lines
1.6 KiB
Rust
Raw Normal View History

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
#[derive(Debug, Default)]
pub struct Hostname;
2022-12-25 18:29:09 -05:00
impl Cmd for Hostname {
fn cli(&self) -> clap::Command {
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: &ArgMatches) -> Result<(), Box<dyn Error>> {
2022-12-25 18:29:09 -05:00
if let Some(name) = matches.get_one::<String>("NAME") {
unistd::sethostname(name)?;
2022-12-25 18:29:09 -05:00
Ok(())
} else {
let hostname = unistd::gethostname()?;
2022-12-25 18:29:09 -05:00
if matches.get_flag("STRIP") {
println!(
"{}",
if let Some(s) = hostname.split('.').next() {
2022-12-25 18:29:09 -05:00
s
} else {
return Err(io::Error::new(
io::ErrorKind::Other,
"hostname: missing operand",
)
.into());
}
);
} else {
println!("{hostname}");
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<shitbox::Path> {
Some(shitbox::Path::Bin)
2022-12-25 18:29:09 -05:00
}
2022-12-20 12:05:21 -05:00
}