git.delta.rocks / jrsonnet / refs/commits / 7de62040eec5

difftreelog

refactor replace builtins.currentSystem with pure alternative

Yaroslav Bolyukin2024-11-30parent: #3e7b063.patch.diff
in: trunk

5 files changed

addedcrates/fleet-base/build.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/fleet-base/build.rs
@@ -0,0 +1,15 @@
+use std::env;
+
+fn main() {
+	let target = env::var("TARGET").expect("TARGET env var is set by cargo");
+
+	let nix_system = if target.starts_with("x86_64-unknown-linux-") {
+		"x86_64-linux"
+	} else if target.starts_with("aarch64-unknown-linux-") {
+		"aarch64-linux"
+	} else {
+		panic!("unknown nix system name for rust {target} triple!");
+	};
+
+	println!("cargo:rustc-env=NIX_SYSTEM={nix_system}");
+}
modifiedcrates/fleet-base/src/opts.rsdiffbeforeafterboth
--- a/crates/fleet-base/src/opts.rs
+++ b/crates/fleet-base/src/opts.rs
@@ -8,7 +8,7 @@
 
 use anyhow::Result;
 use clap::Parser;
-use nix_eval::{nix_go, nix_go_json, util::assert_warn, NixSessionPool, Value};
+use nix_eval::{nix_go, util::assert_warn, NixSessionPool, Value};
 use nom::{
 	bytes::complete::take_while1,
 	character::complete::char,
@@ -85,14 +85,16 @@
 
 	/// Override detected system for host, to perform builds via
 	/// binfmt-declared qemu instead of trying to crosscompile
-	// TODO: Remove, as it is not used anymore.
-	#[clap(long, default_value = "detect")]
+	#[clap(long, default_value = env!("NIX_SYSTEM"))]
 	pub local_system: String,
 }
 
 impl FleetOpts {
-	pub async fn filter_skipped(&self, hosts: impl IntoIterator<Item = ConfigHost>) -> Result<Vec<ConfigHost>> {
-		let mut out = Vec::new();	
+	pub async fn filter_skipped(
+		&self,
+		hosts: impl IntoIterator<Item = ConfigHost>,
+	) -> Result<Vec<ConfigHost>> {
+		let mut out = Vec::new();
 		for host in hosts {
 			if self.should_skip(&host).await? {
 				continue;
@@ -182,15 +184,15 @@
 	pub async fn build(&self, nix_args: Vec<OsString>) -> Result<Config> {
 		let directory = current_dir()?;
 
-		let pool = NixSessionPool::new(directory.as_os_str().to_owned(), nix_args.clone()).await?;
+		let pool = NixSessionPool::new(
+			directory.as_os_str().to_owned(),
+			nix_args.clone(),
+			self.local_system.clone(),
+		)
+		.await?;
 		let nix_session = pool.get().await?;
 
 		let builtins_field = Value::binding(nix_session.clone(), "builtins").await?;
-		let local_system = if self.local_system == "detect" {
-			nix_go_json!(builtins_field.currentSystem)
-		} else {
-			self.local_system.clone()
-		};
 
 		let mut fleet_data_path = directory.clone();
 		fleet_data_path.push("fleet.nix");
@@ -210,14 +212,14 @@
 
 		let default_pkgs = nix_go!(nixpkgs(Obj {
 			overlays,
-			system: local_system.clone(),
+			system: self.local_system.clone(),
 		}));
 
 		Ok(Config(Arc::new(FleetConfigInternals {
 			nix_session,
 			directory,
 			data,
-			local_system,
+			local_system: self.local_system.clone(),
 			nix_args,
 			config_field,
 			default_pkgs,
modifiedcrates/nix-eval/src/lib.rsdiffbeforeafterboth
--- a/crates/nix-eval/src/lib.rs
+++ b/crates/nix-eval/src/lib.rs
@@ -41,8 +41,8 @@
 
 #[instrument(skip(session, values))]
 async fn build_multiple(name: String, session: NixSession, values: Vec<Value>) -> Result<()> {
+	let system = session.0.lock().await.nix_system.clone();
 	let builtins = Value::binding(session, "builtins").await?;
-	let system = nix_go!(builtins.currentSystem);
 	let drv = nix_go!(builtins.derivation(Obj {
 		system,
 		name,
modifiedcrates/nix-eval/src/pool.rsdiffbeforeafterboth
before · crates/nix-eval/src/pool.rs
1use std::ffi::OsString;2use std::sync::{Arc, OnceLock};34use r2d2::Pool;56use crate::session::NixSessionInner;7use crate::{Error, NixSession, Result};89pub struct NixSessionPool(Pool<NixSessionPoolInner>);10impl NixSessionPool {11	pub async fn new(flake: OsString, nix_args: Vec<OsString>) -> Result<Self> {12		let inner = tokio::task::block_in_place(|| {13			r2d2::Builder::<NixSessionPoolInner>::new()14				.min_idle(Some(0))15				.build(NixSessionPoolInner { flake, nix_args })16		})?;17		Ok(Self(inner))18	}19	pub async fn get(&self) -> Result<NixSession> {20		let v = tokio::task::block_in_place(|| self.0.get())?;21		Ok(NixSession(Arc::new(tokio::sync::Mutex::new(v))))22	}23}2425pub(crate) struct NixSessionPoolInner {26	flake: OsString,27	nix_args: Vec<OsString>,28}2930impl r2d2::ManageConnection for NixSessionPoolInner {31	type Connection = NixSessionInner;32	type Error = Error;33	fn connect(&self) -> std::result::Result<Self::Connection, Self::Error> {34		let _v = TOKIO_RUNTIME35			.get()36			.expect("missed tokio runtime init!")37			.enter();38		Ok(futures::executor::block_on(NixSessionInner::new(39			self.flake.as_os_str(),40			self.nix_args.iter().map(OsString::as_os_str),41		))?)42	}4344	fn is_valid(&self, conn: &mut Self::Connection) -> std::result::Result<(), Self::Error> {45		let _v = TOKIO_RUNTIME46			.get()47			.expect("missed tokio runtime init!")48			.enter();49		let res = futures::executor::block_on(conn.execute_expression_number("2 + 2"))?;50		if res != 4 {51			// just in case, should fail much earlier52			return Err(Error::SessionInit("misbehaving session"));53		};54		Ok(())55	}5657	fn has_broken(&self, _conn: &mut Self::Connection) -> bool {58		false59	}60}61pub static TOKIO_RUNTIME: OnceLock<tokio::runtime::Handle> = OnceLock::new();
after · crates/nix-eval/src/pool.rs
1use std::{2	ffi::OsString,3	sync::{Arc, OnceLock},4};56use r2d2::Pool;78use crate::{session::NixSessionInner, Error, NixSession, Result};910pub struct NixSessionPool(Pool<NixSessionPoolInner>);11impl NixSessionPool {12	pub async fn new(flake: OsString, nix_args: Vec<OsString>, nix_system: String) -> Result<Self> {13		let inner = tokio::task::block_in_place(|| {14			r2d2::Builder::<NixSessionPoolInner>::new()15				.min_idle(Some(0))16				.build(NixSessionPoolInner {17					flake,18					nix_args,19					nix_system,20				})21		})?;22		Ok(Self(inner))23	}24	pub async fn get(&self) -> Result<NixSession> {25		let v = tokio::task::block_in_place(|| self.0.get())?;26		Ok(NixSession(Arc::new(tokio::sync::Mutex::new(v))))27	}28}2930pub(crate) struct NixSessionPoolInner {31	flake: OsString,32	nix_args: Vec<OsString>,33	pub(crate) nix_system: String,34}3536impl r2d2::ManageConnection for NixSessionPoolInner {37	type Connection = NixSessionInner;38	type Error = Error;39	fn connect(&self) -> std::result::Result<Self::Connection, Self::Error> {40		let _v = TOKIO_RUNTIME41			.get()42			.expect("missed tokio runtime init!")43			.enter();44		Ok(futures::executor::block_on(NixSessionInner::new(45			self.flake.as_os_str(),46			self.nix_args.iter().map(OsString::as_os_str),47			self.nix_system.clone(),48		))?)49	}5051	fn is_valid(&self, conn: &mut Self::Connection) -> std::result::Result<(), Self::Error> {52		let _v = TOKIO_RUNTIME53			.get()54			.expect("missed tokio runtime init!")55			.enter();56		let res = futures::executor::block_on(conn.execute_expression_number("2 + 2"))?;57		if res != 4 {58			// just in case, should fail much earlier59			return Err(Error::SessionInit("misbehaving session"));60		};61		Ok(())62	}6364	fn has_broken(&self, _conn: &mut Self::Connection) -> bool {65		false66	}67}68pub static TOKIO_RUNTIME: OnceLock<tokio::runtime::Handle> = OnceLock::new();
modifiedcrates/nix-eval/src/session.rsdiffbeforeafterboth
--- a/crates/nix-eval/src/session.rs
+++ b/crates/nix-eval/src/session.rs
@@ -206,6 +206,8 @@
 
 	next_id: u32,
 	pub(crate) free_list: Vec<u32>,
+
+	pub nix_system: String,
 }
 
 /// Discover inter-message repl delimiter
@@ -222,6 +224,7 @@
 	pub(crate) async fn new(
 		flake: &OsStr,
 		extra_args: impl IntoIterator<Item = &OsStr>,
+		nix_system: String,
 	) -> Result<Self> {
 		let mut cmd = Command::new("nix");
 		cmd.arg("repl")
@@ -280,6 +283,8 @@
 
 			next_id: 0,
 			free_list: vec![],
+
+			nix_system,
 		};
 		res.train().await?;
 		Ok(res)