How to reduce the depth of an existing git clone?

前端 未结 4 680
感动是毒
感动是毒 2021-01-03 19:53

I have a clone. I want to reduce the history on it, without cloning from scratch with a reduced depth. Worked example:

$ git clone git@github.com:apache/spa         


        
4条回答
  •  说谎
    说谎 (楼主)
    2021-01-03 20:57

    OK here's an attempt to bash it, that ignores non-default branches, and also assumed the remote is called 'origin':

    #!/bin/sh
    
    set -e
    
    mkdir .git_slimmer
    
    cd $1
    
    changed_lines=$(git status --porcelain | wc -l)
    ahead_of_remote=$(git status | grep "Your branch is ahead" | wc -l)
    remote_url=$(git remote show origin  | grep Fetch | cut -d' ' -f5)
    latest_sha=$(git log | head -n 1 | cut -d' ' -f2)
    
    cd ..
    
    if [ "$changed_lines" -gt "0" ]
    then
      echo "Untracked Changes - won't make the clone slimmer in that situation"
      exit 1
    fi
    
    if [ "$ahead_of_remote" -gt "0" ]
    then
      echo "Local commits not in the remote - won't make the clone slimmer in that situation"
      exit 1
    fi
    
    cd .git_slimmer
    git clone $remote_url --no-checkout --depth 1 foo
    cd foo
    latest_sha_for_new=$(git log | head -n 1 | cut -d' ' -f2)
    cd ../..
    
    if [ "$latest_sha" == "$latest_sha_for_new" ]
    then
      mv "$1/.git" "$1/.gitOLD"
      mv ".git_slimmer/foo/.git" "$1/"
      rm -rf "$1/.gitOLD"
      cd "$1"
      git add .
      cd ..
    else
      echo "SHA from head of existing get clone does not match the latest one from the remote: do a git pull first"
      exit 1
    fi
    
    rm -rf .git_slimmer
    

    Use: 'git-slimmer.sh '

提交回复
热议问题