{"record":{"id":"0de19fa2c3360850","repo":"affaan-m/ECC","slug":"git-apply-failed-while-trying-to-action-stderr","errorCode":null,"errorMessage":"git apply failed while trying to {action}: {stderr}","messagePattern":"git apply failed while trying to (.+?): (.+?)","errorType":"exception","errorClass":"anyhow::Error","httpStatus":null,"severity":"error","filePath":"ecc2/src/worktree/mod.rs","lineNumber":1198,"sourceCode":"\n    {\n        let stdin = child\n            .stdin\n            .as_mut()\n            .context(\"Failed to open git apply stdin\")?;\n        stdin\n            .write_all(patch.as_bytes())\n            .with_context(|| format!(\"Failed to write patch for {action}\"))?;\n    }\n\n    let output = child\n        .wait_with_output()\n        .with_context(|| format!(\"Failed to wait for git apply while trying to {action}\"))?;\n    if output.status.success() {\n        Ok(())\n    } else {\n        let stderr = String::from_utf8_lossy(&output.stderr);\n        anyhow::bail!(\"git apply failed while trying to {action}: {stderr}\");\n    }\n}\n\n#[derive(Debug, Clone, PartialEq, Eq)]\nstruct SharedDependencyStrategy {\n    label: &'static str,\n    dir_name: &'static str,\n    fingerprint_files: Vec<&'static str>,\n}\n\nfn sync_shared_dependency_dirs_in_repo(\n    worktree: &WorktreeInfo,\n    repo_root: &Path,\n) -> Result<Vec<String>> {\n    let mut applied = Vec::new();\n    for strategy in detect_shared_dependency_strategies(repo_root) {\n        if sync_shared_dependency_dir(worktree, repo_root, &strategy)? {\n            applied.push(strategy.label.to_string());","sourceCodeStart":1180,"sourceCodeEnd":1216,"githubUrl":"https://github.com/affaan-m/ECC/blob/8321021c54d670126ce3b2969d5deb880b4b0c2a/ecc2/src/worktree/mod.rs#L1180-L1216","documentation":"`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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Re-read the error's stderr (git prints 'patch does not apply' / 'hunk failed') and refresh the diff view before retrying","Regenerate the patch from current file state, then reapply the operation","Add '--3way' (merge fallback) or adjust whitespace sensitivity ('--ignore-whitespace') if content is otherwise intact","Check for a stale .git/index.lock and remove it if no git process is active","Restore the file to its prior state (undo the manual edit) so the original patch applies again"],"exampleFix":"// before: stale patch fails hard\ngit_apply_patch(action, &patch)?;\n// after: refresh view when apply fails\nif let Err(e) = git_apply_patch(action, &patch) {\n    let fresh = git_diff_patch_text_for_paths(&wt, &paths)?;\n    git_apply_patch(action, &fresh)?;\n}","handlingStrategy":"fallback","validationCode":"// verify the patch applies before committing to it\nlet check = Command::new(\"git\")\n    .args([\"apply\", \"--check\"])\n    .stdin(Stdio::piped())\n    .spawn()\n    .and_then(|mut c| {\n        c.stdin.as_mut().unwrap().write_all(patch.as_bytes())?;\n        c.wait_with_output()\n    })?;\nlet applies = check.status.success();","typeGuard":null,"tryCatchPattern":"match git_apply_patch(action, &patch) {\n    Ok(()) => (),\n    Err(e) => {\n        // refresh diff from current tree and retry once\n        let fresh = regenerate_patch(&wt, &paths)?;\n        git_apply_patch(action, &fresh).map_err(|e2| e.context(e2.to_string()))?\n    }\n}","preventionTips":["Regenerate patches immediately before applying; never cache hunks across edits","Normalize line endings (git config core.autocrlf) so whitespace context matches","Disable editor autosave on worktree files while hunk operations are pending","Use 'git apply --check' as a preflight in scripts"],"tags":["git","patch","apply","stale-state"],"backgroundTag":"git-command-failed","analyzedSha":"8321021c54d670126ce3b2969d5deb880b4b0c2a","analyzedAt":"2026-09-16T10:08:13.343Z","contentChangedAt":"2026-09-16T10:08:13.343Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}