【问题标题】:Git commands to save current files in temporary branch without committing to masterGit命令将当前文件保存在临时分支中而不提交到master
【发布时间】:2018-07-08 17:28:31
【问题描述】:

假设我有一个本地 Git 存储库和一些未提交的更改。因为更改可能非常混乱,我还不想提交到我的分支,但我确实想在云上测试它。

我正在寻找一系列 git 命令,它们可以:

  1. 将“杂乱的更改”提交到另一个分支,例如mymessydev
  2. git push origin mymessydev
  3. 切换回 master 分支,进行相同的未提交更改,就好像什么都没发生过一样。

【问题讨论】:

  • 你查看过这篇文章了吗:stackoverflow.com/questions/1519006/…
  • 当您有很多分支时,使用stash 可能会变得复杂。另一种方法是git worktree 命令,它有一些缺点,如其手册中所述(并非所有工具都正确支持它)

标签: git


【解决方案1】:

假设您在 master 分支上,然后进行了混乱的更改,

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

此时,您不会放弃这些更改,因为它们已经推送到 messybranch。为了将这些更改恢复到 master,您可以合并 messybranch 或在 master 上选择提交

git merge messybranch

git cherry-pick #commit

cherry-pickmerge 提交您的更改,但如果您希望它们暂存而不提交,您可以这样做

git reset head~1

【讨论】:

  • 看起来cherry-pick 将提交混乱的更改。我发现了另一个可以取消挑选樱桃的帖子:stackoverflow.com/a/1526093/3453033
  • 编辑了我的答案以删除 master 分支上的提交和取消暂存 - 让我知道这是否适合您。
  • 看起来现在应该可以工作了,我会继续将您的答案标记为已接受。谢谢!
  • 查看我的新答案
【解决方案2】:

我编写了一个 python 脚本来自动化这个过程。它甚至适用于未跟踪的文件!

首先安装python绑定: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:])

【讨论】:

    猜你喜欢
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多