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

om health: Shell dotfiles are Nix-managed #306

Draft
wants to merge 12 commits into
base: main
Choose a base branch
from
Draft
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
2 changes: 1 addition & 1 deletion crates/omnix-health/src/check/direnv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ fn install_check(
}

/// Check that the path is in the Nix store (usually /nix/store)
fn is_path_in_nix_store(path: &std::path::Path) -> bool {
pub fn is_path_in_nix_store(path: &std::path::Path) -> bool {
path.starts_with("/nix/store")
}

Expand Down
1 change: 1 addition & 0 deletions crates/omnix-health/src/check/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ pub mod flake_enabled;
pub mod max_jobs;
pub mod min_nix_version;
pub mod rosetta;
pub mod shell;
pub mod trusted_users;
173 changes: 173 additions & 0 deletions crates/omnix-health/src/check/shell.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

use crate::traits::{Check, CheckResult, Checkable};

/// Shell types
///
#[derive(Debug, Serialize, Deserialize, Clone, Hash, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum Shell {
Zsh,
Bash,
Undeterminable,
#[serde(other)]
Other,
}

impl std::fmt::Display for Shell {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let shell_str = match self {
Shell::Zsh => "zsh",
Shell::Bash => "bash",
Shell::Other => "<unsupported shell>",
Shell::Undeterminable => "<undeterminable shell>",
};
write!(f, "{}", shell_str)
}
}

impl Shell {
/// Creates a `Shell` from a path string.
fn from_path(path: &str) -> Self {
let shell_name = Path::new(path).file_name().and_then(|name| name.to_str());

match shell_name {
None => Shell::Undeterminable,
Some("zsh") => Shell::Zsh,
Some("bash") => Shell::Bash,
Some(_) => Shell::Other,
}
}

/// Returns the dotfiles for a given `shell`
fn get_dotfiles_of_shell(shell: &Shell) -> Result<Vec<String>, ShellError> {
match shell {
Shell::Zsh => Ok(vec![".zshrc".to_string()]),
Shell::Bash => Ok(vec![
".bashrc".to_string(),
".bash_profile".to_string(),
".profile".to_string(),
]),
Shell::Other => Err(ShellError::UnsupportedShell),
Shell::Undeterminable => Err(ShellError::UndeterminableShell),
}
}
}

impl Default for Shell {
fn default() -> Self {
let shell_path = std::env::var("SHELL").expect("Environment variable `SHELL` not set");
Shell::from_path(&shell_path)
}
}

impl Checkable for Shell {
fn check(
&self,
_nix_info: &nix_rs::info::NixInfo,
_flake: Option<&nix_rs::flake::url::FlakeUrl>,
) -> Vec<Check> {
let check = Check {
title: "Shell Configurations".to_string(),
info: "Dotfiles managed by Nix".to_string(),
result: match are_dotfiles_nix_managed(self) {
Ok(true) => CheckResult::Green,
Ok(false) => {
let shell = Shell::default();
CheckResult::Red {
msg: format!(
"Default Shell: {} is not managed by Nix",
shell
),
suggestion: format!("Manage {} configurations through https://github.com/juspay/nixos-unified-template", shell)
}
}
Err(ShellError::UnsupportedShell) => CheckResult::Red {
msg: "Checking configurations for shell is not supported".to_owned(),
suggestion: "We support only Bash & Zsh Shells. Manage Zsh or Bash through https://github.com/juspay/nixos-unified-template".to_owned(),
},
Err(error) => {
panic!(
"Error occurred while checking shell configuration: {}",
error
);
}
},
required: false,
};
vec![check]
}
}

/// Checks if all dotfiles for a given shell are managed by nix
///
/// # Returns
/// * `true` if all dotfiles are nix-managed
/// * `false` if any dotfile is not nix-managed
/// * `Err` if there was an error during the check
fn are_dotfiles_nix_managed(shell: &Shell) -> Result<bool, ShellError> {
let home_dir = PathBuf::from(
std::env::var("HOME").map_err(|_| ShellError::EnvVarNotSet("HOME".to_string()))?,
);

let dotfiles = Shell::get_dotfiles_of_shell(shell)?;

// Iterate over each dotfile and check if it is managed by nix
for dotfile in dotfiles {
if !check_dotfile_is_managed_by_nix(&home_dir, &dotfile)? {
return Ok(false);
}
}
Ok(true)
}

fn check_dotfile_is_managed_by_nix(home_dir: &Path, dotfile: &str) -> Result<bool, ShellError> {
let path = home_dir.join(dotfile);
// TODO: Remove after debuging
check_path(path.clone());
let target = std::fs::read_link(path).map_err(ReadlinkError)?;
Ok(super::direnv::is_path_in_nix_store(&target))
}

fn check_path(path: PathBuf) {
println!("Checking path: {}", path.display());
println!("Path exists: {}", path.exists());
println!("Is symlink: {}", path.is_symlink());

// Try to get metadata
match path.metadata() {
Ok(meta) => println!("Metadata: {:?}", meta),
Err(e) => println!("Cannot get metadata: {}", e),
}

// Try to read link
match std::fs::read_link(path) {
Ok(target) => println!("Link target: {}", target.display()),
Err(e) => println!("Read link error: {}", e),
}
}

#[derive(thiserror::Error, Debug)]
pub struct ReadlinkError(#[from] std::io::Error);

impl std::fmt::Display for ReadlinkError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.0)
}
}

#[derive(thiserror::Error, Debug)]
pub enum ShellError {
#[error("Checking configurations for shell is not supported")]
UnsupportedShell,

#[error("Unable to determine user's default shell")]
UndeterminableShell,

#[error("Cannot read symlink target of config path: {0}")]
ReadlinkError(#[from] ReadlinkError),

#[error("Environent variable {0} not set")]
EnvVarNotSet(String),
}
4 changes: 3 additions & 1 deletion crates/omnix-health/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use traits::Check;

use self::check::{
caches::Caches, flake_enabled::FlakeEnabled, max_jobs::MaxJobs, min_nix_version::MinNixVersion,
rosetta::Rosetta, trusted_users::TrustedUsers,
rosetta::Rosetta, shell::Shell, trusted_users::TrustedUsers,
};

/// Nix Health check information for user's install
Expand All @@ -36,6 +36,7 @@ pub struct NixHealth {
pub trusted_users: TrustedUsers,
pub caches: Caches,
pub direnv: Direnv,
pub shell: Shell,
}

impl<'a> IntoIterator for &'a NixHealth {
Expand All @@ -52,6 +53,7 @@ impl<'a> IntoIterator for &'a NixHealth {
&self.trusted_users,
&self.caches,
&self.direnv,
&self.shell,
];
items.into_iter()
}
Expand Down
Loading