(* 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 message_arg = let doc = "Commit message. Repeat $(b,-m) to add paragraphs: each value becomes its \ own paragraph, separated by a blank line, as with $(b,git commit)." in Arg.(value & opt_all string [] & info [ "m"; "message" ] ~docv:"MSG" ~doc) let paths_arg = let doc = "File, directory, or source address to commit. May be repeated. A \ directory commits every change under it; a path missing from the working \ tree commits as a deletion. A source address has the form \ $(b,file.ml:Module.value) and commits only that definition." in Arg.(value & pos_all string [] & info [] ~docv:"PATH" ~doc) let dry_run_arg = let doc = "List the changes that would be committed, without committing." in Arg.(value & flag & info [ "n"; "dry-run" ] ~doc) let no_verify_arg = let doc = "Bypass the pre-commit and commit-msg hooks (the repository hooks and any \ $(b,gitx.hook.pre-commit) / $(b,gitx.hook.commit-msg) commands)." in Arg.(value & flag & info [ "no-verify" ] ~doc) let hook_dir_arg = let doc = "Scope the pre-commit hook to $(docv), a subdirectory of the work tree. \ The hook still runs at the work-tree root, but $(docv) reaches it as its \ first argument and as the $(b,GIT_X_HOOK_DIR) environment variable, so a \ formatter or linter the hook invokes can confine itself to that subtree \ (for example $(b,merlint \"\\$GIT_X_HOOK_DIR\") or $(b,dune build \ @\"\\$GIT_X_HOOK_DIR\"/fmt)). Unrelated changes elsewhere in the tree \ then cannot make the hook reject the commit. Without this option, git-x \ infers the scope when every selected path belongs to one top-level Dune \ package; root-level and mixed-package changes use the whole tree. $(docv) \ must be an existing directory within the work tree. The commit-msg hook \ is unaffected: it operates on the message, not a subtree." in let env = Cmd.Env.info "GIT_X_HOOK_DIR" in Arg.( value & opt (some string) None & info [ "hook-dir" ] ~docv:"DIR" ~env ~doc) let pp_change ppf (c : Git_eio.Repository.change) = let letter = match c.kind with Modified -> 'M' | Deleted -> 'D' | Untracked -> 'A' in Fmt.pf ppf " %c %s@." letter c.path let is_address_spec s = match Git_outline.Address.(qualifier (of_string s)) with | [] -> false | _ -> true let split_specs specs = List.partition is_address_spec specs let package_for_selected_path repo path = let path = if String.starts_with ~prefix:"./" path then String.sub path 2 (String.length path - 2) else path in let path = let n = String.length path in if n > 0 && path.[n - 1] = '/' then String.sub path 0 (n - 1) else path in let components = String.split_on_char '/' path in match components with | [] | "" :: _ | "." :: _ | ".." :: _ -> None | _ when List.mem "." components || List.mem ".." components -> None | top :: _ -> let fs = Git_eio.Repository.fs repo in let work_dir = Git_eio.Repository.work_dir repo in let package_dir = Eio.Path.(fs / work_dir / top) in let dune_project = Eio.Path.(package_dir / "dune-project") in if Eio.Path.is_directory package_dir && Eio.Path.is_file dune_project then Some top else None let inferred_hook_dir repo paths = match paths with | [] -> None | path :: rest -> ( match package_for_selected_path repo path with | None -> None | Some package -> if List.for_all (fun path -> package_for_selected_path repo path = Some package) rest then Some package else None) let line_chunks s = let len = String.length s in let rec loop start i acc = if i = len then let acc = if start < len then String.sub s start (len - start) :: acc else acc in Array.of_list (List.rev acc) else if s.[i] = '\n' then let chunk = String.sub s start (i - start + 1) in loop (i + 1) (i + 1) (chunk :: acc) else loop start (i + 1) acc in loop 0 0 [] let add_range buf lines start_line end_line = let n = Array.length lines in let first = max 1 start_line in let last = min n end_line in for i = first to last do Buffer.add_string buf lines.(i - 1) done let patch_ranges base ranges = let base_lines = line_chunks base in let buf = Buffer.create (String.length base) in let next = ref 1 in List.iter (fun (old_range, new_source, new_range) -> add_range buf base_lines !next (old_range.Git_outline.start_line - 1); add_range buf (line_chunks new_source) new_range.Git_outline.start_line new_range.end_line; next := old_range.end_line + 1) ranges; add_range buf base_lines !next (Array.length base_lines); Buffer.contents buf let ensure_non_overlapping path ranges = let rec loop prev_end = function | [] -> Ok () | (range, _, _) :: rest -> if range.Git_outline.start_line <= prev_end then Fmt.error_msg "overlapping address ranges in %s" path else loop range.end_line rest in loop 0 ranges let perm_of_worktree repo path = let full = Eio.Path.( Git_eio.Repository.fs repo / Git_eio.Repository.work_dir repo / path) in match Eio.Path.stat ~follow:false full with | stat when stat.perm land 0o111 <> 0 -> `Exec | _ -> `Normal | exception Eio.Io _ -> `Normal let address_overlay repo addr = let path = Git_outline.Address.path addr in match ( Git_eio.Repository.read_head_file repo ~path, Git_eio.Repository.read_worktree_file repo ~path ) with | None, _ -> Fmt.error_msg "address %a: file is not tracked in HEAD" Git_outline.Address.pp addr | _, None -> Fmt.error_msg "address %a: file is not a regular worktree file" Git_outline.Address.pp addr | Some base, Some work -> ( let base_outline = Git_outline.outline ~path base in let work_outline = Git_outline.outline ~path work in match ( Git_outline.resolve base_outline addr, Git_outline.resolve work_outline addr ) with | None, _ -> Fmt.error_msg "address %a: not found in HEAD" Git_outline.Address.pp addr | _, None -> Fmt.error_msg "address %a: not found in worktree" Git_outline.Address.pp addr | Some old_range, Some new_range -> Ok (path, base, (old_range, work, new_range))) let overlays_of_addresses repo specs = let open Result.Syntax in let add_one acc spec = let addr = Git_outline.Address.of_string spec in match address_overlay repo addr with | Error _ as e -> e | Ok (path, base, range) -> let prev = Option.value ~default:(base, []) (List.assoc_opt path acc) in let acc = List.remove_assoc path acc in Ok ((path, (base, range :: snd prev)) :: acc) in let* grouped = List.fold_left (fun acc spec -> let* acc = acc in add_one acc spec) (Ok []) specs in grouped |> List.map (fun (path, (base, ranges)) -> let ranges = List.sort (fun (a, _, _) (b, _, _) -> compare a.Git_outline.start_line b.Git_outline.start_line) ranges in let* () = ensure_non_overlapping path ranges in Ok Git_eio.Repository. { path; content = patch_ranges base ranges; perm = perm_of_worktree repo path; }) |> List.fold_left (fun acc item -> let* acc = acc in let* item = item in Ok (item :: acc)) (Ok []) let overlays_of_paths repo changes = changes |> List.map (fun (change : Git_eio.Repository.change) -> match change.kind with | Deleted -> Fmt.error_msg "cannot combine outline addresses with deleted path %s" change.path | Modified | Untracked -> ( match Git_eio.Repository.read_worktree_file repo ~path:change.path with | Some content -> Ok Git_eio.Repository. { path = change.path; content; perm = perm_of_worktree repo change.path; } | None -> Fmt.error_msg "cannot read regular file %s" change.path)) |> List.fold_left (fun acc item -> let open Result.Syntax in let* acc = acc in let* item = item in Ok (item :: acc)) (Ok []) let first_line s = match String.index_opt s '\n' with None -> s | Some i -> String.sub s 0 i let run_dry_run repo paths = let address_specs, path_specs = split_specs paths in let path_changes = Result.map_error (fun (`Msg e) -> e) (Git_eio.Repository.changes_under repo ~paths:path_specs) in let address_changes = match overlays_of_addresses repo address_specs with | Error (`Msg e) -> Error e | Ok overlays -> Ok (List.map (fun (o : Git_eio.Repository.content_overlay) -> { Git_eio.Repository.kind = Modified; path = o.path }) overlays) in match (path_changes, address_changes) with | Error e, _ | _, Error e -> Common.cmd_error e | Ok path_changes, Ok address_changes -> ( match path_changes @ address_changes with | [] -> Fmt.pr "nothing to commit under: %s@." (String.concat " " paths); `Ok () | changed -> Fmt.pr "Would commit:@."; List.iter (Fmt.pr "%a" pp_change) changed; `Ok ()) (* Bring the index in line with the new HEAD for exactly the committed paths. Best-effort: the commit already landed via the object database and a ref CAS. *) let refresh_index repo (changed : Git_eio.Repository.change list) = let added = List.filter_map (fun (c : Git_eio.Repository.change) -> match c.kind with | Modified | Untracked -> Some c.path | Deleted -> None) changed in (if added <> [] then match Git_eio.Repository.add_to_index repo added with _ -> ()); List.iter (fun (c : Git_eio.Repository.change) -> match c.kind with | Deleted -> ( match Git_eio.Repository.remove_from_index repo c.path with _ -> ()) | Modified | Untracked -> ()) changed let refresh_index_to_head repo paths = match Git_eio.Repository.add_head_to_index repo paths with _ -> () type refresh_plan = | Worktree | Mixed of { address_paths : string list; path_changes : Git_eio.Repository.change list; } let commit_address_specs repo ~author ~committer ~message ~address_specs ~path_specs = match overlays_of_addresses repo address_specs with | Error e -> (Error e, Worktree) | Ok address_overlays -> ( match Result.bind (Git_eio.Repository.changes_under repo ~paths:path_specs) (fun path_changes -> Result.map (fun overlays -> (path_changes, overlays)) (overlays_of_paths repo path_changes)) with | Error e -> (Error e, Worktree) | Ok (path_changes, path_overlays) -> let overlays = List.rev_append address_overlays path_overlays in let refresh = Mixed { address_paths = List.map (fun (o : Git_eio.Repository.content_overlay) -> o.path) address_overlays; path_changes; } in ( Git_eio.Repository.commit_overlays repo ~author ~committer ~message ~overlays, refresh )) let commit_specs repo ~author ~committer ~message ~paths ~address_specs ~path_specs = match address_specs with | [] -> ( Git_eio.Repository.commit_paths repo ~author ~committer ~message ~paths, Worktree ) | _ :: _ -> commit_address_specs repo ~author ~committer ~message ~address_specs ~path_specs (* Config-defined hooks (gitx.hook.commit-msg) run after the repository hook, each as a shell command with the message file path appended. *) let config_hooks repo name = match Git_eio.Repository.config repo with | Error e -> Fmt.failwith "%a" Git.Config_layers.pp_error e | Ok cfg -> Git.Config.all cfg (Git.Config.section_sub "gitx" "hook") name (* githooks(5) pre-commit semantics: a non-zero exit aborts the commit. git-x commits named working-tree paths rather than the index, so the hook runs in the work tree before those paths are read into the commit. *) (* Validate [hook_dir]: an existing directory within the work tree. *) let validate_hook_dir repo hook_dir = match hook_dir with | None -> Ok None | Some sub -> ( let fs = Git_eio.Repository.fs repo in let root = Eio.Path.(fs / Git_eio.Repository.work_dir repo) in let full = Eio.Path.(root / sub) in match Eio.Path.is_directory full with | true -> Ok (Some sub) | false | (exception Eio.Io _) -> Fmt.error "hook directory %S is not a directory in the work tree" sub) (* The current environment with [GIT_X_HOOK_DIR] set to the scoped subtree. *) let hook_env = function | None -> None | Some dir -> let keep v = not (String.starts_with ~prefix:"GIT_X_HOOK_DIR=" v) in let base = List.filter keep (Array.to_list (Unix.environment ())) in Some (Array.of_list (("GIT_X_HOOK_DIR=" ^ dir) :: base)) let run_pre_commit_hooks ~proc ?hook_dir repo = let std = Git_eio.Repository.hook repo "pre-commit" in match (std, config_hooks repo "pre-commit") with | None, [] -> Ok () | std, cfg -> ( match validate_hook_dir repo hook_dir with | Error _ as e -> e | Ok dir -> let fs = Git_eio.Repository.fs repo in let cwd = Eio.Path.(fs / Git_eio.Repository.work_dir repo) in let env = hook_env dir in (* [hook] returns the executable relative to the work-tree root. *) let abs h = Fpath.(to_string (append (v (Sys.getcwd ())) h)) in let arg = match dir with Some d -> [ d ] | None -> [] in let cmds = (match std with Some h -> [ abs h :: arg ] | None -> []) @ List.map (fun c -> [ "/bin/sh"; "-c"; c; "sh" ] @ arg) cfg in let rejected = List.exists (fun args -> match Eio.Process.run proc ~cwd ?env args with | () -> false | exception Eio.Io _ -> true) cmds in if rejected then Error "pre-commit hook rejected the commit" else Ok ()) (* The hook protocol hands the message over as a file, which is newline terminated; the commit object stores it without that trailing newline. *) let with_trailing_newline s = if s <> "" && s.[String.length s - 1] = '\n' then s else s ^ "\n" let without_trailing_newline s = let n = String.length s in if n > 0 && s.[n - 1] = '\n' then String.sub s 0 (n - 1) else s (* The command a hook was configured as, for a diagnostic. Not the argument vector, whose temp message file name carries the pid. *) let commit_msg_command = function | [ "/bin/sh"; "-c"; _wrapper; cfg; _msgfile ] -> cfg | prog :: _ -> prog | [] -> "commit-msg" (* A non-zero exit is the hook rejecting the message, not a fault. *) let commit_msg_rejects ~proc ~cwd args = match Eio.Process.run proc ~cwd args with | () -> false | exception Eio.Io (Eio.Process.E (Eio.Process.Child_error (`Exited _)), _) -> true | exception (Eio.Io _ as ex) -> Fmt.epr "error: commit-msg hook %s could not run: %a@." (commit_msg_command args) Eio.Exn.pp ex; true let run_commit_msg_hooks ~proc repo message = let std = Git_eio.Repository.hook repo "commit-msg" in match (std, config_hooks repo "commit-msg") with | None, [] -> Ok message | std, cfg -> let fs = Git_eio.Repository.fs repo in let file = Eio.Path.( fs / Fpath.to_string (Git_eio.Repository.git_dir repo) / Fmt.str "gitx-commit-msg-%d" (Unix.getpid ())) in Eio.Path.save ~create:(`Or_truncate 0o600) file (with_trailing_newline message); let finally () = try Eio.Path.unlink file with Eio.Io _ -> () in Fun.protect ~finally @@ fun () -> let msgfile = Eio.Path.native_exn file in let cwd = Eio.Path.(fs / Git_eio.Repository.work_dir repo) in let cmds = (match std with | Some h -> [ [ Fpath.to_string h; msgfile ] ] | None -> []) @ List.map (fun c -> [ "/bin/sh"; "-c"; c ^ " \"$@\""; c; msgfile ]) cfg in if List.exists (commit_msg_rejects ~proc ~cwd) cmds then Error "commit-msg hook rejected the commit message" else Ok (without_trailing_newline (Eio.Path.load file)) (* Resolve the message through the commit-msg hook, write the commit, and refresh the index. *) let finish_commit ~proc repo ~user ~message ~paths ~address_specs ~path_specs ~nothing ~no_verify = let message = if no_verify || Git_eio.Repository.hook repo "commit-msg" = None && config_hooks repo "commit-msg" = [] then Ok message else if nothing then Fmt.error "nothing to commit under: %s" (String.concat " " paths) else run_commit_msg_hooks ~proc repo message in match message with | Error e -> Common.cmd_error e | Ok message -> ( let result, refresh = commit_specs repo ~author:user ~committer:user ~message ~paths ~address_specs ~path_specs in match result with | Error (`Msg e) -> Common.cmd_error e | Ok (hash, changed) -> (match refresh with | Worktree -> refresh_index repo changed | Mixed { address_paths; path_changes } -> refresh_index_to_head repo address_paths; refresh_index repo path_changes); let branch = Option.value ~default:"HEAD" (Git_eio.Repository.current_branch repo) in let short = String.sub (Git.Hash.to_hex hash) 0 7 in Fmt.pr "[%s %s] %s@." branch short (first_line message); List.iter (Fmt.pr "%a" pp_change) changed; `Ok ()) let run_commit ~proc repo ~message ~paths ~no_verify ~hook_dir = match Common.user_or_error repo with | Error (`Msg e) -> Common.cmd_error e | Ok user -> ( let address_specs, path_specs = split_specs paths in let selected_paths = path_specs @ List.map (fun spec -> Git_outline.Address.(path (of_string spec))) address_specs in let hook_dir = match hook_dir with | Some _ -> hook_dir | None -> inferred_hook_dir repo selected_paths in match Git_eio.Repository.changes_under repo ~paths:path_specs with | Error (`Msg e) -> Common.cmd_error e | Ok path_changes -> ( let nothing = path_changes = [] && address_specs = [] in (* Hooks run only when a commit will be attempted. *) match if no_verify || nothing then Ok () else run_pre_commit_hooks ~proc ?hook_dir repo with | Error e -> Common.cmd_error e | Ok () -> finish_commit ~proc repo ~user ~message ~paths ~address_specs ~path_specs ~nothing ~no_verify)) let run ~repo_path ~message ~paths ~dry_run ~no_verify ~hook_dir () = if paths = [] then Common.cmd_error "no paths given; name the files or directories to commit" else Common.with_repo_env repo_path @@ fun ~env ~sw:_ repo -> if dry_run then run_dry_run repo paths else match message with | None -> Common.cmd_error "missing commit message (-m MSG)" | Some message -> let proc = Eio.Stdenv.process_mgr env in run_commit ~proc repo ~message ~paths ~no_verify ~hook_dir let term = Term.( ret (const (fun () repo_path messages paths dry_run no_verify hook_dir -> let message = match messages with | [] -> None | _ -> Some (String.concat "\n\n" messages) in run ~repo_path ~message ~paths ~dry_run ~no_verify ~hook_dir ()) $ Common.setup $ Common.repo_path $ message_arg $ paths_arg $ dry_run_arg $ no_verify_arg $ hook_dir_arg)) let subcmd_man = [ `S Manpage.s_description; `P "$(tname) commits the working-tree state of exactly the named paths. The \ commit is built on the object database as an overlay of those files \ over the branch tip's tree; the branch's index is then refreshed for \ exactly those paths so $(b,git status) shows them clean. Files staged \ by other users (humans, tools, agents) are not swept into the commit \ and their staged state is left alone. The branch ref advances by \ compare-and-swap under git's ref lock, retrying on a concurrently moved \ tip, so parallel commits from several writers serialise instead of \ losing one."; `S "HOOKS"; `P "When a commit will be attempted, $(tname) runs the repository's \ $(b,pre-commit) hook (from $(b,core.hooksPath) or $(b,.git/hooks)) in \ the work tree; a non-zero exit aborts the commit. Because the commit is \ built from the named working-tree paths rather than the index, the hook \ sees no staged content, so a hook meant for $(tname) should inspect the \ work tree rather than $(b,git diff --cached). Without an explicit \ scope, $(tname) infers one when all selected paths belong to a single \ top-level Dune package; root-level or mixed-package selections use the \ whole tree. Each $(b,gitx.hook.pre-commit) config value then runs as a \ shell command, in config order."; `P "$(b,--hook-dir DIR) runs the pre-commit hook with its working directory \ scoped to $(b,DIR), a subdirectory of the work tree. The hook still \ runs at the work-tree root, so a cwd-relative formatter or linter \ ($(b,dune fmt), $(b,merlint .)) it invokes resolves the workspace from \ the root while acting on that subtree. The commit-msg hook is \ unaffected and always runs at the work-tree root."; `P "Before writing the commit, $(tname) then runs the $(b,commit-msg) hook \ with the path of a file holding the message; the hook may edit the file \ in place, and a non-zero exit aborts the commit. Each \ $(b,gitx.hook.commit-msg) config value then runs as a shell command \ with the same path appended, in config order. $(b,--no-verify) skips \ all of these hooks."; `S Manpage.s_examples; `P "Commit two files, ignoring whatever other users have staged:"; `Pre " $(mname) create -m 'fix parser' lib/parser.ml lib/parser.mli"; `P "Commit every change under one package:"; `Pre " $(mname) create -m 'port to eio' ocaml-foo/"; `P "Explicitly scope the pre-commit hook to one package:"; `Pre " $(mname) create --hook-dir ocaml-foo -m 'port to eio' ocaml-foo/"; `P "Commit one OCaml definition, leaving other edits in the file:"; `Pre " $(mname) create -m 'fix jwt helper' test.ml:jwks_json"; `P "Preview what a directory commit would record:"; `Pre " $(mname) create --dry-run ocaml-foo/"; ] let subcmd = let info = Cmd.info "create" ~doc:"Commit the working-tree state of named paths" ~man:subcmd_man in Cmd.v info term let cmd = let info = Cmd.info "commit" ~doc:"Create commits and rewrite single commits in history" ~man: [ `S Manpage.s_description; `P "Create a commit from named working-tree paths ($(b,create)), or \ rewrite a single commit in history without touching the working \ tree or HEAD ($(b,drop), $(b,reword), $(b,sort), $(b,squash), \ $(b,split)). With no subcommand, $(tname) behaves as $(b,create)."; ] in Cmd.group info ~default:term [ subcmd; Cmd_commit_drop.cmd; Cmd_commit_reword.cmd; Cmd_commit_sort.cmd; Cmd_commit_squash.cmd; Cmd_commit_split.cmd; ]