Adding Importing functionality

This commit is contained in:
Peritia 2025-08-06 09:34:26 +02:00
parent 62594d312c
commit 2f9ff34ad4
17 changed files with 1188 additions and 307 deletions

17
nyx/default.nix Normal file
View file

@ -0,0 +1,17 @@
# Import all modules so only needs to Import nyx.nix
{ config, pkgs, lib, nixDirectory, ... }:
{
imports = [
# System modules
# Rebuild
./nyx-rebuild.nix
# Custom Banner
./nyx-tool.nix
# Nyx cleanup
./nyx-cleanup.nix
];
}

176
nyx/nyx-cleanup.nix Normal file
View file

@ -0,0 +1,176 @@
{ config, lib, pkgs, ... }:
let
cfg = config.nyx.nyx-cleanup;
logDirDefault = "/home/${toString cfg.username}/.nyx/nyx-cleanup/logs";
in
{
options.nyx.nyx-cleanup = {
enable = lib.mkEnableOption "Enable nyx-cleanup script";
username = lib.mkOption {
type = lib.types.str;
description = "The user this module applies to.";
};
nixDirectory = lib.mkOption {
type = lib.types.path;
description = "Path to NixOS flake configuration.";
};
logDir = lib.mkOption {
type = lib.types.str;
default = logDirDefault;
description = "Directory for storing cleanup logs.";
};
keepGenerations = lib.mkOption {
type = lib.types.int;
default = 5;
description = "Number of NixOS generations to keep.";
};
autoPush = lib.mkOption {
type = lib.types.bool;
default = false;
description = "Whether to auto-push git commits after cleanup.";
};
enableAlias = lib.mkOption {
type = lib.types.bool;
default = true;
description = "If true, add alias 'nc' for 'nyx-cleanup'.";
};
};
config = lib.mkIf cfg.enable {
home.packages = [
(pkgs.writeShellScriptBin "nyx-cleanup" ''
#!/usr/bin/env bash
nyx-cleanup(){
set -euo pipefail
# === CONFIGURATION ===
log_dir="${toString cfg.logDir}"
keep_generations=${toString cfg.keepGenerations}
auto_push=${if cfg.autoPush then "true" else "false"}
git_bin="${pkgs.git}/bin/git"
# Derived repo dir (assumes: ~/.nyx/nyx-cleanup/logs → ~/.nyx)
repo_dir="$(dirname "$(dirname "$log_dir")")"
# === INITIAL SETUP ===
version="1.0.0"
start_time=$(date +%s)
start_human=$(date '+%Y-%m-%d %H:%M:%S')
cleanup_success=false
exit_code=1
# === COLORS ===
if [[ -t 1 ]]; then
RED=$'\e[31m'; GREEN=$'\e[32m'; YELLOW=$'\e[33m'
BLUE=$'\e[34m'; MAGENTA=$'\e[35m'; CYAN=$'\e[36m'
BOLD=$'\e[1m'; RESET=$'\e[0m'
else
RED=""; GREEN=""; YELLOW=""
BLUE=""; MAGENTA=""; CYAN=""
BOLD=""; RESET=""
fi
# === LOGGING ===
mkdir -p "$log_dir"
timestamp=$(date '+%Y-%m-%d_%H-%M-%S')
cleanup_log="$log_dir/cleanup-''${timestamp}.log"
console-log() {
echo -e "$@" | tee -a "$cleanup_log"
}
print_line() {
console-log ""
console-log "''${BOLD}==================================================''${RESET}"
console-log ""
}
finish_cleanup() {
duration=$(( $(date +%s) - start_time ))
if [[ "$cleanup_success" == true ]]; then
echo -e "''${GREEN}''${BOLD}
##############################
# ✅ Nyx Cleanup Complete! #
##############################''${RESET}"
echo -e "''${CYAN}''${BOLD}📋 Stats:''${RESET}"
echo " 🕒 Started: $start_human"
echo " Duration: ''${duration} sec"
else
echo -e "''${RED}''${BOLD}
##############################
# ❌ Nyx Cleanup Failed! #
##############################''${RESET}"
echo " 🕒 Started: $start_human"
echo " Duration: ''${duration} sec"
fi
}
trap finish_cleanup EXIT
print_line
console-log "''${BLUE}''${BOLD}🧹 Starting cleanup...''${RESET}"
# === REMOVE OLD LOGS ===
console-log "''${CYAN}''${BOLD}🗑 Removing logs older than 30 days...''${RESET}"
find "$log_dir" -type f -mtime +30 -print -delete
# === REMOVE HOME MANAGER BACKUPS ===
print_line
console-log "''${CYAN}''${BOLD}📁 Deleting Home Manager backup files...''${RESET}"
find ~ -type f -name '*delme-HMbackup' -print -delete
# === GARBAGE COLLECTION ===
print_line
console-log "''${MAGENTA}''${BOLD}🧼 Running Nix garbage collection...''${RESET}"
sudo nix-collect-garbage -d | tee -a "$cleanup_log"
# === GIT SETUP ===
print_line
if [[ ! -d "$repo_dir/.git" ]]; then
console-log "''${YELLOW} No git repo in: $repo_dir. Initializing...''${RESET}"
"$git_bin" -C "$repo_dir" init | tee -a "$cleanup_log"
fi
# === GIT AUTO PUSH ===
if [[ "$auto_push" == "true" ]]; then
print_line
console-log "''${BLUE}''${BOLD}🚀 Auto-pushing git commits in $repo_dir...''${RESET}"
cd "$repo_dir"
if "$git_bin" remote | grep -q .; then
"$git_bin" add .
"$git_bin" commit -m "chore(cleanup): auto cleanup $(date)" || true
"$git_bin" push
else
console-log "''${YELLOW} No git remote configured. Skipping push.''${RESET}"
console-log "''${YELLOW}📂 Check logs in: $log_dir''${RESET}"
fi
fi
cleanup_success=true
exit_code=0
print_line
console-log "''${GREEN}🎉 Cleanup finished successfully!''${RESET}"
print_line
}
nyx-cleanup
'')
];
home.shellAliases = lib.mkIf cfg.enableAlias {
nc = "nyx-cleanup";
};
};
}

