Skip to main content

grit_lib/notes/
core.rs

1//! `git notes` tree manipulation — the fanout tree mapping `object -> note blob`.
2//!
3//! Notes are stored as blobs in a tree referenced by `refs/notes/commits` (or a
4//! custom namespace via `--ref`). Each leaf in the notes tree is named by the
5//! full hex SHA of the annotated object, optionally split into a fanout layout
6//! (`ab/cd/ef…`) once the note count grows large.
7//!
8//! This module owns the *pure tree operations* over the object database: reading
9//! the notes tree into a flat entry list, computing the fanout layout, writing a
10//! new notes tree + commit, combining note blobs (concatenate / cat_sort_uniq),
11//! and the notes-merge data model (pairing local/remote/base changes and applying
12//! a merge strategy). Notes refs are read and updated through the repository's
13//! [`RefStore`](crate::refs::store::RefStore), so every ref backend (loose/packed,
14//! reftable, or an injected store) sees the same notes.
15
16use crate::error::NotesError;
17use std::collections::{BTreeMap, BTreeSet, HashMap};
18use std::fs;
19
20use time::{OffsetDateTime, UtcOffset};
21
22use crate::commit::assemble_identity;
23use crate::config::ConfigSet;
24use crate::error::{Error, Result};
25use crate::ident::parse_signature_times;
26use crate::ident_resolve::{IdentRole, IdentityEnv};
27use crate::merge_base::merge_bases_first_vs_rest;
28use crate::objects::{
29    parse_commit, parse_tree, serialize_commit, serialize_tree, tree_name_cmp, CommitData,
30    ObjectId, ObjectKind, TreeEntry,
31};
32use crate::refs::list_refs_for_repository;
33use crate::refs::should_autocreate_reflog_with_config;
34use crate::refs::store::{Expected, RawRef, RefNameRef, ReflogUpdate};
35use crate::refs::store_write_value_on_store;
36use crate::repo::Repository;
37use crate::rev_parse::resolve_revision;
38use crate::wildmatch::wildmatch;
39use merge3::{Merge3, StandardMarkers};
40
41/// Per-worktree subdirectory holding the conflicted note blobs during a notes merge.
42const NOTES_MERGE_WORKTREE: &str = "NOTES_MERGE_WORKTREE";
43
44/// One leaf entry in a notes fanout tree (blob pointing at a note object).
45#[derive(Clone, Debug, PartialEq, Eq)]
46pub struct NotesTreeEntry {
47    /// Git tree entry mode for the note blob (typically `100644`).
48    pub mode: u32,
49    /// Fanout path segments ending in the annotated object's hex id.
50    pub path: Vec<u8>,
51    /// Note blob object id stored at this path.
52    pub oid: ObjectId,
53}
54
55/// One annotated object's note change: `(object_id, old_blob, new_blob)`.
56type NoteBlobChange = (ObjectId, Option<ObjectId>, Option<ObjectId>);
57
58enum NotesTreeChild {
59    Blob {
60        /// Tree entry mode for the note blob.
61        mode: u32,
62        /// Note blob object id.
63        oid: ObjectId,
64    },
65    Tree(Vec<NotesTreeEntry>),
66}
67
68/// Extract the annotated object's hex id from a notes tree entry path, if well-formed.
69pub fn note_object_name(path: &[u8]) -> Option<String> {
70    let compact: Vec<u8> = path.iter().copied().filter(|byte| *byte != b'/').collect();
71    if !ObjectId::is_hex_len(compact.len()) || !compact.iter().all(u8::is_ascii_hexdigit) {
72        return None;
73    }
74    String::from_utf8(compact)
75        .ok()
76        .map(|name| name.to_ascii_lowercase())
77}
78
79fn collect_notes_tree_entries(
80    repo: &Repository,
81    tree_oid: &ObjectId,
82    prefix: &[u8],
83    out: &mut Vec<NotesTreeEntry>,
84    max_listable_notes: Option<usize>,
85    listable_seen: &mut usize,
86    truncated: &mut bool,
87) -> Result<()> {
88    if max_listable_notes.is_some_and(|max| *listable_seen >= max) {
89        *truncated = true;
90        return Ok(());
91    }
92    let tree_obj = repo.odb().read(tree_oid)?;
93    if tree_obj.kind != ObjectKind::Tree {
94        return Err(Error::Notes(NotesError::UnexpectedObjectKind {
95            oid: *tree_oid,
96            expected: ObjectKind::Tree,
97            found: tree_obj.kind,
98        }));
99    }
100
101    for entry in parse_tree(&tree_obj.data)? {
102        if max_listable_notes.is_some_and(|max| *listable_seen >= max) {
103            *truncated = true;
104            return Ok(());
105        }
106        let mut path = prefix.to_vec();
107        if !path.is_empty() {
108            path.push(b'/');
109        }
110        path.extend_from_slice(&entry.name);
111
112        if entry.mode == 0o040000 {
113            collect_notes_tree_entries(
114                repo,
115                &entry.oid,
116                &path,
117                out,
118                max_listable_notes,
119                listable_seen,
120                truncated,
121            )?;
122            if *truncated {
123                return Ok(());
124            }
125        } else {
126            let counts = note_object_name(&path).is_some();
127            if max_listable_notes.is_none() || counts {
128                out.push(NotesTreeEntry {
129                    mode: entry.mode,
130                    path,
131                    oid: entry.oid,
132                });
133            }
134            if counts {
135                *listable_seen += 1;
136                if max_listable_notes.is_some_and(|max| *listable_seen >= max) {
137                    *truncated = true;
138                    return Ok(());
139                }
140            }
141        }
142    }
143
144    Ok(())
145}
146
147/// Current target of `notes_ref` in the repository's ref store, or `None` when the ref is absent.
148fn notes_ref_tip(repo: &Repository, notes_ref: &str) -> Result<Option<ObjectId>> {
149    match repo
150        .ref_store()
151        .read_raw(RefNameRef::from_trusted(notes_ref))?
152    {
153        None => Ok(None),
154        Some(RawRef::Direct(oid)) => Ok(Some(oid)),
155        Some(RawRef::Symbolic(_)) => repo
156            .ref_store()
157            .resolve(RefNameRef::from_trusted(notes_ref))
158            .map(Some),
159    }
160}
161
162/// Read the notes tree entries from the notes ref.
163///
164/// `notes_ref` is looked up in the repository's ref store; when no such ref exists it is
165/// resolved as a revision instead (so a notes commit or tree id works too). The target may be a
166/// notes commit or a bare tree.
167///
168/// # Errors
169///
170/// - [`crate::error::NotesError::RefNotCommit`] when the target is neither a commit nor a tree.
171/// - [`crate::error::NotesError::UnexpectedObjectKind`] when a subtree entry is not a tree.
172/// - Ref store and object read failures.
173///
174/// Returns an empty vec when neither a ref nor a revision named `notes_ref` exists.
175pub(crate) fn read_notes_tree(repo: &Repository, notes_ref: &str) -> Result<Vec<NotesTreeEntry>> {
176    Ok(read_notes_snapshot(repo, notes_ref)?.entries)
177}
178
179/// Notes tree entries together with the notes ref tip they were read from.
180pub(crate) struct NotesSnapshot {
181    /// Tip of the notes ref when the entries were read; `None` when the ref did not exist.
182    /// Writes based on these entries must use it as both parent and compare-and-swap value.
183    pub(crate) tip: Option<ObjectId>,
184    /// Flat note entries of the tree at `tip`.
185    pub(crate) entries: Vec<NotesTreeEntry>,
186}
187
188/// Like [`read_notes_tree`], also returning the ref tip the entries came from.
189pub(crate) fn read_notes_snapshot(repo: &Repository, notes_ref: &str) -> Result<NotesSnapshot> {
190    let ref_tip = notes_ref_tip(repo, notes_ref)?;
191    let tip = match ref_tip {
192        Some(oid) => oid,
193        None => match resolve_revision(repo, notes_ref) {
194            Ok(oid) => oid,
195            Err(_) => {
196                return Ok(NotesSnapshot {
197                    tip: None,
198                    entries: Vec::new(),
199                })
200            }
201        },
202    };
203    let obj = repo.odb().read(&tip)?;
204    let tree_oid = match obj.kind {
205        ObjectKind::Commit => parse_commit(&obj.data)?.tree,
206        ObjectKind::Tree => tip,
207        found => {
208            return Err(Error::Notes(NotesError::RefNotCommit {
209                notes_ref: notes_ref.to_owned(),
210                found,
211            }))
212        }
213    };
214    let mut entries = Vec::new();
215    let mut listable_seen = 0usize;
216    let mut truncated = false;
217    collect_notes_tree_entries(
218        repo,
219        &tree_oid,
220        b"",
221        &mut entries,
222        None,
223        &mut listable_seen,
224        &mut truncated,
225    )?;
226    debug_assert!(!truncated, "unlimited notes collect must not truncate");
227    Ok(NotesSnapshot {
228        tip: ref_tip,
229        entries,
230    })
231}
232
233/// Read note tree entries, stopping after `max_listable_notes` **listable** notes when set.
234///
235/// Non-object path segments (for example fanout `!` markers) do not count toward the cap.
236///
237/// Returns `(entries, truncated)` where `truncated` is true when the tree held more listable
238/// notes than returned.
239pub(crate) fn read_notes_tree_limited(
240    repo: &Repository,
241    notes_ref: &str,
242    max_entries: Option<usize>,
243) -> Result<(Vec<NotesTreeEntry>, bool)> {
244    let ref_tip = notes_ref_tip(repo, notes_ref)?;
245    let tip = match ref_tip {
246        Some(oid) => oid,
247        None => match resolve_revision(repo, notes_ref) {
248            Ok(oid) => oid,
249            Err(_) => return Ok((Vec::new(), false)),
250        },
251    };
252    let obj = repo.odb().read(&tip)?;
253    let tree_oid = match obj.kind {
254        ObjectKind::Commit => parse_commit(&obj.data)?.tree,
255        ObjectKind::Tree => tip,
256        found => {
257            return Err(Error::Notes(NotesError::RefNotCommit {
258                notes_ref: notes_ref.to_owned(),
259                found,
260            }))
261        }
262    };
263    let mut entries = Vec::new();
264    let mut listable_seen = 0usize;
265    let mut truncated = false;
266    collect_notes_tree_entries(
267        repo,
268        &tree_oid,
269        b"",
270        &mut entries,
271        max_entries,
272        &mut listable_seen,
273        &mut truncated,
274    )?;
275    Ok((entries, truncated))
276}
277
278fn notes_fanout(entries: &[NotesTreeEntry]) -> usize {
279    let mut note_count = entries
280        .iter()
281        .filter(|entry| note_object_name(&entry.path).is_some())
282        .count();
283    let mut fanout = 0usize;
284    while note_count > 0xff {
285        note_count >>= 8;
286        fanout += 1;
287    }
288    fanout
289}
290
291fn path_with_fanout(hex: &str, fanout: usize) -> Vec<u8> {
292    let mut path = Vec::with_capacity(hex.len() + fanout);
293    let bytes = hex.as_bytes();
294    let split = fanout.min(bytes.len() / 2);
295    for idx in 0..split {
296        let start = idx * 2;
297        path.extend_from_slice(&bytes[start..start + 2]);
298        path.push(b'/');
299    }
300    path.extend_from_slice(&bytes[split * 2..]);
301    path
302}
303
304/// Notes ref tip and root notes tree when the ref exists.
305pub(crate) fn resolve_notes_ref_tree(
306    repo: &Repository,
307    notes_ref: &str,
308) -> Result<(Option<ObjectId>, Option<ObjectId>)> {
309    let tip = notes_ref_tip(repo, notes_ref)?;
310    let Some(tip) = tip else {
311        return Ok((None, None));
312    };
313    Ok((Some(tip), Some(notes_tree_oid(repo, &tip)?)))
314}
315
316fn notes_tree_oid(repo: &Repository, tip: &ObjectId) -> Result<ObjectId> {
317    let obj = repo.odb().read(tip)?;
318    match obj.kind {
319        ObjectKind::Commit => Ok(parse_commit(&obj.data)?.tree),
320        ObjectKind::Tree => Ok(*tip),
321        found => Err(Error::Notes(NotesError::RefNotCommit {
322            notes_ref: String::new(),
323            found,
324        })),
325    }
326}
327
328fn read_tree_entries(repo: &Repository, tree_oid: &ObjectId) -> Result<Vec<TreeEntry>> {
329    let tree_obj = repo.odb().read(tree_oid)?;
330    if tree_obj.kind != ObjectKind::Tree {
331        return Err(Error::Notes(NotesError::UnexpectedObjectKind {
332            oid: *tree_oid,
333            expected: ObjectKind::Tree,
334            found: tree_obj.kind,
335        }));
336    }
337    parse_tree(&tree_obj.data)
338}
339
340fn is_fanout_tree_name(name: &[u8]) -> bool {
341    name.len() == 2 && name.iter().all(u8::is_ascii_hexdigit)
342}
343
344fn is_full_note_blob_name(name: &[u8]) -> bool {
345    ObjectId::is_hex_len(name.len()) && name.iter().all(u8::is_ascii_hexdigit)
346}
347
348#[derive(Clone, Copy, PartialEq, Eq)]
349enum NotesTreeLayout {
350    Empty,
351    FlatNotes,
352    FanoutNotes,
353    Irregular,
354}
355
356fn classify_notes_tree(entries: &[TreeEntry]) -> NotesTreeLayout {
357    if entries.is_empty() {
358        return NotesTreeLayout::Empty;
359    }
360    let mut flat = false;
361    let mut fanout = false;
362    for entry in entries {
363        if entry.mode == 0o040000 {
364            if is_fanout_tree_name(&entry.name) {
365                fanout = true;
366            }
367        } else if is_full_note_blob_name(&entry.name) {
368            flat = true;
369        }
370    }
371    match (flat, fanout) {
372        (true, true) => NotesTreeLayout::Irregular,
373        (true, false) => NotesTreeLayout::FlatNotes,
374        (false, true) => NotesTreeLayout::FanoutNotes,
375        (false, false) => NotesTreeLayout::Empty,
376    }
377}
378
379fn count_flat_note_entries(entries: &[TreeEntry]) -> usize {
380    entries
381        .iter()
382        .filter(|e| e.mode != 0o040000 && is_full_note_blob_name(&e.name))
383        .count()
384}
385
386fn store_tree_entries(repo: &Repository, entries: &[TreeEntry]) -> Result<ObjectId> {
387    let mut sorted = entries.to_vec();
388    sorted.sort_by(|a, b| tree_name_cmp(&a.name, a.mode == 0o040000, &b.name, b.mode == 0o040000));
389    repo.odb().write(ObjectKind::Tree, &serialize_tree(&sorted))
390}
391
392/// One hop on the path from the notes root to a note blob.
393struct NoteTreeHop {
394    entries: Vec<TreeEntry>,
395    child_index: usize,
396}
397
398/// ASCII case-insensitive equality for hex path segments (Git may store `AB` vs `ab`).
399fn hex_name_eq(left: &[u8], right: &[u8]) -> bool {
400    left.len() == right.len()
401        && left
402            .iter()
403            .zip(right)
404            .all(|(a, b)| a.eq_ignore_ascii_case(b))
405}
406
407/// Locate a note blob in an existing fanout or flat tree without reading sibling subtrees.
408pub(crate) fn lookup_note_blob_oid(
409    repo: &Repository,
410    root_tree: &ObjectId,
411    object_hex: &str,
412) -> Result<Option<ObjectId>> {
413    let hex = object_hex.as_bytes();
414    let mut tree_oid = *root_tree;
415    let mut offset = 0usize;
416    loop {
417        let entries = read_tree_entries(repo, &tree_oid)?;
418        if let Some(entry) = entries
419            .iter()
420            .find(|e| e.mode != 0o040000 && hex_name_eq(e.name.as_slice(), &hex[offset..]))
421        {
422            return Ok(Some(entry.oid));
423        }
424        if offset + 2 > hex.len() {
425            return Ok(None);
426        }
427        let prefix = &hex[offset..offset + 2];
428        let Some(child) = entries
429            .iter()
430            .find(|e| e.mode == 0o040000 && hex_name_eq(e.name.as_slice(), prefix))
431        else {
432            return Ok(None);
433        };
434        offset += 2;
435        tree_oid = child.oid;
436    }
437}
438
439/// Result of an in-place notes tree splice; [`NotesSpliceResult::Fallback`] means callers should
440/// rebuild with [`write_notes_tree`].
441pub(crate) enum NotesSpliceResult {
442    Tree(ObjectId),
443    Fallback,
444}
445
446pub(crate) fn splice_note_upsert(
447    repo: &Repository,
448    root_tree: Option<ObjectId>,
449    object_hex: &str,
450    blob_oid: ObjectId,
451) -> Result<NotesSpliceResult> {
452    let hex = object_hex.as_bytes();
453    if !ObjectId::is_hex_len(hex.len()) {
454        return Ok(NotesSpliceResult::Fallback);
455    }
456    let Some(root) = root_tree else {
457        let tree = store_tree_entries(
458            repo,
459            &[TreeEntry {
460                mode: 0o100644,
461                name: hex.to_vec(),
462                oid: blob_oid,
463            }],
464        )?;
465        return Ok(NotesSpliceResult::Tree(tree));
466    };
467
468    let root_entries = read_tree_entries(repo, &root)?;
469    match classify_notes_tree(&root_entries) {
470        NotesTreeLayout::Irregular => Ok(NotesSpliceResult::Fallback),
471        NotesTreeLayout::FlatNotes => {
472            if let Some((mode, old)) = find_note_in_flat_tree(&root_entries, hex) {
473                if old == blob_oid {
474                    Ok(NotesSpliceResult::Tree(root))
475                } else {
476                    let mut entries = root_entries;
477                    replace_blob_in_entries(&mut entries, hex, mode, blob_oid);
478                    Ok(NotesSpliceResult::Tree(store_tree_entries(repo, &entries)?))
479                }
480            } else if count_flat_note_entries(&root_entries) >= 0xff {
481                Ok(NotesSpliceResult::Fallback)
482            } else {
483                let mut entries = root_entries;
484                entries.push(TreeEntry {
485                    mode: 0o100644,
486                    name: hex.to_vec(),
487                    oid: blob_oid,
488                });
489                Ok(NotesSpliceResult::Tree(store_tree_entries(repo, &entries)?))
490            }
491        }
492        NotesTreeLayout::Empty | NotesTreeLayout::FanoutNotes => {
493            match walk_note_for_upsert(repo, root, hex, blob_oid)? {
494                Some(tree) => Ok(NotesSpliceResult::Tree(tree)),
495                None => Ok(NotesSpliceResult::Fallback),
496            }
497        }
498    }
499}
500
501pub(crate) fn splice_note_remove(
502    repo: &Repository,
503    root_tree: ObjectId,
504    object_hex: &str,
505) -> Result<NotesSpliceResult> {
506    let hex = object_hex.as_bytes();
507    if !ObjectId::is_hex_len(hex.len()) {
508        return Ok(NotesSpliceResult::Fallback);
509    }
510    let root_entries = read_tree_entries(repo, &root_tree)?;
511    match classify_notes_tree(&root_entries) {
512        NotesTreeLayout::Irregular => Ok(NotesSpliceResult::Fallback),
513        NotesTreeLayout::FlatNotes => {
514            let mut entries = root_entries;
515            if remove_blob_named(&mut entries, hex) {
516                Ok(NotesSpliceResult::Tree(store_tree_entries(repo, &entries)?))
517            } else {
518                Ok(NotesSpliceResult::Tree(root_tree))
519            }
520        }
521        NotesTreeLayout::Empty | NotesTreeLayout::FanoutNotes => {
522            match walk_note_for_remove(repo, root_tree, hex)? {
523                Some(tree) => Ok(NotesSpliceResult::Tree(tree)),
524                None => Ok(NotesSpliceResult::Fallback),
525            }
526        }
527    }
528}
529
530fn find_note_in_flat_tree(entries: &[TreeEntry], hex: &[u8]) -> Option<(u32, ObjectId)> {
531    entries
532        .iter()
533        .find(|e| e.mode != 0o040000 && hex_name_eq(e.name.as_slice(), hex))
534        .map(|e| (e.mode, e.oid))
535}
536
537fn replace_blob_in_entries(entries: &mut [TreeEntry], hex: &[u8], mode: u32, blob: ObjectId) {
538    for entry in entries.iter_mut() {
539        if entry.mode != 0o040000 && hex_name_eq(entry.name.as_slice(), hex) {
540            entry.mode = mode;
541            entry.oid = blob;
542            return;
543        }
544    }
545}
546
547fn remove_blob_named(entries: &mut Vec<TreeEntry>, name: &[u8]) -> bool {
548    let before = entries.len();
549    entries.retain(|e| !(e.mode != 0o040000 && hex_name_eq(e.name.as_slice(), name)));
550    entries.len() < before
551}
552
553fn walk_note_for_upsert(
554    repo: &Repository,
555    root_tree: ObjectId,
556    hex: &[u8],
557    blob_oid: ObjectId,
558) -> Result<Option<ObjectId>> {
559    let mut path: Vec<NoteTreeHop> = Vec::new();
560    let mut tree_oid = root_tree;
561    let mut offset = 0usize;
562    loop {
563        let entries = read_tree_entries(repo, &tree_oid)?;
564        let layout = classify_notes_tree(&entries);
565        if layout == NotesTreeLayout::Irregular {
566            return Ok(None);
567        }
568        if let Some(idx) = entries
569            .iter()
570            .position(|e| e.mode != 0o040000 && hex_name_eq(e.name.as_slice(), &hex[offset..]))
571        {
572            if entries[idx].oid == blob_oid {
573                return Ok(Some(root_tree));
574            }
575            let mut new_entries = entries;
576            new_entries[idx].oid = blob_oid;
577            return Ok(Some(rewrite_note_path(repo, &path, new_entries)?));
578        }
579
580        let can_descend = layout == NotesTreeLayout::FanoutNotes
581            || (layout == NotesTreeLayout::Empty && offset == 0);
582        if can_descend && offset + 2 <= hex.len() {
583            let prefix = &hex[offset..offset + 2];
584            if let Some(child_idx) = entries
585                .iter()
586                .position(|e| e.mode == 0o040000 && hex_name_eq(e.name.as_slice(), prefix))
587            {
588                let child_oid = entries[child_idx].oid;
589                path.push(NoteTreeHop {
590                    entries,
591                    child_index: child_idx,
592                });
593                offset += 2;
594                tree_oid = child_oid;
595                continue;
596            }
597            let leaf = store_tree_entries(
598                repo,
599                &[TreeEntry {
600                    mode: 0o100644,
601                    name: hex[offset + 2..].to_vec(),
602                    oid: blob_oid,
603                }],
604            )?;
605            let mut parent_entries = entries;
606            parent_entries.push(TreeEntry {
607                mode: 0o040000,
608                name: prefix.to_vec(),
609                oid: leaf,
610            });
611            return Ok(Some(rewrite_note_path(repo, &path, parent_entries)?));
612        }
613
614        if layout == NotesTreeLayout::FlatNotes && offset == 0 {
615            return Ok(None);
616        }
617
618        let mut new_entries = entries;
619        new_entries.push(TreeEntry {
620            mode: 0o100644,
621            name: hex[offset..].to_vec(),
622            oid: blob_oid,
623        });
624        return Ok(Some(rewrite_note_path(repo, &path, new_entries)?));
625    }
626}
627
628fn walk_note_for_remove(
629    repo: &Repository,
630    root_tree: ObjectId,
631    hex: &[u8],
632) -> Result<Option<ObjectId>> {
633    let mut path: Vec<NoteTreeHop> = Vec::new();
634    let mut tree_oid = root_tree;
635    let mut offset = 0usize;
636    loop {
637        let entries = read_tree_entries(repo, &tree_oid)?;
638        if classify_notes_tree(&entries) == NotesTreeLayout::Irregular {
639            return Ok(None);
640        }
641        if let Some(idx) = entries
642            .iter()
643            .position(|e| e.mode != 0o040000 && hex_name_eq(e.name.as_slice(), &hex[offset..]))
644        {
645            let mut new_entries = entries;
646            new_entries.remove(idx);
647            return Ok(Some(rewrite_note_path_or_drop(repo, &path, new_entries)?));
648        }
649        if offset + 2 > hex.len() {
650            return Ok(Some(root_tree));
651        }
652        let prefix = &hex[offset..offset + 2];
653        let Some(child_idx) = entries
654            .iter()
655            .position(|e| e.mode == 0o040000 && hex_name_eq(e.name.as_slice(), prefix))
656        else {
657            return Ok(Some(root_tree));
658        };
659        let child_oid = entries[child_idx].oid;
660        path.push(NoteTreeHop {
661            entries,
662            child_index: child_idx,
663        });
664        offset += 2;
665        tree_oid = child_oid;
666    }
667}
668
669fn rewrite_note_path(
670    repo: &Repository,
671    path: &[NoteTreeHop],
672    leaf_entries: Vec<TreeEntry>,
673) -> Result<ObjectId> {
674    let mut oid = store_tree_entries(repo, &leaf_entries)?;
675    for hop in path.iter().rev() {
676        let mut entries = hop.entries.clone();
677        entries[hop.child_index].oid = oid;
678        oid = store_tree_entries(repo, &entries)?;
679    }
680    Ok(oid)
681}
682
683fn rewrite_note_path_or_drop(
684    repo: &Repository,
685    path: &[NoteTreeHop],
686    leaf_entries: Vec<TreeEntry>,
687) -> Result<ObjectId> {
688    if leaf_entries.is_empty() {
689        if let Some(hop) = path.last() {
690            let mut parent = hop.entries.clone();
691            parent.remove(hop.child_index);
692            let parent_path = &path[..path.len().saturating_sub(1)];
693            return rewrite_note_path_or_drop(repo, parent_path, parent);
694        }
695        return store_tree_entries(repo, &leaf_entries);
696    }
697    rewrite_note_path(repo, path, leaf_entries)
698}
699
700fn write_notes_subtree(repo: &Repository, entries: &[NotesTreeEntry]) -> Result<ObjectId> {
701    let mut children: BTreeMap<Vec<u8>, NotesTreeChild> = BTreeMap::new();
702
703    for entry in entries {
704        if let Some(slash_pos) = entry.path.iter().position(|byte| *byte == b'/') {
705            let child_name = entry.path[..slash_pos].to_vec();
706            let child_entry = NotesTreeEntry {
707                mode: entry.mode,
708                path: entry.path[slash_pos + 1..].to_vec(),
709                oid: entry.oid,
710            };
711            children
712                .entry(child_name)
713                .or_insert_with(|| NotesTreeChild::Tree(Vec::new()));
714            if let Some(NotesTreeChild::Tree(tree_entries)) =
715                children.get_mut(&entry.path[..slash_pos])
716            {
717                tree_entries.push(child_entry);
718            }
719        } else {
720            children.insert(
721                entry.path.clone(),
722                NotesTreeChild::Blob {
723                    mode: entry.mode,
724                    oid: entry.oid,
725                },
726            );
727        }
728    }
729
730    let mut tree_entries = Vec::with_capacity(children.len());
731    for (name, child) in children {
732        match child {
733            NotesTreeChild::Blob { mode, oid } => tree_entries.push(TreeEntry { mode, name, oid }),
734            NotesTreeChild::Tree(child_entries) => {
735                let oid = write_notes_subtree(repo, &child_entries)?;
736                tree_entries.push(TreeEntry {
737                    mode: 0o040000,
738                    name,
739                    oid,
740                });
741            }
742        }
743    }
744
745    tree_entries
746        .sort_by(|a, b| tree_name_cmp(&a.name, a.mode == 0o040000, &b.name, b.mode == 0o040000));
747
748    let tree_data = serialize_tree(&tree_entries);
749    repo.odb().write(ObjectKind::Tree, &tree_data)
750}
751
752/// Write `entries` as a notes tree, re-laying out note paths with the fanout their count needs.
753pub(crate) fn materialize_notes_tree(
754    repo: &Repository,
755    entries: &[NotesTreeEntry],
756) -> Result<ObjectId> {
757    write_notes_tree(repo, entries)
758}
759
760fn write_notes_tree(repo: &Repository, entries: &[NotesTreeEntry]) -> Result<ObjectId> {
761    let fanout = notes_fanout(entries);
762    let rewritten_entries: Vec<_> = entries
763        .iter()
764        .map(|entry| NotesTreeEntry {
765            mode: entry.mode,
766            path: note_object_name(&entry.path)
767                .map(|name| path_with_fanout(&name, fanout))
768                .unwrap_or_else(|| entry.path.clone()),
769            oid: entry.oid,
770        })
771        .collect();
772    write_notes_subtree(repo, &rewritten_entries)
773}
774
775/// Identity lines and message for one notes commit.
776pub(crate) struct NotesCommit<'a> {
777    pub(crate) message: &'a str,
778    /// Full author line (`Name <email> unix tz`).
779    pub(crate) author: &'a str,
780    /// Full committer line (`Name <email> unix tz`).
781    pub(crate) committer: &'a str,
782}
783
784/// Write the notes tree for `entries` and a commit on top of `parents`; returns the commit id.
785pub(crate) fn preview_notes_commit(
786    repo: &Repository,
787    parent: Option<ObjectId>,
788    entries: &[NotesTreeEntry],
789    commit: &NotesCommit<'_>,
790) -> Result<ObjectId> {
791    write_notes_commit_object(repo, entries, commit, parent.into_iter().collect())
792}
793
794fn write_notes_commit_object(
795    repo: &Repository,
796    entries: &[NotesTreeEntry],
797    commit: &NotesCommit<'_>,
798    parents: Vec<ObjectId>,
799) -> Result<ObjectId> {
800    let tree = write_notes_tree(repo, entries)?;
801    write_notes_commit_object_on_tree(repo, tree, commit, parents)
802}
803
804fn write_notes_commit_object_on_tree(
805    repo: &Repository,
806    tree: ObjectId,
807    commit: &NotesCommit<'_>,
808    parents: Vec<ObjectId>,
809) -> Result<ObjectId> {
810    let message = if commit.message.ends_with('\n') {
811        commit.message.to_owned()
812    } else {
813        format!("{}\n", commit.message)
814    };
815    let data = CommitData {
816        tree,
817        parents,
818        author: commit.author.to_owned(),
819        committer: commit.committer.to_owned(),
820        author_raw: Vec::new(),
821        committer_raw: Vec::new(),
822        encoding: None,
823        message,
824        raw_message: None,
825        extra_headers: Vec::new(),
826    };
827    repo.odb()
828        .write(ObjectKind::Commit, &serialize_commit(&data))
829}
830
831/// Like [`preview_notes_commit`], but the notes tree is already materialized.
832pub(crate) fn preview_notes_commit_on_tree(
833    repo: &Repository,
834    parent: Option<ObjectId>,
835    tree_oid: ObjectId,
836    commit: &NotesCommit<'_>,
837) -> Result<ObjectId> {
838    write_notes_commit_object_on_tree(repo, tree_oid, commit, parent.into_iter().collect())
839}
840
841pub(crate) fn write_notes_commit_idents_on_tree(
842    repo: &Repository,
843    notes_ref: &str,
844    parent: Option<ObjectId>,
845    tree_oid: ObjectId,
846    message: &str,
847    author: &str,
848    committer: &str,
849) -> Result<()> {
850    let oid = write_notes_commit_object_on_tree(
851        repo,
852        tree_oid,
853        &NotesCommit {
854            message,
855            author,
856            committer,
857        },
858        parent.into_iter().collect(),
859    )?;
860    repo.odb().flush_for_publish()?;
861    update_notes_ref(
862        repo,
863        notes_ref,
864        parent,
865        oid,
866        &NotesCommit {
867            message,
868            author,
869            committer,
870        },
871    )?;
872    Ok(())
873}
874
875/// Timestamp of a full identity line, for the reflog entry written next to it.
876fn signature_time(ident: &str) -> OffsetDateTime {
877    parse_signature_times(ident)
878        .and_then(|times| {
879            let offset =
880                UtcOffset::from_whole_seconds(i32::try_from(times.tz_offset_secs).ok()?).ok()?;
881            let at = OffsetDateTime::from_unix_timestamp(times.unix_seconds).ok()?;
882            Some(at.to_offset(offset))
883        })
884        .unwrap_or(OffsetDateTime::UNIX_EPOCH)
885}
886
887/// Move `notes_ref` from `old` (`None`: the ref must not exist yet) to `new`, logging the update
888/// in the same ref transaction when the ref has or may auto-create a reflog.
889fn update_notes_ref(
890    repo: &Repository,
891    notes_ref: &str,
892    old: Option<ObjectId>,
893    new: ObjectId,
894    commit: &NotesCommit<'_>,
895) -> Result<()> {
896    let config = repo.config().snapshot()?;
897    let log = should_autocreate_reflog_with_config(config.as_ref(), repo.git_dir(), notes_ref)
898        || repo
899            .ref_store()
900            .reflog_exists(RefNameRef::from_trusted(notes_ref))?;
901    let reflog = log.then(|| ReflogUpdate {
902        identity: commit.committer.to_owned(),
903        message: format!("notes: {}", commit.message.trim_end_matches('\n')),
904        time: signature_time(commit.committer),
905        old_oid: None,
906        new_oid: None,
907    });
908    store_write_value_on_store(
909        repo.ref_store(),
910        repo.git_dir(),
911        notes_ref,
912        Some(RawRef::Direct(new)),
913        old.map_or(Expected::Missing, Expected::Oid),
914        reflog,
915    )
916}
917
918/// Commit `entries` on top of `parent` and move `notes_ref` from `parent` to the new commit.
919///
920/// `parent` must be the tip the entries were read from, so a concurrent update in between
921/// fails the compare-and-swap instead of being dropped from the new tree.
922fn commit_notes_tree(
923    repo: &Repository,
924    notes_ref: &str,
925    parent: Option<ObjectId>,
926    entries: &[NotesTreeEntry],
927    commit: &NotesCommit<'_>,
928) -> Result<ObjectId> {
929    let oid = write_notes_commit_object(repo, entries, commit, parent.into_iter().collect())?;
930    repo.odb().flush_for_publish()?;
931    update_notes_ref(repo, notes_ref, parent, oid, commit)?;
932    Ok(oid)
933}
934
935/// Write a new notes tree and commit, updating the notes ref.
936///
937/// Author and committer come from `GIT_{AUTHOR,COMMITTER}_{NAME,EMAIL,DATE}` and `user.*`
938/// config, timestamped with the repository's wall clock. Use
939/// [`RepositoryNotes`](crate::repo_handles::RepositoryNotes) to pass explicit identities.
940///
941/// `entries` replace the whole notes tree. The commit's parent and the compare-and-swap value
942/// are the tip read here, so an update made after the caller read `entries` but before this call
943/// is overwritten; [`RepositoryNotes`](crate::repo_handles::RepositoryNotes) reads and writes
944/// against one tip and rejects such races.
945///
946/// # Errors
947///
948/// - Ref store errors, including a compare-and-swap failure when `notes_ref` moves while the
949///   commit is written.
950/// - Object write and config load failures.
951pub(crate) fn write_notes_commit(
952    repo: &Repository,
953    notes_ref: &str,
954    entries: &[NotesTreeEntry],
955    message: &str,
956) -> Result<()> {
957    let (author, committer) = wall_clock_notes_idents(repo)?;
958    let parent = notes_ref_tip(repo, notes_ref)?;
959    commit_notes_tree(
960        repo,
961        notes_ref,
962        parent,
963        entries,
964        &NotesCommit {
965            message,
966            author: &author,
967            committer: &committer,
968        },
969    )?;
970    Ok(())
971}
972
973/// Write a notes tree commit using explicit author and committer identity lines.
974///
975/// Identity strings must already include timestamp and timezone (`Name <email> unix tz`).
976/// `parent` is the [`NotesSnapshot::tip`] the entries were read from.
977pub(crate) fn write_notes_commit_idents(
978    repo: &Repository,
979    notes_ref: &str,
980    parent: Option<ObjectId>,
981    entries: &[NotesTreeEntry],
982    message: &str,
983    author: &str,
984    committer: &str,
985) -> Result<()> {
986    commit_notes_tree(
987        repo,
988        notes_ref,
989        parent,
990        entries,
991        &NotesCommit {
992            message,
993            author,
994            committer,
995        },
996    )?;
997    Ok(())
998}
999
1000/// Remove a note for `object_hex` when present. Returns whether an entry was removed.
1001#[must_use]
1002pub fn remove_note_entry(entries: &mut Vec<NotesTreeEntry>, object_hex: &str) -> bool {
1003    let before = entries.len();
1004    entries.retain(|e| note_object_name(&e.path).as_deref() != Some(object_hex));
1005    entries.len() < before
1006}
1007
1008/// Author and committer lines for notes commits written without explicit identities.
1009fn wall_clock_notes_idents(repo: &Repository) -> Result<(String, String)> {
1010    let config = repo.config().snapshot()?;
1011    let now = repo.identity_now();
1012    Ok((
1013        notes_ident(repo.environment(), config.as_ref(), IdentRole::Author, now),
1014        notes_ident(
1015            repo.environment(),
1016            config.as_ref(),
1017            IdentRole::Committer,
1018            now,
1019        ),
1020    ))
1021}
1022
1023/// Identity line for a notes commit from `GIT_<ROLE>_{NAME,EMAIL,DATE}` (the committer also
1024/// falls back to the author variables), then `user.name` / `user.email`.
1025fn notes_ident<E: IdentityEnv>(
1026    env: &E,
1027    config: &ConfigSet,
1028    role: IdentRole,
1029    now: OffsetDateTime,
1030) -> String {
1031    let (name_key, email_key, date_key) = match role {
1032        IdentRole::Author => ("GIT_AUTHOR_NAME", "GIT_AUTHOR_EMAIL", "GIT_AUTHOR_DATE"),
1033        IdentRole::Committer => (
1034            "GIT_COMMITTER_NAME",
1035            "GIT_COMMITTER_EMAIL",
1036            "GIT_COMMITTER_DATE",
1037        ),
1038    };
1039    let non_blank = |key: &str| env.var(key).filter(|v| !v.trim().is_empty());
1040    let author_fallback = |key: &str| match role {
1041        IdentRole::Committer => non_blank(key),
1042        IdentRole::Author => None,
1043    };
1044
1045    let name = non_blank(name_key)
1046        .or_else(|| author_fallback("GIT_AUTHOR_NAME"))
1047        .or_else(|| config.value("user.name"))
1048        .unwrap_or_else(|| "Unknown".to_owned());
1049    let email = non_blank(email_key)
1050        .or_else(|| author_fallback("GIT_AUTHOR_EMAIL"))
1051        .or_else(|| config.value("user.email"))
1052        .unwrap_or_default();
1053    assemble_identity(&name, &email, non_blank(date_key).as_deref(), now)
1054}
1055
1056/// How to combine conflicting note blobs during a notes merge.
1057#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1058pub enum NotesMergeStrategy {
1059    /// Leave conflicts for the user to resolve in the worktree.
1060    Manual,
1061    /// Keep the local note blob on conflict.
1062    Ours,
1063    /// Keep the remote note blob on conflict.
1064    Theirs,
1065    /// Concatenate both note blobs on conflict.
1066    Union,
1067    /// Concatenate, sort lines, and deduplicate on conflict.
1068    CatSortUniq,
1069}
1070
1071#[derive(Clone, Debug)]
1072enum LocalNoteState {
1073    Unset,
1074    Deleted,
1075    Present(ObjectId),
1076}
1077
1078#[derive(Clone, Debug)]
1079struct NotesMergePair {
1080    obj: ObjectId,
1081    base_blob: Option<ObjectId>,
1082    remote_blob: Option<ObjectId>,
1083    local: LocalNoteState,
1084}
1085
1086impl NotesMergePair {
1087    /// The local side's note relative to the merge base: `None` when local left the note as it
1088    /// was at the base, `Some(None)` when local deleted it, `Some(Some(blob))` when local set it.
1089    fn local_change(&self) -> Option<Option<ObjectId>> {
1090        match self.local {
1091            LocalNoteState::Unset => None,
1092            LocalNoteState::Present(blob) if Some(blob) == self.base_blob => None,
1093            LocalNoteState::Present(blob) => Some(Some(blob)),
1094            LocalNoteState::Deleted => Some(None),
1095        }
1096    }
1097}
1098
1099/// Full ref name for a Git notes namespace (`refs/notes/…`).
1100#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1101pub struct NotesRef(String);
1102
1103impl NotesRef {
1104    /// Default notes ref (`refs/notes/commits`).
1105    #[must_use]
1106    pub fn commits() -> Self {
1107        Self("refs/notes/commits".to_owned())
1108    }
1109
1110    /// Parse a full ref name that must live under `refs/notes/`.
1111    ///
1112    /// Used for `GIT_NOTES_REF`, `core.notesRef`, and other configured refs (not
1113    /// `--ref`, which uses [`Self::parse`]).
1114    ///
1115    /// # Errors
1116    ///
1117    /// Returns [`crate::error::NotesError::InvalidRef`](crate::error::NotesError::InvalidRef) when
1118    /// `full` is not prefixed with `refs/notes/` or is not a valid ref name (env/config
1119    /// values are not trimmed or otherwise normalized).
1120    pub fn from_full(full: &str) -> Result<Self> {
1121        if !full.starts_with("refs/notes/") {
1122            return Err(Error::Notes(NotesError::InvalidRef {
1123                name: full.to_owned(),
1124            }));
1125        }
1126        use crate::check_ref_format::{check_refname_format, RefFormatOptions};
1127        if check_refname_format(full, &RefFormatOptions::default()).is_err() {
1128            return Err(Error::Notes(NotesError::InvalidRef {
1129                name: full.to_owned(),
1130            }));
1131        }
1132        Ok(Self(full.to_owned()))
1133    }
1134
1135    /// Parse a short or full notes ref the same way Git's `--ref` flag does: `name` and
1136    /// `notes/name` both become `refs/notes/name`; a name already under `refs/notes/` is kept.
1137    #[must_use]
1138    pub fn parse(short_or_full: &str) -> Self {
1139        Self(expand_notes_ref(short_or_full))
1140    }
1141
1142    /// Borrow the canonical ref string.
1143    #[must_use]
1144    pub fn as_str(&self) -> &str {
1145        &self.0
1146    }
1147}
1148
1149impl std::fmt::Display for NotesRef {
1150    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1151        f.write_str(&self.0)
1152    }
1153}
1154
1155/// Resolve the default notes ref from `GIT_NOTES_REF`, then `core.notesRef`, then
1156/// [`NotesRef::commits`].
1157///
1158/// Config and environment values must be full refs under `refs/notes/` (same rules
1159/// as Git's `init_notes_ref`).
1160///
1161/// # Errors
1162///
1163/// Returns [`crate::error::NotesError::InvalidRef`](crate::error::NotesError::InvalidRef) when a
1164/// configured value is empty or outside `refs/notes/`.
1165pub fn resolve_configured_notes_ref<E: IdentityEnv>(
1166    env: &E,
1167    config: &ConfigSet,
1168) -> Result<NotesRef> {
1169    if let Some(value) = env.var("GIT_NOTES_REF") {
1170        return NotesRef::from_full(&value);
1171    }
1172    if let Some(value) = config.value("core.notesRef") {
1173        return NotesRef::from_full(&value);
1174    }
1175    Ok(NotesRef::commits())
1176}
1177
1178/// Expansion behind [`NotesRef::parse`]; configured refs are used verbatim instead.
1179fn expand_notes_ref(short_or_full: &str) -> String {
1180    if short_or_full.starts_with("refs/notes/") {
1181        short_or_full.to_owned()
1182    } else if short_or_full.starts_with("notes/") {
1183        format!("refs/{short_or_full}")
1184    } else {
1185        format!("refs/notes/{short_or_full}")
1186    }
1187}
1188
1189/// Path to the per-merge worktree directory under the repository git dir.
1190fn notes_merge_worktree_path(repo: &Repository) -> std::path::PathBuf {
1191    repo.git_dir().join(NOTES_MERGE_WORKTREE)
1192}
1193
1194/// True when `NOTES_MERGE_WORKTREE` exists and holds at least one entry.
1195fn notes_merge_worktree_nonempty(worktree: &std::path::Path) -> bool {
1196    if !worktree.is_dir() {
1197        return false;
1198    }
1199    let Ok(entries) = fs::read_dir(worktree) else {
1200        return false;
1201    };
1202    entries.flatten().next().is_some()
1203}
1204
1205/// Map annotated object → note blob OID for one notes tree (any fanout layout).
1206fn notes_tree_blob_by_object(
1207    repo: &Repository,
1208    tree_oid: &ObjectId,
1209) -> Result<HashMap<ObjectId, ObjectId>> {
1210    let mut flat = Vec::new();
1211    let mut listable_seen = 0usize;
1212    let mut truncated = false;
1213    collect_notes_tree_entries(
1214        repo,
1215        tree_oid,
1216        b"",
1217        &mut flat,
1218        None,
1219        &mut listable_seen,
1220        &mut truncated,
1221    )?;
1222    debug_assert!(!truncated);
1223    let mut map = HashMap::new();
1224    for entry in flat {
1225        let Some(hex) = note_object_name(&entry.path) else {
1226            continue;
1227        };
1228        map.insert(ObjectId::from_hex(&hex)?, entry.oid);
1229    }
1230    Ok(map)
1231}
1232
1233fn diff_note_blob_changes(
1234    repo: &Repository,
1235    old_tree: Option<&ObjectId>,
1236    new_tree: Option<&ObjectId>,
1237) -> Result<Vec<NoteBlobChange>> {
1238    let old_map = match old_tree {
1239        Some(t) => notes_tree_blob_by_object(repo, t)?,
1240        None => HashMap::new(),
1241    };
1242    let new_map = match new_tree {
1243        Some(t) => notes_tree_blob_by_object(repo, t)?,
1244        None => HashMap::new(),
1245    };
1246    let keys: BTreeSet<ObjectId> = old_map.keys().chain(new_map.keys()).copied().collect();
1247    let mut out = Vec::new();
1248    for obj in keys {
1249        let o_old = old_map.get(&obj).copied();
1250        let o_new = new_map.get(&obj).copied();
1251        match (o_old, o_new) {
1252            (None, Some(new_b)) => out.push((obj, None, Some(new_b))),
1253            (Some(old_b), None) => out.push((obj, Some(old_b), None)),
1254            (Some(old_b), Some(new_b)) if old_b != new_b => {
1255                out.push((obj, Some(old_b), Some(new_b)));
1256            }
1257            _ => {}
1258        }
1259    }
1260    Ok(out)
1261}
1262
1263fn build_merge_pairs(
1264    base_tree: Option<ObjectId>,
1265    local_tree: ObjectId,
1266    remote_tree: ObjectId,
1267    repo: &Repository,
1268) -> Result<Vec<NotesMergePair>> {
1269    let remote_raw = diff_note_blob_changes(repo, base_tree.as_ref(), Some(&remote_tree))?;
1270    let local_raw = diff_note_blob_changes(repo, base_tree.as_ref(), Some(&local_tree))?;
1271    let mut map: HashMap<ObjectId, NotesMergePair> = HashMap::new();
1272    for (obj, old_b, new_b) in remote_raw {
1273        map.insert(
1274            obj,
1275            NotesMergePair {
1276                obj,
1277                base_blob: old_b,
1278                remote_blob: new_b,
1279                local: LocalNoteState::Unset,
1280            },
1281        );
1282    }
1283
1284    for (obj, old_b, new_b) in local_raw {
1285        let local_state = match new_b {
1286            Some(new_oid) => LocalNoteState::Present(new_oid),
1287            None => LocalNoteState::Deleted,
1288        };
1289        if let Some(p) = map.get_mut(&obj) {
1290            p.local = local_state;
1291        } else {
1292            map.insert(
1293                obj,
1294                NotesMergePair {
1295                    obj,
1296                    base_blob: old_b,
1297                    remote_blob: old_b,
1298                    local: local_state,
1299                },
1300            );
1301        }
1302    }
1303
1304    let mut v: Vec<_> = map.into_values().collect();
1305    v.sort_by_key(|a| a.obj);
1306    Ok(v)
1307}
1308
1309/// Bytes of the note blob `oid`.
1310///
1311/// # Errors
1312///
1313/// [`crate::error::NotesError::UnexpectedObjectKind`] when `oid` is not a blob, or object read failures.
1314pub(crate) fn read_blob_bytes(repo: &Repository, oid: &ObjectId) -> Result<Vec<u8>> {
1315    let obj = repo.odb().read(oid)?;
1316    if obj.kind != ObjectKind::Blob {
1317        return Err(Error::Notes(NotesError::UnexpectedObjectKind {
1318            oid: *oid,
1319            expected: ObjectKind::Blob,
1320            found: obj.kind,
1321        }));
1322    }
1323    Ok(obj.data)
1324}
1325
1326/// Join two note blobs with a blank line between them (Git's `concatenate` notes combiner).
1327fn combine_notes_concatenate(
1328    repo: &Repository,
1329    cur: Option<&ObjectId>,
1330    new_oid: Option<&ObjectId>,
1331) -> Result<ObjectId> {
1332    let new_data = match new_oid {
1333        Some(n) => {
1334            let obj = repo.odb().read(n)?;
1335            if obj.kind != ObjectKind::Blob || obj.data.is_empty() {
1336                Vec::new()
1337            } else {
1338                obj.data
1339            }
1340        }
1341        None => Vec::new(),
1342    };
1343    if new_data.is_empty() {
1344        return match (cur, new_oid) {
1345            (Some(c), _) | (None, Some(c)) => Ok(*c),
1346            (None, None) => Ok(repo.odb().write(ObjectKind::Blob, b"")?),
1347        };
1348    }
1349
1350    let cur_data = match cur {
1351        Some(c) => {
1352            let obj = repo.odb().read(c)?;
1353            if obj.kind != ObjectKind::Blob || obj.data.is_empty() {
1354                Vec::new()
1355            } else {
1356                obj.data
1357            }
1358        }
1359        None => Vec::new(),
1360    };
1361
1362    if cur_data.is_empty() {
1363        return repo.odb().write(ObjectKind::Blob, &new_data);
1364    }
1365
1366    let mut cur_len = cur_data.len();
1367    if cur_len > 0 && cur_data[cur_len - 1] == b'\n' {
1368        cur_len -= 1;
1369    }
1370    let mut buf = Vec::with_capacity(cur_len + 2 + new_data.len());
1371    buf.extend_from_slice(&cur_data[..cur_len]);
1372    buf.push(b'\n');
1373    buf.push(b'\n');
1374    buf.extend_from_slice(&new_data);
1375    repo.odb().write(ObjectKind::Blob, &buf)
1376}
1377
1378fn note_blob_lines(data: &[u8]) -> Vec<String> {
1379    if data.is_empty() {
1380        return Vec::new();
1381    }
1382    let s = String::from_utf8_lossy(data);
1383    s.split('\n').map(|l| l.to_owned()).collect()
1384}
1385
1386/// All lines from both blobs, de-duplicated and sorted (Git's `cat_sort_uniq` notes combiner).
1387fn combine_notes_cat_sort_uniq(
1388    repo: &Repository,
1389    cur: Option<&ObjectId>,
1390    new_oid: Option<&ObjectId>,
1391) -> Result<ObjectId> {
1392    let mut lines: Vec<String> = Vec::new();
1393    for oid in [cur, new_oid].into_iter().flatten() {
1394        let obj = repo.odb().read(oid)?;
1395        if obj.kind == ObjectKind::Blob && !obj.data.is_empty() {
1396            lines.extend(note_blob_lines(&obj.data));
1397        }
1398    }
1399    lines.retain(|l| !l.is_empty());
1400    lines.sort();
1401    lines.dedup();
1402    let mut buf = String::new();
1403    for l in &lines {
1404        buf.push_str(l);
1405        buf.push('\n');
1406    }
1407    repo.odb().write(ObjectKind::Blob, buf.as_bytes())
1408}
1409
1410fn blob_to_lines(data: &[u8]) -> Vec<String> {
1411    if data.is_empty() {
1412        return vec![String::new()];
1413    }
1414    let s = String::from_utf8_lossy(data).into_owned();
1415    s.split_inclusive('\n').map(|l| l.to_owned()).collect()
1416}
1417
1418fn merge_note_blobs_conflict_markers(
1419    repo: &Repository,
1420    base: Option<&ObjectId>,
1421    local: &ObjectId,
1422    remote: &ObjectId,
1423    local_ref: &str,
1424    remote_ref: &str,
1425) -> Result<Vec<u8>> {
1426    let base_lines: Vec<String> = match base {
1427        Some(b) => blob_to_lines(&read_blob_bytes(repo, b)?),
1428        None => vec![String::new()],
1429    };
1430    let local_lines = blob_to_lines(&read_blob_bytes(repo, local)?);
1431    let remote_lines = blob_to_lines(&read_blob_bytes(repo, remote)?);
1432
1433    let base_refs: Vec<&str> = base_lines.iter().map(|s| s.as_str()).collect();
1434    let local_refs: Vec<&str> = local_lines.iter().map(|s| s.as_str()).collect();
1435    let remote_refs: Vec<&str> = remote_lines.iter().map(|s| s.as_str()).collect();
1436    let m3 = Merge3::new(&base_refs, &local_refs, &remote_refs);
1437    let markers = StandardMarkers::new(Some(local_ref), Some(remote_ref));
1438    let merged: String = m3
1439        .merge_lines(false, &markers)
1440        .into_iter()
1441        .map(|cow| cow.into_owned())
1442        .collect();
1443    Ok(merged.into_bytes())
1444}
1445
1446/// Note blobs on each side of one conflicting note in a notes merge (`None`: no note).
1447struct NoteConflict {
1448    base: Option<ObjectId>,
1449    local: Option<ObjectId>,
1450    remote: Option<ObjectId>,
1451}
1452
1453fn remove_entry(entries: &mut Vec<NotesTreeEntry>, obj_hex: &str) {
1454    entries.retain(|e| note_object_name(&e.path).as_deref() != Some(obj_hex));
1455}
1456
1457/// Resolve one note changed on both sides; returns `true` when it is left as a conflict file.
1458#[expect(clippy::too_many_arguments)]
1459fn merge_one_note_change(
1460    repo: &Repository,
1461    obj: &ObjectId,
1462    sides: &NoteConflict,
1463    strategy: NotesMergeStrategy,
1464    local_ref: &str,
1465    remote_ref: &str,
1466    worktree: &std::path::Path,
1467    commit_msg: &mut String,
1468    entries: &mut Vec<NotesTreeEntry>,
1469    has_worktree: &mut bool,
1470) -> Result<bool> {
1471    let obj_hex = obj.to_hex();
1472    let combine = match strategy {
1473        NotesMergeStrategy::Ours => return Ok(false),
1474        NotesMergeStrategy::Theirs => {
1475            match sides.remote {
1476                Some(r) => upsert_note_entry(entries, &obj_hex, r),
1477                None => remove_entry(entries, &obj_hex),
1478            }
1479            return Ok(false);
1480        }
1481        NotesMergeStrategy::Union => combine_notes_concatenate,
1482        NotesMergeStrategy::CatSortUniq => combine_notes_cat_sort_uniq,
1483        NotesMergeStrategy::Manual => {
1484            let data = match (&sides.local, &sides.remote) {
1485                (None, None) => {
1486                    remove_entry(entries, &obj_hex);
1487                    return Ok(false);
1488                }
1489                (None, Some(r)) => read_blob_bytes(repo, r)?,
1490                (Some(l), None) => read_blob_bytes(repo, l)?,
1491                (Some(l), Some(r)) => merge_note_blobs_conflict_markers(
1492                    repo,
1493                    sides.base.as_ref(),
1494                    l,
1495                    r,
1496                    local_ref,
1497                    remote_ref,
1498                )?,
1499            };
1500            if !*has_worktree {
1501                if notes_merge_worktree_nonempty(worktree) {
1502                    return Err(Error::Notes(NotesError::MergeInProgress {
1503                        path: worktree.to_path_buf(),
1504                    }));
1505                }
1506                fs::create_dir_all(worktree)?;
1507                *has_worktree = true;
1508            }
1509            if !commit_msg.contains("Conflicts:") {
1510                commit_msg.push_str("\n\nConflicts:\n");
1511            }
1512            commit_msg.push_str(&format!("\t{obj_hex}\n"));
1513            fs::write(worktree.join(&obj_hex), data)?;
1514            remove_entry(entries, &obj_hex);
1515            return Ok(true);
1516        }
1517    };
1518    match (&sides.local, &sides.remote) {
1519        (None, None) => remove_entry(entries, &obj_hex),
1520        (Some(_), None) => {}
1521        (local, Some(r)) => {
1522            let out = combine(repo, local.as_ref(), Some(r))?;
1523            upsert_note_entry(entries, &obj_hex, out);
1524        }
1525    }
1526    Ok(false)
1527}
1528
1529/// Replace or insert the note entry for `hex` in a flat notes entry list.
1530pub fn upsert_note_entry(entries: &mut Vec<NotesTreeEntry>, hex: &str, blob: ObjectId) {
1531    remove_entry(entries, hex);
1532    entries.push(NotesTreeEntry {
1533        mode: 0o100644,
1534        path: hex.as_bytes().to_vec(),
1535        oid: blob,
1536    });
1537}
1538
1539fn remote_unchanged(base: Option<ObjectId>, remote: Option<ObjectId>) -> bool {
1540    match (base, remote) {
1541        (Some(b), Some(r)) => b == r,
1542        (None, None) => true,
1543        _ => false,
1544    }
1545}
1546
1547fn same_change_local_remote(p: &NotesMergePair) -> bool {
1548    match (&p.local, p.remote_blob) {
1549        (LocalNoteState::Present(l), Some(r)) => l == &r,
1550        (LocalNoteState::Deleted, None) => true,
1551        (LocalNoteState::Unset, Some(r)) => Some(r) == p.base_blob,
1552        (LocalNoteState::Unset, None) => p.base_blob.is_none(),
1553        _ => false,
1554    }
1555}
1556
1557fn adopt_remote_note(entries: &mut Vec<NotesTreeEntry>, obj_hex: &str, remote: Option<ObjectId>) {
1558    match remote {
1559        Some(oid) => upsert_note_entry(entries, obj_hex, oid),
1560        None => remove_entry(entries, obj_hex),
1561    }
1562}
1563
1564#[expect(clippy::too_many_arguments)]
1565fn merge_changes_into_entries(
1566    repo: &Repository,
1567    pairs: &[NotesMergePair],
1568    strategy: NotesMergeStrategy,
1569    local_ref: &str,
1570    remote_ref: &str,
1571    worktree: &std::path::Path,
1572    commit_msg: &mut String,
1573    entries: &mut Vec<NotesTreeEntry>,
1574) -> Result<usize> {
1575    let mut conflicts = 0usize;
1576    let mut has_worktree = false;
1577    for p in pairs {
1578        if remote_unchanged(p.base_blob, p.remote_blob) {
1579            continue;
1580        }
1581        if same_change_local_remote(p) {
1582            continue;
1583        }
1584        let Some(local) = p.local_change() else {
1585            adopt_remote_note(entries, &p.obj.to_hex(), p.remote_blob);
1586            continue;
1587        };
1588        let sides = NoteConflict {
1589            base: p.base_blob,
1590            local,
1591            remote: p.remote_blob,
1592        };
1593        if merge_one_note_change(
1594            repo,
1595            &p.obj,
1596            &sides,
1597            strategy,
1598            local_ref,
1599            remote_ref,
1600            worktree,
1601            commit_msg,
1602            entries,
1603            &mut has_worktree,
1604        )? {
1605            conflicts += 1;
1606        }
1607    }
1608    Ok(conflicts)
1609}
1610
1611fn resolve_commit_tree(repo: &Repository, commit_oid: &ObjectId) -> Result<ObjectId> {
1612    let obj = repo.odb().read(commit_oid)?;
1613    if obj.kind != ObjectKind::Commit {
1614        return Err(Error::Notes(NotesError::UnexpectedObjectKind {
1615            oid: *commit_oid,
1616            expected: ObjectKind::Commit,
1617            found: obj.kind,
1618        }));
1619    }
1620    Ok(parse_commit(&obj.data)?.tree)
1621}
1622
1623fn resolve_notes_commit_optional(repo: &Repository, notes_ref: &str) -> Result<Option<ObjectId>> {
1624    let Some(oid) = notes_ref_tip(repo, notes_ref)? else {
1625        return Ok(None);
1626    };
1627    let kind = repo.odb().read(&oid)?.kind;
1628    if kind != ObjectKind::Commit {
1629        return Err(Error::Notes(NotesError::RefNotCommit {
1630            notes_ref: notes_ref.to_owned(),
1631            found: kind,
1632        }));
1633    }
1634    Ok(Some(oid))
1635}
1636
1637/// Whether a notes merge commit moves the notes ref.
1638#[derive(Clone, Copy)]
1639enum NotesRefUpdate {
1640    /// Store the commit in the ODB only (manual merge conflicts keep the live ref at the local tip).
1641    Leave,
1642    /// Move the ref, which must still point at this tip (`None`: must not exist).
1643    From(Option<ObjectId>),
1644}
1645
1646/// Write a notes merge commit with `parents`, then apply `update` to `notes_ref`.
1647fn write_notes_commit_with_parents(
1648    repo: &Repository,
1649    notes_ref: &str,
1650    entries: &[NotesTreeEntry],
1651    message: &str,
1652    parents: &[ObjectId],
1653    update: NotesRefUpdate,
1654) -> Result<ObjectId> {
1655    let (author, committer) = wall_clock_notes_idents(repo)?;
1656    let commit = NotesCommit {
1657        message,
1658        author: &author,
1659        committer: &committer,
1660    };
1661    let oid = write_notes_commit_object(repo, entries, &commit, parents.to_vec())?;
1662    if let NotesRefUpdate::From(old) = update {
1663        repo.odb().flush_for_publish()?;
1664        update_notes_ref(repo, notes_ref, old, oid, &commit)?;
1665    }
1666    Ok(oid)
1667}
1668
1669/// Merge two notes refs and return the resulting notes commit, or a conflict commit oid.
1670///
1671/// # Errors
1672///
1673/// - [`crate::error::NotesError::MergeBothEmpty`] when neither ref has a notes commit.
1674/// - [`crate::error::NotesError::RefNotCommit`] when either ref points at something other than a commit.
1675/// - [`crate::error::NotesError::MergeInProgress`] when [`NotesMergeStrategy::Manual`] finds conflict files
1676///   left by an earlier merge.
1677/// - Ref store, object, and merge-base failures, or a failure while combining blobs.
1678pub(crate) fn notes_merge_inner(
1679    repo: &Repository,
1680    local_ref: &str,
1681    remote_ref: &str,
1682    strategy: NotesMergeStrategy,
1683) -> Result<std::result::Result<ObjectId, ObjectId>> {
1684    let local_commit = resolve_notes_commit_optional(repo, local_ref)?;
1685    let remote_commit = resolve_notes_commit_optional(repo, remote_ref)?;
1686    match (local_commit, remote_commit) {
1687        (None, None) => Err(Error::Notes(NotesError::MergeBothEmpty {
1688            local: local_ref.to_owned(),
1689            remote: remote_ref.to_owned(),
1690        })),
1691        (None, Some(r)) => Ok(Ok(r)),
1692        (Some(l), None) => Ok(Ok(l)),
1693        (Some(local_oid), Some(remote_oid)) => {
1694            if local_oid == remote_oid {
1695                return Ok(Ok(local_oid));
1696            }
1697            let bases = merge_bases_first_vs_rest(repo, local_oid, &[remote_oid])?;
1698            let base_commit = bases.into_iter().next();
1699            if Some(local_oid) == base_commit {
1700                return Ok(Ok(remote_oid));
1701            }
1702            if Some(remote_oid) == base_commit {
1703                return Ok(Ok(local_oid));
1704            }
1705            let base_tree = base_commit
1706                .map(|bc| resolve_commit_tree(repo, &bc))
1707                .transpose()?;
1708            let local_tree = resolve_commit_tree(repo, &local_oid)?;
1709            let remote_tree = resolve_commit_tree(repo, &remote_oid)?;
1710            let mut commit_msg = format!("Merged notes from {remote_ref} into {local_ref}\n\n");
1711            let pairs = build_merge_pairs(base_tree, local_tree, remote_tree, repo)?;
1712            let mut entries = Vec::new();
1713            let mut listable_seen = 0usize;
1714            let mut truncated = false;
1715            collect_notes_tree_entries(
1716                repo,
1717                &local_tree,
1718                b"",
1719                &mut entries,
1720                None,
1721                &mut listable_seen,
1722                &mut truncated,
1723            )?;
1724            debug_assert!(!truncated);
1725            let worktree = notes_merge_worktree_path(repo);
1726            let conflicts = merge_changes_into_entries(
1727                repo,
1728                &pairs,
1729                strategy,
1730                local_ref,
1731                remote_ref,
1732                &worktree,
1733                &mut commit_msg,
1734                &mut entries,
1735            )?;
1736            let merge_parents = vec![local_oid, remote_oid];
1737            if conflicts > 0 {
1738                let partial = write_notes_commit_with_parents(
1739                    repo,
1740                    local_ref,
1741                    &entries,
1742                    &commit_msg,
1743                    &merge_parents,
1744                    NotesRefUpdate::Leave,
1745                )?;
1746                return Ok(Err(partial));
1747            }
1748            let new_oid = write_notes_commit_with_parents(
1749                repo,
1750                local_ref,
1751                &entries,
1752                &commit_msg,
1753                &merge_parents,
1754                NotesRefUpdate::From(Some(local_oid)),
1755            )?;
1756            Ok(Ok(new_oid))
1757        }
1758    }
1759}
1760
1761/// History command that may copy notes onto rewritten commits.
1762#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1763pub enum NotesRewriteCommand {
1764    /// Rebase and other history rewrites (`notes.rewrite.rebase`, default on).
1765    Rebase,
1766    /// Commit amend (`notes.rewrite.amend`, default on).
1767    Amend,
1768}
1769
1770/// How to combine note blobs when several rewritten commits map onto one target.
1771#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1772pub enum NotesRewriteMode {
1773    /// Append the source note after the destination with a blank line between (Git default).
1774    Concatenate,
1775    /// Concatenate, sort lines, and deduplicate.
1776    CatSortUniq,
1777    /// Replace the destination note with the source.
1778    Overwrite,
1779    /// Keep an existing destination note; copy only when the destination had none.
1780    Ignore,
1781}
1782
1783impl NotesRewriteMode {
1784    fn parse(value: &str) -> Result<Self> {
1785        match value {
1786            "concatenate" => Ok(Self::Concatenate),
1787            "cat_sort_uniq" => Ok(Self::CatSortUniq),
1788            "overwrite" => Ok(Self::Overwrite),
1789            "ignore" => Ok(Self::Ignore),
1790            other => Err(Error::Notes(NotesError::UnknownRewriteMode {
1791                mode: other.to_owned(),
1792            })),
1793        }
1794    }
1795}
1796
1797fn notes_rewrite_command_enabled(config: &ConfigSet, command: NotesRewriteCommand) -> bool {
1798    let key = match command {
1799        NotesRewriteCommand::Rebase => "notes.rewrite.rebase",
1800        NotesRewriteCommand::Amend => "notes.rewrite.amend",
1801    };
1802    config.bool_with_default(key, true)
1803}
1804
1805fn resolve_notes_rewrite_mode<E: IdentityEnv>(
1806    config: &ConfigSet,
1807    env: &E,
1808) -> Result<NotesRewriteMode> {
1809    if let Some(value) = env.var("GIT_NOTES_REWRITE_MODE") {
1810        return NotesRewriteMode::parse(value.trim());
1811    }
1812    if let Some(value) = config.value("notes.rewriteMode") {
1813        return NotesRewriteMode::parse(value.trim());
1814    }
1815    Ok(NotesRewriteMode::Concatenate)
1816}
1817
1818fn notes_rewrite_pattern_is_glob(pattern: &str) -> bool {
1819    pattern
1820        .bytes()
1821        .any(|byte| matches!(byte, b'*' | b'?' | b'[' | b'\\'))
1822}
1823
1824fn resolve_notes_rewrite_refs<E: IdentityEnv>(
1825    repo: &Repository,
1826    config: &ConfigSet,
1827    env: &E,
1828) -> Result<Vec<String>> {
1829    let patterns: Vec<String> = if let Some(value) = env.var("GIT_NOTES_REWRITE_REF") {
1830        value
1831            .split(':')
1832            .map(str::trim)
1833            .filter(|part| !part.is_empty())
1834            .map(str::to_owned)
1835            .collect()
1836    } else {
1837        config.values_all("notes.rewriteRef")
1838    };
1839    if patterns.is_empty() {
1840        return Ok(Vec::new());
1841    }
1842    let all_refs = list_refs_for_repository(repo, "refs/")?;
1843    let mut resolved = BTreeSet::new();
1844    for pattern in patterns {
1845        if !pattern.starts_with("refs/notes/") {
1846            continue;
1847        }
1848        if notes_rewrite_pattern_is_glob(&pattern) {
1849            for (name, _) in &all_refs {
1850                if wildmatch(pattern.as_bytes(), name.as_bytes(), 0) {
1851                    resolved.insert(name.clone());
1852                }
1853            }
1854        } else {
1855            resolved.insert(pattern);
1856        }
1857    }
1858    Ok(resolved.into_iter().collect())
1859}
1860
1861fn note_blob_for_object(entries: &[NotesTreeEntry], object: &ObjectId) -> Option<ObjectId> {
1862    let hex = object.to_hex();
1863    entries
1864        .iter()
1865        .find(|entry| note_object_name(&entry.path).as_deref() == Some(hex.as_str()))
1866        .map(|entry| entry.oid)
1867}
1868
1869fn combine_note_for_rewrite(
1870    repo: &Repository,
1871    mode: NotesRewriteMode,
1872    current: Option<ObjectId>,
1873    source: ObjectId,
1874) -> Result<ObjectId> {
1875    match mode {
1876        NotesRewriteMode::Overwrite => Ok(source),
1877        NotesRewriteMode::Ignore => current.map_or(Ok(source), Ok),
1878        NotesRewriteMode::Concatenate => {
1879            combine_notes_concatenate(repo, current.as_ref(), Some(&source))
1880        }
1881        NotesRewriteMode::CatSortUniq => {
1882            combine_notes_cat_sort_uniq(repo, current.as_ref(), Some(&source))
1883        }
1884    }
1885}
1886
1887fn notes_rewrite_commit_message(command: NotesRewriteCommand) -> &'static str {
1888    match command {
1889        NotesRewriteCommand::Rebase => "Notes added by 'git notes copy'",
1890        NotesRewriteCommand::Amend => "Notes added by 'git commit --amend'",
1891    }
1892}
1893
1894fn copy_notes_for_rewrite_on_ref(
1895    repo: &Repository,
1896    notes_ref: &str,
1897    pairs: &[(ObjectId, ObjectId)],
1898    mode: NotesRewriteMode,
1899    message: &str,
1900) -> Result<()> {
1901    let snapshot = read_notes_snapshot(repo, notes_ref)?;
1902    let mut entries = snapshot.entries;
1903    let mut changed = false;
1904    for &(old, new) in pairs {
1905        if old == new {
1906            continue;
1907        }
1908        let Some(source) = note_blob_for_object(&entries, &old) else {
1909            continue;
1910        };
1911        let current = note_blob_for_object(&entries, &new);
1912        let combined = combine_note_for_rewrite(repo, mode, current, source)?;
1913        if current != Some(combined) {
1914            upsert_note_entry(&mut entries, &new.to_hex(), combined);
1915            changed = true;
1916        }
1917    }
1918    if !changed {
1919        return Ok(());
1920    }
1921    let (author, committer) = wall_clock_notes_idents(repo)?;
1922    write_notes_commit_idents(
1923        repo,
1924        notes_ref,
1925        snapshot.tip,
1926        &entries,
1927        message,
1928        &author,
1929        &committer,
1930    )
1931}
1932
1933/// Resolved settings for a notes copy during a rewrite (refs, mode, commit message).
1934#[derive(Clone, Debug, PartialEq, Eq)]
1935pub struct NotesRewritePlan {
1936    /// Notes refs that will receive copied notes.
1937    pub refs: Vec<String>,
1938    /// How to combine blobs when several sources map to one target.
1939    pub mode: NotesRewriteMode,
1940    message: &'static str,
1941}
1942
1943impl NotesRewritePlan {
1944    fn message(&self) -> &str {
1945        self.message
1946    }
1947}
1948
1949/// Validate notes-rewrite configuration for `command` when copies would run for `pairs`.
1950///
1951/// Returns [`None`] when `pairs` is empty, no refs are selected, or the command is disabled.
1952/// Otherwise resolves refs and mode without reading or writing note trees.
1953///
1954/// # Errors
1955///
1956/// Returns [`crate::error::NotesError::UnknownRewriteMode`] when the configured rewrite mode is unknown.
1957pub(crate) fn prepare_notes_for_rewrite(
1958    repo: &Repository,
1959    command: NotesRewriteCommand,
1960    pairs: &[(ObjectId, ObjectId)],
1961) -> Result<Option<NotesRewritePlan>> {
1962    if pairs.is_empty() {
1963        return Ok(None);
1964    }
1965    let config = repo.config().snapshot()?;
1966    let notes_refs = resolve_notes_rewrite_refs(repo, config.as_ref(), repo.environment())?;
1967    if notes_refs.is_empty() {
1968        return Ok(None);
1969    }
1970    if !notes_rewrite_command_enabled(config.as_ref(), command) {
1971        return Ok(None);
1972    }
1973    let mode = resolve_notes_rewrite_mode(config.as_ref(), repo.environment())?;
1974    Ok(Some(NotesRewritePlan {
1975        refs: notes_refs,
1976        mode,
1977        message: notes_rewrite_commit_message(command),
1978    }))
1979}
1980
1981/// Apply a prepared plan from [`prepare_notes_for_rewrite`].
1982///
1983/// # Errors
1984///
1985/// Propagates notes read/write and ref compare-and-swap failures.
1986pub(crate) fn apply_prepared_notes_rewrite(
1987    repo: &Repository,
1988    plan: &NotesRewritePlan,
1989    pairs: &[(ObjectId, ObjectId)],
1990) -> Result<()> {
1991    for notes_ref in &plan.refs {
1992        copy_notes_for_rewrite_on_ref(repo, notes_ref, pairs, plan.mode, plan.message())?;
1993    }
1994    Ok(())
1995}
1996
1997/// Copy notes from rewritten commits to their replacements (Git `git notes copy --for-rewrite`).
1998///
1999/// Honors `notes.rewriteRef` / `GIT_NOTES_REWRITE_REF`, `notes.rewriteMode` /
2000/// `GIT_NOTES_REWRITE_MODE`, and `notes.rewrite.rebase` / `notes.rewrite.amend`. Notes on the
2001/// original object ids are left in place; only the listed `(old, new)` pairs are considered.
2002///
2003/// # Errors
2004///
2005/// Returns [`crate::error::NotesError::UnknownRewriteMode`] when the configured rewrite mode is unknown, and other
2006/// notes or ref store errors while reading or writing notes refs.
2007pub(crate) fn copy_notes_for_rewrite(
2008    repo: &Repository,
2009    command: NotesRewriteCommand,
2010    pairs: &[(ObjectId, ObjectId)],
2011) -> Result<()> {
2012    if let Some(plan) = prepare_notes_for_rewrite(repo, command, pairs)? {
2013        apply_prepared_notes_rewrite(repo, &plan, pairs)?;
2014    }
2015    Ok(())
2016}
2017
2018#[cfg(test)]
2019mod tests {
2020    use super::*;
2021    use crate::environment::RepositoryOptions;
2022    use crate::error::RefError;
2023    use crate::objects::ObjectKind;
2024    use crate::refs::store::RefNameRef;
2025    use crate::repo::Repository;
2026    use std::io::Write;
2027    use std::process::Command;
2028    use tempfile::TempDir;
2029
2030    fn git(dir: &std::path::Path, args: &[&str]) {
2031        let out = Command::new("git")
2032            .current_dir(dir)
2033            .args(args)
2034            .env("GIT_CONFIG_GLOBAL", "/dev/null")
2035            .env("GIT_CONFIG_SYSTEM", "/dev/null")
2036            .env("GIT_AUTHOR_NAME", "Test")
2037            .env("GIT_AUTHOR_EMAIL", "t@example.com")
2038            .env("GIT_COMMITTER_NAME", "Test")
2039            .env("GIT_COMMITTER_EMAIL", "t@example.com")
2040            .output()
2041            .expect("git");
2042        assert!(
2043            out.status.success(),
2044            "git {:?}: {}",
2045            args,
2046            String::from_utf8_lossy(&out.stderr)
2047        );
2048    }
2049
2050    fn open_repo(dir: &std::path::Path) -> Repository {
2051        git(dir, &["init", "-q", "-b", "main", "."]);
2052        std::fs::write(dir.join("f"), b"x\n").unwrap();
2053        git(dir, &["add", "f"]);
2054        git(dir, &["commit", "-qm", "init"]);
2055        Repository::open(
2056            &dir.join(".git"),
2057            &RepositoryOptions::empty().with_work_tree(dir),
2058        )
2059        .expect("open")
2060    }
2061
2062    #[test]
2063    fn note_object_name_parses_flat_and_fanout_paths() {
2064        let full = "0123456789abcdef0123456789abcdef01234567";
2065        assert_eq!(note_object_name(full.as_bytes()), Some(full.to_owned()));
2066        assert_eq!(
2067            note_object_name(b"01/23/456789abcdef0123456789abcdef01234567"),
2068            Some(full.to_owned())
2069        );
2070        assert!(note_object_name(b"not-a-note").is_none());
2071    }
2072
2073    #[test]
2074    fn from_full_rejects_whitespace_padded_ref() {
2075        let err = NotesRef::from_full(" refs/notes/spaced ").expect_err("padded");
2076        assert!(matches!(err, Error::Notes(NotesError::InvalidRef { .. })));
2077        let err = NotesRef::from_full("refs/notes/spaced ").expect_err("trailing");
2078        assert!(matches!(err, Error::Notes(NotesError::InvalidRef { .. })));
2079        let ok = NotesRef::from_full("refs/notes/spaced").expect("valid");
2080        assert_eq!(ok.as_str(), "refs/notes/spaced");
2081    }
2082
2083    #[test]
2084    fn resolve_configured_notes_ref_rejects_empty_git_notes_ref() {
2085        use crate::config::ConfigSet;
2086        use std::collections::HashMap;
2087        use std::ffi::OsString;
2088
2089        struct MapEnv(HashMap<String, String>);
2090        impl crate::ident_resolve::IdentityEnv for MapEnv {
2091            fn var(&self, key: &str) -> Option<String> {
2092                self.0.get(key).cloned()
2093            }
2094            fn var_os(&self, key: &str) -> Option<OsString> {
2095                self.var(key).map(OsString::from)
2096            }
2097        }
2098
2099        let env = MapEnv(HashMap::from([("GIT_NOTES_REF".to_owned(), String::new())]));
2100        let err = resolve_configured_notes_ref(&env, &ConfigSet::default())
2101            .expect_err("empty GIT_NOTES_REF");
2102        assert!(matches!(err, Error::Notes(NotesError::InvalidRef { .. })));
2103    }
2104
2105    #[test]
2106    fn expand_notes_ref_and_parse() {
2107        assert_eq!(expand_notes_ref("commits"), "refs/notes/commits");
2108        assert_eq!(expand_notes_ref("notes/foo"), "refs/notes/foo");
2109        assert_eq!(expand_notes_ref("refs/notes/bar"), "refs/notes/bar");
2110        assert_eq!(NotesRef::parse("review").as_str(), "refs/notes/review");
2111    }
2112
2113    #[test]
2114    fn notes_merge_worktree_nonempty_detects_files() {
2115        let tmp = TempDir::new().unwrap();
2116        let wt = tmp.path().join("wt");
2117        assert!(!notes_merge_worktree_nonempty(&wt));
2118        std::fs::create_dir_all(&wt).unwrap();
2119        assert!(!notes_merge_worktree_nonempty(&wt));
2120        std::fs::write(wt.join("x"), b"").unwrap();
2121        assert!(notes_merge_worktree_nonempty(&wt));
2122    }
2123
2124    #[cfg_attr(
2125        not(feature = "full-tests"),
2126        ignore = "starts system git or is heavy; run with --features full-tests"
2127    )]
2128    #[test]
2129    fn combine_notes_helpers_and_upsert() {
2130        let tmp = TempDir::new().unwrap();
2131        let repo = open_repo(tmp.path());
2132        let a = repo.odb().write(ObjectKind::Blob, b"line1\n").unwrap();
2133        let b = repo.odb().write(ObjectKind::Blob, b"line2\n").unwrap();
2134        let cat = combine_notes_concatenate(&repo, Some(&a), Some(&b)).unwrap();
2135        let merged = repo.odb().read(&cat).unwrap();
2136        assert!(String::from_utf8_lossy(&merged.data).contains("line1"));
2137        let _uniq = combine_notes_cat_sort_uniq(&repo, Some(&a), Some(&b)).unwrap();
2138
2139        let hex = "0123456789abcdef0123456789abcdef01234567";
2140        let mut entries = Vec::new();
2141        upsert_note_entry(&mut entries, hex, a);
2142        upsert_note_entry(&mut entries, hex, b);
2143        assert_eq!(entries.len(), 1);
2144        assert_eq!(entries[0].oid, b);
2145    }
2146
2147    #[cfg_attr(
2148        not(feature = "full-tests"),
2149        ignore = "starts system git or is heavy; run with --features full-tests"
2150    )]
2151    #[test]
2152    fn read_and_write_notes_roundtrip() {
2153        let tmp = TempDir::new().unwrap();
2154        let repo = open_repo(tmp.path());
2155        let head = Command::new("git")
2156            .current_dir(tmp.path())
2157            .args(["rev-parse", "HEAD"])
2158            .output()
2159            .unwrap();
2160        let commit = ObjectId::from_hex(std::str::from_utf8(&head.stdout).unwrap().trim()).unwrap();
2161        let blob = repo.odb().write(ObjectKind::Blob, b"hello\n").unwrap();
2162        upsert_note_entry(&mut vec![], &commit.to_hex(), blob);
2163        let entries = vec![NotesTreeEntry {
2164            mode: 0o100644,
2165            path: commit.to_hex().into_bytes(),
2166            oid: blob,
2167        }];
2168        write_notes_commit(&repo, "refs/notes/commits", &entries, "note").unwrap();
2169        let read_back = read_notes_tree(&repo, "refs/notes/commits").unwrap();
2170        assert_eq!(read_back.len(), 1);
2171        assert_eq!(read_back[0].oid, blob);
2172    }
2173
2174    #[cfg_attr(
2175        not(feature = "full-tests"),
2176        ignore = "starts system git or is heavy; run with --features full-tests"
2177    )]
2178    #[test]
2179    fn notes_merge_ours_keeps_local_note() {
2180        let tmp = TempDir::new().unwrap();
2181        let repo = open_repo(tmp.path());
2182        let commit = ObjectId::from_hex(
2183            std::str::from_utf8(
2184                &Command::new("git")
2185                    .current_dir(tmp.path())
2186                    .args(["rev-parse", "HEAD"])
2187                    .output()
2188                    .unwrap()
2189                    .stdout,
2190            )
2191            .unwrap()
2192            .trim(),
2193        )
2194        .unwrap();
2195        git(
2196            tmp.path(),
2197            &["notes", "add", "-m", "base", &commit.to_hex()],
2198        );
2199        let base = crate::refs::resolve_ref(repo.git_dir(), "refs/notes/commits").unwrap();
2200        git(
2201            tmp.path(),
2202            &["notes", "add", "-f", "-m", "local", &commit.to_hex()],
2203        );
2204        let local = crate::refs::resolve_ref(repo.git_dir(), "refs/notes/commits").unwrap();
2205        git(
2206            tmp.path(),
2207            &["update-ref", "refs/notes/remote", &base.to_hex()],
2208        );
2209        git(
2210            tmp.path(),
2211            &[
2212                "notes",
2213                "--ref=refs/notes/remote",
2214                "add",
2215                "-f",
2216                "-m",
2217                "remote",
2218                &commit.to_hex(),
2219            ],
2220        );
2221        git(
2222            tmp.path(),
2223            &["update-ref", "refs/notes/commits", &local.to_hex()],
2224        );
2225        notes_merge_inner(
2226            &repo,
2227            "refs/notes/commits",
2228            "refs/notes/remote",
2229            NotesMergeStrategy::Ours,
2230        )
2231        .expect("merge")
2232        .expect("ok");
2233        let show = Command::new("git")
2234            .current_dir(tmp.path())
2235            .args(["notes", "show", &commit.to_hex()])
2236            .output()
2237            .unwrap();
2238        assert_eq!(String::from_utf8_lossy(&show.stdout).trim(), "local");
2239    }
2240
2241    #[cfg_attr(
2242        not(feature = "full-tests"),
2243        ignore = "starts system git or is heavy; run with --features full-tests"
2244    )]
2245    #[test]
2246    fn notes_merge_manual_leaves_conflict_commit() {
2247        let tmp = TempDir::new().unwrap();
2248        let repo = open_repo(tmp.path());
2249        let commit = ObjectId::from_hex(
2250            std::str::from_utf8(
2251                &Command::new("git")
2252                    .current_dir(tmp.path())
2253                    .args(["rev-parse", "HEAD"])
2254                    .output()
2255                    .unwrap()
2256                    .stdout,
2257            )
2258            .unwrap()
2259            .trim(),
2260        )
2261        .unwrap();
2262        git(
2263            tmp.path(),
2264            &["notes", "add", "-m", "base", &commit.to_hex()],
2265        );
2266        let base = crate::refs::resolve_ref(repo.git_dir(), "refs/notes/commits").unwrap();
2267        git(
2268            tmp.path(),
2269            &["notes", "add", "-f", "-m", "local", &commit.to_hex()],
2270        );
2271        let local = crate::refs::resolve_ref(repo.git_dir(), "refs/notes/commits").unwrap();
2272        git(
2273            tmp.path(),
2274            &["update-ref", "refs/notes/remote", &base.to_hex()],
2275        );
2276        git(
2277            tmp.path(),
2278            &[
2279                "notes",
2280                "--ref=refs/notes/remote",
2281                "add",
2282                "-f",
2283                "-m",
2284                "remote",
2285                &commit.to_hex(),
2286            ],
2287        );
2288        git(
2289            tmp.path(),
2290            &["update-ref", "refs/notes/commits", &local.to_hex()],
2291        );
2292        let result = notes_merge_inner(
2293            &repo,
2294            "refs/notes/commits",
2295            "refs/notes/remote",
2296            NotesMergeStrategy::Manual,
2297        )
2298        .expect("merge");
2299        let partial = match result {
2300            Err(partial) => partial,
2301            Ok(_) => panic!("manual merge must stop with conflicts"),
2302        };
2303        assert_ne!(
2304            partial, local,
2305            "partial merge commit must differ from the pre-merge tip"
2306        );
2307        assert_eq!(
2308            crate::refs::resolve_ref(repo.git_dir(), "refs/notes/commits").unwrap(),
2309            local,
2310            "manual merge conflicts must leave the live notes ref at the local tip"
2311        );
2312        assert!(notes_merge_worktree_nonempty(&notes_merge_worktree_path(
2313            &repo
2314        )));
2315
2316        let err = notes_merge_inner(
2317            &repo,
2318            "refs/notes/commits",
2319            "refs/notes/remote",
2320            NotesMergeStrategy::Manual,
2321        )
2322        .expect_err("earlier conflicts are still unresolved");
2323        assert!(matches!(
2324            err,
2325            Error::Notes(NotesError::MergeInProgress { ref path }) if *path == notes_merge_worktree_path(&repo)
2326        ));
2327    }
2328
2329    #[cfg_attr(
2330        not(feature = "full-tests"),
2331        ignore = "starts system git or is heavy; run with --features full-tests"
2332    )]
2333    #[test]
2334    fn read_notes_tree_missing_ref_is_empty() {
2335        let tmp = TempDir::new().unwrap();
2336        let repo = open_repo(tmp.path());
2337        assert!(read_notes_tree(&repo, "refs/notes/commits")
2338            .unwrap()
2339            .is_empty());
2340    }
2341
2342    #[cfg_attr(
2343        not(feature = "full-tests"),
2344        ignore = "starts system git or is heavy; run with --features full-tests"
2345    )]
2346    #[test]
2347    fn notes_merge_empty_remote_adopts_remote() {
2348        let tmp = TempDir::new().unwrap();
2349        let repo = open_repo(tmp.path());
2350        let local = write_notes_commit_with_parents(
2351            &repo,
2352            "refs/notes/commits",
2353            &[],
2354            "local only",
2355            &[],
2356            NotesRefUpdate::From(None),
2357        )
2358        .unwrap();
2359        let result = notes_merge_inner(
2360            &repo,
2361            "refs/notes/commits",
2362            "refs/notes/missing",
2363            NotesMergeStrategy::Theirs,
2364        )
2365        .expect("merge");
2366        assert_eq!(result.expect("ok"), local);
2367    }
2368
2369    #[cfg_attr(
2370        not(feature = "full-tests"),
2371        ignore = "starts system git or is heavy; run with --features full-tests"
2372    )]
2373    #[test]
2374    fn notes_merge_of_two_empty_refs_is_typed() {
2375        let tmp = TempDir::new().unwrap();
2376        let repo = open_repo(tmp.path());
2377        let err = notes_merge_inner(
2378            &repo,
2379            "refs/notes/commits",
2380            "refs/notes/missing",
2381            NotesMergeStrategy::Union,
2382        )
2383        .expect_err("nothing to merge");
2384        assert!(matches!(
2385            err,
2386            Error::Notes(NotesError::MergeBothEmpty { ref local, ref remote })
2387                if local == "refs/notes/commits" && remote == "refs/notes/missing"
2388        ));
2389    }
2390
2391    #[cfg_attr(
2392        not(feature = "full-tests"),
2393        ignore = "starts system git or is heavy; run with --features full-tests"
2394    )]
2395    #[test]
2396    fn read_notes_tree_rejects_blob_tip() {
2397        let tmp = TempDir::new().unwrap();
2398        let repo = open_repo(tmp.path());
2399        let blob = repo.odb().write(ObjectKind::Blob, b"not notes\n").unwrap();
2400        git(
2401            tmp.path(),
2402            &["update-ref", "refs/notes/blob", &blob.to_hex()],
2403        );
2404        let err = read_notes_tree(&repo, "refs/notes/blob").expect_err("blob tip");
2405        assert!(matches!(
2406            err,
2407            Error::Notes(NotesError::RefNotCommit { ref notes_ref, found: ObjectKind::Blob })
2408                if notes_ref == "refs/notes/blob"
2409        ));
2410        let err = notes_merge_inner(
2411            &repo,
2412            "refs/notes/commits",
2413            "refs/notes/blob",
2414            NotesMergeStrategy::Ours,
2415        )
2416        .expect_err("blob remote");
2417        assert!(matches!(
2418            err,
2419            Error::Notes(NotesError::RefNotCommit {
2420                found: ObjectKind::Blob,
2421                ..
2422            })
2423        ));
2424    }
2425
2426    #[cfg_attr(
2427        not(feature = "full-tests"),
2428        ignore = "starts system git or is heavy; run with --features full-tests"
2429    )]
2430    #[test]
2431    fn write_notes_commit_goes_through_injected_ref_store() {
2432        let tmp = TempDir::new().unwrap();
2433        let repo = open_repo(tmp.path()).with_ref_store(std::sync::Arc::new(
2434            crate::refs::store::MemoryRefStore::new(),
2435        ));
2436        let blob = repo.odb().write(ObjectKind::Blob, b"in memory\n").unwrap();
2437        let mut entries = Vec::new();
2438        upsert_note_entry(&mut entries, &"ab".repeat(20), blob);
2439        write_notes_commit(&repo, "refs/notes/commits", &entries, "first").unwrap();
2440        let first = repo
2441            .ref_store()
2442            .resolve(RefNameRef::from_trusted("refs/notes/commits"))
2443            .unwrap();
2444        write_notes_commit(&repo, "refs/notes/commits", &[], "second").unwrap();
2445        let second = repo
2446            .ref_store()
2447            .resolve(RefNameRef::from_trusted("refs/notes/commits"))
2448            .unwrap();
2449
2450        let commit = parse_commit(&repo.odb().read(&second).unwrap().data).unwrap();
2451        assert_eq!(commit.parents, vec![first]);
2452        assert!(read_notes_tree(&repo, "refs/notes/commits")
2453            .unwrap()
2454            .is_empty());
2455        assert!(
2456            !tmp.path().join(".git/refs/notes/commits").exists(),
2457            "notes ref must live in the injected store, not on disk"
2458        );
2459    }
2460
2461    #[cfg_attr(
2462        not(feature = "full-tests"),
2463        ignore = "starts system git or is heavy; run with --features full-tests"
2464    )]
2465    #[test]
2466    fn notes_rewrite_write_fails_cas_when_ref_moves_after_snapshot() {
2467        let tmp = TempDir::new().unwrap();
2468        let repo = open_repo(tmp.path());
2469        let head = Command::new("git")
2470            .current_dir(tmp.path())
2471            .args(["rev-parse", "HEAD"])
2472            .output()
2473            .unwrap();
2474        let commit = ObjectId::from_hex(std::str::from_utf8(&head.stdout).unwrap().trim()).unwrap();
2475        let blob = repo.odb().write(ObjectKind::Blob, b"note\n").unwrap();
2476        upsert_note_entry(&mut vec![], &commit.to_hex(), blob);
2477        write_notes_commit(&repo, "refs/notes/commits", &[], "seed").unwrap();
2478        let snapshot = read_notes_snapshot(&repo, "refs/notes/commits").unwrap();
2479        let other = repo.odb().write(ObjectKind::Blob, b"other\n").unwrap();
2480        let mut entries = read_notes_tree(&repo, "refs/notes/commits").unwrap();
2481        upsert_note_entry(&mut entries, &"ab".repeat(20), other);
2482        write_notes_commit(&repo, "refs/notes/commits", &entries, "concurrent").unwrap();
2483        let (author, committer) = wall_clock_notes_idents(&repo).unwrap();
2484        let err = write_notes_commit_idents(
2485            &repo,
2486            "refs/notes/commits",
2487            snapshot.tip,
2488            &entries,
2489            "stale",
2490            &author,
2491            &committer,
2492        )
2493        .expect_err("stale parent must not overwrite a newer notes tip");
2494        assert!(
2495            matches!(err, Error::Ref(RefError::Store(_))),
2496            "expected ref compare-and-swap failure, got {err:?}"
2497        );
2498    }
2499
2500    #[test]
2501    fn notes_rewrite_mode_parses_git_values() {
2502        assert_eq!(
2503            NotesRewriteMode::parse("concatenate").expect("concatenate"),
2504            NotesRewriteMode::Concatenate
2505        );
2506        assert!(matches!(
2507            NotesRewriteMode::parse("nope").expect_err("bad"),
2508            Error::Notes(NotesError::UnknownRewriteMode { .. })
2509        ));
2510    }
2511
2512    #[cfg_attr(
2513        not(feature = "full-tests"),
2514        ignore = "starts system git or is heavy; run with --features full-tests"
2515    )]
2516    #[test]
2517    fn uppercase_hex_note_leaf_matches_git() {
2518        let tmp = TempDir::new().unwrap();
2519        let repo = open_repo(tmp.path());
2520        let commit = ObjectId::from_hex(
2521            std::str::from_utf8(
2522                &Command::new("git")
2523                    .current_dir(tmp.path())
2524                    .args(["rev-parse", "HEAD"])
2525                    .env("GIT_CONFIG_GLOBAL", "/dev/null")
2526                    .env("GIT_CONFIG_SYSTEM", "/dev/null")
2527                    .output()
2528                    .unwrap()
2529                    .stdout,
2530            )
2531            .unwrap()
2532            .trim(),
2533        )
2534        .unwrap();
2535        let note_blob = {
2536            let mut child = Command::new("git")
2537                .current_dir(tmp.path())
2538                .args(["hash-object", "-w", "--stdin"])
2539                .stdin(std::process::Stdio::piped())
2540                .stdout(std::process::Stdio::piped())
2541                .spawn()
2542                .unwrap();
2543            child
2544                .stdin
2545                .take()
2546                .unwrap()
2547                .write_all(b"upper note\n")
2548                .unwrap();
2549            String::from_utf8_lossy(&child.wait_with_output().unwrap().stdout)
2550                .trim()
2551                .to_owned()
2552        };
2553        let upper = commit.to_hex().to_ascii_uppercase();
2554        let tree_in = format!("100644 blob {note_blob}\t{upper}\n");
2555        let tree_oid = {
2556            let mut child = Command::new("git")
2557                .current_dir(tmp.path())
2558                .args(["mktree"])
2559                .stdin(std::process::Stdio::piped())
2560                .stdout(std::process::Stdio::piped())
2561                .spawn()
2562                .unwrap();
2563            child
2564                .stdin
2565                .take()
2566                .unwrap()
2567                .write_all(tree_in.as_bytes())
2568                .unwrap();
2569            String::from_utf8_lossy(&child.wait_with_output().unwrap().stdout)
2570                .trim()
2571                .to_owned()
2572        };
2573        let notes_commit = String::from_utf8_lossy(
2574            &Command::new("git")
2575                .current_dir(tmp.path())
2576                .args(["commit-tree", &tree_oid, "-m", "uppercase leaf"])
2577                .output()
2578                .unwrap()
2579                .stdout,
2580        )
2581        .trim()
2582        .to_owned();
2583        git(
2584            tmp.path(),
2585            &["update-ref", "refs/notes/commits", &notes_commit],
2586        );
2587        assert_eq!(
2588            repo.notes()
2589                .read(&NotesRef::commits(), &commit)
2590                .unwrap()
2591                .as_deref(),
2592            Some(b"upper note\n" as &[u8])
2593        );
2594        assert!(matches!(
2595            repo.notes()
2596                .add(
2597                    &NotesRef::commits(),
2598                    &commit,
2599                    b"x\n",
2600                    &crate::repo_handles::NotesWriteOptions {
2601                        message: "dup".into(),
2602                        committer: "Test <t@example.com> 1700000000 +0000".parse().unwrap(),
2603                        author: None,
2604                    },
2605                    false,
2606                )
2607                .expect_err("exists"),
2608            Error::Notes(NotesError::AlreadyExists { .. })
2609        ));
2610    }
2611
2612    #[cfg_attr(
2613        not(feature = "full-tests"),
2614        ignore = "starts system git or is heavy; run with --features full-tests"
2615    )]
2616    #[test]
2617    fn splice_replace_touches_one_fanout_subtree() {
2618        let tmp = TempDir::new().unwrap();
2619        git(tmp.path(), &["init", "-q", "-b", "main", "."]);
2620        git(tmp.path(), &["config", "user.email", "t@example.com"]);
2621        git(tmp.path(), &["config", "user.name", "Test"]);
2622        std::fs::write(tmp.path().join("seed"), b"s\n").unwrap();
2623        git(tmp.path(), &["add", "seed"]);
2624        git(tmp.path(), &["commit", "-qm", "seed"]);
2625        for i in 0..300 {
2626            std::fs::write(tmp.path().join("f"), format!("v{i}\n")).unwrap();
2627            git(tmp.path(), &["add", "f"]);
2628            git(tmp.path(), &["commit", "-qm", &format!("c{i}")]);
2629            git(
2630                tmp.path(),
2631                &["notes", "add", "-m", &format!("note-{i}"), "HEAD"],
2632            );
2633        }
2634        let head = ObjectId::from_hex(
2635            std::str::from_utf8(
2636                &Command::new("git")
2637                    .current_dir(tmp.path())
2638                    .args(["rev-parse", "HEAD"])
2639                    .output()
2640                    .unwrap()
2641                    .stdout,
2642            )
2643            .unwrap()
2644            .trim(),
2645        )
2646        .unwrap();
2647        let repo = open_repo(tmp.path());
2648        let before = root_tree_child_oids(&repo, "refs/notes/commits");
2649        let opts = crate::repo_handles::NotesWriteOptions {
2650            message: "replace".into(),
2651            committer: "Test <t@example.com> 1700000000 +0000".parse().unwrap(),
2652            author: None,
2653        };
2654        repo.notes()
2655            .add(&NotesRef::commits(), &head, b"replaced\n", &opts, true)
2656            .unwrap();
2657        let after = root_tree_child_oids(&repo, "refs/notes/commits");
2658        assert_eq!(before.len(), after.len());
2659        let changed = before
2660            .iter()
2661            .zip(after.iter())
2662            .filter(|((n0, o0), (n1, o1))| n0 == n1 && o0 != o1)
2663            .count();
2664        assert_eq!(changed, 1);
2665        let show = Command::new("git")
2666            .current_dir(tmp.path())
2667            .args(["notes", "show", &head.to_hex()])
2668            .output()
2669            .unwrap();
2670        assert_eq!(String::from_utf8_lossy(&show.stdout).trim(), "replaced");
2671    }
2672
2673    #[cfg_attr(
2674        not(feature = "full-tests"),
2675        ignore = "benchmark; run with --features full-tests"
2676    )]
2677    #[test]
2678    fn bench_notes_add_matches_git_order_of_magnitude() {
2679        let tmp = TempDir::new().unwrap();
2680        git(tmp.path(), &["init", "-q", "-b", "main", "."]);
2681        git(tmp.path(), &["config", "user.email", "t@example.com"]);
2682        git(tmp.path(), &["config", "user.name", "Test"]);
2683        std::fs::write(tmp.path().join("seed"), b"s\n").unwrap();
2684        git(tmp.path(), &["add", "seed"]);
2685        git(tmp.path(), &["commit", "-qm", "seed"]);
2686        for i in 0..500 {
2687            std::fs::write(tmp.path().join("f"), format!("v{i}\n")).unwrap();
2688            git(tmp.path(), &["add", "f"]);
2689            git(tmp.path(), &["commit", "-qm", &format!("c{i}")]);
2690            git(
2691                tmp.path(),
2692                &["notes", "add", "-m", &format!("note-{i}"), "HEAD"],
2693            );
2694        }
2695        let head = std::str::from_utf8(
2696            &Command::new("git")
2697                .current_dir(tmp.path())
2698                .args(["rev-parse", "HEAD"])
2699                .output()
2700                .unwrap()
2701                .stdout,
2702        )
2703        .unwrap()
2704        .trim()
2705        .to_owned();
2706        let git_start = std::time::Instant::now();
2707        for _ in 0..5 {
2708            git(tmp.path(), &["notes", "add", "-f", "-m", "x", &head]);
2709        }
2710        let git_per = git_start.elapsed() / 5;
2711
2712        let repo = open_repo(tmp.path());
2713        let object = ObjectId::from_hex(&head).unwrap();
2714        let opts = crate::repo_handles::NotesWriteOptions {
2715            message: "x".into(),
2716            committer: "Test <t@example.com> 1700000000 +0000".parse().unwrap(),
2717            author: None,
2718        };
2719        let grit_start = std::time::Instant::now();
2720        for _ in 0..5 {
2721            repo.notes()
2722                .add(&NotesRef::commits(), &object, b"x\n", &opts, true)
2723                .unwrap();
2724        }
2725        let grit_per = grit_start.elapsed() / 5;
2726
2727        eprintln!("git notes add: {git_per:?} per op");
2728        eprintln!("grit notes add: {grit_per:?} per op");
2729        assert!(
2730            grit_per <= git_per * 10,
2731            "grit add should stay within 10x of git, git={git_per:?} grit={grit_per:?}"
2732        );
2733        assert!(
2734            grit_per.as_millis() < 50,
2735            "grit add on ~500-note fanout should stay under 50ms, got {grit_per:?}"
2736        );
2737    }
2738
2739    fn root_tree_child_oids(repo: &Repository, notes_ref: &str) -> Vec<(Vec<u8>, ObjectId)> {
2740        let tip = crate::refs::resolve_ref(repo.git_dir(), notes_ref).unwrap();
2741        let tree_oid = notes_tree_oid(repo, &tip).unwrap();
2742        read_tree_entries(repo, &tree_oid)
2743            .unwrap()
2744            .into_iter()
2745            .map(|e| (e.name, e.oid))
2746            .collect()
2747    }
2748
2749    #[test]
2750    fn local_change_distinguishes_unchanged_deleted_and_set() {
2751        let base = ObjectId::from_hex(&"11".repeat(20)).unwrap();
2752        let other = ObjectId::from_hex(&"22".repeat(20)).unwrap();
2753        let pair = |local| NotesMergePair {
2754            obj: other,
2755            base_blob: Some(base),
2756            remote_blob: None,
2757            local,
2758        };
2759        assert_eq!(pair(LocalNoteState::Unset).local_change(), None);
2760        assert_eq!(pair(LocalNoteState::Present(base)).local_change(), None);
2761        assert_eq!(
2762            pair(LocalNoteState::Present(other)).local_change(),
2763            Some(Some(other))
2764        );
2765        assert_eq!(pair(LocalNoteState::Deleted).local_change(), Some(None));
2766    }
2767}