use std::{io, process::Command};
use eyre::Result;
use thiserror::Error;
use crate::{
config::{Config, CONFIG_FILE_NAME, VERSION},
hint,
tracing::LogResult as _,
warning,
};
#[derive(Debug, Error)]
pub enum NotInGitWorktree {
#[error("Failed to run the git command")]
CannotRunGit(io::Error),
#[error("Not in a Git repository")]
NotInRepo,
#[error("Not inside a Git worktree")]
NotInWorktree,
}
#[tracing::instrument(level = "trace")]
pub fn ensure_in_git_worktree() -> Result<(), NotInGitWorktree> {
let is_inside_work_tree = Command::new("git")
.args(["rev-parse", "--is-inside-work-tree"])
.output()
.map_err(NotInGitWorktree::CannotRunGit)
.log_err()?;
if !is_inside_work_tree.status.success() {
return Err(NotInGitWorktree::NotInRepo).log_err();
}
if is_inside_work_tree.stdout == b"true\n" {
Ok(())
} else {
Err(NotInGitWorktree::NotInWorktree).log_err()
}
}
#[tracing::instrument(level = "trace")]
pub fn load_config() -> Result<Config> {
let config = Config::load()?;
if config.version != VERSION {
warning!("The configuration in {CONFIG_FILE_NAME} is out of date.");
hint!("You can update it by running `git z update`.");
}
Ok(config)
}
#[macro_export]
macro_rules! success {
($($arg:tt)*) => {{
use colored::Colorize;
let message = indoc::formatdoc!($($arg)*).green().bold();
println!("{message}");
}};
}
#[macro_export]
macro_rules! warning {
($($arg:tt)*) => {{
use colored::Colorize;
let log_message = $crate::helpers::uncapitalise(&format!($($arg)*));
let log_message = log_message.trim_end_matches(".");
tracing::warn!("{log_message}");
let message = indoc::formatdoc!($($arg)*).yellow().bold();
eprintln!("{message}");
}};
}
#[macro_export]
macro_rules! error {
($($arg:tt)*) => {{
use colored::Colorize;
let message = indoc::formatdoc!($($arg)*);
let message = $crate::helpers::uncapitalise(&message);
let message = format!("Error: {message}").red().bold();
eprintln!("{message}");
}};
}
#[macro_export]
macro_rules! hint {
($($arg:tt)*) => {{
use colored::Colorize;
let message = indoc::formatdoc!($($arg)*).blue();
eprintln!("{message}");
}};
}