Home > database >  `Git add --patch` multiple files: go to hunk from previous file
`Git add --patch` multiple files: go to hunk from previous file

Time:09-21

When running git add --patch, it presents a series of "hunks" that can be applied or skipped with y or n respectively, along with other options for editing/etc.

On occasion, when working with a lot of files, I have unintentionally marked n to the last, or only, hunk in a file that I actually intended to mark y or e, resulting in me moving on to the next file. In such a case, is there any way when using the patch editor for me to move back 1 hunk to the previous file?

I know that there is a g option to go to a specific hunk within the same file, but I'm unsure how to arbitrarily move back 1 hunk if the hunk came from a previous file. Is there a way to just go "back" one hunk?

My options in such a case appear to be either to add -p all changes again (bad, since there may be a lot of files, with a lot of hunks that need to be skipped), or take note of the individual file that I messed up on and patch-add the single file alone (which may also have many hunks needed to be skipped again).

CodePudding user response:

As suggested in the coment, if you need something more interactive, go for a gui tool.

git comes together with a basic gui tool, which you can invoke with git gui, and which allows you to :

  • view unstaged and staged files (list them, and view their content),
  • select lines within the existing patches (individual lines or blocks of lines) and stage them or unstage them,
  • along with a few other actions, like commiting (with or without amend) or stashing.

I don't know very much the other GUI tools, but I'm certain some of them offer good interfaces to run the equivalent of git add -p.


As a general remark : if you find yourself looking for refined ways of adding parts of patches and seeking how to edit diff chunks inline, perhaps it my be worth asking yourself if what you want isn't :

  • edit the file to the content you want, and stage that

git add -p is certainly a convenient way to select only regions of a file, but it is also a way to create commits you have never tested, because the staged content was never the exact content you had on disk.

  • Related