2013-02-22 21 views
93

我想在這個git倉庫中定義一個新的「根」分支。通過「根」分支,我指的是完全獨立於存儲庫中的所有其他分支的分支。如何創建一個新的(和空的!)「根」分支?

不幸的是,即使是提交(我們稱之爲A)在repo的提交樹的底部也包含很多文件(這是一個已經在相當成熟的項目上初始化的存儲庫)。

這意味着即使我將A作爲新分支的<start-point>,這個新分支不會從「乾淨的標準」開始,而是它將包含所有在A中提交的文件。

是否有某種方法可以在此存儲庫中創建一個完全裸分支,<start-point>儘可能接近A


順便說一句,這是等效於創建一個新的回購。由於很多原因,單獨的回購將不太方便。


編輯:OK,這是我做的,基於vcsjones'回答:

# save rev of the current earliest commit 
OLDBASE=$(git rev-list --max-parents=0 HEAD) 

# create a new orphan branch and switch to it 
git checkout --orphan newbranch 
# make sure it's empty 
git rm -rf . 

# create a new empty commit in the new branch, and 
# save its rev in NEWBASE 
git commit --allow-empty -m 'base commit (empty)' 
NEWBASE=$(git rev-list HEAD) 

# specify $NEWBASE as the new parent for $OLDBASE, and 
# run filter-branch on the original branch 
echo "$OLDBASE $NEWBASE" > .git/info/grafts 
git checkout master 
git filter-branch 

# NOTE: this assumes that the original repo had only one 
# branch; if not, a git-filter-branch -f <branch> command 
# need to be run for each additional branch. 

rm .git/info/grafts 

雖然這個過程是參與了一下,最終的結果是基本提交可以作爲<start-point>用於任何新的「clean-slate分支」;所有我需要做的就是

git checkout -b cleanslate $(git rev-list --max-parents=0 HEAD) 

今後我會一直創造新的存儲庫這樣的:

git init 
git commit --allow-empty -m 'base commit (empty)' 

......從而使第一承諾是,始終可用於啓動一個新的獨立分支。 (這將是的,我知道,一個很少需要的設施,但它是相當費力,使其隨時可用。)

+0

重複的http://stackoverflow.com/questions/13969050/how-to-create-a-new-empty-branch-for-a-new-project – Anonymoose 2013-11-04 04:52:22

+1

@ Anonymoose:只是爲了記錄(而不是辯論):我不同意你的看法。 – kjo 2013-11-04 15:54:59

+1

似乎有一個更簡單的解決方案基於'git rebase --onto',請參閱http://stackoverflow.com/questions/645450/insert-a-commit-before-the-root-commit-in-git – 2015-11-11 21:47:50

回答

151

創建分支時,使用--orphan

git checkout --orphan YourBranchName 

這將創建一個新的分支上沒有提交,但是所有的文件都會上傳。在這一點上,你可以刪除它們。
(「刪除」:一個git reset --hard將清空索引,讓你有一個空的工作樹)

看看在man page結帳關於--orphan更多信息。

+0

這實質上是創造一個空白的石板嗎?從頭開始?還是它保留了以前的所有更改,但只是不在git歷史記錄中? – 2016-07-22 02:58:29

+1

@ConAntonakos這將創建一個沒有父母的新分支。其他分支不受影響,所有更改都保留。 – fuz 2016-10-15 19:14:20

1

要添加到接受的答案 - best practice恢復到清潔狀態是創建an initial empty commit,所以你可以很容易地設置分支爲後代rebase。另外,既然你想要一個乾淨的狀態,你可能已經提交了你不應該的文件,所以你必須從索引中刪除它們。有了這些考慮,你應該:

$ git checkout --orphan dev2 
Switched to a new branch 'dev2' 
$ git reset # unstage all the files, you probably don't want to commit all of them 
$ git commit --allow-empty -m 'Initial empty commit' 
[dev2 (root-commit) a515c28] Initial empty commit 
相關問題