Git,如何使用rebase自动化历史折叠

4
我使用这两篇文章的组合来折叠我的Git历史记录:折叠git仓库的历史记录如何合并Git仓库的前两个提交? 这是结果。
git rebase -i THE_SHA_1_OF_FIRST_COMMIT
# change "pick" into "squash" for all commits except first one
# :wq (if your editor is vi)
git rebase -i THE_SHA_1_OF_FIRST_COMMIT
# change "pick" into "edit"
# :wq (if your editor is vi)
git reset --soft HEAD^
git commit --amend
git rebase --continue
# garbage collect
git reflog expire --expire=1.minute refs/heads/master
git fsck --unreachable
git prune
git gc

这个功能很好,但由于我经常使用它,希望能够在脚本中自动化它。问题是有些命令(如“git rebase -i”)会打开一个文件进行编辑,我必须手动完成(对于“git commit --amend”也是同样的问题)。有没有办法自动化这个过程?我不是要求现成的解决方案,只需要想法。

2个回答

2
我使用命令git config --global core.editor,将提交列表发送到脚本而不是默认编辑器,现在可以通过一个命令折叠我的存储库历史记录了!虽然有点不太干净(也许不够优化),但它确实起作用了。
你需要两个bash脚本。第一个脚本replacepick.sh用于替换编辑器。解析所有行并将“pick”替换为文件中的第(argument 2)行的(argument 1)。
#!/bin/bash

# ./replacepick.sh replacewith fromindex filename

REPLACEWITH=$1
FROMINDEX=$2
FILE=$3


echo $FILE

mathccount=0

if [ -f $FILE ]
then
    OUTPUT=$FILE.tmp
    echo "" > $OUTPUT
    cat $FILE | while read line
    do
        if [[ "$line" == pick* ]]
        then
            matchcount=$(($matchcount + 1))
            if [ $matchcount -gt $FROMINDEX ]
            then
                echo ${line/pick/$REPLACEWITH} >> $OUTPUT
            else
                echo $line >> $OUTPUT
            fi
        else
            echo $line >> $OUTPUT
        fi
    done
    newfilecontent=`cat $OUTPUT`
    echo $newfilecontent > $FILE
fi

bash脚本 collapsehistory.sh 调用git命令:

#!/bin/bash

# Collapse all commits on second commit
`git config --global core.editor "/Users/macbook/Documents/GitTests/replacepick.sh squash 1"`
`git rebase -i $1`
`git rebase --continue`

# Collapse 2 commits on one
`git config --global core.editor "/Users/macbook/Documents/GitTests/replacepick.sh edit 0"`
`git rebase -i $1`

`git reset --soft HEAD^`
`git config --global core.editor "cat"`
`git commit --amend`
`git rebase --continue`

# garbage collect
`git reflog expire --expire=1.minute refs/heads/master`
`git fsck --unreachable`
`git prune`
`git gc`

# restore your favorite editor
`git config --global core.editor "vi"`

然后您执行/path/to/historycollapse.sh SHA1_OF_FIRST_COMMIT,就完成了!希望对您有所帮助。


我认为它在最新版本的git中不再起作用了,但我现在还没有理解。 - jptsetung

1
你应该看一下 git merge --squash,它会将所有的提交合并到你当前的分支上,并且不会实际进行提交。然后你可以检查并提交。

根据这篇文章https://dev59.com/VnE95IYBdhLWcg3wKqyq,git merge --squash不适合我的需求,因为我也想清理历史记录。 - jptsetung

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