macro_rules! debug {
($($arg:tt)*) => {
if cfg!(debug_assertions) {
eprintln!("[DEBUG] {}", format!($($arg)*));
}
};
}
macro_rules! info {
($($arg:tt)*) => {
eprintln!("[INFO] {}", format!($($arg)*));
};
}
macro_rules! warn {
($($arg:tt)*) => {
eprintln!("[WARN] {}", format!($($arg)*));
};
}
macro_rules! bail {
($($arg:tt)*) => {
return Err(format!($($arg)*).into())
};
}
pub mod atomic;
pub mod branch;
pub mod bisect;
pub mod candidates;
pub mod config;
pub mod evolog;
pub mod hidden;
pub mod freeze;
pub mod error;
pub mod lock;
pub mod ops;
pub mod resolution;
pub mod snapshot;
pub mod vcs;
#[cfg(feature = "cli")]
pub mod commands;
#[cfg(feature = "mcp")]
pub mod mcp;
pub use branch::{BranchInfo, BranchManager, BranchStatus, ChangeGroup};
pub use config::Config;
pub use vcs::VcsManager;
#[cfg(feature = "mcp")]
pub use mcp::CodetreeServer;
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub const NAME: &str = env!("CARGO_PKG_NAME");
pub const DESCRIPTION: &str = env!("CARGO_PKG_DESCRIPTION");
pub mod defaults {
pub const CLEANUP_DAYS: u32 = 30;
}
pub mod errors {
use std::fmt;
#[derive(Debug)]
pub enum CodetreeError {
GitError(String),
ConfigError(String),
FileSystemError(String),
BranchNotFound(String),
InvalidOperation(String),
}
impl fmt::Display for CodetreeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CodetreeError::GitError(msg) => write!(f, "Git operation failed: {msg}"),
CodetreeError::ConfigError(msg) => write!(f, "Configuration error: {msg}"),
CodetreeError::FileSystemError(msg) => write!(f, "File system error: {msg}"),
CodetreeError::BranchNotFound(name) => write!(f, "Branch not found: {name}"),
CodetreeError::InvalidOperation(msg) => write!(f, "Invalid operation: {msg}"),
}
}
}
impl std::error::Error for CodetreeError {}
}
pub mod utils {
use std::path::Path;
pub fn should_ignore_path(path: &Path) -> bool {
let path_str = path.to_string_lossy();
let ignore_patterns = [
".git/",
".codetree/",
"target/",
"node_modules/",
".DS_Store",
"*.tmp",
"*.log",
"*.swp",
"*.swo",
"*~",
];
for pattern in &ignore_patterns {
if pattern.ends_with('/') {
if path_str.contains(pattern) {
return true;
}
} else if pattern.contains('*') {
if let Some(suffix) = pattern.strip_prefix('*') {
if path_str.ends_with(suffix) {
return true;
}
} else if let Some(prefix) = pattern.strip_suffix('*') {
if path_str.starts_with(prefix) {
return true;
}
} else {
let pattern_without_star = pattern.replace('*', "");
if path_str.contains(&pattern_without_star) {
return true;
}
}
} else {
if path_str.contains(pattern) {
return true;
}
}
}
false
}
pub fn slugify(s: &str) -> String {
s.to_lowercase()
.replace(|c: char| !c.is_alphanumeric() && c != ' ', " ")
.split_whitespace()
.take(4)
.collect::<Vec<_>>()
.join("_")
}
pub fn generate_branch_name(prefix: &str, timestamp: u64) -> String {
format!("{}_{}", prefix, timestamp)
}
pub fn calculate_similarity(a: &str, b: &str) -> f64 {
if a == b {
return 1.0;
}
if a.is_empty() || b.is_empty() {
return 0.0;
}
let words_a: std::collections::HashSet<&str> = a.split_whitespace().collect();
let words_b: std::collections::HashSet<&str> = b.split_whitespace().collect();
let intersection = words_a.intersection(&words_b).count();
let union = words_a.union(&words_b).count();
if union == 0 {
0.0
} else {
intersection as f64 / union as f64
}
}
pub fn format_file_size(size: u64) -> String {
const UNITS: &[&str] = &["B", "KB", "MB", "GB", "TB"];
let mut size = size as f64;
let mut unit_index = 0;
while size >= 1024.0 && unit_index < UNITS.len() - 1 {
size /= 1024.0;
unit_index += 1;
}
if unit_index == 0 {
format!("{} {}", size as u64, UNITS[unit_index])
} else {
format!("{:.1} {}", size, UNITS[unit_index])
}
}
pub fn truncate_string(s: &str, max_len: usize) -> String {
if s.len() <= max_len {
s.to_string()
} else if max_len <= 3 {
"...".to_string()
} else {
format!("{}...", &s[..max_len - 3])
}
}
pub fn get_file_extension(path: &Path) -> Option<String> {
path.extension()
.and_then(|ext| ext.to_str())
.map(|ext| ext.to_lowercase())
}
pub fn is_source_file(path: &Path) -> bool {
if let Some(ext) = get_file_extension(path) {
matches!(ext.as_str(),
"rs" | "py" | "js" | "ts" | "jsx" | "tsx" | "java" | "c" | "cpp" | "h" | "hpp" |
"go" | "rb" | "php" | "cs" | "swift" | "kt" | "scala" | "clj" | "hs" | "ml" |
"elm" | "dart" | "r" | "jl" | "nim" | "zig" | "v" | "cr" | "ex" | "exs"
)
} else {
false
}
}
pub fn is_config_file(path: &Path) -> bool {
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
matches!(name,
"Cargo.toml" | "package.json" | "requirements.txt" | "Pipfile" | "pyproject.toml" |
"pom.xml" | "build.gradle" | "Makefile" | "CMakeLists.txt" | "Dockerfile" |
".gitignore" | ".dockerignore" | "README.md" | "LICENSE" | "CHANGELOG.md"
) || name.ends_with(".toml") || name.ends_with(".yaml") || name.ends_with(".yml") ||
name.ends_with(".json") || name.ends_with(".xml") || name.ends_with(".ini") ||
name.starts_with(".env")
} else {
false
}
}
pub fn is_test_file(path: &Path) -> bool {
let path_str = path.to_string_lossy().to_lowercase();
path_str.contains("test") || path_str.contains("spec") ||
path_str.ends_with("_test.rs") || path_str.ends_with(".test.js") ||
path_str.ends_with(".spec.js") || path_str.ends_with("_test.py") ||
path_str.contains("/tests/") || path_str.contains("/test/")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_should_ignore_path() {
use std::path::Path;
assert!(utils::should_ignore_path(Path::new(".git/config")));
assert!(utils::should_ignore_path(Path::new("target/debug/main")));
assert!(utils::should_ignore_path(Path::new("node_modules/package/index.js")));
assert!(utils::should_ignore_path(Path::new(".DS_Store")));
assert!(utils::should_ignore_path(Path::new("file.tmp")));
assert!(!utils::should_ignore_path(Path::new("src/main.rs")));
assert!(!utils::should_ignore_path(Path::new("README.md")));
}
#[test]
fn test_should_ignore_path_glob_false_positive() {
use std::path::Path;
assert!(!utils::should_ignore_path(Path::new("my.template")));
assert!(!utils::should_ignore_path(Path::new("document.temporary")));
assert!(!utils::should_ignore_path(Path::new("tmpfile")));
assert!(utils::should_ignore_path(Path::new("file.tmp")));
assert!(utils::should_ignore_path(Path::new("dir/file.tmp")));
}
#[test]
fn test_calculate_similarity() {
assert_eq!(utils::calculate_similarity("hello world", "hello world"), 1.0);
assert_eq!(utils::calculate_similarity("", ""), 1.0);
assert_eq!(utils::calculate_similarity("hello", ""), 0.0);
let sim = utils::calculate_similarity("hello world", "world hello");
assert!(sim > 0.8);
let sim = utils::calculate_similarity("hello world", "goodbye moon");
assert!(sim < 0.5); }
#[test]
fn test_format_file_size() {
assert_eq!(utils::format_file_size(0), "0 B");
assert_eq!(utils::format_file_size(1023), "1023 B");
assert_eq!(utils::format_file_size(1024), "1.0 KB");
assert_eq!(utils::format_file_size(1536), "1.5 KB");
assert_eq!(utils::format_file_size(1048576), "1.0 MB");
}
#[test]
fn test_truncate_string() {
assert_eq!(utils::truncate_string("hello", 10), "hello");
assert_eq!(utils::truncate_string("hello world", 8), "hello...");
assert_eq!(utils::truncate_string("hi", 2), "hi");
assert_eq!(utils::truncate_string("hello", 3), "...");
}
#[test]
fn test_is_source_file() {
use std::path::Path;
assert!(utils::is_source_file(Path::new("main.rs")));
assert!(utils::is_source_file(Path::new("script.py")));
assert!(utils::is_source_file(Path::new("app.js")));
assert!(utils::is_source_file(Path::new("Component.tsx")));
assert!(!utils::is_source_file(Path::new("README.md")));
assert!(!utils::is_source_file(Path::new("data.json")));
assert!(!utils::is_source_file(Path::new("image.png")));
}
#[test]
fn test_is_config_file() {
use std::path::Path;
assert!(utils::is_config_file(Path::new("Cargo.toml")));
assert!(utils::is_config_file(Path::new("package.json")));
assert!(utils::is_config_file(Path::new("config.yaml")));
assert!(utils::is_config_file(Path::new(".env")));
assert!(utils::is_config_file(Path::new(".gitignore")));
assert!(!utils::is_config_file(Path::new("main.rs")));
assert!(!utils::is_config_file(Path::new("data.txt")));
}
#[test]
fn test_is_test_file() {
use std::path::Path;
assert!(utils::is_test_file(Path::new("main_test.rs")));
assert!(utils::is_test_file(Path::new("app.test.js")));
assert!(utils::is_test_file(Path::new("component.spec.ts")));
assert!(utils::is_test_file(Path::new("tests/integration.py")));
assert!(utils::is_test_file(Path::new("test/unit.py")));
assert!(!utils::is_test_file(Path::new("main.rs")));
assert!(!utils::is_test_file(Path::new("README.md")));
}
#[test]
fn test_generate_branch_name() {
let ts = 1700000000u64;
let branch = utils::generate_branch_name("codetree", ts);
assert!(branch.starts_with("codetree_"));
assert!(branch.len() > 10);
let branch = utils::generate_branch_name("prefix", ts);
assert!(branch.starts_with("prefix_"));
assert!(!branch.is_empty());
}
#[test]
fn test_format_file_size_edge_cases() {
assert_eq!(utils::format_file_size(1), "1 B");
assert_eq!(utils::format_file_size(1073741824), "1.0 GB");
}
#[test]
fn test_get_file_extension() {
use std::path::Path;
assert_eq!(utils::get_file_extension(Path::new("main.rs")), Some("rs".to_string()));
assert_eq!(utils::get_file_extension(Path::new(".gitignore")), None);
assert_eq!(utils::get_file_extension(Path::new("data.tar.gz")), Some("gz".to_string()));
assert_eq!(utils::get_file_extension(Path::new("noextension")), None);
assert_eq!(utils::get_file_extension(Path::new("README.MD")), Some("md".to_string()));
}
#[test]
fn test_is_source_file_edge_cases() {
use std::path::Path;
assert!(!utils::is_source_file(Path::new("Makefile"))); assert!(!utils::is_source_file(Path::new(".env")));
assert!(!utils::is_source_file(Path::new("Dockerfile")));
}
#[test]
fn test_is_config_file_edge_cases() {
use std::path::Path;
assert!(utils::is_config_file(Path::new("tsconfig.json")));
assert!(!utils::is_config_file(Path::new("main.rs")));
assert!(!utils::is_config_file(Path::new("app.js")));
}
#[test]
fn test_slugify_basic() {
assert_eq!(utils::slugify("Fix login bug"), "fix_login_bug");
}
#[test]
fn test_slugify_with_punctuation() {
assert_eq!(utils::slugify("Bug: critical error!"), "bug_critical_error");
}
#[test]
fn test_slugify_truncate() {
let long = "This is a very long description with many words";
let result = utils::slugify(long);
let parts: Vec<&str> = result.split('_').collect();
assert!(parts.len() <= 4);
}
#[test]
fn test_slugify_empty() {
assert_eq!(utils::slugify(""), "");
}
#[test]
fn test_slugify_numbers() {
assert_eq!(utils::slugify("Feature 123 with numbers"), "feature_123_with_numbers");
}
}