在Git中,是否有一种方式可以保存当前更改而不需要提交或存储?

11

我改了很多文件,发现我的方法不好。因此,我想尝试另一种方法。在这种情况下,我知道两个解决方案:

  1. 提交: 我不想使用此功能,因为我知道我的当前代码不起作用。
  2. 暂存: 我也不想使用暂存功能,因为我错过了几个文件,我必须重新编写它们。

我要做的是在保存当前更改的同时,丢弃一些我不需要的更改,同时保留其余更改。在这种情况下,如果我发现第二种方法也不起作用,那么我只需要切换到之前的状态即可。

这样的功能存在吗?


2
对我来说,这似乎是一个相当不错的常规分支用例。您不想这样做的原因是什么? - Chris
4个回答

13

我认为 @Signey_Gijzen 的回答可能是最好的,但你也可以使用git stash apply来完成此操作。也就是说,你需要执行以下命令:

$ git stash             # as usual, stashes the changes
... now your changes are gone from the working tree ...
$ git stash apply       # unstashes, but keeps stash around
... now they're all back ...
$ git stash list        # the stash will still be there
stash@{0}: WIP on master: ...
$ git show stash@{0}    # what did that stash look like again?

6

创建一个新分支,添加您的文件并在该分支上提交更改。然后切换回您之前工作的分支。

对于尝试第二种方法,我将使用相同的方法。


这是个好主意,但问题在于当我在新分支上提交更改时,我必须复制/粘贴那些我想要再次出现的文件的更改。所以,我正在寻找你所建议的方法,但我不想失去我的文件(更改)。 - Hesam
@Hesam 也许你可以使用git cherry-pick,这样你就不必手动复制粘贴更改。我将添加一个新答案来展示我的意思。 - ahmadPH

1

Git使用依赖于提交

这是一个一般性的问题(例如没有具体的代码/树示例可供参考),因此您将得到一个一般性的答案。简短版本是:不,Git不能在进行提交或将某些内容添加到索引之外保存工作。即使stash命令也是提交的特殊情况,并利用了这些基本过程。

然而,您肯定可以在Git内部和外部做一些事情。以下是一些例子(无特定顺序):

  1. Do a soft reset to a known-good commit, and then cherry-pick your in-progress changes by using git commit --patch to select diff hunks to add to the index.
  2. Copy your working tree to another directory, revert to your last known-good commit, and copy files or hunks back into your working tree as you go. For example:

    mkdir /tmp/broken_wip
    cp * /tmp/broken_wip
    git reset --hard
    cp /tmp/broken_wip/somefile .
    
  3. Create a temporary branch to store your "dirty" commits, and then change back to the main branch. You can then bring over whatever you like from your temporary branch. For example, assuming you're currently on master:

    git checkout -b broken_branch
    git add .
    git commit -am 'broken WIP'
    git checkout master
    
  4. Using RCS to store your current state, while being sure not to commit the RCS directory or any *,v files.

即使您不想将历史记录发布出去,通常最好将问题代码提交到临时主题分支中,修复或导入内容,然后处理该主题分支。但是,如果您真的需要避免将内容提交到历史记录或索引中,则应该利用辅助版本控制系统或利用文件系统。
效果因人而异。

0

根据Sidney Gizejen的建议,我认为在结尾添加cherry-pick步骤可以让它适用于您。假设您当前在分支current_branch上,并希望将更改保存到分支temp_branch中,则可以执行以下操作:

git checkout -b temp_branch
git add <the_things_you_wanna_add>
git commit -m "..."
git checkout current_branch
git cherry-pick temp_branch -n

cherry-pick 命令将应用给定提交引入的更改。在这种情况下,由于您传递了一个分支,它将使用该分支上的最后一次提交。 -n 选项使得更改被应用但不被提交。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接