gh_pr.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. """Create a pull request from the bot fork using GitHub CLI."""
  2. import argparse
  3. import json
  4. import subprocess
  5. from pathlib import Path
  6. UPSTREAM = 'Light-Beacon/PCL2-NewsHomepage'
  7. BOT = 'Hilda-Bot'
  8. def create_pr(branch, title, body_file):
  9. login = subprocess.check_output(['gh', 'api', 'user', '--jq', '.login'], text=True, timeout=60).strip()
  10. if login.casefold() != BOT.casefold():
  11. raise RuntimeError(f'gh must authenticate as {BOT}; current account: {login}')
  12. head = f'{BOT}:{branch}'
  13. existing = json.loads(subprocess.check_output([
  14. 'gh', 'pr', 'list', '--repo', UPSTREAM, '--state', 'all',
  15. '--head', branch, '--base', 'main', '--limit', '1000',
  16. '--json', 'url,state,headRepositoryOwner'], text=True, timeout=60))
  17. matches = [pr for pr in existing
  18. if pr.get('headRepositoryOwner', {}).get('login', '').casefold() == BOT.casefold()]
  19. if matches:
  20. # Do not silently reopen rejected or merged contributions.
  21. print(matches[0]['url'])
  22. return matches[0]['url']
  23. return subprocess.check_output([
  24. 'gh', 'pr', 'create', '--repo', UPSTREAM, '--base', 'main',
  25. '--head', head, '--title', title, '--body-file', str(body_file.resolve())
  26. ], text=True, timeout=60).strip()
  27. if __name__ == '__main__':
  28. parser = argparse.ArgumentParser(description=__doc__)
  29. parser.add_argument('--branch', required=True)
  30. parser.add_argument('--title', required=True)
  31. parser.add_argument('--body-file', required=True, type=Path)
  32. args = parser.parse_args()
  33. print(create_pr(args.branch, args.title, args.body_file))