get_env.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. #!/usr/bin/env python3
  2. import argparse
  3. import datetime
  4. import json
  5. import os
  6. import random
  7. import re
  8. import shlex
  9. import ssl
  10. import string
  11. import urllib.request
  12. def id_gen(size=5, chars=string.ascii_uppercase + string.digits):
  13. return "".join(random.choice(chars) for _ in range(size))
  14. def parse_args():
  15. parser = argparse.ArgumentParser()
  16. parser.add_argument("--event_file", help="Current GitHub event file", required=True)
  17. parser.add_argument(
  18. "--type",
  19. help="Event file type",
  20. required=True,
  21. choices=["pull", "tag", "other"],
  22. )
  23. args = parser.parse_args()
  24. return args
  25. def get_commit_json(event):
  26. context = ssl._create_unverified_context()
  27. commit_url = event["pull_request"]["base"]["repo"]["commits_url"].replace(
  28. "{/sha}", f"/{event['pull_request']['head']['sha']}"
  29. )
  30. with urllib.request.urlopen(commit_url, context=context) as commit_file:
  31. commit_json = json.loads(commit_file.read().decode("utf-8"))
  32. return commit_json
  33. def get_details(event, args):
  34. data = {}
  35. current_time = datetime.datetime.utcnow().date()
  36. if args.type == "pull":
  37. commit_json = get_commit_json(event)
  38. data["commit_comment"] = shlex.quote(commit_json["commit"]["message"])
  39. data["commit_hash"] = commit_json["sha"]
  40. ref = event["pull_request"]["head"]["ref"]
  41. data["pull_id"] = event["pull_request"]["number"]
  42. data["pull_name"] = shlex.quote(event["pull_request"]["title"])
  43. elif args.type == "tag":
  44. data["commit_comment"] = shlex.quote(event["head_commit"]["message"])
  45. data["commit_hash"] = event["head_commit"]["id"]
  46. ref = event["ref"]
  47. else:
  48. data["commit_comment"] = shlex.quote(event["commits"][-1]["message"])
  49. data["commit_hash"] = event["commits"][-1]["id"]
  50. ref = event["ref"]
  51. data["commit_sha"] = data["commit_hash"][:8]
  52. data["branch_name"] = re.sub("refs/\w+/", "", ref)
  53. data["suffix"] = (
  54. data["branch_name"].replace("/", "_")
  55. + "-"
  56. + current_time.strftime("%d%m%Y")
  57. + "-"
  58. + data["commit_sha"]
  59. )
  60. if ref.startswith("refs/tags/"):
  61. data["suffix"] = data["branch_name"].replace("/", "_")
  62. return data
  63. def add_env(name, value, file):
  64. delimeter = id_gen()
  65. print(f"{name}<<{delimeter}", file=file)
  66. print(f"{value}", file=file)
  67. print(f"{delimeter}", file=file)
  68. def add_set_output_var(name, value, file):
  69. print(f"{name}={value}", file=file)
  70. def add_envs(data, gh_env_file, gh_out_file, args):
  71. add_env("COMMIT_MSG", data["commit_comment"], gh_env_file)
  72. add_env("COMMIT_HASH", data["commit_hash"], gh_env_file)
  73. add_env("COMMIT_SHA", data["commit_sha"], gh_env_file)
  74. add_env("SUFFIX", data["suffix"], gh_env_file)
  75. add_env("BRANCH_NAME", data["branch_name"], gh_env_file)
  76. add_env("DIST_SUFFIX", data["suffix"], gh_env_file)
  77. add_env("WORKFLOW_BRANCH_OR_TAG", data["branch_name"], gh_env_file)
  78. add_set_output_var("branch_name", data["branch_name"], gh_out_file)
  79. add_set_output_var("commit_sha", data["commit_sha"], gh_out_file)
  80. add_set_output_var("default_target", os.getenv("DEFAULT_TARGET"), gh_out_file)
  81. add_set_output_var("suffix", data["suffix"], gh_out_file)
  82. if args.type == "pull":
  83. add_env("PULL_ID", data["pull_id"], gh_env_file)
  84. add_env("PULL_NAME", data["pull_name"], gh_env_file)
  85. def main():
  86. args = parse_args()
  87. event_file = open(args.event_file, "r")
  88. event = json.load(event_file)
  89. gh_env_file = open(os.environ["GITHUB_ENV"], "a")
  90. gh_out_file = open(os.environ["GITHUB_OUTPUT"], "a")
  91. data = get_details(event, args)
  92. add_envs(data, gh_env_file, gh_out_file, args)
  93. event_file.close()
  94. gh_env_file.close()
  95. gh_out_file.close()
  96. if __name__ == "__main__":
  97. main()