美文网首页
彻底删除git中的大文件

彻底删除git中的大文件

作者: geekAppke | 来源:发表于2018-11-10 17:46 被阅读4次

    git 如果提交一个文件,然后删除他,继续提交,那么这个文件是存在 git 中,需要使用特殊的命令才可以删除。

    .git主要记录每次提交变动,当我们的项目越来越大的时候,我们发现 .git文件越来越大
    
    很大的可能是因为提交了大文件,如果你提交了大文件,那么即使你在之后的版本中将其删除,但是,
    实际上,记录中的大文件仍然存在。
    
    虽然你在后面的版本中删除了大文件,但是Git是有版本倒退功能的吧,那么如果大文件不记录下来,
    git拿什么来给你回退呢?但是,.git文件越来越大导致的问题是: 每次拉项目都要耗费大量的时间,并且每个人都要花费
    那么多的时间。。
    
    git给出了解决方案,使用git branch-filter来遍历git history tree, 可以永久删除history中的大文件,达到让.git文件瘦身的目的。
    

    原文链接(英)

    查找大文件:findBigFile.sh

    #!/bin/bash
    #set -x 
    
    # Shows you the largest objects in your repo's pack file.
    # Written for osx.
    #
    # @see http://stubbisms.wordpress.com/2009/07/10/git-script-to-show-largest-pack-objects-and-trim-your-waist-line/
    # @author Antony Stubbs
    
    # set the internal field spereator to line break, so that we can iterate easily over the verify-pack output
    IFS=$'\n';
    
    # list all objects including their size, sort by size, take top 10
    objects=`git verify-pack -v .git/objects/pack/pack-*.idx | grep -v chain | sort -k3nr | head`
    
    echo "All sizes are in kB's. The pack column is the size of the object, compressed, inside the pack file."
    
    output="size,pack,SHA,location"
    for y in $objects
    do
        # extract the size in bytes
        size=$((`echo $y | cut -f 5 -d ' '`/1024))
        # extract the compressed size in bytes
        compressedSize=$((`echo $y | cut -f 6 -d ' '`/1024))
        # extract the SHA
        sha=`echo $y | cut -f 1 -d ' '`
        # find the objects location in the repository tree
        other=`git rev-list --all --objects | grep $sha`
        #lineBreak=`echo -e "\n"`
        output="${output}\n${size},${compressedSize},${other}"
    done
    
    echo -e $output | column -t -s ', '
    
    • 查看文件大小
      • du -ah .git/objects
    • 占用空间最多的五个文件
      • git rev-list --objects --all | grep "$(git verify-pack -v .git/objects/pack/*.idx | sort -k 3 -n | tail -5 | awk '{print$1}')"

    从 git 历史中移除

    git filter-branch --force --index-filter 'git rm -rf --cached --ignore-unmatch 你的大文件名' --prune-empty --tag-name-filter cat -- --all
    

    真正删除

    rm -rf .git/refs/original/
    git reflog expire --expire=now --all
    git gc --prune=now
    git gc --aggressive --prune=now
    git push origin master --force
    

    让远程仓库变小

    git remote prune origin
    

    gitLab发生错误查看:Settings -> Repository -> Protected branch -> unprotect

    参考资料

    Git 内部原理 - Pro Git 简体中文版
    记一次删除Git记录中的大文件的过程-HollisChuang's Blog
    Git仓库瘦身
    为什么你的 Git 仓库变得如此臃肿 - 简书

    相关文章

      网友评论

          本文标题:彻底删除git中的大文件

          本文链接:https://www.haomeiwen.com/subject/amnzxqtx.html