From 4da51a8adb94f2979c0a911157f26596c1ee2cb5 Mon Sep 17 00:00:00 2001 From: DanConwayDev Date: Fri, 28 Nov 2025 09:19:06 +0000 Subject: sync HEAD on state event and git data push --- src/git/handlers.rs | 47 ++++++++- src/git/mod.rs | 273 ++++++++++++++++++++++++++++++++++++++++++++++++- src/nostr/builder.rs | 280 +++++++++++++++++++++++++++++++++++++++++++++++++-- src/nostr/events.rs | 174 ++++++++++++++++++++++++++++++++ 4 files changed, 764 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/git/handlers.rs b/src/git/handlers.rs index 27bec76..73f72f3 100644 --- a/src/git/handlers.rs +++ b/src/git/handlers.rs @@ -13,6 +13,9 @@ use super::authorization::{ }; use super::protocol::{GitService, PktLine}; use super::subprocess::GitSubprocess; +use super::{try_set_head_if_available}; + +use crate::nostr::events::RepositoryState; /// Handle GET /info/refs?service=git-{upload,receive}-pack /// @@ -163,6 +166,9 @@ pub struct PushAuthParams { /// This includes GRASP authorization validation according to GRASP-01: /// "MUST accept pushes via this service that match the latest repo state announcement /// on the relay, respecting the recursive maintainer set." +/// +/// Also per GRASP-01: "MUST set repository HEAD per repository state announcement +/// as soon as the git data related to that branch has been received." pub async fn handle_receive_pack( repo_path: PathBuf, request_body: Bytes, @@ -174,14 +180,17 @@ pub async fn handle_receive_pack( return Err(GitError::RepositoryNotFound); } + // Keep track of state for HEAD setting after push + let mut authorized_state: Option = None; + // GRASP Authorization Check - if let Some(params) = auth_params { + if let Some(ref params) = auth_params { info!( "Authorizing push for {}/{} via {}", params.owner_npub, params.identifier, params.relay_url ); - match authorize_push(¶ms, &request_body).await { + match authorize_push(params, &request_body).await { Ok(auth_result) => { if !auth_result.authorized { warn!( @@ -196,6 +205,8 @@ pub async fn handle_receive_pack( params.identifier, auth_result.maintainers.len() ); + // Save the state for HEAD setting after push + authorized_state = auth_result.state; } Err(e) => { warn!( @@ -246,6 +257,38 @@ pub async fn handle_receive_pack( return Err(GitError::GitFailed(status.code())); } + // GRASP-01: Set HEAD after git data is received + // "MUST set repository HEAD per repository state announcement + // as soon as the git data related to that branch has been received." + if let Some(state) = authorized_state { + if let Some(head_ref) = &state.head { + if let Some(branch_name) = state.get_head_branch() { + if let Some(commit) = state.get_branch_commit(branch_name) { + match try_set_head_if_available(&repo_path, head_ref, commit) { + Ok(true) => { + info!( + "Set HEAD to {} after push to {:?}", + head_ref, repo_path + ); + } + Ok(false) => { + debug!( + "HEAD commit {} not found after push, HEAD not updated", + commit + ); + } + Err(e) => { + warn!( + "Failed to set HEAD after push: {}", + e + ); + } + } + } + } + } + } + Ok(Response::builder() .status(StatusCode::OK) .header("content-type", GitService::ReceivePack.result_content_type()) diff --git a/src/git/mod.rs b/src/git/mod.rs index 81ff277..076e211 100644 --- a/src/git/mod.rs +++ b/src/git/mod.rs @@ -22,7 +22,9 @@ pub mod handlers; pub mod protocol; pub mod subprocess; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; +use std::process::Command; +use tracing::{debug, info}; /// Parse a Git repository path from URL components /// @@ -44,6 +46,130 @@ pub fn resolve_repo_path(git_data_path: &str, npub: &str, identifier: &str) -> P .join(format!("{}.git", identifier)) } +/// Check if a commit exists in the repository +/// +/// # Arguments +/// * `repo_path` - Path to the bare git repository +/// * `commit_hash` - The commit hash to check +/// +/// # Returns +/// True if the commit exists in the repository, false otherwise +pub fn commit_exists(repo_path: &Path, commit_hash: &str) -> bool { + let output = Command::new("git") + .args(["cat-file", "-t", commit_hash]) + .current_dir(repo_path) + .output(); + + match output { + Ok(result) => { + if result.status.success() { + let obj_type = String::from_utf8_lossy(&result.stdout); + // Object exists and is a commit + obj_type.trim() == "commit" + } else { + false + } + } + Err(_) => false, + } +} + +/// Set the repository HEAD to point to a branch +/// +/// This updates the HEAD symbolic ref to point to the specified branch. +/// Per GRASP-01: "MUST set repository HEAD per repository state announcement +/// as soon as the git data related to that branch has been received." +/// +/// # Arguments +/// * `repo_path` - Path to the bare git repository +/// * `head_ref` - The ref to set HEAD to (e.g., "refs/heads/main") +/// +/// # Returns +/// Ok(()) if successful, Err with error message otherwise +pub fn set_repository_head(repo_path: &Path, head_ref: &str) -> Result<(), String> { + // Validate the ref format + if !head_ref.starts_with("refs/heads/") { + return Err(format!("Invalid HEAD ref: {} (must start with refs/heads/)", head_ref)); + } + + debug!("Setting HEAD to {} in {}", head_ref, repo_path.display()); + + let output = Command::new("git") + .args(["symbolic-ref", "HEAD", head_ref]) + .current_dir(repo_path) + .output() + .map_err(|e| format!("Failed to execute git symbolic-ref: {}", e))?; + + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + return Err(format!("git symbolic-ref failed: {}", stderr)); + } + + info!("Updated HEAD to {} in {}", head_ref, repo_path.display()); + Ok(()) +} + +/// Try to set repository HEAD from a repository state event +/// +/// This function checks if the HEAD branch's commit is available in the repository +/// and sets HEAD if it is. This should be called: +/// 1. When a repository state event is received (in case git data already exists) +/// 2. After git data is received (in case a state event was already received) +/// +/// # Arguments +/// * `repo_path` - Path to the bare git repository +/// * `head_ref` - The ref to set HEAD to (e.g., "refs/heads/main") +/// * `head_commit` - The commit hash that the HEAD branch should point to +/// +/// # Returns +/// Ok(true) if HEAD was set, Ok(false) if commit not yet available, Err on failure +pub fn try_set_head_if_available( + repo_path: &Path, + head_ref: &str, + head_commit: &str, +) -> Result { + // Check if repository exists + if !repo_path.exists() { + debug!("Repository not found at {}, cannot set HEAD", repo_path.display()); + return Ok(false); + } + + // Check if the commit exists in the repository + if !commit_exists(repo_path, head_commit) { + debug!( + "Commit {} not found in {}, HEAD not set yet", + head_commit, + repo_path.display() + ); + return Ok(false); + } + + // Commit exists, set HEAD + set_repository_head(repo_path, head_ref)?; + Ok(true) +} + +/// Get the current HEAD ref from a repository +/// +/// # Arguments +/// * `repo_path` - Path to the bare git repository +/// +/// # Returns +/// The current HEAD ref (e.g., "refs/heads/main") or None if not set +pub fn get_repository_head(repo_path: &Path) -> Option { + let output = Command::new("git") + .args(["symbolic-ref", "HEAD"]) + .current_dir(repo_path) + .output() + .ok()?; + + if output.status.success() { + Some(String::from_utf8_lossy(&output.stdout).trim().to_string()) + } else { + None + } +} + /// Extract npub and identifier from a Git URL path /// /// Parses paths like `//.git/info/refs` @@ -77,6 +203,83 @@ pub fn parse_git_url(path: &str) -> Option<(&str, &str, &str)> { #[cfg(test)] mod tests { use super::*; + use std::fs; + use tempfile::TempDir; + + /// Create a test bare repository with optional commits + fn create_test_repo() -> (TempDir, PathBuf) { + let temp_dir = TempDir::new().unwrap(); + let repo_path = temp_dir.path().join("test.git"); + + // Initialize bare repository + Command::new("git") + .args(["init", "--bare", repo_path.to_str().unwrap()]) + .output() + .unwrap(); + + (temp_dir, repo_path) + } + + /// Create a test repository with a commit on a branch + fn create_test_repo_with_commit() -> (TempDir, PathBuf, String) { + let temp_dir = TempDir::new().unwrap(); + let work_dir = temp_dir.path().join("work"); + let bare_repo = temp_dir.path().join("test.git"); + + // Initialize bare repository + Command::new("git") + .args(["init", "--bare", bare_repo.to_str().unwrap()]) + .output() + .unwrap(); + + // Clone to working directory + Command::new("git") + .args(["clone", bare_repo.to_str().unwrap(), work_dir.to_str().unwrap()]) + .output() + .unwrap(); + + // Configure git for commits + Command::new("git") + .args(["config", "user.email", "test@test.com"]) + .current_dir(&work_dir) + .output() + .unwrap(); + Command::new("git") + .args(["config", "user.name", "Test"]) + .current_dir(&work_dir) + .output() + .unwrap(); + + // Create a file and commit + fs::write(work_dir.join("README.md"), "# Test").unwrap(); + Command::new("git") + .args(["add", "README.md"]) + .current_dir(&work_dir) + .output() + .unwrap(); + Command::new("git") + .args(["commit", "-m", "Initial commit"]) + .current_dir(&work_dir) + .output() + .unwrap(); + + // Get commit hash + let output = Command::new("git") + .args(["rev-parse", "HEAD"]) + .current_dir(&work_dir) + .output() + .unwrap(); + let commit_hash = String::from_utf8_lossy(&output.stdout).trim().to_string(); + + // Push to bare repo + Command::new("git") + .args(["push", "origin", "master"]) + .current_dir(&work_dir) + .output() + .unwrap(); + + (temp_dir, bare_repo, commit_hash) + } #[test] fn test_resolve_repo_path() { @@ -125,4 +328,72 @@ mod tests { assert!(parse_git_url("/npub1abc").is_none()); assert!(parse_git_url("/npub1abc/repo").is_none()); } + + #[test] + fn test_commit_exists_nonexistent() { + let (_temp_dir, repo_path) = create_test_repo(); + assert!(!commit_exists(&repo_path, "deadbeef1234567890abcdef1234567890abcdef")); + } + + #[test] + fn test_commit_exists_with_commit() { + let (_temp_dir, repo_path, commit_hash) = create_test_repo_with_commit(); + assert!(commit_exists(&repo_path, &commit_hash)); + } + + #[test] + fn test_set_repository_head() { + let (_temp_dir, repo_path, _commit_hash) = create_test_repo_with_commit(); + + // Default HEAD might be refs/heads/master + let result = set_repository_head(&repo_path, "refs/heads/main"); + assert!(result.is_ok()); + + let head = get_repository_head(&repo_path); + assert_eq!(head, Some("refs/heads/main".to_string())); + } + + #[test] + fn test_set_repository_head_invalid_ref() { + let (_temp_dir, repo_path) = create_test_repo(); + + // Invalid ref format should fail + let result = set_repository_head(&repo_path, "main"); + assert!(result.is_err()); + assert!(result.unwrap_err().contains("must start with refs/heads/")); + } + + #[test] + fn test_try_set_head_if_available_commit_missing() { + let (_temp_dir, repo_path) = create_test_repo(); + + let result = try_set_head_if_available( + &repo_path, + "refs/heads/main", + "deadbeef1234567890abcdef1234567890abcdef", + ); + + // Should return Ok(false) - commit not found + assert!(result.is_ok()); + assert!(!result.unwrap()); + } + + #[test] + fn test_try_set_head_if_available_success() { + let (_temp_dir, repo_path, commit_hash) = create_test_repo_with_commit(); + + let result = try_set_head_if_available( + &repo_path, + "refs/heads/main", + &commit_hash, + ); + + // Should return Ok(true) - HEAD was set + assert!(result.is_ok()); + assert!(result.unwrap()); + + // Verify HEAD was set + let head = get_repository_head(&repo_path); + assert_eq!(head, Some("refs/heads/main".to_string())); + } } \ No newline at end of file diff --git a/src/nostr/builder.rs b/src/nostr/builder.rs index 259c380..285e6f3 100644 --- a/src/nostr/builder.rs +++ b/src/nostr/builder.rs @@ -12,8 +12,10 @@ use nostr::{EventId, Filter, Kind, PublicKey}; use nostr_relay_builder::prelude::*; use crate::config::{Config, DatabaseBackend}; +use crate::git; use crate::nostr::events::{ - validate_announcement, validate_state, RepositoryAnnouncement, KIND_REPOSITORY_ANNOUNCEMENT, KIND_REPOSITORY_STATE, + validate_announcement, validate_state, RepositoryAnnouncement, RepositoryState, + KIND_REPOSITORY_ANNOUNCEMENT, KIND_REPOSITORY_STATE, }; /// NIP-34 Write Policy with Full GRASP-01 Event Validation @@ -77,6 +79,230 @@ impl Nip34WritePolicy { Ok(()) } + /// Check if this state event is the latest for its identifier among authorized authors + /// + /// A state is considered "latest" if no other state event in the database + /// from an authorized author has a newer timestamp. This handles out-of-order + /// delivery where an older event arrives after a newer one. + /// + /// The authorized_pubkeys should be the owner and maintainers of a specific + /// announcement, so different owners with the same identifier don't interfere. + async fn is_latest_state_for_identifier( + database: &Arc, + state: &RepositoryState, + authorized_pubkeys: &[PublicKey], + ) -> Result { + let filter = Filter::new() + .kind(Kind::from(KIND_REPOSITORY_STATE)) + .custom_tag( + SingleLetterTag::lowercase(Alphabet::D), + state.identifier.clone(), + ); + + match database.query(filter).await { + Ok(events) => { + for event in events { + // Skip comparing to self (same event ID) + if event.id == state.event.id { + continue; + } + // Only consider events from authorized authors for this announcement + if !authorized_pubkeys.contains(&event.pubkey) { + continue; + } + // If any existing event from an authorized author is newer, this is not the latest + if event.created_at > state.event.created_at { + tracing::debug!( + "State {} is not latest: found newer state {} from {} (ts {} > {})", + state.event.id.to_hex(), + event.id.to_hex(), + event.pubkey.to_hex(), + event.created_at.as_secs(), + state.event.created_at.as_secs() + ); + return Ok(false); + } + } + Ok(true) + } + Err(e) => Err(format!("Database query failed: {}", e)), + } + } + + /// Find all repository announcements where the given pubkey is authorized + /// + /// A pubkey is authorized for an announcement if: + /// - They are the owner (pubkey of the announcement event), OR + /// - They are listed in the "maintainers" tag + /// + /// This is needed because a maintainer can publish a state event that + /// should update HEAD in the repository of the announcement owner, + /// not in the maintainer's own (possibly non-existent) repository. + async fn find_authorized_announcements( + database: &Arc, + identifier: &str, + state_author: &PublicKey, + ) -> Result, String> { + let filter = Filter::new() + .kind(Kind::from(KIND_REPOSITORY_ANNOUNCEMENT)) + .custom_tag( + SingleLetterTag::lowercase(Alphabet::D), + identifier.to_string(), + ); + + match database.query(filter).await { + Ok(events) => { + let mut authorized = Vec::new(); + let state_author_hex = state_author.to_hex(); + + for event in events { + if let Ok(announcement) = RepositoryAnnouncement::from_event(event.clone()) { + // Check if state author is authorized for this announcement + let is_owner = event.pubkey == *state_author; + let is_maintainer = announcement.maintainers.contains(&state_author_hex); + + if is_owner || is_maintainer { + tracing::debug!( + "Found authorized announcement for {}: owner={}, maintainer={}", + identifier, + if is_owner { event.pubkey.to_hex() } else { "n/a".to_string() }, + is_maintainer + ); + authorized.push(announcement); + } + } + } + Ok(authorized) + } + Err(e) => Err(format!("Database query failed: {}", e)), + } + } + + /// Try to set repository HEAD for all authorized announcement owners + /// + /// Per GRASP-01: "MUST set repository HEAD per repository state announcement + /// as soon as the git data related to that branch has been received." + /// + /// This function: + /// 1. Checks if this state event is the latest for the identifier + /// 2. Finds all announcements where the state author is authorized + /// 3. Updates HEAD in each relevant repository + /// + /// Returns Ok(count) with the number of repositories updated. + async fn try_set_head_for_authorized_repos( + &self, + database: &Arc, + state: &RepositoryState, + ) -> Result { + // Check if state has a HEAD reference + let head_ref = match &state.head { + Some(h) => h, + None => { + tracing::debug!( + "State event for {} has no HEAD reference", + state.identifier + ); + return Ok(0); + } + }; + + // Get the branch name and commit + let branch_name = match state.get_head_branch() { + Some(b) => b, + None => { + tracing::debug!( + "State event for {} has invalid HEAD format: {}", + state.identifier, + head_ref + ); + return Ok(0); + } + }; + + let head_commit = match state.get_branch_commit(branch_name) { + Some(c) => c, + None => { + tracing::debug!( + "State event for {} HEAD branch {} has no commit in state", + state.identifier, + branch_name + ); + return Ok(0); + } + }; + + // Find all announcements where state author is authorized + let announcements = Self::find_authorized_announcements( + database, + &state.identifier, + &state.event.pubkey, + ).await?; + + if announcements.is_empty() { + tracing::debug!( + "No authorized announcements found for state {} by {}", + state.identifier, + state.event.pubkey.to_hex() + ); + return Ok(0); + } + + // Update HEAD in each authorized announcement's repository + let mut updated_count = 0; + for announcement in &announcements { + // Build the list of authorized pubkeys for this specific announcement + // (owner + maintainers) + let mut authorized_pubkeys = vec![announcement.event.pubkey]; + for maintainer_hex in &announcement.maintainers { + if let Ok(pk) = PublicKey::from_hex(maintainer_hex) { + authorized_pubkeys.push(pk); + } + } + + // Check if this is the latest state event for THIS announcement's context + // Different owners with the same identifier should not interfere + if !Self::is_latest_state_for_identifier(database, state, &authorized_pubkeys).await? { + tracing::debug!( + "Skipping HEAD update for {} in {}'s repo - not the latest state event for this context", + state.identifier, + announcement.event.pubkey.to_hex() + ); + continue; + } + + // Build repository path: //.git + let repo_path = self.git_data_path.join(&announcement.repo_path()); + + match git::try_set_head_if_available(&repo_path, head_ref, head_commit) { + Ok(true) => { + tracing::info!( + "Set HEAD to {} in repository {} (from state by {})", + head_ref, + repo_path.display(), + state.event.pubkey.to_hex() + ); + updated_count += 1; + } + Ok(false) => { + tracing::debug!( + "HEAD commit {} not available yet in {}", + head_commit, + repo_path.display() + ); + } + Err(e) => { + tracing::warn!( + "Failed to set HEAD in {}: {}", + repo_path.display(), + e + ); + } + } + } + + Ok(updated_count) + } + /// Extract all reference tags from an event (a, A, q, e, E) /// Returns (addressable_refs, event_refs) fn extract_reference_tags(event: &Event) -> (Vec, Vec) { @@ -345,13 +571,53 @@ impl WritePolicy for Nip34WritePolicy { PolicyResult::Reject(e.to_string()) } }, - KIND_REPOSITORY_STATE =>match validate_state(event) { + KIND_REPOSITORY_STATE => match validate_state(event) { Ok(_) => { - tracing::debug!( - "Accepted repository state: {}", - event_id_str - ); - PolicyResult::Accept + // Parse state to get HEAD and branch info + match RepositoryState::from_event(event.clone()) { + Ok(state) => { + // Try to set HEAD for all authorized repos if this is the latest state + match self.try_set_head_for_authorized_repos(&database, &state).await { + Ok(count) if count > 0 => { + tracing::info!( + "Set HEAD from state event {} for {} repo(s) with identifier {}", + event_id_str, + count, + state.identifier + ); + } + Ok(_) => { + tracing::debug!( + "HEAD not set from state {} - git data not available yet or not latest", + event_id_str + ); + } + Err(e) => { + tracing::warn!( + "Failed to process HEAD from state {}: {}", + event_id_str, + e + ); + } + } + + tracing::debug!( + "Accepted repository state: {}", + event_id_str + ); + PolicyResult::Accept + } + Err(e) => { + tracing::warn!( + "Failed to parse repository state {}: {}", + event_id_str, + e + ); + // Still accept the event even if we can't parse it + // The validation passed, so it's structurally valid + PolicyResult::Accept + } + } } Err(e) => { tracing::warn!( diff --git a/src/nostr/events.rs b/src/nostr/events.rs index 643269a..97688b1 100644 --- a/src/nostr/events.rs +++ b/src/nostr/events.rs @@ -167,6 +167,8 @@ pub struct RepositoryState { pub identifier: String, pub branches: Vec, pub tags: Vec, + /// HEAD reference (e.g., "refs/heads/main") if specified + pub head: Option, } /// Branch state (ref with commit hash) @@ -255,11 +257,39 @@ impl RepositoryState { }) .collect(); + // Extract HEAD reference per NIP-34 + // Tag format: ["HEAD", "ref: refs/heads/main"] or ["HEAD", "refs/heads/main"] + let head = event + .tags + .iter() + .find(|t| { + if let TagKind::Custom(s) = t.kind() { + s.as_ref() == "HEAD" + } else { + false + } + }) + .and_then(|t| { + let parts = t.clone().to_vec(); + if parts.len() >= 2 { + let head_value = &parts[1]; + // Handle both "ref: refs/heads/main" and "refs/heads/main" formats + if let Some(stripped) = head_value.strip_prefix("ref: ") { + Some(stripped.to_string()) + } else { + Some(head_value.clone()) + } + } else { + None + } + }); + Ok(RepositoryState { event, identifier, branches, tags, + head, }) } @@ -283,6 +313,23 @@ impl RepositoryState { pub fn owner_npub(&self) -> String { self.event.pubkey.to_bech32().unwrap_or_default() } + + /// Get the HEAD branch name (without refs/heads/ prefix) + pub fn get_head_branch(&self) -> Option<&str> { + self.head.as_ref().and_then(|h| { + h.strip_prefix("refs/heads/") + }) + } + + /// Check if the HEAD commit is available in the git repository + /// Returns true if we have the git data for the HEAD branch + pub fn head_commit_available(&self) -> bool { + if let Some(head_branch) = self.get_head_branch() { + self.get_branch_commit(head_branch).is_some() + } else { + false + } + } } /// Validate a repository announcement according to GRASP-01 @@ -601,4 +648,131 @@ mod tests { assert_eq!(state.get_branch_commit("main"), Some("a1b2c3d4")); assert_eq!(state.get_tag_commit("v1.0.0"), Some("e5f6g7h8")); } + + #[test] + fn test_state_with_head_ref_prefix() { + use nostr_sdk::Tag; + + let keys = create_test_keys(); + let mut tags = vec![Tag::custom( + nostr_sdk::TagKind::d(), + vec!["test-repo".to_string()], + )]; + + // Add branch + tags.push(Tag::custom( + nostr_sdk::TagKind::Custom("refs/heads/main".into()), + vec!["a1b2c3d4e5f6g7h8".to_string()], + )); + + // Add HEAD with "ref: " prefix (common NIP-34 format) + tags.push(Tag::custom( + nostr_sdk::TagKind::Custom("HEAD".into()), + vec!["ref: refs/heads/main".to_string()], + )); + + let event = EventBuilder::new(Kind::from(KIND_REPOSITORY_STATE), "") + .tags(tags) + .sign_with_keys(&keys) + .unwrap(); + + let state = RepositoryState::from_event(event).unwrap(); + assert_eq!(state.head, Some("refs/heads/main".to_string())); + assert_eq!(state.get_head_branch(), Some("main")); + assert!(state.head_commit_available()); + } + + #[test] + fn test_state_with_head_no_prefix() { + use nostr_sdk::Tag; + + let keys = create_test_keys(); + let mut tags = vec![Tag::custom( + nostr_sdk::TagKind::d(), + vec!["test-repo".to_string()], + )]; + + // Add branch + tags.push(Tag::custom( + nostr_sdk::TagKind::Custom("refs/heads/develop".into()), + vec!["deadbeefcafe".to_string()], + )); + + // Add HEAD without "ref: " prefix (also valid) + tags.push(Tag::custom( + nostr_sdk::TagKind::Custom("HEAD".into()), + vec!["refs/heads/develop".to_string()], + )); + + let event = EventBuilder::new(Kind::from(KIND_REPOSITORY_STATE), "") + .tags(tags) + .sign_with_keys(&keys) + .unwrap(); + + let state = RepositoryState::from_event(event).unwrap(); + assert_eq!(state.head, Some("refs/heads/develop".to_string())); + assert_eq!(state.get_head_branch(), Some("develop")); + assert!(state.head_commit_available()); + } + + #[test] + fn test_state_without_head() { + use nostr_sdk::Tag; + + let keys = create_test_keys(); + let tags = vec![ + Tag::custom( + nostr_sdk::TagKind::d(), + vec!["test-repo".to_string()], + ), + Tag::custom( + nostr_sdk::TagKind::Custom("refs/heads/main".into()), + vec!["a1b2c3d4".to_string()], + ), + ]; + + let event = EventBuilder::new(Kind::from(KIND_REPOSITORY_STATE), "") + .tags(tags) + .sign_with_keys(&keys) + .unwrap(); + + let state = RepositoryState::from_event(event).unwrap(); + assert_eq!(state.head, None); + assert_eq!(state.get_head_branch(), None); + assert!(!state.head_commit_available()); + } + + #[test] + fn test_state_head_commit_not_available() { + use nostr_sdk::Tag; + + let keys = create_test_keys(); + let mut tags = vec![Tag::custom( + nostr_sdk::TagKind::d(), + vec!["test-repo".to_string()], + )]; + + // Add branch for "main" + tags.push(Tag::custom( + nostr_sdk::TagKind::Custom("refs/heads/main".into()), + vec!["a1b2c3d4".to_string()], + )); + + // HEAD points to "develop" which doesn't exist in branches + tags.push(Tag::custom( + nostr_sdk::TagKind::Custom("HEAD".into()), + vec!["refs/heads/develop".to_string()], + )); + + let event = EventBuilder::new(Kind::from(KIND_REPOSITORY_STATE), "") + .tags(tags) + .sign_with_keys(&keys) + .unwrap(); + + let state = RepositoryState::from_event(event).unwrap(); + assert_eq!(state.head, Some("refs/heads/develop".to_string())); + assert_eq!(state.get_head_branch(), Some("develop")); + // HEAD points to develop but only main branch exists in state + assert!(!state.head_commit_available()); + } } -- cgit v1.2.3