帮助用户永久删除 Git 仓库历史中的文件,适用于用户提及 “git filter-repo” 等场景。
When you delete a file in Git, it still remains in the Git repository history.
This skill guides users to use the git filter-repo tool to permanently delete specified files from the complete history of a Git repository.
Ask the user to confirm:
Must wait for user confirmation before proceeding with subsequent steps.
Before performing any operations, backup the repository first:
bash
# Method 1: Copy the entire repository directory
cp -r your-repo your-repo-backup
# Method 2: Create a bare repository backup
git clone --bare your-repo your-repo-backup.git
Choose installation method based on your operating system:
macOS:
bash
brew install git-filter-repo
Ubuntu / Debian:
bash
pip install git-filter-repo
Windows:
bash
pip install git-filter-repo
After entering the repository directory, check:
bash
git status
git remote -v
If there's no remote repository, add one first:
bash
git remote add origin git@github.com:username/repository.git
Assuming the file to delete is secrets.txt:
bash
git filter-repo --path secrets.txt --invert-paths
What this step does:
Delete multiple files:
bash
git filter-repo --path file1.txt --path file2.txt --path secrets/ --invert-paths
Delete entire directory:
bash
git filter-repo --path directory-name/ --invert-paths
Check if the file still exists in history:
bash
git log --all -- filename
If there's no output, the file has been completely removed.
Because the history has been rewritten, a force push is required:
bash
# Push all branches
git push origin --force --all
# Push all tags
git push origin --force --tags
If you deleted sensitive information (keys, tokens, passwords, private keys), in addition to deleting history, you should also:
Important Reminder: Just because history is deleted doesn't mean others haven't copied it before. Once sensitive information is committed to a public repository, it should be considered leaked.
Because the commit history has changed, other people's local repositories will be inconsistent with the remote. You need to notify them:
Re-clone the repository (recommended)
Or execute the following command to sync: bash
git fetch origin
git reset --hard origin/main # Will lose unpushed local changes, use with caution
Warning: Do not continue development based on the old history, otherwise the deleted files will be reintroduced when pushing again
Make sure you're executing commands in the Git repository root directory.
Install git-filter-repo first, refer to the installation steps above.
Run garbage collection:
bash
git gc --aggressive --prune=now
If the file is only in the most recent commit, you don't need filter-repo, use:
bash
git rm --cached filename
git commit --amend
The most core commands:
bash
# Delete file
git filter-repo --path filename --invert-paths
# If no remote, add first
git remote add origin <repo-url>
# Force push
git push origin --force --all
git push origin --force --tags