295
nyx/nyx-rebuild.nix Normal file
View file

@ -0,0 +1,295 @@
{ config, lib, pkgs, ... }:
let
cfg = config.nyx.nyx-rebuild;
nixDirStr = toString cfg.nixDirectory;
logDirDefault = "/home/${cfg.username}/.nyx/nyx-rebuild/logs";
in
{
options.nyx.nyx-rebuild = {
enable = lib.mkEnableOption "Enable nyx-rebuild script";
username = lib.mkOption {
type = lib.types.str;
description = "User this module applies to.";
};
nixDirectory = lib.mkOption {
type = lib.types.path;
description = "Path to NixOS flake configuration.";
};
logDir = lib.mkOption {
type = lib.types.str;
default = logDirDefault;
description = "Directory for storing cleanup logs.";
};
editor = lib.mkOption {
type = lib.types.str;
default = "nvim";
description = "Editor for manual editing step.";
};
formatter = lib.mkOption {
type = lib.types.str;
default = "alejandra";
description = "Formatter to use before rebuild.";
};
startEditor = lib.mkOption {
type = lib.types.bool;
default = false;
description = "Start editor before rebuild.";
};
enableFormatting = lib.mkOption {
type = lib.types.bool;
default = false;
description = "Format Nix files before rebuild.";
};
autoPushLog = lib.mkOption {
type = lib.types.bool;
default = false;
description = "If true, automatically push $git_bin commits containing rebuild logs.";
};
autoPushNixDir = lib.mkOption {
type = lib.types.bool;
default = false;
description = "If true, push $git_bin commits in nixDirectory (configuration repo) after rebuild.";
};
enableAlias = lib.mkOption {
type = lib.types.bool;
default = true;
description = "Add 'nr' alias for nyx-rebuild.";
};
};
config = lib.mkIf cfg.enable {
programs.zsh.enable = lib.mkDefault true;
home.packages = [
# Add formatter if selected
] ++ lib.optional (cfg.enableFormatting && cfg.formatter == "alejandra") pkgs.alejandra
++ [
# Main script
(pkgs.writeShellScriptBin "nyx-rebuild" ''
#!/usr/bin/env bash
nyx-rebuild () {
set -euo pipefail
# === CONFIGURATION ===
nix_dir="${nixDirStr}"
log_dir="${toString cfg.logDir}"
start_editor="${if cfg.startEditor then "true" else "false"}"
enable_formatting="${if cfg.enableFormatting then "true" else "false"}"
editor_cmd="${cfg.editor}"
formatter_cmd="${cfg.formatter}"
auto_push_log="${if cfg.autoPushLog then "true" else "false"}"
auto_push_nixdir="${if cfg.autoPushNixDir then "true" else "false"}"
git_bin="${pkgs.git}/bin/git"
nom_bin="${pkgs.nix-output-monitor}/bin/nom"
# === INITIAL SETUP ===
version="beta-2.0.0"
start_time=$(date +%s)
start_human=$(date '+%Y-%m-%d %H:%M:%S')
stats_duration=0
stats_gen="?"
stats_errors=0
stats_last_error_lines=""
rebuild_success=false
exit_code=1
# === COLORS ===
if [[ -t 1 ]]; then
RED=$'\e[31m'; GREEN=$'\e[32m'; YELLOW=$'\e[33m'
BLUE=$'\e[34m'; MAGENTA=$'\e[35m'; CYAN=$'\e[36m'
BOLD=$'\e[1m'; RESET=$'\e[0m'
else
RED=""; GREEN=""; YELLOW=""
BLUE=""; MAGENTA=""; CYAN=""
BOLD=""; RESET=""
fi
# === LOGGING SETUP ===
hostname=$(hostname)
mkdir -p "$log_dir"
timestamp=$(date '+%Y-%m-%d_%H-%M-%S')
build_log="$log_dir/build-''${timestamp}.log"
error_log="$log_dir/Current-Error-''${timestamp}.txt"
# === HELPERS ===
console-log() {
echo -e "$@" | tee -a "$build_log"
}
print_line() {
console-log ""
console-log "''${BOLD}==================================================''${RESET}"
console-log ""
}
run_with_log() {
local cmd_output
cmd_output=$(mktemp)
(
"$@" 2>&1
echo $? > "$cmd_output"
) | tee -a "$build_log"
local status
status=$(<"$cmd_output")
rm "$cmd_output"
return "$status"
}
run_with_log_rebuild() {
local cmd_output
cmd_output=$(mktemp)
(
"$@" 2>&1
echo $? > "$cmd_output"
) | tee -a "$build_log" | $nom_bin
local status
status=$(<"$cmd_output")
rm "$cmd_output"
return "$status"
}
finish_nyx_rebuild() {
stats_duration=$(( $(date +%s) - start_time ))
echo
if [[ "$rebuild_success" == true ]]; then
echo "''${GREEN}''${BOLD}
##############################
# ✅ NixOS Rebuild Complete! #
##############################''${RESET}"
echo "''${BOLD}''${CYAN}🎯 Success Stats:''${RESET}"
echo " 🕒 Started: $start_human"
echo " Duration: ''${stats_duration} sec"
echo " 📦 Gen: $stats_gen"
else
echo "''${RED}''${BOLD}
##############################
# ❌ NixOS Rebuild Failed! #
##############################''${RESET}"
echo "''${BOLD}''${RED}🚨 Error Stats:''${RESET}"
echo " 🕒 Started: $start_human"
echo " Duration: ''${stats_duration} sec"
echo " Error lines: ''${stats_errors}"
[[ -n "$stats_last_error_lines" ]] && echo -e "\n''${YELLOW}🧾 Last few errors:''${RESET}\n$stats_last_error_lines"
fi
}
trap finish_nyx_rebuild EXIT
# === TOOL INFO ===
echo
nyx-tool "Nyx" "nyx-rebuild" "$version" \
"Smart NixOS configuration rebuilder" \
"by Peritia-System" \
"https://github.com/Peritia-System/Nyx-Tools" \
"https://github.com/Peritia-System/Nyx-Tools/issues" \
"Always up to date for you!"
echo
# === PROJECT PREP ===
cd "$nix_dir" || { exit_code=1; return $exit_code; }
# === CHECK FOR UNCOMMITTED CHANGES ===
console-log "\n''${BOLD}''${BLUE}📁 Checking $git_bin status...''${RESET}"
if [[ -n $($git_bin status --porcelain) ]]; then
echo "''${YELLOW} Uncommitted changes detected!''${RESET}"
echo "''${RED} 5s to cancel...''${RESET}"
sleep 5
fi
# === SCRIPT START ===
print_line
console-log "''${BLUE}''${BOLD}🚀 Starting Nyx Rebuild...''${RESET}"
# === GIT PULL ===
console-log "\n''${BOLD}''${BLUE} Pulling latest changes...''${RESET}"
run_with_log $git_bin pull --rebase || return 1
# === OPTIONAL: OPEN EDITOR ===
if [[ "$start_editor" == "true" ]]; then
console-log "\n''${BOLD}''${BLUE}📝 Editing configuration...''${RESET}"
run_with_log "$editor_cmd"
fi
# === OPTIONAL: FORMAT FILES ===
if [[ "$enable_formatting" == "true" ]]; then
console-log "\n''${BOLD}''${MAGENTA}🎨 Running formatter...''${RESET}"
run_with_log "$formatter_cmd" .
fi
# === GIT DIFF ===
console-log "\n''${BOLD}''${CYAN}🔍 Changes summary:''${RESET}"
run_with_log $git_bin diff --compact-summary
# === SYSTEM REBUILD ===
print_line
console-log "''${BLUE}''${BOLD}🔧 Starting system rebuild...''${RESET}"
console-log "🛠 Removing old HM conf"
run_with_log find ~ -type f -name '*delme-HMbackup' -exec rm -v {} +
print_line
console-log "Getting sudo ticket"
run_with_log sudo whoami > /dev/null
print_line
console-log "🛠 Rebuild started: $(date)"
run_with_log_rebuild sudo nixos-rebuild switch --flake "$nix_dir"
rebuild_status=$?
if [[ $rebuild_status -ne 0 ]]; then
echo "''${RED} Rebuild failed at $(date).''${RESET}" > "$error_log"
stats_errors=$(grep -Ei -A 1 'error|failed' "$build_log" | tee -a "$error_log" | wc -l)
stats_last_error_lines=$(tail -n 10 "$error_log")
cd "$log_dir"
$git_bin add "$log_dir"
$git_bin commit -m "chore(rebuild): failed rebuild on $(date)" || true
[[ "$auto_push_nixdir" == "true" ]] && (cd "$nix_dir" && $git_bin push || true)
cd "$nix_dir"
return 1
fi
# === SUCCESS FLOW ===
rebuild_success=true
gen=$(nixos-rebuild list-generations | grep True | awk '{$1=$1};1')
stats_gen=$(echo "$gen" | awk '{printf "%04d\n", $1}')
finish_nyx_rebuild >> "$build_log"
$git_bin add -u
$git_bin commit -m "Rebuild: $gen" || true
cd "$log_dir"
final_log="$log_dir/nixos-gen_''${stats_gen}-switch-''${timestamp}.log"
mv "$build_log" "$final_log"
$git_bin add "$final_log"
$git_bin commit -m "log for $gen" || true
# === FINAL PUSH LOGS ===
$git_bin add "$final_log"
$git_bin commit -m "chore(rebuild): successful rebuild on $(date)" || true
if [[ "$auto_push_log" == "true" ]]; then
(cd "$repo_dir" && $git_bin push || true)
fi
cd "$nix_dir"
echo -e "\n''${GREEN}🎉 Nyx rebuild completed successfully!''${RESET}"
}
nyx-rebuild
'')
];
home.shellAliases = lib.mkIf cfg.enableAlias {
nr = "nyx-rebuild";
};
};
}

