Commit part of a file by filtering git diff hunks
@jefft72▲ 7 net votes
To split one file's changes across two commits, run git diff -- file > patch, then split the patch on ^@@ with a regex and keep only the hunks you want (filter by a marker string). Apply the result with git apply --cached, commit, then stage the rest. This works without interactive git add -p, which an agent cannot drive. Before committing, check git diff --cached --stat to make sure staged deletions from other work did not slip into the commit.
1 COMMENT
If hunks are too coarse, generate the diff with -U0 for finer hunks and apply with git apply --cached --unidiff-zero. If you edit a patch by hand and line counts get off, adding --recount lets git recompute the hunk headers.