Skip to main content

grit_lib/porcelain/
commit.rs

1//! Create a commit from the current index and move the checked-out branch.
2//!
3//! [`create_commit`] performs incremental cache-tree write-tree, writes the commit
4//! object, persists the index with a valid cache-tree, then updates the branch and `HEAD`
5//! reflogs through [`crate::refs::update_branch_for_commit_on_store`].
6
7use crate::apply::{apply_patch_to_index, FilePatch, IndexApplyOptions};
8use crate::change_id::{change_id, set_change_id, ChangeId, ChangeIdPolicy};
9use crate::commit::assemble_identity;
10use crate::commit::trailers::interpret::{
11    process_trailers, NewTrailerArg, ProcessTrailerOptions, TrailerIfExists, TrailerIfMissing,
12    TrailerWhere,
13};
14use crate::commit_trailers::{append_signoff_trailer_with_dedup, format_signoff_line};
15use crate::config::ident_resolve::IdentRole;
16use crate::config::ConfigSet;
17use crate::diff::refresh_index_stat_content_verified_with_rules;
18use crate::diff::{
19    diff_index_to_tree, diff_tree_path_change_count, diff_trees_with_renames, zero_oid, DiffEntry,
20    DiffStatus,
21};
22use crate::error::ObjectError;
23use crate::error::RefError;
24use crate::error::{Error, Result};
25use crate::history::{
26    ensure_rewrite_apply_ready, persist_rebase_stopped_head_if_missing, HistoryError,
27};
28use crate::hooks::{
29    run_advisory_hook, run_post_rewrite, CommitHookEnv, HookName, PostOperationHooks, RewriteKind,
30};
31use crate::ident::{
32    fsck_commit_idents, parse_signature_times, prepare_commit_author_from_parent,
33    prepare_commit_identity_line, replace_identity_date_suffix, Signature,
34};
35use crate::index::IndexError;
36use crate::index::{Index, IndexLock};
37use crate::notes::{
38    apply_prepared_notes_rewrite, prepare_notes_for_rewrite, NotesRewriteCommand, NotesRewritePlan,
39};
40use crate::objects::odb::Odb;
41use crate::objects::{parse_commit, serialize_commit, CommitData, ObjectId, ObjectKind};
42use crate::pathspec::{matches_pathspec_list_with_context, pathspec_is_exclude, Pathspec};
43use crate::porcelain::add::{
44    stage_on_index, validate_commit_staging_pathspecs, StageMode, StageOptions,
45};
46use crate::porcelain::commit_error::CommitError;
47use crate::porcelain::hunk_select::{
48    diff_options_for_hunk_select, resolve_selection, HunkSelection,
49};
50use crate::porcelain::index_from_tree::index_from_tree_with_seeded_worktree_stats;
51use crate::porcelain::merge::squash_conflict_merge_in_progress;
52use crate::porcelain::merge_error::MergeError;
53use crate::porcelain::pathspec_match::KnownPathspecChecker;
54use crate::porcelain::replay_sequence::finish_replay_commit_state;
55use crate::progress::{poll_cancel, CancelToken, ProgressSink};
56use crate::refs::store::RefNameRef;
57use crate::refs::{
58    update_branch_for_commit_on_store, update_detached_head_for_commit_on_store,
59    BranchCommitRefUpdate,
60};
61use crate::repo::Repository;
62use crate::signing::{
63    extra_headers_without_commit_signatures, should_sign_commit, sign_serialized_commit, GpgConfig,
64};
65use crate::state::{
66    finish_merge_state, grit_rebase_conflict_stop_active, read_cherry_pick_head,
67    read_grit_rebase_stopped_source, read_merge_heads, read_merge_msg, read_revert_head,
68    resolve_head_for_repository, HeadState, InProgressOperation,
69};
70use crate::stripspace::{process, Mode};
71use crate::worktree_rules::WorktreeRules;
72use crate::write_tree::{
73    cache_tree_extension_valid, is_empty_tree_oid, write_tree_update_index, WriteTreeFlags,
74};
75use std::collections::BTreeMap;
76use std::fs;
77use std::path::{Path, PathBuf};
78use std::process;
79use std::sync::{Arc, Mutex};
80
81/// Whether the verifying hooks run before a commit object is written.
82///
83/// The verifying hooks are `pre-commit` (or `pre-merge-commit` for a merge) and `commit-msg`.
84/// `prepare-commit-msg` and the `post-*` hooks run under either policy, as in Git.
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
86pub enum HookPolicy {
87    /// Run the verifying hooks when installed (default).
88    #[default]
89    Run,
90    /// Skip the verifying hooks (`--no-verify`).
91    SkipVerify,
92}
93
94/// Where a commit message came from, as `prepare-commit-msg` is told in its second (and third)
95/// argument.
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub(crate) enum MessageSource {
98    /// Given by the caller (`-m`, `-F`).
99    Message,
100    /// Reused from this commit (`--amend`, `-C`).
101    Commit(ObjectId),
102    /// The merge message in `MERGE_MSG`.
103    Merge,
104    /// The squash message in `SQUASH_MSG`.
105    Squash,
106}
107
108/// Run `prepare-commit-msg` and then, unless `verify` is [`HookPolicy::SkipVerify`],
109/// `commit-msg` on the message file at `msg_path`, appending each hook that ran to `hooks_run`.
110///
111/// Returns the file's contents (with a trailing newline) when either hook ran, since a hook
112/// may have rewritten it, and `None` when neither is installed.
113///
114/// # Errors
115///
116/// [`Error::Hook`] when a hook fails or cannot start, [`Error::Io`] when the file cannot be
117/// read back, and [`CommitError::EmptyCommitMessage`] when a hook left it empty.
118pub(crate) fn run_commit_message_hooks(
119    repo: &Repository,
120    msg_path: &Path,
121    source: MessageSource,
122    verify: HookPolicy,
123    commit_env: &CommitHookEnv<'_>,
124    hooks_run: &mut Vec<HookName>,
125    cancel: &CancelToken,
126) -> Result<Option<String>> {
127    let path_arg = commit_editmsg_hook_argument(repo, msg_path);
128    let source_oid;
129    let prepare_args: Vec<&str> = match source {
130        MessageSource::Message => vec![&path_arg, "message"],
131        MessageSource::Commit(oid) => {
132            source_oid = oid.to_hex();
133            vec![&path_arg, "commit", &source_oid]
134        }
135        MessageSource::Merge => vec![&path_arg, "merge"],
136        MessageSource::Squash => vec![&path_arg, "squash"],
137    };
138    let ran_before = hooks_run.len();
139    if run_commit_hook_recorded(
140        repo,
141        HookName::PrepareCommitMsg,
142        &prepare_args,
143        None,
144        commit_env,
145        cancel,
146    )? {
147        hooks_run.push(HookName::PrepareCommitMsg);
148    }
149    if verify != HookPolicy::SkipVerify
150        && run_commit_hook_recorded(
151            repo,
152            HookName::CommitMsg,
153            &[&path_arg],
154            None,
155            commit_env,
156            cancel,
157        )?
158    {
159        hooks_run.push(HookName::CommitMsg);
160    }
161    if hooks_run.len() == ran_before {
162        return Ok(None);
163    }
164    let mut message = fs::read_to_string(msg_path).map_err(Error::Io)?;
165    if message.trim().is_empty() {
166        return Err(CommitError::EmptyCommitMessage.into());
167    }
168    if !message.ends_with('\n') {
169        message.push('\n');
170    }
171    Ok(Some(message))
172}
173
174/// Author name, email, and date suffix from a written commit header line.
175#[derive(Debug, Clone, PartialEq, Eq)]
176pub struct CommitAuthorInfo {
177    /// Author display name.
178    pub name: String,
179    /// Author email.
180    pub email: String,
181    /// Git timestamp suffix (`<unix> <+HHMM>`).
182    pub date: String,
183}
184
185impl CommitAuthorInfo {
186    /// Parse [`Self::name`], [`Self::email`], and [`Self::date`] as a [`Signature`].
187    #[must_use]
188    pub fn signature(&self) -> Signature {
189        let line = if self.date.is_empty() {
190            format!("{} <{}>", self.name, self.email)
191        } else {
192            format!("{} <{}> {}", self.name, self.email, self.date)
193        };
194        Signature::from_header_lossy(&line)
195    }
196}
197
198#[cfg(feature = "serde-models")]
199impl serde::Serialize for CommitAuthorInfo {
200    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
201    where
202        S: serde::Serializer,
203    {
204        self.signature().serialize(serializer)
205    }
206}
207
208fn guard_incomplete_rewrite_apply(repo: &Repository) -> Result<()> {
209    ensure_rewrite_apply_ready(repo).map_err(|err| match err {
210        crate::error::Error::History(HistoryError::RewriteApplyIncomplete) => {
211            MergeError::OperationInProgress(InProgressOperation::RewriteApply).into()
212        }
213        other => other,
214    })
215}
216
217/// Inputs for [`create_commit`].
218#[derive(Debug, Clone, Default)]
219pub struct CommitRequest {
220    /// Commit message body (first line becomes the subject). A trailing newline is added when missing.
221    ///
222    /// The message is also written to `.git/COMMIT_EDITMSG` for the `prepare-commit-msg` and
223    /// `commit-msg` hooks. The file is read back only when one of them ran, so concurrent
224    /// committers sharing the file never record each other's message.
225    pub message: String,
226    /// Tell `prepare-commit-msg` that [`Self::message`] is the in-progress merge's `MERGE_MSG`
227    /// (source `merge` instead of `message`), as when finishing a merge.
228    pub(crate) message_from_merge: bool,
229    /// Author to record. `None` keeps the replaced commit's author for [`Self::amend`] and the
230    /// source commit's author for [`Self::reuse_message_from`]; otherwise the repository's
231    /// author identity ([`Repository::identity`]) is used. [`Self::author_date`] and
232    /// [`Self::reset_author`] still apply.
233    pub author: Option<Signature>,
234    /// Committer to record; `None` uses the repository's committer identity
235    /// ([`Repository::identity`]).
236    pub committer: Option<Signature>,
237    /// When false (default), reject commits whose tree equals the parent's tree or is the empty tree on an unborn branch.
238    pub allow_empty: bool,
239    /// When `Some(true)`, sign even if `commit.gpgsign` is false; when `Some(false)`, skip signing even when config requests it. When `None`, honor `commit.gpgsign`.
240    pub sign_override: Option<bool>,
241    /// Replace the current branch tip: parents and author come from the tip being replaced; an empty
242    /// [`Self::message`] reuses that commit's message. Same-tree amends are allowed.
243    pub amend: bool,
244    /// When true, skip the post-commit full-tree index stat refresh because the caller already
245    /// synced the index from the worktree (for example via [`crate::porcelain::add::stage_for_commit`]).
246    ///
247    /// [`commit_worktree`] and every [`commit_with_scope`] scope set this themselves, since their
248    /// staging pass already refreshed the index; only [`create_commit`] callers need to choose.
249    pub assume_worktree_synced: bool,
250    /// When true with [`Self::assume_worktree_synced`], skip the pre-commit index↔parent tree
251    /// match; the post-`write_tree` parent comparison still rejects empty commits.
252    pub(crate) skip_pre_commit_tree_match: bool,
253    /// When set with [`Self::skip_pre_commit_tree_match`], use this instead of a full tree diff for
254    /// [`CommitOutcome::changes`].
255    pub(crate) staged_change_count: Option<usize>,
256    /// Hook execution policy for `pre-commit` and `commit-msg`; `prepare-commit-msg` runs either
257    /// way.
258    #[doc(alias = "no-verify")]
259    pub hooks: HookPolicy,
260    /// Author timestamp suffix (`<unix> <+HHMM>`) replacing the author line date when set.
261    pub author_date: Option<String>,
262    /// Trailers to append via [`process_trailers`] (same semantics as `git commit --trailer`).
263    pub trailers: Vec<(String, String)>,
264    /// Append `Signed-off-by` using the committer identity (`-s` / `--signoff`).
265    pub signoff: bool,
266    /// Use the committer as the author with a fresh author date (`--reset-author`).
267    pub reset_author: bool,
268    /// Reuse log message and author from this commit (`-C` / `--reuse-message`); copies get a new change id.
269    pub reuse_message_from: Option<ObjectId>,
270    /// When true, stage in memory and report the files the commit would change (index against the
271    /// parent tree, by object id and mode) without writing objects, the index or refs, or running
272    /// hooks.
273    pub dry_run: bool,
274    /// When true, a [`CommitError::NothingToCommit`] is upgraded to [`CommitError::NothingStagedToCommit`] if the
275    /// work tree still has unstaged or untracked paths (index-only commit).
276    pub(crate) index_only: bool,
277    /// Whether an amend runs `post-rewrite amend` ([`PostOperationHooks::Skip`] is Git's
278    /// `--no-post-rewrite`). `post-commit` runs either way.
279    pub post_rewrite: PostOperationHooks,
280}
281
282impl CommitRequest {
283    /// Start a commit request with `message`; set other fields on the returned value.
284    #[must_use]
285    pub fn new(message: impl Into<String>) -> Self {
286        Self {
287            message: message.into(),
288            ..Self::default()
289        }
290    }
291}
292
293/// One path-level change that would be recorded in a commit.
294#[derive(Debug, Clone, PartialEq, Eq)]
295#[cfg_attr(feature = "serde-models", derive(serde::Serialize))]
296pub struct CommitFile {
297    /// Primary path (`git diff --name-status` path column).
298    pub path: String,
299    /// Kind of change vs the parent commit tree.
300    pub status: DiffStatus,
301    /// Previous path for renames and copies.
302    pub old_path: Option<String>,
303}
304
305/// Planned commit contents and metadata (see [`plan_commit`]).
306#[derive(Debug, Clone, PartialEq, Eq)]
307pub struct CommitPlan {
308    /// Paths that differ from the parent tree, in `git diff --name-status` order.
309    pub files: Vec<CommitFile>,
310    /// Parent OIDs that would be stored on the new commit.
311    pub parents: Vec<ObjectId>,
312    /// Author line that would be recorded.
313    pub author: CommitAuthorInfo,
314    /// Whether the computed tree OID equals the parent tree.
315    pub tree_unchanged: bool,
316}
317
318/// Which paths are included when recording a commit ([`commit_with_scope`]).
319#[derive(Debug, Clone)]
320pub enum CommitScope {
321    /// Stage worktree changes, then commit (default `grit commit` behavior).
322    ///
323    /// Stages tracked modifications and deletions plus untracked files, except when
324    /// `status.showUntrackedFiles` is `no` (or a Git boolean false synonym): then only tracked
325    /// paths are staged, matching `git commit -a` and what [`crate::porcelain::status`] shows.
326    /// Explicit path commits ([`CommitScope::Paths`]) and [`crate::porcelain::add::stage`] are
327    /// unchanged.
328    AutoStage,
329    /// Commit the index as-is (`git commit` without `-a`).
330    Staged,
331    /// Commit only matching paths from the worktree (`git commit --only --` paths).
332    Paths(crate::pathspec::Pathspec),
333    /// Commit only hunks from a unified diff or stable hunk ids (`grit commit --hunks` / `--patch-file`).
334    Patch {
335        /// Hunk ids or pre-parsed file patches (exactly one is populated).
336        input: CommitPatchInput,
337        /// Optional pathspecs narrowing hunk resolution (same as `grit add --hunks`).
338        pathspecs: Vec<String>,
339    },
340}
341
342impl PartialEq for CommitScope {
343    fn eq(&self, other: &Self) -> bool {
344        match (self, other) {
345            (Self::AutoStage, Self::AutoStage) | (Self::Staged, Self::Staged) => true,
346            (Self::Paths(a), Self::Paths(b)) => {
347                a.specs() == b.specs() && a.globals() == b.globals()
348            }
349            (
350                Self::Patch {
351                    input: a,
352                    pathspecs: ap,
353                },
354                Self::Patch {
355                    input: b,
356                    pathspecs: bp,
357                },
358            ) => ap == bp && patch_input_same_kind(a, b),
359            _ => false,
360        }
361    }
362}
363
364impl Eq for CommitScope {}
365
366fn patch_input_same_kind(a: &CommitPatchInput, b: &CommitPatchInput) -> bool {
367    matches!(
368        (a, b),
369        (CommitPatchInput::Hunks(_), CommitPatchInput::Hunks(_))
370            | (CommitPatchInput::Patches(_), CommitPatchInput::Patches(_))
371    )
372}
373
374/// Hunk ids or parsed patches for [`CommitScope::Patch`].
375#[derive(Debug, Clone)]
376pub enum CommitPatchInput {
377    /// Stable ids from `grit diff --json`.
378    Hunks(HunkSelection),
379    /// Unified diff hunks (`git apply --cached` preimage = index).
380    Patches(Vec<FilePatch>),
381}
382
383/// Default [`CommitScope`] from `commit.autoStage` (default true → [`CommitScope::AutoStage`]).
384///
385/// # Errors
386///
387/// Propagates config read failures from [`Repository::config`].
388pub(crate) fn default_commit_scope(repo: &Repository) -> Result<CommitScope> {
389    let config = repo.config().snapshot()?;
390    Ok(default_commit_scope_from_config(config.as_ref()))
391}
392
393/// Read `commit.autoStage` (default true).
394#[must_use]
395pub fn default_commit_scope_from_config(config: &ConfigSet) -> CommitScope {
396    let auto_stage = config
397        .get_bool("commit.autoStage")
398        .ok()
399        .flatten()
400        .unwrap_or(true);
401    if auto_stage {
402        CommitScope::AutoStage
403    } else {
404        CommitScope::Staged
405    }
406}
407
408/// Remove squash merge sentinel files after a successful commit (Git removes `SQUASH_MSG` on commit).
409///
410/// # Errors
411///
412/// Returns [`Error::Io`] if a present file cannot be removed.
413pub(crate) fn clear_squash_commit_state(git_dir: &std::path::Path) -> Result<()> {
414    let squash = git_dir.join("SQUASH_MSG");
415    if !squash.is_file() {
416        return Ok(());
417    }
418    fs::remove_file(&squash).map_err(Error::Io)?;
419    if !git_dir.join("MERGE_HEAD").is_file() {
420        let merge_msg = git_dir.join("MERGE_MSG");
421        if merge_msg.is_file() {
422            fs::remove_file(&merge_msg).map_err(Error::Io)?;
423        }
424    }
425    Ok(())
426}
427
428/// Default message for the next commit when `SQUASH_MSG` or merge `MERGE_MSG` is present.
429///
430/// # Errors
431///
432/// Propagates I/O and merge-state read failures.
433pub(crate) fn pending_commit_message(repo: &Repository) -> Result<Option<String>> {
434    let git_dir = repo.git_dir();
435    let squash = git_dir.join("SQUASH_MSG");
436    let merge_msg = git_dir.join("MERGE_MSG");
437    // Squash merge conflicts store the editable message (including `-m`) in `MERGE_MSG`.
438    if squash.is_file() && merge_msg.is_file() {
439        return fs::read_to_string(merge_msg).map_err(Error::Io).map(Some);
440    }
441    if squash.is_file() {
442        return fs::read_to_string(squash).map_err(Error::Io).map(Some);
443    }
444    if !read_merge_heads(git_dir)?.is_empty() {
445        return read_merge_msg(git_dir);
446    }
447    if read_cherry_pick_head(git_dir)?.is_some() || read_revert_head(git_dir)?.is_some() {
448        let Some(raw) = read_merge_msg(git_dir)? else {
449            return Ok(None);
450        };
451        let processed = process(raw.as_bytes(), &Mode::StripComments("#".to_owned()));
452        let message = String::from_utf8(processed)
453            .map_err(|_| Error::from(CommitError::EmptyCommitMessage))?;
454        if message.trim().is_empty() {
455            return Ok(None);
456        }
457        return Ok(Some(message));
458    }
459    if grit_rebase_conflict_stop_active(git_dir) {
460        let Some(raw) = read_merge_msg(git_dir)? else {
461            return Ok(None);
462        };
463        let processed = process(raw.as_bytes(), &Mode::StripComments("#".to_owned()));
464        let message = String::from_utf8(processed)
465            .map_err(|_| Error::from(CommitError::EmptyCommitMessage))?;
466        if message.trim().is_empty() {
467            return Ok(None);
468        }
469        return Ok(Some(message));
470    }
471    Ok(None)
472}
473
474fn replay_blocks_partial_commit(git_dir: &std::path::Path) -> Result<bool> {
475    Ok(read_cherry_pick_head(git_dir)?.is_some() || read_revert_head(git_dir)?.is_some())
476}
477
478/// Record a commit using `scope` to decide how the index is prepared.
479///
480/// Staging reports [`crate::progress::ProgressPhase::StagingFiles`] to `progress`; `cancel` stops
481/// the commit with [`Error::Cancelled`] up to the point
482/// the commit object is written, leaving `HEAD` and the branch where they were.
483///
484/// # Errors
485///
486/// Same as [`create_commit`] and [`commit_worktree`], plus:
487///
488/// - [`CommitError::CommitPathsRequired`] for an empty [`CommitScope::Paths`] list.
489/// - [`CommitError::PartialCommitDuringMerge`] for [`CommitScope::Paths`] or [`CommitScope::Patch`]
490///   during an in-progress merge, and pathspec validation errors.
491/// - [`CommitError::HunkSelect`] when a [`CommitScope::Patch`] hunk id is unknown, stale, binary,
492///   or for the wrong side, and [`CommitError::PatchApply`] when the selected patch does not apply
493///   to the index, as from [`commit_with_patch`].
494///
495/// Underlying repository, hook, index, and I/O failures are returned in their own areas.
496pub(crate) fn commit_with_scope(
497    repo: &Repository,
498    req: &CommitRequest,
499    scope: CommitScope,
500    progress: &mut dyn ProgressSink,
501    cancel: &CancelToken,
502) -> Result<CommitOutcome> {
503    guard_incomplete_rewrite_apply(repo)?;
504    match scope {
505        CommitScope::AutoStage => Ok(commit_worktree(repo, req, progress, cancel)?),
506        CommitScope::Staged => {
507            let mut req = req.clone();
508            // Index stats were refreshed when paths were staged; skip full-tree refresh (#1622).
509            req.assume_worktree_synced = true;
510            req.index_only = true;
511            Ok(create_commit(repo, &req, progress, cancel)?)
512        }
513        CommitScope::Paths(paths) => Ok(commit_paths_scope(repo, req, &paths, progress, cancel)?),
514        CommitScope::Patch { input, pathspecs } => Ok(commit_with_patch(
515            repo, req, input, &pathspecs, progress, cancel,
516        )?),
517    }
518}
519
520/// File hunk-selection failures of a partial commit under the commit area.
521fn commit_patch_error(err: Error) -> Error {
522    match err {
523        Error::Diff(crate::error::DiffError::HunkSelection(sel)) => {
524            CommitError::HunkSelect(sel).into()
525        }
526        other => other,
527    }
528}
529
530/// Record a commit after applying `input` to the current index (partial stage + commit).
531///
532/// Applies the selection in memory, commits the resulting tree, then writes the updated index.
533/// Does not auto-stage the worktree (same effective scope as [`CommitScope::Staged`]).
534///
535/// # Errors
536///
537/// [`CommitError::HunkSelect`] for hunk id failures; [`CommitError::PatchApply`] for patch apply;
538/// same commit errors as [`create_commit`].
539pub(crate) fn commit_with_patch(
540    repo: &Repository,
541    req: &CommitRequest,
542    input: CommitPatchInput,
543    pathspecs: &[String],
544    progress: &mut dyn ProgressSink,
545    cancel: &CancelToken,
546) -> Result<CommitOutcome> {
547    guard_incomplete_rewrite_apply(repo)?;
548    commit_patch_scope(repo, req, input, pathspecs, progress, cancel)
549}
550
551fn commit_patch_scope(
552    repo: &Repository,
553    req: &CommitRequest,
554    input: CommitPatchInput,
555    pathspecs: &[String],
556    progress: &mut dyn ProgressSink,
557    cancel: &CancelToken,
558) -> Result<CommitOutcome> {
559    if !read_merge_heads(repo.git_dir())?.is_empty() {
560        return Err(CommitError::PartialCommitDuringMerge.into());
561    }
562    if replay_blocks_partial_commit(repo.git_dir())? {
563        return Err(CommitError::PartialCommitDuringReplay.into());
564    }
565    let index_lock = (!req.dry_run)
566        .then(|| repo.begin_index_update())
567        .transpose()?;
568
569    let patches = match input {
570        CommitPatchInput::Hunks(selection) => {
571            if selection.ids.is_empty() && selection.ranges.is_empty() {
572                return Err(CommitError::NothingToCommit.into());
573            }
574            resolve_selection(
575                repo,
576                crate::diff::DiffSide::Unstaged,
577                &selection,
578                pathspecs,
579                diff_options_for_hunk_select(repo)?,
580            )
581            .map_err(commit_patch_error)?
582        }
583        CommitPatchInput::Patches(patches) => {
584            if patches.is_empty() {
585                return Err(CommitError::NothingToCommit.into());
586            }
587            patches
588        }
589    };
590
591    let head = resolve_head_for_repository(repo)?;
592    let mut index = repo.load_index()?;
593    if index.has_unmerged_entries() {
594        return Err(Error::from(IndexError::unmerged()));
595    }
596
597    let dry_run = req.dry_run;
598    let _patch_overlay = if dry_run {
599        repo.odb().enable_mem_overlay();
600        Some(MemOverlayGuard(repo.odb()))
601    } else {
602        None
603    };
604
605    apply_patch_to_index(
606        repo,
607        &mut index,
608        &patches,
609        &IndexApplyOptions {
610            dry_run: false,
611            ..IndexApplyOptions::default()
612        },
613    )
614    .map_err(|err| match err {
615        crate::error::ApplyError::Cancelled => Error::Cancelled,
616        other => CommitError::PatchApply(other).into(),
617    })?;
618
619    let mut req = req.clone();
620    req.assume_worktree_synced = true;
621    let persist = index_lock.map(|lock| LockedIndex { index: None, lock });
622    create_commit_with_index(repo, head, &mut index, &req, progress, cancel, persist)
623}
624
625/// Preview a commit for `scope` without mutating the repository (objects, index on disk, refs, hooks).
626///
627/// Uses in-memory blob hashing during staging (no new loose objects) and returns the same validation
628/// errors as [`commit_with_scope`] for unmerged index and nothing-to-commit.
629///
630/// # Errors
631///
632/// Same as [`commit_with_scope`].
633pub(crate) fn plan_commit(
634    repo: &Repository,
635    req: &CommitRequest,
636    scope: CommitScope,
637    progress: &mut dyn ProgressSink,
638    cancel: &CancelToken,
639) -> Result<CommitPlan> {
640    let mut req = req.clone();
641    req.dry_run = true;
642    let outcome = commit_with_scope(repo, &req, scope, progress, cancel)?;
643    Ok(CommitPlan {
644        files: outcome.files,
645        parents: outcome.parents,
646        author: outcome.author,
647        tree_unchanged: outcome.changes == 0,
648    })
649}
650
651/// Copy stage-0 rows from `source` into `commit_index` when they are absent from the parent-tree
652/// snapshot but needed for path-scoped staging.
653///
654/// Path-scoped commits build `commit_index` from the parent tree. Ignored paths that are
655/// already staged in the repository index (force-added or tracked) must appear there before
656/// worktree staging runs, or ignored untracked collection skips them. Rows already present from
657/// the parent tree are left untouched so explicitly excluded paths keep their HEAD versions.
658fn seed_commit_index_stage0_from_index(
659    repo: &Repository,
660    commit_index: &mut Index,
661    source: &Index,
662    paths: &Pathspec,
663) -> Result<()> {
664    if paths.is_entire_tree() {
665        return Ok(());
666    }
667    let ctx = repo.pathspec_match_context();
668    let mut seeded = false;
669    for entry in &source.entries {
670        if entry.stage() != 0 {
671            continue;
672        }
673        let path = match std::str::from_utf8(&entry.path) {
674            Ok(p) if !p.is_empty() => p,
675            _ => continue,
676        };
677        if commit_index.get(path.as_bytes(), 0).is_some() {
678            continue;
679        }
680        if !matches_pathspec_list_with_context(path, paths.specs(), ctx) {
681            continue;
682        }
683        commit_index.stage_file(entry.clone());
684        seeded = true;
685    }
686    if seeded {
687        commit_index.ensure_canonical_order();
688    }
689    Ok(())
690}
691
692fn commit_paths_scope(
693    repo: &Repository,
694    req: &CommitRequest,
695    paths: &Pathspec,
696    progress: &mut dyn ProgressSink,
697    cancel: &CancelToken,
698) -> Result<CommitOutcome> {
699    if paths.is_entire_tree() {
700        return Err(CommitError::CommitPathsRequired.into());
701    }
702    if !read_merge_heads(repo.git_dir())?.is_empty() {
703        return Err(CommitError::PartialCommitDuringMerge.into());
704    }
705    if replay_blocks_partial_commit(repo.git_dir())? {
706        return Err(CommitError::PartialCommitDuringReplay.into());
707    }
708    validate_commit_pathspecs(repo, paths)?;
709
710    // Lock before reading HEAD and the index so nothing visible (objects, ref, reflog) is written
711    // when another process holds it, and so nobody can commit or change the index under us.
712    let index_lock = (!req.dry_run)
713        .then(|| repo.begin_index_update())
714        .transpose()?;
715    let head = resolve_head_for_repository(repo)?;
716    if head == HeadState::Invalid {
717        return Err(Error::Ref(RefError::InvalidHead));
718    }
719    let parent_tree = head.tree(repo.odb())?;
720
721    let mut real_index = repo.load_index()?;
722    if real_index.has_unmerged_entries() {
723        return Err(IndexError::unmerged().into());
724    }
725    let path_sources: Vec<String> = paths.iter().map(str::to_owned).collect();
726    let mut stage_opts = StageOptions {
727        pathspecs: paths.specs().to_vec(),
728        pathspec_sources: if path_sources.is_empty() {
729            paths.specs().to_vec()
730        } else {
731            path_sources
732        },
733        mode: StageMode::All,
734        dry_run: req.dry_run,
735        ..StageOptions::default()
736    };
737
738    validate_commit_staging_pathspecs(repo, &real_index, &stage_opts)?;
739    stage_opts.skip_pathspec_ignore_check = true;
740
741    let mut commit_index = match parent_tree.as_ref() {
742        Some(tree) => index_from_tree_with_seeded_worktree_stats(repo, tree, &real_index)?,
743        None => Index::new(),
744    };
745    seed_commit_index_stage0_from_index(repo, &mut commit_index, &real_index, paths)?;
746
747    let staged_commit = stage_on_index(repo, &mut commit_index, &stage_opts, progress, cancel)?;
748    let real_index = match index_lock {
749        Some(lock) => {
750            stage_on_index(repo, &mut real_index, &stage_opts, progress, cancel)?;
751            Some(LockedIndex {
752                index: Some(real_index),
753                lock,
754            })
755        }
756        None => None,
757    };
758
759    let mut req = req.clone();
760    req.assume_worktree_synced = true;
761    req.skip_pre_commit_tree_match = false;
762    req.staged_change_count = Some(staged_commit.total().max(1));
763    req.index_only = true;
764
765    create_commit_with_index(
766        repo,
767        head,
768        &mut commit_index,
769        &req,
770        progress,
771        cancel,
772        real_index,
773    )
774}
775
776/// The repository index to persist after a commit, with the lock taken before the commit started.
777///
778/// Hooks read a temporary copy of the commit index; the repository index is written through the
779/// lock only after the ref moved. Dropping it unwritten releases the lock and leaves the on-disk
780/// index untouched.
781struct LockedIndex {
782    /// Index to persist when it differs from the committed one (path-scoped commits keep other
783    /// staged changes); `None` persists the committed index itself.
784    index: Option<Index>,
785    lock: IndexLock,
786}
787
788fn validate_commit_pathspecs(repo: &Repository, paths: &Pathspec) -> Result<()> {
789    let specs = paths.specs();
790    let sources: Vec<&str> = paths.iter().collect();
791    let pairs: Vec<(&str, &str)> = if sources.len() == specs.len() && !sources.is_empty() {
792        sources
793            .into_iter()
794            .zip(specs.iter())
795            .map(|(a, b)| (a, b.as_str()))
796            .collect()
797    } else {
798        specs.iter().map(|s| (s.as_str(), s.as_str())).collect()
799    };
800    let mut checker = KnownPathspecChecker::new(repo);
801    for (source, resolved) in pairs {
802        if pathspec_is_exclude(source) {
803            continue;
804        }
805        checker.ensure(source, resolved)?;
806    }
807    Ok(())
808}
809
810/// Normalize a commit message body the same way [`create_commit`] does before hooks: stripspace,
811/// reject empty bodies, ensure a trailing newline.
812///
813/// # Errors
814///
815/// Returns [`CommitError::EmptyCommitMessage`] when the cleaned body would be empty.
816pub fn normalize_commit_message(raw: &str) -> Result<String> {
817    let normalized = raw.replace("\r\n", "\n").replace('\r', "\n");
818    let processed = process(normalized.as_bytes(), &Mode::Default);
819    let message =
820        String::from_utf8(processed).map_err(|_| Error::from(CommitError::InvalidCommitMessage))?;
821    if message.is_empty() {
822        return Err(CommitError::EmptyCommitMessage.into());
823    }
824    let mut message = message;
825    while message.ends_with("\n\n") {
826        message.pop();
827    }
828    if !message.ends_with('\n') {
829        message.push('\n');
830    }
831    Ok(message)
832}
833
834fn run_commit_hook_recorded(
835    repo: &Repository,
836    hook: HookName,
837    args: &[&str],
838    stdin_data: Option<&[u8]>,
839    commit_env: &CommitHookEnv<'_>,
840    cancel: &CancelToken,
841) -> Result<bool> {
842    crate::hooks::run_commit_hook_with_cancel(
843        repo,
844        hook.as_str(),
845        args,
846        stdin_data,
847        commit_env,
848        cancel,
849    )?
850    .check(hook.as_str())
851}
852
853fn author_info_from_header_line(line: &str) -> CommitAuthorInfo {
854    let line = line.trim();
855    let date = parse_signature_times(line)
856        .map(|p| {
857            let tz = &line[p.tz_hhmm_range];
858            format!("{} {tz}", p.unix_seconds)
859        })
860        .unwrap_or_default();
861    let contact_end = line.rfind('>').map(|i| i + 1).unwrap_or(line.len());
862    let contact = line[..contact_end].trim();
863    let (name, email) = if let Some(lt) = contact.find('<') {
864        if let Some(gt) = contact.find('>') {
865            (contact[..lt].trim(), contact[lt + 1..gt].trim())
866        } else {
867            (contact, "")
868        }
869    } else if contact.contains('@') && !contact.chars().any(char::is_whitespace) {
870        ("", contact)
871    } else {
872        (contact, "")
873    };
874    CommitAuthorInfo {
875        name: name.to_owned(),
876        email: email.to_owned(),
877        date,
878    }
879}
880
881fn author_line_from_committer(
882    committer: &str,
883    author_date: Option<&str>,
884    now: time::OffsetDateTime,
885) -> String {
886    let info = author_info_from_header_line(committer);
887    assemble_identity(&info.name, &info.email, author_date, now)
888}
889
890fn enrich_commit_message(
891    message: String,
892    trailers: &[(String, String)],
893    signoff: bool,
894    committer: &str,
895    config: &ConfigSet,
896    git_dir: &Path,
897) -> Result<String> {
898    let mut out = message;
899    if signoff {
900        let info = author_info_from_header_line(committer);
901        let sob = format_signoff_line(&info.name, &info.email);
902        append_signoff_trailer_with_dedup(&mut out, &sob, config, true);
903    }
904    if !trailers.is_empty() {
905        let new_args: Vec<NewTrailerArg> = trailers
906            .iter()
907            .map(|(key, value)| NewTrailerArg {
908                text: if value.is_empty() {
909                    format!("{key}:")
910                } else {
911                    format!("{key}: {value}")
912                },
913                where_: TrailerWhere::End,
914                if_exists: TrailerIfExists::AddIfDifferent,
915                if_missing: TrailerIfMissing::Add,
916            })
917            .collect();
918        let opts = ProcessTrailerOptions {
919            only_trailers: false,
920            trim_empty: true,
921            only_input: false,
922            unfold: false,
923            no_divider: false,
924        };
925        out = process_trailers(&out, &opts, &new_args, Some(git_dir));
926    }
927    Ok(out)
928}
929
930/// Result of [`create_commit`].
931#[derive(Debug, Clone, PartialEq, Eq)]
932#[cfg_attr(feature = "serde-models", derive(serde::Serialize))]
933pub struct CommitOutcome {
934    /// OID of the new commit object written to the object database.
935    pub oid: ObjectId,
936    /// Short name of the branch the commit advanced (e.g. `main`), or `None` when `HEAD` is
937    /// detached and only `HEAD` moved.
938    pub branch: Option<String>,
939    /// Parent commit OID, or `None` for the root commit on an unborn branch.
940    pub parent: Option<ObjectId>,
941    /// Every parent OID stored in the new commit object (empty only before the first commit is written).
942    pub parents: Vec<ObjectId>,
943    /// Author recorded on the commit object.
944    pub author: CommitAuthorInfo,
945    /// Committer recorded on the commit object.
946    pub committer: CommitAuthorInfo,
947    /// Full commit message body written to the object (including trailing newline).
948    pub message: String,
949    /// Hooks that were installed and ran during this commit, in order: `pre-commit`,
950    /// `prepare-commit-msg`, `commit-msg`, `post-commit`, and `post-rewrite` (with `amend`) when
951    /// [`CommitRequest::amend`] is set.
952    pub hooks_run: Vec<HookName>,
953    /// Number of path-level changes between the parent commit tree and this commit's tree.
954    pub changes: usize,
955    /// Stored `change-id` header when present on the new commit object.
956    pub change_id: Option<ChangeId>,
957    /// Path-level changes vs the parent tree (`git diff --name-status` between parent and new tree).
958    pub files: Vec<CommitFile>,
959    /// Gitlink paths introduced while auto-staging before this commit (empty when nothing new was
960    /// recorded as a nested repository).
961    pub embedded_gitlinks: Vec<String>,
962    /// Rerere postimage events when this commit concluded a conflict resolution.
963    pub rerere: Vec<crate::rerere::RerereEvent>,
964}
965
966impl CommitOutcome {
967    /// Whether the commit was made on a detached `HEAD` ([`Self::branch`] is `None`).
968    #[must_use]
969    pub fn is_detached(&self) -> bool {
970        self.branch.is_none()
971    }
972}
973
974/// Write a commit from the current index and advance the checked-out branch.
975///
976/// Loads the index from disk, builds the commit tree with an incremental cache-tree
977/// write-tree, writes the commit object, writes the index back with an updated cache-tree,
978/// then atomically updates the branch ref and reflogs (see [`crate::refs::update_branch_for_commit_on_store`]).
979///
980/// # Parameters
981///
982/// - `repo` — open repository with a work tree and branch `HEAD`.
983/// - `req` — message, author/committer identities, and empty-commit policy.
984/// - `progress` — progress sink; staging callers see [`crate::progress::ProgressPhase::StagingFiles`].
985/// - `cancel` — checked before anything is written and again before the commit object is
986///   written; after that the branch update always completes.
987///
988/// # Errors
989///
990/// - [`Error::Cancelled`] when `cancel` fired before the
991///   commit object was written; `HEAD` and the branch are unchanged. Hook failures and cancel
992///   after hooks leave the on-disk index unchanged when the caller holds an index lock (for
993///   example [`commit_worktree`] and path-scoped commits).
994/// - [`crate::porcelain::CommitError::AmendUnborn`] when [`CommitRequest::amend`] is set but the branch has no commits yet.
995/// - [`CommitError::NothingToCommit`] when the new tree is empty (unborn branch) or matches the parent tree and [`CommitRequest::allow_empty`] is false (not applied when amending).
996/// - [`IndexError::unmerged()`] when the index has conflict stages.
997/// - Index write or diff failures before the branch is updated; the branch tip is not advanced.
998/// - Ref/reflog failures from [`crate::refs::update_branch_for_commit_on_store`]; the branch tip is not left advanced without reflogs when logging is enabled.
999pub(crate) fn create_commit(
1000    repo: &Repository,
1001    req: &CommitRequest,
1002    progress: &mut dyn ProgressSink,
1003    cancel: &CancelToken,
1004) -> Result<CommitOutcome> {
1005    guard_incomplete_rewrite_apply(repo)?;
1006    let head = resolve_head_for_repository(repo)?;
1007    let mut index = repo.load_index()?;
1008    create_commit_with_index(repo, head, &mut index, req, progress, cancel, None)
1009}
1010
1011/// Stage every worktree change and record a commit using a single in-memory index (issue #1064).
1012///
1013/// Avoids an extra index load/write between implicit staging and commit tree construction. The
1014/// staging pass is the only work-tree scan: it refreshes the stat data of every tracked entry, so
1015/// the commit always runs as if [`CommitRequest::assume_worktree_synced`] were set.
1016///
1017/// When staging changed the index but the result matches the parent tree (for example a new
1018/// file that was staged and then deleted from the work tree), the staged index is still written
1019/// before [`CommitError::NothingToCommit`] is returned, so the on-disk index matches `HEAD` afterwards.
1020/// [`CommitRequest::dry_run`] never writes the index, refs, or stored objects. Symlinks are
1021/// compared and previewed as link-target bytes, including directory and dangling links.
1022///
1023/// Staging reports [`crate::progress::ProgressPhase::StagingFiles`] and polls `cancel`; a cancel
1024/// during staging returns [`Error::Cancelled`] with the on-disk index, `HEAD` and refs unchanged.
1025/// A failing `pre-commit`, `prepare-commit-msg`, or `commit-msg` hook also leaves the on-disk
1026/// index and worktree unchanged (issue #2253): auto-staging runs in memory and hooks read a
1027/// temporary index file until the ref moves.
1028///
1029/// # Errors
1030///
1031/// Same as [`create_commit`], plus staging failures from [`crate::porcelain::add::stage_for_commit`],
1032/// including [`crate::worktree::WorktreeError::UnmergedConflictMarkers`] when a path's conflict stages were dropped
1033/// (after a merge, pick, revert, rebase or stash pop) while its worktree file still has
1034/// a conflict-marker block that its `HEAD` version does not. Neither the index nor `HEAD` moves in that case.
1035pub(crate) fn commit_worktree(
1036    repo: &Repository,
1037    req: &CommitRequest,
1038    progress: &mut dyn ProgressSink,
1039    cancel: &CancelToken,
1040) -> Result<CommitOutcome> {
1041    guard_incomplete_rewrite_apply(repo)?;
1042    let index_lock = (!req.dry_run)
1043        .then(|| repo.begin_index_update())
1044        .transpose()?;
1045    let head = resolve_head_for_repository(repo)?;
1046    let mut index = repo.load_index()?;
1047    let staged = crate::porcelain::add::stage_for_commit_on_index(
1048        repo,
1049        &mut index,
1050        progress,
1051        cancel,
1052        req.dry_run,
1053    )?;
1054    let staged_count = staged.total();
1055    let stat_refreshed = staged.stat_refreshed;
1056    if index.has_unmerged_entries() {
1057        return Err(IndexError::unmerged().into());
1058    }
1059    let mut req = req.clone();
1060    req.assume_worktree_synced = true;
1061    if req.skip_pre_commit_tree_match {
1062        req.staged_change_count = Some(staged_count);
1063    }
1064    let embedded_gitlinks = staged.embedded_gitlinks.clone();
1065    let persist = index_lock.map(|lock| LockedIndex { index: None, lock });
1066    let result = create_commit_with_index(repo, head, &mut index, &req, progress, cancel, persist);
1067    let result = result.map(|mut outcome| {
1068        outcome.embedded_gitlinks = embedded_gitlinks;
1069        outcome
1070    });
1071    if matches!(result, Err(Error::Commit(CommitError::NothingToCommit)))
1072        && !req.dry_run
1073        && (staged_count > 0 || stat_refreshed)
1074    {
1075        repo.write_index(&mut index)?;
1076    }
1077    if matches!(result, Err(Error::Commit(CommitError::NothingToCommit))) && staged_count == 0 {
1078        let mut worktree_index = match repo.load_index() {
1079            Ok(real) => real,
1080            Err(_) => index.clone(),
1081        };
1082        if let Ok((unstaged, untracked)) =
1083            crate::porcelain::status::count_unstaged_and_untracked_paths(repo, &mut worktree_index)
1084        {
1085            if unstaged + untracked > 0 {
1086                return Err(CommitError::NothingStagedToCommit {
1087                    unstaged,
1088                    untracked,
1089                }
1090                .into());
1091            }
1092        }
1093    }
1094    result
1095}
1096
1097fn commit_files_from_diff_entries(entries: &[DiffEntry]) -> Vec<CommitFile> {
1098    let mut files: Vec<CommitFile> = entries
1099        .iter()
1100        .filter(|e| e.status != DiffStatus::Unmerged)
1101        .map(|e| {
1102            let (path, old_path) = match e.status {
1103                DiffStatus::Renamed | DiffStatus::Copied => {
1104                    (e.new_path.clone().unwrap_or_default(), e.old_path.clone())
1105                }
1106                DiffStatus::Deleted => (e.old_path.clone().unwrap_or_default(), None),
1107                _ => (e.new_path.clone().unwrap_or_default(), None),
1108            };
1109            CommitFile {
1110                path,
1111                status: e.status,
1112                old_path,
1113            }
1114        })
1115        .collect();
1116    files.sort_by(|a, b| a.path.cmp(&b.path));
1117    files
1118}
1119
1120fn commit_files_between_trees(
1121    odb: &crate::odb::Odb,
1122    old_tree: Option<&ObjectId>,
1123    new_tree: &ObjectId,
1124) -> Result<Vec<CommitFile>> {
1125    let entries = diff_trees_with_renames(odb, old_tree, Some(new_tree), "", 50)?;
1126    Ok(commit_files_from_diff_entries(&entries))
1127}
1128
1129/// Files of a root commit, read from the index its tree was just written from: every path is
1130/// added, so this skips the whole-tree diff and its per-path entries.
1131///
1132/// Returns `None` when the index holds sparse-directory placeholders, whose files only the
1133/// tree lists.
1134fn root_commit_files_from_index(index: &Index) -> Option<Vec<CommitFile>> {
1135    let mut files = Vec::with_capacity(index.entries().len());
1136    for entry in index.entries() {
1137        if entry.mode == crate::index::MODE_TREE {
1138            return None;
1139        }
1140        if entry.stage() != 0 || entry.intent_to_add() {
1141            continue;
1142        }
1143        files.push(CommitFile {
1144            path: crate::repo_relpath::storage_string(&entry.path),
1145            status: DiffStatus::Added,
1146            old_path: None,
1147        });
1148    }
1149    files.sort_by(|a, b| a.path.cmp(&b.path));
1150    Some(files)
1151}
1152
1153fn commit_files_index_vs_parent_tree(
1154    odb: &crate::odb::Odb,
1155    index: &Index,
1156    parent_tree: Option<&ObjectId>,
1157) -> Result<Vec<CommitFile>> {
1158    if parent_tree.is_none() {
1159        if let Some(files) = root_commit_files_from_index(index) {
1160            return Ok(files);
1161        }
1162    }
1163    // The diff pairs and reports paths as lossy UTF-8: distinct non-UTF-8 names can collide, and
1164    // file lists must carry the `storage_string` form.
1165    if index
1166        .entries()
1167        .iter()
1168        .any(|e| std::str::from_utf8(&e.path).is_err())
1169    {
1170        return commit_files_from_raw_paths(odb, index, parent_tree);
1171    }
1172    let entries = diff_index_to_tree(odb, index, parent_tree, false)?;
1173    if entries.iter().all(diff_entry_paths_are_stored_exactly) {
1174        return Ok(commit_files_from_diff_entries(&entries));
1175    }
1176    commit_files_from_raw_paths(odb, index, parent_tree)
1177}
1178
1179/// Whether the lossy UTF-8 paths [`diff_index_to_tree`] reports equal the
1180/// [`crate::repo_relpath::storage_string`] form commit file lists use (tree-only paths can still
1181/// be non-UTF-8 when the index paths are not).
1182fn diff_entry_paths_are_stored_exactly(entry: &DiffEntry) -> bool {
1183    [entry.old_path.as_deref(), entry.new_path.as_deref()]
1184        .into_iter()
1185        .flatten()
1186        .all(|path| {
1187            !path.contains(char::REPLACEMENT_CHARACTER)
1188                && !path.starts_with(crate::repo_relpath::STORAGE_PREFIX)
1189        })
1190}
1191
1192/// Files that differ between `index` and `parent_tree`, comparing raw path bytes.
1193///
1194/// Reads every tree under `parent_tree`; used only when a changed path does not round-trip
1195/// through UTF-8.
1196fn commit_files_from_raw_paths(
1197    odb: &crate::odb::Odb,
1198    index: &Index,
1199    parent_tree: Option<&ObjectId>,
1200) -> Result<Vec<CommitFile>> {
1201    fn collect(
1202        odb: &crate::odb::Odb,
1203        tree: &ObjectId,
1204        prefix: &[u8],
1205        out: &mut BTreeMap<Vec<u8>, (u32, ObjectId)>,
1206    ) -> Result<()> {
1207        for entry in crate::objects::parse_tree(&odb.read(tree)?.data)? {
1208            let path = crate::repo_relpath::join_rel(prefix, &entry.name);
1209            if entry.mode == crate::index::MODE_TREE {
1210                collect(odb, &entry.oid, &path, out)?;
1211            } else {
1212                out.insert(path, (entry.mode, entry.oid));
1213            }
1214        }
1215        Ok(())
1216    }
1217
1218    let mut parent = BTreeMap::new();
1219    if let Some(tree) = parent_tree {
1220        collect(odb, tree, b"", &mut parent)?;
1221    }
1222    let mut files = Vec::new();
1223    for entry in index.entries() {
1224        if entry.stage() != 0 || entry.intent_to_add() {
1225            continue;
1226        }
1227        let status = match parent.remove(entry.path.as_slice()) {
1228            None => DiffStatus::Added,
1229            Some((old_mode, old_oid)) if old_oid != entry.oid || old_mode != entry.mode => {
1230                DiffStatus::for_content_change(old_mode, entry.mode)
1231            }
1232            Some(_) => continue,
1233        };
1234        files.push(CommitFile {
1235            path: crate::repo_relpath::storage_string(&entry.path),
1236            status,
1237            old_path: None,
1238        });
1239    }
1240    files.extend(parent.into_keys().map(|path| CommitFile {
1241        path: crate::repo_relpath::storage_string(&path),
1242        status: DiffStatus::Deleted,
1243        old_path: None,
1244    }));
1245    files.sort_by(|a, b| a.path.cmp(&b.path));
1246    Ok(files)
1247}
1248
1249struct MemOverlayGuard<'a>(&'a Odb);
1250
1251impl Drop for MemOverlayGuard<'_> {
1252    fn drop(&mut self) {
1253        self.0.disable_mem_overlay();
1254    }
1255}
1256
1257#[allow(clippy::too_many_arguments)]
1258fn finish_commit_dry_run(
1259    repo: &Repository,
1260    index: &mut Index,
1261    req: &CommitRequest,
1262    short_name: Option<String>,
1263    parent: Option<ObjectId>,
1264    parent_tree: Option<ObjectId>,
1265    merge_heads: Vec<ObjectId>,
1266    concluding_merge: bool,
1267    amend_author: Option<String>,
1268    amend_author_raw: Vec<u8>,
1269    amend_parents: Vec<ObjectId>,
1270    amend_default_message: Option<String>,
1271    req_amend: bool,
1272    reuse_author: Option<String>,
1273    reuse_author_raw: Vec<u8>,
1274    reuse_message: Option<String>,
1275) -> Result<CommitOutcome> {
1276    let files = commit_files_index_vs_parent_tree(repo.odb(), index, parent_tree.as_ref())?;
1277
1278    if !req.allow_empty && !req_amend {
1279        if parent_tree.is_none() && index.entries.is_empty() {
1280            return Err(empty_commit_error(repo, index, req));
1281        }
1282        if !concluding_merge && files.is_empty() {
1283            return Err(empty_commit_error(repo, index, req));
1284        }
1285    }
1286
1287    let mut message = if !req.message.trim().is_empty() {
1288        normalize_commit_message(&req.message)?
1289    } else if let Some(reuse_msg) = reuse_message {
1290        reuse_msg
1291    } else if req_amend {
1292        amend_default_message.unwrap_or_default()
1293    } else if let Some(pending) = pending_commit_message(repo)? {
1294        normalize_commit_message(&pending)?
1295    } else {
1296        return Err(CommitError::EmptyCommitMessage.into());
1297    };
1298    if message.trim().is_empty() {
1299        return Err(CommitError::EmptyCommitMessage.into());
1300    }
1301    if !message.ends_with('\n') {
1302        message.push('\n');
1303    }
1304    let config = repo.config().snapshot()?;
1305    let now = repo.identity_now();
1306    let committer = commit_identity_line(repo, req.committer.as_ref(), IdentRole::Committer, now)?;
1307    let message_with_trailers = enrich_commit_message(
1308        message,
1309        &req.trailers,
1310        req.signoff,
1311        &committer,
1312        config.as_ref(),
1313        repo.git_dir(),
1314    )?;
1315
1316    let (author, _author_raw) = resolve_author_for_commit(
1317        repo,
1318        req,
1319        &committer,
1320        amend_author,
1321        amend_author_raw,
1322        reuse_author,
1323        reuse_author_raw,
1324        req_amend,
1325    )?;
1326    let mut commit_parents = if req_amend {
1327        amend_parents
1328    } else {
1329        parent.into_iter().collect()
1330    };
1331    if !req_amend {
1332        for merge_head in merge_heads {
1333            if !commit_parents.iter().any(|p| p == &merge_head) {
1334                commit_parents.push(merge_head);
1335            }
1336        }
1337    }
1338    let author_info = author_info_from_header_line(&author);
1339    let committer_info = author_info_from_header_line(&committer);
1340    let changes = files.len();
1341
1342    Ok(CommitOutcome {
1343        oid: zero_oid(),
1344        branch: short_name,
1345        parent,
1346        parents: commit_parents,
1347        author: author_info,
1348        committer: committer_info,
1349        message: message_with_trailers,
1350        hooks_run: Vec::new(),
1351        changes,
1352        change_id: None,
1353        files,
1354        embedded_gitlinks: Vec::new(),
1355        rerere: Vec::new(),
1356    })
1357}
1358
1359#[allow(clippy::too_many_arguments)]
1360fn resolve_author_for_commit(
1361    repo: &Repository,
1362    req: &CommitRequest,
1363    committer: &str,
1364    amend_author: Option<String>,
1365    amend_author_raw: Vec<u8>,
1366    reuse_author: Option<String>,
1367    reuse_author_raw: Vec<u8>,
1368    req_amend: bool,
1369) -> Result<(String, Vec<u8>)> {
1370    let now = repo.identity_now();
1371    if req.reset_author {
1372        return Ok((
1373            author_line_from_committer(committer, req.author_date.as_deref(), now),
1374            Vec::new(),
1375        ));
1376    }
1377    if let Some(author) = req.author.as_ref() {
1378        author.validate()?;
1379        let user_line = author.header_line();
1380        if req.author_date.is_none() {
1381            if let Some(picked) = read_cherry_pick_head(repo.git_dir())? {
1382                let obj = repo.odb().read(&picked)?;
1383                if obj.kind == ObjectKind::Commit {
1384                    let picked_commit = parse_commit(&obj.data)?;
1385                    if let Ok((picked_line, _)) = prepare_commit_author_from_parent(
1386                        &picked_commit.author,
1387                        &picked_commit.author_raw,
1388                        None,
1389                        now,
1390                    ) {
1391                        if let Some(date_suffix) = picked_line.split('>').nth(1).map(str::trim) {
1392                            if !date_suffix.is_empty() {
1393                                return Ok((
1394                                    replace_identity_date_suffix(&user_line, date_suffix),
1395                                    Vec::new(),
1396                                ));
1397                            }
1398                        }
1399                    }
1400                }
1401            }
1402        }
1403        let author = prepare_commit_identity_line(&user_line, req.author_date.as_deref(), now)?;
1404        return Ok((author, Vec::new()));
1405    }
1406    if let Some(a) = reuse_author {
1407        return Ok(prepare_commit_author_from_parent(
1408            &a,
1409            &reuse_author_raw,
1410            req.author_date.as_deref(),
1411            now,
1412        )?);
1413    }
1414    if !req_amend && !req.reset_author && req.author.is_none() {
1415        if let Some(picked) = read_cherry_pick_head(repo.git_dir())? {
1416            let picked_commit = repo.odb().read_commit(&picked)?;
1417            return Ok(prepare_commit_author_from_parent(
1418                &picked_commit.author,
1419                &picked_commit.author_raw,
1420                req.author_date.as_deref(),
1421                now,
1422            )?);
1423        }
1424        if let Some(stopped) = read_grit_rebase_stopped_source(repo.git_dir())? {
1425            let stopped_commit = repo.odb().read_commit(&stopped)?;
1426            return Ok(prepare_commit_author_from_parent(
1427                &stopped_commit.author,
1428                &stopped_commit.author_raw,
1429                req.author_date.as_deref(),
1430                now,
1431            )?);
1432        }
1433    }
1434    if req_amend {
1435        let author = amend_author.unwrap_or_default();
1436        return Ok(prepare_commit_author_from_parent(
1437            &author,
1438            &amend_author_raw,
1439            req.author_date.as_deref(),
1440            now,
1441        )?);
1442    }
1443    let author = repo.identity(IdentRole::Author, now)?.header_line();
1444    let author = prepare_commit_identity_line(&author, req.author_date.as_deref(), now)?;
1445    Ok((author, Vec::new()))
1446}
1447
1448/// The committer (or author) header line for a new commit: `identity` when given, otherwise
1449/// the repository's identity for `role`.
1450fn commit_identity_line(
1451    repo: &Repository,
1452    identity: Option<&Signature>,
1453    role: IdentRole,
1454    now: time::OffsetDateTime,
1455) -> Result<String> {
1456    match identity {
1457        Some(signature) => {
1458            signature.validate()?;
1459            Ok(signature.header_line())
1460        }
1461        None => Ok(repo.identity(role, now)?.header_line()),
1462    }
1463}
1464
1465const NEXT_INDEX_FILE_PREFIX: &str = "next-index-";
1466
1467/// Reclaim `next-index-<pid>` hook index copies left when a commit process was killed.
1468///
1469/// Scans [`Repository::git_dir`], the common git directory when it differs, and each linked
1470/// worktree admin directory. Only removes files whose suffix is a decimal PID that is not the
1471/// current process and is not running on this host; non-numeric suffixes are left alone.
1472pub(crate) fn reap_stale_next_index_files(repo: &Repository, dry_run: bool) -> Result<usize> {
1473    let mut reaped = 0;
1474    for dir in next_index_git_dirs(repo)? {
1475        reaped += reap_stale_next_index_files_in_dir(&dir, dry_run)?;
1476    }
1477    Ok(reaped)
1478}
1479
1480fn next_index_git_dirs(repo: &Repository) -> Result<Vec<PathBuf>> {
1481    use crate::worktree::list_worktrees;
1482
1483    let git_dir = repo.git_dir().to_path_buf();
1484    let common = repo.common_git_dir().to_path_buf();
1485    let mut dirs = vec![git_dir.clone()];
1486    if common != git_dir {
1487        dirs.push(common);
1488    }
1489    for wt in list_worktrees(repo)? {
1490        if !dirs.iter().any(|d| d == &wt.admin_dir) {
1491            dirs.push(wt.admin_dir);
1492        }
1493    }
1494    Ok(dirs)
1495}
1496
1497fn reap_stale_next_index_files_in_dir(dir: &Path, dry_run: bool) -> Result<usize> {
1498    use crate::lockfile::is_process_running;
1499
1500    let current = u64::from(process::id());
1501    let entries = match fs::read_dir(dir) {
1502        Ok(entries) => entries,
1503        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(0),
1504        Err(e) => return Err(e.into()),
1505    };
1506    let mut reaped = 0;
1507    for entry in entries.flatten() {
1508        let name = entry.file_name();
1509        let name = name.to_string_lossy();
1510        let Some(pid_str) = name.strip_prefix(NEXT_INDEX_FILE_PREFIX) else {
1511            continue;
1512        };
1513        if pid_str.is_empty() || !pid_str.bytes().all(|b| b.is_ascii_digit()) {
1514            continue;
1515        }
1516        let Ok(pid) = pid_str.parse::<u64>() else {
1517            continue;
1518        };
1519        if pid == current || is_process_running(pid) {
1520            continue;
1521        }
1522        if dry_run {
1523            reaped += 1;
1524            continue;
1525        }
1526        let path = entry.path();
1527        if is_process_running(pid) {
1528            continue;
1529        }
1530        if fs::remove_file(&path).is_ok() {
1531            reaped += 1;
1532        }
1533    }
1534    Ok(reaped)
1535}
1536
1537/// Removes a partial-commit hook index file on drop (Git `next-index-<pid>`).
1538struct TempHookIndexFile(PathBuf);
1539
1540impl Drop for TempHookIndexFile {
1541    fn drop(&mut self) {
1542        let _ = fs::remove_file(&self.0);
1543    }
1544}
1545
1546/// Write a merge-continue (or other) commit from a caller-owned index.
1547///
1548/// The index must have no unmerged stages; it is written back with the new cache-tree.
1549pub(crate) fn create_commit_with_loaded_index(
1550    repo: &Repository,
1551    index: &mut Index,
1552    req: &CommitRequest,
1553    progress: &mut dyn ProgressSink,
1554    cancel: &CancelToken,
1555) -> Result<CommitOutcome> {
1556    if index.has_unmerged_entries() {
1557        return Err(IndexError::unmerged().into());
1558    }
1559    let head = resolve_head_for_repository(repo)?;
1560    create_commit_with_index(repo, head, index, req, progress, cancel, None)
1561}
1562
1563/// Record a commit of `index` on top of `head`.
1564///
1565/// `head` must be read before the content `index` was built from: the branch update then
1566/// compares against that same tip, so a commit landed by another process in between makes this
1567/// one fail instead of silently reverting it.
1568///
1569/// Cancellation is checked before anything is written, while commit hooks run (including a
1570/// long-running `pre-commit`), and again before the commit object is written; once the object is
1571/// written the ref update always follows.
1572#[allow(clippy::too_many_arguments)]
1573fn create_commit_with_index(
1574    repo: &Repository,
1575    head: HeadState,
1576    index: &mut Index,
1577    req: &CommitRequest,
1578    progress: &mut dyn ProgressSink,
1579    cancel: &CancelToken,
1580    persist_index: Option<LockedIndex>,
1581) -> Result<CommitOutcome> {
1582    poll_cancel(progress, cancel)?;
1583    let (refname, short_name, mut parent) = match head {
1584        HeadState::Branch {
1585            refname,
1586            short_name,
1587            oid,
1588        } => (refname, Some(short_name), oid),
1589        HeadState::Detached { oid } => ("HEAD".to_owned(), None, Some(oid)),
1590        HeadState::Invalid => {
1591            return Err(Error::Ref(RefError::InvalidHead));
1592        }
1593    };
1594
1595    let mut amend_parents = Vec::new();
1596    let mut amend_author = None;
1597    let mut amend_author_raw = Vec::new();
1598    let mut amend_extra_headers = Vec::new();
1599    let mut amend_default_message = None;
1600    let mut replaced_tip = None;
1601    let mut reuse_author = None;
1602    let mut reuse_author_raw = Vec::new();
1603    let mut reuse_message = None;
1604    if let Some(reuse_oid) = req.reuse_message_from {
1605        let source = repo.odb().read_commit(&reuse_oid)?;
1606        reuse_message = Some(source.message);
1607        reuse_author = Some(source.author);
1608        reuse_author_raw = source.author_raw;
1609    }
1610    if req.amend {
1611        if replay_blocks_partial_commit(repo.git_dir())? {
1612            return Err(CommitError::PartialCommitDuringReplay.into());
1613        }
1614        let Some(tip) = parent.take() else {
1615            return Err(CommitError::AmendUnborn.into());
1616        };
1617        let old = repo.odb().read_commit(&tip)?;
1618        amend_parents = old.parents.clone();
1619        parent = old.parents.first().copied();
1620        amend_author = Some(old.author);
1621        amend_author_raw = old.author_raw;
1622        amend_extra_headers = extra_headers_without_commit_signatures(&old.extra_headers);
1623        amend_default_message = Some(old.message);
1624        replaced_tip = Some(tip);
1625    }
1626
1627    if index.has_unmerged_entries() {
1628        return Err(IndexError::unmerged().into());
1629    }
1630    let merge_heads = read_merge_heads(repo.git_dir())?;
1631    let concluding_merge = !merge_heads.is_empty();
1632    let index_path = repo.index_path_for_env()?;
1633    let parent_tree = parent
1634        .as_ref()
1635        .map(|parent_oid| repo.odb().commit_tree(parent_oid))
1636        .transpose()?;
1637
1638    // A dry run derives its file list from the same index-vs-parent diff and rejects an empty
1639    // one there, so it skips this pass.
1640    if !req.dry_run && !req.allow_empty && !req.amend && !concluding_merge {
1641        let skip_tree_match = req.assume_worktree_synced && req.skip_pre_commit_tree_match;
1642        if !skip_tree_match {
1643            if let Some(ref old) = parent_tree {
1644                if index_staged_tree_matches(repo.odb(), index, old) {
1645                    return Err(empty_commit_error(repo, index, req));
1646                }
1647            } else if index.entries.is_empty() {
1648                return Err(empty_commit_error(repo, index, req));
1649            }
1650        }
1651    }
1652
1653    if req.dry_run {
1654        return finish_commit_dry_run(
1655            repo,
1656            index,
1657            req,
1658            short_name,
1659            parent,
1660            parent_tree,
1661            merge_heads,
1662            concluding_merge,
1663            amend_author,
1664            amend_author_raw,
1665            amend_parents,
1666            amend_default_message,
1667            req.amend,
1668            reuse_author,
1669            reuse_author_raw,
1670            reuse_message,
1671        );
1672    }
1673
1674    let persist_through_lock = persist_index.is_some();
1675    let _temp_hook_index_guard = if persist_through_lock {
1676        let path = repo.git_dir().join(format!("next-index-{}", process::id()));
1677        repo.write_index_at(&path, index)?;
1678        Some(TempHookIndexFile(path))
1679    } else {
1680        repo.write_index(index)?;
1681        None
1682    };
1683
1684    let temp_hook_index_path = _temp_hook_index_guard.as_ref().map(|g| g.0.clone());
1685
1686    let hook_index_path: PathBuf = temp_hook_index_path
1687        .clone()
1688        .unwrap_or_else(|| index_path.clone());
1689
1690    let commit_env = CommitHookEnv {
1691        index_file: Some(hook_index_path.as_path()),
1692        git_editor: Some(":"),
1693        git_prefix: None,
1694        extra_env: &[],
1695    };
1696    let mut hooks_run = Vec::new();
1697    if req.hooks != HookPolicy::SkipVerify
1698        && run_commit_hook_recorded(repo, HookName::PreCommit, &[], None, &commit_env, cancel)?
1699    {
1700        hooks_run.push(HookName::PreCommit);
1701    }
1702
1703    if !req.amend && grit_rebase_conflict_stop_active(repo.git_dir()) {
1704        persist_rebase_stopped_head_if_missing(repo)?;
1705    }
1706
1707    let message_source = if req.message_from_merge {
1708        MessageSource::Merge
1709    } else if !req.message.trim().is_empty() {
1710        MessageSource::Message
1711    } else if let Some(oid) = req.reuse_message_from.or(replaced_tip) {
1712        MessageSource::Commit(oid)
1713    } else if repo.git_dir().join("SQUASH_MSG").is_file() {
1714        MessageSource::Squash
1715    } else {
1716        MessageSource::Merge
1717    };
1718    let mut message = if !req.message.trim().is_empty() {
1719        normalize_commit_message(&req.message)?
1720    } else if let Some(reuse_msg) = reuse_message {
1721        reuse_msg
1722    } else if req.amend {
1723        amend_default_message.unwrap_or_default()
1724    } else if let Some(pending) = pending_commit_message(repo)? {
1725        normalize_commit_message(&pending)?
1726    } else {
1727        return Err(CommitError::EmptyCommitMessage.into());
1728    };
1729    if message.trim().is_empty() {
1730        return Err(CommitError::EmptyCommitMessage.into());
1731    }
1732    if !message.ends_with('\n') {
1733        message.push('\n');
1734    }
1735    let config = repo.config().snapshot()?;
1736    let now = repo.identity_now();
1737    let committer = commit_identity_line(repo, req.committer.as_ref(), IdentRole::Committer, now)?;
1738    message = enrich_commit_message(
1739        message,
1740        &req.trailers,
1741        req.signoff,
1742        &committer,
1743        config.as_ref(),
1744        repo.git_dir(),
1745    )?;
1746    let editmsg_path = repo.git_dir().join("COMMIT_EDITMSG");
1747    fs::write(&editmsg_path, &message).map_err(Error::Io)?;
1748    // COMMIT_EDITMSG is shared by every committer in the repository, so it is only read back
1749    // when a hook may have edited it; otherwise the in-memory message wins.
1750    if let Some(edited) = run_commit_message_hooks(
1751        repo,
1752        &editmsg_path,
1753        message_source,
1754        req.hooks,
1755        &commit_env,
1756        &mut hooks_run,
1757        cancel,
1758    )? {
1759        message = edited;
1760    }
1761
1762    let (author, author_raw) = resolve_author_for_commit(
1763        repo,
1764        req,
1765        &committer,
1766        amend_author,
1767        amend_author_raw,
1768        reuse_author,
1769        reuse_author_raw,
1770        req.amend,
1771    )?;
1772
1773    let tree = write_tree_update_index(repo.odb(), index, "", WriteTreeFlags::silent())?;
1774    let root_files = parent_tree
1775        .is_none()
1776        .then(|| root_commit_files_from_index(index))
1777        .flatten();
1778    let commit_files = match root_files {
1779        Some(files) => files,
1780        None => commit_files_between_trees(repo.odb(), parent_tree.as_ref(), &tree)?,
1781    };
1782
1783    if !req.allow_empty && !req.amend {
1784        if parent_tree.is_none() && is_empty_tree_oid(repo.odb(), &tree) {
1785            return Err(empty_commit_error(repo, index, req));
1786        }
1787        if !concluding_merge {
1788            if let Some(ref old) = parent_tree {
1789                if old == &tree {
1790                    return Err(empty_commit_error(repo, index, req));
1791                }
1792            }
1793        }
1794    }
1795
1796    let mut commit_parents = if req.amend {
1797        amend_parents
1798    } else {
1799        parent.into_iter().collect()
1800    };
1801    if !req.amend {
1802        for merge_head in merge_heads {
1803            if !commit_parents.iter().any(|p| p == &merge_head) {
1804                commit_parents.push(merge_head);
1805            }
1806        }
1807    }
1808    let author_info = author_info_from_header_line(&author);
1809    let mut commit_data = CommitData {
1810        tree,
1811        parents: commit_parents.clone(),
1812        author,
1813        committer: committer.clone(),
1814        author_raw,
1815        committer_raw: Vec::new(),
1816        encoding: None,
1817        message,
1818        raw_message: None,
1819        extra_headers: amend_extra_headers,
1820    };
1821    let policy = ChangeIdPolicy::from_config(config.as_ref());
1822    if policy.enabled() {
1823        if req.amend {
1824            if change_id(&commit_data).is_none() {
1825                if let Some(tip) = replaced_tip {
1826                    set_change_id(&mut commit_data, &ChangeId::derived_from_commit_id(&tip));
1827                }
1828            }
1829        } else if let Some(stopped) = read_grit_rebase_stopped_source(repo.git_dir())? {
1830            let template = repo.odb().read_commit(&stopped)?;
1831            let id =
1832                change_id(&template).unwrap_or_else(|| ChangeId::derived_from_commit_id(&stopped));
1833            set_change_id(&mut commit_data, &id);
1834        } else {
1835            stamp_change_id_on_new_commit(repo, &policy, &mut commit_data)?;
1836        }
1837    }
1838    let bytes = prepare_commit_bytes(repo, &commit_data, req.sign_override)?;
1839    fsck_commit_idents(&bytes, repo.odb().hash_algo()).map_err(|check| ObjectError::Invalid {
1840        kind: ObjectKind::Commit,
1841        check,
1842    })?;
1843    poll_cancel(progress, cancel)?;
1844    let oid = repo.odb().write(ObjectKind::Commit, &bytes)?;
1845    repo.odb().flush_for_publish()?;
1846
1847    let amend_notes_rewrite: Option<NotesRewritePlan> =
1848        if let Some(old_tip) = replaced_tip.filter(|_| req.amend && req.post_rewrite.enabled()) {
1849            prepare_notes_for_rewrite(repo, NotesRewriteCommand::Amend, &[(old_tip, oid)])?
1850        } else {
1851            None
1852        };
1853
1854    let concluding_replay = read_cherry_pick_head(repo.git_dir())?.is_some()
1855        || read_revert_head(repo.git_dir())?.is_some();
1856    let previous_tip = replaced_tip.or(parent);
1857    let reflog_old = previous_tip.unwrap_or_else(zero_oid);
1858    let subject = commit_subject(&commit_data.message);
1859    let reflog_msg = if req.amend {
1860        format!("commit (amend): {subject}")
1861    } else if concluding_replay && read_cherry_pick_head(repo.git_dir())?.is_some() {
1862        format!("commit (cherry-pick): {subject}")
1863    } else if parent.is_some() {
1864        format!("commit: {subject}")
1865    } else {
1866        format!("commit (initial): {subject}")
1867    };
1868
1869    let expected_old = previous_tip.or_else(|| {
1870        matches!(repo.references().resolve_if_exists(&refname), Ok(Some(_))).then_some(reflog_old)
1871    });
1872
1873    if !persist_through_lock {
1874        if !req.assume_worktree_synced {
1875            if let Some(work_tree) = repo.work_tree() {
1876                let rules = WorktreeRules::from_repository(repo, index).ok();
1877                let rules_arc = rules.map(|r| Arc::new(Mutex::new(r)));
1878                let _ = refresh_index_stat_content_verified_with_rules(
1879                    repo.odb(),
1880                    repo.git_dir(),
1881                    index,
1882                    work_tree,
1883                    None,
1884                    Some(config.as_ref()),
1885                    None,
1886                    rules_arc.as_ref(),
1887                )?;
1888            }
1889        }
1890        repo.write_index(index)?;
1891    }
1892
1893    let changes = if parent_tree.as_ref() == Some(&tree) {
1894        0
1895    } else if !commit_files.is_empty() {
1896        commit_files.len()
1897    } else if req.assume_worktree_synced && req.skip_pre_commit_tree_match {
1898        // Large-index commits skip the tree diff for speed (issue #1064); smaller repos keep
1899        // accurate path counts for pre-staged and JSON output.
1900        const LARGE_INDEX_CHANGE_COUNT_FAST_PATH: usize = 4096;
1901        let large_index = index.entries.len() >= LARGE_INDEX_CHANGE_COUNT_FAST_PATH;
1902        if large_index {
1903            if let Some(n) = req.staged_change_count.filter(|&n| n > 0) {
1904                n
1905            } else {
1906                diff_tree_path_change_count(repo.odb(), parent_tree.as_ref(), Some(&tree), "")?
1907            }
1908        } else {
1909            diff_tree_path_change_count(repo.odb(), parent_tree.as_ref(), Some(&tree), "")?
1910        }
1911    } else {
1912        diff_tree_path_change_count(repo.odb(), parent_tree.as_ref(), Some(&tree), "")?
1913    };
1914
1915    if short_name.is_none() {
1916        update_detached_head_for_commit_on_store(
1917            repo.ref_store(),
1918            expected_old,
1919            oid,
1920            &committer,
1921            &reflog_msg,
1922            config.as_ref(),
1923        )?;
1924    } else {
1925        update_branch_for_commit_on_store(
1926            repo.ref_store(),
1927            &BranchCommitRefUpdate {
1928                branch_ref: RefNameRef::from_trusted(refname.as_str()),
1929                expected_old,
1930                new_oid: oid,
1931                identity: &committer,
1932                reflog_message: &reflog_msg,
1933            },
1934            config.as_ref(),
1935        )?;
1936    }
1937
1938    let mut rerere_events = Vec::new();
1939    if concluding_merge {
1940        rerere_events = finish_merge_state(repo)?.rerere;
1941    } else {
1942        let conclude_rerere = squash_conflict_merge_in_progress(repo.git_dir())
1943            || grit_rebase_conflict_stop_active(repo.git_dir())
1944            || concluding_replay;
1945        if conclude_rerere {
1946            rerere_events = crate::rerere::finish_merge_rerere(repo)?;
1947        }
1948    }
1949    if concluding_replay {
1950        finish_replay_commit_state(repo, oid)?;
1951    }
1952    clear_squash_commit_state(repo.git_dir())?;
1953
1954    if let Some(LockedIndex {
1955        index: mut separate,
1956        mut lock,
1957    }) = persist_index
1958    {
1959        let persist = separate.as_mut().unwrap_or(index);
1960        if !req.assume_worktree_synced {
1961            if let Some(work_tree) = repo.work_tree() {
1962                let rules = WorktreeRules::from_repository(repo, persist).ok();
1963                let rules_arc = rules.map(|r| Arc::new(Mutex::new(r)));
1964                let _ = refresh_index_stat_content_verified_with_rules(
1965                    repo.odb(),
1966                    repo.git_dir(),
1967                    persist,
1968                    work_tree,
1969                    None,
1970                    Some(config.as_ref()),
1971                    None,
1972                    rules_arc.as_ref(),
1973                )?;
1974            }
1975        }
1976        repo.write_index_with_lock(&mut lock, persist, false)?;
1977    }
1978
1979    let post_commit_env = CommitHookEnv {
1980        index_file: Some(
1981            temp_hook_index_path
1982                .as_deref()
1983                .unwrap_or(index_path.as_path()),
1984        ),
1985        git_editor: Some(":"),
1986        git_prefix: None,
1987        extra_env: &[],
1988    };
1989    if run_advisory_hook(
1990        repo,
1991        HookName::PostCommit,
1992        &[],
1993        None,
1994        Some(&post_commit_env),
1995    ) {
1996        hooks_run.push(HookName::PostCommit);
1997    }
1998    if let Some(old_tip) = replaced_tip.filter(|_| req.post_rewrite.enabled()) {
1999        if let Some(notes_plan) = amend_notes_rewrite.as_ref() {
2000            apply_prepared_notes_rewrite(repo, notes_plan, &[(old_tip, oid)])?;
2001        }
2002        if run_post_rewrite(repo, RewriteKind::Amend, &[(old_tip, oid)]) {
2003            hooks_run.push(HookName::PostRewrite);
2004        }
2005    }
2006
2007    let stored_change_id = change_id(&commit_data);
2008    let committer_info = author_info_from_header_line(&commit_data.committer);
2009    Ok(CommitOutcome {
2010        oid,
2011        branch: short_name,
2012        parent,
2013        parents: commit_data.parents,
2014        author: author_info,
2015        committer: committer_info,
2016        message: commit_data.message.clone(),
2017        hooks_run,
2018        changes,
2019        change_id: stored_change_id,
2020        files: commit_files,
2021        embedded_gitlinks: Vec::new(),
2022        rerere: rerere_events,
2023    })
2024}
2025
2026/// When [`ChangeIdPolicy`] is enabled, assign a fresh id to a newly written commit.
2027///
2028/// Does not run on amends or history rewrites; callers pass an empty `extra_headers`
2029/// so source change ids never carry over (pick, revert, clean merge).
2030///
2031/// # Errors
2032///
2033/// Propagates change-id generation failures as [`CommitError::ChangeId`].
2034pub(crate) fn stamp_change_id_on_new_commit(
2035    repo: &Repository,
2036    policy: &ChangeIdPolicy,
2037    data: &mut CommitData,
2038) -> Result<()> {
2039    if let Some(id) = policy
2040        .id_for_new_commit(
2041            data,
2042            repo.odb().hash_algo(),
2043            repo.change_id_generator().as_ref(),
2044        )
2045        .map_err(CommitError::ChangeId)?
2046    {
2047        set_change_id(data, &id);
2048    }
2049    Ok(())
2050}
2051
2052/// Serialize `data` and sign the bytes when [`should_sign_commit`] says so.
2053///
2054/// Does not assign change ids. Callers that need a `change-id` header (for example
2055/// [`create_commit`]) set it with [`crate::change_id::set_change_id`] first. Stash,
2056/// notes, and other auxiliary commits use this path without adding ids.
2057///
2058/// # Errors
2059///
2060/// Propagates signing and config errors from [`GpgConfig::from_config`] and
2061/// [`sign_serialized_commit`].
2062pub(crate) fn prepare_commit_bytes(
2063    repo: &Repository,
2064    data: &CommitData,
2065    sign_override: Option<bool>,
2066) -> Result<Vec<u8>> {
2067    let config = repo.config().snapshot()?;
2068    let unsigned = serialize_commit(data);
2069    if !should_sign_commit(config.as_ref(), sign_override)? {
2070        return Ok(unsigned);
2071    }
2072    let gpg = GpgConfig::from_config(config.as_ref())?.with_command_runner(repo.command_runner());
2073    sign_serialized_commit(
2074        &gpg,
2075        &unsigned,
2076        &data.committer,
2077        None,
2078        repo.odb().hash_algo(),
2079    )
2080}
2081
2082/// Write a commit object to the ODB, honoring `commit.gpgsign` and `sign_override`.
2083///
2084/// Does not assign change ids; see [`prepare_commit_bytes`].
2085///
2086/// # Errors
2087///
2088/// Same as [`prepare_commit_bytes`], plus object-database write failures.
2089pub(crate) fn write_commit_object(
2090    repo: &Repository,
2091    data: &CommitData,
2092    sign_override: Option<bool>,
2093) -> Result<ObjectId> {
2094    let bytes = prepare_commit_bytes(repo, data, sign_override)?;
2095    let oid = repo.odb().write(ObjectKind::Commit, &bytes)?;
2096    repo.odb().flush_for_publish()?;
2097    Ok(oid)
2098}
2099
2100fn empty_commit_error(repo: &Repository, index: &mut Index, req: &CommitRequest) -> Error {
2101    if req.index_only {
2102        let mut worktree_index = match repo.load_index() {
2103            Ok(real) => real,
2104            Err(_) => index.clone(),
2105        };
2106        if let Ok((unstaged, untracked)) =
2107            crate::porcelain::status::count_unstaged_and_untracked_paths(repo, &mut worktree_index)
2108        {
2109            if unstaged + untracked > 0 {
2110                return CommitError::NothingStagedToCommit {
2111                    unstaged,
2112                    untracked,
2113                }
2114                .into();
2115            }
2116        }
2117    }
2118    CommitError::NothingToCommit.into()
2119}
2120
2121/// True when stage-0 index entries describe `tree_oid`, using a valid cache-tree when present.
2122fn index_staged_tree_matches(
2123    odb: &crate::odb::Odb,
2124    index: &crate::index::Index,
2125    tree_oid: &ObjectId,
2126) -> bool {
2127    if index.cache_tree_root == Some(*tree_oid)
2128        && cache_tree_extension_valid(index.cache_tree.as_ref())
2129    {
2130        return true;
2131    }
2132    crate::diff::diff_index_to_tree(odb, index, Some(tree_oid), false)
2133        .map(|d| d.is_empty())
2134        .unwrap_or(false)
2135}
2136
2137fn commit_subject(message: &str) -> &str {
2138    message.split('\n').next().unwrap_or("").trim_end()
2139}
2140
2141/// Path passed as `argv[1]` to the `commit-msg` hook (Git: `.git/COMMIT_EDITMSG` when possible).
2142fn commit_editmsg_hook_argument(repo: &Repository, editmsg_path: &Path) -> String {
2143    if let Some(wt) = repo.work_tree() {
2144        if let Ok(rel) = editmsg_path.strip_prefix(wt) {
2145            let s = rel.to_string_lossy();
2146            if !s.is_empty() {
2147                return s.replace('\\', "/");
2148            }
2149        }
2150    }
2151    editmsg_path.to_string_lossy().into_owned()
2152}
2153
2154#[cfg(test)]
2155mod tests {
2156    #![allow(clippy::expect_used, clippy::unwrap_used)]
2157    use crate::worktree::WorktreeError;
2158
2159    use crate::environment::RepositoryOptions;
2160
2161    use super::*;
2162    use crate::error::Error;
2163    use crate::index::{entry_from_stat, Index, MODE_REGULAR};
2164    use crate::objects::ObjectKind;
2165    use crate::pathspec::{Pathspec, PathspecGlobalFlags};
2166    use crate::porcelain::add::{stage, StageOptions};
2167    use crate::progress::NullProgress;
2168    use crate::reflog::read_reflog;
2169    use crate::refs::resolve_ref;
2170    use crate::test_support::inject::{
2171        set_test_inject_index_write_fail, set_test_inject_reflog_fail,
2172    };
2173    use crate::write_tree::{cache_tree_fully_valid, verify_cache_tree};
2174    use std::fs;
2175    use std::io::Write;
2176    use std::path::Path;
2177    use std::process::Command;
2178    use std::str::FromStr;
2179    use tempfile::TempDir;
2180
2181    fn init_repo(root: &Path) -> Repository {
2182        let git = root.join(".git");
2183        fs::create_dir_all(git.join("objects")).unwrap();
2184        fs::create_dir_all(git.join("refs/heads")).unwrap();
2185        fs::write(git.join("HEAD"), "ref: refs/heads/main\n").unwrap();
2186        fs::write(
2187            git.join("config"),
2188            "[core]\n\trepositoryformatversion = 0\n\tbare = false\n\tlogAllRefUpdates = true\n",
2189        )
2190        .unwrap();
2191        Repository::open(&git, &RepositoryOptions::empty().with_work_tree(root)).unwrap()
2192    }
2193
2194    fn ident() -> String {
2195        "Test User <t@example.com> 1 +0000".to_owned()
2196    }
2197
2198    fn stage_file_in_index(repo: &Repository, index: &mut Index, rel: &str, contents: &[u8]) {
2199        let wt = repo.work_tree().unwrap();
2200        let abs = wt.join(rel);
2201        if let Some(parent) = abs.parent() {
2202            fs::create_dir_all(parent).unwrap();
2203        }
2204        fs::write(&abs, contents).unwrap();
2205        let oid = repo.odb().write(ObjectKind::Blob, contents).unwrap();
2206        let entry = entry_from_stat(&abs, rel.as_bytes(), oid, MODE_REGULAR).unwrap();
2207        index.add_or_replace(entry);
2208    }
2209
2210    fn write_index(repo: &Repository, index: &mut Index) {
2211        index.sort();
2212        repo.write_index(index).unwrap();
2213    }
2214
2215    #[test]
2216    fn reap_stale_next_index_files_removes_dead_pid_only() {
2217        let dir = TempDir::new().unwrap();
2218        let repo = init_repo(dir.path());
2219        let git = repo.git_dir();
2220        let dead_pid = 99_999_999_u64;
2221        let live_pid = u64::from(std::process::id());
2222        fs::write(git.join(format!("next-index-{dead_pid}")), b"orphan").unwrap();
2223        fs::write(git.join(format!("next-index-{live_pid}")), b"live").unwrap();
2224        fs::write(git.join("next-index-not-a-pid"), b"weird").unwrap();
2225        assert_eq!(reap_stale_next_index_files(&repo, false).unwrap(), 1);
2226        assert!(!git.join(format!("next-index-{dead_pid}")).exists());
2227        assert!(git.join(format!("next-index-{live_pid}")).exists());
2228        assert!(git.join("next-index-not-a-pid").exists());
2229    }
2230
2231    #[test]
2232    fn begin_index_update_reaps_stale_next_index_file() {
2233        let dir = TempDir::new().unwrap();
2234        let repo = init_repo(dir.path());
2235        let dead = repo.git_dir().join("next-index-99999998");
2236        fs::write(&dead, b"x").unwrap();
2237        let _lock = repo.begin_index_update().unwrap();
2238        assert!(!dead.exists());
2239    }
2240
2241    #[test]
2242    fn root_commit_files_from_index_match_the_tree_diff() {
2243        let dir = TempDir::new().unwrap();
2244        let repo = init_repo(dir.path());
2245        let mut index = Index::new();
2246        for rel in ["a.txt", "dir/sub/b.txt", "dir-x.txt", "z/last.txt"] {
2247            stage_file_in_index(&repo, &mut index, rel, rel.as_bytes());
2248        }
2249        let template = index.get(b"a.txt", 0).unwrap().clone();
2250        let with_path = |path: &[u8], mode: u32, oid: ObjectId| {
2251            let mut entry = template.clone();
2252            entry.path = path.to_vec();
2253            entry.flags = path.len() as u16;
2254            entry.mode = mode;
2255            entry.oid = oid;
2256            entry
2257        };
2258        let blob = repo.odb().write(ObjectKind::Blob, b"raw\n").unwrap();
2259        index.add_or_replace(with_path(b"bin\xff.txt", MODE_REGULAR, blob));
2260        let gitlink = ObjectId::from_hex("1111111111111111111111111111111111111111").unwrap();
2261        index.add_or_replace(with_path(b"module", crate::index::MODE_GITLINK, gitlink));
2262        let mut ita = with_path(b"ita.txt", MODE_REGULAR, blob);
2263        ita.set_intent_to_add(true);
2264        index.add_or_replace(ita);
2265        index.sort();
2266
2267        let tree =
2268            write_tree_update_index(repo.odb(), &mut index, "", WriteTreeFlags::silent()).unwrap();
2269        let from_tree = commit_files_between_trees(repo.odb(), None, &tree).unwrap();
2270        let from_index = root_commit_files_from_index(&index).expect("no sparse placeholders");
2271        assert_eq!(from_index.len(), 6);
2272        assert_eq!(from_index, from_tree);
2273
2274        let mut placeholder = with_path(b"sparse/", crate::index::MODE_TREE, tree);
2275        placeholder.set_skip_worktree(true);
2276        index.add_or_replace(placeholder);
2277        assert!(root_commit_files_from_index(&index).is_none());
2278    }
2279
2280    fn commit_req(message: &str) -> CommitRequest {
2281        let ident = ident();
2282        let sig: crate::ident::Signature = ident.parse().expect("signature");
2283        let mut req = CommitRequest::new(message);
2284        req.author = Some(sig.clone());
2285        req.committer = Some(sig);
2286        req
2287    }
2288
2289    fn repo_snapshot(repo: &Repository) -> (Vec<u8>, String, usize, bool, usize) {
2290        let index_path = repo.git_dir().join("index");
2291        let index_bytes = fs::read(&index_path).unwrap_or_default();
2292        let head = fs::read_to_string(repo.git_dir().join("HEAD")).unwrap_or_default();
2293        let reflog_len = read_reflog(repo.git_dir(), "refs/heads/main")
2294            .map(|e| e.len())
2295            .unwrap_or(0);
2296        let editmsg = repo.git_dir().join("COMMIT_EDITMSG").exists();
2297        let mut objects = 0usize;
2298        if let Ok(entries) = fs::read_dir(repo.git_dir().join("objects")) {
2299            for entry in entries.flatten() {
2300                let path = entry.path();
2301                if path.is_dir() && path.file_name().is_some_and(|n| n.len() == 2) {
2302                    objects += fs::read_dir(path).map(|d| d.count()).unwrap_or(0);
2303                } else if path.is_file() {
2304                    objects += 1;
2305                }
2306            }
2307        }
2308        (index_bytes, head, reflog_len, editmsg, objects)
2309    }
2310
2311    fn dry_run_req(message: &str) -> CommitRequest {
2312        let mut req = commit_req(message);
2313        req.dry_run = true;
2314        req
2315    }
2316
2317    fn assert_commit_with_scope_err(
2318        repo: &Repository,
2319        req: &CommitRequest,
2320        scope: CommitScope,
2321        f: impl FnOnce(&Error),
2322    ) {
2323        let err = commit_with_scope(
2324            repo,
2325            req,
2326            scope,
2327            &mut NullProgress,
2328            &crate::progress::CancelToken::never(),
2329        )
2330        .unwrap_err();
2331        f(&err);
2332    }
2333
2334    #[cfg(unix)]
2335    #[test]
2336    fn dry_run_includes_mode_only_and_mixed_worktree_changes() {
2337        use std::os::unix::fs::PermissionsExt;
2338
2339        let tmp = TempDir::new().unwrap();
2340        let root = tmp.path();
2341        let repo = init_repo(root);
2342        fs::write(root.join("c"), b"c\n").unwrap();
2343        fs::write(root.join("s"), b"s\n").unwrap();
2344        commit_worktree(
2345            &repo,
2346            &commit_req("base"),
2347            &mut NullProgress,
2348            &crate::progress::CancelToken::never(),
2349        )
2350        .unwrap();
2351        let before = repo_snapshot(&repo);
2352        let before_tip = resolve_ref(repo.git_dir(), "refs/heads/main").unwrap();
2353
2354        let mut perms = fs::metadata(root.join("c")).unwrap().permissions();
2355        perms.set_mode(0o100755);
2356        fs::set_permissions(root.join("c"), perms).unwrap();
2357
2358        let preview = commit_worktree(
2359            &repo,
2360            &dry_run_req("mode"),
2361            &mut NullProgress,
2362            &crate::progress::CancelToken::never(),
2363        )
2364        .unwrap();
2365        assert_eq!(preview.changes, 1);
2366        assert_eq!(preview.files.len(), 1);
2367        assert_eq!(preview.files[0].path, "c");
2368        assert_eq!(preview.files[0].status, DiffStatus::Modified);
2369        assert_eq!(repo_snapshot(&repo), before);
2370        assert_eq!(
2371            resolve_ref(repo.git_dir(), "refs/heads/main").unwrap(),
2372            before_tip
2373        );
2374
2375        fs::OpenOptions::new()
2376            .append(true)
2377            .open(root.join("s"))
2378            .unwrap()
2379            .write_all(b"n\n")
2380            .unwrap();
2381
2382        let preview = commit_worktree(
2383            &repo,
2384            &dry_run_req("mixed"),
2385            &mut NullProgress,
2386            &crate::progress::CancelToken::never(),
2387        )
2388        .unwrap();
2389        assert_eq!(preview.changes, 2);
2390        let paths: Vec<_> = preview.files.iter().map(|f| f.path.as_str()).collect();
2391        assert!(paths.contains(&"c"));
2392        assert!(paths.contains(&"s"));
2393
2394        let committed = commit_worktree(
2395            &repo,
2396            &commit_req("mixed"),
2397            &mut NullProgress,
2398            &crate::progress::CancelToken::never(),
2399        )
2400        .unwrap();
2401        assert_eq!(committed.files, preview.files);
2402    }
2403
2404    #[cfg(unix)]
2405    #[test]
2406    fn parallel_symlink_worktree_preview_is_clean_or_matches_commit() {
2407        use crate::parallel::ThreadPolicy;
2408        use std::os::unix::fs::symlink;
2409
2410        let tmp = TempDir::new().unwrap();
2411        let root = tmp.path();
2412        let repo = init_repo(root);
2413        fs::create_dir(root.join("files")).unwrap();
2414        for n in 0..1024 {
2415            fs::write(root.join(format!("files/{n}")), b"data\n").unwrap();
2416        }
2417        for (path, target) in [
2418            ("linkdir", "files"),
2419            ("linkfile", "files/0"),
2420            ("linkmissing", "missing"),
2421        ] {
2422            symlink(target, root.join(path)).unwrap();
2423        }
2424        commit_worktree(
2425            &repo,
2426            &commit_req("initial"),
2427            &mut NullProgress,
2428            &crate::progress::CancelToken::never(),
2429        )
2430        .unwrap();
2431        let mut index = repo.load_index().unwrap();
2432        for entry in &mut index.entries {
2433            entry.mtime_sec = 0;
2434            entry.mtime_nsec = 0;
2435            entry.size = 0;
2436        }
2437        repo.write_index(&mut index).unwrap();
2438        let before = repo_snapshot(&repo);
2439        let before_tip = resolve_ref(repo.git_dir(), "refs/heads/main").unwrap();
2440        for threads in [1, 4] {
2441            let repo = Repository::open(
2442                repo.git_dir(),
2443                &RepositoryOptions::empty().with_work_tree(root),
2444            )
2445            .unwrap()
2446            .with_thread_policy(ThreadPolicy::with_threads_override(Some(threads)));
2447            let err = commit_worktree(
2448                &repo,
2449                &dry_run_req("clean"),
2450                &mut NullProgress,
2451                &crate::progress::CancelToken::never(),
2452            )
2453            .unwrap_err();
2454            assert!(
2455                matches!(err, Error::Commit(CommitError::NothingToCommit)),
2456                "{err:?}"
2457            );
2458            assert_eq!(repo_snapshot(&repo), before);
2459            assert_eq!(
2460                resolve_ref(repo.git_dir(), "refs/heads/main").unwrap(),
2461                before_tip
2462            );
2463        }
2464        for (path, target) in [
2465            ("linkdir", "."),
2466            ("linkfile", "files/1"),
2467            ("linkmissing", "absent"),
2468        ] {
2469            fs::remove_file(root.join(path)).unwrap();
2470            symlink(target, root.join(path)).unwrap();
2471        }
2472        let mut preview_files = None;
2473        for threads in [1, 4] {
2474            let repo = Repository::open(
2475                repo.git_dir(),
2476                &RepositoryOptions::empty().with_work_tree(root),
2477            )
2478            .unwrap()
2479            .with_thread_policy(ThreadPolicy::with_threads_override(Some(threads)));
2480            let preview = commit_worktree(
2481                &repo,
2482                &dry_run_req("retarget"),
2483                &mut NullProgress,
2484                &crate::progress::CancelToken::never(),
2485            )
2486            .unwrap();
2487            assert_eq!(preview.changes, 3);
2488            if let Some(expected) = &preview_files {
2489                assert_eq!(&preview.files, expected);
2490            }
2491            preview_files = Some(preview.files);
2492            assert_eq!(repo_snapshot(&repo), before);
2493            assert_eq!(
2494                resolve_ref(repo.git_dir(), "refs/heads/main").unwrap(),
2495                before_tip
2496            );
2497        }
2498        let committed = commit_worktree(
2499            &repo,
2500            &commit_req("retarget"),
2501            &mut NullProgress,
2502            &crate::progress::CancelToken::never(),
2503        )
2504        .unwrap();
2505        assert_eq!(Some(committed.files), preview_files);
2506    }
2507
2508    #[test]
2509    fn create_commit_initial() {
2510        let tmp = TempDir::new().unwrap();
2511        let root = tmp.path();
2512        let repo = init_repo(root);
2513        fs::write(root.join("README"), b"hello\n").unwrap();
2514        stage(
2515            &repo,
2516            &StageOptions::default(),
2517            &mut NullProgress,
2518            &crate::progress::CancelToken::never(),
2519        )
2520        .unwrap();
2521
2522        let outcome = create_commit(
2523            &repo,
2524            &commit_req("initial"),
2525            &mut NullProgress,
2526            &crate::progress::CancelToken::never(),
2527        )
2528        .unwrap();
2529        assert!(outcome.parent.is_none());
2530        assert_eq!(outcome.branch.as_deref(), Some("main"));
2531        assert!(!outcome.is_detached());
2532        assert_eq!(outcome.changes, 1);
2533        assert_eq!(
2534            resolve_ref(&repo.git_dir(), "refs/heads/main").unwrap(),
2535            outcome.oid
2536        );
2537    }
2538
2539    #[test]
2540    fn create_commit_rejects_empty_initial_index() {
2541        let tmp = TempDir::new().unwrap();
2542        let repo = init_repo(tmp.path());
2543        let err = create_commit(
2544            &repo,
2545            &commit_req("empty"),
2546            &mut NullProgress,
2547            &crate::progress::CancelToken::never(),
2548        )
2549        .unwrap_err();
2550        assert!(matches!(err, Error::Commit(CommitError::NothingToCommit)));
2551        assert!(resolve_ref(&repo.git_dir(), "refs/heads/main").is_err());
2552    }
2553
2554    #[test]
2555    fn create_commit_normal() {
2556        let tmp = TempDir::new().unwrap();
2557        let root = tmp.path();
2558        let repo = init_repo(root);
2559        fs::write(root.join("a.txt"), b"1\n").unwrap();
2560        stage(
2561            &repo,
2562            &StageOptions::default(),
2563            &mut NullProgress,
2564            &crate::progress::CancelToken::never(),
2565        )
2566        .unwrap();
2567        create_commit(
2568            &repo,
2569            &commit_req("first"),
2570            &mut NullProgress,
2571            &crate::progress::CancelToken::never(),
2572        )
2573        .unwrap();
2574
2575        fs::write(root.join("a.txt"), b"2\n").unwrap();
2576        stage(
2577            &repo,
2578            &StageOptions::default(),
2579            &mut NullProgress,
2580            &crate::progress::CancelToken::never(),
2581        )
2582        .unwrap();
2583        let outcome = create_commit(
2584            &repo,
2585            &commit_req("second"),
2586            &mut NullProgress,
2587            &crate::progress::CancelToken::never(),
2588        )
2589        .unwrap();
2590        assert_eq!(outcome.changes, 1);
2591        assert!(outcome.parent.is_some());
2592    }
2593
2594    #[test]
2595    fn create_commit_nothing_to_commit() {
2596        let tmp = TempDir::new().unwrap();
2597        let root = tmp.path();
2598        let repo = init_repo(root);
2599        fs::write(root.join("a.txt"), b"1\n").unwrap();
2600        stage(
2601            &repo,
2602            &StageOptions::default(),
2603            &mut NullProgress,
2604            &crate::progress::CancelToken::never(),
2605        )
2606        .unwrap();
2607        create_commit(
2608            &repo,
2609            &commit_req("first"),
2610            &mut NullProgress,
2611            &crate::progress::CancelToken::never(),
2612        )
2613        .unwrap();
2614
2615        let err = create_commit(
2616            &repo,
2617            &commit_req("noop"),
2618            &mut NullProgress,
2619            &crate::progress::CancelToken::never(),
2620        )
2621        .unwrap_err();
2622        assert!(matches!(err, Error::Commit(CommitError::NothingToCommit)));
2623    }
2624
2625    #[test]
2626    fn missing_identity_does_not_write_dangling_tree() {
2627        let tmp = TempDir::new().unwrap();
2628        let root = tmp.path();
2629        let repo = init_repo(root);
2630        fs::write(root.join("a.txt"), b"1\n").unwrap();
2631        stage(
2632            &repo,
2633            &StageOptions::default(),
2634            &mut NullProgress,
2635            &crate::progress::CancelToken::never(),
2636        )
2637        .unwrap();
2638        let objects_before = fs::read_dir(repo.git_dir().join("objects"))
2639            .unwrap()
2640            .filter_map(|e| e.ok())
2641            .count();
2642        let err = commit_worktree(
2643            &repo,
2644            &CommitRequest {
2645                message: "first".into(),
2646                ..CommitRequest::default()
2647            },
2648            &mut NullProgress,
2649            &crate::progress::CancelToken::never(),
2650        )
2651        .unwrap_err();
2652        assert!(matches!(
2653            err,
2654            Error::Commit(CommitError::Identity(
2655                crate::config::ident_resolve::IdentityError::MissingConfiguredEmail { .. }
2656            ))
2657        ));
2658        let objects_after = fs::read_dir(repo.git_dir().join("objects"))
2659            .unwrap()
2660            .filter_map(|e| e.ok())
2661            .count();
2662        assert_eq!(
2663            objects_before, objects_after,
2664            "commit must not store objects"
2665        );
2666        let fsck = Command::new("git")
2667            .args(["--git-dir", &repo.git_dir().to_string_lossy(), "fsck"])
2668            .output()
2669            .unwrap();
2670        assert!(
2671            fsck.status.success(),
2672            "{}",
2673            String::from_utf8_lossy(&fsck.stderr)
2674        );
2675        let stderr = String::from_utf8_lossy(&fsck.stderr);
2676        assert!(
2677            !stderr.contains("dangling tree"),
2678            "unexpected dangling tree: {stderr}"
2679        );
2680    }
2681
2682    #[test]
2683    fn commit_worktree_nothing_to_commit_persists_staged_deletion() {
2684        let tmp = TempDir::new().unwrap();
2685        let root = tmp.path();
2686        let repo = init_repo(root);
2687        fs::write(root.join("a.txt"), b"1\n").unwrap();
2688        commit_worktree(
2689            &repo,
2690            &commit_req("first"),
2691            &mut NullProgress,
2692            &crate::progress::CancelToken::never(),
2693        )
2694        .unwrap();
2695
2696        let mut index = repo.load_index().unwrap();
2697        stage_file_in_index(&repo, &mut index, "n.txt", b"staged\n");
2698        write_index(&repo, &mut index);
2699        fs::remove_file(root.join("n.txt")).unwrap();
2700
2701        let err = commit_worktree(
2702            &repo,
2703            &dry_run_req("noop"),
2704            &mut NullProgress,
2705            &crate::progress::CancelToken::never(),
2706        )
2707        .unwrap_err();
2708        assert!(matches!(err, Error::Commit(CommitError::NothingToCommit)));
2709        assert!(repo.load_index().unwrap().get(b"n.txt", 0).is_some());
2710
2711        let err = commit_worktree(
2712            &repo,
2713            &commit_req("noop"),
2714            &mut NullProgress,
2715            &crate::progress::CancelToken::never(),
2716        )
2717        .unwrap_err();
2718        assert!(matches!(err, Error::Commit(CommitError::NothingToCommit)));
2719        let index = repo.load_index().unwrap();
2720        assert!(index.get(b"n.txt", 0).is_none());
2721        assert!(index.get(b"a.txt", 0).is_some());
2722    }
2723
2724    #[test]
2725    fn create_commit_detached_head_advances_head() {
2726        let tmp = TempDir::new().unwrap();
2727        let root = tmp.path();
2728        let repo = init_repo(root);
2729        fs::write(root.join("a.txt"), b"1\n").unwrap();
2730        stage(
2731            &repo,
2732            &StageOptions::default(),
2733            &mut NullProgress,
2734            &crate::progress::CancelToken::never(),
2735        )
2736        .unwrap();
2737        let first = create_commit(
2738            &repo,
2739            &commit_req("first"),
2740            &mut NullProgress,
2741            &crate::progress::CancelToken::never(),
2742        )
2743        .unwrap();
2744        fs::write(repo.git_dir().join("HEAD"), first.oid.to_hex()).unwrap();
2745
2746        fs::write(root.join("b.txt"), b"2\n").unwrap();
2747        stage(
2748            &repo,
2749            &StageOptions::default(),
2750            &mut NullProgress,
2751            &crate::progress::CancelToken::never(),
2752        )
2753        .unwrap();
2754        let second = create_commit(
2755            &repo,
2756            &commit_req("second"),
2757            &mut NullProgress,
2758            &crate::progress::CancelToken::never(),
2759        )
2760        .unwrap();
2761        assert_eq!(second.branch, None);
2762        assert!(second.is_detached());
2763        assert_eq!(second.parent, Some(first.oid));
2764        let head = fs::read_to_string(repo.git_dir().join("HEAD")).unwrap();
2765        assert_eq!(head.trim(), second.oid.to_hex());
2766        let main_tip = crate::refs::resolve_ref(repo.git_dir(), "refs/heads/main").unwrap();
2767        assert_eq!(main_tip, first.oid, "branch tip must stay unchanged");
2768    }
2769
2770    #[test]
2771    fn create_commit_updates_reflogs() {
2772        let tmp = TempDir::new().unwrap();
2773        let root = tmp.path();
2774        let repo = init_repo(root);
2775        fs::write(root.join("a.txt"), b"1\n").unwrap();
2776        stage(
2777            &repo,
2778            &StageOptions::default(),
2779            &mut NullProgress,
2780            &crate::progress::CancelToken::never(),
2781        )
2782        .unwrap();
2783        let outcome = create_commit(
2784            &repo,
2785            &commit_req("subject line"),
2786            &mut NullProgress,
2787            &crate::progress::CancelToken::never(),
2788        )
2789        .unwrap();
2790
2791        let branch_log = read_reflog(&repo.git_dir(), "refs/heads/main").unwrap();
2792        assert_eq!(branch_log.len(), 1);
2793        assert_eq!(branch_log[0].new_oid, outcome.oid);
2794        assert_eq!(branch_log[0].message, "commit (initial): subject line");
2795
2796        let head_log = read_reflog(&repo.git_dir(), "HEAD").unwrap();
2797        assert_eq!(head_log.len(), 1);
2798        assert_eq!(head_log[0].new_oid, outcome.oid);
2799    }
2800
2801    #[test]
2802    fn create_commit_index_write_failure_does_not_advance_branch() {
2803        let tmp = TempDir::new().unwrap();
2804        let root = tmp.path();
2805        let repo = init_repo(root);
2806        fs::write(root.join("a.txt"), b"1\n").unwrap();
2807        stage(
2808            &repo,
2809            &StageOptions::default(),
2810            &mut NullProgress,
2811            &crate::progress::CancelToken::never(),
2812        )
2813        .unwrap();
2814
2815        set_test_inject_index_write_fail(true);
2816        let err = create_commit(
2817            &repo,
2818            &commit_req("fail"),
2819            &mut NullProgress,
2820            &crate::progress::CancelToken::never(),
2821        )
2822        .unwrap_err();
2823        set_test_inject_index_write_fail(false);
2824        assert!(!matches!(err, Error::Commit(CommitError::NothingToCommit)));
2825
2826        assert!(
2827            resolve_ref(&repo.git_dir(), "refs/heads/main").is_err(),
2828            "branch must not advance when index write fails"
2829        );
2830    }
2831
2832    #[test]
2833    fn create_commit_rolls_back_branch_when_head_reflog_fails() {
2834        let tmp = TempDir::new().unwrap();
2835        let root = tmp.path();
2836        let repo = init_repo(root);
2837        fs::write(root.join("a.txt"), b"1\n").unwrap();
2838        stage(
2839            &repo,
2840            &StageOptions::default(),
2841            &mut NullProgress,
2842            &crate::progress::CancelToken::never(),
2843        )
2844        .unwrap();
2845
2846        set_test_inject_reflog_fail(Some("HEAD"));
2847        let err = create_commit(
2848            &repo,
2849            &commit_req("fail"),
2850            &mut NullProgress,
2851            &crate::progress::CancelToken::never(),
2852        )
2853        .unwrap_err();
2854        set_test_inject_reflog_fail(None);
2855        assert!(!matches!(err, Error::Commit(CommitError::NothingToCommit)));
2856
2857        assert!(
2858            resolve_ref(&repo.git_dir(), "refs/heads/main").is_err(),
2859            "branch must not advance when HEAD reflog fails"
2860        );
2861        assert!(read_reflog(&repo.git_dir(), "refs/heads/main")
2862            .unwrap()
2863            .is_empty());
2864        assert!(read_reflog(&repo.git_dir(), "HEAD").unwrap().is_empty());
2865    }
2866
2867    #[test]
2868    fn create_commit_leaves_valid_cache_tree() {
2869        let tmp = TempDir::new().unwrap();
2870        let root = tmp.path();
2871        let repo = init_repo(root);
2872        let mut index = Index::new();
2873        stage_file_in_index(&repo, &mut index, "dir/one.txt", b"1\n");
2874        stage_file_in_index(&repo, &mut index, "dir/two.txt", b"2\n");
2875        write_index(&repo, &mut index);
2876
2877        let outcome = create_commit(
2878            &repo,
2879            &commit_req("tree"),
2880            &mut NullProgress,
2881            &crate::progress::CancelToken::never(),
2882        )
2883        .unwrap();
2884
2885        let index = repo.load_index().unwrap();
2886        verify_cache_tree(&index).expect("cache-tree valid");
2887        assert!(cache_tree_fully_valid(
2888            &repo.odb(),
2889            index.cache_tree.as_ref()
2890        ));
2891        let commit_obj = repo.odb().read(&outcome.oid).unwrap();
2892        let tree = parse_commit(&commit_obj.data).unwrap().tree;
2893        assert_eq!(index.cache_tree_root, Some(tree));
2894    }
2895
2896    #[test]
2897    fn create_commit_amend_same_tree() {
2898        let tmp = TempDir::new().unwrap();
2899        let root = tmp.path();
2900        let repo = init_repo(root);
2901        fs::write(root.join("a.txt"), b"1\n").unwrap();
2902        stage(
2903            &repo,
2904            &StageOptions::default(),
2905            &mut NullProgress,
2906            &crate::progress::CancelToken::never(),
2907        )
2908        .unwrap();
2909        create_commit(
2910            &repo,
2911            &commit_req("first"),
2912            &mut NullProgress,
2913            &crate::progress::CancelToken::never(),
2914        )
2915        .unwrap();
2916        fs::write(root.join("a.txt"), b"2\n").unwrap();
2917        stage(
2918            &repo,
2919            &StageOptions::default(),
2920            &mut NullProgress,
2921            &crate::progress::CancelToken::never(),
2922        )
2923        .unwrap();
2924        create_commit(
2925            &repo,
2926            &commit_req("second"),
2927            &mut NullProgress,
2928            &crate::progress::CancelToken::never(),
2929        )
2930        .unwrap();
2931
2932        let mut req = commit_req("");
2933        req.amend = true;
2934        let tip = resolve_ref(&repo.git_dir(), "refs/heads/main").unwrap();
2935        let outcome = create_commit(
2936            &repo,
2937            &req,
2938            &mut NullProgress,
2939            &crate::progress::CancelToken::never(),
2940        )
2941        .unwrap();
2942        assert_eq!(
2943            outcome.oid, tip,
2944            "same tree and message with fixed committer yields the same object id"
2945        );
2946        assert!(outcome.parent.is_some());
2947
2948        let branch_log = read_reflog(&repo.git_dir(), "refs/heads/main").unwrap();
2949        assert_eq!(branch_log.len(), 3);
2950        assert_eq!(branch_log[2].message, "commit (amend): second");
2951    }
2952
2953    #[test]
2954    fn create_commit_amend_preserves_message_bytes() {
2955        let tmp = TempDir::new().unwrap();
2956        let root = tmp.path();
2957        let repo = init_repo(root);
2958        fs::write(root.join("a.txt"), b"a\n").unwrap();
2959        stage(
2960            &repo,
2961            &StageOptions::default(),
2962            &mut NullProgress,
2963            &crate::progress::CancelToken::never(),
2964        )
2965        .unwrap();
2966        create_commit(
2967            &repo,
2968            &commit_req("oneline subject"),
2969            &mut NullProgress,
2970            &crate::progress::CancelToken::never(),
2971        )
2972        .unwrap();
2973        let baseline = {
2974            let oid = resolve_ref(&repo.git_dir(), "refs/heads/main").unwrap();
2975            parse_commit(&repo.odb().read(&oid).unwrap().data)
2976                .unwrap()
2977                .message
2978        };
2979
2980        for extra in 1..=2 {
2981            fs::write(root.join("a.txt"), format!("a\n{extra}\n")).unwrap();
2982            stage(
2983                &repo,
2984                &StageOptions::default(),
2985                &mut NullProgress,
2986                &crate::progress::CancelToken::never(),
2987            )
2988            .unwrap();
2989            let mut req = commit_req("");
2990            req.amend = true;
2991            create_commit(
2992                &repo,
2993                &req,
2994                &mut NullProgress,
2995                &crate::progress::CancelToken::never(),
2996            )
2997            .unwrap();
2998            let oid = resolve_ref(&repo.git_dir(), "refs/heads/main").unwrap();
2999            let message = parse_commit(&repo.odb().read(&oid).unwrap().data)
3000                .unwrap()
3001                .message;
3002            assert_eq!(message, baseline, "after amend {extra}");
3003        }
3004    }
3005
3006    #[test]
3007    fn create_commit_amend_unborn() {
3008        let tmp = TempDir::new().unwrap();
3009        let repo = init_repo(tmp.path());
3010        fs::write(tmp.path().join("a.txt"), b"1\n").unwrap();
3011        stage(
3012            &repo,
3013            &StageOptions::default(),
3014            &mut NullProgress,
3015            &crate::progress::CancelToken::never(),
3016        )
3017        .unwrap();
3018        let mut req = commit_req("nope");
3019        req.amend = true;
3020        let err = create_commit(
3021            &repo,
3022            &req,
3023            &mut NullProgress,
3024            &crate::progress::CancelToken::never(),
3025        )
3026        .unwrap_err();
3027        assert!(matches!(err, Error::Commit(CommitError::AmendUnborn)));
3028    }
3029
3030    #[test]
3031    fn create_commit_allow_empty() {
3032        let tmp = TempDir::new().unwrap();
3033        let root = tmp.path();
3034        let repo = init_repo(root);
3035        fs::write(root.join("a.txt"), b"1\n").unwrap();
3036        stage(
3037            &repo,
3038            &StageOptions::default(),
3039            &mut NullProgress,
3040            &crate::progress::CancelToken::never(),
3041        )
3042        .unwrap();
3043        create_commit(
3044            &repo,
3045            &commit_req("first"),
3046            &mut NullProgress,
3047            &crate::progress::CancelToken::never(),
3048        )
3049        .unwrap();
3050
3051        let mut req = commit_req("empty");
3052        req.allow_empty = true;
3053        let parent = resolve_ref(&repo.git_dir(), "refs/heads/main").unwrap();
3054        let outcome = create_commit(
3055            &repo,
3056            &req,
3057            &mut NullProgress,
3058            &crate::progress::CancelToken::never(),
3059        )
3060        .unwrap();
3061        assert_eq!(outcome.changes, 0);
3062        assert_eq!(outcome.parent, Some(parent));
3063        assert_ne!(outcome.oid, parent);
3064    }
3065
3066    #[test]
3067    fn scope_staged_commits_index_only() {
3068        let tmp = TempDir::new().unwrap();
3069        let root = tmp.path();
3070        let repo = init_repo(root);
3071        fs::write(root.join("a.txt"), b"1\n").unwrap();
3072        fs::write(root.join("b.txt"), b"1\n").unwrap();
3073        stage(
3074            &repo,
3075            &StageOptions::default(),
3076            &mut NullProgress,
3077            &crate::progress::CancelToken::never(),
3078        )
3079        .unwrap();
3080        create_commit(
3081            &repo,
3082            &commit_req("first"),
3083            &mut NullProgress,
3084            &crate::progress::CancelToken::never(),
3085        )
3086        .unwrap();
3087
3088        fs::write(root.join("a.txt"), b"2\n").unwrap();
3089        fs::write(root.join("b.txt"), b"2\n").unwrap();
3090        let mut index = repo.load_index().unwrap();
3091        stage_file_in_index(&repo, &mut index, "a.txt", b"2\n");
3092        write_index(&repo, &mut index);
3093
3094        let outcome = commit_with_scope(
3095            &repo,
3096            &commit_req("only a"),
3097            CommitScope::Staged,
3098            &mut NullProgress,
3099            &crate::progress::CancelToken::never(),
3100        )
3101        .unwrap();
3102        assert_eq!(outcome.changes, 1);
3103        let index = repo.load_index().unwrap();
3104        let b_oid = index.get(b"b.txt", 0).unwrap().oid;
3105        let b_blob = repo.odb().read(&b_oid).unwrap();
3106        assert_eq!(b_blob.data, b"1\n", "unstaged paths stay in the index");
3107    }
3108
3109    #[test]
3110    fn scope_paths_does_not_hash_a_throwaway_validation_index() {
3111        let tmp = TempDir::new().unwrap();
3112        let root = tmp.path();
3113        let repo = init_repo(root);
3114        let mut bytes = vec![b'x'; 2 * 1024 * 1024];
3115        fs::write(root.join("large"), &bytes).unwrap();
3116        stage(
3117            &repo,
3118            &StageOptions::default(),
3119            &mut NullProgress,
3120            &crate::progress::CancelToken::never(),
3121        )
3122        .unwrap();
3123        create_commit(
3124            &repo,
3125            &commit_req("initial"),
3126            &mut NullProgress,
3127            &crate::progress::CancelToken::never(),
3128        )
3129        .unwrap();
3130        bytes.push(b'y');
3131        fs::write(root.join("large"), &bytes).unwrap();
3132        let passes = repo.odb().hot_path_metrics().staging_passes();
3133        let result = commit_with_scope(
3134            &repo,
3135            &commit_req("selected path"),
3136            CommitScope::Paths(Pathspec::scoped(["large"], PathspecGlobalFlags::default())),
3137            &mut NullProgress,
3138            &crate::progress::CancelToken::never(),
3139        )
3140        .unwrap();
3141        assert_eq!(result.changes, 1);
3142        // The commit view and repository view each stage once. Validation must not
3143        // add a third pass, regardless of extra hashing needed for racy stat rows.
3144        assert_eq!(repo.odb().hot_path_metrics().staging_passes(), passes + 2);
3145        let index = repo.load_index().unwrap();
3146        let oid = index.get(b"large", 0).unwrap().oid;
3147        assert_eq!(repo.odb().read(&oid).unwrap().data, bytes);
3148    }
3149
3150    #[test]
3151    fn scope_paths_leaves_other_staged_entries() {
3152        let tmp = TempDir::new().unwrap();
3153        let root = tmp.path();
3154        let repo = init_repo(root);
3155        fs::write(root.join("file"), b"1\n").unwrap();
3156        fs::write(root.join("baz"), b"1\n").unwrap();
3157        stage(
3158            &repo,
3159            &StageOptions::default(),
3160            &mut NullProgress,
3161            &crate::progress::CancelToken::never(),
3162        )
3163        .unwrap();
3164        create_commit(
3165            &repo,
3166            &commit_req("initial"),
3167            &mut NullProgress,
3168            &crate::progress::CancelToken::never(),
3169        )
3170        .unwrap();
3171
3172        fs::write(root.join("file"), b"2\n").unwrap();
3173        fs::write(root.join("baz"), b"2\n").unwrap();
3174        stage(
3175            &repo,
3176            &StageOptions {
3177                pathspecs: vec!["baz".into()],
3178                ..StageOptions::default()
3179            },
3180            &mut NullProgress,
3181            &crate::progress::CancelToken::never(),
3182        )
3183        .unwrap();
3184
3185        let paths = Pathspec::scoped(["file"], PathspecGlobalFlags::default());
3186        commit_with_scope(
3187            &repo,
3188            &commit_req("file only"),
3189            CommitScope::Paths(paths),
3190            &mut NullProgress,
3191            &crate::progress::CancelToken::never(),
3192        )
3193        .unwrap();
3194
3195        let index = repo.load_index().unwrap();
3196        let baz_oid = index.get(b"baz", 0).unwrap().oid;
3197        assert_eq!(repo.odb().read(&baz_oid).unwrap().data, b"2\n");
3198    }
3199
3200    #[test]
3201    fn scope_paths_deleted_and_untracked() {
3202        let tmp = TempDir::new().unwrap();
3203        let root = tmp.path();
3204        let repo = init_repo(root);
3205        fs::write(root.join("tracked.txt"), b"1\n").unwrap();
3206        stage(
3207            &repo,
3208            &StageOptions::default(),
3209            &mut NullProgress,
3210            &crate::progress::CancelToken::never(),
3211        )
3212        .unwrap();
3213        create_commit(
3214            &repo,
3215            &commit_req("first"),
3216            &mut NullProgress,
3217            &crate::progress::CancelToken::never(),
3218        )
3219        .unwrap();
3220
3221        fs::write(root.join("new.txt"), b"new\n").unwrap();
3222        fs::remove_file(root.join("tracked.txt")).unwrap();
3223
3224        let paths = Pathspec::scoped(["new.txt", "tracked.txt"], PathspecGlobalFlags::default());
3225        commit_with_scope(
3226            &repo,
3227            &commit_req("add and remove"),
3228            CommitScope::Paths(paths),
3229            &mut NullProgress,
3230            &crate::progress::CancelToken::never(),
3231        )
3232        .unwrap();
3233
3234        let index = repo.load_index().unwrap();
3235        assert!(index.get(b"tracked.txt", 0).is_none());
3236        assert!(index.get(b"new.txt", 0).is_some());
3237    }
3238
3239    #[cfg_attr(
3240        not(feature = "full-tests"),
3241        ignore = "starts system git or is heavy; run with --features full-tests"
3242    )]
3243    #[test]
3244    fn scope_paths_nested_dirs_round_trip_with_git() {
3245        use std::process::Command;
3246
3247        let tmp = TempDir::new().unwrap();
3248        let root = tmp.path();
3249        let git = |args: &[&str]| -> String {
3250            let out = Command::new("git")
3251                .env("GIT_CONFIG_NOSYSTEM", "1")
3252                .env("GIT_CONFIG_GLOBAL", "/dev/null")
3253                .env("GIT_AUTHOR_NAME", "Test")
3254                .env("GIT_AUTHOR_EMAIL", "test@example.com")
3255                .env("GIT_COMMITTER_NAME", "Test")
3256                .env("GIT_COMMITTER_EMAIL", "test@example.com")
3257                .current_dir(root)
3258                .args(args)
3259                .output()
3260                .unwrap();
3261            assert!(
3262                out.status.success(),
3263                "git {args:?}: {}",
3264                String::from_utf8_lossy(&out.stderr)
3265            );
3266            String::from_utf8(out.stdout).unwrap()
3267        };
3268        git(&["init", "-q", "-b", "main"]);
3269        for (rel, body) in [
3270            ("a/x.txt", "x1\n"),
3271            ("a/y.txt", "y1\n"),
3272            ("b/c/z.txt", "z1\n"),
3273            ("b/w.txt", "w1\n"),
3274            ("d/e.txt", "e1\n"),
3275            ("top.txt", "t1\n"),
3276        ] {
3277            fs::create_dir_all(root.join(rel).parent().unwrap()).unwrap();
3278            fs::write(root.join(rel), body).unwrap();
3279        }
3280        git(&["add", "-A"]);
3281        git(&["commit", "-qm", "init"]);
3282
3283        fs::write(root.join("a/x.txt"), b"x2\n").unwrap();
3284        fs::write(root.join("b/c/z.txt"), b"z2\n").unwrap();
3285        fs::write(root.join("b/w.txt"), b"w2\n").unwrap();
3286        fs::write(root.join("top.txt"), b"t2\n").unwrap();
3287        git(&["add", "b/w.txt"]);
3288
3289        let repo = Repository::discover(Some(root), &RepositoryOptions::empty()).unwrap();
3290        let specs = vec!["a/x.txt".to_owned(), "b/c/z.txt".to_owned()];
3291        commit_with_scope(
3292            &repo,
3293            &commit_req("partial"),
3294            CommitScope::Paths(Pathspec::scoped(
3295                specs.clone(),
3296                PathspecGlobalFlags::default(),
3297            )),
3298            &mut NullProgress,
3299            &crate::progress::CancelToken::never(),
3300        )
3301        .unwrap();
3302
3303        git(&["fsck", "--strict", "--no-progress"]);
3304        assert_eq!(
3305            git(&["diff", "--name-only", "HEAD~1", "HEAD"]),
3306            "a/x.txt\nb/c/z.txt\n"
3307        );
3308        assert_eq!(git(&["show", "HEAD:a/x.txt"]), "x2\n");
3309        assert_eq!(git(&["show", "HEAD:b/c/z.txt"]), "z2\n");
3310        assert_eq!(git(&["show", "HEAD:b/w.txt"]), "w1\n");
3311        assert_eq!(
3312            git(&["rev-parse", "HEAD:d"]),
3313            git(&["rev-parse", "HEAD~1:d"])
3314        );
3315        assert_eq!(git(&["diff", "--cached", "--name-only"]), "b/w.txt\n");
3316        assert_eq!(git(&["diff", "--name-only"]), "top.txt\n");
3317    }
3318
3319    #[test]
3320    fn scope_paths_no_match_errors() {
3321        let tmp = TempDir::new().unwrap();
3322        let root = tmp.path();
3323        let repo = init_repo(root);
3324        fs::write(root.join("a.txt"), b"1\n").unwrap();
3325        stage(
3326            &repo,
3327            &StageOptions::default(),
3328            &mut NullProgress,
3329            &crate::progress::CancelToken::never(),
3330        )
3331        .unwrap();
3332        create_commit(
3333            &repo,
3334            &commit_req("first"),
3335            &mut NullProgress,
3336            &crate::progress::CancelToken::never(),
3337        )
3338        .unwrap();
3339
3340        let paths = Pathspec::scoped(["missing.txt"], PathspecGlobalFlags::default());
3341        assert_commit_with_scope_err(
3342            &repo,
3343            &commit_req("nope"),
3344            CommitScope::Paths(paths),
3345            |err| {
3346                assert!(matches!(
3347                    err,
3348                    Error::Worktree(WorktreeError::PathspecNoMatch { .. })
3349                ));
3350            },
3351        );
3352    }
3353
3354    #[test]
3355    fn scope_paths_refused_during_merge() {
3356        let tmp = TempDir::new().unwrap();
3357        let root = tmp.path();
3358        let repo = init_repo(root);
3359        fs::write(root.join("a.txt"), b"1\n").unwrap();
3360        stage(
3361            &repo,
3362            &StageOptions::default(),
3363            &mut NullProgress,
3364            &crate::progress::CancelToken::never(),
3365        )
3366        .unwrap();
3367        create_commit(
3368            &repo,
3369            &commit_req("first"),
3370            &mut NullProgress,
3371            &crate::progress::CancelToken::never(),
3372        )
3373        .unwrap();
3374        let tip = resolve_ref(&repo.git_dir(), "refs/heads/main").unwrap();
3375        fs::write(repo.git_dir().join("MERGE_HEAD"), format!("{tip}\n")).unwrap();
3376
3377        let paths = Pathspec::scoped(["a.txt"], PathspecGlobalFlags::default());
3378        let err = commit_with_scope(
3379            &repo,
3380            &commit_req("partial"),
3381            CommitScope::Paths(paths),
3382            &mut NullProgress,
3383            &crate::progress::CancelToken::never(),
3384        )
3385        .unwrap_err();
3386        assert!(matches!(
3387            err,
3388            crate::error::Error::Commit(CommitError::PartialCommitDuringMerge)
3389        ));
3390    }
3391
3392    fn system_git(root: &Path, args: &[&str]) -> String {
3393        let out = grit_test_support::merge_git_config_env(&mut Command::new("git"), &[])
3394            .env("GIT_CONFIG_NOSYSTEM", "1")
3395            .env("GIT_CONFIG_GLOBAL", "/dev/null")
3396            .env("GIT_AUTHOR_NAME", "Test")
3397            .env("GIT_AUTHOR_EMAIL", "test@example.com")
3398            .env("GIT_COMMITTER_NAME", "Test")
3399            .env("GIT_COMMITTER_EMAIL", "test@example.com")
3400            .current_dir(root)
3401            .args(args)
3402            .output()
3403            .unwrap();
3404        assert!(
3405            out.status.success(),
3406            "git {args:?}: {}",
3407            String::from_utf8_lossy(&out.stderr)
3408        );
3409        String::from_utf8(out.stdout).unwrap()
3410    }
3411
3412    fn sharedindex_file_paths(git_dir: &Path) -> Vec<PathBuf> {
3413        fs::read_dir(git_dir)
3414            .unwrap()
3415            .flatten()
3416            .filter_map(|e| {
3417                let name = e.file_name();
3418                let s = name.to_string_lossy();
3419                if s.starts_with("sharedindex.") {
3420                    Some(e.path())
3421                } else {
3422                    None
3423                }
3424            })
3425            .collect()
3426    }
3427
3428    /// `git init` + one commit of `f1.txt`, then `f1.txt` modified in the worktree (issue #1789).
3429    fn git_repo_with_modified_file(root: &Path) -> Repository {
3430        system_git(root, &["init", "-q", "-b", "main"]);
3431        fs::write(root.join("f1.txt"), b"a\n").unwrap();
3432        system_git(root, &["add", "."]);
3433        system_git(root, &["commit", "-qm", "init"]);
3434        fs::write(root.join("f1.txt"), b"a\nb\n").unwrap();
3435        Repository::discover(Some(root), &RepositoryOptions::empty()).unwrap()
3436    }
3437
3438    #[cfg(unix)]
3439    #[test]
3440    #[cfg_attr(
3441        not(feature = "full-tests"),
3442        ignore = "starts system git or is heavy; run with --features full-tests"
3443    )]
3444    fn dry_run_files_match_commit_and_git_with_and_without_cache_tree() {
3445        use std::os::unix::fs::PermissionsExt;
3446
3447        for keep_cache_tree in [true, false] {
3448            let tmp = TempDir::new().unwrap();
3449            let root = tmp.path();
3450            system_git(root, &["init", "-q", "-b", "main"]);
3451            for dir in ["a", "b", "c", "e"] {
3452                fs::create_dir(root.join(dir)).unwrap();
3453            }
3454            for (path, body) in [
3455                ("a/x", "x\n"),
3456                ("a/y", "y\n"),
3457                ("b/z", "z\n"),
3458                ("c/w", "w\n"),
3459                ("e/keep", "keep\n"),
3460                ("top", "top\n"),
3461            ] {
3462                fs::write(root.join(path), body).unwrap();
3463            }
3464            system_git(root, &["add", "."]);
3465            system_git(root, &["commit", "-qm", "init"]);
3466            let repo = Repository::discover(Some(root), &RepositoryOptions::empty()).unwrap();
3467            let mut index = repo.load_index().unwrap();
3468            assert!(index.cache_tree.is_some(), "git writes a cache-tree");
3469            if !keep_cache_tree {
3470                index.cache_tree = None;
3471                index.cache_tree_root = None;
3472                repo.write_index(&mut index).unwrap();
3473            }
3474
3475            fs::write(root.join("a/x"), b"x changed\n").unwrap();
3476            fs::remove_file(root.join("b/z")).unwrap();
3477            fs::create_dir(root.join("d")).unwrap();
3478            fs::write(root.join("d/new"), b"brand new\n").unwrap();
3479            fs::write(root.join("added-top"), b"also new\n").unwrap();
3480            let mut perms = fs::metadata(root.join("c/w")).unwrap().permissions();
3481            perms.set_mode(0o755);
3482            fs::set_permissions(root.join("c/w"), perms).unwrap();
3483
3484            let before = repo_snapshot(&repo);
3485            let preview = commit_worktree(
3486                &repo,
3487                &dry_run_req("mixed"),
3488                &mut NullProgress,
3489                &crate::progress::CancelToken::never(),
3490            )
3491            .unwrap();
3492            assert_eq!(repo_snapshot(&repo), before, "dry run must not write");
3493            let listed: Vec<(&str, DiffStatus)> = preview
3494                .files
3495                .iter()
3496                .map(|f| (f.path.as_str(), f.status))
3497                .collect();
3498            assert_eq!(
3499                listed,
3500                vec![
3501                    ("a/x", DiffStatus::Modified),
3502                    ("added-top", DiffStatus::Added),
3503                    ("b/z", DiffStatus::Deleted),
3504                    ("c/w", DiffStatus::Modified),
3505                    ("d/new", DiffStatus::Added),
3506                ],
3507                "cache-tree kept: {keep_cache_tree}"
3508            );
3509            assert_eq!(preview.changes, preview.files.len());
3510
3511            let committed = commit_worktree(
3512                &repo,
3513                &commit_req("mixed"),
3514                &mut NullProgress,
3515                &crate::progress::CancelToken::never(),
3516            )
3517            .unwrap();
3518            assert_eq!(committed.files, preview.files);
3519            let git_listed = system_git(root, &["diff", "--name-status", "--no-renames", "HEAD~1"]);
3520            let expected: Vec<String> = preview
3521                .files
3522                .iter()
3523                .map(|f| format!("{}\t{}", f.status.letter(), f.path))
3524                .collect();
3525            assert_eq!(git_listed.lines().collect::<Vec<_>>(), expected);
3526        }
3527    }
3528
3529    #[cfg(unix)]
3530    #[test]
3531    fn dry_run_lists_non_utf8_paths_in_storage_form_like_commit() {
3532        use std::os::unix::ffi::OsStrExt;
3533
3534        let raw = |root: &Path, name: &[u8]| root.join(std::ffi::OsStr::from_bytes(name));
3535        let check = |repo: &Repository, expected: &[(&[u8], DiffStatus)]| {
3536            let preview = commit_worktree(
3537                repo,
3538                &dry_run_req("preview"),
3539                &mut NullProgress,
3540                &crate::progress::CancelToken::never(),
3541            )
3542            .unwrap();
3543            let listed: Vec<(String, DiffStatus)> = preview
3544                .files
3545                .iter()
3546                .map(|f| (f.path.clone(), f.status))
3547                .collect();
3548            let mut want: Vec<(String, DiffStatus)> = expected
3549                .iter()
3550                .map(|(p, s)| (crate::repo_relpath::storage_string(p), *s))
3551                .collect();
3552            want.sort_by(|a, b| a.0.cmp(&b.0));
3553            assert_eq!(listed, want);
3554            let committed = commit_worktree(
3555                repo,
3556                &commit_req("commit"),
3557                &mut NullProgress,
3558                &crate::progress::CancelToken::never(),
3559            )
3560            .unwrap();
3561            assert_eq!(committed.files, preview.files);
3562        };
3563
3564        let tmp = TempDir::new().unwrap();
3565        let root = tmp.path();
3566        let repo = init_repo(root);
3567        fs::create_dir(root.join("dir")).unwrap();
3568        fs::write(raw(root, b"dir/keep\xff"), b"keep\n").unwrap();
3569        fs::write(raw(root, b"dir/mod\xfe"), b"before\n").unwrap();
3570        fs::write(raw(root, b"dir/del\xfd"), b"gone\n").unwrap();
3571        fs::write(root.join("plain"), b"plain\n").unwrap();
3572        commit_worktree(
3573            &repo,
3574            &commit_req("initial"),
3575            &mut NullProgress,
3576            &crate::progress::CancelToken::never(),
3577        )
3578        .unwrap();
3579
3580        fs::write(raw(root, b"dir/mod\xfe"), b"after\n").unwrap();
3581        fs::remove_file(raw(root, b"dir/del\xfd")).unwrap();
3582        fs::write(root.join("plain"), b"plain changed\n").unwrap();
3583        check(
3584            &repo,
3585            &[
3586                (b"dir/mod\xfe", DiffStatus::Modified),
3587                (b"dir/del\xfd", DiffStatus::Deleted),
3588                (b"plain", DiffStatus::Modified),
3589            ],
3590        );
3591
3592        fs::remove_file(raw(root, b"dir/keep\xff")).unwrap();
3593        fs::remove_file(raw(root, b"dir/mod\xfe")).unwrap();
3594        check(
3595            &repo,
3596            &[
3597                (b"dir/keep\xff", DiffStatus::Deleted),
3598                (b"dir/mod\xfe", DiffStatus::Deleted),
3599            ],
3600        );
3601    }
3602
3603    #[test]
3604    fn dry_run_root_commit_lists_every_index_path() {
3605        let tmp = TempDir::new().unwrap();
3606        let root = tmp.path();
3607        let repo = init_repo(root);
3608        fs::create_dir(root.join("dir")).unwrap();
3609        fs::write(root.join("dir/b"), b"b\n").unwrap();
3610        fs::write(root.join("a"), b"a\n").unwrap();
3611        let preview = commit_worktree(
3612            &repo,
3613            &dry_run_req("root"),
3614            &mut NullProgress,
3615            &crate::progress::CancelToken::never(),
3616        )
3617        .unwrap();
3618        let listed: Vec<(&str, DiffStatus)> = preview
3619            .files
3620            .iter()
3621            .map(|f| (f.path.as_str(), f.status))
3622            .collect();
3623        assert_eq!(
3624            listed,
3625            vec![("a", DiffStatus::Added), ("dir/b", DiffStatus::Added)]
3626        );
3627        assert!(preview.parents.is_empty());
3628        assert!(resolve_ref(repo.git_dir(), "refs/heads/main").is_err());
3629    }
3630
3631    fn f1_paths() -> Pathspec {
3632        Pathspec::scoped(["f1.txt"], PathspecGlobalFlags::default())
3633    }
3634
3635    /// Run `scope` while a foreign `index.lock` exists and check nothing became visible.
3636    ///
3637    /// `objects_untouched` additionally requires that no loose object was written; scopes that
3638    /// hash content before writing the index may leave unreferenced blobs.
3639    fn assert_commit_refused_by_foreign_lock(
3640        root: &Path,
3641        repo: &Repository,
3642        scope: CommitScope,
3643        objects_untouched: bool,
3644    ) {
3645        let lock_path = repo.git_dir().join("index.lock");
3646        fs::write(&lock_path, b"foreign\n").unwrap();
3647        let before = repo_snapshot(repo);
3648        let tip_before = resolve_ref(&repo.git_dir(), "refs/heads/main").unwrap();
3649
3650        let err = commit_with_scope(
3651            repo,
3652            &commit_req("x"),
3653            scope,
3654            &mut NullProgress,
3655            &crate::progress::CancelToken::never(),
3656        )
3657        .unwrap_err();
3658        match &err {
3659            Error::LockHeld(crate::error::LockHeldError {
3660                path: reported,
3661                holder,
3662            }) => {
3663                assert_eq!(reported, &lock_path);
3664                assert_eq!(*holder, None);
3665            }
3666            other => panic!("expected Error::LockHeld, got {other:?}"),
3667        }
3668        assert!(err.to_string().contains("index.lock"), "{err}");
3669
3670        let (index, head, reflog, _editmsg, objects) = repo_snapshot(repo);
3671        assert_eq!(index, before.0, "index bytes must be unchanged");
3672        assert_eq!(head, before.1, "HEAD must be unchanged");
3673        assert_eq!(reflog, before.2, "no reflog entry may be written");
3674        if objects_untouched {
3675            assert_eq!(objects, before.4, "no objects may be written");
3676        }
3677        assert_eq!(
3678            resolve_ref(&repo.git_dir(), "refs/heads/main").unwrap(),
3679            tip_before
3680        );
3681        assert_eq!(
3682            fs::read(&lock_path).unwrap(),
3683            b"foreign\n",
3684            "someone else's lock must be left alone"
3685        );
3686        let leftovers: Vec<_> = fs::read_dir(repo.git_dir())
3687            .unwrap()
3688            .flatten()
3689            .filter(|e| e.file_name().to_string_lossy().starts_with("next-index-"))
3690            .collect();
3691        assert!(leftovers.is_empty(), "temporary hook index left behind");
3692
3693        fs::remove_file(&lock_path).unwrap();
3694        assert_eq!(system_git(root, &["status", "--porcelain"]), " M f1.txt\n");
3695        system_git(root, &["fsck", "--strict", "--no-progress"]);
3696    }
3697
3698    #[cfg_attr(
3699        not(feature = "full-tests"),
3700        ignore = "starts system git or is heavy; run with --features full-tests"
3701    )]
3702    #[test]
3703    fn scope_paths_with_held_index_lock_creates_nothing() {
3704        let tmp = TempDir::new().unwrap();
3705        let root = tmp.path();
3706        let repo = git_repo_with_modified_file(root);
3707        assert_commit_refused_by_foreign_lock(root, &repo, CommitScope::Paths(f1_paths()), true);
3708
3709        let outcome = commit_with_scope(
3710            &repo,
3711            &commit_req("x"),
3712            CommitScope::Paths(f1_paths()),
3713            &mut NullProgress,
3714            &crate::progress::CancelToken::never(),
3715        )
3716        .unwrap();
3717        assert!(!repo.git_dir().join("index.lock").exists());
3718        assert_eq!(
3719            system_git(root, &["rev-parse", "HEAD"]).trim(),
3720            outcome.oid.to_hex()
3721        );
3722        assert_eq!(system_git(root, &["status", "--porcelain"]), "");
3723        system_git(root, &["fsck", "--strict", "--no-progress"]);
3724    }
3725
3726    #[cfg_attr(
3727        not(feature = "full-tests"),
3728        ignore = "starts system git or is heavy; run with --features full-tests"
3729    )]
3730    #[test]
3731    fn scope_staged_and_auto_stage_with_held_index_lock_create_nothing() {
3732        let tmp = TempDir::new().unwrap();
3733        let root = tmp.path();
3734        let repo = git_repo_with_modified_file(root);
3735        assert_commit_refused_by_foreign_lock(root, &repo, CommitScope::AutoStage, true);
3736
3737        system_git(root, &["add", "f1.txt"]);
3738        let lock_path = repo.git_dir().join("index.lock");
3739        fs::write(&lock_path, b"foreign\n").unwrap();
3740        let tip_before = resolve_ref(&repo.git_dir(), "refs/heads/main").unwrap();
3741        assert_commit_with_scope_err(&repo, &commit_req("x"), CommitScope::Staged, |inner| {
3742            assert!(
3743                matches!(inner, Error::LockHeld(lock) if lock.path == repo.git_dir().join("index.lock")),
3744                "{inner:?}"
3745            );
3746        });
3747        assert_eq!(
3748            resolve_ref(&repo.git_dir(), "refs/heads/main").unwrap(),
3749            tip_before
3750        );
3751        assert_eq!(fs::read(&lock_path).unwrap(), b"foreign\n");
3752    }
3753
3754    #[cfg_attr(
3755        not(feature = "full-tests"),
3756        ignore = "starts system git or is heavy; run with --features full-tests"
3757    )]
3758    #[test]
3759    fn scope_patch_with_held_index_lock_creates_nothing() {
3760        use crate::diff::{hunk_ids, DiffSide};
3761        use crate::diff::{unstaged_file_diffs_with_peer_hunks, DiffOptions};
3762        use crate::porcelain::hunk_select::HunkSelection;
3763
3764        let tmp = TempDir::new().unwrap();
3765        let root = tmp.path();
3766        let repo = git_repo_with_modified_file(root);
3767        let (files, peers) =
3768            unstaged_file_diffs_with_peer_hunks(&repo, &[], DiffOptions::default()).unwrap();
3769        let ids = hunk_ids(
3770            DiffSide::Unstaged,
3771            "f1.txt",
3772            &files[0].hunks,
3773            peers.get("f1.txt").map(|v| v.as_slice()).unwrap_or(&[]),
3774        );
3775        let scope = CommitScope::Patch {
3776            input: CommitPatchInput::Hunks(HunkSelection {
3777                ids: vec![ids[0].clone()],
3778                ranges: Vec::new(),
3779            }),
3780            pathspecs: Vec::new(),
3781        };
3782        assert_commit_refused_by_foreign_lock(root, &repo, scope.clone(), true);
3783
3784        let outcome = commit_with_scope(
3785            &repo,
3786            &commit_req("x"),
3787            scope,
3788            &mut NullProgress,
3789            &crate::progress::CancelToken::never(),
3790        )
3791        .unwrap();
3792        assert!(!repo.git_dir().join("index.lock").exists());
3793        assert_eq!(
3794            system_git(root, &["rev-parse", "HEAD"]).trim(),
3795            outcome.oid.to_hex()
3796        );
3797        assert_eq!(system_git(root, &["status", "--porcelain"]), "");
3798        let index = repo.load_index().unwrap();
3799        verify_cache_tree(&index).expect("cache-tree valid");
3800        assert!(cache_tree_fully_valid(
3801            &repo.odb(),
3802            index.cache_tree.as_ref()
3803        ));
3804        let tree = parse_commit(&repo.odb().read(&outcome.oid).unwrap().data)
3805            .unwrap()
3806            .tree;
3807        assert_eq!(index.cache_tree_root, Some(tree));
3808        system_git(root, &["fsck", "--strict", "--no-progress"]);
3809    }
3810
3811    #[cfg_attr(
3812        not(feature = "full-tests"),
3813        ignore = "starts system git or is heavy; run with --features full-tests"
3814    )]
3815    #[test]
3816    fn scope_paths_split_index_round_trips_with_git() {
3817        let tmp = TempDir::new().unwrap();
3818        let root = tmp.path();
3819        system_git(root, &["init", "-q", "-b", "main"]);
3820        system_git(root, &["config", "core.splitIndex", "true"]);
3821        system_git(root, &["config", "splitIndex.maxPercentChange", "100"]);
3822        for name in ["a.txt", "b.txt", "c.txt"] {
3823            fs::write(root.join(name), b"1\n").unwrap();
3824        }
3825        system_git(root, &["add", "."]);
3826        system_git(root, &["commit", "-qm", "init"]);
3827        fs::write(root.join("a.txt"), b"2\n").unwrap();
3828        fs::write(root.join("b.txt"), b"2\n").unwrap();
3829        system_git(root, &["add", "b.txt"]);
3830
3831        let repo = Repository::discover(Some(root), &RepositoryOptions::empty()).unwrap();
3832        let specs = vec!["a.txt".to_owned()];
3833        commit_with_scope(
3834            &repo,
3835            &commit_req("partial"),
3836            CommitScope::Paths(Pathspec::scoped(
3837                specs.clone(),
3838                PathspecGlobalFlags::default(),
3839            )),
3840            &mut NullProgress,
3841            &crate::progress::CancelToken::never(),
3842        )
3843        .unwrap();
3844
3845        assert!(!repo.git_dir().join("index.lock").exists());
3846        assert!(
3847            system_git(root, &["ls-files", "--debug"]).contains("a.txt"),
3848            "git must read the split index"
3849        );
3850        assert_eq!(system_git(root, &["status", "--porcelain"]), "M  b.txt\n");
3851        assert_eq!(system_git(root, &["show", "HEAD:a.txt"]), "2\n");
3852        assert_eq!(system_git(root, &["show", "HEAD:b.txt"]), "1\n");
3853        system_git(root, &["fsck", "--strict", "--no-progress"]);
3854        let shared: Vec<_> = fs::read_dir(repo.git_dir())
3855            .unwrap()
3856            .flatten()
3857            .filter(|e| e.file_name().to_string_lossy().starts_with("sharedindex."))
3858            .collect();
3859        assert!(!shared.is_empty(), "index must stay split");
3860    }
3861
3862    #[cfg_attr(
3863        not(feature = "full-tests"),
3864        ignore = "starts system git or is heavy; run with --features full-tests"
3865    )]
3866    #[test]
3867    fn commit_worktree_reuses_shared_index_on_small_change() {
3868        let tmp = TempDir::new().unwrap();
3869        let root = tmp.path();
3870        system_git(root, &["init", "-q", "-b", "main"]);
3871        for i in 0..30 {
3872            fs::write(root.join(format!("f{i:02}.txt")), format!("{i}\n")).unwrap();
3873        }
3874        system_git(root, &["add", "."]);
3875        system_git(root, &["commit", "-qm", "init"]);
3876        system_git(root, &["config", "core.splitIndex", "true"]);
3877        system_git(root, &["update-index", "--split-index"]);
3878
3879        let before = sharedindex_file_paths(&root.join(".git"));
3880        assert_eq!(before.len(), 1, "git must create one shared index");
3881
3882        fs::write(root.join("f00.txt"), b"changed\n").unwrap();
3883        let repo = Repository::discover(Some(root), &RepositoryOptions::empty()).unwrap();
3884        commit_worktree(
3885            &repo,
3886            &commit_req("one file"),
3887            &mut NullProgress,
3888            &crate::progress::CancelToken::never(),
3889        )
3890        .unwrap();
3891
3892        let after = sharedindex_file_paths(repo.git_dir());
3893        assert_eq!(
3894            before.len(),
3895            after.len(),
3896            "small commit must not write a new sharedindex"
3897        );
3898        assert!(
3899            system_git(root, &["ls-files", "--debug"]).contains("f00.txt"),
3900            "split link must remain readable by git"
3901        );
3902        assert_eq!(system_git(root, &["status", "--porcelain"]), "");
3903        system_git(root, &["fsck", "--strict", "--no-progress"]);
3904    }
3905
3906    #[cfg_attr(
3907        not(feature = "full-tests"),
3908        ignore = "starts system git or is heavy; run with --features full-tests"
3909    )]
3910    #[test]
3911    fn commit_worktree_rebuilds_shared_index_when_max_percent_exceeded() {
3912        let tmp = TempDir::new().unwrap();
3913        let root = tmp.path();
3914        system_git(root, &["init", "-q", "-b", "main"]);
3915        for i in 0..10 {
3916            fs::write(root.join(format!("f{i}.txt")), format!("{i}\n")).unwrap();
3917        }
3918        system_git(root, &["add", "."]);
3919        system_git(root, &["commit", "-qm", "init"]);
3920        system_git(root, &["config", "core.splitIndex", "true"]);
3921        system_git(root, &["config", "splitIndex.maxPercentChange", "20"]);
3922        system_git(root, &["update-index", "--split-index"]);
3923
3924        let first = sharedindex_file_paths(&root.join(".git"));
3925        assert_eq!(first.len(), 1);
3926        let first_oid = first[0]
3927            .file_name()
3928            .unwrap()
3929            .to_string_lossy()
3930            .strip_prefix("sharedindex.")
3931            .unwrap()
3932            .to_string();
3933
3934        for i in 0..4 {
3935            fs::write(root.join(format!("n{i}.txt")), format!("n{i}\n")).unwrap();
3936        }
3937        let repo = Repository::discover(Some(root), &RepositoryOptions::empty()).unwrap();
3938        commit_worktree(
3939            &repo,
3940            &commit_req("many new files"),
3941            &mut NullProgress,
3942            &crate::progress::CancelToken::never(),
3943        )
3944        .unwrap();
3945
3946        let shared = sharedindex_file_paths(repo.git_dir());
3947        let second_oid = shared
3948            .iter()
3949            .map(|p| {
3950                p.file_name()
3951                    .unwrap()
3952                    .to_string_lossy()
3953                    .strip_prefix("sharedindex.")
3954                    .unwrap()
3955                    .to_string()
3956            })
3957            .find(|oid| oid != &first_oid)
3958            .expect("maxPercentChange should force a new shared index base");
3959        assert_ne!(first_oid, second_oid);
3960        system_git(root, &["fsck", "--strict", "--no-progress"]);
3961    }
3962
3963    #[cfg_attr(
3964        not(feature = "full-tests"),
3965        ignore = "starts system git or is heavy; run with --features full-tests"
3966    )]
3967    #[test]
3968    fn commit_worktree_failed_pre_commit_leaves_split_index_unchanged() {
3969        let tmp = TempDir::new().unwrap();
3970        let root = tmp.path();
3971        system_git(root, &["init", "-q", "-b", "main"]);
3972        for i in 0..12 {
3973            fs::write(root.join(format!("f{i}.txt")), format!("{i}\n")).unwrap();
3974        }
3975        system_git(root, &["add", "."]);
3976        system_git(root, &["commit", "-qm", "init"]);
3977        system_git(root, &["config", "core.splitIndex", "true"]);
3978        system_git(root, &["update-index", "--split-index"]);
3979        fs::write(
3980            root.join(".git/config"),
3981            format!(
3982                "{}\n[hook \"hc\"]\n\tcommand = exit 1\n\tevent = pre-commit\n",
3983                fs::read_to_string(root.join(".git/config")).unwrap()
3984            ),
3985        )
3986        .unwrap();
3987
3988        fs::write(root.join("f0.txt"), b"blocked\n").unwrap();
3989        let repo = Repository::discover(Some(root), &RepositoryOptions::empty()).unwrap();
3990        let index_path = repo.git_dir().join("index");
3991        let index_before = fs::read(&index_path).unwrap();
3992        let shared_before = sharedindex_file_paths(repo.git_dir());
3993        let tip_before = resolve_ref(&repo.git_dir(), "refs/heads/main").unwrap();
3994
3995        let mut req = commit_req("blocked");
3996        req.hooks = HookPolicy::Run;
3997        assert!(commit_worktree(
3998            &repo,
3999            &req,
4000            &mut NullProgress,
4001            &crate::progress::CancelToken::never(),
4002        )
4003        .is_err());
4004
4005        assert_eq!(fs::read(&index_path).unwrap(), index_before);
4006        assert_eq!(sharedindex_file_paths(repo.git_dir()), shared_before);
4007        assert_eq!(
4008            resolve_ref(&repo.git_dir(), "refs/heads/main").unwrap(),
4009            tip_before
4010        );
4011        system_git(root, &["fsck", "--strict", "--no-progress"]);
4012    }
4013
4014    #[cfg_attr(
4015        not(feature = "full-tests"),
4016        ignore = "starts system git or is heavy; run with --features full-tests"
4017    )]
4018    #[test]
4019    fn commit_on_split_index_with_skip_hash_stays_readable_by_git() {
4020        for key in ["index.skipHash", "feature.manyFiles"] {
4021            let tmp = TempDir::new().unwrap();
4022            let root = tmp.path();
4023            system_git(root, &["init", "-q", "-b", "main"]);
4024            fs::write(root.join("a"), b"1\n").unwrap();
4025            system_git(root, &["add", "a"]);
4026            system_git(root, &["commit", "-qm", "c1"]);
4027            system_git(root, &["config", "core.splitIndex", "true"]);
4028            system_git(root, &["update-index", "--split-index"]);
4029            fs::write(root.join("a"), b"1\n2\n").unwrap();
4030            system_git(root, &["add", "a"]);
4031            system_git(root, &["commit", "-qm", "c2"]);
4032            system_git(root, &["config", key, "true"]);
4033            assert_eq!(system_git(root, &["status", "--short"]), "");
4034            fs::write(root.join("n"), b"n\n").unwrap();
4035
4036            let repo = Repository::discover(Some(root), &RepositoryOptions::empty()).unwrap();
4037            let outcome = commit_with_scope(
4038                &repo,
4039                &commit_req("g"),
4040                CommitScope::AutoStage,
4041                &mut NullProgress,
4042                &crate::progress::CancelToken::never(),
4043            )
4044            .unwrap();
4045
4046            assert_eq!(system_git(root, &["ls-files"]), "a\nn\n", "{key}");
4047            // Keep git from rebuilding the shared index itself: under skipHash it names it
4048            // `sharedindex.000…0` and then reads its own index as unsplit.
4049            system_git(root, &["config", "splitIndex.maxPercentChange", "100"]);
4050            assert_eq!(system_git(root, &["status", "--porcelain"]), "", "{key}");
4051            assert_eq!(
4052                system_git(root, &["rev-parse", "HEAD"]).trim(),
4053                outcome.oid.to_hex()
4054            );
4055            system_git(root, &["fsck", "--strict", "--no-progress"]);
4056            fs::write(root.join("m"), b"m\n").unwrap();
4057            system_git(root, &["add", "-A"]);
4058            system_git(root, &["commit", "-qm", "git after grit"]);
4059            assert_eq!(system_git(root, &["ls-files"]), "a\nm\nn\n", "{key}");
4060            assert_eq!(repo.load_index().unwrap().entries.len(), 3, "{key}");
4061        }
4062    }
4063
4064    fn author_info_from_commit(repo: &Repository, oid: ObjectId) -> CommitAuthorInfo {
4065        let data = repo.odb().read(&oid).unwrap().data;
4066        author_info_from_header_line(&parse_commit(&data).unwrap().author)
4067    }
4068
4069    fn git_head_commit_message(repo: &std::path::Path) -> String {
4070        let out = std::process::Command::new("git")
4071            .args(["cat-file", "commit", "HEAD"])
4072            .current_dir(repo)
4073            .output()
4074            .expect("git cat-file commit");
4075        assert!(out.status.success());
4076        let bytes = out.stdout;
4077        let mut i = 0usize;
4078        while i < bytes.len() {
4079            if i + 1 < bytes.len() && bytes[i] == b'\n' && bytes[i + 1] == b'\n' {
4080                i += 2;
4081                break;
4082            }
4083            i += 1;
4084        }
4085        String::from_utf8(bytes[i..].to_vec()).expect("utf-8 commit message")
4086    }
4087
4088    #[cfg_attr(
4089        not(feature = "full-tests"),
4090        ignore = "starts system git or is heavy; run with --features full-tests"
4091    )]
4092    #[test]
4093    fn message_file_stripspace() {
4094        let raw = "  subject  \n\n  body line  \n\n";
4095        let msg = normalize_commit_message(raw).unwrap();
4096        let tmp = TempDir::new().unwrap();
4097        let msg_path = tmp.path().join("msg.txt");
4098        std::fs::write(&msg_path, raw).unwrap();
4099        std::process::Command::new("git")
4100            .args(["init", "-q"])
4101            .current_dir(tmp.path())
4102            .status()
4103            .unwrap();
4104        std::process::Command::new("git")
4105            .args(["config", "user.name", "T"])
4106            .current_dir(tmp.path())
4107            .status()
4108            .unwrap();
4109        std::process::Command::new("git")
4110            .args(["config", "user.email", "t@e.com"])
4111            .current_dir(tmp.path())
4112            .status()
4113            .unwrap();
4114        std::fs::write(tmp.path().join("f"), "x\n").unwrap();
4115        std::process::Command::new("git")
4116            .args(["add", "f"])
4117            .current_dir(tmp.path())
4118            .status()
4119            .unwrap();
4120        std::process::Command::new("git")
4121            .args(["commit", "-F"])
4122            .arg(&msg_path)
4123            .current_dir(tmp.path())
4124            .status()
4125            .unwrap();
4126        let git_body = git_head_commit_message(tmp.path());
4127        assert_eq!(msg, git_body);
4128    }
4129
4130    #[cfg_attr(
4131        not(feature = "full-tests"),
4132        ignore = "starts system git or is heavy; run with --features full-tests"
4133    )]
4134    #[test]
4135    fn message_normalization_crlf_and_trailing_blanks_match_git_commit_f() {
4136        let raw = "\r\n  title  \r\n\r\n  body  \r\n\r\n\r\n";
4137        let grit_msg = normalize_commit_message(raw).unwrap();
4138        let tmp = tempfile::TempDir::new().unwrap();
4139        let msg_path = tmp.path().join("msg.txt");
4140        std::fs::write(&msg_path, raw).unwrap();
4141        let git_msg = std::process::Command::new("git")
4142            .args(["init", "-q"])
4143            .current_dir(tmp.path())
4144            .status()
4145            .unwrap();
4146        assert!(git_msg.success());
4147        std::process::Command::new("git")
4148            .args(["config", "user.name", "T"])
4149            .current_dir(tmp.path())
4150            .status()
4151            .unwrap();
4152        std::process::Command::new("git")
4153            .args(["config", "user.email", "t@e.com"])
4154            .current_dir(tmp.path())
4155            .status()
4156            .unwrap();
4157        std::fs::write(tmp.path().join("f"), "x\n").unwrap();
4158        std::process::Command::new("git")
4159            .args(["add", "f"])
4160            .current_dir(tmp.path())
4161            .status()
4162            .unwrap();
4163        std::process::Command::new("git")
4164            .args(["commit", "-F"])
4165            .arg(&msg_path)
4166            .current_dir(tmp.path())
4167            .status()
4168            .unwrap();
4169        let git_body = git_head_commit_message(tmp.path());
4170        assert_eq!(grit_msg, git_body);
4171    }
4172
4173    #[test]
4174    fn no_verify_skips_pre_commit_and_commit_msg() {
4175        let tmp = TempDir::new().unwrap();
4176        let root = tmp.path();
4177        let repo = init_repo(root);
4178        std::fs::write(
4179            repo.git_dir().join("config"),
4180            "[core]\n\trepositoryformatversion = 0\n\tbare = false\n\tlogAllRefUpdates = true\n[hook \"hc\"]\n\tcommand = exit 1\n\tevent = pre-commit\n[hook \"hc2\"]\n\tcommand = exit 1\n\tevent = commit-msg\n",
4181        )
4182        .unwrap();
4183        fs::write(root.join("a.txt"), b"1\n").unwrap();
4184        stage(
4185            &repo,
4186            &StageOptions::default(),
4187            &mut NullProgress,
4188            &crate::progress::CancelToken::never(),
4189        )
4190        .unwrap();
4191
4192        let mut req = commit_req("blocked");
4193        req.hooks = HookPolicy::Run;
4194        assert!(create_commit(
4195            &repo,
4196            &req,
4197            &mut NullProgress,
4198            &crate::progress::CancelToken::never()
4199        )
4200        .is_err());
4201
4202        req.hooks = HookPolicy::SkipVerify;
4203        let outcome = create_commit(
4204            &repo,
4205            &req,
4206            &mut NullProgress,
4207            &crate::progress::CancelToken::never(),
4208        )
4209        .unwrap();
4210        assert!(outcome.hooks_run.is_empty());
4211    }
4212
4213    #[test]
4214    fn post_commit_hook_failure_does_not_fail_commit() {
4215        use crate::hooks::HookName;
4216
4217        let tmp = TempDir::new().unwrap();
4218        let root = tmp.path();
4219        let repo = init_repo(root);
4220        std::fs::write(
4221            repo.git_dir().join("config"),
4222            "[core]\n\trepositoryformatversion = 0\n\tbare = false\n\tlogAllRefUpdates = true\n[hook \"hc\"]\n\tcommand = exit 9\n\tevent = post-commit\n",
4223        )
4224        .unwrap();
4225        fs::write(root.join("a.txt"), b"1\n").unwrap();
4226        stage(
4227            &repo,
4228            &StageOptions::default(),
4229            &mut NullProgress,
4230            &crate::progress::CancelToken::never(),
4231        )
4232        .unwrap();
4233        let outcome = create_commit(
4234            &repo,
4235            &commit_req("after post"),
4236            &mut NullProgress,
4237            &crate::progress::CancelToken::never(),
4238        )
4239        .unwrap();
4240        assert_eq!(
4241            resolve_ref(&repo.git_dir(), "refs/heads/main").unwrap(),
4242            outcome.oid
4243        );
4244        assert!(outcome.hooks_run.contains(&HookName::PostCommit));
4245    }
4246
4247    #[test]
4248    fn hooks_run_lists_executed_hooks() {
4249        use crate::hooks::HookName;
4250
4251        let tmp = TempDir::new().unwrap();
4252        let root = tmp.path();
4253        let repo = init_repo(root);
4254        std::fs::write(
4255            repo.git_dir().join("config"),
4256            "[core]\n\trepositoryformatversion = 0\n\tbare = false\n\tlogAllRefUpdates = true\n[hook \"hc\"]\n\tcommand = true\n\tevent = pre-commit\n[hook \"hc2\"]\n\tcommand = true\n\tevent = commit-msg\n[hook \"hc3\"]\n\tcommand = true\n\tevent = post-commit\n[hook \"hp\"]\n\tcommand = echo \"prepared $2\" >>$1\n\tevent = prepare-commit-msg\n",
4257        )
4258        .unwrap();
4259        fs::write(root.join("a.txt"), b"1\n").unwrap();
4260        stage(
4261            &repo,
4262            &StageOptions::default(),
4263            &mut NullProgress,
4264            &crate::progress::CancelToken::never(),
4265        )
4266        .unwrap();
4267        let outcome = create_commit(
4268            &repo,
4269            &commit_req("hooks"),
4270            &mut NullProgress,
4271            &crate::progress::CancelToken::never(),
4272        )
4273        .unwrap();
4274        assert_eq!(
4275            outcome.hooks_run,
4276            vec![
4277                HookName::PreCommit,
4278                HookName::PrepareCommitMsg,
4279                HookName::CommitMsg,
4280                HookName::PostCommit
4281            ]
4282        );
4283        let commit = parse_commit(&repo.odb().read(&outcome.oid).unwrap().data).unwrap();
4284        assert_eq!(commit.message, "hooks\nprepared message\n");
4285
4286        fs::write(root.join("a.txt"), b"2\n").unwrap();
4287        stage(
4288            &repo,
4289            &StageOptions::default(),
4290            &mut NullProgress,
4291            &crate::progress::CancelToken::never(),
4292        )
4293        .unwrap();
4294        let mut req = commit_req("skip verify");
4295        req.hooks = HookPolicy::SkipVerify;
4296        let outcome = create_commit(
4297            &repo,
4298            &req,
4299            &mut NullProgress,
4300            &crate::progress::CancelToken::never(),
4301        )
4302        .unwrap();
4303        assert_eq!(
4304            outcome.hooks_run,
4305            vec![HookName::PrepareCommitMsg, HookName::PostCommit]
4306        );
4307    }
4308
4309    #[test]
4310    fn author_date_override() {
4311        let tmp = TempDir::new().unwrap();
4312        let root = tmp.path();
4313        let repo = init_repo(root);
4314        fs::write(root.join("a.txt"), b"1\n").unwrap();
4315        stage(
4316            &repo,
4317            &StageOptions::default(),
4318            &mut NullProgress,
4319            &crate::progress::CancelToken::never(),
4320        )
4321        .unwrap();
4322        let mut req = commit_req("dated");
4323        req.author_date = Some("946684800 +0000".to_owned());
4324        let outcome = create_commit(
4325            &repo,
4326            &req,
4327            &mut NullProgress,
4328            &crate::progress::CancelToken::never(),
4329        )
4330        .unwrap();
4331        assert_eq!(outcome.author.date, "946684800 +0000");
4332    }
4333
4334    #[test]
4335    fn trailers_appended_and_deduped() {
4336        let tmp = TempDir::new().unwrap();
4337        let root = tmp.path();
4338        let repo = init_repo(root);
4339        fs::write(root.join("a.txt"), b"1\n").unwrap();
4340        stage(
4341            &repo,
4342            &StageOptions::default(),
4343            &mut NullProgress,
4344            &crate::progress::CancelToken::never(),
4345        )
4346        .unwrap();
4347        let mut req = commit_req("trailers");
4348        req.trailers = vec![
4349            ("Acked-by".to_owned(), "Alice".to_owned()),
4350            ("Acked-by".to_owned(), "Alice".to_owned()),
4351        ];
4352        let outcome = create_commit(
4353            &repo,
4354            &req,
4355            &mut NullProgress,
4356            &crate::progress::CancelToken::never(),
4357        )
4358        .unwrap();
4359        let msg = parse_commit(&repo.odb().read(&outcome.oid).unwrap().data)
4360            .unwrap()
4361            .message;
4362        assert_eq!(msg.matches("Acked-by: Alice").count(), 1);
4363    }
4364
4365    #[test]
4366    fn signoff_uses_committer() {
4367        let tmp = TempDir::new().unwrap();
4368        let root = tmp.path();
4369        let repo = init_repo(root);
4370        fs::write(root.join("a.txt"), b"1\n").unwrap();
4371        stage(
4372            &repo,
4373            &StageOptions::default(),
4374            &mut NullProgress,
4375            &crate::progress::CancelToken::never(),
4376        )
4377        .unwrap();
4378        let mut req = commit_req("signoff");
4379        req.committer = Some(
4380            "Committer Name <committer@example.com> 2 +0000"
4381                .parse()
4382                .expect("signature"),
4383        );
4384        req.signoff = true;
4385        let outcome = create_commit(
4386            &repo,
4387            &req,
4388            &mut NullProgress,
4389            &crate::progress::CancelToken::never(),
4390        )
4391        .unwrap();
4392        let msg = parse_commit(&repo.odb().read(&outcome.oid).unwrap().data)
4393            .unwrap()
4394            .message;
4395        assert!(msg.contains("Signed-off-by: Committer Name <committer@example.com>"));
4396    }
4397
4398    #[test]
4399    fn signoff_before_explicit_trailers() {
4400        let tmp = TempDir::new().unwrap();
4401        let root = tmp.path();
4402        let repo = init_repo(root);
4403        fs::write(root.join("a.txt"), b"1\n").unwrap();
4404        stage(
4405            &repo,
4406            &StageOptions::default(),
4407            &mut NullProgress,
4408            &crate::progress::CancelToken::never(),
4409        )
4410        .unwrap();
4411        let mut req = commit_req("subject\n");
4412        req.committer = Some(
4413            "Committer Name <committer@example.com> 2 +0000"
4414                .parse()
4415                .expect("signature"),
4416        );
4417        req.signoff = true;
4418        req.trailers = vec![("Acked-by".to_owned(), "Alice".to_owned())];
4419        let outcome = create_commit(
4420            &repo,
4421            &req,
4422            &mut NullProgress,
4423            &crate::progress::CancelToken::never(),
4424        )
4425        .unwrap();
4426        let msg = parse_commit(&repo.odb().read(&outcome.oid).unwrap().data)
4427            .unwrap()
4428            .message;
4429        let sob = msg.find("Signed-off-by:").expect("signoff trailer");
4430        let ack = msg.find("Acked-by:").expect("acked trailer");
4431        assert!(sob < ack, "signoff must precede explicit trailers:\n{msg}");
4432    }
4433
4434    #[test]
4435    fn amend_reuse_message_from_source() {
4436        let tmp = TempDir::new().unwrap();
4437        let root = tmp.path();
4438        let repo = init_repo(root);
4439        fs::write(root.join("a.txt"), b"1\n").unwrap();
4440        stage(
4441            &repo,
4442            &StageOptions::default(),
4443            &mut NullProgress,
4444            &crate::progress::CancelToken::never(),
4445        )
4446        .unwrap();
4447        let mut source = commit_req("source subject\n");
4448        source.author = Some(
4449            "Source Author <author@example.com> 978307200 +0000"
4450                .parse()
4451                .expect("signature"),
4452        );
4453        source.committer = Some(ident().parse().expect("signature"));
4454        let source_out = create_commit(
4455            &repo,
4456            &source,
4457            &mut NullProgress,
4458            &crate::progress::CancelToken::never(),
4459        )
4460        .unwrap();
4461
4462        fs::write(root.join("a.txt"), b"2\n").unwrap();
4463        stage(
4464            &repo,
4465            &StageOptions::default(),
4466            &mut NullProgress,
4467            &crate::progress::CancelToken::never(),
4468        )
4469        .unwrap();
4470        let mut tip = commit_req("tip subject\n");
4471        tip.author = Some(
4472            "Tip Author <tip@example.com> 1792591163 +0000"
4473                .parse()
4474                .expect("signature"),
4475        );
4476        create_commit(
4477            &repo,
4478            &tip,
4479            &mut NullProgress,
4480            &crate::progress::CancelToken::never(),
4481        )
4482        .unwrap();
4483
4484        fs::write(root.join("a.txt"), b"3\n").unwrap();
4485        stage(
4486            &repo,
4487            &StageOptions::default(),
4488            &mut NullProgress,
4489            &crate::progress::CancelToken::never(),
4490        )
4491        .unwrap();
4492        let mut amend = commit_req("");
4493        amend.amend = true;
4494        amend.author = None;
4495        amend.reuse_message_from = Some(source_out.oid);
4496        let outcome = create_commit(
4497            &repo,
4498            &amend,
4499            &mut NullProgress,
4500            &crate::progress::CancelToken::never(),
4501        )
4502        .unwrap();
4503        let author = author_info_from_commit(&repo, outcome.oid);
4504        assert_eq!(author.name, "Source Author");
4505        assert_eq!(author.email, "author@example.com");
4506        assert_eq!(author.date, "978307200 +0000");
4507        let msg = parse_commit(&repo.odb().read(&outcome.oid).unwrap().data)
4508            .unwrap()
4509            .message;
4510        assert!(msg.starts_with("source subject"));
4511    }
4512
4513    #[test]
4514    fn amend_reuse_message_reset_author_uses_committer() {
4515        let tmp = TempDir::new().unwrap();
4516        let root = tmp.path();
4517        let repo = init_repo(root);
4518        fs::write(root.join("a.txt"), b"1\n").unwrap();
4519        stage(
4520            &repo,
4521            &StageOptions::default(),
4522            &mut NullProgress,
4523            &crate::progress::CancelToken::never(),
4524        )
4525        .unwrap();
4526        let mut source = commit_req("source subject\n");
4527        source.author = Some(
4528            "Source Author <author@example.com> 978307200 +0000"
4529                .parse()
4530                .expect("signature"),
4531        );
4532        let source_out = create_commit(
4533            &repo,
4534            &source,
4535            &mut NullProgress,
4536            &crate::progress::CancelToken::never(),
4537        )
4538        .unwrap();
4539
4540        fs::write(root.join("a.txt"), b"2\n").unwrap();
4541        stage(
4542            &repo,
4543            &StageOptions::default(),
4544            &mut NullProgress,
4545            &crate::progress::CancelToken::never(),
4546        )
4547        .unwrap();
4548        create_commit(
4549            &repo,
4550            &commit_req("tip"),
4551            &mut NullProgress,
4552            &crate::progress::CancelToken::never(),
4553        )
4554        .unwrap();
4555
4556        fs::write(root.join("a.txt"), b"3\n").unwrap();
4557        stage(
4558            &repo,
4559            &StageOptions::default(),
4560            &mut NullProgress,
4561            &crate::progress::CancelToken::never(),
4562        )
4563        .unwrap();
4564        let mut amend = commit_req("");
4565        amend.amend = true;
4566        amend.author = None;
4567        amend.reset_author = true;
4568        amend.committer = Some(
4569            "Reset Author <reset@example.com> 1800000000 +0000"
4570                .parse()
4571                .expect("signature"),
4572        );
4573        amend.reuse_message_from = Some(source_out.oid);
4574        let outcome = create_commit(
4575            &repo,
4576            &amend,
4577            &mut NullProgress,
4578            &crate::progress::CancelToken::never(),
4579        )
4580        .unwrap();
4581        let author = author_info_from_commit(&repo, outcome.oid);
4582        assert_eq!(author.name, "Reset Author");
4583        assert_eq!(author.email, "reset@example.com");
4584    }
4585
4586    #[test]
4587    fn reuse_message_keeps_author() {
4588        let tmp = TempDir::new().unwrap();
4589        let root = tmp.path();
4590        let repo = init_repo(root);
4591        fs::write(root.join("a.txt"), b"1\n").unwrap();
4592        stage(
4593            &repo,
4594            &StageOptions::default(),
4595            &mut NullProgress,
4596            &crate::progress::CancelToken::never(),
4597        )
4598        .unwrap();
4599        let mut first = commit_req("source");
4600        first.author = Some(
4601            "Source Author <source@example.com> 99 +0000"
4602                .parse()
4603                .expect("signature"),
4604        );
4605        first.committer = Some(ident().parse().expect("signature"));
4606        let first_out = create_commit(
4607            &repo,
4608            &first,
4609            &mut NullProgress,
4610            &crate::progress::CancelToken::never(),
4611        )
4612        .unwrap();
4613
4614        fs::write(root.join("a.txt"), b"2\n").unwrap();
4615        stage(
4616            &repo,
4617            &StageOptions::default(),
4618            &mut NullProgress,
4619            &crate::progress::CancelToken::never(),
4620        )
4621        .unwrap();
4622        let mut req = commit_req("");
4623        req.author = None;
4624        req.reuse_message_from = Some(first_out.oid);
4625        let outcome = create_commit(
4626            &repo,
4627            &req,
4628            &mut NullProgress,
4629            &crate::progress::CancelToken::never(),
4630        )
4631        .unwrap();
4632        let author = author_info_from_commit(&repo, outcome.oid);
4633        assert_eq!(author.name, "Source Author");
4634        assert_eq!(author.email, "source@example.com");
4635        assert_eq!(author.date, "99 +0000");
4636    }
4637
4638    #[test]
4639    fn reset_author_with_reuse_and_amend() {
4640        let tmp = TempDir::new().unwrap();
4641        let root = tmp.path();
4642        let repo = init_repo(root);
4643        fs::write(root.join("a.txt"), b"1\n").unwrap();
4644        stage(
4645            &repo,
4646            &StageOptions::default(),
4647            &mut NullProgress,
4648            &crate::progress::CancelToken::never(),
4649        )
4650        .unwrap();
4651        let mut first = commit_req("source");
4652        first.author = Some("Old <old@example.com> 1 +0000".parse().expect("signature"));
4653        create_commit(
4654            &repo,
4655            &first,
4656            &mut NullProgress,
4657            &crate::progress::CancelToken::never(),
4658        )
4659        .unwrap();
4660
4661        fs::write(root.join("a.txt"), b"2\n").unwrap();
4662        stage(
4663            &repo,
4664            &StageOptions::default(),
4665            &mut NullProgress,
4666            &crate::progress::CancelToken::never(),
4667        )
4668        .unwrap();
4669        create_commit(
4670            &repo,
4671            &commit_req("second"),
4672            &mut NullProgress,
4673            &crate::progress::CancelToken::never(),
4674        )
4675        .unwrap();
4676
4677        let mut amend = commit_req("");
4678        amend.amend = true;
4679        amend.author = None;
4680        amend.reset_author = true;
4681        amend.committer = Some(
4682            "New Committer <new@example.com> 2000 +0000"
4683                .parse()
4684                .expect("signature"),
4685        );
4686        let outcome = create_commit(
4687            &repo,
4688            &amend,
4689            &mut NullProgress,
4690            &crate::progress::CancelToken::never(),
4691        )
4692        .unwrap();
4693        let author = author_info_from_commit(&repo, outcome.oid);
4694        assert_eq!(author.name, "New Committer");
4695        assert_eq!(author.email, "new@example.com");
4696    }
4697
4698    #[test]
4699    fn reuse_message_gets_new_change_id() {
4700        use crate::change_id::{change_id, ChangeIdError, ChangeIdGenerator};
4701        use std::sync::Arc;
4702
4703        struct FixedGenerator([u8; 16]);
4704        impl ChangeIdGenerator for FixedGenerator {
4705            fn random_bytes(&self) -> std::result::Result<[u8; 16], ChangeIdError> {
4706                Ok(self.0)
4707            }
4708        }
4709
4710        let tmp = TempDir::new().unwrap();
4711        let root = tmp.path();
4712        let gen1: Arc<dyn ChangeIdGenerator> = Arc::new(FixedGenerator([0x11; 16]));
4713        let git = root.join(".git");
4714        fs::create_dir_all(git.join("objects")).unwrap();
4715        fs::create_dir_all(git.join("refs/heads")).unwrap();
4716        fs::write(git.join("HEAD"), "ref: refs/heads/main\n").unwrap();
4717        fs::write(
4718            git.join("config"),
4719            "[core]\n\trepositoryformatversion = 0\n\tbare = false\n\tlogAllRefUpdates = true\n",
4720        )
4721        .unwrap();
4722        let repo = Repository::open(
4723            &git,
4724            &RepositoryOptions::empty()
4725                .with_work_tree(root)
4726                .with_change_id_generator(gen1),
4727        )
4728        .unwrap();
4729        fs::write(root.join("a.txt"), b"1\n").unwrap();
4730        stage(
4731            &repo,
4732            &StageOptions::default(),
4733            &mut NullProgress,
4734            &crate::progress::CancelToken::never(),
4735        )
4736        .unwrap();
4737        let source = create_commit(
4738            &repo,
4739            &commit_req("source"),
4740            &mut NullProgress,
4741            &crate::progress::CancelToken::never(),
4742        )
4743        .unwrap();
4744        let source_data = parse_commit(&repo.odb().read(&source.oid).unwrap().data).unwrap();
4745        let source_id = change_id(&source_data).expect("source change id");
4746
4747        let gen2: Arc<dyn ChangeIdGenerator> = Arc::new(FixedGenerator([0x22; 16]));
4748        let repo = Repository::open(
4749            &git,
4750            &RepositoryOptions::empty()
4751                .with_work_tree(root)
4752                .with_change_id_generator(gen2),
4753        )
4754        .unwrap();
4755        fs::write(root.join("a.txt"), b"2\n").unwrap();
4756        stage(
4757            &repo,
4758            &StageOptions::default(),
4759            &mut NullProgress,
4760            &crate::progress::CancelToken::never(),
4761        )
4762        .unwrap();
4763        let mut req = commit_req("");
4764        req.author = None;
4765        req.reuse_message_from = Some(source.oid);
4766        let copy = create_commit(
4767            &repo,
4768            &req,
4769            &mut NullProgress,
4770            &crate::progress::CancelToken::never(),
4771        )
4772        .unwrap();
4773        let copy_data = parse_commit(&repo.odb().read(&copy.oid).unwrap().data).unwrap();
4774        let copy_id = change_id(&copy_data).expect("copy change id");
4775        assert_ne!(copy_id, source_id);
4776    }
4777
4778    #[test]
4779    fn outcome_parents_merge_commit() {
4780        let tmp = TempDir::new().unwrap();
4781        let root = tmp.path();
4782        let repo = init_repo(root);
4783        fs::write(root.join("a.txt"), b"1\n").unwrap();
4784        stage(
4785            &repo,
4786            &StageOptions::default(),
4787            &mut NullProgress,
4788            &crate::progress::CancelToken::never(),
4789        )
4790        .unwrap();
4791        let first = create_commit(
4792            &repo,
4793            &commit_req("first"),
4794            &mut NullProgress,
4795            &crate::progress::CancelToken::never(),
4796        )
4797        .unwrap();
4798
4799        fs::write(root.join("b.txt"), b"2\n").unwrap();
4800        stage(
4801            &repo,
4802            &StageOptions::default(),
4803            &mut NullProgress,
4804            &crate::progress::CancelToken::never(),
4805        )
4806        .unwrap();
4807        let second = create_commit(
4808            &repo,
4809            &commit_req("second"),
4810            &mut NullProgress,
4811            &crate::progress::CancelToken::never(),
4812        )
4813        .unwrap();
4814
4815        fs::write(
4816            repo.git_dir().join("MERGE_HEAD"),
4817            format!("{}\n", first.oid.to_hex()),
4818        )
4819        .unwrap();
4820        fs::write(root.join("a.txt"), b"merged\n").unwrap();
4821        stage(
4822            &repo,
4823            &StageOptions::default(),
4824            &mut NullProgress,
4825            &crate::progress::CancelToken::never(),
4826        )
4827        .unwrap();
4828        let merge = create_commit(
4829            &repo,
4830            &commit_req("merge"),
4831            &mut NullProgress,
4832            &crate::progress::CancelToken::never(),
4833        )
4834        .unwrap();
4835        assert_eq!(merge.parents.len(), 2);
4836        assert_eq!(merge.parents[0], second.oid);
4837        assert_eq!(merge.parents[1], first.oid);
4838    }
4839
4840    #[test]
4841    fn auto_stage_config_false_defaults_to_staged() {
4842        let tmp = TempDir::new().unwrap();
4843        let root = tmp.path();
4844        let git = root.join(".git");
4845        fs::create_dir_all(git.join("objects")).unwrap();
4846        fs::create_dir_all(git.join("refs/heads")).unwrap();
4847        fs::write(git.join("HEAD"), "ref: refs/heads/main\n").unwrap();
4848        fs::write(
4849            git.join("config"),
4850            "[core]\n\trepositoryformatversion = 0\n\tbare = false\n\tlogAllRefUpdates = true\n[commit]\n\tautoStage = false\n",
4851        )
4852        .unwrap();
4853        let repo =
4854            Repository::open(&git, &RepositoryOptions::empty().with_work_tree(root)).unwrap();
4855        assert_eq!(
4856            default_commit_scope_from_config(&repo.config().snapshot().unwrap()),
4857            CommitScope::Staged
4858        );
4859    }
4860
4861    #[test]
4862    fn dry_run_path_scope_includes_untracked_add() {
4863        let tmp = TempDir::new().unwrap();
4864        let root = tmp.path();
4865        let repo = init_repo(root);
4866        fs::write(root.join("tracked.txt"), b"1\n").unwrap();
4867        stage(
4868            &repo,
4869            &StageOptions::default(),
4870            &mut NullProgress,
4871            &crate::progress::CancelToken::never(),
4872        )
4873        .unwrap();
4874        create_commit(
4875            &repo,
4876            &commit_req("first"),
4877            &mut NullProgress,
4878            &crate::progress::CancelToken::never(),
4879        )
4880        .unwrap();
4881        fs::write(root.join("new.txt"), b"new\n").unwrap();
4882        let paths = Pathspec::scoped(["new.txt"], PathspecGlobalFlags::default());
4883        let before = repo_snapshot(&repo);
4884        let plan = plan_commit(
4885            &repo,
4886            &dry_run_req("add new"),
4887            CommitScope::Paths(paths),
4888            &mut NullProgress,
4889            &crate::progress::CancelToken::never(),
4890        )
4891        .unwrap();
4892        assert_eq!(plan.files.len(), 1);
4893        assert_eq!(plan.files[0].path, "new.txt");
4894        assert_eq!(repo_snapshot(&repo), before);
4895    }
4896
4897    #[test]
4898    fn dry_run_amend_honors_author_override() {
4899        let tmp = TempDir::new().unwrap();
4900        let root = tmp.path();
4901        let repo = init_repo(root);
4902        fs::write(root.join("a.txt"), b"1\n").unwrap();
4903        stage(
4904            &repo,
4905            &StageOptions::default(),
4906            &mut NullProgress,
4907            &crate::progress::CancelToken::never(),
4908        )
4909        .unwrap();
4910        create_commit(
4911            &repo,
4912            &commit_req("first"),
4913            &mut NullProgress,
4914            &crate::progress::CancelToken::never(),
4915        )
4916        .unwrap();
4917        fs::write(root.join("a.txt"), b"2\n").unwrap();
4918        stage(
4919            &repo,
4920            &StageOptions::default(),
4921            &mut NullProgress,
4922            &crate::progress::CancelToken::never(),
4923        )
4924        .unwrap();
4925        let mut req = dry_run_req("amend");
4926        req.amend = true;
4927        req.author = Some(
4928            "Override <o@example.com> 1700000000 +0000"
4929                .parse()
4930                .expect("signature"),
4931        );
4932        let outcome = commit_with_scope(
4933            &repo,
4934            &req,
4935            CommitScope::Staged,
4936            &mut NullProgress,
4937            &crate::progress::CancelToken::never(),
4938        )
4939        .unwrap();
4940        assert_eq!(outcome.author.email, "o@example.com");
4941        assert_eq!(outcome.author.name, "Override");
4942    }
4943
4944    fn git(dir: &std::path::Path, args: &[&str]) {
4945        let out = grit_test_support::merge_git_config_env(&mut Command::new("git"), &[])
4946            .current_dir(dir)
4947            .args(args)
4948            .env("GIT_CONFIG_GLOBAL", "/dev/null")
4949            .env("GIT_CONFIG_SYSTEM", "/dev/null")
4950            .output()
4951            .expect("git");
4952        assert!(
4953            out.status.success(),
4954            "git {args:?}: {}",
4955            String::from_utf8_lossy(&out.stderr)
4956        );
4957    }
4958
4959    fn two_hunk_file() -> (String, String) {
4960        let mut base = String::new();
4961        for i in 0..24 {
4962            base.push_str(&format!("line{i}\n"));
4963        }
4964        let mut edited = base.clone();
4965        edited = edited.replacen("line5\n", "LINE5\n", 1);
4966        edited = edited.replacen("line18\n", "LINE18\n", 1);
4967        (base, edited)
4968    }
4969
4970    fn tree_blob(repo: &Repository, tree_oid: &ObjectId, path: &str) -> Vec<u8> {
4971        for (p, _mode, oid) in crate::diff::flatten_tree_entries(repo.odb(), tree_oid).unwrap() {
4972            if p == path {
4973                return repo.odb().read(&oid).unwrap().data;
4974            }
4975        }
4976        panic!("missing {path} in tree");
4977    }
4978
4979    #[test]
4980    fn commit_hunks_only_selected_in_tree() {
4981        use crate::diff::{hunk_ids, DiffSide};
4982        use crate::diff::{unstaged_file_diffs_with_peer_hunks, DiffOptions};
4983        use crate::porcelain::hunk_select::HunkSelection;
4984
4985        let tmp = TempDir::new().unwrap();
4986        let root = tmp.path();
4987        let repo = init_repo(root);
4988        let (base, edited) = two_hunk_file();
4989        fs::write(root.join("f.txt"), base).unwrap();
4990        stage(
4991            &repo,
4992            &StageOptions::default(),
4993            &mut NullProgress,
4994            &crate::progress::CancelToken::never(),
4995        )
4996        .unwrap();
4997        create_commit(
4998            &repo,
4999            &commit_req("init"),
5000            &mut NullProgress,
5001            &crate::progress::CancelToken::never(),
5002        )
5003        .unwrap();
5004        fs::write(root.join("f.txt"), edited).unwrap();
5005
5006        let (files, peers) =
5007            unstaged_file_diffs_with_peer_hunks(&repo, &[], DiffOptions::default()).unwrap();
5008        let ids = hunk_ids(
5009            DiffSide::Unstaged,
5010            "f.txt",
5011            &files[0].hunks,
5012            peers.get("f.txt").map(|v| v.as_slice()).unwrap_or(&[]),
5013        );
5014        commit_with_patch(
5015            &repo,
5016            &commit_req("one hunk"),
5017            CommitPatchInput::Hunks(HunkSelection {
5018                ids: vec![ids[0].clone()],
5019                ranges: Vec::new(),
5020            }),
5021            &[],
5022            &mut NullProgress,
5023            &crate::progress::CancelToken::never(),
5024        )
5025        .unwrap();
5026
5027        let tip = resolve_ref(&repo.git_dir(), "refs/heads/main").unwrap();
5028        let tree = parse_commit(&repo.odb().read(&tip).unwrap().data)
5029            .unwrap()
5030            .tree;
5031        let blob = tree_blob(&repo, &tree, "f.txt");
5032        let text = String::from_utf8_lossy(&blob);
5033        assert!(text.contains("LINE5"), "first hunk in commit tree");
5034        assert!(
5035            !text.contains("LINE18"),
5036            "second hunk must not be in commit tree: {text}"
5037        );
5038    }
5039
5040    #[cfg_attr(
5041        not(feature = "full-tests"),
5042        ignore = "starts system git or is heavy; run with --features full-tests"
5043    )]
5044    #[test]
5045    fn commit_hunks_leaves_other_unstaged() {
5046        use crate::diff::{hunk_ids, DiffSide};
5047        use crate::diff::{unstaged_file_diffs_with_peer_hunks, DiffOptions};
5048        use crate::porcelain::hunk_select::HunkSelection;
5049
5050        let tmp = TempDir::new().unwrap();
5051        let root = tmp.path();
5052        let repo = init_repo(root);
5053        let (base, edited) = two_hunk_file();
5054        fs::write(root.join("f.txt"), base).unwrap();
5055        stage(
5056            &repo,
5057            &StageOptions::default(),
5058            &mut NullProgress,
5059            &crate::progress::CancelToken::never(),
5060        )
5061        .unwrap();
5062        create_commit(
5063            &repo,
5064            &commit_req("init"),
5065            &mut NullProgress,
5066            &crate::progress::CancelToken::never(),
5067        )
5068        .unwrap();
5069        fs::write(root.join("f.txt"), edited).unwrap();
5070
5071        let (files, peers) =
5072            unstaged_file_diffs_with_peer_hunks(&repo, &[], DiffOptions::default()).unwrap();
5073        let ids = hunk_ids(
5074            DiffSide::Unstaged,
5075            "f.txt",
5076            &files[0].hunks,
5077            peers.get("f.txt").map(|v| v.as_slice()).unwrap_or(&[]),
5078        );
5079        commit_with_patch(
5080            &repo,
5081            &commit_req("partial"),
5082            CommitPatchInput::Hunks(HunkSelection {
5083                ids: vec![ids[0].clone()],
5084                ranges: Vec::new(),
5085            }),
5086            &[],
5087            &mut NullProgress,
5088            &crate::progress::CancelToken::never(),
5089        )
5090        .unwrap();
5091
5092        let diff = run_grit_status_unstaged(root);
5093        assert!(
5094            diff.contains("line18") || diff.contains("LINE18"),
5095            "remaining hunk still unstaged: {diff}"
5096        );
5097        git(root, &["fsck", "--strict"]);
5098    }
5099
5100    fn run_grit_status_unstaged(root: &std::path::Path) -> String {
5101        let out = Command::new("git")
5102            .current_dir(root)
5103            .args(["diff"])
5104            .env("GIT_CONFIG_GLOBAL", "/dev/null")
5105            .env("GIT_CONFIG_SYSTEM", "/dev/null")
5106            .output()
5107            .unwrap();
5108        String::from_utf8_lossy(&out.stdout).into_owned()
5109    }
5110
5111    fn format_patch_for_git(patch: &FilePatch) -> String {
5112        use crate::apply::HunkLine;
5113        let mut out = String::new();
5114        let path = patch.effective_path().unwrap_or("f");
5115        out.push_str(&format!("diff --git a/{path} b/{path}\n"));
5116        if patch.is_new {
5117            out.push_str("new file mode 100644\n");
5118        }
5119        let old = if patch.is_new {
5120            "/dev/null".to_string()
5121        } else {
5122            format!("a/{}", patch.old_path.as_deref().unwrap_or(path))
5123        };
5124        let new = if patch.is_deleted {
5125            "/dev/null".to_string()
5126        } else {
5127            format!("b/{}", patch.new_path.as_deref().unwrap_or(path))
5128        };
5129        out.push_str(&format!("--- {old}\n"));
5130        out.push_str(&format!("+++ {new}\n"));
5131        for h in &patch.hunks {
5132            out.push_str(&format!(
5133                "@@ -{},{} +{},{} @@\n",
5134                h.old_start, h.old_count, h.new_start, h.new_count
5135            ));
5136            for line in &h.lines {
5137                match line {
5138                    HunkLine::Context(s) => {
5139                        out.push(' ');
5140                        out.push_str(s);
5141                        if !s.ends_with('\n') {
5142                            out.push('\n');
5143                        }
5144                    }
5145                    HunkLine::Add(s) => {
5146                        out.push('+');
5147                        out.push_str(s);
5148                        if !s.ends_with('\n') {
5149                            out.push('\n');
5150                        }
5151                    }
5152                    HunkLine::Remove(s) => {
5153                        out.push('-');
5154                        out.push_str(s);
5155                        if !s.ends_with('\n') {
5156                            out.push('\n');
5157                        }
5158                    }
5159                    HunkLine::NoNewline => out.push_str("\\ No newline at end of file\n"),
5160                }
5161            }
5162        }
5163        out
5164    }
5165
5166    #[cfg_attr(
5167        not(feature = "full-tests"),
5168        ignore = "starts system git or is heavy; run with --features full-tests"
5169    )]
5170    #[test]
5171    fn commit_patch_file_matches_git_apply_cached_then_commit() {
5172        use crate::diff::{hunk_ids, DiffSide};
5173        use crate::diff::{unstaged_file_diffs_with_peer_hunks, DiffOptions};
5174        use crate::porcelain::hunk_select::{resolve_selection, HunkSelection};
5175
5176        let tmp = TempDir::new().unwrap();
5177        let root = tmp.path();
5178        let repo = init_repo(root);
5179        let (base, edited) = two_hunk_file();
5180        fs::write(root.join("f.txt"), base.clone()).unwrap();
5181        stage(
5182            &repo,
5183            &StageOptions::default(),
5184            &mut NullProgress,
5185            &crate::progress::CancelToken::never(),
5186        )
5187        .unwrap();
5188        create_commit(
5189            &repo,
5190            &commit_req("init"),
5191            &mut NullProgress,
5192            &crate::progress::CancelToken::never(),
5193        )
5194        .unwrap();
5195        fs::write(root.join("f.txt"), edited.clone()).unwrap();
5196
5197        let (files, peers) =
5198            unstaged_file_diffs_with_peer_hunks(&repo, &[], DiffOptions::default()).unwrap();
5199        let ids = hunk_ids(
5200            DiffSide::Unstaged,
5201            "f.txt",
5202            &files[0].hunks,
5203            peers.get("f.txt").map(|v| v.as_slice()).unwrap_or(&[]),
5204        );
5205        let patch = resolve_selection(
5206            &repo,
5207            DiffSide::Unstaged,
5208            &HunkSelection {
5209                ids: vec![ids[0].clone()],
5210                ranges: Vec::new(),
5211            },
5212            &[],
5213            DiffOptions::default(),
5214        )
5215        .unwrap();
5216        let patch_text = patch.iter().map(format_patch_for_git).collect::<String>();
5217
5218        commit_with_patch(
5219            &repo,
5220            &commit_req("grit partial"),
5221            CommitPatchInput::Patches(patch),
5222            &[],
5223            &mut NullProgress,
5224            &crate::progress::CancelToken::never(),
5225        )
5226        .unwrap();
5227        let grit_tip = resolve_ref(&repo.git_dir(), "refs/heads/main").unwrap();
5228        let grit_tree = parse_commit(&repo.odb().read(&grit_tip).unwrap().data)
5229            .unwrap()
5230            .tree;
5231
5232        let git_dir = tempfile::tempdir().unwrap();
5233        git(git_dir.path(), &["init", "-q", "-b", "main"]);
5234        fs::write(git_dir.path().join("f.txt"), base).unwrap();
5235        git(git_dir.path(), &["add", "f.txt"]);
5236        git(git_dir.path(), &["commit", "-qm", "init"]);
5237        fs::write(git_dir.path().join("f.txt"), edited).unwrap();
5238        fs::write(git_dir.path().join("partial.patch"), &patch_text).unwrap();
5239        git(git_dir.path(), &["apply", "--cached", "partial.patch"]);
5240        git(git_dir.path(), &["commit", "-qm", "git partial"]);
5241        let git_tip = Command::new("git")
5242            .current_dir(git_dir.path())
5243            .args(["rev-parse", "HEAD^{tree}"])
5244            .env("GIT_CONFIG_GLOBAL", "/dev/null")
5245            .env("GIT_CONFIG_SYSTEM", "/dev/null")
5246            .output()
5247            .unwrap();
5248        let git_tree_hex = String::from_utf8_lossy(&git_tip.stdout);
5249        let git_tree = ObjectId::from_hex(git_tree_hex.trim()).unwrap();
5250        assert_eq!(grit_tree, git_tree);
5251        git(root, &["fsck", "--strict"]);
5252    }
5253
5254    fn loose_object_count(repo: &Repository) -> usize {
5255        repo.odb().count_loose_objects().unwrap_or(0)
5256    }
5257
5258    #[test]
5259    fn commit_patch_dry_run_writes_no_loose_objects() {
5260        use crate::diff::{hunk_ids, DiffSide};
5261        use crate::diff::{unstaged_file_diffs_with_peer_hunks, DiffOptions};
5262        use crate::porcelain::hunk_select::{resolve_selection, HunkSelection};
5263
5264        let tmp = TempDir::new().unwrap();
5265        let root = tmp.path();
5266        let repo = init_repo(root);
5267        let (base, edited) = two_hunk_file();
5268        fs::write(root.join("f.txt"), base).unwrap();
5269        stage(
5270            &repo,
5271            &StageOptions::default(),
5272            &mut NullProgress,
5273            &crate::progress::CancelToken::never(),
5274        )
5275        .unwrap();
5276        create_commit(
5277            &repo,
5278            &commit_req("init"),
5279            &mut NullProgress,
5280            &crate::progress::CancelToken::never(),
5281        )
5282        .unwrap();
5283        fs::write(root.join("f.txt"), edited).unwrap();
5284
5285        let before_loose = loose_object_count(&repo);
5286        let (files, peers) =
5287            unstaged_file_diffs_with_peer_hunks(&repo, &[], DiffOptions::default()).unwrap();
5288        let ids = hunk_ids(
5289            DiffSide::Unstaged,
5290            "f.txt",
5291            &files[0].hunks,
5292            peers.get("f.txt").map(|v| v.as_slice()).unwrap_or(&[]),
5293        );
5294        let patch = resolve_selection(
5295            &repo,
5296            DiffSide::Unstaged,
5297            &HunkSelection {
5298                ids: vec![ids[0].clone()],
5299                ranges: Vec::new(),
5300            },
5301            &[],
5302            DiffOptions::default(),
5303        )
5304        .unwrap();
5305        let before_tip = resolve_ref(&repo.git_dir(), "refs/heads/main").unwrap();
5306        let before_index = repo.load_index().unwrap().entries[0].oid;
5307
5308        let mut req = commit_req("dry preview");
5309        req.dry_run = true;
5310        commit_with_patch(
5311            &repo,
5312            &req,
5313            CommitPatchInput::Patches(patch),
5314            &[],
5315            &mut NullProgress,
5316            &crate::progress::CancelToken::never(),
5317        )
5318        .unwrap();
5319
5320        assert_eq!(loose_object_count(&repo), before_loose);
5321        assert_eq!(
5322            resolve_ref(&repo.git_dir(), "refs/heads/main").unwrap(),
5323            before_tip
5324        );
5325        assert_eq!(repo.load_index().unwrap().entries[0].oid, before_index);
5326    }
5327
5328    #[test]
5329    fn commit_hunks_stale_id_no_commit() {
5330        use crate::diff::HunkId;
5331        use crate::porcelain::hunk_select::HunkSelection;
5332
5333        let tmp = TempDir::new().unwrap();
5334        let root = tmp.path();
5335        let repo = init_repo(root);
5336        fs::write(root.join("f.txt"), b"one\n").unwrap();
5337        stage(
5338            &repo,
5339            &StageOptions::default(),
5340            &mut NullProgress,
5341            &crate::progress::CancelToken::never(),
5342        )
5343        .unwrap();
5344        create_commit(
5345            &repo,
5346            &commit_req("init"),
5347            &mut NullProgress,
5348            &crate::progress::CancelToken::never(),
5349        )
5350        .unwrap();
5351        let before_tip = resolve_ref(&repo.git_dir(), "refs/heads/main").unwrap();
5352        let before_index_oid = repo.load_index().unwrap().entries[0].oid;
5353
5354        fs::write(root.join("f.txt"), b"two\n").unwrap();
5355        let err = commit_with_patch(
5356            &repo,
5357            &commit_req("nope"),
5358            CommitPatchInput::Hunks(HunkSelection {
5359                ids: vec![HunkId::from_str("000000000001").unwrap()],
5360                ranges: Vec::new(),
5361            }),
5362            &[],
5363            &mut NullProgress,
5364            &crate::progress::CancelToken::never(),
5365        )
5366        .unwrap_err();
5367        assert!(matches!(
5368            err,
5369            crate::error::Error::Commit(CommitError::HunkSelect(_))
5370        ));
5371        assert_eq!(
5372            resolve_ref(&repo.git_dir(), "refs/heads/main").unwrap(),
5373            before_tip
5374        );
5375        assert_eq!(repo.load_index().unwrap().entries[0].oid, before_index_oid);
5376    }
5377
5378    #[test]
5379    fn commit_with_scope_stale_hunk_id_is_typed() {
5380        use crate::diff::HunkId;
5381        use crate::porcelain::hunk_select::{HunkSelectError, HunkSelection};
5382
5383        let tmp = TempDir::new().unwrap();
5384        let root = tmp.path();
5385        let repo = init_repo(root);
5386        fs::write(root.join("a.txt"), b"one\ntwo\n").unwrap();
5387        commit_with_scope(
5388            &repo,
5389            &commit_req("first"),
5390            CommitScope::AutoStage,
5391            &mut NullProgress,
5392            &crate::progress::CancelToken::never(),
5393        )
5394        .unwrap();
5395        let before_tip = resolve_ref(&repo.git_dir(), "refs/heads/main").unwrap();
5396        let before_index_oid = repo.load_index().unwrap().entries[0].oid;
5397
5398        fs::write(root.join("a.txt"), b"one\ntwo\nthree\n").unwrap();
5399        let stale = HunkId::from_str("000000000000").unwrap();
5400        let err = commit_with_scope(
5401            &repo,
5402            &commit_req("bogus"),
5403            CommitScope::Patch {
5404                input: CommitPatchInput::Hunks(HunkSelection {
5405                    ids: vec![stale.clone()],
5406                    ranges: Vec::new(),
5407                }),
5408                pathspecs: Vec::new(),
5409            },
5410            &mut NullProgress,
5411            &crate::progress::CancelToken::never(),
5412        )
5413        .unwrap_err();
5414        match &err {
5415            crate::error::Error::Commit(CommitError::HunkSelect(HunkSelectError::StaleId {
5416                id,
5417                ..
5418            })) => {
5419                assert_eq!(id, &stale)
5420            }
5421            other => panic!("expected stale hunk id error, got {other:?}"),
5422        }
5423        assert_eq!(err.to_string(), "stale hunk id 000000000000");
5424        assert_eq!(err.kind_name(), "hunk_selection");
5425        assert_eq!(
5426            resolve_ref(&repo.git_dir(), "refs/heads/main").unwrap(),
5427            before_tip
5428        );
5429        assert_eq!(repo.load_index().unwrap().entries[0].oid, before_index_oid);
5430
5431        let plan_err = plan_commit(
5432            &repo,
5433            &commit_req("bogus"),
5434            CommitScope::Patch {
5435                input: CommitPatchInput::Hunks(HunkSelection {
5436                    ids: vec![stale],
5437                    ranges: Vec::new(),
5438                }),
5439                pathspecs: Vec::new(),
5440            },
5441            &mut NullProgress,
5442            &crate::progress::CancelToken::never(),
5443        )
5444        .unwrap_err();
5445        assert!(matches!(
5446            plan_err,
5447            Error::Commit(CommitError::HunkSelect(HunkSelectError::StaleId { .. }))
5448        ));
5449    }
5450
5451    #[test]
5452    fn commit_with_scope_patch_apply_failure_is_typed() {
5453        use crate::diff::{hunk_ids, DiffSide};
5454        use crate::diff::{unstaged_file_diffs_with_peer_hunks, DiffOptions};
5455        use crate::porcelain::hunk_select::{resolve_selection, HunkSelection};
5456
5457        let tmp = TempDir::new().unwrap();
5458        let root = tmp.path();
5459        let repo = init_repo(root);
5460        let (base, edited) = two_hunk_file();
5461        fs::write(root.join("f.txt"), base).unwrap();
5462        stage(
5463            &repo,
5464            &StageOptions::default(),
5465            &mut NullProgress,
5466            &crate::progress::CancelToken::never(),
5467        )
5468        .unwrap();
5469        create_commit(
5470            &repo,
5471            &commit_req("init"),
5472            &mut NullProgress,
5473            &crate::progress::CancelToken::never(),
5474        )
5475        .unwrap();
5476        fs::write(root.join("f.txt"), edited).unwrap();
5477
5478        let (files, peers) =
5479            unstaged_file_diffs_with_peer_hunks(&repo, &[], DiffOptions::default()).unwrap();
5480        let ids = hunk_ids(
5481            DiffSide::Unstaged,
5482            "f.txt",
5483            &files[0].hunks,
5484            peers.get("f.txt").map(|v| v.as_slice()).unwrap_or(&[]),
5485        );
5486        let patch = resolve_selection(
5487            &repo,
5488            DiffSide::Unstaged,
5489            &HunkSelection {
5490                ids: vec![ids[0].clone()],
5491                ranges: Vec::new(),
5492            },
5493            &[],
5494            DiffOptions::default(),
5495        )
5496        .unwrap();
5497        let patch_scope = |patch: Vec<FilePatch>| CommitScope::Patch {
5498            input: CommitPatchInput::Patches(patch),
5499            pathspecs: Vec::new(),
5500        };
5501        commit_with_scope(
5502            &repo,
5503            &commit_req("first hunk"),
5504            patch_scope(patch.clone()),
5505            &mut NullProgress,
5506            &crate::progress::CancelToken::never(),
5507        )
5508        .unwrap();
5509        let before_tip = resolve_ref(&repo.git_dir(), "refs/heads/main").unwrap();
5510
5511        // The index already holds the postimage, so the same patch no longer applies.
5512        let err = commit_with_scope(
5513            &repo,
5514            &commit_req("again"),
5515            patch_scope(patch),
5516            &mut NullProgress,
5517            &crate::progress::CancelToken::never(),
5518        )
5519        .unwrap_err();
5520        assert!(
5521            matches!(err, crate::error::Error::Commit(CommitError::PatchApply(_))),
5522            "got {err:?}"
5523        );
5524        assert_eq!(err.kind_name(), "apply");
5525        assert_eq!(
5526            resolve_ref(&repo.git_dir(), "refs/heads/main").unwrap(),
5527            before_tip
5528        );
5529    }
5530
5531    #[test]
5532    fn commit_with_scope_empty_paths_is_typed() {
5533        let tmp = TempDir::new().unwrap();
5534        let root = tmp.path();
5535        let repo = init_repo(root);
5536        fs::write(root.join("a.txt"), b"one\n").unwrap();
5537        commit_with_scope(
5538            &repo,
5539            &commit_req("first"),
5540            CommitScope::AutoStage,
5541            &mut NullProgress,
5542            &crate::progress::CancelToken::never(),
5543        )
5544        .unwrap();
5545        let before_tip = resolve_ref(&repo.git_dir(), "refs/heads/main").unwrap();
5546
5547        fs::write(root.join("a.txt"), b"two\n").unwrap();
5548        let err = commit_with_scope(
5549            &repo,
5550            &commit_req("x"),
5551            CommitScope::Paths(Pathspec::entire_tree(PathspecGlobalFlags::default())),
5552            &mut NullProgress,
5553            &crate::progress::CancelToken::never(),
5554        )
5555        .unwrap_err();
5556        assert!(
5557            matches!(
5558                err,
5559                crate::error::Error::Commit(CommitError::CommitPathsRequired)
5560            ),
5561            "got {err:?}"
5562        );
5563        assert_eq!(err.to_string(), "you must specify path(s)");
5564        assert_eq!(err.kind_name(), "commit_paths_required");
5565        assert_eq!(
5566            resolve_ref(&repo.git_dir(), "refs/heads/main").unwrap(),
5567            before_tip
5568        );
5569    }
5570
5571    fn init_nested_git_repo(inner: &Path) {
5572        Command::new("git")
5573            .args(["init", "-q", "-b", "main"])
5574            .current_dir(inner)
5575            .output()
5576            .expect("git init nested");
5577        Command::new("git")
5578            .args(["config", "user.email", "t@example.com"])
5579            .current_dir(inner)
5580            .output()
5581            .expect("git config email");
5582        Command::new("git")
5583            .args(["config", "user.name", "Test"])
5584            .current_dir(inner)
5585            .output()
5586            .expect("git config name");
5587        fs::write(inner.join("inside.txt"), b"inside\n").expect("write nested file");
5588        Command::new("git")
5589            .args(["add", "inside.txt"])
5590            .current_dir(inner)
5591            .output()
5592            .expect("git add nested");
5593        Command::new("git")
5594            .args(["commit", "-qm", "nested"])
5595            .current_dir(inner)
5596            .output()
5597            .expect("git commit nested");
5598    }
5599
5600    #[test]
5601    fn commit_worktree_dry_run_reports_embedded_gitlink() {
5602        if Command::new("git").arg("--version").output().is_err() {
5603            return;
5604        }
5605        let dir = TempDir::new().unwrap();
5606        let repo = init_repo(dir.path());
5607        fs::write(dir.path().join("a"), b"a\n").unwrap();
5608        commit_worktree(
5609            &repo,
5610            &commit_req("seed"),
5611            &mut NullProgress,
5612            &crate::progress::CancelToken::never(),
5613        )
5614        .expect("seed commit");
5615
5616        let vendor = dir.path().join("vendor");
5617        fs::create_dir_all(&vendor).unwrap();
5618        init_nested_git_repo(&vendor);
5619
5620        let mut req = commit_req("nested\n");
5621        req.dry_run = true;
5622        req.hooks = HookPolicy::SkipVerify;
5623        let outcome = commit_worktree(
5624            &repo,
5625            &req,
5626            &mut NullProgress,
5627            &crate::progress::CancelToken::never(),
5628        )
5629        .expect("dry-run commit with embedded repo");
5630        assert_eq!(outcome.embedded_gitlinks, vec!["vendor".to_owned()]);
5631    }
5632}