有沒有辦法將提交從源分支重播到目標分支,但考慮到目標分支中所做的更改.gitignore?
這是場景:
假設我從 master 分支出來并開始提交檔案,包括.bin應該已經存在.gitignore但沒有的檔案。有什么辦法可以讓我去掌握,提交“* .bin” .gitignore,然后在重新設定主題分支(或其他一些自動操作)時修復它?通過修復,我的意思是洗掉任何 .bin 檔案的變更集,這些變更集現在被忽略。這意味著 1) 如果提交有更改a.txt并且foo.bin應該只提交a.txt2) 如果提交只有更改foo.bin應該完全洗掉
目標是輕松清除僅在 Pull Request 時發現的多個錯誤。
常規git rebase沒用。即使在 repo 的(新)線性歷史記錄中,錯誤提交的檔案仍然提交,在錯誤提交之前存在 gitignore 模式
uj5u.com熱心網友回復:
有沒有辦法將提交從源分支重播到目標分支,但考慮到目標分支中所做的更改
.gitignore?
是的,這是可能的,但是,這需要一些腳本作業。(我在下面回圈中的示例腳本甚至可以按原樣為您作業。)基本上,您將模擬 rebase,但在每次提交之間有幾個步驟。演算法看起來像這樣:
- 獲取要重寫的提交串列并將它們存盤在陣列或串列中。
- 將源分支重置為目標。(該
.gitignore檔案現在應該就位。) - 對于串列中的每個提交:使用
--no-commit標志挑選提交,這樣您就不會完成提交,然后reset取消更改,然后將add它們回傳并遵循.gitignore說明。
這是一個作業示例 bash 腳本(將其另存為檔案并在空目錄中運行以進行測驗):
#!/bin/bash -v
git init
git branch -m main # rename to main in case that's not your default branch name
echo asdf > asdf.txt && git add . && git commit -m "Add asdf.txt"
git branch test-branch
echo "*.log" > .gitignore && git add . && git commit -m "Add .gitignore"
git switch test-branch
echo abc > abc.txt
echo def > def.log
git add . && git commit -m "Add abc.txt and def.log"
echo ghi > ghi.txt
echo hij > hij.log
git add . && git commit -m "Add ghi.txt and hij.log"
git log --all --graph --name-only
# Get all the commit IDs that would be rebased if we rebased test-branch onto main,
# and store them into an array in reverse order
declare -a commitIDs=(`git log main..test-branch --pretty=format:"%h" --reverse`)
# reset test-branch to main
git reset --hard main
# loop through the commitIDs and cherry-pick each one without committing
for i in "${commitIDs[@]}"
do
echo "About to cherry-pick commit $i"
git cherry-pick $i --no-commit # this leaves the commit staged
git reset # unstage so we can commit with the .gitignore
git add . # this doesn't add ignored files
git commit --reuse-message=$i
done
git log --all --graph --name-only
完成后,查看兩個git log陳述句的輸出。第一個有 2 個提交,每個提交都包含一個 .txt 和 .log 檔案。第二個使用該.gitignore檔案從這些提交中洗掉所有 .log 檔案。
注意我在重寫時使用了以前的提交訊息,因為這通常是您想要的。但是我故意以這種方式命名我的提交,以突出顯示您不想這樣做的場景,例如當您在提交訊息中指定忽略的檔案名時。
uj5u.com熱心網友回復:
不,您需要使用git rm來洗掉您已經在跟蹤的檔案(或者如果您想洗掉它的所有痕跡git-filter-branch)。這是 gitignore 手冊頁中的相關部分(注意最后一句):
gitignore 檔案指定了 Git 應該忽略的有意未跟蹤的檔案。已被 Git 跟蹤的檔案不受影響
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/313222.html
