getsentry-dispatch-setup 2.4 KB

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