use crate::error::{Context, Result};
use crate::vcs::VcsManager;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TagAnnotation {
pub commit: String,
pub tagger: String,
pub timestamp: u64,
pub message: String,
}
pub enum TagAction {
Create {
name: String,
commit: Option<String>,
annotate: Option<String>,
},
List,
Delete { name: String },
}
pub async fn tag_command(action: TagAction) -> Result<()> {
let current_dir = std::env::current_dir()
.context("Failed to get current directory")?;
let git_manager = VcsManager::new(current_dir.clone())?;
let repo = git_manager.repo();
match action {
TagAction::Create { name, commit, annotate } => {
let target_id = if let Some(spec) = commit {
let head_id = repo.refs().resolve_head()?
.context("HEAD does not point to a commit")?;
git_manager.resolve_commit_pub(&spec, &head_id)?
} else {
repo.refs().resolve_head()?
.context("HEAD does not point to a commit")?
};
if repo.refs().get_tag(&name)?.is_some() {
bail!("Tag '{}' already exists. Use `codetree tag delete {}` first.", name, name);
}
repo.refs().set_tag(&name, &target_id)?;
let short = &target_id[..7.min(target_id.len())];
if let Some(message) = annotate {
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let tagger = std::env::var("CODETREE_USER")
.unwrap_or_else(|_| "agent".to_string());
let annotation = TagAnnotation {
commit: target_id.clone(),
tagger,
timestamp,
message,
};
let annot_path = repo.refs().tag_path(&name)
.with_extension("annot");
crate::atomic::write_atomic(&annot_path, serde_json::to_string_pretty(&annotation)?.as_bytes())?;
println!("Created annotated tag '{}' -> {} (message: \"{}\")",
name, short, annotation.message);
} else {
println!("Created tag '{}' -> {}", name, short);
}
}
TagAction::List => {
let tags = repo.refs().list_tags()?;
if tags.is_empty() {
println!("No tags found.");
return Ok(());
}
println!("{:<20} {:<8} MESSAGE", "TAG", "COMMIT");
println!("{}", "-".repeat(50));
for tag in &tags {
let commit_id = repo.refs().get_tag(tag)?.unwrap_or_default();
let short = &commit_id[..7.min(commit_id.len())];
let annot_path = repo.refs().tag_path(tag)
.with_extension("annot");
let message = if annot_path.exists() {
let content = std::fs::read_to_string(&annot_path)?;
let ann: TagAnnotation = serde_json::from_str(&content)?;
ann.message
} else {
String::new()
};
println!("{:<20} {:<8} {}", tag, short, message);
}
}
TagAction::Delete { name } => {
if repo.refs().get_tag(&name)?.is_none() {
bail!("Tag '{}' not found.", name);
}
repo.refs().delete_tag(&name)?;
let annot_path = repo.refs().tag_path(&name)
.with_extension("annot");
if annot_path.exists() {
std::fs::remove_file(&annot_path)?;
}
println!("Deleted tag '{}'.", name);
}
}
Ok(())
}