簡體   English   中英

在提交之間移動文件

[英]Move files between commits

我有兩個相應的提交,在本地歷史的某個地方,並且一個文件被錯誤地添加到第二個。 我想解決這個問題。

我不明白我應該如何使用交互式rebase。 我做了git rebase -i HEAD~10並選擇用文件編輯提交,以便從那里檢查出來。 我使用git guit但是,在提交區域看不到任何文件。 我可以選擇修改之前的提交然后我看到文件。 但是,我無法將錯放的文件添加到之前的提交中,因為我沒有看到當前提交中的文件開頭。

因此,在重新定位時,選擇編輯錯誤添加文件的提交和要按順序添加文件的提交。 如果文件在稍后的提交中,但應該在較早的提交中,則必須對行重新排序。 例如,我開始

pick 8de731b Commit with missing file.
pick bbef925 Commit with too many files.
pick 52490ce More history.

我需要改成它

edit bbef925 Commit with too many files.
edit 8de731b Commit with missing file.
pick 52490ce More history.

然后,

# In the commit containing an extra file
git reset HEAD^ badfile.c
git commit --amend
git rebase --continue

# Now in the commit to add it to
git add badfile.c
git commit --amend
git rebase --continue

不幸的是,在一個分支中編輯歷史記錄時,我不知道有什么方法可以避免在所有分支中編輯歷史記錄。 應該盡早重新進行重新定位,以避免這樣的問題。 在我的簡單案例中,我可以合並master和另一個分支,但是提交不合並,然后我必須在master中重新定義,並重新排序和壓縮提交,如下所示:

pick 7cd915f Commit with missing file.
fixup 8de731b Commit with missing file. #This was the higher of the two entries
pick 8b92c5a Commit with too many files.
fixup bbef925 Commit with too many files. #This was the higher of the two entries
pick 94c3f7f More history.
fixup 52490ce More history. #This was the higher of the two entries

后期編輯:我剛注意到我不小心將提交歷史記錄重新排序為原始答案中的遺留物。 交換rebase中的行會改變您提交的順序; 在編輯之后,您可以再次進行rebase並將它們交換回原始提交順序。

如果我沒有弄錯,你想要的是移動一些包含提交2到提交1的更改。

我發現最簡單的方法是做兩個連續的交互式rebase。

在第一個中,您將提交2拆分為兩個提交:第一個包括您要移動的更改,第二個包括所有其他提交。 我們現在提交1,2.1和2.2。

然后再次進行rebase,這次選擇將2.1提交壓縮為1。

由於我經常偶然發現這個問題,我為此編寫了一個腳本。 它完全自動運行。 你可以在Github上找到它。 將其復制到本地文件系統,將其添加到PATH,您將能夠將其運行為:

mv-changes <source-commit> <destination-commit> <path>...

您還可以在Windows上的Git-Bash shell中運行該腳本。

請注意,如果在source-commitdestination-commit之間的中間提交中有<path>更改,則它將不起作用。

這里提供更多細節。

首先了解簡短歷史

> git log --oneline -n 3 --decorate=short
333333  (HEAD -> work_AAA) added test              /*file is updated here*/
222222  corrected bug 
111111  (origin/master, origin/HEAD, master) version XXX 

所以我們可以在提交22222時重新定義並停止

> git rebase -i master 
pick 22222 corected bug 
pick 33333 added test

改成 :

edit 22222 corected bug 
pick 33333 added test

那么你將在提交22222中處於更新模式,它顯示如下:

Stopped at 22222... corrected bug
You can amend the commit now, with
   git commit --amend 
Once you are satisfied with your changes, run
   git rebase --continue

這里將文件從commit 3復制到commit 2

git show 33333:path/to/file  >  path/to/file

修改提交2並繼續rebase

git commit --amend --no-edit path/to/file
git rebase --continue

做完了!

我有同樣的問題,想解釋一下我做了什么。

在提交AI中添加了一個文件f,我必須在以下提交B中刪除它。

現在我想在兩個提交中刪除該文件,但也想避免拆分提交,因為涉及許多其他文件。 我這樣做了

  • 恢復文件
  • 在提交ADD中再次添加它
  • 在提交REM中刪除它 - 現在有歷史A - B - ADD - REM
  • squash使用REM提交A - 然后文件從A B中消失
  • drop commit ADD - 現在文件已經消失了

也許這是一個古怪的解決方案,但對我來說它是有效的。
如果您因某些原因覺得這很糟糕,請發表評論。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM