Rename all old branch script

Viewed 152

How can I rename all branch where the last commit older than 31/12/2019 adding "OLD_" before the actual name on the remote repository

1 Answers

Here's a script that does something like you want (+ example).

Here's a list of some random branches of mine that were last updated in 2018 which we'll run the script on. This script requires you to have a local copy of each branch, but i'll show at the end how to modify the script to be fully automated (i'm not much for automating things that end up on the remote).

    zrrbite@ZRRBITE MINGW64 /d/dev/git/jspaint (master)
    $ git for-each-ref --sort='-committerdate' --format='%(refname)%09%(committerdate)' 
    refs/heads | sed -e 's-refs/heads/--'

    master          Mon Aug 31 13:54:23 2020 +0200
    newnewbr        Tue Aug 28 00:08:31 2018 +0200
    newbranch       Tue Aug 28 00:06:51 2018 +0200
    gh-pages        Tue Feb 6 21:12:34 2018 +0100
    some_branch     Thu Feb 1 20:57:43 2018 +0100
    test            Thu Feb 6 18:47:16 2014 -0800

Script:

    #!/bin/bash
    for k in $(git branch | sed /\*/d); do
      if [ -n "$(git log -1 --before='2019-12-31' -s $k)" ]; then
        git branch -m $k OLD_$k
      fi
    done

Output of running the script:

zrrbite@ZRRBITE MINGW64 /d/dev/git/jspaint (OLD_test)
$ git branch
  OLD_gh-pages
  OLD_newbranch
  OLD_newnewbr
  OLD_some_branch
* OLD_test

Now you could push those branches and delete the old ones on the remote, manually. If you wanted to push the renamed branch and delete the old ones automatically you could re-write the script to:

    #!/bin/bash
    for k in $(git branch | sed /\*/d); do
      if [ -n "$(git log -1 --before='2019-12-31' -s $k)" ]; then
        git branch -m $k OLD_$k
        git push origin --delete $k
        git push origin OLD_$k
      fi
    done

If you want to take it even further and assume that you have no local branches checked out you could instead:

  • check git branch -r (for remote branches)
  • check out the branch and rename it if applicable
  • push the branch
  • delete the old

If you have a lot of branches, and don't have a local copy, then it is probably wise to try this approach.

Related