Something went wrong. Try again.
Git format in pure OCaml
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447(* Copyright (c) 2024-2026 Thomas Gazagnaire <thomas@gazagnaire.org>
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. *)
(** History rewriting by path predicate, functored over a {!Store.S}. *)
module Hash = Object_hash
let src = Logs.Src.create "git.filter" ~doc:"history rewriting"
module Log = (val Logs.src_log src : Logs.LOG)
type predicate = path:string list -> bool
let keep_all ~path:_ = truelet drop_all ~path:_ = falselet combine ps ~path = List.for_all (fun p -> p ~path) ps
(* Glob matching is delegated to Re.Glob. We compile each pattern into a Re.t once and execute it on basenames or full paths depending on whether the pattern contains a [/]. *)
let compile_pattern pattern = if String.contains pattern '/' then (* Path pattern: [*] does not cross [/]; [**] does. *) Re.Glob.glob ~anchored:true ~pathname:true ~match_backslashes:false ~double_asterisk:true pattern |> Re.compile else (* Basename pattern: simple matching, [*] matches any chars. *) Re.Glob.glob ~anchored:true ~pathname:false pattern |> Re.compile
let glob_match ~pattern s = Re.execp (compile_pattern pattern) s
let glob patterns = let compiled = List.map (fun pat -> let on_full = String.contains pat '/' in (on_full, compile_pattern pat)) patterns in fun ~path -> let basename = match List.rev path with [] -> "" | x :: _ -> x in let full = String.concat "/" path in not (List.exists (fun (on_full, re) -> Re.execp re (if on_full then full else basename)) compiled)
let pp_path ppf = function | [] -> Fmt.string ppf "/" | ps -> Fmt.pf ppf "/%s" (String.concat "/" ps)
(* Memo for a single filter run: (tree_hash, prefix) -> (new_hash, dropped). Prefix matters because the predicate sees full paths, so the same tree hash visited under two different prefixes can legitimately yield different results. *)module Memo_key = struct type t = Hash.t * string list
let equal (h1, p1) (h2, p2) = Hash.equal h1 h2 && List.equal String.equal p1 p2
let hash (h, p) = Hash.v h lxor Hashtbl.hash p land max_intend
module Memo_tbl = Hashtbl.Make (Memo_key)
(* Counters tracked per [history] run. Attached to the memo so tree_aux updates them alongside the cache, no global ref. *)type tree_memo = { table : (Hash.t * int) Memo_tbl.t; mutable memo_hits : int; mutable memo_misses : int;}
let memo () = { table = Memo_tbl.create 4096; memo_hits = 0; memo_misses = 0 }
type stats = { commits_visited : int; commits_rewritten : int; commits_dropped : int; trees_rewritten : int; entries_dropped : int; refs_updated : int; tree_memo_hits : int; (** Tree-walks that found [(hash, prefix)] already computed. *) tree_memo_misses : int; (** Tree-walks that had to read and filter the tree. *)}
let empty_stats = { commits_visited = 0; commits_rewritten = 0; commits_dropped = 0; trees_rewritten = 0; entries_dropped = 0; refs_updated = 0; tree_memo_hits = 0; tree_memo_misses = 0; }
let merge_stats a b = { commits_visited = a.commits_visited + b.commits_visited; commits_rewritten = a.commits_rewritten + b.commits_rewritten; commits_dropped = a.commits_dropped + b.commits_dropped; trees_rewritten = a.trees_rewritten + b.trees_rewritten; entries_dropped = a.entries_dropped + b.entries_dropped; refs_updated = a.refs_updated + b.refs_updated; tree_memo_hits = a.tree_memo_hits + b.tree_memo_hits; tree_memo_misses = a.tree_memo_misses + b.tree_memo_misses; }
let pp_stats ppf s = Fmt.pf ppf "@[<v>commits visited: %d@,\ commits rewritten: %d@,\ commits dropped: %d@,\ trees rewritten: %d@,\ entries dropped: %d@,\ refs updated: %d@,\ tree memo hits: %d@,\ tree memo misses: %d@]" s.commits_visited s.commits_rewritten s.commits_dropped s.trees_rewritten s.entries_dropped s.refs_updated s.tree_memo_hits s.tree_memo_misses
let map_parents map old_parents = List.map (fun p -> match Hashtbl.find_opt map p with Some np -> np | None -> p) old_parents
module Make (S : Store.S) = struct (* The store a rewrite reads and writes: [repo] itself, or, for a dry run, [repo] under a table that holds the objects the rewrite makes and answers reads of them, so [repo] is left as it was. *) type view = { repo : S.t; pending : (Hash.t, Value.t) Hashtbl.t option }
let store repo = { repo; pending = None }
let read v h = match Option.bind v.pending (fun p -> Hashtbl.find_opt p h) with | Some value -> Ok value | None -> S.read v.repo h
let write v value ~into = match v.pending with | None -> into v.repo | Some p -> let h = Value.digest value in Hashtbl.replace p h value; h
let write_tree v t = write v (Value.tree t) ~into:(fun r -> S.write_tree r t)
let write_commit v c = write v (Value.commit c) ~into:(fun r -> S.write_commit r c)
module R = Rev_list.Make (struct type t = view
let read = read let commit_graph v = S.commit_graph v.repo end)
let rewritten_dir_entry repo entry entry_path sub_hash = match read repo sub_hash with | Ok (Value.Tree sub) when Tree.is_empty sub -> `Drop | Ok (Value.Tree _) -> `Keep { entry with Tree.hash = sub_hash } | Ok _ | Error _ -> Fmt.failwith "Filter.tree: subtree read failed at %a (rewritten tree %a)" pp_path entry_path Hash.pp sub_hash
let rec tree_aux_memo memo repo pred prefix hash = let key = (hash, prefix) in match Memo_tbl.find_opt memo.table key with | Some r -> memo.memo_hits <- memo.memo_hits + 1; r | None -> memo.memo_misses <- memo.memo_misses + 1; let r = tree_aux_compute memo repo pred prefix hash in Memo_tbl.add memo.table key r; r
and fold_dir_entry memo repo pred entry entry_path acc dropped = let sub_hash, sub_dropped = tree_aux_memo memo repo pred entry_path entry.Tree.hash in let dropped = dropped + sub_dropped in if Hash.equal sub_hash entry.hash then (entry :: acc, dropped) else match rewritten_dir_entry repo entry entry_path sub_hash with | `Drop -> (acc, dropped) | `Keep e -> (e :: acc, dropped)
and fold_tree_entry memo repo pred prefix (acc, dropped) (entry : Tree.entry) = let entry_path = prefix @ [ entry.name ] in if not (pred ~path:entry_path) then (acc, dropped + 1) else match entry.perm with | `Dir -> fold_dir_entry memo repo pred entry entry_path acc dropped | _ -> (entry :: acc, dropped)
and tree_aux_compute memo repo pred prefix hash = match read repo hash with | Error (`Msg m) -> Fmt.failwith "Filter.tree: %s at %a (tree %a)" m pp_path prefix Hash.pp hash | Ok (Value.Tree tree) -> let entries = Tree.to_list tree in let kept_rev, dropped = List.fold_left (fold_tree_entry memo repo pred prefix) ([], 0) entries in if dropped = 0 then (hash, 0) else let new_tree = Tree.v (List.rev kept_rev) in let new_hash = write_tree repo new_tree in (new_hash, dropped) | Ok _ -> Fmt.failwith "Filter.tree: expected a tree at %a (hash %a)" pp_path prefix Hash.pp hash
let tree_aux = tree_aux_memo
let tree repo pred ?(prefix = []) hash = let memo = memo () in fst (tree_aux memo (store repo) pred prefix hash)
let tree_of_commit_exn repo h = match read repo h with | Ok (Value.Commit c) -> Commit.tree c | Ok _ -> failwith "Filter: expected a commit object" | Error (`Msg m) -> failwith ("Filter: read commit: " ^ m)
(* Recurse into [h]'s subtrees looking for [subtree]. Caller has already marked [h] as visited and confirmed [h <> subtree]. *) let rec walk_subtrees repo ~visited ~subtree h = match read repo h with | Ok (Value.Tree t) -> List.exists (fun (e : Tree.entry) -> e.perm = `Dir && walk_for_subtree repo ~visited ~subtree e.hash) (Tree.to_list t) | _ -> false
and walk_for_subtree repo ~visited ~subtree h = if Hashtbl.mem visited h then false else begin Hashtbl.add visited h (); if Hash.equal h subtree then true else walk_subtrees repo ~visited ~subtree h end
(* [true] iff [subtree] equals [root] or appears as a tree entry at any depth inside [root]. Memoised per call to skip shared subtrees. *) let contains_subtree repo ~root ~subtree = if Hash.equal root subtree then true else let visited = Hashtbl.create 64 in walk_for_subtree repo ~visited ~subtree root
(* Return parents whose tree was placed somewhere in [old_tree] (a subtree graft) and is no longer placed anywhere in [new_tree] after the rewrite. *) let detached repo ~old_tree ~new_tree ~new_parents = match new_parents with | [] | [ _ ] -> [] | _ -> List.filter (fun p -> let p_tree = tree_of_commit_exn repo p in contains_subtree repo ~root:old_tree ~subtree:p_tree && not (contains_subtree repo ~root:new_tree ~subtree:p_tree)) new_parents
(* Decide whether a rewritten commit is "empty" against its parents and can be pruned. Root commits are never pruned. *) let is_empty_after_filter repo new_tree new_parents = match new_parents with | [] -> false | [ p ] -> Hash.equal new_tree (tree_of_commit_exn repo p) | first :: rest -> List.for_all (Hash.equal first) rest && Hash.equal new_tree (tree_of_commit_exn repo first)
(* Rewrite one commit during {!history}. Mutates [map] and [stats]. *) let process_commit_for_history repo pred memo map stats h commit = let old_tree = Commit.tree commit in let new_tree, dropped = try tree_aux memo repo pred [] old_tree with Failure m -> Fmt.failwith "%s at commit %a" m Hash.pp h in let old_parents = Commit.parents commit in let mapped_parents = map_parents map old_parents in let detached = detached repo ~old_tree ~new_tree ~new_parents:mapped_parents in let new_parents = if detached = [] then mapped_parents else List.filter (fun p -> not (List.exists (Hash.equal p) detached)) mapped_parents in let tree_changed = not (Hash.equal new_tree old_tree) in let parents_changed = not (Hash.equal_list new_parents old_parents) in if dropped > 0 && is_empty_after_filter repo new_tree new_parents then begin let target = List.hd new_parents in Hashtbl.add map h target; stats := { !stats with commits_dropped = !stats.commits_dropped + 1; entries_dropped = !stats.entries_dropped + dropped; } end else if (not tree_changed) && not parents_changed then Hashtbl.add map h h else begin let new_commit = Commit.v ~tree:new_tree ~author:(Commit.author commit) ~committer:(Commit.committer commit) ~parents:new_parents ~extra:(Commit.extra commit) (Commit.message commit) in let new_hash = write_commit repo new_commit in Hashtbl.add map h new_hash; stats := { !stats with commits_rewritten = !stats.commits_rewritten + 1; trees_rewritten = (!stats.trees_rewritten + if tree_changed then 1 else 0); entries_dropped = !stats.entries_dropped + dropped; } end
type state = { pred : predicate; map : (Hash.t, Hash.t) Hashtbl.t; tree_memo : tree_memo; pending : (Hash.t, Value.t) Hashtbl.t option; }
let state ?(dry_run = false) pred = { pred; map = Hashtbl.create 1024; tree_memo = memo (); pending = (if dry_run then Some (Hashtbl.create 1024) else None); }
let history ?state:st repo pred head = let st = match st with | None -> state pred | Some st when st.pred == pred -> st | Some _ -> invalid_arg "Filter.history: state of another predicate" in let { map; tree_memo = memo; pending; _ } = st in let repo = { repo; pending } in match R.topo_sort_reverse repo head ~stop:(Hashtbl.mem map) with | Error (`Msg m) -> failwith ("Filter.history: " ^ m) | Ok commits -> let hits = memo.memo_hits and misses = memo.memo_misses in let stats = ref { empty_stats with commits_visited = List.length commits } in List.iter (fun (ci : Rev_list.commit_info) -> match read repo ci.hash with | Ok (Value.Commit commit) -> process_commit_for_history repo pred memo map stats ci.hash commit | Ok _ -> failwith "Filter.history: expected a commit object" | Error (`Msg m) -> failwith ("Filter.history: read commit: " ^ m)) commits; let new_head = match Hashtbl.find_opt map head with Some h -> h | None -> head in let final_stats = { !stats with tree_memo_hits = memo.memo_hits - hits; tree_memo_misses = memo.memo_misses - misses; } in (new_head, final_stats)
(* Defined under [ref_of_apply] internally so that the name [ref] does not shadow [Stdlib.ref] in the rest of the module. The public alias [ref] is bound at the bottom. *) let ref_of_apply ?state repo pred ~ref_name = (match state with | Some { pending = Some _; _ } -> invalid_arg "Filter.ref: a dry-run state" | Some { pending = None; _ } | None -> ()); match S.read_ref repo ref_name with | Error (`Msg m) -> Error (`Msg m) | Ok None -> Ok None | Ok (Some old_tip) -> let new_tip, stats = history ?state repo pred old_tip in if not (Hash.equal new_tip old_tip) then begin S.write_ref repo ref_name new_tip; Log.info (fun m -> m "ref %s: %a -> %a" ref_name Hash.pp old_tip Hash.pp new_tip); Ok (Some { stats with refs_updated = stats.refs_updated + 1 }) end else Ok (Some stats)
let ref_of_applys repo pred ~patterns = let all = S.list_refs repo in let matches = List.filter (fun r -> List.exists (fun pat -> glob_match ~pattern:pat r) patterns) all in let state = state pred in let rec go acc = function | [] -> Ok acc | ref_name :: rest -> ( match ref_of_apply ~state repo pred ~ref_name with | Error (`Msg m) -> Error (`Msg m) | Ok None -> go acc rest | Ok (Some s) -> go (merge_stats acc s) rest) in go empty_stats matches
(* Public aliases. [ref] is exposed last so internal code can still use [Stdlib.ref] for mutable cells. *) let ref = ref_of_apply let refs = ref_of_applys let tree_contains_subtree repo = contains_subtree (store repo) let detached_parents repo = detached (store repo)end