(* Copyright (c) 2026 Thomas Gazagnaire Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) module Hash = Object_hash let err_msgf fmt = Fmt.kstr (fun s -> Error (`Msg s)) fmt (* {1 Lines} *) let before_nul s = match String.index_opt s '\000' with None -> s | Some i -> String.sub s 0 i let lines note = List.filter (fun l -> l <> "") (String.split_on_char '\n' (before_nul note)) let validate_line line = if line = "" then invalid_arg "Notes.add_line: empty line"; if String.exists (fun c -> c = '\n' || c = '\000') line then Fmt.invalid_arg "Notes.add_line: %S is not one line" line let line_separator note = let n = String.length note in if n = 0 || note.[n - 1] = '\n' then "" else "\n" let add_line note line = validate_line line; String.concat "" [ note; line_separator note; line; "\n" ] (* String.compare is a bytewise comparison, as git's strcmp. *) let cat_sort_uniq local remote = List.sort_uniq String.compare (lines local @ lines remote) |> List.map (fun l -> l ^ "\n") |> String.concat "" (* {1 Stores} *) type reader_cache = (Hash.t * (Hash.t -> Hash.t option)) option ref let reader_cache () = ref None module type S = sig type t val read : t -> Hash.t -> (Value.t, [ `Msg of string ]) result val write : t -> Value.t -> Hash.t val commit_graph : t -> Commit_graph.t option val read_ref : t -> string -> (Hash.t option, [ `Msg of string ]) result val compare_and_swap_ref : t -> string -> expected:Hash.t option -> reflog:User.t * string -> Hash.t -> (unit, [ `Raced | `Locked of string | `Msg of string ]) result end type merge_result = Up_to_date | Fast_forward of Hash.t | Merged of Hash.t let pp_merge_result ppf = function | Up_to_date -> Fmt.string ppf "up to date" | Fast_forward h -> Fmt.pf ppf "fast-forward to %a" Hash.pp h | Merged h -> Fmt.pf ppf "merged as %a" Hash.pp h (* {1 The notes tree} The tree in memory is git's (notes.c): a trie of sixteen-way nodes indexed by the hex digits of the annotated object's id. A slot holds nothing, a note, an internal node, or a fan-out directory not read yet. A note sits at the first level where no other entry shares its digits; a directory is read only when a lookup or an insertion goes through it, so a change reads and writes again only the trees on its path. Writing decides the fan-out per directory from the shape of the trie, as git does, so a tree written here is the one git writes from the same tree for the same change. *) exception Broken of string let fail_broken fmt = Fmt.kstr (fun s -> raise (Broken s)) fmt let raw_size = Hash.digest_size (* A subtree's key is its prefix, zero bytes, and the prefix length in the last byte. *) let key_index = raw_size - 1 type leaf = { key : string; mutable value : Hash.t } type slot = Empty | Note of leaf | Subtree of leaf | Internal of slot array module Paths = Map.Make (String) type t = { root : slot array; mutable others : (Tree.perm * Hash.t) Paths.t; (* The entries that are not notes, by their path from the root. *) mutable read : Hash.Set.t; (* The directories read. *) load : Hash.t -> Tree.t; } let nibble n key = let b = Char.code key.[n lsr 1] in if n land 1 = 0 then b lsr 4 else b land 0x0f let prefix_length sub = Char.code sub.[key_index] let under ~key sub = let n = prefix_length sub in let rec go i = i >= n || (key.[i] = sub.[i] && go (i + 1)) in go 0 let hex_value = function | '0' .. '9' as c -> Char.code c - 48 | 'a' .. 'f' as c -> Char.code c - 87 | 'A' .. 'F' as c -> Char.code c - 55 | _ -> -1 (* [decode buf off name] writes the bytes the hex [name] spells at [off] of [buf], or is [false] if [name] is not hex; upper case is hex, as git's hex_to_bytes reads it. *) let decode buf off name = let rec go i = i >= String.length name / 2 || let h = hex_value name.[2 * i] and l = hex_value name.[(2 * i) + 1] in h >= 0 && l >= 0 && (Bytes.set buf (off + i) (Char.chr ((h lsl 4) lor l)); go (i + 1)) in go 0 let hex_of key = Hash.to_hex (Hash.of_raw_string key) let is_regular = function | `Normal | `Everybody | `Exec -> true | `Link | `Dir | `Commit -> false let empty_node () = Array.make 16 Empty let null = Hash.null let leaf_slot leaf ~subtree = if subtree then Subtree leaf else Note leaf (* [consolidate node parent index] puts in [parent.(index)], in place of [node], what [node] holds if that is nothing or a single note, and is [true] iff it does. *) let consolidate node parent index = let live = Array.fold_left (fun acc s -> match s with Empty -> acc | s -> s :: acc) [] node in match live with | [] -> parent.(index) <- Empty; true | [ (Note _ as s) ] -> parent.(index) <- s; true | _ -> false (* [search t node n key] is the node and level whose slot for [key] holds the leaf [key] would be compared with, reading on the way each directory [key] falls under. *) let rec search t node n key = match node.(0) with | Subtree l when under ~key l.key -> node.(0) <- Empty; load_subtree t l node n; search t node n key | _ -> ( let i = nibble n key in match node.(i) with | Internal child -> search t child (n + 1) key | Subtree l when under ~key l.key -> node.(i) <- Empty; load_subtree t l node n; search t node n key | _ -> (node, n)) (* [insert t node n leaf ~subtree ~combine] puts [leaf] in the trie below [node], at level [n]. A note for an object that has one already takes [combine ~cur new], and goes when that is the null id; a null note is not inserted. *) and insert t node n leaf ~subtree ~combine = let node, n = search t node n leaf.key in let i = nibble n leaf.key in match node.(i) with | Empty -> if not (Hash.equal leaf.value null) then node.(i) <- leaf_slot leaf ~subtree | Note l when (not subtree) && String.equal l.key leaf.key -> if not (Hash.equal l.value leaf.value) then begin l.value <- combine ~cur:l.value leaf.value; if Hash.equal l.value null then remove t leaf.key end | Note l when subtree && under ~key:l.key leaf.key -> load_subtree t leaf node n | (Note l | Subtree l) as other -> if not (Hash.equal leaf.value null) then begin let child = empty_node () in let is_subtree = match other with Subtree _ -> true | _ -> false in insert t child (n + 1) l ~subtree:is_subtree ~combine; node.(i) <- Internal child; insert t child (n + 1) leaf ~subtree ~combine end | Internal _ -> invalid_arg "Notes.insert: search stopped on an internal node" (* [load_subtree t sub node n] reads the directory [sub] into [node], at level [n]: an entry named by the rest of an object id is a note if it is a file, one named by two hex digits is a directory below if it is a tree, and every other entry is kept as it is, at its path (notes.c, load_subtree). A tree read at a second prefix is refused: its notes would annotate objects whose ids share every digit below the prefix, which git never writes, and the notes such a tree names grow as the power of its depth, not as the trees that hold them. *) and load_subtree t sub node n = if Hash.Set.mem sub.value t.read then fail_broken "the notes tree %a is the directory of two prefixes" Hash.pp sub.value; t.read <- Hash.Set.add sub.value t.read; let plen = prefix_length sub.key in let prefix = String.sub (hex_of sub.key) 0 (2 * plen) in let dirs = String.concat "" (List.init plen (fun i -> String.sub prefix (2 * i) 2 ^ "/")) in Tree.iter (fun (e : Tree.entry) -> let len = String.length e.name in let other () = t.others <- Paths.add (dirs ^ e.name) (e.perm, e.hash) t.others in if len = 2 * (raw_size - plen) then begin let buf = Bytes.of_string sub.key in if is_regular e.perm && decode buf plen e.name then insert t node n { key = Bytes.to_string buf; value = e.hash } ~subtree:false ~combine:(fun ~cur:_ _ -> fail_broken "%s holds two notes for %s" (Hash.to_hex sub.value) (hex_of (Bytes.to_string buf))) else other () end else if len = 2 then begin let buf = Bytes.make raw_size '\000' in Bytes.blit_string sub.key 0 buf 0 plen; if e.perm = `Dir && decode buf plen e.name then begin Bytes.set buf key_index (Char.chr (plen + 1)); insert t node n { key = Bytes.to_string buf; value = e.hash } ~subtree:true ~combine:(fun ~cur _ -> cur) end else other () end else other ()) (t.load sub.value) (* [remove t key] removes the note of [key], then folds each node left with a single note into its parent (notes.c, note_tree_remove). *) and remove t key = let node, n = search t t.root 0 key in let i = nibble n key in match node.(i) with | Note l when String.equal l.key key -> node.(i) <- Empty; let parents = Array.make (n + 1) t.root in for j = 0 to n - 1 do match parents.(j).(nibble j key) with | Internal child -> parents.(j + 1) <- child | _ -> assert false done; let rec unwind j = if j > 0 && consolidate parents.(j) parents.(j - 1) (nibble (j - 1) key) then unwind (j - 1) in unwind n | _ -> () let tree_of ~load root = let t = { root = empty_node (); others = Paths.empty; read = Hash.Set.empty; load } in Option.iter (fun h -> load_subtree t { key = String.make raw_size '\000'; value = h } t.root 0) root; t let note t key = let node, n = search t t.root 0 key in match node.(nibble n key) with | Note l when String.equal l.key key -> Some l.value | _ -> None let add t key value ~combine = insert t t.root 0 { key; value } ~subtree:false ~combine let overwrite ~cur:_ v = v (* [below t node n i acc] is [acc] with every note below the slot [i] of [node], at level [n], before it, in reverse object order, reading every directory under the slot. *) let rec below t node n i acc = match node.(i) with | Empty -> acc | Note l -> (l.key, l.value) :: acc | Internal child -> below_node t child (n + 1) acc | Subtree l -> node.(i) <- Empty; load_subtree t l node n; below t node n i acc and below_node t node n acc = let acc = ref acc in for i = 0 to 15 do acc := below t node n i !acc done; !acc (* Every note, in object order, reading every directory. *) let bindings t = List.rev_map (fun (key, value) -> (Hash.of_raw_string key, value)) (below_node t t.root 0 []) (* The notes of two sorted lists of notes that differ, before [acc], in reverse order. *) let rec apart xs ys acc = match (xs, ys) with | [], [] -> acc | (k, v) :: xs, [] -> apart xs [] ((k, Some v, None) :: acc) | [], (k, v) :: ys -> apart [] ys ((k, None, Some v) :: acc) | (kx, vx) :: xs', (ky, vy) :: ys' -> let c = String.compare kx ky in if c < 0 then apart xs' ys ((kx, Some vx, None) :: acc) else if c > 0 then apart xs ys' ((ky, None, Some vy) :: acc) else if Hash.equal vx vy then apart xs' ys' acc else apart xs' ys' ((kx, Some vx, Some vy) :: acc) (* The notes [a] and [b] hold apart, walking the two tries together: a directory both hold at one place with the same id holds the same notes and is not read; one of them reads only on the places they differ. *) let changes a b = let rec walk na nb n acc = let acc = ref acc in for i = 0 to 15 do acc := slot na nb n i !acc done; !acc and slot na nb n i acc = match (na.(i), nb.(i)) with | Subtree la, Subtree lb when String.equal la.key lb.key && Hash.equal la.value lb.value -> acc | Subtree la, _ -> na.(i) <- Empty; load_subtree a la na n; slot na nb n i acc | _, Subtree lb -> nb.(i) <- Empty; load_subtree b lb nb n; slot na nb n i acc | Empty, Empty -> acc | Internal ca, Internal cb -> walk ca cb (n + 1) acc | Note la, Note lb when String.equal la.key lb.key -> if Hash.equal la.value lb.value then acc else (la.key, Some la.value, Some lb.value) :: acc | _ -> apart (List.rev (below a na n i [])) (List.rev (below b nb n i [])) acc in List.rev_map (fun (key, va, vb) -> (Hash.of_raw_string key, va, vb)) (walk a.root b.root 0 []) (* {2 Writing} [determine_fanout] is git's: one level more below a directory whose sixteen slots at that level all hold an internal node or a directory not read. A directory not read is written back as it is while it sits above the fan-out of its place, and read into its place otherwise. *) let determine_fanout node n fanout = if n land 1 = 1 || n > 2 * fanout then fanout else if Array.for_all (function Subtree _ | Internal _ -> true | _ -> false) node then fanout + 1 else fanout (* The path of [key] under [fanout] directories (notes.c, construct_path_with_fanout). *) let path_with_fanout key fanout = let hex = hex_of key in let dirs = List.init fanout (fun i -> String.sub hex (2 * i) 2 ^ "/") in String.concat "" dirs ^ String.sub hex (2 * fanout) (40 - (2 * fanout)) let subtree_path key fanout = let plen = prefix_length key in let p = String.sub (path_with_fanout key fanout) 0 ((2 * plen) + fanout) in if String.ends_with ~suffix:"/" p then String.sub p 0 (String.length p - 1) else p (* The entries of the trees to write, by name, before they are written. *) type item = File of Tree.perm * Hash.t | Dir of (string, item) Hashtbl.t (* [put root path perm hash] adds the entry [path] to the trees below [root], and refuses a name used twice in one tree: git writes both entries, a tree git fsck refuses. *) let put root path perm hash = let twice () = fail_broken "two entries named %s in the notes tree" path in let rec go dir = function | [] -> invalid_arg "Notes.put: empty path" | [ name ] -> if Hashtbl.mem dir name then twice (); Hashtbl.replace dir name (File (perm, hash)) | name :: rest -> ( match Hashtbl.find_opt dir name with | Some (Dir sub) -> go sub rest | Some (File _) -> twice () | None -> let sub = Hashtbl.create 16 in Hashtbl.replace dir name (Dir sub); go sub rest) in go root (String.split_on_char '/' path) (* [place t root node n fanout] adds to [root] the notes and the directories not read below [node], at level [n] under [fanout] levels of fan-out. *) let rec place t root node n fanout = let fanout = determine_fanout node n fanout in for i = 0 to 15 do let rec slot () = match node.(i) with | Empty -> () | Note l -> put root (path_with_fanout l.key fanout) `Normal l.value | Internal child -> place t root child (n + 1) fanout | Subtree l -> (* The path of a directory kept as it is spells its prefix with one slash per level of fan-out, which names the directory only when the prefix is at most one byte longer than the fan-out; git writes a longer one at a path that does not, and here it is read into place instead. *) if n < 2 * fanout && prefix_length l.key <= fanout + 1 then put root (subtree_path l.key fanout) `Dir l.value else begin node.(i) <- Empty; load_subtree t l node n; slot () end in slot () done let rec write_dir ~write d = Hashtbl.fold (fun name item acc -> match item with | File (perm, hash) -> Tree.entry ~perm ~name hash :: acc | Dir sub -> Tree.entry ~perm:`Dir ~name (write_dir ~write sub) :: acc) d [] |> Tree.v |> fun tree -> write (Value.Tree tree) (* [encode ~write t] writes the trees of [t] with [write] and is the root. *) let encode ~write t = let root = Hashtbl.create 256 in place t root t.root 0 0; Paths.iter (fun path (perm, hash) -> put root path perm hash) t.others; write_dir ~write root (* {1 Notes refs} *) let max_attempts = 32 let valid_ref name = if String.starts_with ~prefix:"refs/notes/" name then Ok () else err_msgf "%s is outside refs/notes/: git keeps notes there" name let append_message = "Notes added by 'git notes append'\n" module Make (S : S) = struct module Walk = Rev_list.Make (S) let ( let* ) = Result.bind let read_tree store h = if Hash.equal h Tree.empty_digest then Tree.empty else match S.read store h with | Ok (Value.Tree tree) -> tree | Ok _ -> fail_broken "%a is not a tree" Hash.pp h | Error (`Msg m) -> fail_broken "%s" m let read_blob store h = match S.read store h with | Ok (Value.Blob b) -> Blob.to_string b | Ok _ -> fail_broken "the note %a is not a blob" Hash.pp h | Error (`Msg m) -> fail_broken "%s" m let write_blob store s = S.write store (Value.Blob (Blob.of_string s)) let load store root = tree_of ~load:(read_tree store) root let guard f = try f () with Broken m -> Error (`Msg m) (* The tip of [name] and the notes tree it names. *) let tip store name = let* tip = S.read_ref store name in match tip with | None -> Ok None | Some h -> ( match S.read store h with | Ok (Value.Commit c) -> Ok (Some (h, Commit.tree c, `Commit)) | Ok (Value.Tree _) -> Ok (Some (h, h, `Tree)) | Ok _ -> err_msgf "%s names neither a commit nor a tree" name | Error (`Msg m) -> Error (`Msg m)) (* The commit a write goes on: git commits notes only on a commit. *) let parent store name = let* tip = tip store name in match tip with | None -> Ok None | Some (h, tree, `Commit) -> Ok (Some (h, tree)) | Some (_, _, `Tree) -> err_msgf "%s names a tree, not a commit" name let find store ~ref obj = let* tip = tip store ref in match tip with | None -> Ok None | Some (_, tree, _) -> guard @@ fun () -> let t = load store (Some tree) in Ok (Option.map (read_blob store) (note t (Hash.to_raw_string obj))) let reader_tree store tree = let notes = lazy (load store (Some tree)) in fun obj -> try note (Lazy.force notes) (Hash.to_raw_string obj) with Broken m -> failwith m let reader store ~ref = let* tip = tip store ref in match tip with | None -> Ok (fun _ -> None) | Some (_, tree, _) -> Ok (reader_tree store tree) let list store ~ref = let* tip = tip store ref in match tip with | None -> Ok [] | Some (_, tree, _) -> guard @@ fun () -> Ok (bindings (load store (Some tree))) let commit_tree store h = match S.read store h with | Ok (Value.Commit c) -> Ok (Commit.tree c) | Ok _ -> err_msgf "%a is not a notes commit" Hash.pp h | Error (`Msg m) -> Error (`Msg m) let reader_commit ?cache store h = match Option.bind cache (fun cache -> !cache) with | Some (at, read) when Hash.equal at h -> Ok read | _ -> let* tree = commit_tree store h in let read = reader_tree store tree in Option.iter (fun cache -> cache := Some (h, read)) cache; Ok read let list_commit store h = let* tree = commit_tree store h in guard @@ fun () -> Ok (bindings (load store (Some tree))) let diff_commits store a b = let* ta = commit_tree store a in let* tb = commit_tree store b in if Hash.equal ta tb then Ok [] else guard @@ fun () -> Ok (changes (load store (Some ta)) (load store (Some tb))) let commit store ~author ~committer ~parents ~message tree = S.write store (Value.Commit (Commit.v ~tree ~author ~committer ~parents (Some message))) let note_update ~committer ~message name ~expected hash = let first = match String.index_opt message '\n' with | Some i -> String.sub message 0 i | None -> message in let reflog : Ref_transaction.reflog = { committer; message = "notes: " ^ String.trim first; create = false } in { Ref_transaction.name; expected = Option.fold ~none:Ref_transaction.Absent ~some:(fun hash -> Ref_transaction.Value hash) expected; target = Ref_transaction.Set hash; reflog = Some reflog; } let publish store (update : Ref_transaction.update) = match (update.expected, update.target, update.reflog) with | (Absent | Value _), Set hash, Some reflog -> ( let expected = match update.expected with Value hash -> Some hash | _ -> None in match S.compare_and_swap_ref store update.name ~expected ~reflog:(reflog.committer, reflog.message) hash with | Ok () -> Ok `Moved | Error `Raced -> Ok (`Lost "another writer moved the ref") | Error (`Locked lock) -> Ok (`Lost (Fmt.str "another writer held %s" lock)) | Error (`Msg _) as e -> e) | _ -> err_msgf "notes publication needs an observed direct ref update" (* A single-ref publisher retains the backend's lock wait and retry result. *) let swap store ~committer name ~expected ~message hash = publish store (note_update ~committer ~message name ~expected hash) let rec retry ?(why = "") what attempt f = if attempt > max_attempts then err_msgf "%s: no attempt of %d moved the ref; on the last, %s" what max_attempts why else let* r = f () in match r with | `Done v -> Ok v | `Lost why -> retry ~why what (attempt + 1) f (* [outcome moved v] is [`Done v] once the ref moved, else the loss. *) let outcome moved v = match moved with `Moved -> `Done v | `Lost _ as lost -> lost (* [entries] grouped by object, in the order each object first appears, each with its lines in order. *) let by_object entries = let lines = Hashtbl.create (List.length entries) in let order = List.fold_left (fun order (obj, line) -> let key = Hash.to_raw_string obj in match Hashtbl.find_opt lines key with | Some l -> Hashtbl.replace lines key (line :: l); order | None -> Hashtbl.add lines key [ line ]; key :: order) [] entries in List.rev_map (fun key -> (key, List.rev (Hashtbl.find lines key))) order (* Preconditions are immutable observations, checked in each newly loaded tree before any append in that attempt. *) let check_expected t ~ref expected = List.fold_left (fun acc (obj, observed) -> let* () = acc in let current = note t (Hash.to_raw_string obj) in if Option.equal Hash.equal current observed then Ok () else err_msgf "the note of %a under %s changed since it was observed" Hash.pp obj ref) (Ok ()) expected let append_entries ~ref entries = List.iter (fun (_, line) -> validate_line line) entries; let* () = valid_ref ref in Ok (by_object entries) let append_proposal store ~message ~expected ~author ~committer ~ref notes = let* parent = parent store ref in let* after = guard @@ fun () -> let t = load store (Option.map snd parent) in let* () = check_expected t ~ref expected in List.iter (fun (key, lines) -> let note = match note t key with None -> "" | Some h -> read_blob store h in let suffix = List.concat_map (fun line -> [ line; "\n" ]) lines in let note = String.concat "" (note :: line_separator note :: suffix) in add t key (write_blob store note) ~combine:overwrite) notes; let tree = encode ~write:(S.write store) t in Ok (commit store ~author ~committer ~parents:(Option.to_list (Option.map fst parent)) ~message tree) in Ok (note_update ~committer ~message ref ~expected:(Option.map fst parent) after) let append_objects store ?(message = append_message) ?(expected = []) ~author ~committer ~ref entries = let* notes = append_entries ~ref entries in match notes with | [] -> Ok None | notes -> let* update = append_proposal store ~message ~expected ~author ~committer ~ref notes in Ok (Some update) let append_all store ?(message = append_message) ?(expected = []) ~author ~committer ~ref entries = let* notes = append_entries ~ref entries in match notes with | [] -> Ok None | notes -> ( retry ref 1 @@ fun () -> let* update = append_proposal store ~message ~expected ~author ~committer ~ref notes in let* moved = publish store update in match update.target with | Ref_transaction.Set hash -> Ok (outcome moved (Some hash)) | _ -> err_msgf "notes append proposal has no new commit") let append store ?message ~author ~committer ~ref obj line = let* c = append_all store ?message ~author ~committer ~ref [ (obj, line) ] in match c with | Some c -> Ok c | None -> err_msgf "%s: the append wrote no commit" ref let union_of_lines store ~cur v = let text h = if Hash.equal h null then "" else read_blob store h in write_blob store (cat_sort_uniq (text cur) (text v)) (* Whether the lines of the note [before] are among those of [theirs], in whatever order: a sorted merge, linear in their lines once sorted. *) let among before theirs = String.equal (cat_sort_uniq before theirs) (cat_sort_uniq "" theirs) let union_commit ?(valid = fun _ _ -> Ok ()) store ~author ~committer ~ref remote = let* () = valid_ref ref in let* remote_tree = commit_tree store remote in let message = Fmt.str "Union notes from %a into %s" Hash.pp remote ref in (* The notes of [remote] that differ from those of [base]'s tree, each checked by [valid] before it is read. *) let incoming base = let* base_tree = match base with | None -> Ok None | Some b -> Result.map Option.some (commit_tree store b) in guard @@ fun () -> let changed = changes (load store base_tree) (load store (Some remote_tree)) in List.iter (function | obj, _, Some blob -> ( match valid obj blob with | Ok () -> () | Error (`Msg m) -> raise (Broken m)) | _, _, None -> ()) changed; Ok changed in retry ref 1 @@ fun () -> let* local = parent store ref in match local with | None -> let* _ = incoming None in let* moved = swap store ~committer ref ~expected:None ~message remote in Ok (outcome moved (Fast_forward remote)) | Some (l, local_tree) -> ( let base = Walk.merge_base store l remote in match base with | Some b when Hash.equal b remote -> Ok (`Done Up_to_date) | _ -> let* changed = incoming base in (* Whether the local notes hold a line the remote's lack, among the notes [remote] changed: when [ref] is [base], every other note is the same on both sides. *) let extra = Stdlib.ref false in let* tree = guard @@ fun () -> let t = load store (Some local_tree) in List.iter (fun (obj, _, after) -> let key = Hash.to_raw_string obj in let before = match note t key with | None -> "" | Some h -> read_blob store h in match after with | None -> if lines before <> [] then extra := true | Some blob -> let theirs = read_blob store blob in if not (among before theirs) then extra := true; let after = cat_sort_uniq before theirs in if before <> after then add t key (write_blob store after) ~combine:overwrite) changed; Ok (encode ~write:(S.write store) t) in if Option.equal Hash.equal base (Some l) && (Hash.equal tree remote_tree || not !extra) then let* moved = swap store ~committer ref ~expected:(Some l) ~message remote in Ok (outcome moved (Fast_forward remote)) else let* c = guard @@ fun () -> Ok (commit store ~author ~committer ~parents:[ l; remote ] ~message tree) in let* moved = swap store ~committer ref ~expected:(Some l) ~message c in Ok (outcome moved (Merged c))) (* The tree [git notes merge -s cat_sort_uniq] writes (notes-merge.c, merge_from_diffs): the notes of [local] with each change [remote] made since [base], each note unread by the changes left as [local] has it. *) let merge_trees store ~base ~local ~remote = let changed = changes (load store base) (load store (Some remote)) in let t = load store (Some local) in List.iter (fun (obj, bv, rv) -> let key = Hash.to_raw_string obj in let lv = note t key in let value = Option.value rv ~default:null in if Option.equal Hash.equal lv rv then () else if Option.equal Hash.equal lv bv then add t key value ~combine:overwrite else add t key value ~combine:(union_of_lines store)) changed; encode ~write:(S.write store) t let merge store ~author ~committer ~ref from = let* () = valid_ref ref in let message = Fmt.str "Merged notes from %s into %s" from ref in retry ref 1 @@ fun () -> let* local = parent store ref in let* remote = parent store from in match (local, remote) with | None, None -> err_msgf "cannot merge empty notes ref %s into empty notes ref %s" from ref | Some _, None -> Ok (`Done Up_to_date) | None, Some (r, _) -> let* moved = swap store ~committer ref ~expected:None ~message r in Ok (outcome moved (Fast_forward r)) | Some (l, local_tree), Some (r, remote_tree) -> ( match Walk.merge_base store l r with | Some b when Hash.equal b r -> Ok (`Done Up_to_date) | Some b when Hash.equal b l -> let* moved = swap store ~committer ref ~expected:(Some l) ~message r in Ok (outcome moved (Fast_forward r)) | base -> let* base = match base with | None -> Ok None | Some b -> ( match S.read store b with | Ok (Value.Commit c) -> Ok (Some (Commit.tree c)) | Ok _ -> err_msgf "%a is not a commit" Hash.pp b | Error (`Msg m) -> Error (`Msg m)) in let* c = guard @@ fun () -> let tree = merge_trees store ~base ~local:local_tree ~remote:remote_tree in Ok (commit store ~author ~committer ~parents:[ l; r ] ~message tree) in let* moved = swap store ~committer ref ~expected:(Some l) ~message c in Ok (outcome moved (Merged c))) end