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

Phi*_*lip 107 git interactive rebase squash

我正在尝试压缩一系列提交 - HEAD到HEAD~3.有没有快速的方法来做到这一点,还是我需要使用rebase --interactive?

wil*_*ell 137

确保您的工作树是干净的

git reset --soft HEAD~3
git commit -m 'new commit message'
Run Code Online (Sandbox Code Playgroud)

  • @Phillip:你可以在git别名中嵌入一个shell函数.`git config alias.mysquash'!f(){git reset --soft HEAD~ $ 1 && git commit $ {2:+ - m"$ 2"}; }; f'`.`git mysquash 3'一些消息'将起作用,但我也调整了它,因此`git musquash 3`将完全省略-m标志,因此在这种情况下你将获得交互式`git commit`用户界面. (7认同)
  • 如果它只是行数:`git reset --soft HEAD~3 && git commit -m"我的消息"` (5认同)
  • 只是说清楚:它与壁球不一样.壁球还将合并提交消息.如果进行软复位,则会丢失所有提交的消息.如果你想压缩尝试http://stackoverflow.com/a/27697274/974186 (3认同)

n8t*_*8tr 30

我个人喜欢wilhelmtell的解决方案:

git reset --soft HEAD~3
git commit -m 'new commit message'
Run Code Online (Sandbox Code Playgroud)

但是,我创建了一个带有错误检查的别名,以便您可以这样做:

git squash 3 'my commit message'
Run Code Online (Sandbox Code Playgroud)

我建议设置实际运行脚本的别名,以便更容易(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
Run Code Online (Sandbox Code Playgroud)

然后将该squash.sh脚本连接到git别名,创建另一个脚本来设置你的git别名(create_aliases.commandcreate_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 '----------------'
Run Code Online (Sandbox Code Playgroud)

  • 你也可以将它放在名为`git-squash.sh`的`$ PATH`中,它将自动别名为`git squash`.我没有改变你的答案,以防万一有理由使用我不知道的`create-aiases.sh`脚本. (4认同)

小智 9

我用了:

EDITOR="sed -i '2,/^$/s/^pick\b/s/'" git rebase -i <ref>
Run Code Online (Sandbox Code Playgroud)

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


小智 8

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

git reset --soft HEAD~2
git commit --all --amend --no-edit    
Run Code Online (Sandbox Code Playgroud)

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

  • 这是正确的答案,因为它压缩了一系列导致 head 的提交,并且它使用了第一个提交的消息。它是非交互式的。 (7认同)