post_status_to_github.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import datetime
  2. import os
  3. import json
  4. from github import Github, Auth as GithubAuth
  5. from github.PullRequest import PullRequest
  6. def post(is_valid, error_description):
  7. gh = Github(auth=GithubAuth.Token(os.environ["GITHUB_TOKEN"]))
  8. with open(os.environ["GITHUB_EVENT_PATH"]) as fp:
  9. event = json.load(fp)
  10. pr = gh.create_from_raw_data(PullRequest, event["pull_request"])
  11. header = f"<!-- status pr={pr.number}, validate PR description status -->"
  12. body = [header]
  13. comment = None
  14. for c in pr.get_issue_comments():
  15. if c.body.startswith(header):
  16. print(f"found comment id={c.id}")
  17. comment = c
  18. status_to_header = {
  19. True: "The validation of the Pull Request description is successful.",
  20. False: "The validation of the Pull Request description has failed. Please update the description."
  21. }
  22. color = "green" if is_valid else "red"
  23. indicator = f":{color}_circle:"
  24. timestamp_str = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
  25. body.append(f"{indicator} `{timestamp_str}` {status_to_header[is_valid]}")
  26. if not is_valid:
  27. body.append(f"\n{error_description}")
  28. body = "\n".join(body)
  29. if comment:
  30. print(f"edit comment")
  31. comment.edit(body)
  32. else:
  33. print(f"post new comment")
  34. pr.create_issue_comment(body)