{"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":null,"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/01e15490f04e29cfefe3896951f43db46994d8ee/ecc2/src/worktree/mod.rs#L1180-L1216","documentation":"Thrown by git_apply_patch at ecc2/src/worktree/mod.rs:1198 when a `git -C <worktree_path> apply <args>` child process (fed the patch via stdin) exits non-zero. The `action` string parameter is interpolated so the error names what the apply was attempting (e.g. 'sync node_modules', 'restore staged hunk'). Stdout is redirected to null and stderr is captured, so only the stderr channel is reported.","triggerScenarios":"Applying a patch whose context lines no longer match the worktree's current content; applying a patch generated with different --line-prefix or whitespace settings; applying a patch to files that were modified or deleted since the patch was generated; `git apply --check` semantics where a hunk fails to apply cleanly; partial apply (3-way merge disabled) leaving the worktree half-patched.","commonSituations":"Syncing shared dependency dirs (node_modules, target/, venv) when the worktree's source files diverged from the fingerprint; restoring staged hunks after a concurrent edit; applying a patch across line-ending conversions (CRLF vs LF); path prefix mismatch when the patch was generated from repo root but applied in a sub-worktree.","solutions":["Regenerate the patch from the worktree's current state before applying (the context lines must match).","Apply with --3way for content reconciliation: pass `--3way` in args so git falls back to merge resolution instead of failing on context mismatch.","Verify the patch was generated with matching path prefixes (use `git apply --p=<n>` or `--directory=<dir>` to align).","Discard the half-applied state with `git -C <worktree_path> checkout -- .` and re-attempt from a clean tree."],"exampleFix":"// before\nlet args = [\"--index\"];\ngit_apply_patch(&wt.path, &args, &patch, \"stage hunk\")?;\n\n// after: retry with 3-way merge on context mismatch\nlet args = [\"--index\"];\nif let Err(e) = git_apply_patch(&wt.path, &args, &patch, \"stage hunk\") {\n    tracing::warn!(\"plain apply failed ({e}); retrying with --3way\");\n    let args3 = [\"--index\", \"--3way\"];\n    git_apply_patch(&wt.path, &args3, &patch, \"stage hunk\")?;\n}","handlingStrategy":"retry","validationCode":"// Dry-run the patch before committing to it\nfn patch_applies_cleanly(worktree_path: &Path, args: &[&str], patch: &str) -> bool {\n    let mut cmd = Command::new(\"git\");\n    cmd.arg(\"-C\").arg(worktree_path).arg(\"apply\").arg(\"--check\").args(args)\n        .stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null());\n    if let Ok(mut child) = cmd.spawn() {\n        if let Some(stdin) = child.stdin.as_mut() { let _ = stdin.write_all(patch.as_bytes()); }\n        child.wait().map(|s| s.success()).unwrap_or(false)\n    } else { false }\n}\nif !patch_applies_cleanly(&wt.path, &args, &patch) {\n    anyhow::bail!(\"patch context no longer matches; regenerate it\");\n}","typeGuard":"null","tryCatchPattern":"match git_apply_patch(&wt.path, &args, &patch, action) {\n    Ok(()) => (),\n    Err(e) if e.to_string().starts_with(\"git apply failed\") => {\n        // retry with 3-way merge so git reconciles context\n        let args3: Vec<&str> = args.iter().chain([&\"--3way\"]).copied().collect();\n        git_apply_patch(&wt.path, &args3, &patch, action)?;\n    }\n    Err(e) => return Err(e),\n}","preventionTips":["Generate the patch immediately before applying it; stale patches are the usual cause.","Always pass --3way for shared-dependency sync patches where context drifts.","Ensure line-ending settings (.gitattributes / core.autocrlf) match between generation and application.","Validate path prefixes between patch generation and apply (use --directory or --p=N when they differ)."],"tags":["git","apply","patch","conflict","subprocess-failure"],"backgroundTag":null,"analyzedSha":"01e15490f04e29cfefe3896951f43db46994d8ee","analyzedAt":"2026-08-13T00:31:08.655Z","schemaVersion":2},"datasetVersion":"2026-08-13T04:17:16.726Z"}