Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GIT - How to switch Branch without carrying changes and viceversa

Tags:

git

recently we moved from TFS to GIT so I am still learning how to use this amazing tool.

At the moment I am working in a very simple structure like the following one:

main -------------------------------------- 01 ----------
\                                           /
 dev ----------------------- 01 ---------- 02 ----------
  \                          /             /
   feat/login ------ 01 --- 02 --- 03 --- 04 --- 05 ---
  • Developers work on feature/something and every tot hours they check-in and trigger a build with tests
  • When the feature is stable they merge back into dev which will contains 1 or more checkins from feature/something
  • When the whole feature is ready, they merge the feature from dev into main

The questions are the following:

  • If I start to work from feat/login, if I do git checkout dev I don't get the latest code from dev but also my latest local file changed in feat/login. How can I checkout dev without carry over the local changes not commited from my previous branch?
  • Assuming a developer made a mistake, how can I rollback to a previous check-in 01 in dev and push it so that the latest check-in 02 is not the last one anymore?
like image 216
Raffaeu Avatar asked Jan 04 '23 04:01

Raffaeu


2 Answers

1) Stash your changes, checkout to another branch, make some changes there and come back to your original branch and apply/pop your stash.

$ git stash
$ git checkout dev

# do something in you dev branch

$ git checkout feat/login
$ git stash apply

You can view your stash list using the command $ git stash list

2) It seems like you want to revert back the changes. I recommend you to not play with git history as a beginner. Anyways, if you do want to try it out here's a good answer how to do it. As Lasse said it's better to create another commit that reverts the effect of the one you want to undo.

like image 50
Saugat Avatar answered Jan 07 '23 17:01

Saugat


Another feature that you may use, is git worktree (https://git-scm.com/docs/git-worktree) which allows you to have working copies of multiple branches at the same time, so e.g. lets assume you are on master:

git worktree add -b dev ../dev origin/dev
git worktree add -b feat_login ../feat_login origin/feat/login

will give you 2 additional working copies in ../dev and ../feat_login that contain a working copy of the dev and feat_login branch.

I find this feature especially useful in projects were I have to switch between branches very often.

like image 22
andipla Avatar answered Jan 07 '23 19:01

andipla