gpt4 book ai didi

git - 代码更改是否应该在不同的分支中持续存在?

转载 作者:行者123 更新时间:2023-12-04 16:30:51 24 4
gpt4 key购买 nike

我对 git 分支的行为感到困惑。

我有这个 git 仓库:

$ 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 status 时,我看到 README.md 文件有来 self 的 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

最佳答案

让我们先考虑一下当您 checkout 不同的分支并且没有修改任何文件时会发生什么

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

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

现在,如果在检查另一个分支之前修改了文件会发生什么?

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

不,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

这并不意味着该文件可以“安全”地带入这个新分支。还是修改了。仍然未提交。

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

关于git - 代码更改是否应该在不同的分支中持续存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42866820/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com