Skip to content

--file argument analogous to nix build & friends #320

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion nix/tests/default.nix
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,12 @@ in {
isLocal = false;
deployArgs = "-s .#server --remote-build -- --offline";
};
non-flake-remote-build = mkTest {
name = "non-flake-remote-build";
isLocal = false;
flakes = false;
deployArgs = "-s .#server --remote-build";
};
# Deployment with overridden options
options-overriding = mkTest {
name = "options-overriding";
Expand All @@ -158,8 +164,13 @@ in {
};
# Deployment using a non-flake nix
non-flake-build = mkTest {
name = "local-build";
name = "non-flake-build";
flakes = false;
deployArgs = "-s .#server";
};
non-flake-with-flakes = mkTest {
name = "non-flake-with-flakes";
flakes = true;
deployArgs = "--file . --targets server";
};
}
33 changes: 28 additions & 5 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ pub struct Opts {
/// A list of flakes to deploy alternatively
#[clap(long, group = "deploy")]
targets: Option<Vec<String>>,
/// Treat targets as files instead of flakes
#[clap(short, long)]
file: Option<String>,
/// Check signatures when using `nix copy`
#[clap(short, long)]
checksigs: bool,
Expand Down Expand Up @@ -672,15 +675,28 @@ pub async fn run(args: Option<&ArgMatches>) -> Result<(), RunError> {
error!("Cannot use both --dry-activate & --boot!");
}

// if opts.file.is_some() && (opts.targets.is_some() || opts.target.is_some()) {
// error!("When using --file, only one target is supported!")
// }

let deploys = opts
.clone()
.targets
.unwrap_or_else(|| vec![opts.clone().target.unwrap_or_else(|| ".".to_string())]);

let deploy_flakes: Vec<DeployFlake> = deploys
let deploy_flakes: Vec<DeployFlake> =
if let Some(file) = &opts.file {
deploys
.iter()
.map(|f| deploy::parse_file(file.as_str(), f.as_str()))
.collect::<Result<Vec<DeployFlake>, ParseFlakeError>>()?
}
else {
deploys
.iter()
.map(|f| deploy::parse_flake(f.as_str()))
.collect::<Result<Vec<DeployFlake>, ParseFlakeError>>()?;
.collect::<Result<Vec<DeployFlake>, ParseFlakeError>>()?
};

let cmd_overrides = deploy::CmdOverrides {
ssh_user: opts.ssh_user,
Expand All @@ -700,22 +716,29 @@ pub async fn run(args: Option<&ArgMatches>) -> Result<(), RunError> {
};

let supports_flakes = test_flake_support().await.map_err(RunError::FlakeTest)?;
let do_not_want_flakes = opts.file.is_some();

if !supports_flakes {
warn!("A Nix version without flakes support was detected, support for this is work in progress");
}

if do_not_want_flakes {
warn!("The --file option for deployments without flakes is experimental");
}

let using_flakes = supports_flakes && !do_not_want_flakes;

if !opts.skip_checks {
for deploy_flake in &deploy_flakes {
check_deployment(supports_flakes, deploy_flake.repo, &opts.extra_build_args).await?;
check_deployment(using_flakes, deploy_flake.repo, &opts.extra_build_args).await?;
}
}
let result_path = opts.result_path.as_deref();
let data = get_deployment_data(supports_flakes, &deploy_flakes, &opts.extra_build_args).await?;
let data = get_deployment_data(using_flakes, &deploy_flakes, &opts.extra_build_args).await?;
run_deploy(
deploy_flakes,
data,
supports_flakes,
using_flakes,
opts.checksigs,
opts.interactive,
&cmd_overrides,
Expand Down
59 changes: 59 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,65 @@ fn test_parse_flake() {
);
}

pub fn parse_file<'a>(file: &'a str, attribute: &'a str) -> Result<DeployFlake<'a>, ParseFlakeError> {
let repo = file; //format!("./{file}");

let mut node: Option<String> = None;
let mut profile: Option<String> = None;

let ast = rnix::parse(attribute);

let first_child = match ast.root().node().first_child() {
Some(x) => x,
None => {
return Ok(DeployFlake {
repo: &repo,
node: None,
profile: None,
})
}
};

let mut node_over = false;

for entry in first_child.children_with_tokens() {
let x: Option<String> = match (entry.kind(), node_over) {
(TOKEN_DOT, false) => {
node_over = true;
None
}
(TOKEN_DOT, true) => {
return Err(ParseFlakeError::PathTooLong);
}
(NODE_IDENT, _) => Some(entry.into_node().unwrap().text().to_string()),
(TOKEN_IDENT, _) => Some(entry.into_token().unwrap().text().to_string()),
(NODE_STRING, _) => {
let c = entry
.into_node()
.unwrap()
.children_with_tokens()
.nth(1)
.unwrap();

Some(c.into_token().unwrap().text().to_string())
}
_ => return Err(ParseFlakeError::Unrecognized),
};

if !node_over {
node = x;
} else {
profile = x;
}
}

Ok(DeployFlake {
repo: &repo,
node,
profile,
})
}

#[derive(Debug, Clone)]
pub struct DeployData<'a> {
pub node_name: &'a str,
Expand Down
13 changes: 7 additions & 6 deletions src/push.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//
// SPDX-License-Identifier: MPL-2.0

use log::{debug, info};
use log::{debug, info, warn};
use std::collections::HashMap;
use std::path::Path;
use std::process::Stdio;
Expand Down Expand Up @@ -41,8 +41,6 @@ pub enum PushProfileError {
Copy(std::io::Error),
#[error("Nix copy command resulted in a bad exit code: {0:?}")]
CopyExit(Option<i32>),
#[error("The remote building option is not supported when using legacy nix")]
RemoteBuildWithLegacyNix,

#[error("Failed to run Nix path-info command: {0}")]
PathInfo(std::io::Error),
Expand Down Expand Up @@ -169,7 +167,9 @@ pub async fn build_profile_remotely(data: &PushProfileData<'_>, derivation_name:


// copy the derivation to remote host so it can be built there
let copy_command_status = Command::new("nix").arg("copy")
let copy_command_status = Command::new("nix")
.arg("--experimental-features").arg("nix-command")
.arg("copy")
.arg("-s") // fetch dependencies from substitures, not localhost
.arg("--to").arg(&store_address)
.arg("--derivation").arg(derivation_name)
Expand All @@ -186,6 +186,7 @@ pub async fn build_profile_remotely(data: &PushProfileData<'_>, derivation_name:

let mut build_command = Command::new("nix");
build_command
.arg("--experimental-features").arg("nix-command")
.arg("build").arg(derivation_name)
.arg("--eval-store").arg("auto")
.arg("--store").arg(&store_address)
Expand Down Expand Up @@ -244,7 +245,7 @@ pub async fn build_profile(data: PushProfileData<'_>) -> Result<(), PushProfileE
.next()
.ok_or(PushProfileError::ShowDerivationEmpty)?;

let new_deriver = &if data.supports_flakes {
let new_deriver = &if data.supports_flakes || data.deploy_data.merged_settings.remote_build.unwrap_or(false) {
// Since nix 2.15.0 'nix build <path>.drv' will build only the .drv file itself, not the
// derivation outputs, '^out' is used to refer to outputs explicitly
deriver.to_owned().to_string() + "^out"
Expand Down Expand Up @@ -276,7 +277,7 @@ pub async fn build_profile(data: PushProfileData<'_>) -> Result<(), PushProfileE
};
if data.deploy_data.merged_settings.remote_build.unwrap_or(false) {
if !data.supports_flakes {
return Err(PushProfileError::RemoteBuildWithLegacyNix)
warn!("remote builds using non-flake nix are experimental");
}

build_profile_remotely(&data, &deriver).await?;
Expand Down