「gitlabでブランチを切ったのに、ローカルPCでブランチを切り替えず、masterやdevelopなどの主流ブランチでコード変更してしまった」
やってしまったらgit stashで変更を退避しておき、目的のブランチに切り替えてgit stash applyすることで本来の開発ブランチに変更を移します。
目次
手順
あ、masterで作業してた。orz
$ git branch
1-
6-
* master
git statusでmasterの変更分を確認
$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: src/pages/gallery/actions.ts
modified: src/pages/gallery/gallery.html
modified: src/pages/gallery/gallery.scss
modified: src/pages/photo/actions.ts
no changes added to commit (use "git add" and/or "git commit -a")
git stashで変更を退避
$ git stash
warning: LF will be replaced by CRLF in www/build/main.css.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in www/build/main.js.
The file will have its original line endings in your working directory.
Saved working directory and index state WIP on master: bea9c4a Merge branch '6-' into 'master'
HEAD is now at bea9c4a Merge branch '6-' into 'master'
masterから退避されたことを確認
この時点でmasterを編集してしまった差分は無くなる。
$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working tree clean
退避されたstashを確認
$ git stash list
stash@{0}: WIP on master: bea9c4a Merge branch '6-' into 'master'
本来の開発ブランチに移動
リモートを取り込めてなければ一度git fetch。
$ git fetch
$ git checkout 17-
$ git branch
1-
* 17-
6-
master
git stash applyでstashした内容を目的のブランチに適用
$ git stash apply
On branch 17-
Your branch is up-to-date with 'origin/17-'.
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: src/pages/gallery/actions.ts
modified: src/pages/gallery/gallery.html
modified: src/pages/gallery/gallery.scss
modified: src/pages/photo/actions.ts
no changes added to commit (use "git add" and/or "git commit -a")
masterで編集してしまった内容を、本来編集するはずだった17-ブランチに移動させることが出来ました。
焦らずにgit stashすれば大丈夫ですね。