difftreelog
refactor perform build using nix repl
in: trunk
8 files changed
cmds/fleet/src/better_nix_eval.rsdiffbeforeafterboth--- a/cmds/fleet/src/better_nix_eval.rs
+++ b/cmds/fleet/src/better_nix_eval.rs
@@ -1,5 +1,7 @@
+use std::collections::HashMap;
use std::ffi::{OsStr, OsString};
-use std::fmt::Display;
+use std::fmt::{self, Display};
+use std::path::PathBuf;
use std::process::Stdio;
use std::sync::{Arc, OnceLock};
@@ -8,7 +10,7 @@
use itertools::Itertools;
use r2d2::{Pool, PooledConnection};
use serde::de::DeserializeOwned;
-use serde::Deserialize;
+use serde::{Deserialize, Serialize};
use tokio::io::AsyncWriteExt;
use tokio::process::{ChildStderr, ChildStdin, ChildStdout, Command};
use tokio::select;
@@ -72,14 +74,20 @@
// s.split('\n').filter(|s| !s.trim().is_empty()).map(|v| v.)
// }
if !self.collected.is_empty() {
- bail!("{}", self.collected.iter().map(|v| {
- if let Some(f) = v.strip_prefix("\u{1b}[31;1merror:\u{1b}[0m ") {
- let v = unindent::unindent(f.trim_start());
- v.trim().to_owned()
- } else {
- v.to_owned()
- }
- }).join("\n"));
+ bail!(
+ "{}",
+ self.collected
+ .iter()
+ .map(|v| {
+ if let Some(f) = v.strip_prefix("\u{1b}[31;1merror:\u{1b}[0m ") {
+ let v = unindent::unindent(f.trim_start());
+ v.trim().to_owned()
+ } else {
+ v.to_owned()
+ }
+ })
+ .join("\n")
+ );
}
Ok(())
}
@@ -150,6 +158,13 @@
}
}
+struct WarnHandler;
+impl Handler for WarnHandler {
+ fn handle_line(&mut self, e: &str) {
+ warn!(target: "nix", "{e}")
+ }
+}
+
impl NixSessionInner {
async fn new(flake: &OsStr, extra_args: impl IntoIterator<Item = &OsStr>) -> Result<Self> {
let mut cmd = Command::new("nix");
@@ -174,12 +189,13 @@
stdin.flush().await?;
let nix_handler = NixHandler::default();
let mut full_delimiter = None;
+ let mut errors = vec![];
while let Some(line) = out.next().await {
let line = match line {
OutputLine::Out(o) => o,
OutputLine::Err(_e) => {
// Handle startup errors, but skip repl hello?
- //nix_handler.handle_line(&e);
+ errors.push(_e);
continue;
}
};
@@ -190,6 +206,9 @@
}
}
let Some(full_delimiter) = full_delimiter else {
+ for e in errors {
+ error!("{e}");
+ }
bail!("failed to discover delimiter");
};
let mut res = Self {
@@ -342,21 +361,93 @@
#[derive(Clone)]
pub struct NixSession(Arc<tokio::sync::Mutex<PooledConnection<NixSessionPoolInner>>>);
+#[macro_export]
+macro_rules! nix_path {
+ (@o($o:ident) $var:ident $($tt:tt)*) => {{
+ $o.push(Index::var(stringify!($var)));
+ nix_path!(@o($o) $($tt)*);
+ }};
+ (@o($o:ident) . $var:ident $($tt:tt)*) => {{
+ $o.push(Index::attr(stringify!($var)));
+ nix_path!(@o($o) $($tt)*);
+ }};
+ (@o($o:ident) . $var:literal $($tt:tt)*) => {{
+ $o.push(Index::attr($var));
+ nix_path!(@o($o) $($tt)*);
+ }};
+ (@o($o:ident) . { $var:expr } $($tt:tt)*) => {{
+ $o.push(Index::attr($var));
+ nix_path!(@o($o) $($tt)*);
+ }};
+ (@o($o:ident) [ $var:literal ] $($tt:tt)*) => {{
+ $o.push(Index::idx($var));
+ nix_path!(@o($o) $($tt)*);
+ }};
+ (@o($o:ident) ($e:expr) $($tt:tt)*) => {
+ $o.push(Index::apply($e));
+ nix_path!(@o($o) $($tt)*);
+ };
+ (@o($o:ident)) => {};
+ ($($tt:tt)+) => {{
+ use $crate::{nix_path, better_nix_eval::Index};
+ let mut out = vec![];
+ nix_path!(@o(out) $($tt)*);
+ out
+ }}
+}
+
#[derive(Clone)]
-enum Index {
+pub enum Index {
+ Var(String),
String(String),
- // Idx(u32),
+ Apply(String),
+ Idx(u32),
}
+impl Index {
+ pub fn var(v: impl AsRef<str>) -> Self {
+ let v = v.as_ref();
+ assert!(
+ !(v.contains('.') | v.contains(' ')),
+ "bad variable name: {v}"
+ );
+ Self::Var(v.to_owned())
+ }
+ pub fn attr(v: impl AsRef<str>) -> Self {
+ Self::String(v.as_ref().to_owned())
+ }
+ pub fn idx(v: u32) -> Self {
+ Self::Idx(v)
+ }
+ pub fn apply(v: impl Serialize) -> Self {
+ let serialized = nixlike::serialize(v).expect("invalid value for apply");
+ Self::Apply(serialized)
+ }
+}
impl Display for Index {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
+ Index::Var(v) => {
+ write!(f, "{v}")
+ }
Index::String(k) => {
let v = nixlike::format_identifier(k.as_str());
write!(f, ".{v}")
}
+ Index::Apply(o) => {
+ let v = nixlike::serialize(o).map_err(|_| fmt::Error)?;
+ write!(f, "<apply>({v})")
+ }
+ Index::Idx(i) => {
+ write!(f, "[{i}]")
+ }
}
}
}
+impl fmt::Debug for Index {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{self}")
+ }
+}
struct PathDisplay<'i>(&'i [Index]);
impl Display for PathDisplay<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
@@ -381,43 +472,49 @@
}
}
pub async fn field(session: NixSession, field: &str) -> Result<Self> {
- Self::root(session).get_field_deep([field]).await
+ Self::root(session)
+ .select([Index::var(field)])
+ .await
}
pub async fn get_json_deep<'a, V: DeserializeOwned>(
&self,
- name: impl IntoIterator<Item = &'a str>,
+ name: impl IntoIterator<Item = Index>,
) -> Result<V> {
- let field = self.get_field_deep(name).await?;
+ let field = self.select(name).await?;
field.as_json().await
}
- pub async fn get_field(&self, name: &str) -> Result<Self> {
- self.get_field_deep([name]).await
- }
- pub async fn get_field_deep<'a>(
- &self,
- name: impl IntoIterator<Item = &'a str>,
- ) -> Result<Self> {
- let mut iter = name.into_iter();
+ pub async fn select<'a>(&self, name: impl IntoIterator<Item = Index>) -> Result<Self> {
+ let mut name = name.into_iter();
let mut full_path = self.full_path.clone();
let mut query = if let Some(id) = self.value {
format!("sess_field_{id}")
} else {
- let first = iter.next().expect("name not empty");
- ensure!(
- !(first.contains('.') | first.contains(' ')),
- "bad name for root query: {first}"
- );
- full_path.push(Index::String(first.to_string()));
- first.to_string()
+ let first = name.next();
+ if let Some(Index::Var(i)) = first {
+ full_path.push(Index::Var(i.clone()));
+ i.clone()
+ } else {
+ panic!("first path item should be variable, got {first:?}")
+ }
};
- for v in iter {
- full_path.push(Index::String(v.to_string()));
- // Escape
- let escaped = nixlike::serialize(v)?;
- let escaped = escaped.trim();
- query.push('.');
- query.push_str(escaped);
+ for v in name {
+ full_path.push(v.clone());
+ match v {
+ Index::Var(_) => panic!("var item may only be first"),
+ Index::String(s) => {
+ let escaped = nixlike::serialize(s)?;
+ query.push('.');
+ query.push_str(escaped.trim());
+ }
+ Index::Apply(a) => {
+ query.push(' ');
+ query.push_str(&a);
+ }
+ Index::Idx(idx) => {
+ query = format!("builtins.elemAt ({query}) {idx}");
+ }
+ }
}
let vid = self
@@ -454,6 +551,28 @@
.await
.with_context(|| format!("full path: {}", PathDisplay(&self.full_path)))
}
+ pub async fn build(&self) -> Result<HashMap<String, PathBuf>> {
+ let id = self.value.expect("can't use build on not-value");
+ let vid = self
+ .session
+ .0
+ .lock()
+ .await
+ .execute_expression_raw(&format!(":b sess_field_{id}"), &mut NixHandler::default())
+ .await?;
+ ensure!(!vid.is_empty(), "build failed");
+ let Some(vid) = vid.strip_prefix("This derivation produced the following outputs:\n")
+ else {
+ panic!("unexpected build output: {vid:?}");
+ };
+ let outputs = vid
+ .split('\n')
+ .filter(|v| !v.is_empty())
+ .map(|v| v.split_once(" -> ").expect("unexpected build output"))
+ .map(|(a, b)| (a.trim_start().to_owned(), PathBuf::from(b)))
+ .collect();
+ Ok(outputs)
+ }
}
impl Drop for Field {
fn drop(&mut self) {
cmds/fleet/src/cmds/build_systems.rsdiffbeforeafterboth--- a/cmds/fleet/src/cmds/build_systems.rs
+++ b/cmds/fleet/src/cmds/build_systems.rs
@@ -1,8 +1,10 @@
+use std::os::unix::fs::symlink;
use std::path::PathBuf;
use std::{env::current_dir, time::Duration};
use crate::command::MyCommand;
use crate::host::Config;
+use crate::nix_path;
use anyhow::{anyhow, Result};
use clap::Parser;
use itertools::Itertools;
@@ -11,15 +13,9 @@
#[derive(Parser, Clone)]
pub struct BuildSystems {
- /// Do not continue on error
- #[clap(long)]
- fail_fast: bool,
/// Disable automatic rollback
#[clap(long)]
disable_rollback: bool,
- /// Run builds as sudo
- #[clap(long)]
- privileged_build: bool,
#[clap(subcommand)]
subcommand: Subcommand,
}
@@ -294,34 +290,11 @@
async fn build_task(self, config: Config, host: String) -> Result<()> {
info!("building");
let action = Action::from(self.subcommand.clone());
- let built = {
- let dir = tempfile::tempdir()?;
- dir.path().to_owned()
- };
-
- let mut nix_build = MyCommand::new("nix");
- nix_build
- .args([
- "build",
- "--impure",
- "--json",
- // "--show-trace",
- "--no-link",
- ])
- .comparg("--out-link", &built)
- .arg(
- config.configuration_attr_name(&format!(
- "buildSystems.{}.{host}",
- action.build_attr()
- )),
- )
- .args(&config.nix_args);
-
- if self.privileged_build {
- nix_build = nix_build.sudo();
- }
-
- nix_build.run_nix().await.map_err(|e| {
+ let drv = config
+ .fleet_field
+ .select(nix_path!(.buildSystems.{action.build_attr()}.{&host}))
+ .await?;
+ let outputs = drv.build().await.map_err(|e| {
if action.build_attr() == "sdImage" {
info!("sd-image build failed");
info!("Make sure you have imported modulesPath/installer/sd-card/sd-image-<arch>[-installer].nix (For installer, you may want to check config)");
@@ -329,7 +302,9 @@
}
e
})?;
- let built = std::fs::canonicalize(built)?;
+ let out_output = outputs
+ .get("out")
+ .ok_or_else(|| anyhow!("system build should produce \"out\" output"))?;
match action {
Action::Upload { action } => {
@@ -342,7 +317,7 @@
.arg("sign")
.comparg("--key-file", "/etc/nix/private-key")
.arg("-r")
- .arg(&built);
+ .arg(out_output);
if let Err(e) = sign.sudo().run_nix().await {
warn!("Failed to sign store paths: {e}");
};
@@ -353,7 +328,7 @@
nix.arg("copy")
.arg("--substitute-on-destination")
.comparg("--to", format!("ssh-ng://{host}"))
- .arg(&built);
+ .arg(out_output);
match nix.run_nix().await {
Ok(()) => break,
Err(e) if tries < 3 => {
@@ -366,53 +341,22 @@
}
}
if let Some(action) = action {
- execute_upload(&self, &config, action, &host, built).await?
+ execute_upload(&self, &config, action, &host, out_output.clone()).await?
}
}
Action::Package(PackageAction::SdImage) => {
let mut out = current_dir()?;
out.push(format!("sd-image-{}", host));
- info!("building sd image to {:?}", out);
- let mut nix_build = MyCommand::new("nix");
- nix_build
- .args(["build", "--impure", "--no-link"])
- .comparg("--out-link", &out)
- .arg(config.configuration_attr_name(&format!("buildSystems.sdImage.{}", host,)))
- .args(&config.nix_args);
- if !self.fail_fast {
- nix_build.arg("--keep-going");
- }
- if self.privileged_build {
- nix_build = nix_build.sudo();
- }
-
- nix_build.run_nix().await?;
+ info!("linking sd image to {:?}", out);
+ symlink(out_output, out)?;
}
Action::Package(PackageAction::InstallationCd) => {
let mut out = current_dir()?;
out.push(format!("installation-cd-{}", host));
- info!("building sd image to {:?}", out);
- let mut nix_build = MyCommand::new("nix");
- nix_build
- .args(["build", "--impure", "--no-link"])
- .comparg("--out-link", &out)
- .arg(
- config.configuration_attr_name(&format!(
- "buildSystems.installationCd.{}",
- host,
- )),
- )
- .args(&config.nix_args);
- if !self.fail_fast {
- nix_build.arg("--keep-going");
- }
- if self.privileged_build {
- nix_build = nix_build.sudo();
- }
-
- nix_build.run_nix().await?;
+ info!("linking iso image to {:?}", out);
+ symlink(out_output, out)?;
}
};
Ok(())
cmds/fleet/src/cmds/info.rsdiffbeforeafterboth--- a/cmds/fleet/src/cmds/info.rs
+++ b/cmds/fleet/src/cmds/info.rs
@@ -1,6 +1,7 @@
use std::collections::BTreeSet;
use crate::host::Config;
+use crate::nix_path;
use anyhow::{ensure, Result};
use clap::Parser;
@@ -38,7 +39,7 @@
if !tagged.is_empty() {
let tags: Vec<String> = config
.fleet_field
- .get_field_deep(["configuredSystems", &host.name, "config", "tags"])
+ .select(nix_path!(.configuredSystems.{&host.name}.config.tags))
.await?
.as_json()
.await?;
@@ -64,7 +65,7 @@
let host = config.system_config(&host).await?;
if external {
out.extend(
- host.get_field_deep(["network", "externalIps"])
+ host.select(nix_path!(.network.externalIps))
.await?
.as_json::<Vec<String>>()
.await?,
@@ -72,7 +73,7 @@
}
if internal {
out.extend(
- host.get_field_deep(["network", "internalIps"])
+ host.select(nix_path!(.network.internalIps))
.await?
.as_json::<Vec<String>>()
.await?,
cmds/fleet/src/cmds/secrets/mod.rsdiffbeforeafterboth--- a/cmds/fleet/src/cmds/secrets/mod.rs
+++ b/cmds/fleet/src/cmds/secrets/mod.rs
@@ -1,6 +1,6 @@
use crate::{
fleetdata::{FleetSecret, FleetSharedSecret},
- host::Config,
+ host::Config, nix_path,
};
use anyhow::{bail, ensure, Context, Result};
use chrono::Utc;
@@ -339,7 +339,7 @@
let mut data = config.shared_secret(name)?;
let expected_owners: Vec<String> = config
.config_field
- .get_json_deep(["sharedSecrets", name, "expectedOwners"])
+ .get_json_deep(nix_path!(sharedSecrets.{name}.expectedOwners))
.await?;
if expected_owners.is_empty() {
warn!("secret was removed from fleet config: {name}, removing from data");
@@ -352,7 +352,7 @@
if set != expected_set {
let owner_dependent: bool = config
.config_field
- .get_json_deep(["sharedSecrets", name, "ownerDependent"])
+ .get_json_deep(nix_path!(.sharedSecrets.{name}.ownerDependent))
.await?;
if !owner_dependent {
warn!("reencrypting secret '{name}' for new owner set");
cmds/fleet/src/command.rsdiffbeforeafterboth--- a/cmds/fleet/src/command.rs
+++ b/cmds/fleet/src/command.rs
@@ -1,5 +1,4 @@
use std::{
- borrow::Cow,
collections::HashMap,
ffi::OsStr,
process::Stdio,
@@ -247,10 +246,14 @@
pub struct NixHandler {
spans: HashMap<u64, Span>,
}
-fn process_message(m: &str) -> Cow<'_, str> {
+fn process_message(m: &str) -> String {
static OSC_CLEANER: Lazy<Regex> =
Lazy::new(|| Regex::new(r"\x1B\]([^\x07\x1C]*[\x07\x1C])?|\r").unwrap());
- OSC_CLEANER.replace_all(m, "")
+ static DETABBER: Lazy<Regex> = Lazy::new(|| Regex::new(r"\t").unwrap());
+ let m = OSC_CLEANER.replace_all(m, "");
+ // Indicatif can't format tabs. This is not the correct tab formatting, as correct one should be aligned,
+ // and not just be replaced with the constant number of spaces, but it's ok for now, as statuses are single-line.
+ DETABBER.replace_all(m.as_ref(), " ").to_string()
}
impl Handler for NixHandler {
fn handle_line(&mut self, e: &str) {
cmds/fleet/src/host.rsdiffbeforeafterboth1use std::{2 env::current_dir,3 ffi::OsString,4 io::Write,5 ops::Deref,6 path::PathBuf,7 sync::{Arc, Mutex, MutexGuard},8};910use anyhow::{anyhow, bail, Context, Result};11use clap::{ArgGroup, Parser};12use openssh::SessionBuilder;13use tempfile::NamedTempFile;1415use crate::{16 better_nix_eval::{Field, NixSessionPool},17 command::MyCommand,18 fleetdata::{FleetData, FleetSecret, FleetSharedSecret},19};2021pub struct FleetConfigInternals {22 pub local_system: String,23 pub directory: PathBuf,24 pub opts: FleetOpts,25 pub data: Mutex<FleetData>,26 pub nix_args: Vec<OsString>,27 // fleetConfigurations.<name>28 pub fleet_field: Field,29 // fleet_config.configUnchecked30 pub config_field: Field,31}3233#[derive(Clone)]34pub struct Config(Arc<FleetConfigInternals>);3536impl Deref for Config {37 type Target = FleetConfigInternals;3839 fn deref(&self) -> &Self::Target {40 &self.041 }42}4344pub struct ConfigHost {45 pub name: String,46}47impl ConfigHost {48 async fn open_session(&self) -> Result<openssh::Session> {49 let mut session = SessionBuilder::default();5051 session52 .connect(&self.name)53 .await54 .map_err(|e| anyhow!("ssh error: {e}"))55 }56}5758impl Config {59 pub fn should_skip(&self, host: &str) -> bool {60 if !self.opts.skip.is_empty() {61 self.opts.skip.iter().any(|h| h as &str == host)62 } else if !self.opts.only.is_empty() {63 !self.opts.only.iter().any(|h| h as &str == host)64 } else {65 false66 }67 }68 pub fn is_local(&self, host: &str) -> bool {69 self.opts.localhost.as_ref().map(|s| s as &str) == Some(host)70 }7172 pub async fn run_on(&self, host: &str, mut command: MyCommand, sudo: bool) -> Result<()> {73 if sudo {74 command = command.sudo();75 }76 if !self.is_local(host) {77 command = command.ssh(host);78 }79 command.run().await80 }81 pub async fn run_string_on(82 &self,83 host: &str,84 mut command: MyCommand,85 sudo: bool,86 ) -> Result<String> {87 if sudo {88 command = command.sudo();89 }90 if !self.is_local(host) {91 command = command.ssh(host);92 }93 command.run_string().await94 }9596 pub fn configuration_attr_name(&self, name: &str) -> OsString {97 let mut str = self.directory.as_os_str().to_owned();98 str.push("#");99 str.push(&format!(100 "fleetConfigurations.default.{}.{}",101 self.local_system, name102 ));103 str104 }105106 pub async fn list_hosts(&self) -> Result<Vec<ConfigHost>> {107 let names = self108 .fleet_field109 .get_field_deep(["configuredHosts"])110 .await?111 .list_fields()112 .await?;113 let mut out = vec![];114 for name in names {115 out.push(ConfigHost { name })116 }117 Ok(out)118 }119 pub async fn system_config(&self, host: &str) -> Result<Field> {120 self.fleet_field121 .get_field_deep(["configuredSystems", host, "config"])122 .await123 }124125 pub(super) fn data(&self) -> MutexGuard<FleetData> {126 self.data.lock().unwrap()127 }128 pub(super) fn data_mut(&self) -> MutexGuard<FleetData> {129 self.data.lock().unwrap()130 }131 /// Shared secrets configured in fleet.nix or in flake132 pub async fn list_configured_shared(&self) -> Result<Vec<String>> {133 self.config_field134 .get_field("sharedSecrets")135 .await?136 .list_fields()137 .await138 }139 /// Shared secrets configured in fleet.nix140 pub fn list_shared(&self) -> Vec<String> {141 let data = self.data();142 data.shared_secrets.keys().cloned().collect()143 }144 pub fn has_shared(&self, name: &str) -> bool {145 let data = self.data();146 data.shared_secrets.contains_key(name)147 }148 pub fn replace_shared(&self, name: String, shared: FleetSharedSecret) {149 let mut data = self.data_mut();150 data.shared_secrets.insert(name.to_owned(), shared);151 }152 pub fn remove_shared(&self, secret: &str) {153 let mut data = self.data_mut();154 data.shared_secrets.remove(secret);155 }156157 pub fn has_secret(&self, host: &str, secret: &str) -> bool {158 let data = self.data();159 let Some(host_secrets) = data.host_secrets.get(host) else {160 return false;161 };162 host_secrets.contains_key(secret)163 }164 pub fn insert_secret(&self, host: &str, secret: String, value: FleetSecret) {165 let mut data = self.data_mut();166 let host_secrets = data.host_secrets.entry(host.to_owned()).or_default();167 host_secrets.insert(secret, value);168 }169170 pub async fn decrypt_on_host(&self, host: &str, data: Vec<u8>) -> Result<Vec<u8>> {171 let data = z85::encode(&data);172 let mut cmd = MyCommand::new("fleet-install-secrets");173 cmd.arg("decrypt").eqarg("--secret", data);174 cmd = cmd.sudo().ssh(host);175 let encoded = cmd176 .run_string()177 .await178 .context("failed to call remote host for decrypt")?179 .trim()180 .to_owned();181 z85::decode(encoded).context("bad encoded data? outdated host?")182 }183 pub async fn reencrypt_on_host(184 &self,185 host: &str,186 data: Vec<u8>,187 targets: Vec<String>,188 ) -> Result<Vec<u8>> {189 let data = z85::encode(&data);190 let mut recmd = MyCommand::new("fleet-install-secrets");191 recmd.arg("reencrypt").eqarg("--secret", data);192 for target in targets {193 recmd.eqarg("--targets", target);194 }195 recmd = recmd.sudo().ssh(host);196 let encoded = recmd197 .run_string()198 .await199 .context("failed to call remote host for decrypt")?200 .trim()201 .to_owned();202 z85::decode(encoded).context("bad encoded data? outdated host?")203 }204205 pub fn host_secret(&self, host: &str, secret: &str) -> Result<FleetSecret> {206 let data = self.data();207 let Some(host_secrets) = data.host_secrets.get(host) else {208 bail!("no secrets for machine {host}");209 };210 let Some(secret) = host_secrets.get(secret) else {211 bail!("machine {host} has no secret {secret}");212 };213 Ok(secret.clone())214 }215 pub fn shared_secret(&self, secret: &str) -> Result<FleetSharedSecret> {216 let data = self.data();217 let Some(secret) = data.shared_secrets.get(secret) else {218 bail!("no shared secret {secret}");219 };220 Ok(secret.clone())221 }222 pub async fn shared_secret_expected_owners(&self, secret: &str) -> Result<Vec<String>> {223 self.config_field224 .get_field_deep(["sharedSecrets", secret, "expectedOwners"])225 .await?226 .as_json()227 .await228 }229230 pub fn save(&self) -> Result<()> {231 let mut tempfile = NamedTempFile::new_in(self.directory.clone())?;232 let data = nixlike::serialize(&self.data() as &FleetData)?;233 tempfile.write_all(234 format!(235 "# This file contains fleet state and shouldn't be edited by hand\n\n{}\n\n# vim: ts=2 et nowrap\n",236 data237 )238 .as_bytes(),239 )?;240 let mut fleet_data_path = self.directory.clone();241 fleet_data_path.push("fleet.nix");242 tempfile.persist(fleet_data_path)?;243 Ok(())244 }245}246247#[derive(Parser, Clone)]248#[clap(group = ArgGroup::new("target_hosts"))]249pub struct FleetOpts {250 /// All hosts except those would be skipped251 #[clap(long, number_of_values = 1, group = "target_hosts")]252 only: Vec<String>,253254 /// Hosts to skip255 #[clap(long, number_of_values = 1, group = "target_hosts")]256 skip: Vec<String>,257258 /// Host, which should be threaten as current machine259 #[clap(long)]260 pub localhost: Option<String>,261262 // TODO: unhardcode x86_64-linux263 /// Override detected system for host, to perform builds via264 /// binfmt-declared qemu instead of trying to crosscompile265 #[clap(long, default_value = "detect")]266 pub local_system: String,267}268269impl FleetOpts {270 pub async fn build(mut self, nix_args: Vec<OsString>) -> Result<Config> {271 if self.localhost.is_none() {272 self.localhost273 .replace(hostname::get().unwrap().to_str().unwrap().to_owned());274 }275 let directory = current_dir()?;276277 let pool = NixSessionPool::new(directory.as_os_str().to_owned(), nix_args.clone()).await?;278 let root_field = pool.get().await?;279280 if self.local_system == "detect" {281 let builtins_field = Field::field(root_field.clone(), "builtins").await?;282 let system = builtins_field.get_field("currentSystem").await?;283 self.local_system = system.as_json().await?;284 }285 let local_system = self.local_system.clone();286287 let fleet_root = Field::field(root_field, "fleetConfigurations").await?;288289 let fleet_field = fleet_root290 .get_field_deep(["default", &local_system])291 .await?;292 let config_field = fleet_field.get_field("configUnchecked").await?;293294 let mut fleet_data_path = directory.clone();295 fleet_data_path.push("fleet.nix");296 let bytes = std::fs::read_to_string(fleet_data_path)?;297 let data = nixlike::parse_str(&bytes)?;298299 Ok(Config(Arc::new(FleetConfigInternals {300 opts: self,301 directory,302 data,303 local_system,304 nix_args,305 fleet_field,306 config_field,307 })))308 }309}cmds/fleet/src/main.rsdiffbeforeafterboth--- a/cmds/fleet/src/main.rs
+++ b/cmds/fleet/src/main.rs
@@ -1,3 +1,4 @@
+#![recursion_limit = "512"]
#![feature(try_blocks)]
pub(crate) mod cmds;
flake.nixdiffbeforeafterboth--- a/flake.nix
+++ b/flake.nix
@@ -19,6 +19,7 @@
rustPlatform = pkgs.makeRustPlatform { cargo = rust; rustc = rust; };
in
{
+ packages = (import ./pkgs) pkgs pkgs;
devShell = (pkgs.mkShell.override { stdenv = llvmPkgs.stdenv; }) {
nativeBuildInputs = with pkgs; [
rust