summaryrefslogtreecommitdiffstats
path: root/pkgs/by-name/fu/fupdate-sys2/src
diff options
context:
space:
mode:
authorSoispha Peetz <soispha@b-peetz.de>2026-12-03 23:12:40 +0100
committerSoispha Peetz <soispha@b-peetz.de>2026-12-03 23:19:04 +0100
commit605f131560a65af3448f02fb3990c1967ad488d0 (patch)
tree784938bd4532b8199b927adb41fc840da493940c /pkgs/by-name/fu/fupdate-sys2/src
parentpkgs/rollup: Also check if the `owner`'s tree is dirty in the general check (diff)
downloadnixos-config-605f131560a65af3448f02fb3990c1967ad488d0.zip
pkgs/fupdate-sys2: Re-implement in rust
Does not yet remove the shell version, because I'm not fully sure the rust version works. The rust version should also set the new boot entry forever, and not just for exactly one boot.
Diffstat (limited to 'pkgs/by-name/fu/fupdate-sys2/src')
-rw-r--r--pkgs/by-name/fu/fupdate-sys2/src/cli.rs84
-rw-r--r--pkgs/by-name/fu/fupdate-sys2/src/main.rs193
2 files changed, 277 insertions, 0 deletions
diff --git a/pkgs/by-name/fu/fupdate-sys2/src/cli.rs b/pkgs/by-name/fu/fupdate-sys2/src/cli.rs
new file mode 100644
index 00000000..cf8a796e
--- /dev/null
+++ b/pkgs/by-name/fu/fupdate-sys2/src/cli.rs
@@ -0,0 +1,84 @@
+// nixos-config - My current NixOS configuration
+//
+// Copyright (C) 2025 Benedikt Peetz <benedikt.peetz@b-peetz.de>
+// 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 <https://www.gnu.org/licenses/gpl-3.0.txt>.
+
+use core::fmt;
+use std::{ffi::OsStr, process::Command};
+
+use clap::{Parser, ValueEnum};
+use clap_complete::{CompletionCandidate, engine::ArgValueCompleter};
+
+/// This is a Nix flake update manager.
+#[derive(Parser, Debug)]
+#[command(author, version, about)]
+pub struct CliArgs {
+ /// The branch to update from.
+ #[arg(short, long, add = ArgValueCompleter::new(get_branches))]
+ pub branch: Option<String>,
+
+ /// The mode to update with.
+ #[arg(short, long, default_value_t = Mode::Switch)]
+ pub mode: Mode,
+
+ /// Don't actually make changes.
+ #[arg(short, long)]
+ pub dry_run: bool,
+}
+
+#[derive(Debug, Clone, Copy, ValueEnum)]
+pub enum Mode {
+ Switch,
+ Boot,
+ Test,
+ Build,
+ DryBuild,
+ DryActivate,
+ Edit,
+ Repl,
+ BuildVm,
+ BuildVmWithBootloader,
+}
+
+impl fmt::Display for Mode {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", format!("{self:?}").to_lowercase())
+ }
+}
+
+fn get_branches(current: &OsStr) -> Vec<CompletionCandidate> {
+ let mut output = vec![];
+
+ let Some(current) = current.to_str() else {
+ return output;
+ };
+
+ let Ok(git_output) = Command::new("git")
+ .args(["branch", "--list", "--format", "'%(refname:short)'"])
+ .current_dir("/etc/nixos")
+ .output()
+ else {
+ return output;
+ };
+
+ if !git_output.status.success() {
+ return output;
+ }
+
+ let Ok(possible) = String::from_utf8(git_output.stdout) else {
+ return output;
+ };
+
+ for possible in possible.trim().split('\n') {
+ if possible.starts_with(current) {
+ output.push(CompletionCandidate::new(possible));
+ }
+ }
+
+ output
+}
diff --git a/pkgs/by-name/fu/fupdate-sys2/src/main.rs b/pkgs/by-name/fu/fupdate-sys2/src/main.rs
new file mode 100644
index 00000000..d2dd19f3
--- /dev/null
+++ b/pkgs/by-name/fu/fupdate-sys2/src/main.rs
@@ -0,0 +1,193 @@
+// nixos-config - My current NixOS configuration
+//
+// Copyright (C) 2025 Benedikt Peetz <benedikt.peetz@b-peetz.de>
+// 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 <https://www.gnu.org/licenses/gpl-3.0.txt>.
+
+use std::{
+ ops::Deref,
+ process::{Command, Stdio},
+ thread,
+};
+
+use anyhow::{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),*) => {{
+ eprintln!("# \x1b[1;96m{}\x1b[0m {}", $name, [$($arg),*].join(" "));
+
+ if $dry_run {
+ String::new()
+ } else {
+ let output = Command::new($name)
+ .args([
+ $($arg),*
+ ])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::inherit())
+ .current_dir("/etc/nixos")
+ .output()?;
+
+ if !output.status.success() {
+ bail!("`\x1b[1;96m{}\x1b[0m {}` failed.", $name, [$($arg),*].join(" "));
+ }
+
+ String::from_utf8(output.stdout)?
+ }
+ }};
+}
+
+fn msg(message: &'static str) {
+ eprintln!("\x1b[1;96m==>\x1b[0m\x1b[1;93m {message}\x1b[0m");
+}
+fn msg2(message: impl Deref<Target = str>) {
+ 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()
+ );
+
+ let remote_default_branch = handle.join().unwrap()?;
+ cmd!(args.dry_run, "git", "switch", &remote_default_branch);
+ msg2(format!("Switched to branch '{remote_default_branch}'"));
+
+ msg("Setting oneshot boot entry to new generation..");
+
+ let new_generation = {
+ let base = cmd!(false, "bootctl", "list", "--json=short");
+
+ let json: Value = serde_json::from_str(&base)?;
+
+ 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, "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())?;
+
+ let str = cmd!(
+ false,
+ "hexdump",
+ "-C",
+ named.path().as_os_str().to_str().unwrap()
+ );
+ eprintln!("{str}");
+
+ 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<String> {
+ let mut final_output = None;
+
+ let output = cmd!(false, "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::<String>()
+ .replacen(" *", "", 1)
+ .chars()
+ .rev()
+ .collect::<String>()
+ .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();
+ }
+}