git.delta.rocks / jrsonnet / refs/commits / bb34d421e2a0

difftreelog

source

src/host.rs3.2 KiBsourcehistory
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 structopt::clap::ArgGroup;13use structopt::StructOpt;1415use crate::{command::CommandExt, fleetdata::FleetData};1617pub struct FleetConfigInternals {18	pub directory: PathBuf,19	pub opts: FleetOpts,20	pub data: RefCell<FleetData>,21}2223#[derive(Clone)]24pub struct Config(Arc<FleetConfigInternals>);2526impl Deref for Config {27	type Target = FleetConfigInternals;2829	fn deref(&self) -> &Self::Target {30		&self.031	}32}3334impl Config {35	pub fn should_skip(&self, host: &str) -> bool {36		if !self.opts.skip.is_empty() {37			self.opts.skip.iter().any(|h| h as &str == host)38		} else if !self.opts.only.is_empty() {39			!self.opts.only.iter().any(|h| h as &str == host)40		} else {41			false42		}43	}44	pub fn is_local(&self, host: &str) -> bool {45		self.opts.localhost.as_ref().map(|s| s as &str) == Some(host)46	}4748	pub fn command_on(&self, host: &str, program: impl AsRef<OsStr>, sudo: bool) -> Command {49		if self.is_local(host) {50			if sudo {51				let mut cmd = Command::new("sudo");52				cmd.arg(program);53				cmd54			} else {55				Command::new(program)56			}57		} else {58			let mut cmd = Command::new("ssh");59			cmd.arg(host).arg("--");60			if sudo {61				cmd.arg("sudo");62			}63			cmd.arg(program);64			cmd65		}66	}6768	pub fn full_attr_name(&self, attr_name: &str) -> OsString {69		let mut str = self.directory.as_os_str().to_owned();70		str.push("#");71		str.push(attr_name);72		str73	}7475	pub fn list_hosts(&self) -> Result<Vec<String>> {76		Command::new("nix")77			.arg("eval")78			.arg(self.full_attr_name("fleetConfigurations.default.configuredHosts"))79			.args(&["--apply", "builtins.attrNames", "--json", "--show-trace"])80			.inherit_stdio()81			.run_json()82	}8384	pub fn data(&self) -> Ref<FleetData> {85		self.data.borrow()86	}87	pub fn data_mut(&self) -> RefMut<FleetData> {88		self.data.borrow_mut()89	}9091	pub fn save(&self) -> Result<()> {92		let mut fleet_data_path = self.directory.clone();93		fleet_data_path.push("fleet.nix");94		let data = nixlike::serialize(&self.data() as &FleetData)?;95		std::fs::write(96			fleet_data_path,97			format!(98				"# This file contains fleet state and shouldn't be edited by hand\n\n{}\n",99				data100			),101		)?;102		Ok(())103	}104}105106#[derive(StructOpt, Clone)]107#[structopt(group = ArgGroup::with_name("target_hosts"))]108pub struct FleetOpts {109	/// All hosts except those would be skipped110	#[structopt(long, number_of_values = 1, group = "target_hosts")]111	only: Vec<String>,112113	/// Hosts to skip114	#[structopt(long, number_of_values = 1, group = "target_hosts")]115	skip: Vec<String>,116117	/// Host, which should be threaten as current machine118	#[structopt(long)]119	pub localhost: Option<String>,120}121122impl FleetOpts {123	pub fn build(mut self) -> Result<Config> {124		if self.localhost.is_none() {125			self.localhost126				.replace(hostname::get().unwrap().to_str().unwrap().to_owned());127		}128		let directory = current_dir()?;129130		let mut fleet_data_path = directory.clone();131		fleet_data_path.push("fleet.nix");132		let bytes = std::fs::read_to_string(fleet_data_path)?;133		let data = nixlike::parse_str(&bytes)?;134135		Ok(Config(Arc::new(FleetConfigInternals {136			opts: self,137			directory,138			data,139		})))140	}141}