Getting rid of '… does not point to a valid object' for an old git branch

前端 未结 13 2016
不知归路
不知归路 2020-12-13 03:51

I have a fork of a Git repo and my clone appears to have an issue with an old, no longer existant, branch. I keep seeing this message:

error: refs/heads/t_1140

13条回答
  •  隐瞒了意图╮
    2020-12-13 04:19

    I run into this error on a regular basis. git remote prune origin does not work for me.

    [ Update. AFAIU, I'm running into this problem because of using git alternate. Say I've got repo A, registered as alternate for repo B. When I create a new branch br in repo A, and fetch repo A as remote in repo B, git will create a remote ref .git/refs/remotes/A/br for the new branch. When I delete the branch in repo A, and after the corresponding object is garbage-collected, I get the 'error: refs/remotes/A/br does not point to a valid object!' ]

    I've written this script (updated to deal with packed refs) to remove the dangling refs (using the info in Validate if commit exists).

    #!/bin/sh
    
    set -e
    
    if [ $# -eq 0 ]; then
        dir="."
    else
        dir="$1"
    fi
    
    if [ ! -d "$dir" ]; then
        echo "not a dir: $dir"
        exit 1
    fi
    
    if [ ! -d "$dir/.git" ]; then
        echo "not a git repo: $dir"
        exit 1
    fi
    
    cd "$dir"
    
    files=$(find .git/refs -type f)
    
    for f in $files; do
        id=$(cat "$f")
        if ! git rev-parse --quiet "$id" \
        >/dev/null 2>&1; then
        continue
        fi
        if ! git rev-parse --quiet --verify "$id^{commit}" \
        >/dev/null 2>&1; then
        echo "Removing ref $f with missing commit $id"
        rm "$f"
        fi
    done
    
    if [ ! -f .git/packed-refs ]; then
        exit 0
    fi
    
    packfiles=$(cat .git/packed-refs \
        | grep -v '#' \
        | awk '{print $2}')
    
    for f in $packfiles; do
        if ! git rev-parse --quiet --verify "$f" \
        >/dev/null 2>&1; then
        continue
        fi
        id=$(git rev-parse "$f")
        if ! git rev-parse --quiet --verify "$id" \
        >/dev/null 2>&1; then
        continue
        fi
        if ! git rev-parse --quiet --verify "$id^{commit}" \
        >/dev/null 2>&1; then
        echo "Removing packed ref $f with missing commit $id"
        git update-ref -d $f
        fi
    done
    

提交回复
热议问题