79
nyx/nyx-tool.nix Normal file
View file

@ -0,0 +1,79 @@
{ config, lib, pkgs, ... }:
let
cfg = config.nyx.nyx-tool;
in
{
options.nyx.nyx-tool = {
enable = lib.mkEnableOption "Enable nyx-tool Script for Banner display.";
nixDirectory = lib.mkOption {
type = lib.types.str;
description = "Path to the main Nix directory used for scripts.";
};
};
config = lib.mkIf cfg.enable {
programs.zsh.enable = lib.mkDefault true;
home.packages =
[ pkgs.figlet ]
++ [
(pkgs.writeShellScriptBin "nyx-tool" ''
#!/usr/bin/env bash
nyx-tool() {
# nyx-tool: reusable metadata banner printer with Base16 theme
local logo="''${1:-Nyx}"
local name="''${2:-nix-script}"
local version="''${3:-Version Unknown - Please Open Issue}"
local description="''${4:-A Nix utility}"
local credit="''${5:-Peritia-System}"
local github="''${6:-https://github.com/example/repo}"
local issues="''${7:-''${github}/issues}"
local message="''${8:-Use responsibly}"
# Base16 color palette (ANSI escape codes)
local RESET="\033[0m"
local BOLD="\033[1m"
local HEADER="\033[38;5;33m" # blue
local LABEL="\033[38;5;70m" # green
local VALUE="\033[38;5;250m" # gray
local EMPHASIS="\033[38;5;196m" # red
local CYAN="\033[38;5;51m"
local GREEN="\033[38;5;82m"
local line
line=$(printf '=%.0s' $(seq 1 35))
echo ""
echo -e "''${HEADER}''${line}''${RESET}"
echo -e "''${HEADER}=====[ ''${BOLD}Peritia System Tools''${RESET}''${HEADER} ]=====''${RESET}"
echo -e "''${VALUE}''${BOLD}"
# Figlet logo rendering
if command -v figlet &>/dev/null; then
figlet -f banner3 "$logo" | sed 's/#/█/g'
else
echo "$logo"
fi
echo -e "''${RESET}''${HEADER}by Peritia-System''${RESET}"
echo -e "''${HEADER}''${line}''${RESET}"
echo ""
echo -e "''${LABEL}🛠 Name: ''${VALUE}''${name}''${RESET}"
echo -e "''${LABEL}🏷 Version: ''${VALUE}''${version}''${RESET}"
echo -e "''${LABEL}📝 Description: ''${VALUE}''${description}''${RESET}"
echo -e "''${LABEL}👤 Credit: ''${VALUE}''${credit}''${RESET}"
echo -e "''${LABEL}🌐 GitHub: ''${VALUE}''${github}''${RESET}"
echo -e "''${LABEL}🐛 Issues: ''${VALUE}''${issues}''${RESET}"
echo ""
echo -e "''${LABEL}📌 Message: ''${BOLD}''${message}''${RESET}"
echo ""
}
nyx-tool "$@"
'')
];
};
}