1use std::{2 cell::{Ref, RefCell, RefMut},3 env::current_dir,4 ffi::{OsStr, OsString},5 ops::Deref,6 path::PathBuf,7 process::Command,8 sync::Arc,9};1011use anyhow::Result;12use clap::Clap;1314use crate::{command::CommandExt, fleetdata::FleetData};1516pub struct FleetConfigInternals {17 pub directory: PathBuf,18 pub opts: FleetOpts,19 pub data: RefCell<FleetData>,20}2122#[derive(Clone)]23pub struct Config(Arc<FleetConfigInternals>);2425impl Deref for Config {26 type Target = FleetConfigInternals;2728 fn deref(&self) -> &Self::Target {29 &self.030 }31}3233impl Config {34 pub fn should_skip(&self, host: &str) -> bool {35 if !self.opts.skip.is_empty() {36 self.opts.skip.iter().any(|h| h as &str == host)37 } else if !self.opts.only.is_empty() {38 !self.opts.only.iter().any(|h| h as &str == host)39 } else {40 false41 }42 }43 pub fn is_local(&self, host: &str) -> bool {44 self.opts.localhost.as_ref().map(|s| s as &str) == Some(host)45 }4647 pub fn command_on(&self, host: &str, program: impl AsRef<OsStr>, sudo: bool) -> Command {48 if self.is_local(host) {49 if sudo {50 let mut cmd = Command::new("sudo");51 cmd.arg(program);52 cmd53 } else {54 Command::new(program)55 }56 } else {57 let mut cmd = Command::new("ssh");58 cmd.arg(host).arg("--");59 if sudo {60 cmd.arg("sudo");61 }62 cmd.arg(program);63 cmd64 }65 }6667 pub fn full_attr_name(&self, attr_name: &str) -> OsString {68 let mut str = self.directory.as_os_str().to_owned();69 str.push("#");70 str.push(attr_name);71 str72 }7374 pub fn list_hosts(&self) -> Result<Vec<String>> {75 Command::new("nix")76 .arg("eval")77 .arg(self.full_attr_name("fleetConfigurations.default.configuredHosts"))78 .args(&["--apply", "builtins.attrNames", "--json", "--show-trace"])79 .inherit_stdio()80 .run_json()81 }8283 pub fn data(&self) -> Ref<FleetData> {84 self.data.borrow()85 }86 pub fn data_mut(&self) -> RefMut<FleetData> {87 self.data.borrow_mut()88 }8990 pub fn save(&self) -> Result<()> {91 let mut fleet_data_path = self.directory.clone();92 fleet_data_path.push("fleet.nix");93 let data = nixlike::serialize(&self.data() as &FleetData)?;94 std::fs::write(95 fleet_data_path,96 format!(97 "# This file contains fleet state and shouldn't be edited by hand\n\n{}\n",98 data99 ),100 )?;101 Ok(())102 }103}104105#[derive(Clap, Clone)]106#[clap(group = clap::ArgGroup::new("target_hosts"))]107pub struct FleetOpts {108 109 #[clap(long, number_of_values = 1, group = "target_hosts")]110 only: Vec<String>,111112 113 #[clap(long, number_of_values = 1, group = "target_hosts")]114 skip: Vec<String>,115116 117 #[clap(long)]118 pub localhost: Option<String>,119}120121impl FleetOpts {122 pub fn build(mut self) -> Result<Config> {123 if self.localhost.is_none() {124 self.localhost125 .replace(hostname::get().unwrap().to_str().unwrap().to_owned());126 }127 let directory = current_dir()?;128129 let mut fleet_data_path = directory.clone();130 fleet_data_path.push("fleet.nix");131 let bytes = std::fs::read_to_string(fleet_data_path)?;132 let data = nixlike::parse_str(&bytes)?;133134 Ok(Config(Arc::new(FleetConfigInternals {135 opts: self,136 directory,137 data,138 })))139 }140}