Search code examples
gitterminalxargs

Tag every branch with prefix and delete branch


I realized that somehow after a while my team and i collected ~80 stale branches in one repo. The history should be kept.

So I thought just tag every branch with a prefix "archive/". But i struggle a bit to automate that progress.

I struggle with getting the tag name (which is based on the branch name) together into the git tag command with the git commit hash. this what im currenty came up with:

git branch --remote | grep -vE "release|MLS|HEAD|main|master" | xargs -I{} git rev-parse {}  

So but now i want to reference also the output of the right most command with the output of the second command. But i dont find a solution for that? Any idea how? My idea would be something like this where would be the output of the second command but origin/ has to be removed too.

git branch --remote | grep -vE "release|MLS|HEAD|main|master" | xargs -I{} git rev-parse {}  | xargs -I{} git tag archive/<branchname> {} | git push origin --delete <branchname>

Solution

  • You should be able to create a tag based on origin/wat and remove the branch in a single command: git push origin origin/wat:refs/tags/archive/wat :refs/heads/wat

    If you want to do that for all origin/ branches at once (except those you skipped in your code snippet):

    git branch -r | grep -Po '(?<=\sorigin/)\S+' | sort -u | grep -vE '^(release|MLS|HEAD|main|master)$' | sed 's~.*~origin/&:refs/tags/archive/&\n:refs/heads/&~' | xargs -d'\n' git push --dry-run origin
    

    This is a dry-run version of the command, that doesn't actually perform the actions of tagging/deleting.
    Run it to see if the output it produces reflects what you want to do.
    If so, make a fresh clone of the remote repo and save it somewhere as backup.
    After that remove the --dry-run parameter from the command and run it again to actually create the tags and delete the branches.