comment-pr.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #!/usr/bin/env python
  2. import datetime
  3. import os
  4. import json
  5. import argparse
  6. from github import Github, Auth as GithubAuth
  7. from github.PullRequest import PullRequest
  8. def update_pr_comment_text(pr: PullRequest, build_preset: str, run_number: int, color: str, text: str, rewrite: bool):
  9. header = f"<!-- status pr={pr.number}, preset={build_preset}, run={run_number} -->"
  10. body = comment = None
  11. for c in pr.get_issue_comments():
  12. if c.body.startswith(header):
  13. print(f"found comment id={c.id}")
  14. comment = c
  15. if not rewrite:
  16. body = [c.body]
  17. break
  18. if body is None:
  19. body = [header]
  20. indicator = f":{color}_circle:"
  21. timestamp_str = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC")
  22. body.append(f"{indicator} `{timestamp_str}` {text}")
  23. body = "\n".join(body)
  24. if comment is None:
  25. print(f"post new comment")
  26. pr.create_issue_comment(body)
  27. else:
  28. print(f"edit comment")
  29. comment.edit(body)
  30. def main():
  31. parser = argparse.ArgumentParser()
  32. parser.add_argument("--rewrite", dest="rewrite", action="store_true")
  33. parser.add_argument("--color", dest="color", default="white")
  34. parser.add_argument("text", type=argparse.FileType("r"), nargs="?", default="-")
  35. args = parser.parse_args()
  36. color = args.color
  37. run_number = int(os.environ.get("GITHUB_RUN_NUMBER"))
  38. build_preset = os.environ["BUILD_PRESET"]
  39. gh = Github(auth=GithubAuth.Token(os.environ["GITHUB_TOKEN"]))
  40. with open(os.environ["GITHUB_EVENT_PATH"]) as fp:
  41. event = json.load(fp)
  42. pr = gh.create_from_raw_data(PullRequest, event["pull_request"])
  43. text = args.text.read()
  44. if text.endswith("\n"):
  45. # dirty hack because echo adds a new line
  46. # and 'echo | comment-pr.py' leads to an extra newline
  47. text = text[:-1]
  48. update_pr_comment_text(pr, build_preset, run_number, color, text, args.rewrite)
  49. if __name__ == "__main__":
  50. if os.environ.get('GITHUB_EVENT_NAME', '').startswith('pull_request'):
  51. main()