File indexing completed on 2024-05-19 04:19:32
0001 import os 0002 import sys 0003 import json 0004 import shlex 0005 import requests 0006 from urllib.parse import urljoin, quote_plus 0007 0008 0009 def fail(msg): 0010 sys.stderr.write(msg+"\n") 0011 sys.exit(1) 0012 0013 0014 def environ(varname, failmsg=""): 0015 try: 0016 return os.environ[varname] 0017 except KeyError: 0018 fail("Missing environment variable %s: %s\n" % (varname, failmsg)) 0019 0020 0021 class GitlabApi: 0022 default_project_url = "https://gitlab.com/mattbas/glaxnimate" 0023 default_project_id = "19921167" 0024 0025 def __init__(self, project_url=default_project_url, project_id=default_project_id, api_key=None): 0026 self.project_url = project_url 0027 self.project_id = project_id 0028 self.api_version = "v4" 0029 self.api_url = urljoin(self.project_url, "/api/%s/projects/%s" % (self.api_version, self.project_id)) 0030 self.api_key = api_key 0031 0032 def request(self, method, url, **kwargs): 0033 kwargs.setdefault("headers", {}) 0034 0035 if self.api_key: 0036 kwargs["headers"]["PRIVATE-TOKEN"] = self.api_key 0037 0038 if "json" in kwargs: 0039 kwargs["headers"]["Content-Type"] = "application/json" 0040 can_fail = not kwargs.pop("can_fail", False) 0041 0042 self.debug_curl(method, url, **kwargs) 0043 res = requests.request(method, url, **kwargs) 0044 if can_fail: 0045 res.raise_for_status() 0046 return res.json() 0047 0048 def project_request(self, method, url, **kwargs): 0049 return self.request(method, "/".join([self.api_url] + url), **kwargs) 0050 0051 def debug_curl(self, method, url, **kwargs): 0052 command = "curl -i -X %s %s" % (method.upper(), shlex.quote(url)) 0053 0054 if "data" in kwargs: 0055 command += " -d " + shlex.quote(kwargs.pop("data")) 0056 elif "json" in kwargs: 0057 command += " -d " + shlex.quote(json.dumps(kwargs.pop("json"))) 0058 0059 for header, value in kwargs.pop("headers", {}).items(): 0060 command += " -H \"%s: " % shlex.quote(header) 0061 if value == self.api_key: 0062 command += "$GITLAB_ACCESS_TOKEN" 0063 else: 0064 command += shlex.quote(value) 0065 command += '"' 0066 0067 print("CURL:") 0068 print(command) 0069 if kwargs: 0070 print(kwargs) 0071 0072 def artifact_url(self, ref, job, file): 0073 return self.artifacts_url(ref) + "/%s?job=%s" % (file, job.replace(":", "%3A")) 0074 0075 def artifacts_url(self, ref): 0076 return self.api_url + "/jobs/artifacts/%s/raw" % ref.replace(".", "%2E") 0077 0078 @classmethod 0079 def from_env(cls): 0080 project_url = environ("CI_PROJECT_URL") 0081 project_id = environ("CI_PROJECT_ID") 0082 api_key = environ("GITLAB_ACCESS_TOKEN", "You must specify an access token. See https://gitlab.com/-/profile/personal_access_tokens") 0083 return cls(project_url, project_id, api_key) 0084 0085 @classmethod 0086 def fake_env(cls): 0087 os.environ.setdefault("CI_PROJECT_URL", cls.default_project_url) 0088 os.environ.setdefault("CI_PROJECT_ID", cls.default_project_id)