File indexing completed on 2024-11-24 04:54:31

0001 #!/usr/bin/env python
0002 
0003 import json
0004 import os
0005 import re
0006 import sys
0007 
0008 REQUESTS_DIR = os.path.abspath(os.path.join(__file__, '..', '..', '..',
0009                                             'vendor', 'requests'))
0010 sys.path.append(os.path.join(REQUESTS_DIR, 'build', 'lib'))
0011 sys.path.append(os.path.join(REQUESTS_DIR, 'build', 'lib.linux-x86_64-2.7'))
0012 import requests
0013 
0014 GITHUB_URL = 'https://api.github.com'
0015 GITHUB_UPLOAD_ASSET_URL = 'https://uploads.github.com'
0016 
0017 class GitHub:
0018   def __init__(self, access_token):
0019     self._authorization = 'token %s' % access_token
0020 
0021     pattern = '^/repos/{0}/{0}/releases/{1}/assets$'.format('[^/]+', '[0-9]+')
0022     self._releases_upload_api_pattern = re.compile(pattern)
0023 
0024   def __getattr__(self, attr):
0025     return _Callable(self, '/%s' % attr)
0026 
0027   def send(self, method, path, **kw):
0028     if not 'headers' in kw:
0029       kw['headers'] = dict()
0030     headers = kw['headers']
0031     headers['Authorization'] = self._authorization
0032     headers['Accept'] = 'application/vnd.github.manifold-preview'
0033 
0034     # Switch to a different domain for the releases uploading API.
0035     if self._releases_upload_api_pattern.match(path):
0036       url = '%s%s' % (GITHUB_UPLOAD_ASSET_URL, path)
0037     else:
0038       url = '%s%s' % (GITHUB_URL, path)
0039       # Data are sent in JSON format.
0040       if 'data' in kw:
0041         kw['data'] = json.dumps(kw['data'])
0042 
0043     r = getattr(requests, method)(url, **kw).json()
0044     if 'message' in r:
0045       raise Exception(json.dumps(r, indent=2, separators=(',', ': ')))
0046     return r
0047 
0048 
0049 class _Executable:
0050   def __init__(self, gh, method, path):
0051     self._gh = gh
0052     self._method = method
0053     self._path = path
0054 
0055   def __call__(self, **kw):
0056     return self._gh.send(self._method, self._path, **kw)
0057 
0058 
0059 class _Callable(object):
0060   def __init__(self, gh, name):
0061     self._gh = gh
0062     self._name = name
0063 
0064   def __call__(self, *args):
0065     if len(args) == 0:
0066       return self
0067 
0068     name = '%s/%s' % (self._name, '/'.join([str(arg) for arg in args]))
0069     return _Callable(self._gh, name)
0070 
0071   def __getattr__(self, attr):
0072     if attr in ['get', 'put', 'post', 'patch', 'delete']:
0073       return _Executable(self._gh, attr, self._name)
0074 
0075     name = '%s/%s' % (self._name, attr)
0076     return _Callable(self._gh, name)