Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add changes to staging area from another branch?

I have two branch,

  • master
  • new-features

New features have a commit I want to add to master but I want the control how much I want to merge.

I would like the option to add/reject changes for each line. Similar I can do with git add -p

I have searched a lot probably I was searching wrong term. This seems quite obvious task.

like image 653
Sisir Avatar asked Jul 04 '16 06:07

Sisir


People also ask

How are changes added to the staging area?

git add. The git add command adds a change in the working directory to the staging area. It tells Git that you want to include updates to a particular file in the next commit. However, git add doesn't really affect the repository in any significant way—changes are not actually recorded until you run git commit .

Is staging area common for all branches?

So looks like - any changes you make, including modifying files and staging, happen to ALL branches.


2 Answers

I think you can try to use patch file.
To create patch file run:

git checkout master
git diff ..new-features > patch.diff

In file patch.diff you have difference between branches master and new-features.
Now you can apply patch file, run:

git apply patch.diff

Now you can manage your changes in any desired way.

like image 33
cn007b Avatar answered Oct 13 '22 04:10

cn007b


Use git cherry-pick with the -n|--no-commit option and then interactively select what to commit:

git cherry-pick

...

-n, --no-commit

Usually git cherry-pick automatically creates a sequence of commits. This flag applies the changes necessary to cherry-pick each named commit to your working tree and the index, without making any commit. In addition, when this option is used, your index does not have to match the HEAD commit. The cherry-pick is done against the beginning state of your index.

This is useful when cherry-picking more than one commits' effect to your index in a row.

So the sequence of commands will be the following:

git cherry-pick -n <commitid>  # merge commitid into the index and working-tree
git reset                      # clear the index
git add -p                     # selectively add merged changes to the index

Alternatively, you can use git reset -p to remove undesired hunks from the staging area:

git cherry-pick -n <commitid>  # merge commitid into the index and working-tree
git reset -p   # interactively remove from the index changes brought by commitid
like image 106
Leon Avatar answered Oct 13 '22 03:10

Leon