Skip to main content

git_internal/internal/object/
note.rs

1//! Git Note object implementation
2//!
3//! Git Notes are a mechanism for adding metadata to existing Git objects (usually commits)
4//! without modifying the original objects. Notes are commonly used for:
5//!
6//! - Adding review comments or approval metadata
7//! - Storing CI/CD build status and code scan results  
8//! - Attaching author signatures, annotations, or other metadata
9//!
10//! In Git's object model, Notes are stored as Blob objects, with the association between
11//! notes and target objects managed through the refs/notes/* namespace.
12
13use std::fmt::Display;
14
15use crate::{
16    errors::GitError,
17    hash::{HashKind, ObjectHash},
18    internal::object::{ObjectTrait, ObjectType},
19};
20
21/// Git Note object structure
22///
23/// A Note represents additional metadata attached to a Git object (typically a commit).
24/// The Note itself is stored as a Blob object in Git's object database, with the
25/// association managed through Git's reference system.
26#[derive(
27    Eq,
28    Debug,
29    Clone,
30    serde::Serialize,
31    serde::Deserialize,
32    rkyv::Archive,
33    rkyv::Serialize,
34    rkyv::Deserialize,
35)]
36pub struct Note {
37    /// The ObjectHash of this Note object (same as the underlying Blob)
38    pub id: ObjectHash,
39    /// The ObjectHash of the object this Note annotates (usually a commit)
40    pub target_object_id: ObjectHash,
41    /// The textual content of the Note
42    pub content: String,
43}
44
45impl PartialEq for Note {
46    /// Two Notes are equal if they have the same ID
47    fn eq(&self, other: &Self) -> bool {
48        self.id == other.id
49    }
50}
51
52impl Display for Note {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        writeln!(f, "Note for object: {}", self.target_object_id)?;
55        writeln!(f, "Content: {}", self.content)
56    }
57}
58
59impl Note {
60    /// Create a new Note for the specified target object with the given content
61    ///
62    /// # Arguments
63    /// * `target_object_id` - The ObjectHash of the object to annotate
64    /// * `content` - The textual content of the note
65    ///
66    /// Create a Note for `target_object_id` with an explicit repository `kind`.
67    ///
68    /// Notes are hashed as blobs. Does not consult the thread-local
69    /// [`HashKind`]; the target ID must belong to `kind`, otherwise the call
70    /// fails closed with [`GitError::InvalidHashValue`]. Never panics.
71    pub fn new_with_kind(
72        kind: HashKind,
73        target_object_id: ObjectHash,
74        content: String,
75    ) -> Result<Self, GitError> {
76        target_object_id.ensure_kind(kind)?;
77        let id =
78            ObjectHash::from_type_and_data_for_kind(kind, ObjectType::Blob, content.as_bytes())?;
79        Ok(Self {
80            id,
81            target_object_id,
82            content,
83        })
84    }
85
86    /// Create a Note with a placeholder (zero) target of an explicit repository `kind`.
87    ///
88    /// The placeholder target is [`ObjectHash::zero_for_kind`] so that it has the
89    /// right width for the repository; see [`Note::from_content`] for the
90    /// thread-local variant.
91    pub fn from_content_with_kind(kind: HashKind, content: &str) -> Result<Self, GitError> {
92        Self::new_with_kind(kind, ObjectHash::zero_for_kind(kind), content.to_string())
93    }
94
95    /// # Returns
96    /// A new Note instance with calculated ID based on the content
97    ///
98    /// Uses the thread-local [`HashKind`]; see [`Note::new_with_kind`].
99    pub fn new(target_object_id: ObjectHash, content: String) -> Self {
100        // Calculate the SHA-1/ SHA-256 hash for this Note's content
101        // Notes are stored as Blob objects in Git
102        let id = ObjectHash::from_type_and_data(ObjectType::Blob, content.as_bytes());
103
104        Self {
105            id,
106            target_object_id,
107            content,
108        }
109    }
110
111    /// Create a Note from content string, with default target object
112    ///
113    /// This is a convenience method for creating Notes when the target
114    /// will be set later by the notes management system.
115    ///
116    /// # Arguments
117    /// * `content` - The textual content of the note
118    ///
119    /// # Returns
120    /// A new Note instance with default target object ID
121    ///
122    /// The default target is the SHA-1 zero ID regardless of the thread-local
123    /// kind (legacy behaviour); see [`Note::from_content_with_kind`] for a
124    /// kind-correct placeholder.
125    pub fn from_content(content: &str) -> Self {
126        Self::new(ObjectHash::default(), content.to_string())
127    }
128
129    /// Get the size of the Note content in bytes
130    pub fn content_size(&self) -> usize {
131        self.content.len()
132    }
133
134    /// Check if the Note is empty (has no content)
135    pub fn is_empty(&self) -> bool {
136        self.content.is_empty()
137    }
138
139    /// Update the target object ID for this Note
140    ///
141    /// This method allows changing which object this Note annotates
142    /// without changing the Note's content or ID.
143    ///
144    /// # Arguments
145    /// * `new_target` - The new target object SHA-1/ SHA-256 hash
146    pub fn set_target(&mut self, new_target: ObjectHash) {
147        self.target_object_id = new_target;
148    }
149
150    /// Create a Note object from raw bytes with explicit target object ID
151    ///
152    /// This is the preferred method when you know both the content and the target object,
153    /// as it preserves the complete Note association information.
154    ///
155    /// # Arguments
156    /// * `data` - The raw byte data (UTF-8 encoded text content)
157    /// * `hash` - The SHA-1/ SHA-256 hash of this Note object
158    /// * `target_object_id` - The SHA-1/ SHA-256 hash of the object this Note annotates
159    ///
160    /// # Returns
161    /// A Result containing the Note object with complete association info
162    pub fn from_bytes_with_target(
163        data: &[u8],
164        hash: ObjectHash,
165        target_object_id: ObjectHash,
166    ) -> Result<Self, GitError> {
167        let content = String::from_utf8(data.to_vec())
168            .map_err(|e| GitError::InvalidNoteObject(format!("Invalid UTF-8 content: {e}")))?;
169
170        Ok(Note {
171            id: hash,
172            target_object_id,
173            content,
174        })
175    }
176
177    /// Serialize a Note with its target association for external storage
178    ///
179    /// This method returns both the Git object data and the target object ID,
180    /// which can be used by higher-level systems to manage the refs/notes/* references.
181    ///
182    /// # Returns
183    /// A tuple of (object_data, target_object_id)
184    pub fn to_data_with_target(&self) -> Result<(Vec<u8>, ObjectHash), GitError> {
185        let data = self.to_data()?;
186        Ok((data, self.target_object_id))
187    }
188}
189
190impl ObjectTrait for Note {
191    /// Create a Note object from raw bytes and hash
192    ///
193    /// # Arguments
194    /// * `data` - The raw byte data (UTF-8 encoded text content)
195    /// * `hash` - The SHA-1/ SHA-256 hash of this Note object
196    ///
197    /// # Returns
198    /// A Result containing the Note object or an error
199    fn from_bytes(data: &[u8], hash: ObjectHash) -> Result<Self, GitError>
200    where
201        Self: Sized,
202    {
203        // Convert bytes to UTF-8 string
204        let content = String::from_utf8(data.to_vec())
205            .map_err(|e| GitError::InvalidNoteObject(format!("Invalid UTF-8 content: {e}")))?;
206
207        Ok(Note {
208            id: hash,
209            // Target association is managed externally; the placeholder has the
210            // width of the note's own repository kind (never a fixed SHA-1 zero).
211            target_object_id: ObjectHash::zero_for_kind(hash.kind()),
212            content,
213        })
214    }
215
216    /// Get the Git object type for Notes
217    ///
218    /// Notes are stored as Blob objects in Git's object database
219    fn get_type(&self) -> ObjectType {
220        ObjectType::Blob
221    }
222
223    /// Get the size of the Note content
224    fn get_size(&self) -> usize {
225        self.content.len()
226    }
227
228    /// Convert the Note to raw byte data for storage
229    ///
230    /// # Returns
231    /// A Result containing the byte representation or an error
232    fn to_data(&self) -> Result<Vec<u8>, GitError> {
233        Ok(self.content.as_bytes().to_vec())
234    }
235}
236
237#[cfg(test)]
238mod tests {
239    use std::str::FromStr;
240
241    use super::*;
242    use crate::hash::{HashKind, ObjectHash, set_hash_kind_for_test};
243
244    /// Helper to build a Note, serialize/deserialize with/without target under given hash kind.
245    fn round_trip(kind: HashKind) {
246        let _guard = set_hash_kind_for_test(kind);
247        // `1234567890abcdef…` repeated to the width of `kind`; no exhaustive match on
248        // `HashKind`, so adding a variant does not break this helper.
249        let pattern: Vec<u8> = [0x12u8, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef]
250            .iter()
251            .cycle()
252            .take(kind.size())
253            .copied()
254            .collect();
255        let target_id = ObjectHash::from_bytes_for_kind(kind, &pattern).unwrap();
256        let hash_len = kind.hex_len();
257        let content = "This commit needs review".to_string();
258        let note = Note::new(target_id, content.clone());
259
260        assert_eq!(note.target_object_id, target_id);
261        assert_eq!(note.content, content);
262        assert_eq!(note.get_type(), ObjectType::Blob);
263        assert_eq!(note.id.to_string().len(), hash_len);
264
265        // serialization without target
266        let data = note.to_data().unwrap();
267        assert_eq!(data, content.as_bytes());
268        assert_eq!(note.get_size(), content.len());
269
270        // basic deserialization (placeholder target has the note's own kind width)
271        let basic = Note::from_bytes(&data, note.id).unwrap();
272        assert_eq!(basic.content, content);
273        assert_eq!(basic.id, note.id);
274        assert_eq!(basic.target_object_id, ObjectHash::zero_for_kind(kind));
275        assert_eq!(basic.target_object_id.kind(), kind);
276
277        // with target
278        let (data_with_target, returned_target) = note.to_data_with_target().unwrap();
279        assert_eq!(returned_target, target_id);
280        let restored = Note::from_bytes_with_target(&data_with_target, note.id, target_id).unwrap();
281        assert_eq!(restored, note);
282        assert_eq!(restored.target_object_id, target_id);
283        assert_eq!(restored.content, content);
284    }
285
286    /// Test round-trip Note serialization/deserialization with SHA-1 and SHA-256
287    #[tokio::test]
288    async fn note_async_round_trip() {
289        round_trip(HashKind::Sha1);
290        round_trip(HashKind::Sha256);
291    }
292
293    /// Invalid UTF-8 content should return an error in both constructors.
294    #[test]
295    fn note_invalid_utf8_errors() {
296        let _guard = set_hash_kind_for_test(HashKind::Sha1);
297        let invalid_utf8 = vec![0xFF, 0xFE, 0xFD];
298        let hash = ObjectHash::from_str("3333333333333333333333333333333333333333").unwrap();
299        let target = ObjectHash::from_str("4444444444444444444444444444444444444444").unwrap();
300        assert!(Note::from_bytes(&invalid_utf8, hash).is_err());
301        assert!(Note::from_bytes_with_target(&invalid_utf8, hash, target).is_err());
302    }
303
304    /// Test Note demo functionality showcasing best practices
305    #[test]
306    fn test_note_demo_functionality() {
307        let _guard = set_hash_kind_for_test(HashKind::Sha1);
308        // This is a demonstration test that shows the complete functionality
309        // It's kept separate from unit tests for clarity
310        println!("\n🚀 Git Note Object Demo - Best Practices");
311        println!("==========================================");
312
313        let commit_id = ObjectHash::from_str("a1b2c3d4e5f6789012345678901234567890abcd").unwrap();
314
315        println!("\n1️⃣ Creating a new Note object:");
316        let note = Note::new(
317            commit_id,
318            "Code review: LGTM! Great implementation.".to_string(),
319        );
320        println!("   Target Commit: {}", note.target_object_id);
321        println!("   Note ID: {}", note.id);
322        println!("   Content: {}", note.content);
323        println!("   Size: {} bytes", note.get_size());
324
325        println!("\n2️⃣ Serializing Note with target association:");
326        let (serialized_data, target_id) = note.to_data_with_target().unwrap();
327        println!("   Serialized size: {} bytes", serialized_data.len());
328        println!("   Target object ID: {}", target_id);
329        println!(
330            "   Git object format: blob {}\\0<content>",
331            note.content.len()
332        );
333        println!(
334            "   Raw data preview: {:?}...",
335            &serialized_data[..std::cmp::min(30, serialized_data.len())]
336        );
337
338        println!("\n3️⃣ Basic deserialization (ObjectTrait):");
339        let basic_note = Note::from_bytes(&serialized_data, note.id).unwrap();
340        println!("   Successfully deserialized!");
341        println!(
342            "   Target Commit: {} (default - target managed externally)",
343            basic_note.target_object_id
344        );
345        println!("   Content: {}", basic_note.content);
346        println!("   Content matches: {}", note.content == basic_note.content);
347
348        println!("\n4️⃣ Best practice deserialization (with target):");
349        let complete_note =
350            Note::from_bytes_with_target(&serialized_data, note.id, target_id).unwrap();
351        println!("   Successfully deserialized with target!");
352        println!("   Target Commit: {}", complete_note.target_object_id);
353        println!("   Content: {}", complete_note.content);
354        println!("   Complete objects are equal: {}", note == complete_note);
355
356        // Basic assertions to ensure demo works
357        assert_eq!(note, complete_note);
358        assert_eq!(target_id, commit_id);
359    }
360
361    /// Test Note demo functionality showcasing best practices with SHA-256
362    #[test]
363    fn test_note_demo_functionality_sha256() {
364        let _guard = set_hash_kind_for_test(HashKind::Sha256);
365        // This is a demonstration test that shows the complete functionality
366        // It's kept separate from unit tests for clarity
367        println!("\n🚀 Git Note Object Demo - Best Practices");
368        println!("==========================================");
369
370        let commit_id = ObjectHash::from_str(
371            "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
372        )
373        .unwrap();
374
375        println!("\n1️⃣ Creating a new Note object:");
376        let note = Note::new(
377            commit_id,
378            "Code review: LGTM! Great implementation.".to_string(),
379        );
380        println!("   Target Commit: {}", note.target_object_id);
381        println!("   Note ID: {}", note.id);
382        println!("   Content: {}", note.content);
383        println!("   Size: {} bytes", note.get_size());
384
385        println!("\n2️⃣ Serializing Note with target association:");
386        let (serialized_data, target_id) = note.to_data_with_target().unwrap();
387        println!("   Serialized size: {} bytes", serialized_data.len());
388        println!("   Target object ID: {}", target_id);
389        println!(
390            "   Git object format: blob {}\\0<content>",
391            note.content.len()
392        );
393        println!(
394            "   Raw data preview: {:?}...",
395            &serialized_data[..std::cmp::min(30, serialized_data.len())]
396        );
397
398        println!("\n3️⃣ Basic deserialization (ObjectTrait):");
399        let basic_note = Note::from_bytes(&serialized_data, note.id).unwrap();
400        println!("   Successfully deserialized!");
401        println!(
402            "   Target Commit: {} (default - target managed externally)",
403            basic_note.target_object_id
404        );
405        println!("   Content: {}", basic_note.content);
406        println!("   Content matches: {}", note.content == basic_note.content);
407
408        println!("\n4️⃣ Best practice deserialization (with target):");
409        let complete_note =
410            Note::from_bytes_with_target(&serialized_data, note.id, target_id).unwrap();
411        println!("   Successfully deserialized with target!");
412        println!("   Target Commit: {}", complete_note.target_object_id);
413        println!("   Content: {}", complete_note.content);
414        println!("   Complete objects are equal: {}", note == complete_note);
415
416        // Basic assertions to ensure demo works
417        assert_eq!(note, complete_note);
418        assert_eq!(target_id, commit_id);
419    }
420}