【问题标题】:Checking out a branch with GitPython. making commits, and then switching back to the previous branch使用 GitPython 签出一个分支。提交,然后切换回上一个分支
【发布时间】:2016-06-27 18:08:06
【问题描述】:

我正在使用GitPython 库进行一些简单的 Git 操作,我想签出一个分支,进行提交,然后签出上一个分支。文档对如何执行此操作有些困惑。到目前为止,我有这个:

import git
repo = git.Repo()
previous_branch = repo.active_branch
new_branch_name = "foo"
new_branch = repo.create_head(new_branch_name)
new_branch.checkout()
repo.index.commit("my commit message")  # this seems wrong
## ?????

我可以通过 git 命令验证它是否有效,但我觉得我做错了。我不知道如何使用原始 git 命令(直接从库中)安全地切换回上一个分支。

【问题讨论】:

    标签: python git


    【解决方案1】:

    来自http://gitpython.readthedocs.io/en/stable/tutorial.html

    切换分支

    要在类似于 git checkout 的分支之间切换,您实际上需要将 HEAD 符号引用指向新分支并重置您的索引和工作副本以匹配。以下是一种简单的手动方法

        # Reset our working tree 10 commits into the past
        past_branch = repo.create_head('past_branch', 'HEAD~10')
        repo.head.reference = past_branch
        assert not repo.head.is_detached
        # reset the index and working tree to match the pointed-to commit
        repo.head.reset(index=True, working_tree=True)
    
        # To detach your head, you have to point to a commit directy
        repo.head.reference = repo.commit('HEAD~5')
        assert repo.head.is_detached
        # now our head points 15 commits into the past, whereas the working tree
        # and index are 10 commits in the past
    

    虽然之前的方法会粗暴地覆盖用户在工作副本和索引中的更改,并且不如 git-checkout 复杂。后者通常会阻止您破坏您的工作。使用如下更安全的方法。

        # checkout the branch using git-checkout. It will fail as the working tree appears dirty
        self.failUnlessRaises(git.GitCommandError, repo.heads.master.checkout)
        repo.heads.past_branch.checkout()
    

    或者,就在下面: 直接使用 git 如果您因为没有被包装而缺少功能,您可以方便地直接使用 git 命令。它由每个存储库实例拥有。

        git = repo.git
        git.checkout('HEAD', b="my_new_branch")         # create a new branch
        git.branch('another-new-one')
        git.branch('-D', 'another-new-one')             # pass strings for full control over argument order
        git.for_each_ref()                              # '-' becomes '_' when calling it
    

    只需执行 git.checkout() 方法

    【讨论】:

    • repo.head.reference = repo.commit(someSHA) 和say git checkout someSHA 有什么区别?我看到使用 python 时的 ref 指向 HEAD 和 master 但使用 git cli 时只有 HEAD。这意味着通过 python 使用它时工作目录很脏。如何以分离状态结束并使用 python 工具进行清理?
    猜你喜欢
    • 1970-01-01
    • 2013-12-30
    • 2017-02-12
    • 2011-11-24
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多