Git: move changes off of master branch

后端 未结 6 450
南旧
南旧 2021-02-03 20:53

Basic question but this happens to me all the time:

  • Make changes in a working-branch
  • Switch to master
  • git merg
6条回答
  •  囚心锁ツ
    2021-02-03 21:25

    1. prevent direct edits on master (warning perhaps)

    You're not the only one to want this. The best idea I've come across is to put the git branch directly in your shell prompt. My prompt looks like this:

    [user@host directory:git_branch]
    

    I also color the git_branch entry, so it's quite obvious what I'm working on at all times. These two links on Stack Overflow should help with your prompt.

    2. to move all edits over to working-branch and clear master so I can continue editing on working-branch

    or

    3. to spin edits into an entirely new branch new-working-branch and then discard working-branch?

    These are really the same question - how to move changes off of master onto a branch, whether it's an old branch or a new branch. And your own answer is correct. Although at second glance, assuming you're on master, you could more simply run:

    git branch new_branch
    git reset --hard origin/master
    

    I prefer to just reset master to origin/master rather than worry about a specific commit SHA. But your steps were essentially correct. As to why you lost changes, I'd have to think that by mistake there wasn't a branch pointer to Q when you reset master. No other explanation makes sense. Again, having the branch shell prompt will help avoid these mistakes. Further more, I'm a big fan of using gitk or git log --graph to verify where my branches are before I move them around. Since I can't easily use gitk at work, I have an alias in my .gitconfig called "graph," which is essentially a command-line version of it:

    [alias]
        graph = log --graph --all --date=short --pretty=format':%C(yellow)%h%Cblue%d%Creset %s %Cgreen %aN, %ad%Creset'
    

    This will show the graph on the far left, the commit SHA in yellow, the branches in blue, the commit message in white, and the author & date in green. Of course this can be modified to your own liking.

    [edited to make the above commands simpler]

    ==============================

    In response to the comment below:

    Start with

    A-B < origin/master
       \
        C-D < master
    

    Now perform git checkout -b new_branch

    A-B < origin/master
       \
        C-D < master, new_branch
    

    Now checkout master, git checkout master. Note that git checkout -b new_branch && git checkout master is the same as git branch new_branch if you were already on master. I edited the above answer to reflect this.

    Now reset master to origin/master, git reset --hard origin/master

    A-B < master, origin/master
       \
        C-D < new_branch
    

    Because you had a branch (new_branch) pointing at D, no changes are lost. If I've made a mistake, please elaborate where.

提交回复
热议问题