6

Let's say you have a branch master and another branch production, both containing a version of the file prog.py, as well as many other files. Imagine that you modify many files in the production branch, including prog.py. Now, what is the best way of having only some changes made on prog.py in the production branch be applied to its version in the master branch?

I started moving to the master branch and importing the file from the production branch:

git checkout master
git checkout production -- prog.py

because I was hoping to be able to do git add -p and select the changes by hand. The problem is that prog.py is both in the working tree and in the index. How can I remove it from the index without touching the working tree?

Or is there a better way of choosing which changes in prog.py should be imported from the production branch into the master branch?

Zoe
  • 27,060
  • 21
  • 118
  • 148
Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260

3 Answers3

17

I'm not sure if this was true when this question was asked, but with a current version of git you can do the following:

git checkout -p production -- prog.py

and you'll get the same interactive hunk-picker you do for most -p commands.

Potherca
  • 13,207
  • 5
  • 76
  • 94
amalloy
  • 89,153
  • 8
  • 140
  • 205
4

Making small and granular commits that only do one thing, and then later cherry-picking the changes you also want in the other branch using git cherry-pick $commit_id would seem like a reasonable approach.

rafl
  • 11,980
  • 2
  • 55
  • 77
  • Thanks. Does cherry-pick allow you to cherry pick changes *within* a single file? – Eric O. Lebigot Oct 06 '10 at 13:35
  • 1
    It cherry-picks commits, which you can certainly modify later if it turns out you didn't do your commits as granular as you might've wanted to. eg. `git reset HEAD~1`, and `git add -p`, and `git commit -c $commit_id`, – rafl Oct 06 '10 at 13:46
1

Alright, I just tried git reset, and it did remove the changes stored in the index. git add -p then works as expected, allowing one to choose the individual changes that should be applied (i.e. stored in the index). The non-wanted changes can then be discarded with git commit, and then git reset --hard.

Hopefully the question and this answer will be of interest to someone else! :)

PS: I marked this answer as the accepted one because it does check out a single file, as asked in the original question.

Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260