代码更改是否应该持续跨越不同的分支?

时间:2017-03-17 20:47:38

标签: git

我对git branch行为感到困惑。

我有这个git repo:

$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working tree clean

我像这样创建一个本地分支:

$ git checkout -b foo
Switched to a new branch 'foo'
$ git branch
* foo
  master
$ git status
On branch foo
nothing to commit, working tree clean

现在我更改了README.md文件。

$ date >> README.md 
$ git status
On branch foo
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   README.md

no changes added to commit (use "git add" and/or "git commit -a")

现在我像这样跳回我的主分支:

$ git checkout master
M   README.md
Switched to branch 'master'
Your branch is up-to-date with 'origin/master'.

但是当我执行git状态时,我看到README.md文件中有来自我的foo分支的修改!我不应该看到未修改的README.md文件版本吗?我在这里做错了什么?

$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   README.md


no changes added to commit (use "git add" and/or "git commit -a")
$ tail README.md 
# README.md
-----------

Meanvoy is just an idea I had to replace envoy with facter and
a mean stack backend.
Fri Mar 17 13:43:04 PDT 2017

1 个答案:

答案 0 :(得分:4)

让我们先考虑一下,当您签出另一个分支并且没有修改任何文件时会发生什么。

当你这样做时,git将首先将HEAD移动到历史记录中的新位置,这是另一个分支,然后git将更新你的工作文件夹,以包含根据另一个分支的所有文件的状态。

因此,例如,如果您签出功能分支,您的工作文件夹将更新以反映此功能分支的当前状态。到目前为止听起来不错?好。

现在,如果在您查看其他分支之前修改文件,会发生什么?

好吧,除非明确告知,否则git会尽量避免丢失您的更改。那该怎么办?拒绝签出这个其他分支,因为你修改了一些文件但没有提交它们

不,git会改为尝试来带来变化。

只有在安全的情况下才会这样做。如果文件在两个分支之间发散,git将拒绝出现

行的错误
$ git checkout feature/x
error: Your local changes to the following files would be overwritten by checkout:
        test1.txt
Please commit your changes or stash them before you switch branches.
Aborting

这并不意味着该文件对于这个新分支来说是“安全的”。仍在修改中。仍未提交。

您必须决定如何处理该文件。如果您希望它“保留”在上一个分支上,那么应该在提交新的分支之前提交