David Dahan
David Dahan

Reputation: 11162

How to use git branches for project features?

I'm working (alone) on a project that need several features to be added. I'm used to create a branch for each feature. Once the feature is developed and well tested, I merge that branch-feature with the master branch.

Now, I started a feature (let's call it feature A) on branch-A that is not finished. However, I urgently need to create a new feature B and push it before finishing feature A. That's why I created branch-B and switched to it.

However, running a git status command, I can see all the changed I made in the branch-A. I don't understand this default behaviour. I expected to see "no change" because they are different branches. I absolutely need that a commit in branch B ignores everything I dit in branch A.

What am I missing? How could I create the right workflow?

Upvotes: 4

Views: 88

Answers (3)

nwinkler
nwinkler

Reputation: 54457

You are probably seeing the changes from branch-A because you have not committed them yet. Untracked changes are not removed when you switch between branches.

Do the following:

# Switch back to branch-A
git checkout branch-A

# Check the status
git status

# Add all of the changes
git add .

# Commit the changes
git commit -a

# Switch back to branch-B
git checkout branch-B

# Check git status
git status

If you want to commit your changes temporarily (and you don't want to use git stash), you could create a new branch off of branch-A:

# Switch back to branch-A
git checkout branch-A

# Create a new branch
git checkout -b branch-A-temp

# Add all of the changes
git add .

# Commit the changes
git commit -a

# Switch back to branch-B
git checkout branch-B

# Check git status
git status

You can go back to branch-A-temp later and continue to work on the changes. Once you're done, you can merge them into branch-A.

Learn to use branches liberally - they're lightweight and easy to use. If you want to try something, create a branch for it. They minimize the risk of losing changes, and you still have the full history, you can merge back and forth, etc. Branches are great for this kind of work.

Upvotes: 0

TheGeorgeous
TheGeorgeous

Reputation: 4061

I think you created a the new branch B while in branch A. This would create the branch B with the branch A as base. You must create branch B while in master. Or simply use this command

git checkout -b new-feature master

Upvotes: 0

shytikov
shytikov

Reputation: 9538

You haven't committed your changes into branch-A and switched to branch-B, so you received all this mess.

To avoid this behavior either commit your changes to branch-A permanently or stash them temporarily.

Upvotes: 2

Related Questions