getsentry-dispatch-setup 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env python3
  2. import argparse
  3. import json
  4. import os
  5. import urllib.request
  6. LABEL = "Trigger: getsentry tests"
  7. def _has_write(repo_id: int, username: str, *, token: str) -> bool:
  8. req = urllib.request.Request(
  9. f"https://api.github.com/repositories/{repo_id}/collaborators/{username}/permission",
  10. headers={"Authorization": f"token {token}"},
  11. )
  12. contents = json.load(urllib.request.urlopen(req, timeout=10))
  13. return contents["permission"] in {"admin", "write"}
  14. def _remove_label(repo_id: int, pr: int, label: str, *, token: str) -> None:
  15. req = urllib.request.Request(
  16. f"https://api.github.com/repositories/{repo_id}/issues/{pr}/labels/{label}",
  17. method="DELETE",
  18. headers={"Authorization": f"token {token}"},
  19. )
  20. urllib.request.urlopen(req)
  21. def main() -> int:
  22. parser = argparse.ArgumentParser()
  23. parser.add_argument("--repo-id", type=int, required=True)
  24. parser.add_argument("--pr", type=int, required=True)
  25. parser.add_argument("--event", required=True)
  26. parser.add_argument("--username", required=True)
  27. parser.add_argument("--label-names", type=json.loads, required=True)
  28. args = parser.parse_args()
  29. token = os.environ["GITHUB_TOKEN"]
  30. write_permission = _has_write(args.repo_id, args.username, token=token)
  31. if (
  32. not write_permission
  33. # `reopened` is included here due to close => push => reopen
  34. and args.event in {"synchronize", "reopened"}
  35. and LABEL in args.label_names
  36. ):
  37. print(f"invalidating label({LABEL}) due to code change...")
  38. _remove_label(args.repo_id, args.pr, LABEL, token=token)
  39. args.label_names.remove(LABEL)
  40. if write_permission or LABEL in args.label_names:
  41. print("permissions passed!")
  42. print(f"- has write permission: {write_permission}")
  43. print(f"- has [{LABEL}] label: {LABEL in args.label_names}")
  44. return 0
  45. else:
  46. print(
  47. f"please have a collaborator add the [{LABEL}] label once they "
  48. f"have reviewed the code to trigger downstream tests."
  49. )
  50. return 1
  51. if __name__ == "__main__":
  52. raise SystemExit(main())