use agtrace_types::{ProjectHash, RepositoryHash};
use sha2::{Digest, Sha256};
use std::path::{Path, PathBuf};
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub enum Error {
Io(std::io::Error),
Config(String),
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::Io(err) => write!(f, "IO error: {}", err),
Error::Config(msg) => write!(f, "Config error: {}", msg),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Io(err) => Some(err),
Error::Config(_) => None,
}
}
}
impl From<std::io::Error> for Error {
fn from(err: std::io::Error) -> Self {
Error::Io(err)
}
}
pub fn resolve_workspace_path(explicit_path: Option<&str>) -> Result<PathBuf> {
if let Some(path) = explicit_path {
return Ok(expand_tilde(path));
}
if let Ok(env_path) = std::env::var("AGTRACE_PATH") {
return Ok(expand_tilde(&env_path));
}
if let Some(data_dir) = dirs::data_dir() {
return Ok(data_dir.join("agtrace"));
}
if let Some(home) = std::env::var_os("HOME") {
return Ok(PathBuf::from(home).join(".agtrace"));
}
Err(Error::Config(
"Could not determine workspace path: no HOME directory or system data directory found"
.to_string(),
))
}
pub fn expand_tilde(path: &str) -> PathBuf {
if let Some(stripped) = path.strip_prefix("~/")
&& let Some(home) = std::env::var_os("HOME")
{
return PathBuf::from(home).join(stripped);
}
PathBuf::from(path)
}
pub fn project_hash_from_root(project_root: &str) -> ProjectHash {
let normalized = normalize_path(Path::new(project_root));
let path_str = normalized.to_string_lossy();
let mut hasher = Sha256::new();
hasher.update(path_str.as_bytes());
ProjectHash::new(format!("{:x}", hasher.finalize()))
}
pub fn normalize_path(path: &Path) -> PathBuf {
path.canonicalize().unwrap_or_else(|_| {
if path.is_absolute() {
path.to_path_buf()
} else {
std::env::current_dir()
.map(|cwd| cwd.join(path))
.unwrap_or_else(|_| path.to_path_buf())
}
})
}
pub fn paths_equal(path1: &Path, path2: &Path) -> bool {
normalize_path(path1) == normalize_path(path2)
}
pub fn discover_project_root(explicit_project_root: Option<&str>) -> Result<PathBuf> {
if let Some(root) = explicit_project_root {
return Ok(PathBuf::from(root));
}
if let Ok(env_root) = std::env::var("AGTRACE_PROJECT_ROOT") {
return Ok(PathBuf::from(env_root));
}
let cwd = std::env::current_dir()?;
Ok(cwd)
}
pub fn resolve_effective_project_hash(
explicit_hash: Option<&ProjectHash>,
all_projects: bool,
) -> Result<(Option<ProjectHash>, bool)> {
if let Some(hash) = explicit_hash {
Ok((Some(hash.clone()), false))
} else if all_projects {
Ok((None, true))
} else {
let project_root_path = discover_project_root(None)?;
let current_project_hash = project_hash_from_root(&project_root_path.to_string_lossy());
Ok((Some(current_project_hash), false))
}
}
pub fn project_hash_from_log_path(log_path: &Path) -> ProjectHash {
let mut hasher = Sha256::new();
hasher.update(log_path.to_string_lossy().as_bytes());
ProjectHash::new(format!("{:x}", hasher.finalize()))
}
pub fn repository_hash_from_path(path: &Path) -> Option<RepositoryHash> {
use std::process::Command;
let git_common_dir = Command::new("git")
.args(["rev-parse", "--git-common-dir"])
.current_dir(path)
.output()
.ok()?;
if !git_common_dir.status.success() {
return None;
}
let common_dir_str = String::from_utf8_lossy(&git_common_dir.stdout);
let common_dir_path = Path::new(common_dir_str.trim());
let normalized = normalize_path(common_dir_path);
let path_str = normalized.to_string_lossy();
let mut hasher = Sha256::new();
hasher.update(path_str.as_bytes());
Some(RepositoryHash::new(format!("{:x}", hasher.finalize())))
}