有没有办法以非交互方式压缩一些提交?

时间:2011-09-01 19:31:52

标签: git interactive rebase squash

我正在尝试压缩一系列提交 - HEAD到HEAD~3。有没有快速的方法,或者我需要使用rebase --interactive?

8 个答案:

答案 0 :(得分:126)

确保您的工作树干净,然后

git reset --soft HEAD~3
git commit -m'new commit message'

答案 1 :(得分:30)

我个人喜欢wilhelmtell's解决方案:

git reset --soft HEAD~3
git commit -m 'new commit message'

但是,我创建了一个带有错误检查的别名,以便您可以执行此操作:

git squash 3 'my commit message'

我建议设置实际运行脚本的别名,以便更容易(a)编写脚本代码,以及(b)通过错误检查执行更复杂的工作。下面是一个执行壁球工作的脚本,然后是一个用于设置git别名的脚本。

压缩脚本(squash.sh)

#!/bin/bash
#

#get number of commits to squash
squashCount=$1

#get the commit message
shift
commitMsg=$@

#regular expression to verify that squash number is an integer
regex='^[0-9]+$'

echo "---------------------------------"
echo "Will squash $squashCount commits"
echo "Commit message will be '$commitMsg'"

echo "...validating input"
if ! [[ $squashCount =~ $regex ]]
then
    echo "Squash count must be an integer."
elif [ -z "$commitMsg" ]
then
    echo "Invalid commit message.  Make sure string is not empty"
else
    echo "...input looks good"
    echo "...proceeding to squash"
    git reset --soft HEAD~$squashCount
    git commit -m "$commitMsg"
    echo "...done"
fi

echo
exit 0

然后将 squash.sh 脚本连接到git别名,再设置另一个脚本来设置你的git别名( create_aliases.command create_aliases.sh ):

#!/bin/sh
echo '-----------------------'
echo 'adding git aliases....'
echo '-----------------------'
echo
git config --global alias.squash "!bash -c 'bash <path to scripts directory>/squash.sh \$1 \$2' -"
#add your other git aliases setup here
#and here
#etc.
echo '------------------------------------'
echo 'here is your global gitconfig file:'
echo '------------------------------------'
more ~/.gitconfig
echo 
echo
echo '----------------'
echo 'end of script...'
echo '----------------'

答案 2 :(得分:9)

我用过:

EDITOR="sed -i '2,/^$/s/^pick\b/s/'" git rebase -i <ref>

工作得很好。只是不要尝试使用以“pick”开头的行提交日志:)

答案 3 :(得分:8)

要通过wilhelmtell添加答案,我发现软重置为HEAD~2然后修改HEAD~3的提交很方便:

git reset --soft HEAD~2
git commit --all --amend --no-edit    

这会将所有提交合并到HEAD~3提交并使用其提交消息。一定要从干净的工作树开始。

答案 4 :(得分:3)

使用以下命令压缩上次提交中的最后4次提交:

git squash 4

使用别名:

squash = !"f() { NL=$1; GIT_EDITOR=\"sed -i '2,$NL s/pick/squash/;/# This is the 2nd commit message:/,$ {d}'\"; git rebase -i HEAD~$NL; }; f"
sq = !git squash $1
sqpsf = !git squash $1 && git psf 

来自https://github.com/brauliobo/gitconfig/blob/master/configs/.gitconfig

答案 5 :(得分:2)

这是一个用于压缩最后两次提交的内容。在此示例中,将保留最后一次提交的消息。您可以根据需要更改邮件。

git commit -am "$(git log -1 --skip=1 --pretty=%B | xargs && git reset --soft HEAD~2)"

如果为此命令创建别名并使用别名,则此命令非常有用。

答案 6 :(得分:0)

你可以与

非常接近
git rebase --onto HEAD~4 HEAD~ master

这假设你是主人,有线性历史。它不是一个壁球,因为它丢弃了中间提交。您需要修改新的HEAD以修改提交消息。

答案 7 :(得分:0)

要分解所有内容,因为分支是从主分支出来的:

/dev/ttyACM0