(* 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. *) open Cmdliner let shas_arg = let doc = "Hex SHA-1s (or 4+ char prefixes) of the commits to squash." in Arg.(non_empty & pos_all string [] & info [] ~docv:"SHA" ~doc) let message_arg = let doc = "New commit message. Repeat $(b,-m) to add paragraphs: each value becomes \ its own paragraph, separated by a blank line, as with $(b,git commit). \ Defaults to the originals' messages joined by blank lines in \ ancestor-first order." in Arg.(value & opt_all string [] & info [ "m"; "message" ] ~docv:"MSG" ~doc) let rec partition_shas repo = function | [] -> Ok [] | s :: rest -> ( match Common.parse_sha ~repo s with | Error (`Msg m) -> Error (`Msg m) | Ok h -> ( match partition_shas repo rest with | Ok hs -> Ok (h :: hs) | Error e -> Error e)) let run ~repo_path ~shas ~message ~ref_name () = Common.with_repo repo_path @@ fun repo -> match Common.resolve_target_ref repo ref_name with | Error (`Msg m) -> Common.pp_error Fmt.stderr m; `Error (false, m) | Ok ref_name -> ( match partition_shas repo shas with | Error (`Msg m) -> Common.pp_error Fmt.stderr m; `Error (false, m) | Ok [] -> let m = "no commits given" in Common.pp_error Fmt.stderr m; `Error (false, m) | Ok [ _ ] -> let m = "squash needs at least two commits" in Common.pp_error Fmt.stderr m; `Error (false, m) | Ok commits -> Git_eio.Rewrite.squash_commits repo ~commits ?message ~ref_name () |> Common.report_rewrite_result) let term = Term.( ret (const (fun () repo_path shas messages ref_name -> let message = match messages with | [] -> None | _ -> Some (String.concat "\n\n" messages) in run ~repo_path ~shas ~message ~ref_name ()) $ Common.setup $ Common.repo_path $ shas_arg $ message_arg $ Common.target_ref_arg)) let cmd = let info = Cmd.info "squash" ~doc:"Collapse a contiguous chain of commits into a single commit." ~man: [ `S Manpage.s_description; `P "Replace the commits named by $(b,SHA...) with a single commit on \ $(b,--ref). The squashed commit keeps the newest commit's tree, \ author, and committer; the message defaults to the originals' \ messages joined by blank lines and can be overridden with \ $(b,--message)."; `P "The commits may be given in any order; the tool sorts them \ topologically. When they aren't a parent-child chain, intervening \ commits are replayed onto the squashed tree via an in-memory \ 3-way merge; a merge conflict aborts the squash without touching \ the object database or the ref."; `P "Refuses merge commits and commits not reachable from $(b,--ref)."; `S Manpage.s_examples; `P "Squash the three most recent commits on main:"; `Pre " $(tname) abc1234 def5678 9abcdef"; `P "With a custom message:"; `Pre " $(tname) abc1234 def5678 -m \"feat: merged change\""; ] in Cmd.v info term