乐闻世界logo
搜索文章和话题

How can I remove/delete a large file from the commit history in the Git repository?

1个答案

1

When dealing with large files in a Git repository, especially to completely remove them from the commit history, several effective methods are available. Here are several effective methods to address this issue:

Method 1: Using git filter-branch

The git filter-branch command can rewrite the commit history across multiple branches to remove unnecessary large files. Specific steps are as follows:

  1. Identify large files: Use git rev-list combined with git ls-tree to check the size of each object and identify the large files to remove.

    bash
    git rev-list --objects --all | git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' | sort -k3nr
  2. Execute filter-branch: After identifying the file path, use the git filter-branch command with --index-filter to remove the specified file.

    bash
    git filter-branch --force --index-filter \ "git rm --cached --ignore-unmatch path/to/file" \ --prune-empty --tag-name-filter cat -- --all
  3. Push changes: After rewriting the local history, force-push to the remote repository.

    bash
    git push origin --force --all git push origin --force --tags

Method 2: Using git-lfs

For large files that change frequently, using Git Large File Storage (LFS) is a better strategy. It allows committing pointers to large files to the Git repository while storing the actual file content on a remote server.

  1. Install Git LFS: First, install the Git LFS tool.

    bash
    git lfs install
  2. Track large files: Use the git lfs track command to track those large files.

    bash
    git lfs track "*.psd" git add .gitattributes
  3. Commit and push: Commit the changes and push to the remote repository.

    bash
    git add filename.psd git commit -m "Add large file with LFS" git push

Method 3: Using BFG Repo-Cleaner

BFG is a faster tool than git filter-branch, specifically designed to remove large files or passwords from Git repositories.

  1. Download and run BFG:

    bash
    java -jar bfg.jar --strip-blobs-bigger-than 100M
  2. Force-push to remote repository:

    bash
    git reflog expire --expire=now --all && git gc --prune=now --aggressive git push

Using these methods can effectively clear large files from the Git repository's commit history, helping to reduce repository size and improve performance. The choice of method depends on specific circumstances and personal preference.

2024年8月8日 09:30 回复

你的答案