2012-03-09 30 views
4

歷史崩潰我使用這2個物品的組合瓦解我的提交歷史:Collapsing a git repository's historyCombine the first two commits of a Git repository?混帳,如何使自動化與底墊

這是結果

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

我得到它的工作使用命令git config --global core.editor將提交列表發送到腳本而不是默認編輯器。感覺有點骯髒(也許沒有優化),但它可以工作,現在我可以在一個命令中摺疊我的倉庫的歷史!

您需要2個bash腳本。

第一個腳本replacepick.sh,用於代替編輯器的腳本。解析所有行,並用文件(參數3)中的行#(參數2)替換(選擇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就大功告成了!希望它也能幫助你們中的一些人。

+0

我認爲它不再適用於最新版本的git,但我現在還沒有設法理解。 – jptsetung 2012-09-09 09:26:16

1

您應該看看git merge --squash,它會合並並壓縮所有提交到您當前的分支而不實際進行提交。然後您可以檢查並提交。

+0

這個。根據這篇文章http://stackoverflow.com/questions/2427238/in-git-what-is-the-difference-between-merge-squash-and-rebase混帳合併--squash不適合我的需要,因爲我也想清理歷史。 – jptsetung 2012-03-09 12:43:55