How to find empty branches and tags in git

廉价感情. 提交于 2020-02-03 08:19:16

问题


I've migrated a big svn repository with hundreds of branches and tags, split them into multiple repositories and now i'm looking to check if there are any empty* branches/tags in these repositories that should be deleted before pushing the migration live.

Is there a faster way to find this than having to go to every repository and checkout every branch ?


*For the purpose of this question, "empty branch" or "empty tag" means a branch or tag that points to a commit that contains no files.


回答1:


Run git ls-tree <branch/tag> | wc -l for every branch and tag using the programming language of you choice and check for 0. You get a list of branches with git branch and a list of tags with git tag.

Here is a simple example for branches using bash:

#!/bin/bash

for branch in $(git branch | cut -c 3-)
do
  if [ $(git ls-tree $branch | wc -m) -eq 0 ]
  then
    echo "branch $branch is empty"
  fi
done



回答2:


I actually end up doing this script for it:

https://github.com/maxandersen/jbosstools-gitmigration/blob/master/deleteemptybranches.sh

    ## this will treat $1 as a repository and go through it and delete all branches and tags with empty content.

export GIT_DIR=$1/.git
export GIT_WORK_TREE=$1

echo Looking for empty branches in $1
git branch | while read BRANCH
do
 REALBRANCH=`echo "$BRANCH" | sed -e 's/\*//g'`
 NOFILES=`git ls-tree $REALBRANCH | wc -l | tr -d ' '`
# echo $NAME "$REALBRANCH" $NOFILES
 if [[ "$NOFILES" == "0" ]]
  then
     git branch -D $REALBRANCH 
  fi
done

git tag | while read BRANCH
do
 REALBRANCH=`echo "$BRANCH" | sed -e 's/\*//g'`
 NOFILES=`git ls-tree $REALBRANCH | wc -l | tr -d ' '`
# echo $NAME "$REALBRANCH" $NOFILES
 if [[ "$NOFILES" == "0" ]]
  then
     git tag -d $REALBRANCH 
  fi
done


来源:https://stackoverflow.com/questions/12686027/how-to-find-empty-branches-and-tags-in-git

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!