Skip to content

Instantly share code, notes, and snippets.

@legendof-selda
Last active July 27, 2021 09:49
Show Gist options
  • Save legendof-selda/8b4ea9271fc1da0414ebfcf14a43bcc3 to your computer and use it in GitHub Desktop.
Save legendof-selda/8b4ea9271fc1da0414ebfcf14a43bcc3 to your computer and use it in GitHub Desktop.
A python script to cleanup stale or old branches in git using last commit date and required flag
import pandas as pd
import subprocess
import os
env = os.environ.copy()
STALE_PERIOD = 10
REQUIRED_BRANCHES = ['master', 'staging', 'develop']
branches = subprocess.run('git branch -r' , capture_output=True, env=env, shell=True)
branches = branches.stdout.decode('utf-8').strip().split('\n')[1:]
last_commit_date = []
for i in range(len(branches)):
branches[i] = branches[i].strip()
cd = subprocess.run(f'git log {branches[i]} -1 --date=format:"%Y/%m/%d %T" --format="%cd"', capture_output=True, env=env, shell=True)
last_commit_date.append(cd.stdout.decode('utf-8').strip())
branches = pd.DataFrame({
'branch_full': branches,
'branch': [b.replace('origin/', '') for b in branches],
'last_commit': last_commit_date,
'required': [False for _ in range(len(last_commit_date))]
})
branches.last_commit = pd.to_datetime(branches.last_commit)
branches.iloc[branches[branches.branch.isin(REQUIRED_BRANCHES)].index, -1] = True
branches['LAST_UPDATE'] = pd.to_datetime("now") - branches.last_commit
# set any other branches as required
# ...
to_delete = branches[(branches['LAST_UPDATE'] > pd.Timedelta(STALE_PERIOD, unit='d')) & (branches.required != True)]
for branch in to_delete.branch.values:
subprocess.run(f'git tag archive/{branch} origin/{branch}', env=env, shell=True)
subprocess.run(f'git push origin --delete {branch}', env=env, shell=True)
subprocess.run('git push --tags', env=env, shell=True)
print(to_delete)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment