I'm trying to create a script with list merged remote release
branches which haven't had any updates in last 6 months, and then remove them.
So far, I've been trying to do the list branches part with following script:
import subprocess
import subprocess
import sys
import git
from git import Repo, repo
from git import Git
def get_merged_release_branches():
result_release = subprocess.getoutput("git branch -r --merged | grep release | sed 's#origin/##'")
return (result_release)
command = 'git log -1 --pretty=format:"%Cgreen%as" --before \\\'6 month ago'
for branch in get_merged_release_branches():
output = subprocess.Popen(command, universal_newlines=True, shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
print(output)
but that doesn´t seems to work. Getting black screen like iterating into something.
Also not sure if with subprocess.popen
is the best choice. What should be the best recommendation if not for this?
Also tried with:
output = subprocess.call(["git","log -1","--pretty=format:\\\"%Cgreen%as\\\ --before \\\'6 month ago'"])
but didn´t work either.
I also know you have git for python here but don´t know the best way to implement this.
CodePudding user response:
For such a simple workflow, you can achieve this quite simply with a few subprocess
calls.
import subprocess
def get_merged_release_branches():
result_release = subprocess.getoutput("git branch -r --merged")
if "release" in result_release:
yield result_release
def is_release_branch_stale(branch_name):
commits_since_sixmonths = subprocess.getoutput(f"git log -1 {branch_name} --after '6 month ago'")
if commits_since_sixmonths is not None:
return True
return False
for branch in get_merged_release_branches():
if is_release_branch_stale(branch):
print(f"Branch {branch} is stale and can be deleted!")
this will print all the merged remote branches which are stale (which for you means no commits since six months ago).
You can now easily add another method to delete the branches from the remote:
def delete_stale_remote_branch(branch_name):
delete_status = subprocess.getoutput(f"git branch -d {branch_name}")
print(delete_status)