我想将一个文件中的函数提取出来并放入另一个文件,但要保留其历史记录。
cp a.php b.php
vim b.php
# delete everything but 1 function
vim a.php
# delete the 1 function
git add a.php b.php
git commit
但是,如果我运行 git blame b.php
,我只看到它责备到这个新提交。
维护责任历史的通用规则是在任何编辑之前先进行一个独立的移动提交。我的经验是,这样可以使git blame
工作而无需使用-C
选项。因此,在将文件拆分为新文件的情况下,可以通过两个提交来完成:
在提供的示例中,操作步骤如下:
cp a.php b.php
mv a.php c.php
git add a.php b.php c.php
git commit
vim b.php # delete everything but 1 function
vim c.php # delete the 1 function
git add b.php c.php
git commit
git add
命令在 Git 1.9 版本之后对不存在的文件的行为发生了改变。如果要反映已删除的文件,您需要使用 git rm
或 git add -A
命令。 - Damian Yerrickgit add <path>
与 git add -A <path>
相同”,因为它包括删除操作)。 - vine77我稍微修改了Peter在这里回答另一个问题的答案,创建了一个可重复使用、非交互式的shell脚本,名为git-split.sh
:
#!/bin/sh
if [[ $# -ne 2 ]] ; then
echo "Usage: git-split.sh original copy"
exit 0
fi
git mv $1 $2
git commit -n -m "Split history $1 to $2"
REV=`git rev-parse HEAD`
git reset --hard HEAD^
git mv $1 temp
git commit -n -m "Split history $1 to $2"
git merge $REV
git commit -a -n -m "Split history $1 to $2"
git mv temp $1
git commit -n -m "Split history $1 to $2"
它只是将源文件复制到一个新文件中,两个文件具有相同的历史记录。为什么这样做可以工作的解释可以在那篇其他答案中看到。
git mv $1 $2
重命名原始文件就可以了)。 - jessexknightgit blame -C -C b.php
。提醒一下,我发布了一个 NPM 包(可以直接通过 npx 命令调用),它可以为您拆分(复制)文件。它比 shell 脚本慢一些,但如果您正在使用 npm,则可以轻松执行,无需创建文件或将其检入 git 存储库中,以与团队共享。
https://www.npmjs.com/package/swgh
你会做
npx swgh myFile.txt myDuplicatedFileWithHistory.someOtherExtensionIfYouWantTo
这个版本是我对Lukas' answer的改进。
通过按名称添加特定文件,并使用git reset --soft
,它得到了改进,所以工作目录中可以有文件,但它们不会受到 git-split.sh 的影响。
#!/bin/sh
if [[ $# -ne 2 ]] ; then
echo "Usage: git-split.sh original copy"
exit 0
fi
git mv $1 $2
git add $2
git commit -m "renamed: $1 -> $2"
git branch temp-git-split
git reset HEAD~1 --soft
git mv $2 temp-git-split-file
git commit -m "renamed: $1 -> temp-git-split-file"
git merge temp-git-split
git add temp-git-split-file
git add $2
git rm $1
git commit -m "merging history"
git branch -d temp-git-split
git mv temp-git-split-file $1
git commit -m "renamed: temp-git-split-file -> $1"