如何在我的分支中只存储多个已更改文件中的一个?


当前回答

由于在Git中创建分支很简单,您可以创建一个临时分支并将各个文件检入其中。

其他回答

git stash push -p -m "my commit message"

-p让我们选择应该隐藏的大块;也可以选择整个文件。

系统将提示您对每个大块执行一些操作:

   y - stash this hunk
   n - do not stash this hunk
   q - quit; do not stash this hunk or any of the remaining ones
   a - stash this hunk and all later hunks in the file
   d - do not stash this hunk or any of the later hunks in the file
   g - select a hunk to go to
   / - search for a hunk matching the given regex
   j - leave this hunk undecided, see next undecided hunk
   J - leave this hunk undecided, see next hunk
   k - leave this hunk undecided, see previous undecided hunk
   K - leave this hunk undecided, see previous hunk
   s - split the current hunk into smaller hunks
   e - manually edit the current hunk
   ? - print help

将以下代码保存到一个文件中,例如,名为stash。用法是stash<filename_regex>。参数是文件完整路径的正则表达式。例如,要隐藏a/b/c.txt、隐藏a/b/c.txt或隐藏.*/c.txt等。

$ chmod +x stash
$ stash .*.xml
$ stash xyz.xml

要复制到文件中的代码:

#! /usr/bin/expect --
log_user 0
set filename_regexp [lindex $argv 0]

spawn git stash -p

for {} 1 {} {
  expect {
    -re "diff --git a/($filename_regexp) " {
      set filename $expect_out(1,string)
    }
    "diff --git a/" {
      set filename ""
    }
    "Stash this hunk " {
      if {$filename == ""} {
        send "n\n"
      } else {
        send "a\n"
        send_user "$filename\n"
      }
    }
    "Stash deletion " {
      send "n\n"
    }
    eof {
      exit
    }
  }
}

要隐藏单个文件,请使用git stash--patch[file]。

这将提示:Stash This hunk[y,n,q,a,d,j,j,g,/,e,?]?。只需键入一个(将此大块和所有后续大块存储在文件中),就可以了。

免责声明:以下答案适用于2.13之前的git。对于2.13及以上的数字,请查看下面的另一个答案。


警告

正如评论中所指出的那样,这将所有的东西都放进了储藏室,无论是暂存的还是未暂存的。--keep索引只是在存储完成后保留索引。这可能会在以后弹出存储时导致合并冲突。


这将隐藏您以前未添加的所有内容。只需git添加要保留的内容,然后运行它。

git stash --keep-index

例如,如果要将旧提交拆分为多个变更集,可以使用以下过程:

gitrebase-i<最后一次提交>将某些更改标记为编辑。git重置HEAD^git add<您要在此更改中保留的文件>git stash—保留索引必要时修理一下。不要忘记git添加任何更改。git提交吉特藏弹根据需要,从第5步开始重复。git rebase—继续

另一种方法是:

# Save everything
git stash 

# Re-apply everything, but keep the stash
git stash apply

git checkout <"files you don't want in your stash">

# Save only the things you wanted saved
git stash

# Re-apply the original state and drop it from your stash
git stash apply stash@{1}
git stash drop stash@{1}

git checkout <"files you put in your stash">

在我(再次)来到这个页面并不喜欢前两个答案(第一个答案只是不回答问题,我不太喜欢使用-p交互模式)之后,我想到了这个问题。

这一想法与@VonC建议的使用存储库外的文件相同,您可以将所需的更改保存在某个位置,删除存储库中不需要的更改,然后重新应用您移开的更改。然而,我使用了git隐藏作为“某处”(因此,最后还有一个额外的步骤:移除你放在隐藏中的cahnges,因为你也把它们移到了一边)。