diff --git a/.gitignore b/.gitignore index b802fae..cd59d9f 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,4 @@ -toy.py \ No newline at end of file +*.py? +.workon +toy.py +github3.egg-info/ diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000..bcf74ac --- /dev/null +++ b/AUTHORS @@ -0,0 +1,14 @@ +python-github3 is written and maintained by Kenneth Reitz and +various contributors: + +Development Lead +```````````````` + +- Kenneth Reitz + + +Patches and Suggestions +``````````````````````` + +- Mahdi Yusuf +- Rok Garbas \ No newline at end of file diff --git a/HACKING b/HACKING new file mode 100644 index 0000000..018f9b7 --- /dev/null +++ b/HACKING @@ -0,0 +1,14 @@ +Where possible, please follow PEP8 with regard to coding style. Sometimes the line +length restriction is too hard to follow, so don't bend over backwards there. + +Triple-quotes should always be """, single quotes are ' unless using " +would result in less escaping within the string. + +All modules, functions, and methods should be well documented reStructuredText for +Sphinx AutoDoc. + +All functionality should be available in pure Python. Optional C (via Cython) +implementations may be written for performance reasons, but should never +replace the Python implementation. + +Lastly, don't take yourself too seriously :) \ No newline at end of file diff --git a/LICENSE b/LICENSE index 8cb0518..8a9ee98 100644 --- a/LICENSE +++ b/LICENSE @@ -1,7 +1,13 @@ -Copyright (c) 2011 Kenneth Reitz +Copyright (c) 2011 Kenneth Reitz. -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. \ No newline at end of file diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..4c7a2bc --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1 @@ +include README.rst LICENSE AUTHORS \ No newline at end of file diff --git a/Makefile b/Makefile deleted file mode 100644 index 74a993d..0000000 --- a/Makefile +++ /dev/null @@ -1,3 +0,0 @@ -init: - pip install -r requirements.txt - diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..0a0d3fe --- /dev/null +++ b/NOTICE @@ -0,0 +1,65 @@ +python-github3 includes some vendorized python libraries: ordereddict, omijson, and simplejson. + + +OrderedDict License +=================== + +Copyright (c) 2009 Raymond Hettinger + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation files +(the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of the Software, +and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + + +OmniJSON License +================== + +Copyright (c) 2011 Kenneth Reitz + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +SimpleJSON License +================== + + +Copyright (c) 2006 Bob Ippolito + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.rst b/README.rst index 51ad11a..4e5df72 100644 --- a/README.rst +++ b/README.rst @@ -1,36 +1,78 @@ -Github3: Python API Wrapper -=========================== +Github3: Python wrapper for the (new) GitHub API v3 +=================================================== + +Github has a new API. This is the best Python wrapper for it. + +**This a work in progress.** Should be relased soon. -This is an awesome Python wrapper for the Github API. Usage ----- -Detailed docs forthcoming. +:: + + import github3 + + gh = github3.basic_auth('username', 'password') + + gh.get_repo('kennethreitz', 'python-github3') + + + Installation ------------ -To install github3, simply:: +To install Github3, simply: :: $ pip install github3 -Or, if you absolutely must:: +Or, if you absolutely must: :: $ easy_install github3 -But, you `really shouldn't do that `_. +But, you really shouldn't do that. + License ------- -Copyright (c) 2011 Kenneth Reitz +ISC License. :: -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + Copyright (c) 2011, Kenneth Reitz -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted, provided that the above + copyright notice and this permission notice appear in all copies. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +Contribute +---------- + +If you'd like to contribute, simply fork `the repository`_, commit your changes +to the **develop** branch (or branch off of it), and send a pull request. Make +sure you add yourself to AUTHORS_. + + + +Roadmap +------- -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file +- Get it Started +- HTTP BASIC +- Get it working +- Sphinx Documetnation +- Examples +- Unittests +- OAuth Last (how?) \ No newline at end of file diff --git a/github3/__init__.py b/github3/__init__.py index 02ad01e..c2fdbad 100644 --- a/github3/__init__.py +++ b/github3/__init__.py @@ -1,39 +1,3 @@ # -*- coding: utf-8 -*- -# I8 ,dPYb, ,dPYb, -# I8 IP'`Yb IP'`Yb -# gg 88888888 I8 8I I8 8I -# "" I8 I8 8' I8 8' -# ,gggg,gg gg I8 I8 dPgg, gg gg I8 dP -# dP" "Y8I 88 I8 I8dP" "8I I8 8I I8dP 88gg -# i8' ,8I 88 ,I8, I8P I8 I8, ,8I I8P 8I -# ,d8, ,d8I _,88,_ ,d88b, ,d8 I8,,d8b, ,d8b,,d8b, ,8I -# P"Y8888P"8888P""Y8 8P""Y8 88P `Y88P'"Y88P"`Y88P'"Y88P"' -# ,d8I' -# ,dP'8I -# ,8" 8I -# I8 8I -# `8, ,8I -# `Y8P" - - -""" -github3 -~~~~~~~ - -:copyright: (c) 2011 by Kenneth Reitz. -:license: MIT, see LICENSE for more details. -""" - -# Meta. - -__title__ = 'github3' -__author__ = 'Kenneth Reitz' -__copyright__ = 'Copyright 2011 Kenneth Reitz' -__license__ = 'MIT' - -__version__ = '0.0.1' - -# Module namespace. - -from .core import login \ No newline at end of file +from core import * \ No newline at end of file diff --git a/github3/api.py b/github3/api.py index b210135..8734823 100644 --- a/github3/api.py +++ b/github3/api.py @@ -2,62 +2,36 @@ """ github3.api -~~~~~~~~~~ +~~~~~~~~~~~ -This module provides the basic API interface for Github. +This module provies the core GitHub3 API interface. """ -import json +from .packages import omnijson as json +from .packages.link_header import parse_link_value -import requests -from .helpers import is_collection -from .structures import KeyedListResource from .models import * +from .helpers import is_collection, to_python, to_api, get_scope +from .config import settings -GITHUB_URL = 'https://api.github.com' - - -class GithubCore(object): - """The core Github class.""" - def __init__(self): - super(GithubCore, self).__init__() - - #: The User's API Key. - self._api_key = None - self._api_key_verified = None - self._s = requests.session() - self._github_url = GITHUB_URL - - # We only want JSON back. - self._s.headers.update({'Accept': 'application/json'}) - def __repr__(self): - return '' % (id(self)) +import requests - def login(self, username, password): - """Logs user into Github with given credentials.""" +from decorator import decorator - # Attach auth to session. - self._s.auth = (username.password) - return True +class GithubCore(object): - @property - def is_authenticated(self): - if self._api_key_verified is None: - return self._verify_api_key() - else: - return self._api_key_verified + _rate_limit = None + _rate_limit_remaining = None - def _url_for(self, *args): - args = map(str, args) - return '/'.join([self._github_url] + list(args)) @staticmethod def _resource_serialize(o): """Returns JSON serialization of given object.""" return json.dumps(o) + @staticmethod def _resource_deserialize(s): """Returns dict deserialization of a given JSON string.""" @@ -67,64 +41,140 @@ def _resource_deserialize(s): except ValueError: raise ResponseError('The API Response was not valid.') - def _http_resource(self, method, resource, params=None, data=None): - """Makes an HTTP request.""" - if not is_collection(resource): - resource = [resource] + @staticmethod + def _generate_url(endpoint): + """Generates proper endpoint URL.""" + + if is_collection(endpoint): + resource = map(str, endpoint) + resource = '/'.join(endpoint) + else: + resource = endpoint + + return (settings.base_url + resource) + + + def _requests_pre_hook(self, *args, **kwargs): + """Pre-processing for HTTP requests arguments.""" + return args, kwargs + + + def _requests_post_hook(self, r): + """Post-processing for HTTP response objects.""" - url = self._url_for(*resource) - r = self._s.request(method, url, params=params, data=data) + self._ratelimit = int(r.headers.get('x-ratelimit-limit', -1)) + self._ratelimit_remaining = int(r.headers.get('x-ratelimit-remaining', -1)) + + return r + + + def _http_resource(self, verb, endpoint, data=None, params=None, authed=True): + + url = self._generate_url(endpoint) + if authed: + args, kwargs = self._requests_pre_hook(verb, url, data=data, params=params) + else: + args = (verb, url) + kwargs = {'data': data, 'params': params} + r = requests.request(*args, **kwargs) + r = self._requests_post_hook(r) + # print self._ratelimit_remaining r.raise_for_status() return r - def _get_resource(self, resource, obj, params=None, **kwargs): - """Returns a mapped object from an HTTP resource.""" - r = self._http_resource('GET', resource, params=params) + + def _get_resource(self, resource, obj, authed=True, **kwargs): + + r = self._http_resource('GET', resource, params=kwargs, authed=authed) item = self._resource_deserialize(r.content) - return obj.new_from_dict(item, h=self, **kwargs) + return obj.new_from_dict(item, gh=self) + + + def _get_resources(self, resource, obj, authed=True, **kwargs): - def _get_resources(self, resource, obj, params=None, map=None, **kwargs): - """Returns a list of mapped objects from an HTTP resource.""" - r = self._http_resource('GET', resource, params=params) + r = self._http_resource('GET', resource, params=kwargs, authed=authed) d_items = self._resource_deserialize(r.content) - items = [obj.new_from_dict(item, h=self, **kwargs) for item in d_items] + items = [] + + for item in d_items: + items.append(obj.new_from_dict(item, gh=self)) + + return items + + + def _delete_resource(self, resource, authed=True, **kwargs): + + r = self._http_resource('DELETE', resource, params=kwargs, authed=authed) + + return True + + + def _post_resource(self, resource, obj, data=None, authed=True, **kwargs): - if map is None: - map = KeyedListResource + r = self._http_resource('POST', resource, data=data, params=kwargs, authed=authed) + item = self._resource_deserialize(r.content) + + return obj.new_from_dict(item, gh=self) + + + def _to_map(self, obj, iterable): + """Maps given dict iterable to a given Resource object.""" + + a = list() + + for it in iterable: + a.append(obj.new_from_dict(it, rdd=self)) + + return a - list_resource = map(items=items) - list_resource._h = self - list_resource._obj = obj + def _get_url(self, resource): + + if is_collection(resource): + resource = map(str, resource) + resource = '/'.join(resource) + + return resource - return list_resource class Github(GithubCore): - """The main Github class.""" + """docstring for Github""" def __init__(self): super(Github, self).__init__() + self.is_authenticated = False + + + def get_user(self, username): + """Get a single user.""" + return self._get_resource(('users', username), User) + + def get_org(self, orgname): + """Get a single organization.""" + return self._get_resource(('orgs', orgname), Organization) + + def get_me(self): + """Get the authenticated user.""" + return self._get_resource(('user'), CurrentUser) - def __repr__(self): - return '' % (id(self)) + # def get_repos(self, username): + # """Get repos.""" + # return self._get_resource(('user', 'username', 'repos'), Repo) - # @property - # def addons(self): - # return self._get_resources(('addons'), Addon) + def get_repo(self, username, reponame): + """Get the authenticated user.""" + return self._get_resource(('repos', username, reponame), Repo) - # @property - # def apps(self): - # return self._get_resources(('apps'), App) + def get_issues(self, username, reponame): + return self._get_resources(('repos', username, reponame, 'issues'), + Issue) - # @property - # def keys(self): - # return self._get_resources(('user', 'keys'), Key, map=SSHKeyListResource) +class ResponseError(Exception): + """The API Response was unexpected.""" -class ResponseError(ValueError): - """The API Response was unexpected.""" \ No newline at end of file diff --git a/github3/config.py b/github3/config.py new file mode 100644 index 0000000..ad233c2 --- /dev/null +++ b/github3/config.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- + +""" +github3.config +~~~~~~~~~~~~~~ + +This module provides the Github3 settings feature set. + +""" + +class Settings(object): + _singleton = {} + + # attributes with defaults + __attrs__ = [] + + def __init__(self, **kwargs): + super(Settings, self).__init__() + + self.__dict__ = self._singleton + + + def __call__(self, *args, **kwargs): + # new instance of class to call + r = self.__class__() + + # cache previous settings for __exit__ + r.__cache = self.__dict__.copy() + map(self.__cache.setdefault, self.__attrs__) + + # set new settings + self.__dict__.update(*args, **kwargs) + + return r + + + def __enter__(self): + pass + + + def __exit__(self, *args): + + # restore cached copy + self.__dict__.update(self.__cache.copy()) + del self.__cache + + + def __getattribute__(self, key): + if key in object.__getattribute__(self, '__attrs__'): + try: + return object.__getattribute__(self, key) + except AttributeError: + return None + return object.__getattribute__(self, key) + +settings = Settings() +settings.verbose = False +settings.base_url = 'https://api.github.com/' +settings.github_upload_file_url = 'http://github.s3.amazonaws.com' diff --git a/github3/core.py b/github3/core.py index 071dea2..0a338c7 100644 --- a/github3/core.py +++ b/github3/core.py @@ -2,19 +2,60 @@ """ github3.core -~~~~~~~~~~~~~ +~~~~~~~~~~~~ -This module provides the base entrypoint for github3. +This module provides the entrance point for the GitHub3 module. """ -from .api import Github +__version__ = '0.0.0' +__license__ = 'MIT' +__author__ = 'Kenneth Reitz' -def login(username, password): - """Returns an authenticated Github instance, via API Key.""" + +import envoy + +from .api import Github, settings + + + +def no_auth(): + """Returns an un-authenticated Github object.""" gh = Github() - # Login. - gh.login(username, password) + return gh + + +def basic_auth(username, password): + """Returns an authenticated Github object, via HTTP Basic.""" + + def enable_auth(*args, **kwargs): + kwargs['auth'] = (username, password) + return args, kwargs + + gh = Github() + gh.is_authenticated = True + gh._requests_pre_hook = enable_auth return gh + + + +def git_config(): + """Returns an authenticated Github object, via HTTP Basic. + + GitHub API token is taken from `git config`. + """ + + username = envoy.run('git config github.user').std_out.strip() + token = envoy.run('git config github.token').std_out.strip() + + def enable_auth(*args, **kwargs): + kwargs['auth'] = (username, token) + return args, kwargs + + gh = Github() + gh.is_authenticated = True + gh._requests_pre_hook = enable_auth + + return gh \ No newline at end of file diff --git a/github3/helpers.py b/github3/helpers.py index d742acb..6d17be0 100644 --- a/github3/helpers.py +++ b/github3/helpers.py @@ -2,15 +2,17 @@ """ github3.helpers -~~~~~~~~~~~~~~~ +~~~~~~~~~~~~~~~~ -This module contians the helpers. +This module provides various helper functions to the rest of the package. """ +import inspect from datetime import datetime from dateutil.parser import parse as parse_datetime + def is_collection(obj): """Tests if an object is a collection.""" @@ -23,17 +25,14 @@ def is_collection(obj): return val - -# from kennethreitz/python-github3 +# from arc90/python-readability-api def to_python(obj, in_dict, str_keys=None, date_keys=None, int_keys=None, object_map=None, - bool_keys=None, - dict_keys=None, - **kwargs): + bool_keys=None, **kwargs): """Extends a given object for API Consumption. :param obj: Object to extend. @@ -43,53 +42,46 @@ def to_python(obj, :param object_map: Dict of {key, obj} map, for nested object results. """ - d = dict() - if str_keys: for in_key in str_keys: - d[in_key] = in_dict.get(in_key) + obj.__dict__[in_key] = in_dict.get(in_key) if date_keys: for in_key in date_keys: in_date = in_dict.get(in_key) try: - out_date = parse_datetime(in_date) - except TypeError, e: - raise e + out_date = datetime.strptime(in_date, '%Y-%m-%dT%H:%M:%SZ') + except TypeError: out_date = None - d[in_key] = out_date + obj.__dict__[in_key] = out_date if int_keys: for in_key in int_keys: if (in_dict is not None) and (in_dict.get(in_key) is not None): - d[in_key] = int(in_dict.get(in_key)) + obj.__dict__[in_key] = int(in_dict.get(in_key)) if bool_keys: for in_key in bool_keys: if in_dict.get(in_key) is not None: - d[in_key] = bool(in_dict.get(in_key)) - - if dict_keys: - for in_key in dict_keys: - if in_dict.get(in_key) is not None: - d[in_key] = dict(in_dict.get(in_key)) + obj.__dict__[in_key] = bool(in_dict.get(in_key)) if object_map: for (k, v) in object_map.items(): - if in_dict.get(k): - d[k] = v.new_from_dict(in_dict.get(k)) + o = in_dict.get(k) + if o: + # Handle collections separately + if isinstance(o, list): + obj.__dict__[k] = [v.new_from_dict(i) for i in o] + else: + obj.__dict__[k] = v.new_from_dict(in_dict.get(k)) - obj.__dict__.update(d) obj.__dict__.update(kwargs) - # Save the dictionary, for write comparisons. - obj._cache = d - obj.__cache = in_dict - return obj +# from arc90/python-readability-api def to_api(in_dict, int_keys=None, date_keys=None, bool_keys=None): """Extends a given object for API Production.""" @@ -123,3 +115,28 @@ def to_api(in_dict, int_keys=None, date_keys=None, bool_keys=None): del in_dict[k] return in_dict + + + +# from kennethreitz/showme +def get_scope(f, args=None): + """Get scope of given function for Exception scopes.""" + + if args is None: + args=list() + + scope = inspect.getmodule(f).__name__ + # guess that function is a method of it's class + try: + if f.func_name in dir(args[0].__class__): + scope += '.' + args[0].__class__.__name__ + scope += '.' + f.__name__ + else: + scope += '.' + f.__name__ + except IndexError: + scope += '.' + f.__name__ + + # scrub readability.models namespace + scope = scope.replace('readability.api.', '') + + return scope diff --git a/github3/models.py b/github3/models.py index 4380b62..ea10106 100644 --- a/github3/models.py +++ b/github3/models.py @@ -1,263 +1,268 @@ -# -*- coding: utf-8 -*- - """ github3.models ~~~~~~~~~~~~~~ -This module contains the models that comprise the Github API. +This module provides the Github3 object model. """ -import json -from urllib import quote - +from .helpers import to_python, to_api +import os +import magic +from .config import settings import requests -from .helpers import to_python -from .structures import * - class BaseResource(object): + """A BaseResource object.""" _strs = [] _ints = [] _dates = [] _bools = [] - _dicts = [] _map = {} - _pks = [] + _writeable = [] + _modified = [] + def __init__(self): self._bootstrap() - self._h = None super(BaseResource, self).__init__() - def __repr__(self): - return "".format(self._id) + + def __dir__(self): + d = self.__dict__.copy() + + try: + del d['_gh'] + except KeyError: + pass + + return d.keys() + def _bootstrap(self): """Bootstraps the model object based on configured values.""" - for attr in self._keys(): + for attr in (self._strs + self._ints + self._dates + self._bools + self._map.keys()): setattr(self, attr, None) - def _keys(self): - return self._strs + self._ints + self._dates + self._bools + self._map.keys() - @property - def _id(self): - try: - return getattr(self, self._pks[0]) - except IndexError: - return None - - @property - def _ids(self): - """The list of primary keys to validate against.""" - for pk in self._pks: - yield getattr(self, pk) + @classmethod + def new_from_dict(cls, d, gh=None): + + return to_python( + obj=cls(), in_dict=d, + str_keys = cls._strs, + int_keys = cls._ints, + date_keys = cls._dates, + bool_keys = cls._bools, + object_map = cls._map, + _gh = gh + ) - for pk in self._pks: + def update(self): + pass - try: - yield str(getattr(self, pk)) - except ValueError: - pass + def setattr(self, k, v): + # TODO: when writable key changed, + pass - def dict(self): - d = dict() - for k in self.keys(): - d[k] = self.__dict__.get(k) +class Plan(BaseResource): + """Github Plan object model.""" - return d + _strs = ['name'] + _ints = ['space', 'collaborators', 'private_repos'] - @classmethod - def new_from_dict(cls, d, h=None, **kwargs): - - d = to_python( - obj=cls(), - in_dict=d, - str_keys=cls._strs, - int_keys=cls._ints, - date_keys=cls._dates, - bool_keys=cls._bools, - dict_keys= cls._dicts, - object_map=cls._map, - _h = h - ) + def __repr__(self): + return ''.format(str(self.name)) - d.__dict__.update(kwargs) - return d +class User(BaseResource): + """Github User object model.""" -class App(BaseResource): - """Heroku App.""" + _strs = [ + 'login','gravatar_url', 'url', 'name', 'company', 'blog', 'location', + 'email', 'bio', 'html_url'] - _strs = ['name', 'create_status', 'stack', 'repo_migrate_status'] - _ints = ['id', 'slug_size', 'repo_size', 'dynos', 'workers'] + _ints = ['id', 'public_repos', 'public_gists', 'followers', 'following'] _dates = ['created_at',] - _pks = ['name', 'id'] - - def __init__(self): - super(App, self).__init__() + _bools = ['hireable', ] + # _map = {} + # _writeable = [] def __repr__(self): - return "".format(self.name) + return ''.format(self.login) - def new(self, name=None, stack='cedar'): - """Creates a new app.""" + def repos(self, limit=None): + return self._gh._get_resources(('users', self.login, 'repos'), Repo) - payload = {} + def orgs(self): + return self._gh._get_resources(('users', self.login, 'orgs'), Org) - if name: - payload['app[name]'] = name - if stack: - payload['app[stack]'] = stack +class Organization(User): - r = self._h._http_resource( - method='POST', - resource=('apps',), - data=payload - ) + _bools = [] - name = json.loads(r.content).get('name') - return self._h.apps.get(name) + def __repr__(self): + return ''.format(self.login) - @property - def addons(self): - return self._h._get_resources( - resource=('apps', self.name, 'addons'), - obj=Addon, app=self - ) + def repos(self, repo_type="all"): + repos = self._gh._get_resources(('orgs', self.login, 'repos'), Repo, + type=repo_type) + return repos - @property - def collaborators(self): - """The collaborators for this app.""" - return self._h._get_resources( - resource=('apps', self.name, 'collaborators'), - obj=Collaborator, app=self - ) - @property - def domains(self): - """The domains for this app.""" - return self._h._get_resources( - resource=('apps', self.name, 'domains'), - obj=Domain, app=self - ) +class CurrentUser(User): + """Github Current User object model.""" - @property - def releases(self): - """The releases for this app.""" - return self._h._get_resources( - resource=('apps', self.name, 'releases'), - obj=Release, app=self - ) + _ints = [ + 'id', 'public_repos', 'public_gists', 'followers', 'following', + 'total_private_repos', 'owned_private_repos', 'private_gists', + 'disk_usage', 'collaborators'] + _map = {'plan': Plan} + _writeable = ['name', 'email', 'blog', 'company', 'location', 'hireable', 'bio'] - @property - def processes(self): - """The proccesses for this app.""" - return self._h._get_resources( - resource=('apps', self.name, 'ps'), - obj=Process, app=self, map=ProcessListResource - ) + def __repr__(self): + return ''.format(self.login) - @property - def config(self): - """The envs for this app.""" + def repos(self, limit=None): + return self._gh._get_resources(('user', 'repos'), Repo) - return self._h._get_resource( - resource=('apps', self.name, 'config_vars'), - obj=ConfigVars, app=self - ) + def orgs(self): + return self._gh._get_resources(('user', 'orgs'), Org) - @property - def info(self): - """Returns current info for this app.""" - return self._h._get_resource( - resource=('apps', self.name), - obj=App, - ) +class Org(BaseResource): + """Github Organization object model.""" - def rollback(self, release): - """Rolls back the release to the given version.""" - r = self._h._http_resource( - method='POST', - resource=('apps', self.name, 'releases'), - data={'rollback': release} - ) - return self.releases[-1] + _strs = [ + 'login', 'url', 'avatar_url', 'name', 'company', 'blog', 'location', 'email' + 'html_url', 'type'] + _ints = [ + 'id', 'public_repos', 'public_gists', 'followers', 'following', + 'total_private_repos', 'owned_private_repos', 'private_gists', 'disk_usage', + 'collaborators'] + _dates = ['created_at'] + _map = {'plan': Plan} + _writable = ['billing_email', 'blog', 'company', 'email', 'location', 'name'] + def __repr__(self): + return ''.format(self.login) - def rename(self, name): - """Renames app to given name.""" + def repos(self, limit=None): + return self._gh._get_resources(('orgs', self.login, 'repos'), Repo) - r = self._h._http_resource( - method='PUT', - resource=('apps', self.name), - data={'app[name]': name} - ) - return r.ok - def transfer(self, user): - """Transfers app to given username's account.""" +class Repo(BaseResource): + _strs = [ + 'url', 'html_url', 'clone_url', 'git_url', 'ssh_url', 'svn_url', + 'name', 'description', 'homepage', 'language', 'master_branch'] + _bools = ['private', 'fork'] + _ints = ['forks', 'watchers', 'size',] + _dates = ['pushed_at', 'created_at'] + _map = {'owner': User} - r = self._h._http_resource( - method='PUT', - resource=('apps', self.name), - data={'app[transfer_owner]': user} - ) - return r.ok + def __repr__(self): + return ''.format(self.owner.login, self.name) + + def issues(self, **params): + return self._gh._get_resources(('repos', self.owner.login, + self.name, 'issues'), Issue, **params) + + def milestones(self, **params): + return self._gh._get_resources(('repos', self.owner.login, + self.name, 'milestones'), Milestone, **params) + + def downloads(self, **params): + return self._gh._get_resources(('repos', self.owner.login, + self.name, 'downloads'), Download, **params) + + def create_download(self, filepath, **params): + m = magic.open(magic.MAGIC_MIME) + m.load() + mime_type = m.file(filepath) + data = {'size': os.path.getsize(filepath), 'name': filepath.split('/')[-1], 'content_type': mime_type} + + dlressource = self._gh._post_resource(('repos', self.owner.login, + self.name, 'downloads'), + DownloadRessource, + data=self._gh._resource_serialize(data), + **params) + form = {} + form['key'] = dlressource.path + form['acl'] = dlressource.acl + form['success_action_status'] = '201' + form['Filename'] = dlressource.name + form['AWSAccessKeyId'] = dlressource.accesskeyid + form['Policy'] = dlressource.policy + form['Signature'] = dlressource.signature + form['Content-Type'] = dlressource.mime_type + + myfile = open(filepath) + + files = {'file' : myfile} + + r = requests.post(settings.github_upload_file_url, data=form, files=files, **params) + return dlressource; + + +class IssueLabel(BaseResource): + _strs = ['url', 'name', 'color'] - def maintenance(self, on=True): - """Toggles maintenance mode.""" + def __repr__(self): + return '