affaan-m/ECC · error · anyhow::Error

git apply failed while trying to

Error message

git apply failed while trying to {action}: {stderr}

What it means

`git_apply_patch` pipes a patch into `git apply` and bails with the action label and git's stderr when the apply fails. Callers stage, unstage, or reset individual hunks, so this error means the patch no longer applies cleanly to the working tree/index — usually because the file content changed since the patch was generated.

Solutions

  1. Re-read the error's stderr (git prints 'patch does not apply' / 'hunk failed') and refresh the diff view before retrying
  2. Regenerate the patch from current file state, then reapply the operation
  3. Add '--3way' (merge fallback) or adjust whitespace sensitivity ('--ignore-whitespace') if content is otherwise intact
  4. Check for a stale .git/index.lock and remove it if no git process is active
  5. Restore the file to its prior state (undo the manual edit) so the original patch applies again

Example fix

// before: stale patch fails hard
git_apply_patch(action, &patch)?;
// after: refresh view when apply fails
if let Err(e) = git_apply_patch(action, &patch) {
    let fresh = git_diff_patch_text_for_paths(&wt, &paths)?;
    git_apply_patch(action, &fresh)?;
}
Defensive patterns

Strategy: fallback

Validate before calling

// verify the patch applies before committing to it
let check = Command::new("git")
    .args(["apply", "--check"])
    .stdin(Stdio::piped())
    .spawn()
    .and_then(|mut c| {
        c.stdin.as_mut().unwrap().write_all(patch.as_bytes())?;
        c.wait_with_output()
    })?;
let applies = check.status.success();

Try / catch

match git_apply_patch(action, &patch) {
    Ok(()) => (),
    Err(e) => {
        // refresh diff from current tree and retry once
        let fresh = regenerate_patch(&wt, &paths)?;
        git_apply_patch(action, &fresh).map_err(|e2| e.context(e2.to_string()))?
    }
}

Prevention

When it happens

Trigger: Calling stage_hunk, unstage_hunk, or reset_hunk with a stale hunk after the file was edited; applying a patch with wrong context (whitespace drift); applying to a file that was deleted or renamed; index.lock contention.

Common situations: User edits a file in the editor between rendering the diff and clicking stage; line endings normalized (CRLF/LF) by an editor or git autocrlf; hunk offsets stale after an earlier hunk was applied to the same region.

Understand the failure class

Background: "git command failed": what it means when a tool shells out to git and git exits non-zero — this error's family across 21 libraries.

Related errors


AI-assisted analysis of affaan-m/ECC@8321021c54 (2026-09-16). Data as JSON: /api/errors/0de19fa2c3360850. Report an issue: GitHub.

Appendix: source

Thrown at ecc2/src/worktree/mod.rs:1198

    {
        let stdin = child
            .stdin
            .as_mut()
            .context("Failed to open git apply stdin")?;
        stdin
            .write_all(patch.as_bytes())
            .with_context(|| format!("Failed to write patch for {action}"))?;
    }

    let output = child
        .wait_with_output()
        .with_context(|| format!("Failed to wait for git apply while trying to {action}"))?;
    if output.status.success() {
        Ok(())
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("git apply failed while trying to {action}: {stderr}");
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct SharedDependencyStrategy {
    label: &'static str,
    dir_name: &'static str,
    fingerprint_files: Vec<&'static str>,
}

fn sync_shared_dependency_dirs_in_repo(
    worktree: &WorktreeInfo,
    repo_root: &Path,
) -> Result<Vec<String>> {
    let mut applied = Vec::new();
    for strategy in detect_shared_dependency_strategies(repo_root) {
        if sync_shared_dependency_dir(worktree, repo_root, &strategy)? {
            applied.push(strategy.label.to_string());

View on GitHub (pinned to 8321021c54)