2013-09-26 08:32:39 +00:00
|
|
|
#!/usr/bin/env python
|
|
|
|
|
2013-09-26 11:48:48 +00:00
|
|
|
import json
|
2013-09-26 12:31:17 +00:00
|
|
|
import re
|
2013-09-26 08:32:39 +00:00
|
|
|
import requests
|
|
|
|
|
|
|
|
GITHUB_URL = 'https://api.github.com'
|
2013-09-26 12:31:17 +00:00
|
|
|
GITHUB_UPLOAD_ASSET_URL = 'https://uploads.github.com'
|
2013-09-26 08:32:39 +00:00
|
|
|
|
|
|
|
class GitHub:
|
|
|
|
def __init__(self, access_token):
|
|
|
|
self._authorization = 'token %s' % access_token
|
|
|
|
|
2013-09-26 12:31:17 +00:00
|
|
|
pattern = '^/repos/{0}/{0}/releases/{1}/assets$'.format('[^/]+', '[0-9]+')
|
|
|
|
self._releases_upload_api_pattern = re.compile(pattern)
|
|
|
|
|
2013-09-26 08:32:39 +00:00
|
|
|
def __getattr__(self, attr):
|
|
|
|
return _Callable(self, '/%s' % attr)
|
|
|
|
|
2013-09-27 02:21:27 +00:00
|
|
|
def send(self, method, path, **kw):
|
2013-09-26 08:32:39 +00:00
|
|
|
if not 'headers' in kw:
|
|
|
|
kw['headers'] = dict()
|
2013-09-26 11:48:48 +00:00
|
|
|
headers = kw['headers']
|
|
|
|
headers['Authorization'] = self._authorization
|
|
|
|
headers['Accept'] = 'application/vnd.github.manifold-preview'
|
2013-09-26 12:31:17 +00:00
|
|
|
|
|
|
|
# Switch to a different domain for the releases uploading API.
|
|
|
|
if self._releases_upload_api_pattern.match(path):
|
|
|
|
url = '%s%s' % (GITHUB_UPLOAD_ASSET_URL, path)
|
|
|
|
else:
|
|
|
|
url = '%s%s' % (GITHUB_URL, path)
|
2013-10-10 10:05:01 +00:00
|
|
|
# Data are sent in JSON format.
|
|
|
|
if 'data' in kw:
|
|
|
|
kw['data'] = json.dumps(kw['data'])
|
2013-09-26 12:31:17 +00:00
|
|
|
|
2013-09-26 11:48:48 +00:00
|
|
|
r = getattr(requests, method)(url, **kw).json()
|
|
|
|
if 'message' in r:
|
|
|
|
raise Exception(json.dumps(r, indent=2, separators=(',', ': ')))
|
|
|
|
return r
|
2013-09-26 08:32:39 +00:00
|
|
|
|
|
|
|
|
|
|
|
class _Executable:
|
|
|
|
def __init__(self, gh, method, path):
|
|
|
|
self._gh = gh
|
|
|
|
self._method = method
|
|
|
|
self._path = path
|
|
|
|
|
|
|
|
def __call__(self, **kw):
|
2013-09-27 02:21:27 +00:00
|
|
|
return self._gh.send(self._method, self._path, **kw)
|
2013-09-26 08:32:39 +00:00
|
|
|
|
|
|
|
|
|
|
|
class _Callable(object):
|
|
|
|
def __init__(self, gh, name):
|
|
|
|
self._gh = gh
|
|
|
|
self._name = name
|
|
|
|
|
|
|
|
def __call__(self, *args):
|
|
|
|
if len(args) == 0:
|
|
|
|
return self
|
|
|
|
|
|
|
|
name = '%s/%s' % (self._name, '/'.join([str(arg) for arg in args]))
|
|
|
|
return _Callable(self._gh, name)
|
|
|
|
|
|
|
|
def __getattr__(self, attr):
|
|
|
|
if attr in ['get', 'put', 'post', 'patch', 'delete']:
|
|
|
|
return _Executable(self._gh, attr, self._name)
|
|
|
|
|
|
|
|
name = '%s/%s' % (self._name, attr)
|
|
|
|
return _Callable(self._gh, name)
|