【Git】如何重置版本控制專案

【Git】如何重置版本控制專案

本篇重點

  • 移除專案根目錄的 .git,即可移除本機既有 Git Repository,並且不影響其他專案檔案
  • .git 移除後,原本的 commit history、branch、tag、remote 與 Repository 層級設定等都不再存在
  • 重新初始化 git 版控流程

在軟體開發過程中,若遇到專案架構大幅改動、歷史紀錄過於混亂或是要將既有專案作為新模板發佈時,可以考慮徹底清除舊有 Git 歷史紀錄並重新初始化。

Git Repository 的本機資料位於專案根目錄的 .git,其中包含 Repository 的物件資料、references、Repository 層級設定等。git init 建立新的 Repository 時,同樣會建立新的 .git 目錄。

移除本機 Git 版控

移除專案版控的機制在於刪除專案根目錄下的 .git 隱藏資料夾。

刪除 .git 後的 Repository 變化

範例

當 .git 資料夾被刪除後,將產生以下影響:

  • 清除範圍:全數 Commit 歷史紀錄、本地與遠端分支(Branch)、標籤(Tag)、Stash 暫存紀錄以及既有的 Remote 連接設定等等。
  • 保留範圍:工作目錄中的所有實體程式碼、資源檔案與資料夾結構不受影響。

Git 重置前後檔案結構

Windows 環境 (PowerShell)

在專案根目錄下執行以下指令:

powershell
1
2
Remove-Item -Recurse -Force .git
# -Recurse 用於移除 .git 內部內容,-Force 則處理隱藏項目。

Linux / macOS 環境 (Bash / Zsh)

在專案根目錄下執行以下指令:

bash
1
rm -rf .git

重新初始化與建立版控

刪除舊有的 .git 資料夾後,專案已還原為無版控狀態,接著按照標準流程進行重新初始化。

重新初始化

在專案根目錄執行以下指令,重新建立全新的 .git 資料夾結構:

git
1
git init

建立或檢查 .gitignore

為避免將編譯產物、敏感金鑰或相依性套件納入全新版控,需確認根目錄下的 .gitignore 檔案設定完整。

Node.js 專案 .gitignore 範例

.gitignore
1
2
3
node_modules/
.env
dist/

設定 Git 身份

所有專案都使用相同的 Git 身分,可以設定:

git
1
2
git config --global user.name "Your Name"
git config --global user.email "you@example.com"

user.name 與 user.email 會用於 Commit 的 author 與 committer 資訊。

如果只希望設定目前這個 Repository,則省略 --global:

git
1
2
git config user.name "Your Name"
git config user.email "you@example.com"

這些設定會寫入目前 Repository 的 .git/config。

重新連接 GitHub

重新建立 Git Repository 後,目前 Repository 還沒有 Remote,因此需要重新設定 GitHub Repository URL

git
1
git remote add origin <repository-url>

例如

git
1
2
3
git remote add origin https://github.com/example/my-project.git
# 或使用 SSH
git remote add origin git@github.com:example/my-project.git

健忘筆記

origin 不是固定名稱,只是慣例上用 origin 來代表主要 Remote 的名稱;git remote add 可以將指定名稱與遠端儲存庫建立關聯。

驗證 Remote

git
1
2
3
4
git remote -v

origin https://github.com/example/my-project.git (fetch)
origin https://github.com/example/my-project.git (push)

結論

Git 版本控制重設流程

透過刪除本機的 .git 隱藏資料夾,可以在保留原有專案檔案的情況下,清除既有的 Commit 歷史與分支紀錄。接著,透過 git init 重新初始化版本控制,並設定適當的 .gitignore,最後連接新遠端儲存庫,即可建立全新的版控起點。

延伸閱讀

發表於

2026-10-20

更新於

2026-10-20

許可協議


你可能也想看

【GitHub】解析 Reference System:Issue、Pull Request、Commit 如何建立關聯
【Git】使用 Conventional Commits 規範優化 commit message
【Git】了解 git config 設定

評論

複製完成