3

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.
Ainz Titor
  • 1,497
  • 1
  • 15
  • 22
  • Did you checked this post: https://stackoverflow.com/questions/1519006/how-do-you-create-a-remote-git-branch/1519032#1519032 – Stefan Großmann Jan 29 '18 at 22:34
  • When you have a lot of branches, using `stash` may get complicated. An alternative is `git worktree` command, which has some drawbacks as explained in its man (and not all tools support it correctly) – Patrick Mevzek Jan 29 '18 at 22:37

2 Answers2

4

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

Pankaj Gadge
  • 2,748
  • 3
  • 18
  • 25
2

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:])
Ainz Titor
  • 1,497
  • 1
  • 15
  • 22