Skip to content

Instantly share code, notes, and snippets.

@mbstacy
Last active October 30, 2018 17:04
Show Gist options
  • Save mbstacy/6c769be0b5c7aac0b52e6037592da397 to your computer and use it in GitHub Desktop.
Save mbstacy/6c769be0b5c7aac0b52e6037592da397 to your computer and use it in GitHub Desktop.

gitPushAdminEnforcement

gitPushAdminEnforcement uses Github API to turn off admin enforcement, run git push, and re-enable admin enforcement.

Installation:

  1. pip install PyGithub
  2. Copy gitPushAdminEnforcement in a bin directory (eg: ~/.local/bin)
  3. Add bin directory to PATH variable
  4. chmod +x ~/.local/bin/gitPushAdminEnforcement
  5. Create Github Personal Access Token
  6. Set Environmental Variable GITHUB_PERSONAL_ACCESS_TOKEN= < personal access token >

Usage

  gitPushAdminEnforcement <remote> <branch>
#!/usr/bin/env python
from github import Github
from sys import argv
from subprocess import check_output
import os
token = os.environ.get("GITHUB_PERSONAL_ACCESS_TOKEN")
g = Github(login_or_token=token)
def getOrgRepo(remote):
output= check_output(['git','remote','-v'])
for itm in output.split(b'\n'):
if remote in str(itm):
if 'https' in str(itm):
return "/".join(str(itm).split('/')[-2:]).split('.')[0]
else:
return str(itm).split(':')[1].split('.')[0]
raise Exception("Git Remote: {0} was not found".format(remote))
def gitCommitAdminProtection(remote,branchName):
orgRepo = getOrgRepo(remote)
print(orgRepo,remote,branchName)
branch = g.get_repo(orgRepo).get_branch(branchName)
statusEnforcement=branch.get_admin_enforcement()
if statusEnforcement:
branch.remove_admin_enforcement()
else:
print("Repository branch ({0}) does not have Admin Enforcement".format(branchName))
return None
try:
output= check_output(['git','push',remote, branchName])
branch.set_admin_enforcement()
return output
except KeyboardInterrupt:
branch.set_admin_enforcement()
return None
if __name__ == '__main__':
try:
remote=argv[1]
except:
raise Exception("Git remote is required")
try:
branch=argv[2]
except:
raise Exception("Git Branch is required")
gitPushAdminEnforcement(remote,branch)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment