use crate::core::{
error::AppError,
hosts::{self, profiles},
};
use clap::{Args, Subcommand};
use std::{io::Read, path::PathBuf};
#[derive(Args, Debug)]
pub(super) struct HostsArgs {
#[command(subcommand)]
command: HostsCommand,
}
#[derive(Subcommand, Debug)]
enum HostsCommand {
List,
Show { reference: String },
Create {
#[arg(long)]
name: String,
#[command(flatten)]
input: Input,
},
Update {
reference: String,
#[arg(long)]
revision: String,
#[command(flatten)]
input: Input,
},
Rename {
reference: String,
#[arg(long)]
name: String,
#[arg(long)]
revision: String,
},
Copy {
reference: String,
#[arg(long)]
name: String,
},
Delete {
reference: String,
#[arg(long)]
revision: String,
},
Apply {
reference: String,
#[arg(long)]
revision: String,
#[arg(long)]
system_revision: String,
},
#[cfg(target_os = "macos")]
RevokeAuthorization,
System {
#[command(subcommand)]
command: SystemCommand,
},
}
#[derive(Subcommand, Debug)]
enum SystemCommand {
Read,
Write {
#[arg(long)]
revision: String,
#[command(flatten)]
input: Input,
},
}
#[derive(Args, Debug)]
struct Input {
#[arg(long)]
file: PathBuf,
}
impl Input {
fn read(&self) -> anyhow::Result<String> {
let source: Box<dyn Read> = if self.file == std::path::Path::new("-") {
Box::new(std::io::stdin())
} else {
Box::new(std::fs::File::open(&self.file)?)
};
let mut bytes = Vec::new();
source.take(1024 * 1024 + 1).read_to_end(&mut bytes)?;
if bytes.len() > 1024 * 1024 {
return Err(AppError::invalid_input("HOSTS_TOO_LARGE").into());
}
String::from_utf8(bytes).map_err(|_| AppError::invalid_input("HOSTS_ENCODING").into())
}
}
fn resolve(reference: &str) -> anyhow::Result<profiles::HostsProfile> {
let mut profiles = profiles::list().map_err(AppError::io)?;
if let Some(index) = profiles.iter().position(|p| p.id == reference) {
return Ok(profiles.swap_remove(index));
}
let mut matches = profiles.into_iter().filter(|p| p.name == reference);
let profile = matches
.next()
.ok_or_else(|| AppError::not_found("HOSTS_PROFILE_NOT_FOUND"))?;
if matches.next().is_some() {
return Err(AppError::invalid_input("HOSTS_PROFILE_AMBIGUOUS: use the profile ID").into());
}
Ok(profile)
}
pub(super) fn run(args: &HostsArgs, isolated: bool, json: bool) -> anyhow::Result<()> {
if isolated
&& matches!(
args.command,
HostsCommand::Apply { .. }
| HostsCommand::System {
command: SystemCommand::Write { .. }
}
)
{
return Err(AppError::invalid_input(
"System Hosts writes cannot be combined with --skills-root",
)
.into());
}
#[cfg(target_os = "macos")]
if isolated && matches!(args.command, HostsCommand::RevokeAuthorization) {
return Err(AppError::invalid_input(
"Hosts authorization cannot be combined with --skills-root",
)
.into());
}
use HostsCommand::*;
match &args.command {
#[cfg(target_os = "macos")]
RevokeAuthorization => {
hosts::macos_helper::revoke().map_err(AppError::io)?;
super::print_json(&serde_json::json!({"ok": true, "revoked": true}), json);
}
List => super::print_json(&profiles::list().map_err(AppError::io)?, json),
Show { reference } => super::print_json(&resolve(reference)?, json),
Create { name, input } => super::print_json(
&profiles::create(name, &input.read()?).map_err(AppError::io)?,
json,
),
Update {
reference,
revision,
input,
} => {
let profile = resolve(reference)?;
super::print_json(
&profiles::update(&profile.id, &profile.name, &input.read()?, revision)
.map_err(AppError::io)?,
json,
);
}
Rename {
reference,
name,
revision,
} => {
let profile = resolve(reference)?;
super::print_json(
&profiles::update(&profile.id, name, &profile.content, revision)
.map_err(AppError::io)?,
json,
);
}
Copy { reference, name } => {
let profile = resolve(reference)?;
super::print_json(
&profiles::create(name, &profile.content).map_err(AppError::io)?,
json,
);
}
Delete {
reference,
revision,
} => {
let profile = resolve(reference)?;
profiles::delete(&profile.id, revision).map_err(AppError::io)?;
super::print_json(
&serde_json::json!({"ok":true,"id":profile.id,"deleted":true}),
json,
);
}
Apply {
reference,
revision,
system_revision,
} => {
let profile = resolve(reference)?;
super::print_json(
&profiles::apply(&profile.id, revision, system_revision).map_err(AppError::io)?,
json,
);
}
System {
command: SystemCommand::Read,
} => super::print_json(&hosts::read_for_editor().map_err(AppError::io)?, json),
System {
command: SystemCommand::Write { revision, input },
} => super::print_json(
&hosts::save(&input.read()?, revision).map_err(AppError::io)?,
json,
),
}
Ok(())
}