(* Copyright (c) 2024-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. *) (** Native git push, functored over a {!Store.S}. [local] copies the reachable object graph between two stores; [negotiate] drives a smart-protocol push over any transport. *) module Hash = Object_hash let src = Logs.Src.create "git.push" ~doc:"Git push operations" module L = (val Logs.src_log src : Logs.LOG) let err_msg fmt = Fmt.kstr (fun s -> Error (`Msg s)) fmt let agent = "nox-git/0" let pack_span = Probe.span "git.push.pack" ~doc:"Prepare missing objects for a push" Probe.Fields.unit module Reader = Bytesrw.Bytes.Reader type pushed = | Up_to_date | Created | Fast_forwarded of Hash.t | Forced of Hash.t type expect = Any | Fast_forward | Lease of Hash.t option type update = { dst_ref : string; value : Hash.t option; expect : expect } type update_error = [ `Msg of string | `Non_fast_forward of string | `Stale of string * Hash.t option ] type remote_update_error = [ update_error | `Declined of string ] type atomic = Independent | Prefer_atomic | Require_atomic type outcome = Unchanged | Updated | Refused of string type failure = [ `Unreachable of string | `Refused of string | `Unknown of string | `Stale of string * Hash.t option ] let failure ~sent = function | (`Unreachable why | `Msg why) when sent -> `Unknown why | `Unreachable why -> `Unreachable why | `Msg why | `Declined why -> `Refused why | `Non_fast_forward r -> `Refused (r ^ " is not a fast-forward") | `Stale (r, held) -> `Stale (r, held) type negotiate_error = [ `Msg of string | `Rejected of string * Hash.t * Hash.t | `Declined of string ] (* Capabilities to request: only those advertised that we can honour. *) let receive_caps (adv : Smart.Message.Advertisement.t) = let caps = List.filter (Smart.Message.Capability.mem adv.capabilities) [ "report-status"; "side-band-64k" ] in if Smart.Message.Capability.mem adv.capabilities "agent" then (caps @ [ "agent=" ^ agent ], List.mem "side-band-64k" caps) else (caps, List.mem "side-band-64k" caps) type deny_action = Refuse | Warn | Ignore | Update_instead (* receive-pack.c, parse_deny_action: a name, ignoring case, else a boolean, [true] for refuse; every value is read, the last one decides. *) let deny_action key = function | None -> Ok Refuse | Some v -> ( match String.lowercase_ascii v with | "ignore" -> Ok Ignore | "warn" -> Ok Warn | "refuse" -> Ok Refuse | "updateinstead" -> Ok Update_instead | _ -> ( match Config.bool_codec.decode v with | Some true -> Ok Refuse | Some false -> Ok Ignore | None -> err_msg "bad value %S for receive.%s" v key)) let deny key cfg = List.fold_left (fun acc (e : Config.entry) -> Result.bind acc (fun _ -> Result.map Option.some (deny_action key e.value))) (Ok None) (Config.entries cfg (Config.section "receive") key) let deny_current_branch cfg = deny "denyCurrentBranch" cfg let deny_delete_current cfg = deny "denyDeleteCurrent" cfg type refusal = [ `Checked_out | `Deletion_denied | `Delete_current | `Not_fast_forward | `Not_commits | `Unstaged | `Staged | `Not_updated of string | `Shallow_update of Hash.t list | `Msg of string ] (* receive-pack.c, update, push_to_deploy and update_shallow_info: the reasons of the [ng] status. *) let refusal_reason = function | `Checked_out -> "branch is currently checked out" | `Deletion_denied -> "deletion prohibited" | `Not_fast_forward -> "non-fast-forward" | `Not_commits -> "bad ref" | `Delete_current -> "deletion of the current branch prohibited" | `Unstaged -> "Working directory has unstaged changes" | `Staged -> "Working directory has staged changes" | `Not_updated _ -> "Could not update working tree to new HEAD" | `Shallow_update _ -> "shallow update not allowed" | `Msg m -> m let pp_refusal ppf r = let reason = refusal_reason r in match r with | `Checked_out -> Fmt.pf ppf "%s: receive.denyCurrentBranch refuses it, unset or refuse; set it to \ updateInstead or ignore to allow the push" reason | `Deletion_denied -> Fmt.pf ppf "%s: receive.denyDeletes refuses the deletion of a branch; set it to \ false to allow it" reason | `Not_fast_forward -> Fmt.pf ppf "%s: receive.denyNonFastForwards refuses a branch update that does not \ descend from the value it replaces, forced or not; set it to false to \ allow it" reason | `Not_commits -> Fmt.pf ppf "%s: receive.denyNonFastForwards compares commits, and the value the \ branch holds or the one it is given is not a commit" reason | `Delete_current -> Fmt.pf ppf "%s: receive.denyDeleteCurrent refuses it, unset or refuse; set it to \ warn or ignore to allow the deletion" reason | `Unstaged -> Fmt.pf ppf "%s: the working tree holds uncommitted changes" reason | `Staged -> Fmt.pf ppf "%s: the index holds uncommitted changes" reason | `Not_updated m -> Fmt.pf ppf "%s: %s" reason m | `Shallow_update cut -> Fmt.pf ppf "%s: the destination lacks the history below %a; receive.shallowUpdate \ refuses to record it as shallow, unset or false; set it to true to \ accept the push" reason Fmt.(list ~sep:comma Hash.pp) cut | `Msg m -> Fmt.string ppf m module type S = sig include Store.S val worktrees : t -> t list val update_instead : t -> base:Hash.t option -> target:Hash.t -> (unit, [ `Unstaged | `Staged | `Msg of string ]) result val check_instead : t -> base:Hash.t option -> target:Hash.t -> (unit, [ `Unstaged | `Staged | `Msg of string ]) result end (* [pack], the pack [pack ~on_written] writes as the transport reads it, reported to [on_progress]: each entry written, and the bytes sent so far. *) let reported ?on_progress pack = match on_progress with | None -> pack ~on_written:ignore | Some f -> let sent = ref 0 in Result.map (Reader.tap (fun s -> if not (Bytesrw.Bytes.Slice.is_eod s) then begin sent := !sent + Bytesrw.Bytes.Slice.length s; f (Progress.Sent !sent) end)) (pack ~on_written:(fun k -> f (Progress.Written k))) module Make (S : S) = struct module Revisions = Rev_list.Make (S) (* The object [ref_or_hex] names in [src], [Ok None] for none, or why a ref it may name cannot be read. *) let resolve_src_hash src ref_or_hex = if String.length ref_or_hex = 40 then Ok (try Some (Hash.of_hex ref_or_hex) with Invalid_argument _ -> None) else let candidates = [ ref_or_hex; "refs/heads/" ^ ref_or_hex; "refs/remotes/origin/" ^ ref_or_hex; "refs/tags/" ^ ref_or_hex; ] in let rec first = function | [] -> Ok None | r :: rest -> ( match S.read_ref src r with | Ok None -> first rest | (Ok (Some _) | Error _) as answer -> answer) in first candidates (* receive-pack.c, receive_pack_config: the boolean [receive.key] of [dst], false when unset; receive.shallowUpdate (update_shallow_info), receive.denyDeletes and receive.denyNonFastForwards are read so. *) let receive_bool dst key = match S.config dst with | Error e -> Error (`Msg (Fmt.to_to_string Config_layers.pp_error e)) | Ok cfg -> ( match Config.bool cfg (Config.section "receive") key with | Error (`Msg m) -> Error (`Msg m) | Ok v -> Ok (Option.value ~default:false v)) let is_branch = String.starts_with ~prefix:"refs/heads/" (* receive-pack.c, update: receive.denyDeletes refuses the deletion of a branch, and no other ref. *) let deny_deletes dst ~dst_ref ~held ~target = match (held, target) with | Some _, None when is_branch dst_ref -> ( match receive_bool dst "denyDeletes" with | Error (`Msg m) -> Error (`Msg m) | Ok false -> Ok () | Ok true -> Error `Deletion_denied) | _ -> Ok () (* receive-pack.c, update: receive.denyNonFastForwards refuses to move a branch to a commit that does not descend from the one it held, whether the push is forced or not; both values must be commits. *) let deny_non_fast_forwards dst ~dst_ref ~held ~target = match (held, target) with | Some held, Some target when is_branch dst_ref -> ( match receive_bool dst "denyNonFastForwards" with | Error (`Msg m) -> Error (`Msg m) | Ok false -> Ok () | Ok true -> ( match (S.read dst held, S.read dst target) with | Ok (Value.Commit _), Ok (Value.Commit _) -> if S.is_ancestor dst ~ancestor:held ~descendant:target then Ok () else Error `Not_fast_forward | _ -> Error `Not_commits)) | _ -> Ok () (* receive-pack.c, update: receive.denyCurrentBranch, for a branch a non-bare worktree has checked out, is whether that working tree follows the branch. *) let deny_checked_out cfg ~dst_ref = match deny_current_branch cfg with | Error (`Msg m) -> Error (`Msg m) | Ok (None | Some Refuse) -> Error `Checked_out | Ok (Some Ignore) -> Ok false | Ok (Some Warn) -> L.warn (fun m -> m "push: updating the current branch %s" dst_ref); Ok false | Ok (Some Update_instead) -> Ok true (* receive-pack.c, update: receive.denyDeleteCurrent, bare or not. *) let deny_delete cfg ~dst_ref = match deny_delete_current cfg with | Error (`Msg m) -> Error (`Msg m) | Ok (None | Some (Refuse | Update_instead)) -> Error `Delete_current | Ok (Some Ignore) -> Ok () | Ok (Some Warn) -> L.warn (fun m -> m "push: deleting the current branch %s" dst_ref); Ok () (* receive-pack.c, update: [find_shared_symref] looks for the branch in every worktree but a bare main one, and [head_name] is the branch the HEAD of [dst] names. Both are read once for every command of a push. [current] is the configuration and the non-bare worktree that has [dst_ref] checked out, for a [dst_ref] that one of them names and that still holds the value it moves from; [None] for any other. *) let receive_with ~update_instead ~published dst = let heads = Option.map (( ^ ) "refs/heads/") in let head = heads (S.current_branch dst) in let checked_out = List.mapi (fun i w -> (heads (S.current_branch w), i = 0, w)) (S.worktrees dst) in let current ~dst_ref ~held ~target = let candidates = List.filter_map (fun (b, main, w) -> if b = Some dst_ref then Some (main, w) else None) checked_out in let unchecked () = match S.read_ref dst dst_ref with | Error (`Msg m) -> Error (`Msg m) | Ok now -> Ok (not (Option.equal Hash.equal now (if published then target else held))) in match if List.is_empty candidates && head <> Some dst_ref then Ok true else unchecked () with | Error (`Msg m) -> Error (`Msg m) | Ok true -> Ok None | Ok false -> ( match S.config dst with | Error e -> Error (`Msg (Fmt.to_to_string Config_layers.pp_error e)) | Ok cfg -> ( match Config.bool cfg (Config.section "core") "bare" with | Error (`Msg m) -> Error (`Msg m) | Ok bare -> let bare = Option.value ~default:false bare in let worktree = List.find_map (fun (main, w) -> if main && bare then None else Some w) candidates in if Option.is_none worktree && head <> Some dst_ref then Ok None else Ok (Some (cfg, worktree)))) in (* The checks run in receive-pack's order: the checked-out branch, the deletion of a branch, the deletion of the current branch, a non-fast-forward, and then the working tree moves. A published update has passed the policy already. *) fun ~dst_ref ~held ~target -> let ( let* ) = Result.bind in let policy check = if published then Ok () else check dst ~dst_ref ~held ~target in let* current = current ~dst_ref ~held ~target in let* instead = match current with | Some (cfg, Some w) -> let* instead = deny_checked_out cfg ~dst_ref in Ok (if instead then Some w else None) | Some (_, None) | None -> Ok None in let* () = policy deny_deletes in let* () = match (current, target) with | Some (cfg, _), None -> deny_delete cfg ~dst_ref | _ -> Ok () in let* () = policy deny_non_fast_forwards in match (instead, target) with | None, _ -> Ok () | Some _, None -> Error (`Not_updated "the branch is deleted") | Some w, Some target -> ( match update_instead w ~base:held ~target with | Ok () -> Ok () | Error ((`Unstaged | `Staged) as e) -> Error e | Error (`Msg m) -> Error (`Not_updated m)) let receive dst = receive_with ~update_instead:S.update_instead ~published:false dst let refusal_msg ~dst_ref r = err_msg "push: refusing to update %s: %a" dst_ref pp_refusal r (* Traverse the source's commit graph from [target] looking for [current] as an ancestor. Confirms a fast-forward push. *) let is_ancestor_of src ~ancestor:current ~tip:target = let seen = Hashtbl.create 64 in let rec walk = function | [] -> false | h :: _ when Hash.equal h current -> true | h :: rest when Hashtbl.mem seen h -> walk rest | h :: rest -> ( Hashtbl.replace seen h (); match S.read src h with | Ok (Value.Commit c) -> walk (Commit.parents c @ rest) | _ -> walk rest) in walk [ target ] (* Git's rule for moving one ref from [held] to [target] (git-push(1), "NOTE ABOUT FAST-FORWARDS"): the move is refused, as [Error held], when [target] does not descend from [held] and [force] is [false]. A [held] that [src] does not have cannot be an ancestor of anything in [src], and is refused without a walk ("fetch first"). *) let classify ~src ~force ~held ~target = match held with | None -> Ok Created | Some held when Hash.equal held target -> Ok Up_to_date | Some held when S.exists src held && is_ancestor_of src ~ancestor:held ~tip:target -> Ok (Fast_forwarded held) | Some held -> if force then Ok (Forced held) else Error held (* The objects of [target]'s history outside [have], down to [src]'s shallow boundary, and the boundary commits among them: those [dst] has to record as shallow, which [receive.shallowUpdate] decides (receive-pack.c, update_shallow_info). The commits and trees of the history are read before the first write, so a source that lacks one of them is refused, naming it, with [dst] untouched. [edge] is told the commits [have] holds that the history names as parents. *) let closure ~counted ~edge ~src ~dst ~have ~dst_ref ~target = let boundary = Hashtbl.create 8 in List.iter (fun h -> Hashtbl.replace boundary h ()) (S.read_shallow src); let shallow = Hashtbl.mem boundary in match Fetch.reachable_named ~shallow ~edge ~counted ~read:(S.read src) ~exists:(Hashtbl.mem have) target with | exception Fetch.Unreadable_object (h, reason) -> err_msg "the history of %a cannot be sent: object %a cannot be read (%s)" Hash.pp target Hash.pp h reason | objects -> ( List.iter (fun (o : Store.pack_object) -> Hashtbl.replace have o.hash ()) objects; match List.filter_map (fun (o : Store.pack_object) -> if shallow o.hash then Some o.hash else None) objects with | [] -> Ok (objects, []) | cut -> ( match receive_bool dst "shallowUpdate" with | Error (`Msg _) as e -> e | Ok true -> Ok (objects, cut) | Ok false -> refusal_msg ~dst_ref (`Shallow_update cut))) (* receive-pack.c, cmd_receive_pack: the count of objects under which a push is written loose rather than kept as a pack, receive.unpackLimit, else transfer.unpackLimit, else 100; a negative value is unset. *) let unpack_limit dst = match S.config dst with | Error e -> Error (`Msg (Fmt.to_to_string Config_layers.pp_error e)) | Ok cfg -> ( let limit section = match Config.int cfg (Config.section section) "unpackLimit" with | Ok (Some n) when n >= 0 -> Ok (Some n) | Ok _ -> Ok None | Error (`Msg m) -> Error (`Msg m) in match limit "receive" with | Error _ as e -> e | Ok (Some n) -> Ok n | Ok None -> Result.map (Option.value ~default:100) (limit "transfer")) (* unpack-objects: each of [objects] written loose, an object [src] cannot read refusing the push; [on_progress] is told each one written. *) let unpack ~on_progress ~src ~dst objects = let rec go written = function | [] -> Ok () | ({ hash = h; _ } : Store.pack_object) :: rest -> ( match S.read src h with | Error (`Msg m) -> err_msg "push: object %a cannot be read (%s)" Hash.pp h m | Ok value -> let _ : Hash.t = S.write dst value in on_progress (Progress.Written (written + 1)); go (written + 1) rest) in go 0 objects (* index-pack --fix-thin: [objects] kept in [dst] as one pack, written as [src] packs them, thin against the objects at their paths in [edges], in writes of 64 KiB, not one per entry; an object [src] cannot read refuses the push and leaves no pack. *) let keep ~on_progress ~edges ~src ~dst objects = let on_written k = on_progress (Progress.Written k) in let bases = Fetch.preferred_bases ~read:(S.read src) ~edges objects in let write ~writer = match S.pack_objects ~bases ~on_written src objects with | Error _ as e -> e | Ok pack -> ( let pack = Bytesrw.Bytes.Reader.reslice ~slice_length:65536 pack in try Ok (Bytesrw.Bytes.Writer.write_reader ~eod:false writer pack) with Bytesrw.Bytes.Stream.Error e -> Error (`Msg (Bytesrw.Bytes.Stream.error_message e))) in match S.stream_pack dst write with | Ok ((), _) -> Ok () | Error (`Msg m) -> Error (`Msg m) (* receive-pack.c, unpack: the objects a push sends are kept as one pack when they are at least [dst]'s unpack limit, and written loose otherwise. *) let send_objects ?(on_progress = ignore) ~edges ~src ~dst objects = match unpack_limit dst with | Error _ as e -> e | Ok limit -> L.debug (fun m -> m "local push: sending %d objects" (List.length objects)); if List.length objects < limit then unpack ~on_progress ~src ~dst objects else keep ~on_progress ~edges ~src ~dst objects (* receive-pack.c, update_shallow_ref: the commits a push cut at join the destination's boundary. *) let record_shallow dst = function | [] -> () | cut -> S.write_shallow dst (S.read_shallow dst @ cut) (* The objects a remote whose refs hold [tips] has, as far as a push of [targets] reads them (revision.c, mark_trees_uninteresting_sparse, git's pack.useSparse): each tip [src] holds, and of the trees of the tips only the objects at the paths where the trees the push sends differ from them. A path whose tree is the same on both sides is had whole and is not read, so a push reads its change and not the remote's store. The tips are traversal boundaries: their histories are not enumerated, so an object of an older snapshot, or one at another path, may be sent again, which is safe and avoids reading history to save it. *) let tips_have src tips ~targets = let ( let* ) = Result.bind in let read = S.read src in let have = Hashtbl.create 1024 in let had h = Hashtbl.replace have h () in let rec tip_trees acc = function | [] -> Ok acc | h :: rest when Hashtbl.mem have h || not (S.exists src h) -> tip_trees acc rest | h :: rest -> ( match read h with | Error (`Msg m) -> Error (`Msg m) | Ok value when not (Hash.equal (Value.digest value) h) -> err_msg "push: object hash mismatch: %a" Hash.pp h | Ok (Value.Commit c) -> had h; tip_trees (Commit.tree c :: acc) rest | Ok (Value.Tag t) -> had h; tip_trees acc (Tag.obj t :: rest) | Ok (Value.Tree _) -> tip_trees (h :: acc) rest | Ok (Value.Blob _) -> had h; tip_trees acc rest) in (* The root trees of the commits the push sends, down to the tips and to [src]'s shallow boundary; what cannot be read is left to the closure, which refuses it. *) let shallow = S.read_shallow src in let seen = Hashtbl.create 64 in let rec sent_trees acc = function | [] -> acc | h :: rest when Hashtbl.mem have h || Hashtbl.mem seen h -> sent_trees acc rest | h :: rest -> ( Hashtbl.replace seen h (); match read h with | Ok (Value.Commit c) -> let parents = if List.exists (Hash.equal h) shallow then [] else Commit.parents c in sent_trees (Commit.tree c :: acc) (parents @ rest) | Ok (Value.Tag t) -> sent_trees acc (Tag.obj t :: rest) | Ok (Value.Tree _) -> sent_trees (h :: acc) rest | Ok (Value.Blob _) | Error _ -> sent_trees acc rest) in let tree h = match read h with Ok (Value.Tree t) -> Some t | _ -> None in (* [had_trees] and [sent] are the trees at one path: the remote has the first, and of the second those it lacks are read with them. Where it has none, there is nothing to mark and nothing is read. *) let rec sparse ~had_trees sent = let had_trees = List.sort_uniq Hash.compare had_trees in let sent = List.sort_uniq Hash.compare sent in List.iter had had_trees; match (had_trees, List.filter (fun h -> not (Hashtbl.mem have h)) sent) with | [], _ | _, [] -> () | _, sent -> let paths = Hashtbl.create 16 in let at name = Option.value ~default:([], []) (Hashtbl.find_opt paths name) in let side f trees = List.iter (fun h -> Option.iter (Tree.iter f) (tree h)) trees in side (fun (e : Tree.entry) -> match e.perm with | `Commit -> () | `Dir -> let o, n = at e.name in Hashtbl.replace paths e.name (e.hash :: o, n) | `Normal | `Everybody | `Exec | `Link -> had e.hash) had_trees; side (fun (e : Tree.entry) -> if e.perm = `Dir then let o, n = at e.name in Hashtbl.replace paths e.name (o, e.hash :: n)) sent; Hashtbl.iter (fun _ (o, n) -> if n <> [] then sparse ~had_trees:o n else List.iter had o) paths in let* had_trees = tip_trees [] tips in if had_trees <> [] then sparse ~had_trees (sent_trees [] targets); Ok have let remote_have src (adv : Smart.Message.Advertisement.t) targets = let ( let* ) = Result.bind in let tips = List.map (fun (r : Smart.Message.ref_entry) -> r.hash) adv.refs in let shallow = S.read_shallow src @ adv.shallows in let* edge = Revisions.boundary src ~shallow ~bases:tips targets in tips_have src ~targets (tips @ edge) (* What [dst] advertises: the values of its refs. *) let dst_tips dst = let rec go acc = function | [] -> Ok acc | name :: rest -> ( match S.read_ref dst name with | Error (`Msg m) -> Error (`Msg m) | Ok None -> go acc rest | Ok (Some h) -> go (h :: acc) rest) in go [] (S.list_refs dst) (* git pack-objects: the objects reachable from [targets] in [src] that the remote does not already have are enumerated first, reading commits and trees only; their pack is then written as the transport reads it, thin unless the remote advertises no-thin (send-pack.c): against the objects at their paths in the commits the remote holds at the edge of the push ({!Fetch.preferred_bases}). What the remote can make this spend is bounded by [src]: an advertised tip it holds marks its tree and the common boundary with the push. The writer holds a few words per object sent with the delta window, never the pack. *) let pack_missing_all ?on_progress src adv targets = Probe.with_span pack_span () @@ fun () -> let ( let* ) = Result.bind in let* have = remote_have src adv targets in let edges = ref [] in let edge h = edges := h :: !edges in let counted = Option.fold ~none:ignore ~some:Progress.counter on_progress in let to_send = List.concat_map (fun target -> let objects = Fetch.reachable_named ~edge ~counted ~read:(S.read src) ~exists:(Hashtbl.mem have) target in List.iter (fun (o : Store.pack_object) -> Hashtbl.replace have o.hash ()) objects; objects) targets in let bases = if Smart.Message.Capability.mem adv.capabilities "no-thin" then [] else Fetch.preferred_bases ~read:(S.read src) ~edges:(List.rev !edges) to_send in reported ?on_progress (fun ~on_written -> S.pack_objects ~bases ~on_written src to_send) (* [send body], where a pack that cannot be written as it is read ends the request with the reason. *) let sent send body = try send body with Bytesrw.Bytes.Stream.Error e -> Error (`Msg (Bytesrw.Bytes.Stream.error_message e)) let pack_missing ?on_progress src adv target = pack_missing_all ?on_progress src adv [ target ] (* The report-status of [resp], the remote's band-2 text given to [on_progress] as lines. *) let read_status ?on_progress client resp = match on_progress with | None -> Smart.Client.Push.read_status client resp | Some f -> let lines = Progress.lines f in let status = Smart.Client.Push.read_status ~progress:(Progress.feed lines) client resp in Progress.flush lines; status (* The advertised value of [ref_name]: an empty repository advertises its capabilities on a zero id, which names no ref. *) let advertised adv ref_name = match Smart.Message.Advertisement.find_ref adv ref_name with | Some h when Hash.equal h Hash.null -> None | v -> v (* The remote's answer to a push, [status] its report-status or why it could not be read: a report read whole that refuses is the remote's refusal, [`Declined]; one that cannot be read leaves the answer unknown, [`Msg]. *) let answer status ok = match status with | Error (`Msg m) -> Error (`Msg m) | Ok status -> ( match Smart.Message.Status.to_result status with | Ok () -> Ok ok | Error (`Msg why) -> Error (`Declined why)) (* The command that moves [dst_ref] from [held] to [target], with the pack of the objects the remote lacks, handed to [send]; then the report-status. *) let send_one ?on_progress ~client ~adv ~src ~send ~dst_ref ~held target = let ( let* ) = Result.bind in answer (let* pack = pack_missing ?on_progress src adv target in let caps, _ = receive_caps adv in let command = match held with | None -> Smart.Message.Command.Create (target, dst_ref) | Some old -> Smart.Message.Command.Update (old, target, dst_ref) in let commands = Smart.Message.Commands.v ~capabilities:caps [ command ] in let* client, body = Smart.Client.Push.request client ~pack commands in let* resp = sent send body in let* _client, status = read_status ?on_progress client resp in Ok status) () (* The transport-independent push driver: decide against the advertised value of [dst_ref], then send the command and the pack, a flush-pkt when there is nothing to send, and nothing when the push is refused. *) let negotiate ?on_progress ~client ~adv ~src ~src_hash ~dst_ref ~force ~send () = match resolve_src_hash src src_hash with | Error (`Msg m) -> Error (`Msg m) | Ok None -> err_msg "push: source ref/hash not found: %s" src_hash | Ok (Some target) -> ( let held = advertised adv dst_ref in match classify ~src ~force ~held ~target with | Error held -> Error (`Rejected (dst_ref, held, target)) | Ok Up_to_date -> ( match send (Reader.of_string Smart.Packet.(to_string Flush)) with | Ok _ -> Ok (target, Up_to_date) | Error (`Msg _) as e -> e) | Ok pushed -> Result.map (fun () -> (target, pushed)) (send_one ?on_progress ~client ~adv ~src ~send ~dst_ref ~held target)) (* {1 Ref updates} *) let same_value a b = Option.equal Hash.equal a b (* Whether [u] may move its ref from [held], the value it holds now. *) let expectation ~src u held = match (u.expect, held, u.value) with | Any, _, _ -> Ok () | Lease expected, _, _ -> if same_value expected held then Ok () else Error (`Stale (u.dst_ref, held)) | Fast_forward, None, Some _ -> Ok () | Fast_forward, Some held, Some value when is_ancestor_of src ~ancestor:held ~tip:value -> Ok () | Fast_forward, _, _ -> Error (`Non_fast_forward u.dst_ref) (* The updates of [updates] that change their ref, each with the value [current] reads for it, once every one is checked against its expectation. *) let prepare_updates ?(keep_unchanged = false) ~src ~current updates = let seen = Hashtbl.create 16 in let rec go acc = function | [] -> Ok (List.rev acc) | u :: _ when Hashtbl.mem seen u.dst_ref -> err_msg "push: %s is updated twice" u.dst_ref | u :: rest -> ( Hashtbl.replace seen u.dst_ref (); match current u.dst_ref with | Error (`Msg m) -> Error (`Msg m) | Ok held -> ( match expectation ~src u held with | Error _ as e -> e | Ok () when (not keep_unchanged) && same_value held u.value -> go acc rest | Ok () -> go ((u, held) :: acc) rest)) in go [] updates (* git send-pack to receive-pack: the objects to send are named from the refs [dst] advertises, reading [src] alone, and arrive as {!send_objects} decides. *) let transfer_updates ?on_progress ~src ~dst changes = let ( let* ) = Result.bind in let* tips = dst_tips dst in let targets = List.filter_map (fun ((u : update), _) -> u.value) changes in let* have = tips_have src tips ~targets in let edges = ref [] in let edge h = edges := h :: !edges in let counted = Option.fold ~none:ignore ~some:Progress.counter on_progress in let rec plan acc = function | [] -> Ok (List.rev acc) | ({ value = None; _ }, _) :: rest -> plan acc rest | ({ dst_ref; value = Some target; _ }, _) :: rest -> ( match closure ~counted ~edge ~src ~dst ~have ~dst_ref ~target with | Ok closure -> plan (closure :: acc) rest | Error (`Msg _) as e -> e) in let* closures = plan [] changes in let objects = List.concat_map fst closures in match objects with | [] -> Ok () | objects -> let* () = send_objects ?on_progress ~edges:(List.rev !edges) ~src ~dst objects in record_shallow dst (List.concat_map snd closures); Ok () let receive_updates_with ~update_instead ~published dst changes = let receive = receive_with ~update_instead ~published dst in let rec go = function | [] -> Ok () | (u, held) :: rest when same_value held u.value -> go rest | (u, held) :: rest -> ( match receive ~dst_ref:u.dst_ref ~held ~target:u.value with | Ok () -> go rest | Error r -> refusal_msg ~dst_ref:u.dst_ref r) in go changes let receive_updates dst changes = receive_updates_with ~update_instead:S.update_instead ~published:false dst changes let check_updates dst changes = receive_updates_with ~update_instead:S.check_instead ~published:false dst changes let apply_updates dst changes = receive_updates_with ~update_instead:S.update_instead ~published:true dst changes let publish_updates ?context dst changes = let ( let* ) = Result.bind in let* () = check_updates dst changes in let refs = List.map (fun (u, expected) -> { Store.name = u.dst_ref; expected; target = u.value }) changes in let* () = match S.update_refs ?context dst refs with | Ok () -> Ok () | Error (`Raced name | `Locked name) -> ( match S.read_ref dst name with | Ok held -> Error (`Stale (name, held)) | Error (`Msg m) -> Error (`Msg m)) | Error (`Msg reason | `Hook_rejected reason | `Partial (_, reason)) -> Error (`Msg reason) in apply_updates dst changes let local_updates ?context ?on_progress ~src ~dst updates = let ( let* ) = Result.bind in let* changes = prepare_updates ~keep_unchanged:true ~src ~current:(S.read_ref dst) updates in let* () = transfer_updates ?on_progress ~src ~dst changes in let* () = publish_updates ?context dst changes in let changes = List.filter (fun (u, held) -> not (same_value held u.value)) changes in Ok (List.map (fun (u, _) -> u.dst_ref) changes) let local ?context ?on_progress ~src ~dst ~src_hash ~dst_ref ~force () = match resolve_src_hash src src_hash with | Error (`Msg m) -> Error (`Msg m) | Ok None -> err_msg "local push: source ref/hash not found: %s" src_hash | Ok (Some target) -> ( match S.read_ref dst dst_ref with | Error (`Msg m) -> Error (`Msg m) | Ok held -> ( match classify ~src ~force ~held ~target with | Error _ -> Error (`Non_fast_forward dst_ref) | Ok Up_to_date -> L.debug (fun m -> m "local push: %s already at %s" dst_ref (Hash.to_hex target)); Ok (target, Up_to_date) | Ok pushed -> L.info (fun m -> m "local push: %s -> %s" (Hash.to_hex target) dst_ref); let update = { dst_ref; value = Some target; expect = Lease held } in let changes = [ (update, held) ] in let ( let* ) = Result.bind in let* () = transfer_updates ?on_progress ~src ~dst changes in let* () = match publish_updates ?context dst changes with | Ok () -> Ok () | Error (`Stale (name, _)) -> err_msg "local push: %s changed before publication" name | Error (`Msg reason | `Non_fast_forward reason) -> Error (`Msg reason) in Ok (target, pushed))) let command (u, held) = match (held, u.value) with | None, Some v -> Smart.Message.Command.Create (v, u.dst_ref) | Some old, Some v -> Smart.Message.Command.Update (old, v, u.dst_ref) | Some old, None -> Smart.Message.Command.Delete (old, u.dst_ref) | None, None -> invalid_arg "Push.command: an unchanged update" let update_caps ~atomic adv changes = let caps, _ = receive_caps adv in let mem = Smart.Message.Capability.mem adv.capabilities in let deletes = List.exists (fun (u, _) -> u.value = None) changes in if deletes && not (mem "delete-refs") then err_msg "push: the remote does not accept deletes (no delete-refs)" else Ok (caps @ (if deletes then [ "delete-refs" ] else []) @ if atomic then [ "atomic" ] else []) let receipt ~atomic changes (status : Smart.Message.Status.t) = match status.unpack with | Error why -> Error (`Declined why) | Ok () -> let expected = Hashtbl.create (List.length changes) in List.iter (fun (u, _) -> Hashtbl.add expected u.dst_ref None) changes; let rec read = function | [] -> if Hashtbl.fold (fun _ v missing -> missing || v = None) expected false then err_msg "push: report-status omitted a requested ref" else let outcomes = List.map (fun (u, _) -> match Hashtbl.find expected u.dst_ref with | Some v -> (u.dst_ref, v) | None -> assert false) changes in if atomic && List.exists (fun (_, v) -> v = Updated) outcomes && List.exists (function _, Refused _ -> true | _ -> false) outcomes then err_msg "push: contradictory atomic report-status" else Ok outcomes | command :: rest -> ( let name, outcome = match command with | Smart.Message.Status.Updated r -> (r, Updated) | Rejected (r, why) -> (r, Refused why) in match Hashtbl.find_opt expected name with | None -> err_msg "push: report-status named an unrequested ref" | Some (Some _) -> err_msg "push: report-status repeated a ref" | Some None -> Hashtbl.replace expected name (Some outcome); read rest) in read status.commands let send_updates ?on_progress ~atomic ~client ~(adv : Smart.Message.Advertisement.t) ~src ~send changes = let ( let* ) = Result.bind in match changes with | [] -> ( match send (Reader.of_string Smart.Packet.(to_string Flush)) with | Ok _ -> Ok [] | Error (`Msg m) -> Error (`Msg m)) | _ -> ( if not (Smart.Message.Capability.mem adv.capabilities "report-status") then err_msg "push: report-status required but not advertised" else let response = let* caps = update_caps ~atomic adv changes in let* pack = match List.filter_map (fun (u, _) -> u.value) changes with | [] -> Ok (Reader.empty ()) | targets -> pack_missing_all ?on_progress src adv targets in let commands = Smart.Message.Commands.v ~capabilities:caps (List.map command changes) in let* client, body = Smart.Client.Push.request client ~pack commands in let* resp = sent send body in let* _client, status = read_status ?on_progress client resp in Ok status in match response with | Error (`Msg why) -> Error (`Msg why) | Ok status -> receipt ~atomic changes status) let negotiate_report ?(atomic = Independent) ?on_progress ~client ~adv ~src ~send updates = let require_atomic = atomic = Require_atomic in let use_atomic = atomic <> Independent && Smart.Message.Capability.mem adv.Smart.Message.Advertisement.capabilities "atomic" in if require_atomic && not (Smart.Message.Capability.mem adv.Smart.Message.Advertisement.capabilities "atomic") then err_msg "push: atomic publication required but not advertised" else match prepare_updates ~keep_unchanged:require_atomic ~src ~current:(fun r -> Ok (advertised adv r)) updates with | Error e -> Error (e :> remote_update_error) | Ok changes when List.exists (fun (u, held) -> u.value = None && held = None) changes -> err_msg "push: absent unchanged guard has no Git wire command" | Ok changes -> let ( let* ) = Result.bind in let* outcomes = (send_updates ?on_progress ~atomic:use_atomic ~client ~adv ~src ~send changes :> ((string * outcome) list, remote_update_error) result) in let outcomes = Hashtbl.of_seq (List.to_seq outcomes) in Ok (List.map (fun u -> ( u.dst_ref, Option.value ~default:Unchanged (Hashtbl.find_opt outcomes u.dst_ref) )) updates) let negotiate_updates ?(require_atomic = false) ?on_progress ~client ~adv ~src ~send updates = let atomic = if require_atomic then Require_atomic else Prefer_atomic in match negotiate_report ~atomic ?on_progress ~client ~adv ~src ~send updates with | Error (`Declined why) -> Error (`Declined ("unpack failed: " ^ why)) | Error _ as e -> e | Ok outcomes -> let rec collect updated = function | [] -> Ok (List.rev updated) | (_, Unchanged) :: rest -> collect updated rest | (name, Updated) :: rest -> collect (name :: updated) rest | (name, Refused why) :: _ -> Error (`Declined (Fmt.str "ref %s rejected: %s" name why)) in collect [] outcomes end