1use std::process::Command;23use crate::{command::CommandExt, host::Config, nix::SYSTEMS_ATTRIBUTE};4use anyhow::Result;5use clap::Clap;6use log::info;78#[derive(Clap)]9#[clap(group = clap::ArgGroup::new("target"))]10pub struct BuildSystems {11 12 #[clap(long)]13 builders: Option<String>,14 15 #[clap(long)]16 jobs: Option<usize>,17 18 #[clap(long)]19 fail_fast: bool,20 #[clap(long)]21 privileged_build: bool,22 #[clap(subcommand)]23 subcommand: Option<Subcommand>,24}2526#[derive(Clap)]27enum Subcommand {28 29 Test,30 31 Boot,32 33 Switch,34}35impl Subcommand {36 fn should_switch_profile(&self) -> bool {37 matches!(self, Self::Test | Self::Switch)38 }39 fn name(&self) -> &'static str {40 match self {41 Self::Test => "test",42 Self::Boot => "boot",43 Self::Switch => "switch",44 }45 }46}4748impl BuildSystems {49 pub fn run(self, config: &Config) -> Result<()> {50 let hosts = config.list_hosts()?;5152 for host in hosts.iter() {53 if config.should_skip(host) {54 continue;55 }56 info!("Building host {}", host);57 let built = {58 let dir = tempfile::tempdir()?;59 dir.path().to_owned()60 };6162 let mut nix_build = if self.privileged_build {63 let mut out = Command::new("sudo");64 out.arg("nix");65 out66 } else {67 Command::new("nix")68 };69 nix_build70 .args(&["build", "--impure", "--no-link", "--out-link"])71 .arg(&built)72 .arg(format!(73 "{}.{}.config.system.build.toplevel",74 SYSTEMS_ATTRIBUTE, host,75 ));7677 if let Some(builders) = &self.builders {78 nix_build.arg("--builders").arg(builders);79 }80 if let Some(jobs) = &self.jobs {81 nix_build.arg("--max-jobs");82 nix_build.arg(format!("{}", jobs));83 }84 if !self.fail_fast {85 nix_build.arg("--keep-going");86 }8788 nix_build.inherit_stdio().run()?;89 let built = std::fs::canonicalize(built)?;90 info!("Built closure: {:?}", built);91 if !config.is_local(host) {92 info!("Uploading system closure");93 Command::new("nix")94 .args(&["copy", "--to"])95 .arg(format!("ssh://root@{}", host))96 .arg(&built)97 .inherit_stdio()98 .run()?;99 }100 if let Some(subcommand) = &self.subcommand {101 if subcommand.should_switch_profile() {102 info!("Switching generation");103 config104 .command_on(host, "nix-env", true)105 .args(&["-p", "/nix/var/nix/profiles/system", "--set"])106 .arg(&built)107 .inherit_stdio()108 .run()?;109 }110 info!("Executing activation script");111 let mut switch_script = built.clone();112 switch_script.push("bin");113 switch_script.push("switch-to-configuration");114 config115 .command_on(host, switch_script, true)116 .arg(subcommand.name())117 .inherit_stdio()118 .run()?;119 }120 }121 Ok(())122 }123}