如何讓 git 將其跟蹤從當前目錄移動到當前目錄中的目錄。(現在是什么)
/current_dir/
/dir_i_want_to_track/
...
...
我想跟蹤dir_i_want_to_track但現在它的跟蹤current_dir
(我想要的)
/dir_i_want_to_track/
...
...
編輯澄清@AD7six
這些目錄位于 repo 中。我開始在 初始化 repo /current_dir,所以 git 一直在跟蹤/current_dir/. 但是,繼續前進,我希望 git 更深入地跟蹤一個目錄的所有更改/dir_i_want_to_track/,而忽略 . 中的其他目錄/current_dir/,這樣當我進入 repo 時,它只會顯示
/dir_i_want_to_track/
...
而不是其他目錄。
(我還想保留所有以前提交的歷史記錄)
uj5u.com熱心網友回復:
緩慢而穩定地做
這里提出的解決方案是兩個不需要高級 git 知識的簡單任務的組合:
- 移動 git 存盤庫
- 在git 存盤庫中移動檔案
考慮以下模擬問題中的狀態:
mkdir -p /tmp/current_dir/dir_i_want_to_track
touch /tmp/current_dir/dir_i_want_to_track/README.md
cd /tmp/current_dir
git init
git add dir_i_want_to_track/README.md
git commit -m "Initial commit"
這是我們的開始狀態:
cd /tmp/current_dir
tree
.
└── dir_i_want_to_track
└── README.md
1 directory, 1 file
移動 git 存盤庫
Git 不關心本地存盤庫的路徑是什么(舊版本 git 中的一些邊緣情況除外) - 所以只需像對任何其他檔案夾一樣重命名即可。在這一步中,我們將重命名current_dir為current_dir/dir_i_want_to_track.
從父目錄:
cd /tmp
mv current_dir current_dir_moved
mkdir current_dir
mv current_dir_moved current_dir/dir_i_want_to_track
這將實作這種中間狀態:
cd /tmp/current_dir
tree
.
└── dir_i_want_to_track
└── dir_i_want_to_track
└── README.md
2 directories, 1 file
請注意,此時current_dir不再是 git 存盤庫。
在git 存盤庫中移動檔案
在 git 中移動檔案是使用git mv完成的:
cd /tmp/current_dir/dir_i_want_to_track
git mv dir_i_want_to_track/* .
git commit -m "move everything one dir up"
從而達到我們想要的最終狀態:
cd /tmp/current_dir/dir_i_want_to_track
tree
.
└── README.md
0 directories, 1 file
uj5u.com熱心網友回復:
盡管可能會出現意外行為,但您可以這樣做:
- 確保您的存盤庫是干凈的(如果不是,請提交)。
.git將名為并位于的隱藏目錄移動current_dir到dir_i_want_to_track.- 從您的新存盤庫中,運行 a
git add --all和 agit commit -m "Change root of repo"
通過這樣做,您的 Git 歷史記錄會告訴您將一堆檔案從子目錄“移動”到主目錄,并且您洗掉了位于主目錄中的所有檔案。
uj5u.com熱心網友回復:
試試git filter-branch --subdirectory-filter。假設您現在在分支上foo。
# backup the current branch foo
git branch foo_backup
# rewrite the branch foo
git filter-branch --prune-empty --subdirectory-filter dir_i_want_to_track
分支foo被重寫。不涉及的提交dir_i_want_to_track將是空提交。在大多數情況下,您不想保留它們。--prune-empty指示在新分支上洗掉這些空提交。
git filter-branch發出警告,建議您使用其他工具,例如git filter-repo. 所以你也可以試試這些工具。
創建新分支后,您需要使用git push --force origin foo:foo更新foo遠程存盤庫中的分支。確保foo在重寫和上傳時沒有其他人在更新,否則他們的作業可能會丟失。
更新:正如@AD7six 指出的那樣,您可能希望保留歷史記錄。dir_i_want_to_track如果是這樣,只需進行一個新的提交,將其作為根目錄進行跟蹤。
# if you have run the previous commands and rewritten the branch, first go back to the previous foo.
# if not, skip the following command.
git reset foo_backup --hard
# create a new commit based on the current head and merge it
git merge $(git commit-tree -p HEAD -m "xxx" HEAD:dir_i_want_to_track)
# amend the commit message
git commit --amend
該git commit-tree部分創建一個新的提交。它的父節點是foo頭部,它的提交訊息是xxx,它的根樹是頭部的dir_i_want_to_track版本foo。這樣,分支就不會被重寫。相反,就像您洗掉所有其他目錄和檔案,將其中的所有內容移動dir_i_want_to_track到存盤庫的根目錄,然后進行新的提交。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/429675.html
