(* 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 hash_size = Hash.digest_size type layer = { read : int -> int -> string; names : Oid_fanout.t; first : int; (** The position of the layer's first commit. *) cdat : int; gda2 : int option; gdo2 : (int * int) option; edge : (int * int) option; checksum : Hash.t; } type t = { layers : layer array; count : int; v2 : bool; on_find : unit -> unit; } let err fmt = Fmt.kstr (fun s -> Error (`Msg ("commit-graph: " ^ s))) fmt let u32 s off = Int32.to_int (String.get_int32_be s off) land 0xffff_ffff let u64 s off = let rec go acc i = if i = 8 then acc else go ((acc lsl 8) lor Char.code s.[off + i]) (i + 1) in go 0 0 let header_size = 8 let commit_data_size = hash_size + 16 (* The Base Graphs List names the checksum of every layer below, lowest first. *) let check_bases ~read ~bases chunks = let n = Array.length bases in if n = 0 then Ok () else match Chunk_table.find chunks "BASE" with | Some (off, len) when len = n * hash_size -> let names = read off len in let named i = Hash.equal (Hash.of_raw_string (String.sub names (i * hash_size) hash_size)) bases.(i).checksum in let rec go i = i >= n || (named i && go (i + 1)) in if go 0 then Ok () else err "the base layers are not the ones named" | Some _ -> err "Base Graphs List does not fit its layers" | None -> err "no Base Graphs List" let required chunks id ~len = match Chunk_table.find chunks id with | Some (off, l) when l = len -> Ok off | Some _ -> err "chunk %s does not fit the number of commits" id | None -> err "no chunk %s" id let header ~base_count ~length read = if length < header_size + 12 + hash_size then err "file too short" else let h = read 0 header_size in if String.sub h 0 4 <> "CGPH" then err "bad signature" else if Char.code h.[4] <> 1 then err "version %d" (Char.code h.[4]) else if Char.code h.[5] <> 1 then err "hash version %d" (Char.code h.[5]) else if Char.code h.[7] <> base_count then err "%d base layers named, %d given" (Char.code h.[7]) base_count else Ok h let object_names ~read chunks = let open Result.Syntax in let* oidf = required chunks "OIDF" ~len:Oid_fanout.fanout_size in let* oidl = match Chunk_table.find chunks "OIDL" with | Some (off, _) -> Ok off | None -> err "no chunk OIDL" in Oid_fanout.v ~fanout:(read oidf Oid_fanout.fanout_size) ~read ~off:oidl let commit_data ~size chunks = let open Result.Syntax in let* _ = required chunks "OIDL" ~len:(size * hash_size) in required chunks "CDAT" ~len:(size * commit_data_size) let graph_tables ~read ~length ~bases h = let open Result.Syntax in let* chunks = Chunk_table.v ~read ~length:(length - hash_size) ~off:header_size ~count:(Char.code h.[6]) in let* () = check_bases ~read ~bases chunks in let* names = object_names ~read chunks in let* cdat = commit_data ~size:(Oid_fanout.count names) chunks in Ok (chunks, names, cdat) let of_read ?base ~length read = let open Result.Syntax in let bases = match base with None -> [||] | Some b -> b.layers in let* h = header ~base_count:(Array.length bases) ~length read in let* chunks, names, cdat = graph_tables ~read ~length ~bases h in let size = Oid_fanout.count names in let gda2 = match Chunk_table.find chunks "GDA2" with | Some (off, len) when len = size * 4 -> Some off | _ -> None in let first = match base with None -> 0 | Some b -> b.count in let layer = { read; names; first; cdat; gda2; gdo2 = Chunk_table.find chunks "GDO2"; edge = Chunk_table.find chunks "EDGE"; checksum = Hash.of_raw_string (read (length - hash_size) hash_size); } in let v2 = Option.is_some gda2 && match base with None -> true | Some b -> b.v2 in Ok { layers = Array.append bases [| layer |]; count = first + size; v2; on_find = ignore; } let of_string ?base s = of_read ?base ~length:(String.length s) (fun off len -> String.sub s off len) let checksum t = t.layers.(Array.length t.layers - 1).checksum let layers t = Array.length t.layers let count t = t.count let corrected_dates t = t.v2 let probed t f = { t with on_find = f } let find t h = t.on_find (); let rec go i = if i < 0 then None else let l = t.layers.(i) in match Oid_fanout.find l.names h with | Some j -> Some (l.first + j) | None -> go (i - 1) in go (Array.length t.layers - 1) (* The layer holding position [i], and [i]'s index in it. *) let locate t i = if i < 0 || i >= t.count then invalid_arg "Commit_graph: position out of bounds"; let rec go k = let l = t.layers.(k) in if i >= l.first then (l, i - l.first) else go (k - 1) in go (Array.length t.layers - 1) let hash t i = let l, j = locate t i in Oid_fanout.hash_at l.names j let data t i = let l, j = locate t i in (l, j, l.read (l.cdat + (j * commit_data_size)) commit_data_size) let tree t i = let _, _, d = data t i in Hash.of_raw_string (String.sub d 0 hash_size) let no_parent = 0x7000_0000 let edge_flag = 0x8000_0000 let position t p = if p >= t.count then invalid_arg "Commit_graph: parent position out of bounds" else p (* The second through last parents of an octopus, from the Extra Edge List: positions until one whose top bit is set, the last. *) let edges t l k = match l.edge with | None -> invalid_arg "Commit_graph: octopus without an Extra Edge List" | Some (off, len) -> let rec go k acc = if (k + 1) * 4 > len then invalid_arg "Commit_graph: Extra Edge List overrun" else let v = u32 (l.read (off + (k * 4)) 4) 0 in let acc = position t (v land lnot edge_flag) :: acc in if v land edge_flag <> 0 then List.rev acc else go (k + 1) acc in go k [] let parents t i = let l, _, d = data t i in let p1 = u32 d hash_size and p2 = u32 d (hash_size + 4) in if p1 = no_parent then [] else if p2 = no_parent then [ position t p1 ] else if p2 land edge_flag <> 0 then position t p1 :: edges t l (p2 land lnot edge_flag) else [ position t p1; position t p2 ] let commit_time t i = let _, _, d = data t i in let hi = u32 d (hash_size + 8) land 3 in Int64.logor (Int64.shift_left (Int64.of_int hi) 32) (Int64.of_int (u32 d (hash_size + 12))) (* A corrected commit date offset with its top bit set is a row of the Generation Data Overflow chunk. *) let offset l j = match l.gda2 with | None -> invalid_arg "Commit_graph: no Generation Data" | Some off -> ( let v = u32 (l.read (off + (j * 4)) 4) 0 in if v land edge_flag = 0 then Int64.of_int v else let k = v land lnot edge_flag in match l.gdo2 with | Some (off, len) when (k + 1) * 8 <= len -> Int64.of_int (u64 (l.read (off + (k * 8)) 8) 0) | _ -> invalid_arg "Commit_graph: Generation Data Overflow overrun") let generation t i = if t.v2 then let l, j = locate t i in Int64.add (commit_time t i) (offset l j) else let _, _, d = data t i in Int64.of_int (u32 d (hash_size + 8) lsr 2) (* {1 Layers} *) let below t = let n = Array.length t.layers in if n = 1 then None else let layers = Array.sub t.layers 0 (n - 1) in Some { t with layers; count = t.layers.(n - 1).first; v2 = Array.for_all (fun l -> Option.is_some l.gda2) layers; } let generation_data t = Option.is_some t.layers.(Array.length t.layers - 1).gda2 let level t i = let _, _, d = data t i in u32 d (hash_size + 8) lsr 2 (* {1 Writing} *) type commit = { hash : Hash.t; tree : Hash.t; parents : Hash.t list; time : int64; } let level_max = 0x3fff_ffff let offset_max = 0x7fff_ffffL let date_mask = Int64.(sub (shift_left 1L 34) 1L) (* The topological level and the corrected commit date of each commit of [cs], from its parents', in git's recurrence (commit-graph.c, compute_generation_from_max): a level is one more than its parents' greatest, at most [level_max]; a corrected date is the commit's date, or one more than its parents' greatest corrected date when that is not less. A date of zero takes the second. A walk with its own stack, as git's: a history is deeper than a native stack. *) let generations ~base ~position cs = let n = Array.length cs in let levels = Array.make n 0 and dates = Array.make n 0L in let parent_values p = match position p with | `Layer j -> if levels.(j) = 0 then `Pending j else `Done (levels.(j), dates.(j)) | `Base i -> let b = Option.get base in `Done (level b i, generation b i) in let rec settle = function | [] -> () | j :: rest as stack -> let c = cs.(j) in let rec scan lmax dmax = function | [] -> levels.(j) <- min lmax (level_max - 1) + 1; dates.(j) <- (if c.time <> 0L && c.time > dmax then c.time else Int64.succ dmax); settle rest | p :: ps -> ( match parent_values p with | `Pending k -> settle (k :: stack) | `Done (l, d) -> scan (max lmax l) (Int64.max dmax d) ps) in scan 0 0L c.parents in for j = 0 to n - 1 do if levels.(j) = 0 then settle [ j ] done; (levels, dates) let be32 b v = Buffer.add_int32_be b (Int32.of_int (v land 0xffff_ffff)) (* The commits sorted by name, and the position of a parent: in the layer, after the base's commits, or in the base. *) let index ?base cs = let cs = Array.of_list cs in Array.sort (fun a b -> Hash.compare a.hash b.hash) cs; let index = Hashtbl.create (Array.length cs) in Array.iteri (fun j c -> if Hashtbl.mem index c.hash then Fmt.invalid_arg "Commit_graph.encode: %a repeats" Hash.pp c.hash; if Option.is_some (Option.bind base (fun b -> find b c.hash)) then Fmt.invalid_arg "Commit_graph.encode: %a is in the base" Hash.pp c.hash; Hashtbl.add index c.hash j) cs; let position p = match Hashtbl.find_opt index p with | Some j -> `Layer j | None -> ( match Option.bind base (fun b -> find b p) with | Some i -> `Base i | None -> Fmt.invalid_arg "Commit_graph.encode: parent %a is in no layer" Hash.pp p) in (cs, position) (* OIDF: how many names start with a byte at most [i]. *) let add_fanout b cs = let k = ref 0 in for i = 0 to 255 do while !k < Array.length cs && Char.code (Hash.to_raw_string cs.(!k).hash).[0] <= i do incr k done; be32 b !k done (* CDAT: the tree, two parent positions, an octopus's second one the start of its run in the Extra Edge List, then the level and the 34-bit date. *) let add_commit_data b ~edge ~levels cs = let edges = ref 0 in Array.iteri (fun j c -> Buffer.add_string b (Hash.to_raw_string c.tree); (match c.parents with | [] -> be32 b no_parent; be32 b no_parent | [ p ] -> be32 b (edge p); be32 b no_parent | [ p; q ] -> be32 b (edge p); be32 b (edge q) | p :: rest -> be32 b (edge p); be32 b (edge_flag lor !edges); edges := !edges + List.length rest); let time = Int64.logand c.time date_mask in be32 b ((levels.(j) lsl 2) lor Int64.to_int (Int64.shift_right_logical time 32)); be32 b (Int64.to_int (Int64.logand time 0xffff_ffffL))) cs (* GDA2, then GDO2 for the offsets past 31 bits. *) let add_generation_data b offsets = let k = ref 0 in Array.iter (fun o -> if o > offset_max then ( be32 b (edge_flag lor !k); incr k) else be32 b (Int64.to_int o)) offsets; Array.iter (fun o -> if o > offset_max then Buffer.add_int64_be b o) offsets (* EDGE: an octopus's second through last parents, the last flagged. *) let add_extra_edges b ~edge cs = Array.iter (fun c -> match c.parents with | _ :: (_ :: _ :: _ as rest) -> let last = List.length rest - 1 in List.iteri (fun i p -> be32 b (if i = last then edge p lor edge_flag else edge p)) rest | _ -> ()) cs let count_if f a = Array.fold_left (fun k x -> if f x then k + 1 else k) 0 a let chunks ~n ~generation_data ~overflows ~extra ~bases = let some cond chunk = if cond then [ chunk ] else [] in [ ("OIDF", Oid_fanout.fanout_size); ("OIDL", n * hash_size); ("CDAT", n * commit_data_size); ] @ some generation_data ("GDA2", n * 4) @ some (overflows > 0) ("GDO2", overflows * 8) @ some (extra > 0) ("EDGE", extra * 4) @ some (bases > 0) ("BASE", bases * hash_size) let encode ?base cs = let cs, position = index ?base cs in let first = match base with None -> 0 | Some b -> b.count in let edge p = match position p with `Layer j -> first + j | `Base i -> i in let levels, dates = generations ~base ~position cs in let generation_data = match base with None -> true | Some b -> generation_data b in (* The corrected date's offset from the commit date the file keeps, its 34 low bits (commit-graph.c, compute_generation_offset). *) let offsets = Array.mapi (fun j c -> Int64.sub dates.(j) (Int64.logand c.time date_mask)) cs in let bases = match base with None -> [||] | Some b -> b.layers in let chunks = chunks ~n:(Array.length cs) ~generation_data ~overflows: (if generation_data then count_if (fun o -> o > offset_max) offsets else 0) ~extra: (Array.fold_left (fun k c -> let m = List.length c.parents in if m > 2 then k + m - 1 else k) 0 cs) ~bases:(Array.length bases) in let b = Buffer.create 4096 in Buffer.add_string b "CGPH\001\001"; Buffer.add_uint8 b (List.length chunks); Buffer.add_uint8 b (Array.length bases); Buffer.add_string b (Chunk_table.encode ~off:header_size chunks); add_fanout b cs; Array.iter (fun c -> Buffer.add_string b (Hash.to_raw_string c.hash)) cs; add_commit_data b ~edge ~levels cs; if generation_data then add_generation_data b offsets; add_extra_edges b ~edge cs; Array.iter (fun l -> Buffer.add_string b (Hash.to_raw_string l.checksum)) bases; let body = Buffer.contents b in body ^ Hash.to_raw_string (Hash.digest_raw body)