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 serde::de::DeserializeOwned;13use structopt::clap::ArgGroup;14use structopt::StructOpt;1516use crate::{command::CommandExt, fleetdata::FleetData};1718pub struct FleetConfigInternals {19 pub directory: PathBuf,20 pub opts: FleetOpts,21 pub data: RefCell<FleetData>,22}2324#[derive(Clone)]25pub struct Config(Arc<FleetConfigInternals>);2627impl Deref for Config {28 type Target = FleetConfigInternals;2930 fn deref(&self) -> &Self::Target {31 &self.032 }33}3435impl Config {36 pub fn should_skip(&self, host: &str) -> bool {37 if !self.opts.skip.is_empty() {38 self.opts.skip.iter().any(|h| h as &str == host)39 } else if !self.opts.only.is_empty() {40 !self.opts.only.iter().any(|h| h as &str == host)41 } else {42 false43 }44 }45 pub fn is_local(&self, host: &str) -> bool {46 self.opts.localhost.as_ref().map(|s| s as &str) == Some(host)47 }4849 pub fn command_on(&self, host: &str, program: impl AsRef<OsStr>, sudo: bool) -> Command {50 if self.is_local(host) {51 if sudo {52 let mut cmd = Command::new("sudo");53 cmd.arg(program);54 cmd55 } else {56 Command::new(program)57 }58 } else {59 let mut cmd = Command::new("ssh");60 cmd.arg(host).arg("--");61 if sudo {62 cmd.arg("sudo");63 }64 cmd.arg(program);65 cmd66 }67 }6869 pub fn full_attr_name(&self, attr_name: &str) -> OsString {70 let mut str = self.directory.as_os_str().to_owned();71 str.push("#");72 str.push(attr_name);73 str74 }7576 pub fn list_hosts(&self) -> Result<Vec<String>> {77 Command::new("nix")78 .arg("eval")79 .arg(self.full_attr_name("fleetConfigurations.default.configuredHosts"))80 .args(&["--apply", "builtins.attrNames", "--json", "--show-trace"])81 .inherit_stdio()82 .run_json()83 }84 pub fn config_attr<T: DeserializeOwned>(&self, host: &str, attr: &str) -> Result<T> {85 Command::new("nix")86 .arg("eval")87 .arg(self.full_attr_name(&format!(88 "fleetConfigurations.default.configuredSystems.{}.config.{}",89 host, attr90 )))91 .args(&["--json", "--show-trace"])92 .inherit_stdio()93 .run_json()94 }9596 pub fn data(&self) -> Ref<FleetData> {97 self.data.borrow()98 }99 pub fn data_mut(&self) -> RefMut<FleetData> {100 self.data.borrow_mut()101 }102103 pub fn save(&self) -> Result<()> {104 let mut fleet_data_path = self.directory.clone();105 fleet_data_path.push("fleet.nix");106 let data = nixlike::serialize(&self.data() as &FleetData)?;107 std::fs::write(108 fleet_data_path,109 format!(110 "# This file contains fleet state and shouldn't be edited by hand\n\n{}\n",111 data112 ),113 )?;114 Ok(())115 }116}117118#[derive(StructOpt, Clone)]119#[structopt(group = ArgGroup::with_name("target_hosts"))]120pub struct FleetOpts {121 122 #[structopt(long, number_of_values = 1, group = "target_hosts")]123 only: Vec<String>,124125 126 #[structopt(long, number_of_values = 1, group = "target_hosts")]127 skip: Vec<String>,128129 130 #[structopt(long)]131 pub localhost: Option<String>,132}133134impl FleetOpts {135 pub fn build(mut self) -> Result<Config> {136 if self.localhost.is_none() {137 self.localhost138 .replace(hostname::get().unwrap().to_str().unwrap().to_owned());139 }140 let directory = current_dir()?;141142 let mut fleet_data_path = directory.clone();143 fleet_data_path.push("fleet.nix");144 let bytes = std::fs::read_to_string(fleet_data_path)?;145 let data = nixlike::parse_str(&bytes)?;146147 Ok(Config(Arc::new(FleetConfigInternals {148 opts: self,149 directory,150 data,151 })))152 }153}