// nixos-config - My current NixOS configuration // // Copyright (C) 2025 Benedikt Peetz // SPDX-License-Identifier: GPL-3.0-or-later // // This file is part of my nixos-config. // // You should have received a copy of the License along with this program. // If not, see . use std::{ ops::Deref, process::{Command, Stdio}, thread, time::Duration, }; use anyhow::{Context, Result, bail}; use clap::{CommandFactory, Parser}; use serde_json::Value; use tempfile::NamedTempFile; pub mod cli; use crate::cli::CliArgs; macro_rules! cmd { ($dry_run:expr, $name:literal, $($arg:expr),*) => { cmd!($dry_run, @pass_throu $name, $($arg),*) }; ($dry_run:expr, @$mode:ident $name:literal, $($arg:expr),*) => {{ let cmd_name = format!("\x1b[1;96m{}\x1b[0m {}", $name, [$($arg),*].join(" ")); eprintln!("# {cmd_name}"); if !$dry_run { let output = Command::new($name) .args([ $($arg),* ]) .stdout(cmd!(@mk_mode_1 $mode)) .stderr(Stdio::inherit()) .current_dir("/etc/nixos") .output().with_context(|| format!("Failed to spawn `{cmd_name}`"))?; if !output.status.success() { bail!("`{cmd_name}` failed."); } cmd!{@mk_mode_2 $mode, output, cmd_name} } else { cmd!(@mk_mode_3 $mode) } }}; (@mk_mode_1 capture) => {Stdio::piped()}; (@mk_mode_2 capture, $output:expr, $cmd_name:expr) => {{ String::from_utf8($output.stdout) .with_context(|| format!("Command `{}` failed to produce valid utf8", $cmd_name))? }}; (@mk_mode_3 capture) => {unreachable!()}; (@mk_mode_1 pass_throu) => {Stdio::inherit()}; (@mk_mode_2 pass_throu, $output:expr, $cmd_name:expr) => {}; (@mk_mode_3 pass_throu) => {()}; } fn msg(message: &'static str) { eprintln!("\x1b[1;96m==>\x1b[0m\x1b[1;93m {message}\x1b[0m"); } fn msg2(message: impl Deref) { eprintln!("\x1b[1;96m ->\x1b[0m\x1b[1;93m {}\x1b[0m", &*message); } fn main() -> Result<(), anyhow::Error> { clap_complete::CompleteEnv::with_factory(CliArgs::command).complete(); let args = CliArgs::parse(); msg("Starting system update..."); cmd!(args.dry_run, "git", "remote", "update", "origin", "--prune"); if let Some(branch) = args.branch { cmd!(args.dry_run, "git", "switch", &branch); msg2(format!("Switched to branch '{branch}'")); } msg2("Updating git repository..."); cmd!(args.dry_run, "git", "pull", "--rebase"); let handle = thread::spawn(get_remote_default_branch); msg2("Updating system..."); cmd!( args.dry_run, "nixos-rebuild", args.mode.to_string().as_str() ); // Give the `nixos-rebuild` some time to finish thread::sleep(Duration::from_millis(200)); let remote_default_branch = handle .join() .unwrap() .context("Failed to determine default remote branch")?; cmd!(args.dry_run, "git", "switch", &remote_default_branch); msg2(format!("Switched to branch '{remote_default_branch}'")); msg("Setting @saved boot entry to new generation.."); let new_generation = { let base = cmd!(false, @capture "bootctl", "list", "--json=short"); let json: Value = serde_json::from_str(&base).context("Failed to parse `bootctl` output.")?; let mut nixos_generations = vec![]; for part in json.as_array().unwrap() { if part.get("sortKey").map(Value::as_str) == Some(Some("lanza")) { nixos_generations.push(part.get("id").unwrap().as_str().unwrap().to_owned()); } } nixos_generations.first().unwrap().to_owned() }; let last_used_variable_name = { let mut name = None; let all = cmd!(false, @capture "efivar", "--list"); for line in all.trim().lines() { if line.contains("LoaderEntryLastBooted") { name = Some(line.to_owned()); } } name.unwrap() }; let data_file = { use std::io::Write; let mut named = NamedTempFile::new()?; let mut data = Vec::with_capacity(new_generation.len() * 2); for ch in new_generation.chars() { data.push(ch as u8); data.push(b'\0'); } data.push(b'\0'); data.push(b'\0'); named.write_all(data.as_slice())?; named }; cmd!( args.dry_run, "efivar", "--name", &last_used_variable_name, "--write", "--datafile", data_file.path().as_os_str().to_str().unwrap() ); data_file.close()?; msg("Finished Update!"); Ok(()) } fn get_remote_default_branch() -> Result { let mut final_output = None; let output = cmd!(false, @capture "git", "remote", "show", "origin"); for line in output.trim().lines() { if line.contains("HEAD") { let base = line.split(':').skip(1).take(1).last().unwrap(); let base = base.replacen(" *", "", 1); let base = base .chars() .rev() .collect::() .replacen(" *", "", 1) .chars() .rev() .collect::() .trim() .to_owned(); final_output = Some(base); } } Ok(final_output.unwrap()) } #[cfg(test)] mod test { use clap::CommandFactory; #[test] fn verify_cli() { super::CliArgs::command().debug_assert(); } }