git_internal/internal/object/
note.rs1use std::fmt::Display;
14
15use crate::{
16 errors::GitError,
17 hash::{HashKind, ObjectHash},
18 internal::object::{ObjectTrait, ObjectType},
19};
20
21#[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 pub id: ObjectHash,
39 pub target_object_id: ObjectHash,
41 pub content: String,
43}
44
45impl PartialEq for Note {
46 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 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 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 pub fn new(target_object_id: ObjectHash, content: String) -> Self {
100 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 pub fn from_content(content: &str) -> Self {
126 Self::new(ObjectHash::default(), content.to_string())
127 }
128
129 pub fn content_size(&self) -> usize {
131 self.content.len()
132 }
133
134 pub fn is_empty(&self) -> bool {
136 self.content.is_empty()
137 }
138
139 pub fn set_target(&mut self, new_target: ObjectHash) {
147 self.target_object_id = new_target;
148 }
149
150 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 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 fn from_bytes(data: &[u8], hash: ObjectHash) -> Result<Self, GitError>
200 where
201 Self: Sized,
202 {
203 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_object_id: ObjectHash::zero_for_kind(hash.kind()),
212 content,
213 })
214 }
215
216 fn get_type(&self) -> ObjectType {
220 ObjectType::Blob
221 }
222
223 fn get_size(&self) -> usize {
225 self.content.len()
226 }
227
228 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 fn round_trip(kind: HashKind) {
246 let _guard = set_hash_kind_for_test(kind);
247 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 let data = note.to_data().unwrap();
267 assert_eq!(data, content.as_bytes());
268 assert_eq!(note.get_size(), content.len());
269
270 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 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 #[tokio::test]
288 async fn note_async_round_trip() {
289 round_trip(HashKind::Sha1);
290 round_trip(HashKind::Sha256);
291 }
292
293 #[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]
306 fn test_note_demo_functionality() {
307 let _guard = set_hash_kind_for_test(HashKind::Sha1);
308 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 assert_eq!(note, complete_note);
358 assert_eq!(target_id, commit_id);
359 }
360
361 #[test]
363 fn test_note_demo_functionality_sha256() {
364 let _guard = set_hash_kind_for_test(HashKind::Sha256);
365 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 assert_eq!(note, complete_note);
418 assert_eq!(target_id, commit_id);
419 }
420}