git.delta.rocks / jrsonnet / refs/commits / 17bf21a48a36

difftreelog

refactor use z85

Yaroslav Bolyukin2021-09-18parent: #2fef068.patch.diff
in: trunk

5 files changed

modifiedsrc/cmds/build_systems.rsdiffbeforeafterboth
--- a/src/cmds/build_systems.rs
+++ b/src/cmds/build_systems.rs
@@ -47,7 +47,6 @@
 
 impl BuildSystems {
 	pub fn run(self, config: &Config) -> Result<()> {
-		println!("Build");
 		let hosts = config.list_hosts()?;
 
 		for host in hosts.iter() {
@@ -76,7 +75,6 @@
 				));
 
 			if let Some(builders) = &self.builders {
-				println!("Using builders: {}", builders);
 				nix_build.arg("--builders").arg(builders);
 			}
 			if let Some(jobs) = &self.jobs {
modifiedsrc/cmds/secrets/mod.rsdiffbeforeafterboth
--- a/src/cmds/secrets/mod.rs
+++ b/src/cmds/secrets/mod.rs
@@ -56,14 +56,15 @@
 					let mut encryptor =
 						age::Encryptor::with_recipients(recipients).wrap_output(&mut encrypted)?;
 					io::copy(&mut Cursor::new(input), &mut encryptor)?;
-					ascii85::encode(&encrypted)
+					encryptor.finish()?;
+					encrypted
 				};
 
 				let mut data = config.data_mut();
-				if data.secret.contains_key(&name) && !force {
+				if data.secrets.contains_key(&name) && !force {
 					bail!("secret already defined");
 				}
-				data.secret.insert(
+				data.secrets.insert(
 					name,
 					FleetSecret {
 						owners: machines,
modifiedsrc/fleetdata.rsdiffbeforeafterboth
--- a/src/fleetdata.rs
+++ b/src/fleetdata.rs
@@ -1,5 +1,5 @@
 use chrono::{DateTime, Utc};
-use serde::{Deserialize, Serialize};
+use serde::{Deserialize, Deserializer, Serialize, Serializer};
 use std::collections::BTreeMap;
 
 #[derive(Serialize, Deserialize, Default)]
@@ -16,7 +16,7 @@
 	pub hosts: BTreeMap<String, HostData>,
 	#[serde(default)]
 	#[serde(skip_serializing_if = "BTreeMap::is_empty")]
-	pub secret: BTreeMap<String, FleetSecret>,
+	pub secrets: BTreeMap<String, FleetSecret>,
 }
 
 #[derive(Serialize, Deserialize)]
@@ -28,5 +28,22 @@
 	pub expire_at: Option<DateTime<Utc>>,
 	#[serde(skip_serializing_if = "Option::is_none")]
 	pub public: Option<String>,
-	pub secret: String,
+	#[serde(serialize_with = "as_z85", deserialize_with = "from_z85")]
+	pub secret: Vec<u8>,
+}
+
+fn as_z85<S>(key: &[u8], serializer: S) -> Result<S::Ok, S::Error>
+where
+	S: Serializer,
+{
+	serializer.serialize_str(&z85::encode(&key))
+}
+
+fn from_z85<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
+where
+	D: Deserializer<'de>,
+{
+	use serde::de::Error;
+	String::deserialize(deserializer)
+		.and_then(|string| z85::decode(&string).map_err(|err| Error::custom(err.to_string())))
 }
modifiedsrc/host.rsdiffbeforeafterboth
before · src/host.rs
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);7172		println!("{:?}", str);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	}8485	pub fn data(&self) -> Ref<FleetData> {86		self.data.borrow()87	}88	pub fn data_mut(&self) -> RefMut<FleetData> {89		self.data.borrow_mut()90	}9192	pub fn save(&self) -> Result<()> {93		let mut fleet_data_path = self.directory.clone();94		fleet_data_path.push("fleet.nix");95		let data = nixlike::serialize(&self.data() as &FleetData)?;96		std::fs::write(97			fleet_data_path,98			format!(99				"# This file contains fleet state and shouldn't be edited by hand\n\n{}\n",100				data101			),102		)?;103		Ok(())104	}105}106107#[derive(Clap, Clone)]108#[clap(group = clap::ArgGroup::new("target_hosts"))]109pub struct FleetOpts {110	/// All hosts except those would be skipped111	#[clap(long, number_of_values = 1, group = "target_hosts")]112	only: Vec<String>,113114	/// Hosts to skip115	#[clap(long, number_of_values = 1, group = "target_hosts")]116	skip: Vec<String>,117118	/// Host, which should be threaten as current machine119	#[clap(long)]120	pub localhost: Option<String>,121}122123impl FleetOpts {124	pub fn build(mut self) -> Result<Config> {125		if self.localhost.is_none() {126			self.localhost127				.replace(hostname::get().unwrap().to_str().unwrap().to_owned());128		}129		let directory = current_dir()?;130131		let mut fleet_data_path = directory.clone();132		fleet_data_path.push("fleet.nix");133		let bytes = std::fs::read_to_string(fleet_data_path)?;134		let data = nixlike::parse_str(&bytes)?;135136		Ok(Config(Arc::new(FleetConfigInternals {137			opts: self,138			directory,139			data,140		})))141	}142}
after · src/host.rs
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	/// All hosts except those would be skipped109	#[clap(long, number_of_values = 1, group = "target_hosts")]110	only: Vec<String>,111112	/// Hosts to skip113	#[clap(long, number_of_values = 1, group = "target_hosts")]114	skip: Vec<String>,115116	/// Host, which should be threaten as current machine117	#[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}
deletedsrc/nixlike.rsdiffbeforeafterboth

no changes