#!/usr/bin/env python3 import subprocess import time from datetime import datetime NOW = time.time() class Branch: name: str timestanp: int keep: bool def for_print(self): date = datetime.utcfromtimestamp(self.timestamp).strftime('%Y-%m-%d') return (f'{date} {self.name}') def git(*args): return subprocess.check_output(('git', *args)).decode() def get_branch_names(): raw = git('branch', '-r') branches = [] for branch in raw.split('\n'): clean_branch = branch.strip() if not clean_branch: continue if '->' in clean_branch: continue branches.append(clean_branch) return branches def get_branch_timestamp(branch_name): return int(git('show', '-s', '--format=%ct', branch_name)) def need_keep(branch): name = branch.name timestamp = branch.timestamp # Keep branches newer than 60 days if NOW - timestamp < 60 * 60 * 24 * 60: return True # Keep release branches if name.startswith('blender-v'): return True # Keep special series branches # if name in ('blender2.4', 'blender2.5', 'blender2.7'): # return True return False def get_branches(): branches = [] for name in get_branch_names(): remote, short_name = name.split('/', 1) if remote != 'origin': continue branch = Branch() branch.name = short_name branch.timestamp = get_branch_timestamp(name) branch.keep = need_keep(branch) branches.append(branch) # return sorted(branches, key=lambda branch: branch.timestamp) return sorted(branches, key=lambda branch: branch.name) branches = get_branches() def human_readable(): print("*" * 72) print("** Old branches classifier script") print("*" * 72) print() print("-" * 32) print("Keep") print() num_keep = 0 for branch in branches: if not branch.keep: continue print(branch.for_print()) num_keep += 1 print(f"Total keep: {num_keep}") print() print("-" * 32) print("Remove") print() num_remove = 0 for branch in branches: if branch.keep: continue print(branch.for_print()) num_remove += 1 print(f"Total remove: {num_remove}") def generate_push_to_staging(): print('set -e') print() for branch in branches: if branch.name == 'main': continue print(f"echo '-> Pushing {branch.name}'") if branch.name in ('temp-dna-rename', ): print(f"git push staging 'refs/remotes/origin/{branch.name}:refs/heads/{branch.name}--archived'") else: print(f"git push staging 'refs/remotes/origin/{branch.name}:refs/heads/{branch.name}'") print('echo') print() def generate_delete_from_origin(): print('set -e') print() for branch in branches: if branch.name == 'main': continue if branch.keep: print() print(f"# Keeping {branch.name}'") print() continue print(f"echo '-> Deleting {branch.name}'") print(f"git push origin ':{branch.name}'") print('echo') print() human_readable() # generate_push_to_staging() # generate_delete_from_origin()