0

Assume a single file gets a few changes related to different issues. We can easily just post git commit with a note to describe each change for each issue, push that, and remind ourselves not to do that again.

Depending on how complex the changes are, I use this pattern to give each change its own commit:

  1. Copy the finished working file to a new Final file.
  2. Revert the working file back to its last commit state.
  3. Diff the working file and the Final file, and hand-merge individual lines for an issue.
  4. Commit with a clean comment for a single issue.
  5. Repeat as required.
  6. Delete the Final file as it's now just a copy of the current working file.

Is there a better way to do this, other than "don't do that"? In short, I'm cherry-picking within a single file. But as any developer knows, changes can spread across multiple files, and sometimes it's difficult to avoid making a change right now when we're looking right at a line that needs to be changed, compared to flagging it and coming back later for a dedicated change/commit. Thanks.

0

Yes, that's basically the purpose of Git's "staging area". Commits do not actually store the working tree, but only changes that you've copied to the staging area. You've already used git add to stage individual files in preparation for a commit, but it also allows more fine-grained operations. See for example Chapter 7.2 in the Git Book.

The usual pattern is to use git add -p to select individual diff hunks, with the ability to edit them further (e.g. in case you have unrelated lines in the same hunk). There is also a corresponding git reset -p to unstage individual changes in case you've added too much.

Use git diff --cached to see what's staged. Finally just run git commit as usual.

(If you want a shortcut, git commit -p does everything in one step.)

You can also run git gui or git citool to get a graphical commit interface, which has the ability to select individual lines with a mouse (right-click to stage). It's also built in to most other graphical Git clients. However, these usually only work at whole-line level – if your file has unrelated changes within the same line, you'll still have to use git add -p and hand-edit the patch.

  • I do sometimes unstage some changes for one commit, then come back to stage others, essentially getting a few consecutive commits from one updated workspace. But you've provided exactly the kind of feedback I was looking for. I'll try your suggestion, report back here, and will check this as the answer if all goes well. Thanks. – TonyG Jan 11 at 21:50

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.