简体   繁体   中英

Git commands to save current files in temporary branch without committing to master

Suppose I have a local Git repo and some uncommitted changes. Because the changes might be very messy, I don't want to commit to my branch yet, but I do want to test it on the cloud.

I'm seeking a sequence of git commands that can:

  1. Commit the "messy changes" to another branch, such as mymessydev
  2. git push origin mymessydev .
  3. Switch back to master branch with the same uncommitted changes, as if nothing has ever happened.

Let's say you're on the master branch with the messy changes then,

git stash
git checkout -b messybranch
git stash apply
git add .
git commit -m "commit"
git push origin messybranch
git checkout master // clean master

At this point, you won't loose these changes as they're already pushed on messybranch . In order to get these changes back to master , you could either merge messybranch or cherry-pick the commit on master

git merge messybranch

OR

git cherry-pick #commit

cherry-pick or merge commits your changes but if you'd like them to be staged and not committed, you can do

git reset head~1

I wrote a python script to automate this process. It works even for untracked files!

First install the python binding: pip install gitpython

import sys
from git import Repo
import time


def save(temp_branch, repo_path='.'):
    repo = Repo(repo_path)
    git = repo.git
    work_branch = repo.active_branch.name

    ret = git.stash()
    is_stash = not 'No local changes' in ret
    # delete the temp branch if already exist
    try:
        git.branch('-D', temp_branch)
    except:  # the branch doesn't exist, fine.
        pass
    git.checkout('-b', temp_branch)
    if is_stash:
        git.stash('apply')
    git.add('.')
    try:
        git.commit('-m', 'temporary save ' + time.strftime('%m/%d/%Y %H:%M:%S'))
    except:
        print('no temporary changes to push')
    git.push('-f', 'origin', temp_branch)
    git.checkout(work_branch)
    git.cherry_pick('-n', temp_branch)
    print(git.reset('HEAD'))


save(*sys.argv[1:])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM