top | item 42129486

(no title)

rapidlua | 1 year ago

I do occasionally attempt to edit patch files produced by git-format-patch. Frequently I end up with corrupt patch. Still curious how to fix those numbers.

discuss

order

mananaysiempre|1 year ago

With git format-patch I’d say take a worktree, git apply the patch to its intended base, commit, rebase, and git format-patch again :)

Otherwise, well, the numbers are -(old start line number),(old line count) +(new start line number),(new line count) for the entire hunk introduced by @@ (whether it contains one group of changed lines or more). I'm sure you see how to fix them up, but accumulating a line number shift as you go through the file sounds very fiddly and error-prone. It also sounds like something the computer should be able to do for you (given the old patch and the new messed-up patch whose hunks correspond one-to-one to the old).

ETA: I seem to have been nerd-sniped. Mind the bugs, etc etc:

  #!/usr/bin/awk -f
  # usage: awk -f fix-patch.awk ORIGINAL EDITED > FIXED
  # assumes hunks in ORIGINAL are grouped by file and sorted by line number
  # assumes every unchanged or deleted line in ORIGINAL remains in EDITED
  # can get confused by lines starting with @@ before start of diff
  
  function flush() {
      coline += odelta; odelta = (coline + cosize) - (oline[n] + osize[n])
      cnline += ndelta; ndelta = (cnline + cnsize) - (nline[n] + nsize[n])
      if (hunk) printf "@@ -%d,%d +%d,%d %s", coline, cosize, cnline, cnsize, hunk
      hunk = ""; coline = cosize = cnline = cnsize = 0
  }
  
  BEGIN { FS = "[-+, ]+" }
  FNR == 1 { n = 0 }
  /^@@ / { n++; coline = $2; cnline = $4 }
  coline { cosize += /^[- ]/; cnsize += /^[+ ]/ }
  /^@@ / && FNR == NR { oline[n] = $2; osize[n] = $3; nline[n] = $4; nsize[n] = $5 }
  cosize == osize[n] && !/^\+/ { flush() } END { flush() }
  FNR == NR { next }
  !hunk && /^\+\+\+/ { odelta = ndelta = 0 }
  /^@@ / { sub(/^@@ [-0-9,]+ [+0-9,]+ /, "") }
  coline { hunk = hunk $0 "\n"; next }
  { print }