git force checkout of duplicate branch?

时间:2017-08-30 20:56:19

标签: git github version-control branch

If I want to create a new branch, I would do:

#!/usr/bin/env python

from bs4 import BeautifulSoup
import requests

url = 'https://www.your_url'
# the user-agent you specified in the comments
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17'}

html = requests.get(url, headers=headers).text
soup = BeautifulSoup(html, "html.parser")
jsinfo = soup.find_all("script")

list_of_interest = ['hl.config.lat', 'hl.config.lon']

d = {}
for line in jsinfo[9].text.split('\n'):
    if any(word in line for word in list_of_interest):
        k,v = line.strip().replace('hl.config.','').split(' = ')
        d[k] = v.strip(';')

print 'Lat => {}'.format(d['lat'])
print 'Lon => {}'.format(d['lon'])

However, sometimes this branch already exists, eg:

Lat => "28.06794"
Lon => "-81.754349"

is there an easier way than doing the following?

list_of_interest

I tried this but it doesn't work:

git checkout -b new-branch

1 个答案:

答案 0 :(得分:3)

你想要的是git checkout -B name。如果 name 未命名现有分支,则会创建指向当前提交的新分支,就像通过常规git checkout -b一样。

如果 name 命名现有分支,那么Git会强制将分支名称重新指向当前提交。这很像git reset --soft。分支名称实际上只是某个Git哈希ID的可读名称,软重置会更改附加到分支名称的哈希ID,而不会触及索引或工作树。以同样的方式,git checkout -B将更改附加到此名称的ID,而不会触及索引或工作树。

(主要答案在这里结束,剩下的就是所有各种成功与失败模式的对比。)

-B--force

之间存在很大差异

这里有一些重要的区别。

这种特殊结账的一般形式是:

git checkout [-b | -B] name [target-commit-specifier]

,例如git checkout -b newbr a234567

此时-b-B之间的区别很明显:如果 name 部分命名已存在的分支,git checkout -b立即失败。 Git不必尝试结帐:名称存在;错误。如果名称不存在,或者您使用了-B,则还有更多可以尝试。

如果你忽略了目标说明符,正如我们在上面和原始问题中所做的那样,一整类问题就会消失。此表单没有目标提交,表示:保留当前提交。根本不要触摸索引或工作树。什么都不做很容易,永远不会失败,所以这部分永远不会失败。

但是,当您使用表单git checkout -B name target-commit-specifier时,该命令会尝试git checkout目标提交a234567。此步骤需要更新索引和/或工作树,这可能会失败,例如:

error: The following ... files would be overwritten ...

在这种情况下,git checkout -bgit checkout -B将被中止,并且不会创建或重新设置分支。 (另见Checkout another branch when there are uncommitted changes on the current branch。)

--force选项告诉Git,如果此结帐步骤即将失败,Git应继续执行结帐,覆盖或删除未安全保存在存储库中的文件。这可以对索引和/或工作树进行各种更改,并且任何非永久,安全存储在提交中的文件数据都可能在这里丢失。因此--force仍然存在危险(因为它可能丢失文件数据),但与-b vs -B无关:它只影响步骤,移动从你当前的提交,无论它是什么,到另一个目标提交。

如果Git得到这么远 - 目前的提交现在安装为当前提交,索引和工作树已更改;或者目标提交当前提交,因此索引和工作树保持不变 - 然后在这一点上整个事情注定要成功。我们已经检查过-b是否存在分支名称。 Git现在要做的就是将当前提交的哈希ID写入分支名称(例如, name 指向a234567)并写入{{1进入ref: refs/heads/name,以便您现在分支 .git/HEAD

相关问题