Skip to content
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

Specific Env Vars and Edit Command #142

Closed
wants to merge 7 commits into from
Closed
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
25 changes: 25 additions & 0 deletions src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ use thiserror::Error;
use subprocess::{Exec, ExitStatus, Redirection};
use tracing::{debug, info};

use crate::interface::FlakeRef;

#[derive(Debug, derive_builder::Builder)]
#[builder(derive(Debug), setter(into))]
pub struct Command {
Expand Down Expand Up @@ -158,3 +160,26 @@ impl BuildCommand {
#[derive(Debug, Error)]
#[error("Command exited with status {0:?}")]
pub struct ExitError(ExitStatus);

pub fn edit(flakeref: FlakeRef) -> Result<()> {
let editor = std::env::var("EDITOR").expect("EDITOR not set");
edit_with(flakeref, editor)
}

pub fn edit_with(flakeref: FlakeRef, editor: String) -> Result<()> {
let mut pieces: Vec<&str> = flakeref.split('/').collect();
let mut final_piece: &str = pieces.remove(pieces.len() - 1);
final_piece = final_piece.split('#').next().unwrap();
pieces.push(final_piece);

let flakedir = pieces.join("/");

Exec::cmd(editor)
.args(&vec!["."])
.cwd(flakedir)
.stderr(Redirection::None)
.stdout(Redirection::None)
.join()?;

Ok(())
}
30 changes: 22 additions & 8 deletions src/home.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ use std::path::PathBuf;
use color_eyre::eyre::bail;
use color_eyre::Result;
use thiserror::Error;
use tracing::{debug, info, instrument};
use tracing::{debug, warn, info, instrument};

use crate::*;
use crate::{
interface::NHRunnable,
interface::{FlakeRef, HomeArgs, HomeRebuildArgs, HomeSubcommand},
interface::{FlakeRef, HomeArgs, HomeRebuildArgs, HomeSubcommand, HomeEditArgs},
util::{compare_semver, get_nix_version},
};

Expand All @@ -27,11 +27,20 @@ impl NHRunnable for HomeArgs {
HomeSubcommand::Switch(args) | HomeSubcommand::Build(args) => {
args.rebuild(&self.subcommand)
}
HomeSubcommand::Edit(args) => {
args.edit()
}
s => bail!("Subcommand {:?} not yet implemented", s),
}
}
}

impl HomeEditArgs {
fn edit(&self) -> Result<()> {
commands::edit(self.flakeref.clone())
}
}

impl HomeRebuildArgs {
fn rebuild(&self, action: &HomeSubcommand) -> Result<()> {
let out_dir = tempfile::Builder::new().prefix("nh-home-").tempdir()?;
Expand All @@ -42,22 +51,27 @@ impl HomeRebuildArgs {

let username = std::env::var("USER").expect("Couldn't get username");

let flakeref = self.flakeref.clone().or_else(|| {
warn!("NH_HOME_FLAKE not set");
std::env::var("FLAKE").ok().map(|s| FlakeRef(s))
}).unwrap_or("./".into());

let hm_config_name = match &self.configuration {
Some(name) => {
if configuration_exists(&self.common.flakeref, name)? {
if configuration_exists(&flakeref, name)? {
name.to_owned()
} else {
return Err(HomeRebuildError::ConfigName(name.to_owned()).into());
}
}
None => get_home_output(&self.common.flakeref, &username)?,
None => get_home_output(&flakeref, &username)?,
};

debug!("hm_config_name: {}", hm_config_name);

let flakeref = format!(
"{}#homeConfigurations.\"{}\".config.home.activationPackage",
&self.common.flakeref.deref(),
flakeref.deref(),
hm_config_name
);

Expand All @@ -77,7 +91,7 @@ impl HomeRebuildArgs {
}
}

update_args.push(&self.common.flakeref);
update_args.push(&flakeref);

debug!("nix_version: {:?}", nix_version);
debug!("update_args: {:?}", update_args);
Expand Down Expand Up @@ -149,7 +163,7 @@ impl HomeRebuildArgs {
drop(out_dir);

Ok(())
}
}
}

fn get_home_output<S: AsRef<str> + std::fmt::Display>(
Expand Down
30 changes: 25 additions & 5 deletions src/interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use color_eyre::Result;
use std::{ffi::OsString, ops::Deref, path::PathBuf};

#[derive(Debug, Clone, Default)]
pub struct FlakeRef(String);
pub struct FlakeRef(pub String);
impl From<&str> for FlakeRef {
fn from(s: &str) -> Self {
FlakeRef(s.to_string())
Expand Down Expand Up @@ -87,11 +87,19 @@ pub enum OsRebuildType {
Test(OsRebuildArgs),
/// Build the new configuration
Build(OsRebuildArgs),
/// Open default editor in the flake directory
Edit(OsEditArgs),
/// Show an overview of the system's info
#[command(hide = true)]
Info,
}

#[derive(Debug, Args)]
pub struct OsEditArgs {
#[arg(env = "NH_OS_FLAKE", value_hint = clap::ValueHint::DirPath)]
pub flakeref: FlakeRef,
}

#[derive(Debug, Args)]
pub struct OsRebuildArgs {
#[command(flatten)]
Expand All @@ -112,6 +120,9 @@ pub struct OsRebuildArgs {
/// Extra arguments passed to nix build
#[arg(last = true)]
pub extra_args: Vec<String>,

#[arg(env = "NH_OS_FLAKE", value_hint = clap::ValueHint::DirPath)]
pub flakeref: Option<FlakeRef>,
}

#[derive(Debug, Args)]
Expand All @@ -124,10 +135,6 @@ pub struct CommonRebuildArgs {
#[arg(long, short)]
pub ask: bool,

/// Flake reference to build
#[arg(env = "FLAKE", value_hint = clap::ValueHint::DirPath)]
pub flakeref: FlakeRef,

/// Update flake inputs before building specified configuration
#[arg(long, short = 'u')]
pub update: bool,
Expand Down Expand Up @@ -246,6 +253,9 @@ pub enum HomeSubcommand {
/// Will check the current $USER and $(hostname) to determine which output to build, unless -c is passed
Build(HomeRebuildArgs),

/// Open default editor in flake directory
Edit(HomeEditArgs),

/// Show an overview of the installation
#[command(hide(true))]
Info,
Expand All @@ -268,6 +278,15 @@ pub struct HomeRebuildArgs {
/// Move existing files by backing up with the extension
#[arg(long, short = 'b')]
pub backup_extension: Option<String>,

#[arg(env = "NH_HOME_FLAKE", value_hint = clap::ValueHint::DirPath)]
pub flakeref: Option<FlakeRef>,
}

#[derive(Debug, Args)]
pub struct HomeEditArgs {
#[arg(env = "NH_HOME_FLAKE", value_hint = clap::ValueHint::DirPath)]
pub flakeref: FlakeRef,
}

#[derive(Debug, Parser)]
Expand All @@ -277,3 +296,4 @@ pub struct CompletionArgs {
#[arg(long, short)]
pub shell: clap_complete::Shell,
}

22 changes: 17 additions & 5 deletions src/nixos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ use std::ops::Deref;
use color_eyre::eyre::{bail, Context};
use color_eyre::Result;

use tracing::{debug, info};
use tracing::{debug, warn, info};

use crate::interface::NHRunnable;
use crate::interface::OsRebuildType::{self, Boot, Build, Switch, Test};
use crate::interface::{self, OsRebuildArgs};
use crate::interface::OsRebuildType::{self, Boot, Build, Switch, Test, Edit};
use crate::interface::{self, OsRebuildArgs, FlakeRef, OsEditArgs};
use crate::util::{compare_semver, get_nix_version};
use crate::*;

Expand All @@ -20,11 +20,18 @@ impl NHRunnable for interface::OsArgs {
fn run(&self) -> Result<()> {
match &self.action {
Switch(args) | Boot(args) | Test(args) | Build(args) => args.rebuild(&self.action),
Edit(args) => args.edit(),
s => bail!("Subcommand {:?} not yet implemented", s),
}
}
}

impl OsEditArgs {
fn edit(&self) -> Result<()> {
commands::edit(self.flakeref.clone())
}
}

impl OsRebuildArgs {
pub fn rebuild(&self, rebuild_type: &OsRebuildType) -> Result<()> {
if nix::unistd::Uid::effective().is_root() {
Expand All @@ -42,9 +49,14 @@ impl OsRebuildArgs {
debug!("out_dir: {:?}", out_dir);
debug!("out_link {:?}", out_link);

let flakeref = self.flakeref.clone().or_else(|| {
warn!("NH_OS_FLAKE not set");
std::env::var("FLAKE").ok().map(|s| FlakeRef(s))
}).unwrap_or("./".into());

let flake_output = format!(
"{}#nixosConfigurations.\"{:?}\".config.system.build.toplevel",
&self.common.flakeref.deref(),
flakeref.deref(),
hostname
);

Expand All @@ -64,7 +76,7 @@ impl OsRebuildArgs {
}
}

update_args.push(&self.common.flakeref);
update_args.push(&flakeref);

debug!("nix_version: {:?}", nix_version);
debug!("update_args: {:?}", update_args);
Expand Down