diff --git a/.gitignore b/.gitignore index fa80f46..f0c73ea 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,9 @@ -*.py? +*.py[co] *.swp +*.DS_STORE +*.rope* +MANIFEST +docs/_build +dist/ +build/ +*egg-info diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..44333a8 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,7 @@ +language: python +python: + - "2.6" + - "2.7" +install: + - pip install -r requirements/dev.txt --use-mirrors +script: nosetests diff --git a/AUTHORS b/AUTHORS deleted file mode 100644 index 29bea31..0000000 --- a/AUTHORS +++ /dev/null @@ -1,16 +0,0 @@ -python-github3 is written and maintained by Kenneth Reitz and -various contributors: - -Development Lead -```````````````` - -- Kenneth Reitz -- David Medina - - -Patches and Suggestions -``````````````````````` - -- Mahdi Yusuf -- Rok Garbas -- Antti Kaihola diff --git a/AUTHORS.rst b/AUTHORS.rst new file mode 100644 index 0000000..9a5f5e1 --- /dev/null +++ b/AUTHORS.rst @@ -0,0 +1,35 @@ +python-github3 is written and maintained by **David Medina** and + +various contributors: + +Development Lead +================= + +- David Medina + +Forked and redesign from Kenneth Reitz's repo +---------------------------------------------- + +Forked from https://github.com/kennethreitz/python-github3 + +Kenneth Reitz is also the author of the awesome +`requests `_ library, which +`python-github3` requires. + +Patches and Suggestions +......................... + +- Mahdi Yusuf +- Rok Garbas +- Antti Kaihola +- Francisco Marcos +- Nathaniel Williams +- Alejandro Gómez +- Stefano Rivera +- Ouertani Mohammed Amine +- Conor Branagan +- Ralph Bean +- Jason A. Donenfeld +- Brad Montgomery +- Thomas Whitton +- Jonas Baumann diff --git a/HACKING b/HACKING deleted file mode 100644 index 018f9b7..0000000 --- a/HACKING +++ /dev/null @@ -1,14 +0,0 @@ -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 8a9ee98..8100337 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2011 Kenneth Reitz. +Copyright (c) 2012 David Medina Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above @@ -10,4 +10,4 @@ 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 +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/MANIFEST.in b/MANIFEST.in index 4c7a2bc..072beda 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1 +1,4 @@ -include README.rst LICENSE AUTHORS \ No newline at end of file +include AUTHORS.rst +include README.rst +include LICENSE +include requirements/base.txt diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..f2b3997 --- /dev/null +++ b/Makefile @@ -0,0 +1,2 @@ +init: + pip install -r requirements/dev.txt diff --git a/NOTICE b/NOTICE deleted file mode 100644 index 0a0d3fe..0000000 --- a/NOTICE +++ /dev/null @@ -1,65 +0,0 @@ -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.md b/README.md deleted file mode 100644 index 334b975..0000000 --- a/README.md +++ /dev/null @@ -1,63 +0,0 @@ -Fork -==== -Refactor and complete api wrapper. Intensive work in progress - -Use with auth user ------------------- - - from github3.api import Github - - gh = Github('user', 'password') - - users_handler = gh.users - for repo in users_handler.get_repos(): - print repo - - gists_handler = gh.gists - gists_handler.create_gist( - u'Description', - files={'file1.txt': {'content': u'Content of first file'}}) - -Installation ------------- - -To install Github3, simply: - - $ pip -e git+https://copitux@github.com/copitux/python-github3#egg=python-github3 - -License -------- - -ISC License. - - Copyright (c) 2011, Kenneth Reitz - - 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 -------- - -- Unittests -- Handlers -- Sphinx Documentation -- Examples -- OAuth Last (how?) diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..dc80034 --- /dev/null +++ b/README.rst @@ -0,0 +1,70 @@ +.. image:: https://secure.travis-ci.org/copitux/python-github3.png + +Pygithub3 +========== + +Pygithub3 is a wrapper to the **Github API v3**, +written in Python. + +It has been developed with extensibility in mind, because the ``API`` is in a +beta state, trying to achieve a very loosly coupled software. + +It should be very easy to extend to support new ``requests`` and ``resources``, +because each of them are managed by itself. + +`Pygithub3 docs `_ + +`Github API v3 docs `_ + +Fast install +------------- +:: + + pip install pygithub3 + +Fast example +------------- +:: + + from pygithub3 import Github + + gh = Github(login='copitux', password='password') + + copitux = gh.users.get() + kennethreitz = gh.users.get('kennethreitz') + + copitux_repos = gh.repos.list().all() + kennethreitz_repos = gh.repos.list('kennethreitz').all() + +Achievements +------------- + +- The core +- `Users service `_ +- `Repos service `_ +- `Gists service `_ +- `Git Data service `_ +- `Pull requests service `_ +- `Orgs service `_ +- `Issues service `_ +- `Events service `_ + +TODO +----- + +- Oauth authorization API (service?) +- Proxy methods into resources (e.g copitux.followers) + +Contribute +----------- + +1. Fork the `repository `_ +2. Write a test to cover new feature or to reproduce bug +3. Code with `pep8 `_ rules +4. Add yourself to ``AUTHORS`` +5. Pull request it to ``develop`` branch + +Tests +----- + +Run ``make init`` to install test requirements and ``nosetests`` to run tests. diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..5e804dc --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,153 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = _build + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + +clean: + -rm -rf $(BUILDDIR)/* + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/pygithub3.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/pygithub3.qhc" + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/pygithub3" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/pygithub3" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..c10f5c0 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,248 @@ +# -*- coding: utf-8 -*- +# +# pygithub3 documentation build configuration file, created by +# sphinx-quickstart on Sun Feb 26 22:08:00 2012. +# +# This file is execfile()d with the current directory set to its containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys, os + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.append(os.path.abspath('../')) +#sys.path.append(os.path.abspath('_themes')) + +# -- General configuration ----------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be extensions +# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx'] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +source_encoding = 'utf-8' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'pygithub3' +copyright = u'2012, David Medina' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +try: + from pygithub3 import __version__ +except: + __version__ = 'dev' +version = __version__ +# The full version, including alpha/beta/rc tags. +release = __version__ + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' +highlight_language = 'python' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + + +# -- Options for HTML output --------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +#html_theme = 'werkzeug' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +html_theme_path = ['_themes'] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'pygithub3doc' + + +# -- Options for LaTeX output -------------------------------------------------- + +latex_elements = { +# The paper size ('letterpaper' or 'a4paper'). +#'papersize': 'letterpaper', + +# The font size ('10pt', '11pt' or '12pt'). +#'pointsize': '10pt', + +# Additional stuff for the LaTeX preamble. +#'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass [howto/manual]). +latex_documents = [ + ('index', 'pygithub3.tex', u'pygithub3 Documentation', + u'David Medina', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output -------------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'pygithub3', u'pygithub3 Documentation', + [u'David Medina'], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------------ + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'pygithub3', u'pygithub3 Documentation', + u'David Medina', 'pygithub3', 'One line description of project.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' diff --git a/docs/events.rst b/docs/events.rst new file mode 100644 index 0000000..49d0de5 --- /dev/null +++ b/docs/events.rst @@ -0,0 +1,150 @@ +.. _Events service: + +Events service +============== + +This service exposes the `Events API`_. Much of this API is read-only, and while +pagination is supported, there is a fixed page size of 30 with a limit of 10 +page requests. + +Many events have an `actor` which denotes the user that performed an event. +Additionally, there may be `org` or `repo` attributes for events related to +Organizations and Repos. Finally, each event object contains a `payload` +attribute containing more detailed information about the event. + +.. _public events: + +Public Events +------------- +Yields the most recent public events from Github. + +:: + + from pygithub3 import Github + + gh = Github() + + events = gh.events.list().all() + print events[0].payload + +Event +....... + +.. autoclass:: pygithub3.services.events.Event + :members: + + .. attribute:: issues + + :ref:`Issues events ` + + .. attribute:: networks + + :ref:`Events network service` + + .. attribute:: orgs + + :ref:`Events org service` + + .. attribute:: repos + + :ref:`Events repo service` + + .. attribute:: users + + :ref:`Events user service` + +.. _repository events: + +Repo Events +----------- + +These are events for a specific repo, including issue and network events. The +Issues events are proxied to the :ref:`Issues service`. + +:: + + events = gh.events.repos.list(user="copitux", repo="python-github3") + for e in events.next(): + print("{t}".format(t=e.type)) + + # Get the issue Events + events = gh.events.issues.list_by_repo(user="copitux", + repo="python-github3") + + # Get the Public Events for a Repo's Network + events = gh.events.networks.list(user="copitux", repo="python-github3") + +.. _Events network service: + +Network +....... + +.. autoclass:: pygithub3.services.events.networks.Network + :members: + + +.. _Events repo service: + +Repo +........ + +.. autoclass:: pygithub3.services.events.repos.Repo + :members: + + +.. _organziation events: + +Organization Events +------------------- + +These are the public events for an Organization + +:: + + events = gh.events.orgs.list(org="Acme") + +You may also get a user's feed of events for an Organization, but you *must* be +authenticated as the provided user, and you must be a member of the given +organization. + +:: + + events = gh.events.users.orgs(user="copitux", org="acme") + +.. _Events org service: + +Org +........ + +.. autoclass:: pygithub3.services.events.orgs.Org + :members: + +.. _user events: + +User Events +----------- + +You can retrieve the public events performed by a user and the public events +that a user receives. If you're authenticated, you may also receive private +events. + +:: + + received_events = gh.events.users.list_received_public(user="copitux") + performed_events = gh.events.users.list_performed_public(user="copitux") + +If authenticated as `copitux`, you could get private events with the +following, otherwise you'll just get the public events as above: + +:: + + received_events = gh.events.users.list_received(user="copitux") + performed_events = gh.events.users.list_performed(user="copitux") + +.. _Events user service: + +User +........ + +.. autoclass:: pygithub3.services.events.users.User + :members: diff --git a/docs/gists.rst b/docs/gists.rst new file mode 100644 index 0000000..3b2915f --- /dev/null +++ b/docs/gists.rst @@ -0,0 +1,37 @@ +.. _Gists service: + +Gists services +=============== + +**Fast sample**:: + + from pygithub3 import Github + + auth = dict(login='octocat', password='pass') + gh = Github(**auth) + + octocat_gists = gh.gists.list() + the_first_gist = gh.gists.get(1) + + the_first_gist_comments = gh.gists.comments.list(1) + +Gist +----- + +.. autoclass:: pygithub3.services.gists.Gist + :members: + + .. attribute:: comments + + :ref:`Comments service` + +.. _Comments service: + +Comments +---------- + +.. autoclass:: pygithub3.services.gists.Comments + :members: + +.. _github gists doc: http://developer.github.com/v3/gists +.. _github comments doc: http://developer.github.com/v3/gists/comments diff --git a/docs/git_data.rst b/docs/git_data.rst new file mode 100644 index 0000000..9045841 --- /dev/null +++ b/docs/git_data.rst @@ -0,0 +1,91 @@ +.. _Git Data service: + +Git Data services +================= + +**Example**:: + + from pygithub3 import Github + + gh = Github(user='someone', repo='some_repo') + + a_blob = gh.git_data.blobs.get('a long sha') + + dev_branch = gh.git_data.references.get('heads/add_a_thing') + + +GitData +------- + +.. autoclass:: pygithub3.services.git_data.GitData + :members: + + .. attribute:: blobs + + :ref:`Blobs service` + + .. attribute:: commits + + :ref:`Gitdata commits service` + + .. attribute:: references + + :ref:`References service` + + .. attribute:: tags + + :ref:`Tags service` + + .. attribute:: trees + + :ref:`Trees service` + + +.. _Blobs service: + +Blobs +----- + +.. autoclass:: pygithub3.services.git_data.Blobs + :members: + + +.. _Gitdata commits service: + +Commits +------- + +.. autoclass:: pygithub3.services.git_data.Commits + :members: + + +.. _References service: + +References +---------- + +.. autoclass:: pygithub3.services.git_data.References + :members: + + +.. _Tags service: + +Tags +---- + +.. autoclass:: pygithub3.services.git_data.Tags + :members: + + +.. _Trees service: + +Trees +----- + +.. autoclass:: pygithub3.services.git_data.Trees + :members: + +.. _github commits doc: http://developer.github.com/v3/git/commits +.. _github refs doc: http://developer.github.com/v3/git/refs +.. _github tags doc: http://developer.github.com/v3/git/tags +.. _github trees doc: http://developer.github.com/v3/git/trees diff --git a/docs/github.rst b/docs/github.rst new file mode 100644 index 0000000..ae4941b --- /dev/null +++ b/docs/github.rst @@ -0,0 +1,7 @@ +Github +======== + +This is the main entrance of **pygithub3** + +.. autoclass:: pygithub3.Github + :members: diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..71f377c --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,44 @@ +Documentation Overview +======================= + +**pygithub3** is a Github APIv3 python wrapper. + +You can consume the API with several :doc:`services` (users, repos...) like +you see in `Github API v3 documentation`_. + +When you do an API request, **pygithub3** map the result into :doc:`resources` +which can do its own related requests in future releases. + +Fast sample +----------- +:: + + from pygithub3 import Github + + gh = Github(login='octocat', password='password') + + octocat = gh.users.get() # Auth required + copitux = gh.users.get('copitux') + # copitux = + + octocat_followers = gh.users.followers.list().all() + copitux_followers = gh.users.followers.list('copitux').all() + # copitux_followers = [, , ...] + + +Others +------- + +You must apologize my English level. I'm trying to do my best + + +.. toctree:: + :maxdepth: 3 + + installation + github + services + result + resources + +.. _Github API v3 documentation: http://developer.github.com diff --git a/docs/installation.rst b/docs/installation.rst new file mode 100644 index 0000000..0601a7e --- /dev/null +++ b/docs/installation.rst @@ -0,0 +1,35 @@ +Installation +============= +:: + + pip install pygithub3 + + or + + easy_install pygithub3 + + +Dependencies +--------------- + +Required +......... + +This library depends only on the `requests`_ module. + +If you install ``pygithub3`` with ``pip`` all is done. This is the best option. + +Optional +......... + +The test suite uses `nose`_, `mock`_, and `unittest2`_ (python 2.6). Compiling +the documentation requires `sphinx`_. + +Install all of these by running ``pip install -r test_requirements.txt``. Then +just run ``nosetests`` to run the tests. + +.. _requests: http://docs.python-requests.org/en/v0.10.6/index.html +.. _nose: http://readthedocs.org/docs/nose/en/latest +.. _mock: http://pypi.python.org/pypi/mock +.. _unittest2: http://pypi.python.org/pypi/unittest2 +.. _sphinx: http://sphinx.pocoo.org/ diff --git a/docs/issues.rst b/docs/issues.rst new file mode 100644 index 0000000..3c35eb8 --- /dev/null +++ b/docs/issues.rst @@ -0,0 +1,74 @@ +.. _Issues service: + +Issues services +=============== + +**Fast sample**:: + + from pygithub3 import Github + + auth = dict(login='octocat', password='pass') + gh = Github(**auth) + + octocat_issues = gh.issues.list() + octocat_repo_issues = gh.issues.list_by_repo('octocat', 'Hello-World') + +Issues +------ + +.. autoclass:: pygithub3.services.issues.Issue + :members: + + .. attribute:: comments + + :ref:`Issues comments service` + + .. attribute:: events + + :ref:`Issues events service` + + .. attribute:: labels + + :ref:`Labels service` + + .. attribute:: milestones + + :ref:`Milestones service` + +.. _Issues comments service: + +Comments +-------- + +.. autoclass:: pygithub3.services.issues.Comments + :members: + +.. _Issues events service: + +Events +------ + +.. autoclass:: pygithub3.services.issues.Events + :members: + +.. _Labels service: + +Labels +------ + +.. autoclass:: pygithub3.services.issues.Labels + :members: + +.. _Milestones service: + +Milestones +---------- + +.. autoclass:: pygithub3.services.issues.Milestones + :members: + +.. _github issues doc: http://developer.github.com/v3/issues +.. _github comments doc: http://developer.github.com/v3/issues/comments +.. _github events doc: http://developer.github.com/v3/issues/events +.. _github labels doc: http://developer.github.com/v3/issues/labels +.. _github milestones doc: http://developer.github.com/v3/issues/milestones diff --git a/docs/orgs.rst b/docs/orgs.rst new file mode 100644 index 0000000..96e7a73 --- /dev/null +++ b/docs/orgs.rst @@ -0,0 +1,46 @@ +.. _Orgs service: + +Orgs services +============== + +**Fast sample**:: + + from pygithub3 import Github + + gh = Github(token='abc123') + + auth_orgs = gh.orgs.list().all() + members = gh.orgs.members.list('github') + +Org +------ + +.. autoclass:: pygithub3.services.orgs.Org + :members: + + .. attribute:: members + + :ref:`Members service` + + .. attribute:: teams + + :ref:`Teams service` + +.. _Members service: + +Members +--------- + +.. autoclass:: pygithub3.services.orgs.members.Members + :members: + +.. _Teams service: + +Teams +------- + +.. autoclass:: pygithub3.services.orgs.teams.Teams + :members: + +.. _github orgs doc: http://developer.github.com/v3/orgs +.. _github orgs teams doc: http://developer.github.com/v3/orgs/teams diff --git a/docs/pull_requests.rst b/docs/pull_requests.rst new file mode 100644 index 0000000..09313eb --- /dev/null +++ b/docs/pull_requests.rst @@ -0,0 +1,35 @@ +.. _Pull Requests service: + +Pull Requests service +===================== + +**Example**:: + + from pygithub3 import Github + + gh = Github(user='octocat', repo='sample') + + pull_requests = gh.pull_requests.list().all() + pull_request_commits = gh.pull_requests.list_commits(2512).all() + +Pull Requests +------------- + +.. autoclass:: pygithub3.services.pull_requests.PullRequests + :members: + + .. attribute:: comments + + :ref:`Pull Request Comments service` + + +.. _Pull Request Comments service: + +Pull Request Comments +--------------------- + +.. autoclass:: pygithub3.services.pull_requests.Comments + :members: + +.. _github pullrequests doc: http://developer.github.com/v3/pulls +.. _github pullrequests comments doc: http://developer.github.com/v3/pulls/comments diff --git a/docs/repos.rst b/docs/repos.rst new file mode 100644 index 0000000..9832f3d --- /dev/null +++ b/docs/repos.rst @@ -0,0 +1,161 @@ +.. _Repos service: + +Repos services +=================== + +**Fast sample**:: + + from pygithub3 import Github + + gh = Github() + + django_compressor = gh.repos.get(user='jezdez', repo='django_compressor') + requests_collaborators = gh.repos.collaborators(user='kennethreitz', + repo='requests') + +.. _config precedence: + +Config precedence +------------------ + +Some request always need ``user`` and ``repo`` parameters, both, to identify +a `repository`. Because there are a lot of requests which need that parameters, +you can :ref:`config each service` with ``user`` and ``repo`` globally. + +So several requests follow a simple precedence +``user_in_arg > user_in_config | repo_in_arg > repo_in_config`` + +You can see it better with an example: :: + + from pygithub3 import Github + + gh = Github(user='octocat', repo='oct_repo') + oct_repo = gh.repos.get() + another_repo_from_octocat = gh.repos.get(repo='another_repo') + + django_compressor = gh.repos.get(user='jezdez', repo='django_compressor') + +.. note:: + + Remember that each service is isolated from the rest :: + + # continue example... + gh.repos.commits.set_user('copitux') + oct_repo = gh.repos.get() + oct_repo_collaborators = gh.repos.collaborators.list().all() + + # Fail because copitux/oct_repo doesn't exist + gh.repos.commits.list_comments() + +Repo +------- + +.. autoclass:: pygithub3.services.repos.Repo + :members: + + .. attribute:: collaborators + + :ref:`Collaborators service` + + .. attribute:: commits + + :ref:`Commits service` + + .. attribute:: downloads + + :ref:`Downloads service` + + .. attribute:: forks + + :ref:`Forks service` + + .. attribute:: keys + + :ref:`RepoKeys service` + + .. attribute:: watchers + + :ref:`Watchers service` + +.. _Collaborators service: + +Collaborators +-------------- + +.. autoclass:: pygithub3.services.repos.Collaborators + :members: + +.. _Commits service: + +Commits +---------- + +.. autoclass:: pygithub3.services.repos.Commits + :members: + +.. _Downloads service: + +Downloads +------------ + +.. autoclass:: pygithub3.services.repos.Downloads + :members: + + +.. _Forks service: + +Forks +--------- + +.. autoclass:: pygithub3.services.repos.Forks + :members: + + +.. _RepoKeys service: + +Keys +---------- + +.. autoclass:: pygithub3.services.repos.Keys + :members: + + +.. _Watchers service: + +Watchers +--------- + +.. autoclass:: pygithub3.services.repos.Watchers + :members: + +.. _Stargazers service: + +Stargazers +--------- + +.. autoclass:: pygithub3.services.repos.Stargazers + :members: + +.. _Hooks service: + +Hooks +--------- + +.. autoclass:: pygithub3.services.repos.Hooks + :members: + +Statuses +--------- + +.. autoclass:: pygithub3.services.repos.Statuses + :members: + +.. _github repos doc: http://developer.github.com/v3/repos +.. _github collaborators doc: http://developer.github.com/v3/repos/collaborators +.. _github commits doc: http://developer.github.com/v3/repos/commits +.. _github downloads doc: http://developer.github.com/v3/repos/downloads +.. _github forks doc: http://developer.github.com/v3/repos/forks +.. _github keys doc: http://developer.github.com/v3/repos/keys +.. _github watching doc: http://developer.github.com/v3/repos/watching +.. _github hooks doc: http://developer.github.com/v3/repos/hooks +.. _github statuses doc: http://developer.github.com/v3/repos/statuses diff --git a/docs/resources.rst b/docs/resources.rst new file mode 100644 index 0000000..24189e2 --- /dev/null +++ b/docs/resources.rst @@ -0,0 +1,2 @@ +Resources +========== diff --git a/docs/result.rst b/docs/result.rst new file mode 100644 index 0000000..182ed5c --- /dev/null +++ b/docs/result.rst @@ -0,0 +1,18 @@ + +Result +======= + +Some requests returns multiple :doc:`resources`, for that reason the +``Github API`` paginate it and **pygithub3** too + +Smart Result +-------------- + +.. autoclass:: pygithub3.core.result.smart.Result + :members: + +Normal Result +--------------- + +.. autoclass:: pygithub3.core.result.normal.Result + diff --git a/docs/services.rst b/docs/services.rst new file mode 100644 index 0000000..998fb7e --- /dev/null +++ b/docs/services.rst @@ -0,0 +1,81 @@ +Services +========== + +:doc:`github` class is a glue to all of them and the recommended option to +start + +Overview +---------- + +You can access to the API requests through the different services. + +If you take a look at +`github API v3 documentation `_, you'll see a +few sections in the sidebar. + +**pygithub3** has one service per each section of request-related + +For example: :: + + repos => services.repos.repo + collaborators => services.repos.collaborators + commits => services.repos.commits + .... + +Each service has the functions to throw the API requests and **is isolated +from the rest**. + +.. _config each service: + +Config each service +---------------------- + +Each service can be configurated with some variables (behind the scenes, each +service has her client which is configurated with this variables). + +.. note:: + + Also you can configure :doc:`github` as a service + +.. autoclass:: pygithub3.services.base.Service + :members: + +.. _mimetypes-section: + +MimeTypes +---------- + +Some services supports `mimetypes`_ + +With them the :doc:`resources` will have ``body``, ``body_text``, ``body_html`` +attributes or all of them. + +.. autoclass:: pygithub3.services.base.MimeTypeMixin + :members: + +**Fast example**:: + + from pygithub3 import Github + + gh = Github() + + gh.gists.comments.set_html() + comment = gh.gists.comments.list(1).all()[0] + print comment.body, comment.body_text, comment.body_html + +List of services +------------------- + +.. toctree:: + :maxdepth: 2 + + users + repos + gists + git_data + pull_requests + orgs + issues + events + +.. _mimetypes: http://developer.github.com/v3/mime diff --git a/docs/users.rst b/docs/users.rst new file mode 100644 index 0000000..139d726 --- /dev/null +++ b/docs/users.rst @@ -0,0 +1,60 @@ +.. _Users service: + +Users services +=============== + +**Fast sample**:: + + from pygithub3 import Github + + auth = dict(login='octocat', password='pass') + gh = Github(**auth) + + # Get copitux user + gh.users.get('copitux') + + # Get copitux's followers + gh.users.followers.list('copitux') + + # Get octocat's emails + gh.users.emails.list() + +User +-------- + +.. autoclass:: pygithub3.services.users.User + :members: + + .. attribute:: emails + + :ref:`Emails service` + .. attribute:: keys + + :ref:`Keys service` + .. attribute:: followers + + :ref:`Followers service` + +.. _Emails service: + +Emails +-------- + +.. autoclass:: pygithub3.services.users.Emails + :members: + +.. _Keys service: + +Keys +------ + +.. autoclass:: pygithub3.services.users.Keys + :members: + +.. _Followers service: + +Followers +----------- + +.. autoclass:: pygithub3.services.users.Followers + :members: diff --git a/github3/__init__.py b/github3/__init__.py deleted file mode 100644 index 40a96af..0000000 --- a/github3/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/github3/api.py b/github3/api.py deleted file mode 100644 index d8d2ffb..0000000 --- a/github3/api.py +++ /dev/null @@ -1,158 +0,0 @@ -#!/usr/bin/env python -# -*- encoding: utf-8 -*- - -import requests -import json -from errors import GithubError -from handlers import users, gists - -RESOURCES_PER_PAGE = 100 - - -#TODO: refactor: loads json in request editing Response object -class GithubCore(object): - """ - Wrapper to github api requests - - Methods: get, head, post, patch, put, delete - """ - - requests_remaining = None - base_url = 'https://api.github.com/' - - def __init__(self): - """ - Init `requests.session` - Init JSON parser - """ - self.session = requests.session() - self.session.params = {'per_page': RESOURCES_PER_PAGE} - self._parser = json - - def get(self, request, paginate=False, **kwargs): - """ - GET request - - :param paginate: Boolean to return link header to paginate - """ - response = self._request('GET', request, **kwargs) - content = self._parser.loads(response.content) - if paginate: - return response.headers.get('link'), content - else: - return content - - def head(self, request, **kwargs): - """ HEAD request """ - return self._request('HEAD', request, **kwargs) - - def post(self, request, data=None, **kwargs): - """ - POST request - - :param data: raw python object to send - """ - kwargs['data'] = self._parser.dumps(data) - response = self._request('POST', request, **kwargs) - assert response.status_code == 201 - return self._parser.loads(response.content) - - def patch(self, request, data=None, **kwargs): - """ - PATCH request - - :param data: raw python object to send - """ - kwargs['data'] = self._parser.dumps(data) - response = self._request('PATCH', request, **kwargs) - assert response.status_code == 200 - return self._parser.loads(response.content) - - def put(self, request, **kwargs): - """ PUT request """ - - response = self._request('PUT', request, - headers={'Content-length': '0'}, **kwargs) - assert response.status_code == 204 - return response - - def delete(self, request, **kwargs): - """ DELETE request """ - - data = kwargs.get('data') - if data: - kwargs['data'] = self._parser.dumps(data) - response = self._request('DELETE', request, **kwargs) - assert response.status_code == 204 - return response - - def _parse_args(self, request_args): - """ - Arg's parser to `_request` method - - Put extra request_args in params - """ - request_core = ( - 'params', 'data', 'headers', 'cookies', 'files', 'auth', 'tiemout', - 'allow_redirects', 'proxies', 'return_response', 'config') - request_params = request_args.get('params') - extra_params = {} - for k, v in request_args.items(): - if k in request_core: - continue - extra_params.update({k: v}) - del request_args[k] - if request_params and getattr(request_params, 'update'): - request_args['params'].update(extra_params) - elif extra_params: - request_args['params'] = extra_params - - return request_args - - def _request(self, verb, request, **kwargs): - """ - Http request wrapper - - :param verb: Http method - :param request : Url query request - :param kwargs: Keyword args to request - """ - request = self.base_url + request - self._parse_args(kwargs) - response = self.session.request(verb, request, **kwargs) - self.requests_remaining = response.headers.get( - 'x-ratelimit-remaining', -1) - error = GithubError(response) - error.process() - - return response - - -class Github(GithubCore): - """ Library enter """ - - def __init__(self, *args): - super(Github, self).__init__() - self.authenticated = False - auth = len(args) - if auth == 2: # Basic auth - self.session.auth = tuple(map(str, args)) - self.authenticated = True - elif auth == 1: # Token oauth - raise NotImplementedError - elif auth > 2: - raise TypeError("user, password or token") - - @property - def users(self): - if self.authenticated: - return users.AuthUser(self) - else: - return users.User(self) - - @property - def gists(self): - if self.authenticated: - return gists.AuthGist(self) - else: - return gists.Gist(self) diff --git a/github3/converters.py b/github3/converters.py deleted file mode 100644 index 9f975be..0000000 --- a/github3/converters.py +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/env python -# -*- encoding: utf-8 -*- - -from .core import Converter - - -class Rawlizer(Converter): - """ Raw converter """ - - def inject(self, fake): - pass - - def loads(self, raw_resource): - return raw_resource - - def dumps(self): - pass - - -class Json(Converter): - """ Json converter """ - - def __init__(self): - import json - self.parser = json - - def inject(self, fake): - pass - - def loads(self, raw_resource): - return self.parser.dumps(raw_resource) - - def dumps(self): - pass - - -class Modelizer(Converter): - """ Own model converter """ - - def __init__(self, model=None): - if model: - self.inject(model) - - def _parse_date(self, string_date): - from datetime import datetime - try: - date = datetime.strptime(string_date, '%Y-%m-%dT%H:%M:%SZ') - except TypeError: - date = None - - return date - - def inject(self, model): - self.model = model - - def _parse_map(self, model, raw_resource): - if hasattr(raw_resource, 'items'): - return Modelizer(model).loads(raw_resource) - - def _parse_collection_map(self, model, raw_resources): - # Dict of resources (Ex: Gist file) - if hasattr(raw_resources, 'items'): - dict_map = {} - for key, raw_resource in raw_resources.items(): - dict_map[key] = Modelizer(model).loads(raw_resource) - return dict_map - # list of resources - elif hasattr(raw_resources, '__iter__'): - return [Modelizer(model).loads(raw_resource) - for raw_resource in raw_resources] - - def loads(self, raw_resource): - attrs = {} - if not getattr(self, 'model', False): - raise NotImplementedError("%s needs model attr" % - self.__class__.__name__) - idl = self.model.idl() - attrs.update( - {attr: raw_resource[attr] for attr in idl.get('strs', ()) - if attr in raw_resource}) - attrs.update( - {attr: raw_resource[attr] for attr in idl.get('ints', ()) - if attr in raw_resource}) - attrs.update( - {attr: self._parse_date(raw_resource[attr]) - for attr in idl.get('dates', ()) if attr in raw_resource}) - attrs.update( - {attr: raw_resource[attr] for attr in idl.get('bools', ()) - if attr in raw_resource}) - attrs.update( - {attr: self._parse_map(model, raw_resource[attr]) - for attr, model in idl.get('maps', {}).items() - if attr in raw_resource}) - attrs.update( - {attr: self._parse_collection_map(model, raw_resource[attr]) - for attr, model in idl.get('collection_maps', {}).items() - if attr in raw_resource}) - - return self.model(attrs) - - def dumps(self, model): - # return JSON - pass diff --git a/github3/core.py b/github3/core.py deleted file mode 100644 index ab71943..0000000 --- a/github3/core.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env python -# -*- encoding: utf-8 -*- - - -class Paginate: - """ Paginate resource iterator - - :param resource: URL resource - :param requester: Bound method to request. See `GithubCore.get` - :param kwargs: Args to request (params) - """ - - def __init__(self, resource, requester, **kwargs): - self.resource = resource - self.requester = requester - self.kwargs = kwargs - self.page = 1 - - def _last_page(self, link): - """ Get and cached last page from link header """ - if not getattr(self, 'last', False): - from github3.packages.link_header import parse_link_value - from urlparse import urlparse, parse_qs - for link, rels in parse_link_value(link).items(): - if rels.get('rel') == 'last': - query = urlparse(link).query - self.last = int(parse_qs(query).get('page').pop()) - - return self.last - - def __iter__(self): - return self - - def initial(self): - """ - First request - Force requester to paginate returning link header - """ - link, content = self.requester(self.resource, paginate=True, - page=1, **self.kwargs) - self.last = self._last_page(link) if link else 1 - return content - - def next(self): - if self.page == 1: - content = self.initial() - self.page += 1 - return content - else: - if self.page > self.last: - raise StopIteration - else: - content = self.requester(self.resource, page=self.page, - **self.kwargs) - self.page += 1 - return content - - -class Converter(object): - """ Abstract converter class """ - - def loads(self): - raise NotImplementedError("%s needs define '%s' method" % - (self.__class__.__name__, 'loads')) - - def dumps(self): - raise NotImplementedError("%s needs define '%s' method" % - (self.__class__.__name__, 'dumps')) - - def inject(self): - raise NotImplementedError("%s needs define '%s' method" % - (self.__class__.__name__, 'inject')) diff --git a/github3/errors.py b/github3/errors.py deleted file mode 100644 index e96e2da..0000000 --- a/github3/errors.py +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env python -# -*- encoding: utf-8 -*- - -import json -import github3.exceptions as exceptions - - -class GithubError(object): - """ Handler for API errors """ - - def __init__(self, response): - self._parser = json - self.status_code = response.status_code - try: - self.debug = self._parser.loads(response.content) - except (ValueError, TypeError): - self.debug = {'message': response.content} - - def error_400(self): - return exceptions.BadRequest("400 - %s" % self.debug.get('message')) - - def error_401(self): - return exceptions.Unauthorized("401 - %s" % self.debug.get('message')) - - def error_404(self): - return exceptions.NotFound("404 - %s" % self.debug.get('message')) - - def error_422(self): - errors = self.debug.get('errors') - if errors: - errors = ['{resource}: {code} => {field}'.format(**error) - for error in errors] - return exceptions.UnprocessableEntity( - '422 - %s %s' % (self.debug.get('message'), errors)) - - def process(self): - raise_error = getattr(self, 'error_%s' % self.status_code, False) - if raise_error: - raise raise_error() diff --git a/github3/exceptions.py b/github3/exceptions.py deleted file mode 100644 index b9070d7..0000000 --- a/github3/exceptions.py +++ /dev/null @@ -1,13 +0,0 @@ -#!/usr/bin/env python -# -*- encoding: utf-8 -*- - -class BadRequest(Exception): - pass -class UnprocessableEntity(Exception): - pass -class NotFound(Exception): - pass -class Unauthorized(Exception): - pass -class UserIsAnonymous(Exception): - pass diff --git a/github3/handlers/__init__.py b/github3/handlers/__init__.py deleted file mode 100644 index 3ac5fdc..0000000 --- a/github3/handlers/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -import users -import gists diff --git a/github3/handlers/base.py b/github3/handlers/base.py deleted file mode 100644 index 565978f..0000000 --- a/github3/handlers/base.py +++ /dev/null @@ -1,125 +0,0 @@ -#!/usr/bin/env python -# -*- encoding: utf-8 -*- - -from github3.core import Paginate -from github3.converters import Modelizer - - -class MimeTypeMixin(object): - - VERSION = 'beta' - - def __init__(self): - self.mimetypes = set() - - def _parse_mime_type(self, type): - return 'application/vnd.github.%s.%s+json' % ( - self.VERSION, type) - - def add_raw(self): - self.mimetypes.add(self._parse_mime_type('raw')) - return self - - def add_text(self): - self.mimetypes.add(self._parse_mime_type('text')) - return self - - def add_html(self): - self.mimetypes.add(self._parse_mime_type('html')) - return self - - def add_full(self): - self.mimetypes.add(self._parse_mime_type('full')) - return self - - def mime_header(self): - if self.mimetypes: - return {'Accept': ', '.join(self.mimetypes)} - return None - - -class Handler(object): - """ Handler base. Requests to API and modelize responses """ - - def __init__(self, gh): - self._gh = gh - super(Handler, self).__init__() - - def _inject_handler(self, handler, prefix=''): - import inspect - for method, callback in inspect.getmembers(handler): - if method.startswith(prefix) and inspect.ismethod(callback): - setattr(self, method, callback) - - def _prefix_resource(self, resource): - prefix = getattr(self, 'prefix', '') - return '/'.join((prefix, str(resource))).strip('/') - - def _get_converter(self, kwargs={}): - converter = kwargs.pop( - 'converter', # 1. in kwargs - getattr(self, 'converter', # 2. in handler - Modelizer)) # 3. Default - - return converter() - - def _put(self, resource, **kwargs): - """ Put proxy request""" - - return self._bool(resource, method='put', **kwargs) - - def _delete(self, resource, **kwargs): - """ Delete proxy request""" - - return self._bool(resource, method='delete', **kwargs) - - def _bool(self, resource, **kwargs): - """ Handler request to boolean response """ - - from github3.exceptions import NotFound - resource = self._prefix_resource(resource) - try: - callback = getattr(self._gh, kwargs.get('method', ''), - self._gh.head) - response = callback(resource, **kwargs) - except NotFound: - return False - assert response.status_code == 204 - return True - - def _get_resources(self, resource, model=None, limit=None, **kwargs): - """ Hander request to multiple resources """ - - if limit: - limit = abs(limit) - resource = self._prefix_resource(resource) - converter = self._get_converter(kwargs) - counter = 1 - for page in Paginate(resource, self._gh.get, **kwargs): - for raw_resource in page: - counter += 1 - converter.inject(model) - yield converter.loads(raw_resource) - if limit and counter > limit: - break - else: - continue - break - - def _get_resource(self, resource, model=None, **kwargs): - """ Handler request to single resource """ - - resource = self._prefix_resource(resource) - converter = self._get_converter(kwargs) - raw_resource = self._gh.get(resource, **kwargs) - converter.inject(model) - return converter.loads(raw_resource) - - def _post_resource(self, resource, data, model=None, **kwargs): - """ Handler request to create a resource """ - - resource = self._prefix_resource(resource) - raw_resource = self._gh.post(resource, data=data) - converter = self._get_converter(kwargs) - converter.inject(model) - return converter.loads(raw_resource) diff --git a/github3/handlers/gists.py b/github3/handlers/gists.py deleted file mode 100644 index ed03c31..0000000 --- a/github3/handlers/gists.py +++ /dev/null @@ -1,145 +0,0 @@ -#!/usr/bin/env python -# -*- encoding: utf-8 -*- - -from .base import Handler, MimeTypeMixin -from github3 import models - - -class Gist(Handler, MimeTypeMixin): - """ Gist handler with public access """ - - prefix = 'gists' - - def __repr__(self): - return '' - - def all_gists(self, limit=None): - """ Return all public gists - - NOTE: It returns all gists in github environment. Maybe you - want to use `limit` parameter - """ - - return self._get_resources('', model=models.Gist, limit=limit) - - def get(self, gist_id): - """ Return gist - - param `gist_id`: Gist id - """ - - return self._get_resource(gist_id, model=models.Gist) - - def get_comments(self, gist_id, limit=None): - """ Return gist's comments - - param `gist_id`: Gist id - param `limit`: Number of comments - """ - - return self._get_resources('%s/comments' % gist_id, - model=models.GistComment, limit=limit, - headers=self.mime_header()) - - def get_comment(self, comment_id): - """ Return gist's comment - - param `comment_id`: Comment id - """ - - return self._get_resource('comments/%s' % comment_id, - model=models.GistComment, headers=self.mime_header()) - - -class AuthGist(Gist): - - def all_gists(self, limit=None): - """ Return all public gists - - NOTE: It returns all gists in github environment. Maybe you - want to use `limit` parameter - """ - - return self._get_resources('public', model=models.Gist, limit=limit) - - def my_gists(self, limit=None): - """ Return authenticated user's gists - - param `limit`: Number of gists - """ - - return self._get_resources('', model=models.Gist, limit=limit) - - def my_starred_gists(self, limit=None): - """ Return authenticated user's starred gists - - param `limit`: Number of gists - """ - - return self._get_resources('starred', model=models.Gist, limit=limit) - - def create_gist(self, is_public, files, desc=None): - """ Create and return a gist """ - - data = { - 'public': bool(is_public), - 'files': files, # TODO: Issue #1 - 'desc': desc or '', - } - return self._post_resource('', data=data, model=models.Gist) - - def star_gist(self, gist_id): - """ Star a gist - - param `gist_id`: Gist id to star - """ - - return self._put('%s/star' % gist_id) - - def unstar_gist(self, gist_id): - """ Unstar a gist - - param `gist_id`: Gist id to unstar - """ - - return self._delete('%s/star' % gist_id) - - def is_starred(self, gist_id): - """ True if gist is starred - - param `gist_id`: Gist id - """ - - return self._bool('%s/star' % gist_id) - - def fork_gist(self, gist_id): - """ Return forked gist from id - - param `gist_id`: Gist id to be forked... - """ - - return self._post_resource('%s/fork' % gist_id, data=None, - model=models.Gist) - - def delete_gist(self, gist_id): - """ Delete the gist - - param `gist_id`: Gist id - """ - - return self._delete(str(gist_id)) - - def create_comment(self, gist_id, comment): - """ Create comment into gist """ - - data = {'body': comment} - return self._post_resource('%s/comments' % gist_id, data=data, - model=models.GistComment) - - def delete_comment(self, comment_id): - """ Delete comment - - param `comment_id`: Comment id - """ - - return self._delete('comments/%s' % comment_id) diff --git a/github3/handlers/users.py b/github3/handlers/users.py deleted file mode 100644 index 2f12184..0000000 --- a/github3/handlers/users.py +++ /dev/null @@ -1,299 +0,0 @@ -#!/usr/bin/env python -# -*- encoding: utf-8 -*- - -from .base import Handler -from github3 import models -from github3.converters import Rawlizer -from github3.exceptions import UserIsAnonymous - - -class User(Handler): - """ User handler with public access """ - - prefix = 'users' - - def __repr__(self): - return ' %s>' % getattr(self, 'username', 'without user') - - def _parse_user(self, user): - """ Parse user, and if it fails then try with username in handler - - :param user: It can be a `models.User` or alphanumeric user string - - """ - username = getattr(user, 'login', user) - if not username or not str(username).isalpha(): - username = getattr(self, 'username', False) - if not username: - raise UserIsAnonymous('%s user is not valid' % username) - return str(username) - - def set_username(self, user): - """ Set username to query public handler - Helper to less writing - - :param user: It can be a `models.User` or alphanumeric user string - - """ - self.username = self._parse_user(user) - return self - - def get(self, user=None): - """ Return user - - :param `user`: User model or username string - - """ - user = self._parse_user(user) - return self._get_resource(user, model=models.User) - - def get_followers(self, user=None, limit=None): - """ Return user's followers - - :param `user`: User model or username string - - """ - user = self._parse_user(user) - return self._get_resources('%s/followers' % user, model=models.User, - limit=limit) - - def get_following(self, user=None, limit=None): - """ Return users that follow - - :param `user`: User model or username string - - """ - user = self._parse_user(user) - return self._get_resources('%s/following' % user, model=models.User, - limit=limit) - - def get_repos(self, user=None, limit=None): - """ Return user's public repositories - - :param `user`: User model or username string - - """ - user = self._parse_user(user) - return self._get_resources('%s/repos' % user, model=models.Repo, - limit=limit) - - def get_watched(self, user=None, limit=None): - """ Return repositories that user watch - - :param `user`: User model or username string - - """ - user = self._parse_user(user) - return self._get_resources('%s/watched' % user, model=models.Repo, - limit=limit) - - def get_orgs(self, user=None, limit=None): - """ Return user's public organizations - - :param `user`: User model or username string - - """ - user = self._parse_user(user) - return self._get_resources('%s/orgs' % user, model=models.Org, - limit=limit) - - def get_gists(self, user=None, limit=None): - """ Return user's gists - - :param `user`: User model or username string - - """ - user = self._parse_user(user) - return self._get_resources('%s/gists' % user, model=models.Gist, - limit=limit) - - -class AuthUser(Handler): - """ User handler with public and private access """ - - prefix = 'user' - - def __init__(self, gh): - super(AuthUser, self).__init__(gh) - self._inject_handler(User(gh), prefix='get') - - def __repr__(self): - return ' %s>' % self._gh.session.auth[0] - - def me(self): - """ Return authenticated user """ - - return self._get_resource('', model=models.AuthUser) - - def my_followers(self, limit=None): - """ Return authenticated user followers """ - - return self._get_resources('followers', model=models.User, - limit=limit) - - def my_following(self, limit=None): - """ Return authenticated user following """ - - return self._get_resources('following', model=models.User, - limit=limit) - - def get_emails(self): - """ Return list of emails """ - - # Ignore converter, it must be Rawlizer - emails = self._get_resource('emails', converter=Rawlizer) - return emails - - def create_emails(self, *args): - """ - Add emails - - :param args: Collection of emails - create_emails(*('test1@example.com', 'test2@example.cm')) - """ - parsed_emails = map(str, args) - all_mails = self._post_resource( - 'emails', data=parsed_emails, converter=Rawlizer) - return all_mails - - def delete_emails(self, *args): - """ - Delete emails - - :param args: Collection of emails - create_emails(*('test1@example.com', 'test2@example.cm')) - """ - parsed_emails = map(str, args) - return self._delete('emails', data=parsed_emails) - - def is_following(self, user): - """ - Return true if you are following the user - - :param `user`: User model or username string - """ - - parse_user = getattr(user, 'login', user) - return self._bool('following/%s' % parse_user) - - def follow(self, user): - """ - Follow user - - :param `user`: User model or username string - - """ - - parse_user = getattr(user, 'login', user) - return self._put('following/%s' % parse_user) - - def unfollow(self, user): - """ - Unfollow user - - :param `user`: User model or username string - """ - - parse_user = getattr(user, 'login', user) - return self._delete('following/%s' % parse_user) - - def get_keys(self, limit=None): - """ Get public keys """ - - return self._get_resources('keys', model=models.Key, - limit=limit) - - def get_key(self, key): - """ Get public key - - :param `key`: Key model or key id - - """ - - parse_key_id = getattr(key, 'id', key) - return self._get_resource('keys/%s' % parse_key_id, model=models.Key) - - def create_key(self, **kwargs): - """ - Create public key - - :param title - :param key: Key string (It must starts with 'ssh-rsa') - """ - - #TODO: render key.pub file - key = { - 'title': kwargs.get('title', ''), - 'key': kwargs.get('key', '') - } - return self._post_resource('keys', data=key, model=models.Key) - - def delete_key(self, key): - """ Delete public key - - :param `key`: Key model or key id - - """ - - parse_key_id = getattr(key, 'id', key) - return self._delete('keys/%s' % parse_key_id) - - def my_repos(self, filter='all', limit=None): - """ - Return user's public repositories - - param: filter: 'all', 'owner', 'public', 'private' or 'member' - """ - - return self._get_resources('repos', model=models.Repo, - limit=limit, type=str(filter)) - - def my_watched(self, limit=None): - """ Return authenticated user repos that he watch """ - - return self._get_resources('watched', model=models.Repo, - limit=limit) - - def is_watching_repo(self, owner, repo): - """ - Return true if you are watching the user repository - - :param owner: Model user or username string - :param repo: Model repo or repo name string - is_watching_repo('copitux', 'python-github3') - """ - - owner = getattr(owner, 'login', owner) - repo = getattr(repo, 'name', repo) - return self._bool('watched/%s/%s' % (owner, repo)) - - def watch_repo(self, owner, repo): - """ - Watch the repository - - :param owner: Model user or username string - :param repo: Model repo or repo name string - """ - - owner = getattr(owner, 'login', owner) - repo = getattr(repo, 'name', repo) - return self._put('watched/%s/%s' % (owner, repo)) - - def unwatch_repo(self, owner, repo): - """ - Unwatch the repository - - :param owner: Model user or username string - :param repo: Model repo or repo name string - """ - - owner = getattr(owner, 'login', owner) - repo = getattr(repo, 'name', repo) - return self._delete('watched/%s/%s' % (owner, repo)) - - def my_orgs(self, limit=None): - """ List public and private organizations - for the authenticated user - """ - - return self._get_resources('orgs', model=models.Org, limit=limit) diff --git a/github3/models/__init__.py b/github3/models/__init__.py deleted file mode 100644 index 0471393..0000000 --- a/github3/models/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -from .user import AuthUser, User, Key -from .repos import Repo -from .orgs import Org -from .gists import Gist, GistComment diff --git a/github3/models/base.py b/github3/models/base.py deleted file mode 100644 index 5295d07..0000000 --- a/github3/models/base.py +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env python -# -*- encoding: utf-8 -*- - -class BaseResource(object): - """A BaseResource object.""" - - def __init__(self, attrs=None): - if attrs: - for attr, value in attrs.items(): - setattr(self, attr, value) - super(BaseResource, self).__init__() - - def __len__(self): - return len(self.__dict__) - - @classmethod - def idl(self): - raise NotImplementedError('Each model need subcass that method') diff --git a/github3/models/gists.py b/github3/models/gists.py deleted file mode 100644 index 8979dbb..0000000 --- a/github3/models/gists.py +++ /dev/null @@ -1,98 +0,0 @@ -#!/usr/bin/env python -# -*- encoding: utf-8 -*- - -from .base import BaseResource -from .user import User - - -class GistComment(BaseResource): - """ Gist comment """ - - @classmethod - def idl(self): - return { - 'strs': ['url', 'body', 'body_text', 'body_html'], - 'ints': ['id'], - 'maps': {'user': User}, - 'dates': ['created_at'], - } - - def __repr__(self): - return '' % self.user.login - - -class File(BaseResource): - """ File model """ - - @classmethod - def idl(self): - return { - 'strs': ['filename', 'raw_url', 'content', 'language', 'type'], - 'ints': ['size'], - } - - def __repr__(self): - return ' %s' % self.filename - - -class GistFork(BaseResource): - """ GistFork model """ - - @classmethod - def idl(self): - return { - 'strs': ['url'], - 'dates': ['created_at'], - 'maps': {'user': User} - } - - def __repr__(self): - return ' %s>' % self.user.login - - -class ChangeStatus(BaseResource): - """ ChangeStatus model """ - - @classmethod - def idl(self): - return { - 'ints': ['deletions', 'additions', 'total'], - } - - def __repr__(self): - return ' change_status>' - - -class GistHistory(BaseResource): - """ """ - - @classmethod - def idl(self): - return { - 'strs': ['url', 'version'], - 'maps': {'user': User, 'change_status': ChangeStatus}, - 'dates': ['committed_at'], - } - - def __repr__(self): - return '' % (self.user, self.committed_at) - - -class Gist(BaseResource): - """ """ - - @classmethod - def idl(self): - return { - 'strs': ['url', 'description', 'html_url', 'git_pull_url', - 'git_push_url'], - 'ints': ['id', 'comments'], - 'bools': ['public'], - 'dates': ['created_at'], - 'maps': {'user': User}, - 'collection_maps': {'files': File, 'forks': GistFork, - 'history': GistHistory}, - } - - def __repr__(self): - return '' % (self.user, self.description) diff --git a/github3/models/orgs.py b/github3/models/orgs.py deleted file mode 100644 index b2dacbd..0000000 --- a/github3/models/orgs.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env python -# -*- encoding: utf-8 -*- - -from .base import BaseResource -from .user import Plan - -class Org(BaseResource): - """Github Organization object model.""" - - @classmethod - def idl(self): - return { - 'strs': ['login', 'url', 'avatar_url', 'name', 'company', 'blog', - 'location', 'email', 'html_url', 'type', 'billing_email'], - 'ints': ['id', 'public_repos', 'public_gists', 'followers', - 'following', 'total_private_repos', 'owned_private_repos', - 'private_gists', 'disk_usage', 'collaborators'], - 'dates': ['created_at'], - 'maps': {'plan': Plan} - } - - def __repr__(self): - return '' % self.login diff --git a/github3/models/repos.py b/github3/models/repos.py deleted file mode 100644 index 882fb37..0000000 --- a/github3/models/repos.py +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env python -# -*- encoding: utf-8 -*- - -from .base import BaseResource -from .user import User -from .orgs import Org - -class Repo(BaseResource): - """ Repo model """ - - @classmethod - def idl(self): - return { - 'strs': [ - 'url', 'html_url', 'clone_url', 'git_url', 'ssh_url', 'svn_url', - 'name', 'description', 'homepage', 'language', 'master_branch'], - 'ints': ['forks', 'watchers', 'size', 'open_issues'], - 'dates': ['created_at', 'pushed_at'], - 'bools': ['private', 'fork', 'has_issues', 'has_wiki', 'has_downloads'], - 'maps': { - 'owner': User, - 'organization': Org, - 'parent': self.__class__, - 'source': self.__class__, - } - } - - def __repr__(self): - return '' % (self.owner.login, self.name) diff --git a/github3/models/user.py b/github3/models/user.py deleted file mode 100644 index aed6f09..0000000 --- a/github3/models/user.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/env python -# -*- encoding: utf-8 -*- - -from .base import BaseResource - - -class Plan(BaseResource): - """Github Plan object model.""" - - @classmethod - def idl(self): - return { - 'strs': ['name'], - 'ints': ['space', 'collaborators', 'private_repos'], - } - - def __repr__(self): - return '' % self.name - - -class Key(BaseResource): - """Github Key object model.""" - - @classmethod - def idl(self): - return { - 'strs': ['url', 'title', 'key'], - 'ints': ['id'], - } - - def __repr__(self): - return '' % self.title - - -class User(BaseResource): - """Github User object model.""" - - @classmethod - def idl(self): - return { - 'strs': [ - 'login', 'avatar_url', 'gravatar_id', 'url', 'name', - 'company', 'blog', 'location', 'email', 'bio', 'html_url', - 'type'], - 'ints': [ - 'id', 'public_repos', 'public_gists', 'followers', 'following', - 'total_private_repos', 'owned_private_repos', 'private_gists', - 'disk_usage', 'collaborators'], - 'maps': {'plan': Plan}, - 'dates': ['created_at', ], - 'bools': ['hireable', ], - } - - def __repr__(self): - return '' % getattr(self, 'login', 'without user') - - #def handler(self): - # return self._gh.users - - -class AuthUser(User): - """Github Authenticated User object model.""" - - def __repr__(self): - return '' % self.login - - #def handler(self): - # return self._gh.users - diff --git a/github3/tests/api_test.py b/github3/tests/api_test.py deleted file mode 100644 index 3ae75ee..0000000 --- a/github3/tests/api_test.py +++ /dev/null @@ -1,124 +0,0 @@ -#!/usr/bin/env python -# -*- encoding: utf-8 -*- - -from mock import Mock, patch -from unittest import TestCase -from github3 import api -from github3.exceptions import * -import json -import requests - - -@patch.object(requests.sessions.Session, 'request') -class TestGithubCore(TestCase): - - def setUp(self): - self.gh = api.GithubCore() - self.assertEquals(self.gh.base_url, 'https://api.github.com/') - self.assertEquals(self.gh._parser, json) - self.base_url = self.gh.base_url - self.parser = self.gh._parser - - def test_parse_args(self, request_method): - args = { - 'data': {'some': 'data'}, - 'params': {'arg0': 'some'}, - 'headers': 'out', - 'auth': 'out', - 'arg1': 'some', - 'arg2': 'some', - 'arg3': {'some': 'data', 'are': {'nested': 'true'}}, - } - self.gh._parse_args(args) - self.assertEquals(args, { - 'data': {'some': 'data'}, - 'params': {'arg0': 'some', 'arg1': 'some', 'arg2': 'some', - 'arg3': {'some': 'data', 'are': {'nested': 'true'}}}, - 'headers': 'out', - 'auth': 'out', - }) - - def test_raise_errors(self, request_method): - real_request = (self.gh._request, 'GET', 'test') - request_method.return_value.status_code = 404 - self.assertRaises(NotFound, *real_request) - - request_method.return_value.status_code = 400 - self.assertRaises(BadRequest, *real_request) - - request_method.return_value.status_code = 422 - self.assertRaises(UnprocessableEntity, *real_request) - - request_method.return_value.status_code = 401 - self.assertRaises(Unauthorized, *real_request) - - def test_get(self, request_method): - response = request_method.return_value - response.content = self.parser.dumps({'test': 'test'}) - content = self.gh.get('core') - request_method.assert_called_with('GET', self.base_url + 'core') - self.assertEquals(content, {'test': 'test'}) - - response = request_method.return_value - response.headers = {'link': 'url_with_links'} - response.content = self.parser.dumps({'test': 'test'}) - header, content = self.gh.get('core', paginate=True) - request_method.assert_called_with('GET', self.base_url + 'core') - self.assertEquals(header, 'url_with_links') - self.assertEquals(content, {'test': 'test'}) - - def test_head(self, request_method): - pass # It has no sense using mocks - - def test_post_and_patch(self, request_method): - data = {'login': 'test', 'bio': 'test'} - response = request_method.return_value - response.status_code = 201 - response.content = self.parser.dumps({'post': 'done'}) - - content = self.gh.post('core', data=data) - request_method.assert_called_with( - 'POST', self.base_url + 'core', - data=self.parser.dumps(data)) - self.assertEquals(content, {'post': 'done'}) - - content = self.gh.post('core') - request_method.assert_called_with( - 'POST', self.base_url + 'core', - data=self.parser.dumps(None)) - self.assertEquals(content, {'post': 'done'}) - - response.status_code = 200 - content = self.gh.patch('core', data=data) - request_method.assert_called_with( - 'PATCH', self.base_url + 'core', - data=self.parser.dumps(data)) - self.assertEquals(content, {'post': 'done'}) - - content = self.gh.patch('core') - request_method.assert_called_with( - 'PATCH', self.base_url + 'core', - data=self.parser.dumps(None)) - self.assertEquals(content, {'post': 'done'}) - - def test_delete(self, request_method): - data = {'test': 'test'} - response = request_method.return_value - response.status_code = 204 - response.content = self.parser.dumps({'delete': 'done'}) - delete = self.gh.delete('core', data=data) - request_method.assert_called_with( - 'DELETE', self.base_url + 'core', - data=self.parser.dumps(data)) - delete = self.gh.delete('core') - request_method.assert_called_with( - 'DELETE', self.base_url + 'core') - - def test_put(self, request_method): - response = request_method.return_value - response.status_code = 204 - response.content = '' - put = self.gh.put('core') - request_method.assert_called_with( - 'PUT', self.base_url + 'core', - headers={'Content-length': '0'}) diff --git a/github3/tests/converters_test.py b/github3/tests/converters_test.py deleted file mode 100644 index 66eedc3..0000000 --- a/github3/tests/converters_test.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python -# -*- encoding: utf-8 -*- - -from github3.converters import * -from github3.models.base import BaseResource -from unittest import TestCase -from datetime import datetime - -API_STUB = { - 'test_str': 'string', - 'test_int': 1, - 'test_date': '2008-01-14T04:33:35Z', - 'test_bool': True, - 'map': {'test_str': 'string'}, - 'dict_map': { - 'map1': { - 'test_str': 'string', - 'test_int': 1 - }, - 'map2': { - 'test_str': 'string', - 'test_int': 2 - }, - }, - 'list_map': [ - {'test_str': 'string', 'test_int': 1}, - {'test_str': 'string', 'test_int': 2}, - ], - 'fake_map': 9, -} - - -class Model(BaseResource): - - @classmethod - def idl(self): - return { - 'strs': ['test_str'], - 'ints': ['test_int'], - 'dates': ['test_date'], - 'bools': ['test_bool'], - 'maps': {'map': Model, 'fake_map': Model}, - 'collection_maps': { - 'dict_map': Model, - 'list_map': Model, - 'fake_map': Model, - }, - } - - -class TestModelizer(TestCase): - - def setUp(self): - model = Model - self.modelizer = Modelizer() - self.modelizer.inject(model) - - def test_loads(self): - parsed_model = self.modelizer.loads(API_STUB) - self.assertEquals(len(parsed_model), len(API_STUB)) - self.assertEquals(parsed_model.test_str, 'string') - self.assertEquals(parsed_model.test_int, 1) - self.assertEquals( - parsed_model.test_date, - datetime(2008, 1, 14, 4, 33, 35)) - self.assertTrue(parsed_model.test_bool) - self.assertTrue(isinstance(parsed_model.map, Model)) - self.assertEquals(parsed_model.map.test_str, 'string') - self.assertTrue(isinstance(parsed_model.dict_map, dict)) - map1 = parsed_model.dict_map['map1'] - map2 = parsed_model.dict_map['map2'] - self.assertTrue(isinstance(map1, Model)) - self.assertTrue(isinstance(map2, Model)) - self.assertEquals(map1.test_str, 'string') - self.assertEquals(map1.test_int, 1) - self.assertEquals(map2.test_str, 'string') - self.assertEquals(map2.test_int, 2) - - list_map = parsed_model.list_map - self.assertTrue(isinstance(list_map, list)) - self.assertEquals(list_map[0].test_str, 'string') - self.assertEquals(list_map[0].test_int, 1) - self.assertEquals(list_map[1].test_str, 'string') - self.assertEquals(list_map[1].test_int, 2) - - -class TestRawlizer(TestCase): - - def setUp(self): - model = Model - self.rawlizer = Rawlizer() - - # Trivial, I know it - def test_loads(self): - raw = self.rawlizer.loads(API_STUB) - self.assertEquals(raw, API_STUB) diff --git a/github3/tests/fixtures.py b/github3/tests/fixtures.py deleted file mode 100644 index ff5179c..0000000 --- a/github3/tests/fixtures.py +++ /dev/null @@ -1,164 +0,0 @@ -#!/usr/bin/env python -# -*- encoding: utf-8 -*- - -GET_USER = { - "login": "octocat", - "id": 1, - "avatar_url": "https://github.com/images/error/octocat_happy.gif", - "gravatar_id": "somehexcode", - "url": "https://api.github.com/users/octocat", - "name": "monalisa octocat", - "company": "GitHub", - "blog": "https://github.com/blog", - "location": "San Francisco", - "email": "octocat@github.com", - "hireable": False, - "bio": "There once was...", - "public_repos": 2, - "public_gists": 1, - "followers": 20, - "following": 0, - "html_url": "https://github.com/octocat", - "created_at": "2008-01-14T04:33:35Z", - "type": "User" -} - -GET_LINK = '; rel="next", \ -; rel="last"' - -GET_RESOURCES = [ - {'login': 'octocat'}, - {'login': 'octocat'} -] - -GET_SHORT_USERS = [ - { - "login": "octocat", - "id": 1, - "avatar_url": "https://github.com/images/error/octocat_happy.gif", - "gravatar_id": "somehexcode", - "url": "https://api.github.com/users/octocat" - }, - { - "login": "octocat", - "id": 1, - "avatar_url": "https://github.com/images/error/octocat_happy.gif", - "gravatar_id": "somehexcode", - "url": "https://api.github.com/users/octocat" - }, -] - -GET_SHORT_ORGS = [ - { - "login": "github", - "id": 1, - "url": "https://api.github.com/orgs/1", - "avatar_url": "https://github.com/images/error/octocat_happy.gif" - } -] - -GET_SHORT_REPOS = [ - { - "url": "https://api.github.com/repos/octocat/Hello-World", - "html_url": "https://github.com/octocat/Hello-World", - "clone_url": "https://github.com/octocat/Hello-World.git", - "git_url": "git://github.com/octocat/Hello-World.git", - "ssh_url": "git@github.com:octocat/Hello-World.git", - "svn_url": "https://svn.github.com/octocat/Hello-World", - "owner": { - "login": "octocat", - "id": 1, - "avatar_url": "https://github.com/images/error/octocat_happy.gif", - "gravatar_id": "somehexcode", - "url": "https://api.github.com/users/octocat" - }, - "name": "Hello-World", - "description": "This your first repo!", - "homepage": "https://github.com", - "language": None, - "private": False, - "fork": False, - "forks": 9, - "watchers": 80, - "size": 108, - "master_branch": "master", - "open_issues": 0, - "pushed_at": "2011-01-26T19:06:43Z", - "created_at": "2011-01-26T19:01:12Z" - } -] - -GET_SHORT_GISTS = [ - { - "url": "https://api.github.com/gists/1", - "id": "1", - "description": "description of gist", - "public": True, - "user": { - "login": "octocat", - "id": 1, - "avatar_url": "https://github.com/images/error/octocat_happy.gif", - "gravatar_id": "somehexcode", - "url": "https://api.github.com/users/octocat" - }, - "files": { - "ring.erl": { - "size": 932, - "filename": "ring.erl", - "raw_url": "https://gist.github.com/raw/365370/8c4d2d43d178df\ - 44f4c03a7f2ac0ff512853564e/ring.erl", - "content": "contents of gist" - } - }, - "comments": 0, - "html_url": "https://gist.github.com/1", - "git_pull_url": "git://gist.github.com/1.git", - "git_push_url": "git@gist.github.com:1.git", - "created_at": "2010-04-14T02:15:15Z" - } -] -GET_FULL_USER = { - "login": "octocat", - "id": 1, - "avatar_url": "https://github.com/images/error/octocat_happy.gif", - "gravatar_id": "somehexcode", - "url": "https://api.github.com/users/octocat", - "name": "monalisa octocat", - "company": "GitHub", - "blog": "https://github.com/blog", - "location": "San Francisco", - "email": "octocat@github.com", - "hireable": False, - "bio": "There once was...", - "public_repos": 2, - "public_gists": 1, - "followers": 20, - "following": 0, - "html_url": "https://github.com/octocat", - "created_at": "2008-01-14T04:33:35Z", - "type": "User", - "total_private_repos": 100, - "owned_private_repos": 100, - "private_gists": 81, - "disk_usage": 10000, - "collaborators": 8, - "plan": { - "name": "Medium", - "space": 400, - "collaborators": 10, - "private_repos": 20 - } -} -GET_USER_EMAILS = [ - "octocat@github.com", - "support@github.com" -] - -GET_USER_KEYS = [ - { - "url": "https://api.github.com/user/keys/1", - "id": 1, - "title": "octocat@octomac", - "key": "ssh-rsa AAA..." - } -] diff --git a/github3/tests/get_handlers_test.py b/github3/tests/get_handlers_test.py deleted file mode 100644 index 0d88670..0000000 --- a/github3/tests/get_handlers_test.py +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env python -# -*- encoding: utf-8 -*- - -from unittest import TestCase -from github3 import api -from github3 import handlers - - -class TestGetHandlers(TestCase): - - def setUp(self): - self.anom_gh = api.Github() - self.auth_gh = api.Github('test', 'password') - - def test_get_user(self): - anom_user = self.anom_gh.users - auth_user = self.auth_gh.users - - self.assertIsInstance(anom_user, handlers.users.User) - self.assertEquals(anom_user.prefix, 'users') - self.assertIsInstance(auth_user, handlers.users.AuthUser) - self.assertEquals(auth_user.prefix, 'user') - - def test_get_gists(self): - anom_gists = self.anom_gh.gists - auth_gists = self.auth_gh.gists - - self.assertIsInstance(anom_gists, handlers.gists.Gist) - self.assertEquals(anom_gists.prefix, 'gists') - self.assertIsInstance(auth_gists, handlers.gists.AuthGist) - self.assertEquals(anom_gists.prefix, 'gists') diff --git a/github3/tests/gists_handler_test.py b/github3/tests/gists_handler_test.py deleted file mode 100644 index ecadcfb..0000000 --- a/github3/tests/gists_handler_test.py +++ /dev/null @@ -1,110 +0,0 @@ -#!/usr/bin/env python -# -*- encoding: utf-8 -*- - -from unittest import TestCase -from mock import Mock, patch -from github3 import api -from github3.models import Gist, GistComment -from github3.handlers.base import Handler - - -class TestGistHandler(TestCase): - - def setUp(self): - self.gh = api.Github() - self.handler = self.gh.gists - - @patch.object(Handler, '_get_resources') - def test_get_gists(self, get): - gists = self.handler.all_gists() - get.assert_called_with('', model=Gist, limit=None) - - @patch.object(Handler, '_get_resource') - def test_get(self, get): - gist = self.handler.get(1) - get.assert_called_with(1, model=Gist) - - @patch.object(Handler, '_get_resources') - def test_get_comments(self, get): - comments = self.handler.get_comments(1) - get.assert_called_with('1/comments', model=GistComment, limit=None, - headers=None) - - @patch.object(Handler, '_get_resource') - def test_get_comment(self, get): - comment = self.handler.get_comment(1) - get.assert_called_with('comments/1', model=GistComment, headers=None) - - -class TestAuthGistHandler(TestCase): - - def setUp(self): - self.gh = api.Github('test', 'pass') - self.handler = self.gh.gists - - def test_inherit(self): - self.assertTrue(hasattr(self.handler, 'get')) - self.assertTrue(hasattr(self.handler, 'get_comments')) - self.assertTrue(hasattr(self.handler, 'get_comment')) - - @patch.object(Handler, '_get_resources') - def test_all_gists(self, get): - gists = self.handler.all_gists() - get.assert_called_with('public', model=Gist, limit=None) - - @patch.object(Handler, '_get_resources') - def test_my_gists(self, get): - gists = self.handler.my_gists() - get.assert_called_with('', model=Gist, limit=None) - - @patch.object(Handler, '_get_resources') - def test_my_starred_gists(self, get): - gists = self.handler.my_starred_gists() - get.assert_called_with('starred', model=Gist, limit=None) - - @patch.object(Handler, '_post_resource') - def test_create_gist(self, post): - data = { - 'public': False, - 'files': {'file': {'contents': 'file_data'}}, - 'desc': 'some' - } - gist = self.handler.create_gist(data['public'], data['files'], - data['desc']) - post.assert_called_with('', data=data, model=Gist) - - @patch.object(Handler, '_put') - def test_star_gist(self, put): - boolean = self.handler.star_gist(1) - put.assert_called_with('1/star') - - @patch.object(Handler, '_delete') - def test_unstar_gist(self, delete): - boolean = self.handler.unstar_gist(1) - delete.assert_callted_with('1/star') - - @patch.object(Handler, '_bool') - def test_is_starred(self, bool): - boolean = self.handler.is_starred(1) - bool.assert_called_with('1/star') - - @patch.object(Handler, '_post_resource') - def test_fork_gist(self, post): - gist = self.handler.fork_gist(1) - post.assert_called_with('1/fork', data=None, model=Gist) - - @patch.object(Handler, '_delete') - def test_delete_gist(self, delete): - boolean = self.handler.delete_gist(1) - delete.assert_called_with('1') - - @patch.object(Handler, '_post_resource') - def test_create_comment(self, post): - gist_comment = self.handler.create_comment(1, 'comment') - post.assert_called_with('1/comments', data={'body': 'comment'}, - model=GistComment) - - @patch.object(Handler, '_delete') - def test_delete_comment(self, delete): - boolean = self.handler.delete_comment(1) - delete.assert_called_with('comments/1') diff --git a/github3/tests/handler_test.py b/github3/tests/handler_test.py deleted file mode 100644 index 83c89ef..0000000 --- a/github3/tests/handler_test.py +++ /dev/null @@ -1,133 +0,0 @@ -#!/usr/bin/env python -# -*- encoding: utf-8 -*- - -from mock import Mock, patch -from unittest import TestCase -from github3 import api -from github3.handlers.base import Handler, MimeTypeMixin -from github3.exceptions import * -from github3.converters import * -from github3.models.user import User -from fixtures import * -import json -import requests - - -class TestMimeTypeMixin(TestCase): - - def setUp(self): - self.mixin = MimeTypeMixin() - - def _parse_mime_type(self, type): - return 'application/vnd.github.%s.%s+json' % ( - MimeTypeMixin.VERSION, type) - - def test_header(self): - self.assertEquals(self.mixin.mime_header(), None) - - def test_add_mimetypes(self): - self.mixin.add_raw() - self.mixin.add_text() - self.mixin.add_html() - self.mixin.add_full() - self.assertEquals(sorted(self.mixin.mime_header()), sorted({ - 'Accept': '%s, %s, %s, %s' % ( - self._parse_mime_type('raw'), - self._parse_mime_type('text'), - self._parse_mime_type('html'), - self._parse_mime_type('full'))})) - - -class TestHandler(TestCase): - - def setUp(self): - self.gh = api.Github() - self.handler = Handler(self.gh) - - def test_get_converter(self): - self.assertIsInstance(self.handler._get_converter(), Modelizer) - kwargs = {'converter': Rawlizer} - self.assertIsInstance(self.handler._get_converter(kwargs), - Rawlizer) - self.assertEquals(kwargs, {}) - self.handler.converter = Modelizer - self.assertIsInstance(self.handler._get_converter(), Modelizer) - - def test_bool(self): - with patch.object(api.Github, 'head') as head: - response = head.return_value - response.status_code = 204 - bool1 = self.handler._bool('test') - head.side_effect = NotFound() - bool2 = self.handler._bool('test') - head.assert_called_with('test') - self.assertTrue(bool1) - self.assertFalse(bool2) - - with patch.object(api.Github, 'put') as put: - response = put.return_value - response.status_code = 204 - booll = self.handler._put('test') - put.assert_called_with('test', method='put') - self.assertTrue(booll) - - with patch.object(api.Github, 'delete') as delete: - response = delete.return_value - response.content = self.gh._parser.dumps({'data': 'test'}) - response.status_code = 204 - bool1 = self.handler._bool('test', method='delete') - bool2 = self.handler._bool('test', method='delete', - data={'some': 'data'}) - self.assertTrue(bool1) - self.assertTrue(bool2) - - @patch.object(api.Github, '_request') - def test_get_resources(self, request): - # Simulating per_page=2 with STUB (it returns two resources) - response = request.return_value - response.status_code = 200 - response.headers = {'link': GET_LINK} - response.content = self.gh._parser.dumps(GET_RESOURCES) - resources = self.handler._get_resources('users', model=User) - self.assertFalse(request.called) - resources = list(resources) - self.assertTrue(request.call_count, 5) - request_args = ('GET', 'users') - self.assertEquals(request.call_args_list, [ - (request_args, {'page': 1}), - (request_args, {'page': 2}), - (request_args, {'page': 3}), - (request_args, {'page': 4}), - (request_args, {'page': 5})]) - self.assertEquals(len(resources), 10) - self.assertEquals(resources[0].login, 'octocat') - - request.reset_mock() - resources = self.handler._get_resources('users', model=User, limit=5) - resources = list(resources) - self.assertEquals(request.call_count, 3) - self.assertEquals(len(resources), 5) - request.reset_mock() - resources = self.handler._get_resources('users', model=User, limit=4) - resources = list(resources) - self.assertEquals(request.call_count, 2) - self.assertEquals(len(resources), 4) - request.reset_mock() - resources = self.handler._get_resources('users', model=User, limit=-5) - resources = list(resources) - self.assertEquals(request.call_count, 3) - self.assertEquals(len(resources), 5) - - @patch.object(api.Github, 'get') - def test_get_resource(self, get): - # Converter test + api(get) test. Half trivial - get.return_value = {'login': 'octocat'} - model = self.handler._get_resource('test', model=User) - self.assertEquals(model.login, 'octocat') - - @patch.object(api.Github, 'post') - def test_post_resource(self, post): - post.return_value = {'data': 'posted'} - data = {'data': 'to_post'} - user_new = self.handler._post_resource('test', data=data, model=User) - post.assert_called_with('test', data=data) diff --git a/github3/tests/user_handler_test.py b/github3/tests/user_handler_test.py deleted file mode 100644 index 33658d2..0000000 --- a/github3/tests/user_handler_test.py +++ /dev/null @@ -1,326 +0,0 @@ -#!/usr/bin/env python -# -*- encoding: utf-8 -*- - -from unittest import TestCase -from mock import Mock, patch -from github3 import api -from fixtures import * -from github3.models import User, AuthUser, Repo, Gist, Org, Key -from github3.exceptions import * -from github3 import handlers - - -class TestAuthUserHandler(TestCase): - """ Test private api about user logged """ - - def setUp(self): - self.gh = api.Github('test', 'pass') - self.handler = self.gh.users - self.user_mock = Mock() - self.user_mock.login = 'user_model' - - def test_inject_user_handler(self): - self.assertEquals(self.handler.get.im_class, handlers.users.User) - self.assertEquals(self.handler.get_followers.im_class, - handlers.users.User) - self.assertEquals(self.handler.get_following.im_class, - handlers.users.User) - self.assertEquals(self.handler.get_repos.im_class, - handlers.users.User) - self.assertEquals(self.handler.get_watched.im_class, - handlers.users.User) - self.assertEquals(self.handler.get_orgs.im_class, - handlers.users.User) - self.assertEquals(self.handler.get_gists.im_class, - handlers.users.User) - - @patch.object(api.Github, 'get') - def test_me(self, get): - get.return_value = GET_FULL_USER - user = self.handler.me() - self.assertIsInstance(user, AuthUser) - get.assert_called_with('user') - self.assertEquals(len(user), len(GET_FULL_USER)) - - @patch.object(handlers.base.Handler, '_get_resource') - def test_get(self, get): - user = self.handler.get('test') - get.assert_called_with('test', model=User) - - @patch.object(handlers.base.Handler, '_get_resources') - def test_get_my_followers(self, get): - followers = self.handler.my_followers() - get.assert_called_with('followers', model=User, limit=None) - - @patch.object(handlers.base.Handler, '_get_resources') - def test_get_my_following(self, get): - following = self.handler.my_following() - get.assert_called_with('following', model=User, limit=None) - - @patch.object(handlers.base.Handler, '_get_resources') - def test_get_my_watched(self, get): - following = self.handler.my_watched() - get.assert_called_with('watched', model=Repo, limit=None) - - @patch.object(handlers.base.Handler, '_get_resources') - def test_get_my_orgs(self, get): - following = self.handler.my_orgs() - get.assert_called_with('orgs', model=Org, limit=None) - - @patch.object(api.Github, 'get') - def test_get_emails(self, get): - get.return_value = GET_USER_EMAILS - emails = self.handler.get_emails() - get.assert_called_with('user/emails') - self.assertEquals(emails, GET_USER_EMAILS) - - @patch.object(api.Github, 'post') - def test_create_emails(self, post): - post.return_value = GET_USER_EMAILS - emails = self.handler.create_emails(*GET_USER_EMAILS) - post.assert_called_with('user/emails', data=GET_USER_EMAILS) - self.assertEquals(emails, GET_USER_EMAILS) - - @patch.object(api.Github, 'delete') - def test_delete_emails(self, delete): - response = delete.return_value - response.return_value = '' - response.status_code = 204 - emails = self.handler.delete_emails(*GET_USER_EMAILS) - delete.assert_called_with('user/emails', data=GET_USER_EMAILS, - method='delete') - self.assertTrue(emails) - - @patch.object(api.Github, 'head') - def test_is_following(self, head): - response = head.return_value - response.status_code = 204 - self.assertTrue(self.handler.is_following('test')) - head.assert_called_with('user/following/test') - self.handler.is_following(self.user_mock) - head.assert_called_with('user/following/user_model') - - @patch.object(api.Github, 'put') - def test_follow(self, put): - response = put.return_value - response.status_code = 204 - self.assertTrue(self.handler.follow('test')) - put.assert_called_with('user/following/test', method='put') - - @patch.object(api.Github, 'delete') - def test_unfollow(self, delete): - response = delete.return_value - response.status_code = 204 - self.assertTrue(self.handler.unfollow('test')) - delete.assert_called_with('user/following/test', method='delete') - - @patch.object(api.Github, '_request') - def test_get_keys(self, request): - response = request.return_value - response.status_code = 200 - response.content = self.gh._parser.dumps(GET_USER_KEYS) - response.headers = {'link': GET_LINK} # 1 per page - keys = list(self.handler.get_keys()) - self.assertEquals(len(keys), 5) - self.assertIsInstance(keys[0], Key) - request.assert_called_with('GET', 'user/keys', page=5) - keys = list(self.handler.get_keys(limit=2)) - self.assertEquals(len(keys), 2) - - @patch.object(api.Github, 'get') - def test_get_key(self, get): - get.return_value = GET_USER_KEYS[0] - key = self.handler.get_key(1) - self.assertIsInstance(key, Key) - get.assert_called_with('user/keys/1') - model_key = Mock() - model_key.id = 1 - key = self.handler.get_key(model_key) - get.assert_called_with('user/keys/1') - - @patch.object(api.Github, 'post') - def test_create_key(self, post): - post.return_value = GET_USER_KEYS[0] - key_data = {'title': 'some', 'key': 'ssh-rsa AAA'} - created_key = self.handler.create_key(**key_data) - self.assertIsInstance(created_key, Key) - post.assert_called_with('user/keys', data=key_data) - - @patch.object(api.Github, 'delete') - def test_delete_key(self, delete): - response = delete.return_value - response.status_code = 204 - self.assertTrue(self.handler.delete_key(1)) - delete.assert_called_with('user/keys/1', method='delete') - model_key = Mock() - model_key.id = 1 - key = self.handler.delete_key(model_key) - delete.assert_called_with('user/keys/1', method='delete') - - @patch.object(api.Github, '_request') - def test_my_repos(self, request): - response = request.return_value - response.status_code = 200 - response.content = self.gh._parser.dumps(GET_SHORT_REPOS) - response.headers = {'link': GET_LINK} # 1 per page - repos = list(self.handler.my_repos(filter='public')) - self.assertEquals(len(repos), 5) - self.assertIsInstance(repos[0], Repo) - request.assert_called_with('GET', 'user/repos', - page=5, type='public') - repos = list(self.handler.my_repos(limit=2)) - self.assertEquals(len(repos), 2) - - @patch.object(api.Github, 'head') - def test_is_watching_repo(self, head): - response = head.return_value - response.status_code = 204 - self.assertTrue(self.handler.is_watching_repo('user', 'repo')) - head.assert_called_with('user/watched/user/repo') - model_user, model_repo = Mock(), Mock() - model_user.login = 'user' - model_repo.name = 'repo' - self.assertTrue(self.handler.is_watching_repo('user', 'repo')) - head.assert_called_with('user/watched/user/repo') - - @patch.object(api.Github, 'put') - def test_watch_repo(self, put): - response = put.return_value - response.status_code = 204 - self.assertTrue(self.handler.watch_repo('user', 'repo')) - put.assert_called_with('user/watched/user/repo', method='put') - model_user, model_repo = Mock(), Mock() - model_user.login = 'user' - model_repo.name = 'repo' - self.assertTrue(self.handler.watch_repo('user', 'repo')) - put.assert_called_with('user/watched/user/repo', method='put') - - @patch.object(api.Github, 'delete') - def test_unwatch_repo(self, delete): - response = delete.return_value - response.status_code = 204 - self.assertTrue(self.handler.unwatch_repo('user', 'repo')) - delete.assert_called_with('user/watched/user/repo', method='delete') - model_user, model_repo = Mock(), Mock() - model_user.login = 'user' - model_repo.name = 'repo' - self.assertTrue(self.handler.unwatch_repo('user', 'repo')) - delete.assert_called_with('user/watched/user/repo', method='delete') - - -class TestUserHandler(TestCase): - """ Test public api about users """ - - def setUp(self): - self.gh = api.Github() - self.handler = self.gh.users - - def test_set_username(self): - handler = self.handler.set_username('test') - self.assertEquals(id(handler), id(self.handler)) - self.assertEquals(handler.username, 'test') - model_user = Mock() - model_user.login = 'test' - handler = self.handler.set_username(model_user) - self.assertEquals(handler.username, 'test') - - def test_parse_user(self): - model_user = Mock() - model_user.login = 'test' - self.assertRaises(UserIsAnonymous, self.handler._parse_user, None) - user = self.handler._parse_user(model_user) - self.assertEquals(user, 'test') - user = self.handler._parse_user('test') - self.assertEquals(user, 'test') - self.assertRaises(UserIsAnonymous, self.handler._parse_user, Mock()) - self.handler.set_username('octocat') - self.assertEquals('octocat', self.handler._parse_user(None)) - self.assertEquals('octocat', self.handler._parse_user(Mock())) - self.assertEquals('test', self.handler._parse_user('test')) - self.assertEquals('test', self.handler._parse_user(model_user)) - - @patch.object(api.Github, 'get') - def test_get(self, get): - get.return_value = GET_USER - self.assertRaises(UserIsAnonymous, self.handler.get) - user = self.handler.get('octocat') - self.assertIsInstance(user, User) - get.assert_called_with('users/octocat') - - @patch.object(api.Github, '_request') - def test_get_followers(self, request): - response = request.return_value - response.headers = {'link': GET_LINK} - response.content = self.gh._parser.dumps(GET_SHORT_USERS) # 2 users - followers = list(self.handler.get_followers('test')) - request.assert_called_with('GET', 'users/test/followers', page=5) - self.assertIsInstance(followers[0], User) - self.assertEquals(len(followers), 10) - followers = list(self.handler.get_followers('test', limit=2)) - self.assertEquals(len(followers), 2) - self.assertEquals(followers[0].login, 'octocat') - - @patch.object(api.Github, '_request') - def test_get_following(self, request): - response = request.return_value - response.headers = {'link': GET_LINK} - response.content = self.gh._parser.dumps(GET_SHORT_USERS) # 2 users - following = list(self.handler.get_following('test')) - request.assert_called_with('GET', 'users/test/following', page=5) - self.assertIsInstance(following[0], User) - self.assertEquals(len(following), 10) - following = list(self.handler.get_following('test', limit=2)) - self.assertEquals(len(following), 2) - - @patch.object(api.Github, '_request') - def test_get_repos(self, request): - response = request.return_value - response.headers = {'link': GET_LINK} - response.content = self.gh._parser.dumps(GET_SHORT_REPOS) # 1 repo - repos = list(self.handler.get_repos('test')) - request.assert_called_with('GET', 'users/test/repos', page=5) - self.assertIsInstance(repos[0], Repo) - self.assertEquals(len(repos), 5) - repos = list(self.handler.get_repos('test', limit=2)) - self.assertEquals(len(repos), 2) - self.assertIsInstance(repos[0].owner, User) - - @patch.object(api.Github, '_request') - def test_get_watched(self, request): - response = request.return_value - response.headers = {'link': GET_LINK} - response.content = self.gh._parser.dumps(GET_SHORT_REPOS) # 1 repo - watched = list(self.handler.get_watched('test')) - request.assert_called_with('GET', 'users/test/watched', page=5) - self.assertIsInstance(watched[0], Repo) - self.assertEquals(len(watched), 5) - watched = list(self.handler.get_watched('test', limit=2)) - self.assertEquals(len(watched), 2) - - @patch.object(api.Github, '_request') - def test_get_orgs(self, request): - response = request.return_value - response.headers = {'link': GET_LINK} - response.content = self.gh._parser.dumps(GET_SHORT_ORGS) # 1 repo - orgs = list(self.handler.get_orgs('test')) - request.assert_called_with('GET', 'users/test/orgs', page=5) - self.assertIsInstance(orgs[0], Org) - self.assertEquals(len(orgs), 5) - orgs = list(self.handler.get_orgs('test', limit=2)) - self.assertEquals(len(orgs), 2) - self.assertEquals(orgs[0].login, 'github') - - @patch.object(api.Github, '_request') - def test_get_gists(self, request): - response = request.return_value - response.headers = {'link': GET_LINK} - response.content = self.gh._parser.dumps(GET_SHORT_GISTS) # 1 repo - gists = list(self.handler.get_gists('test')) - request.assert_called_with('GET', 'users/test/gists', page=5) - self.assertIsInstance(gists[0], Gist) - self.assertEquals(len(gists), 5) - gists = list(self.handler.get_gists('test', limit=2)) - self.assertEquals(len(gists), 2) - self.assertIsInstance(gists[0].files, dict) - from github3.models.gists import File - self.assertIsInstance(gists[0].files['ring.erl'], File) diff --git a/pygithub3/__init__.py b/pygithub3/__init__.py new file mode 100644 index 0000000..461dabe --- /dev/null +++ b/pygithub3/__init__.py @@ -0,0 +1,10 @@ +# -*- encoding: utf-8 -*- + +__title__ = 'pygithub3' +__version__ = '0.5' +__author__ = 'David Medina' +__email__ = 'davidmedina9@gmail.com' +__license__ = 'ISC' +__copyright__ = 'Copyright 2012 David Medina' + +from github import Github diff --git a/github3/packages/__init__.py b/pygithub3/core/__init__.py similarity index 100% rename from github3/packages/__init__.py rename to pygithub3/core/__init__.py diff --git a/pygithub3/core/client.py b/pygithub3/core/client.py new file mode 100644 index 0000000..d4b8cd5 --- /dev/null +++ b/pygithub3/core/client.py @@ -0,0 +1,118 @@ +# -*- encoding: utf-8 -*- + +import requests + +from .errors import GithubError + +VALID_REQUEST_ARGS = set(( + 'params', 'data', 'headers', 'cookies', 'files', 'auth', 'timeout', + 'allow_redirects', 'proxies', 'return_response', 'config', + 'prefetch', 'verify')) + + +class Client(object): + """ Client to send configurated requests""" + + remaining_requests = '~' + + def __init__(self, **kwargs): + self.requester = requests.session() + self.config = { + 'per_page': 100, + 'base_url': 'https://api.github.com/' + } + self.config.update(kwargs) + self.set_credentials(self.config.get('login'), + self.config.get('password')) + self.set_oauth_credentials(self.config.get('client_id'), + self.config.get('client_secret')) + self.set_token(self.config.get('token')) + self.__set_params(self.config) + + @property + def user(self): + return self.config.get('user') + + @user.setter + def user(self, user): + self.config['user'] = user + + @property + def repo(self): + return self.config.get('repo') + + @repo.setter + def repo(self, repo): + self.config['repo'] = repo + + def set_credentials(self, login, password): + if login and password: + self.requester.auth = (login, password) + + def set_oauth_credentials(self, client_id, client_secret): + if client_id and client_secret: + self.requester.params.append(('client_id', client_id)) + self.requester.params.append(('client_secret', client_secret)) + + def set_token(self, token): + if token: + self.requester.params.append(('access_token', token)) + + def __set_params(self, config): + per_page = ('per_page', config.get('per_page')) + self.requester.params.append(per_page) + if config.get('verbose'): + self.requester.config = {'verbose': config['verbose']} + if config.get('timeout'): + self.requester.timeout = config['timeout'] + + def __parse_kwargs(func): + """ Decorator to put extra args into requests.params """ + + def wrapper(self, verb, request, **kwargs): + diffs = set(kwargs.keys()) - VALID_REQUEST_ARGS + new_params = kwargs.get('params', {}) + for key in diffs: # Put each key in new_params and delete it + new_params[key] = kwargs[key] + del kwargs[key] + kwargs['params'] = new_params + return func(self, verb, request, **kwargs) + return wrapper + + @__parse_kwargs + def request(self, verb, request, **kwargs): + request = "%s%s" % (self.config['base_url'], request) + response = self.requester.request(verb, request, **kwargs) + Client.remaining_requests = response.headers.get( + 'x-ratelimit-remaining', -1) + GithubError(response).process() + return response + + def get(self, request, **kwargs): + response = self.request('get', request, **kwargs) + assert response.status_code == 200 + return response + + def post(self, request, **kwargs): + response = self.request('post', request, **kwargs) + assert response.status_code == 201 + return response + + def patch(self, request, **kwargs): + response = self.request('patch', request, **kwargs) + assert response.status_code == 200 + return response + + def put(self, request, **kwargs): + response = self.request('put', request, **kwargs) + # assert response.status_code != '204' + # I don't do an assert. See `services.base.Service._put` comment + return response + + def delete(self, request, **kwargs): + response = self.request('delete', request, **kwargs) + assert response.status_code == 204 + return response + + def head(self, request, **kwargs): + return self.request('head', request, **kwargs) diff --git a/pygithub3/core/compat.py b/pygithub3/core/compat.py new file mode 100644 index 0000000..c6dbf0a --- /dev/null +++ b/pygithub3/core/compat.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- +""" Utils to support python 2.6 compatibility """ + +from collections import MutableMapping + + +def _import_module(module_uri): + return __import__(module_uri, {}, {}, ['']) + + +def import_module(module_uri): + """ Import module by string 'from.path.module' + + To support python 2.6 + """ + try: + from importlib import import_module + callback = import_module + except ImportError: + callback = _import_module + + return callback(module_uri) + + +class _OrderedDict(dict, MutableMapping): + """ + Src: http://code.activestate.com/recipes/576669/ + Author: Raymond Hettinger (Promoter of PEP which introduces OrderDict into + colletions module in python >2.7) + """ + + # Methods with direct access to underlying attributes + + def __init__(self, *args, **kwds): + if len(args) > 1: + raise TypeError('expected at 1 argument, got %d', len(args)) + if not hasattr(self, '_keys'): + self._keys = [] + self.update(*args, **kwds) + + def clear(self): + del self._keys[:] + dict.clear(self) + + def __setitem__(self, key, value): + if key not in self: + self._keys.append(key) + dict.__setitem__(self, key, value) + + def __delitem__(self, key): + dict.__delitem__(self, key) + self._keys.remove(key) + + def __iter__(self): + return iter(self._keys) + + def __reversed__(self): + return reversed(self._keys) + + def popitem(self): + if not self: + raise KeyError + key = self._keys.pop() + value = dict.pop(self, key) + return key, value + + def __reduce__(self): + items = [[k, self[k]] for k in self] + inst_dict = vars(self).copy() + inst_dict.pop('_keys', None) + return (self.__class__, (items,), inst_dict) + + # Methods with indirect access via the above methods + + setdefault = MutableMapping.setdefault + update = MutableMapping.update + pop = MutableMapping.pop + keys = MutableMapping.keys + values = MutableMapping.values + items = MutableMapping.items + + def __repr__(self): + pairs = ', '.join(map('%r: %r'.__mod__, self.items())) + return '%s({%s})' % (self.__class__.__name__, pairs) + + def copy(self): + return self.__class__(self) + + @classmethod + def fromkeys(cls, iterable, value=None): + d = cls() + for key in iterable: + d[key] = value + return d + +try: + from collections import OrderedDict +except ImportError: + OrderedDict = _OrderedDict diff --git a/pygithub3/core/errors.py b/pygithub3/core/errors.py new file mode 100644 index 0000000..d86b2dd --- /dev/null +++ b/pygithub3/core/errors.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- + +from pygithub3.core import json +from pygithub3.exceptions import NotFound, BadRequest, UnprocessableEntity + + +class GithubError(object): + """ Handler for API errors """ + + def __init__(self, response): + self.response = response + self.status_code = response.status_code + try: + self.debug = json.loads(response.content) + except (ValueError, TypeError): + self.debug = {'message': response.content} + + def error_404(self): + raise NotFound("404 - %s" % self.debug.get('message')) + + def error_400(self): + raise BadRequest("400 - %s" % self.debug.get('message')) + + def error_422(self): + errors = self.debug.get('errors', ()) + errors = ['Resource: {resource}: {field} => {code}'.format(**error) + for error in errors] + raise UnprocessableEntity( + '422 - %s %s' % (self.debug.get('message'), errors)) + + def process(self): + raise_error = getattr(self, 'error_%s' % self.status_code, False) + if raise_error: + raise raise_error() + self.response.raise_for_status() diff --git a/pygithub3/core/json/__init__.py b/pygithub3/core/json/__init__.py new file mode 100644 index 0000000..f0adb20 --- /dev/null +++ b/pygithub3/core/json/__init__.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +""" +Emulate json module with encode/decoders to support github datetime format +""" + +from datetime import datetime +try: + import simplejson as json +except ImportError: + import json + +GITHUB_DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ' + + +class GHJSONEncoder(json.JSONEncoder): + def default(self, o): + try: + return datetime.strftime(o, GITHUB_DATE_FORMAT) + except: + return super(GHJSONEncoder, self).default(o) + + +def gh_decoder_hook(dict_): + for k, v in dict_.iteritems(): + try: + date = datetime.strptime(v, GITHUB_DATE_FORMAT) + dict_[k] = date + except: + continue + return dict_ + + +def dumps(obj, cls=GHJSONEncoder, **kwargs): + return json.dumps(obj, cls=cls, **kwargs) + + +def loads(s, object_hook=gh_decoder_hook, **kwargs): + return json.loads(s, object_hook=object_hook, **kwargs) + +dump = json.dump +load = json.load diff --git a/pygithub3/core/result/__init__.py b/pygithub3/core/result/__init__.py new file mode 100644 index 0000000..dae354a --- /dev/null +++ b/pygithub3/core/result/__init__.py @@ -0,0 +1 @@ +# -*- encoding: utf-8 -*- diff --git a/pygithub3/core/result/base.py b/pygithub3/core/result/base.py new file mode 100644 index 0000000..b33f97e --- /dev/null +++ b/pygithub3/core/result/base.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- + +import functools + + +class Method(object): + """ It wraps the requester method, with behaviour to results """ + + def __init__(self, method, request, **method_args): + self.method = functools.partial(method, request, **method_args) + self.resource = request.resource + self.cache = {} + + def __call__(self): + raise NotImplementedError + + +class Page(object): + """ Iterator of resources """ + + def __init__(self, getter, page=1): + self.getter = getter + self.page = page + + def __iter__(self): + return self + + def __add__(self, number): + return self.page + number + + def __radd__(self, number): + return number + self.page + + def __sub__(self, number): + return self.page - number + + def __rsub__(self, number): + return number - self.page + + def __lt__(self, number): + return self.page < number + + def __le__(self, number): + return self.page <= number + + def __eq__(self, number): + return self.page == number + + def __ne__(self, number): + return self.page != number + + def __gt__(self, number): + return self.page > number + + def __ge__(self, number): + return self.page >= number + + @property + def resources(self): + return getattr(self, 'count', None) or '~' + + def get_content(func): + def wrapper(self): + if not hasattr(self, 'count'): + content = self.getter(self.page) + self.count = len(content) + self.iterable = iter(content) + return func(self) + return wrapper + + @get_content + def __next__(self): + try: + return self.iterable.next() + except StopIteration: + self.iterable = iter(self.getter(self.page)) + raise StopIteration + + def next(self): + return self.__next__() + + def __str__(self): + return '<{name}{page} resources={resources}>'.format( + name=self.__class__.__name__, + page=self.page, + resources=self.resources) + + +class Result(object): + """ Iterator of pages """ + + def __init__(self, method): + self.getter = method + + def __iter__(self): + return self + + def next(self): + return self.__next__() + + def iterator(self): + """ generator """ + for page in self: + for resource in page: + yield resource + + def all(self): + return list(self.iterator()) diff --git a/pygithub3/core/result/link.py b/pygithub3/core/result/link.py new file mode 100644 index 0000000..dae8407 --- /dev/null +++ b/pygithub3/core/result/link.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- + +from urlparse import urlparse, parse_qs + +from pygithub3.core.third_libs.link_header import parse_link_value + + +class Link(str): + + class Url(str): + + @property + def query(self): + return urlparse(self).query + + @property + def params(self): + return dict([ + (param, values.pop()) + for param, values in parse_qs(self.query).items()]) + + def __init__(self, object_): + str.__init__(object_) + parsed = parse_link_value(self) + for url in parsed: + setattr(self, parsed[url]['rel'], Link.Url(url)) diff --git a/pygithub3/core/result/normal.py b/pygithub3/core/result/normal.py new file mode 100644 index 0000000..7f0e888 --- /dev/null +++ b/pygithub3/core/result/normal.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- + +from . import base +from .link import Link + + +class Method(base.Method): + """ Cache support and builds next request """ + + def __init__(self, *args, **kwargs): + super(Method, self).__init__(*args, **kwargs) + self.next = True + + def cached(func): + def wrapper(self, page=1): + if str(page) in self.cache: + return self.cache[str(page)]['content'] + return func(self, page) + return wrapper + + def next_getter_from(self, response): + link = Link(response.headers.get('link')) + if hasattr(link, 'next'): + return base.functools.partial(self.method, **link.next.params) + self.next = False + + @cached + def __call__(self, page=1): + prev = self.cache.get(str(page - 1)) + method = prev and prev['next'] or self.method + response = method() + self.cache[str(page)] = { + 'content': self.resource.loads(response.content), + 'next': self.next_getter_from(response) + } + return self.cache[str(page)]['content'] + + +class Page(base.Page): + """ Consumed when instance """ + + def __init__(self, getter, page=1): + super(Page, self).__init__(getter, page) + content = getter(page) + self.iterable = iter(content) + self.count = len(content) + + +class Result(base.Result): + """ + It's a middle-lazy iterator, because to get a new page it needs + make a real request, besides it's **cached**, so never repeats a request. + + You have several ways to consume it + + #. Iterating over the result:: + + result = some_request() + for page in result: + for resource in page: + print resource + + #. With a generator:: + + result = some_request() + for resource in result.iterator(): + print resource + + #. As a list:: + + result = some_request() + print result.all() + + """ + + """ TODO: limit in {all/iterator} + .. note:: + You can use ``limit`` with `all` and `iterator` + :: + result = some_request() + _5resources = result.all(limit=5) + + This exists because it can't request a explitic page, and some requests + can have thousand of resources (e.g Repository's commits) + """ + + def __init__(self, method): + super(Result, self).__init__(method) + self._counter = 0 + self._cached = False + + def _get_cached(func): + def wrapper(self): + if self._cached: + if str(self._counter) in self.getter.cache: + page = Page(self.getter, self._counter) + self._counter += 1 + return page + self._reset() + raise StopIteration + return func(self) + return wrapper + + @_get_cached + def __next__(self): + if self.getter.next: + self._counter += 1 + return Page(self.getter, self._counter) + self._reset() + raise StopIteration + + def _reset(self): + self._counter = 1 + self._cached = True diff --git a/pygithub3/core/result/smart.py b/pygithub3/core/result/smart.py new file mode 100644 index 0000000..0343a9b --- /dev/null +++ b/pygithub3/core/result/smart.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- + +from . import base +from .link import Link + + +class Method(base.Method): + """ Lazy and cache support """ + + def cached(func): + """ Decorator to don't do a request if it's cached """ + def wrapper(self, page=1): + if str(page) in self.cache: + return self.cache[str(page)] + return func(self, page) + return wrapper + + def if_needs_lastpage(func): + """ Decorator to set last page only if it can and it hasn't retrieved + before """ + def wrapper(self, has_link): + has_last_page = hasattr(self, 'last_page') + if not has_last_page and has_link: + return func(self, has_link) + elif not has_last_page and not has_link: + self.last_page = 1 + return wrapper + + @if_needs_lastpage + def __set_last_page_from(self, link_header): + """ Get and set last_page form link header """ + link = Link(link_header) + self.last_page = int(link.last.params.get('page')) + + @cached + def __call__(self, page=1): + """ Call a real request """ + response = self.method(page=page) + self.__set_last_page_from(response.headers.get('link')) + self.cache[str(page)] = self.resource.loads(response.content) + return self.cache[str(page)] + + @property + def last(self): + if not hasattr(self, 'last_page'): + self() + return self.last_page + + +class Result(base.Result): + """ + It's a very **lazy** paginator beacuse only do a real request + when is needed, besides it's **cached**, so never repeats a request. + + You have several ways to consume it + + #. Iterating over the result:: + + result = some_request() + for page in result: + for resource in page: + print resource + + #. With a generator:: + + result = some_request() + for resource in result.iterator(): + print resource + + #. As a list:: + + result = some_request() + print result.all() + + #. Also you can request some page manually + + Each ``Page`` is an iterator and contains resources:: + + result = some_request() + assert result.pages > 3 + page3 = result.get_page(3) + page3_resources = list(page3) + """ + + def __init__(self, method): + super(Result, self).__init__(method) + self.page = base.Page(self.getter) + + def __next__(self): + if self.page <= self.pages: + page_to_return = self.page + self.page = base.Page(self.getter, page_to_return + 1) + return page_to_return + self.page = base.Page(self.getter) + raise StopIteration + + @property + def pages(self): + """ Total number of pages in request """ + return self.getter.last + + def get_page(self, page): + """ Get ``Page`` of resources + + :param int page: Page number + """ + if page in xrange(1, self.pages + 1): + return base.Page(self.getter, page) + return None diff --git a/pygithub3/core/third_libs/__init__.py b/pygithub3/core/third_libs/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/github3/packages/link_header.py b/pygithub3/core/third_libs/link_header.py similarity index 97% rename from github3/packages/link_header.py rename to pygithub3/core/third_libs/link_header.py index 5ad20f1..3959604 100644 --- a/github3/packages/link_header.py +++ b/pygithub3/core/third_libs/link_header.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -# -*- encoding: utf-8 -*- """ HTTP Link Header Parsing @@ -87,4 +86,4 @@ def parse_link_value(instr): if __name__ == '__main__': import sys if len(sys.argv) > 1: - print parse_link_value(sys.argv[1]) + print parse_link_value(sys.argv[1]) \ No newline at end of file diff --git a/pygithub3/exceptions.py b/pygithub3/exceptions.py new file mode 100644 index 0000000..9ee2597 --- /dev/null +++ b/pygithub3/exceptions.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- + + +class InvalidBodySchema(Exception): + """ Raised when the 'valids_body' attribute of Resource isn't in a + valid form (required.issubsetof(schema))""" + pass + + +class RequestDoesNotExist(Exception): + """ Raised when `Request` factory can't find the subclass """ + pass + + +class UriInvalid(Exception): + """ Raised when `Request` factory's maker isn't in a valid form """ + pass + + +class ValidationError(Exception): + """ Raised when a `Request` doesn't have the necessary args to make a + valid URI """ + pass + + +class BadRequest(Exception): + """ Raised when server response is 400 """ + pass + + +class UnprocessableEntity(Exception): + """ Raised when server response is 400 """ + pass + + +class NotFound(Exception): + """ Raised when server response is 404 + + Caught with a pygithub3-exception to `services.base.Service._bool` method + """ + pass diff --git a/pygithub3/github.py b/pygithub3/github.py new file mode 100644 index 0000000..d64577c --- /dev/null +++ b/pygithub3/github.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- + + +#TODO: Move the imports out. setup related +class Github(object): + """ + You can preconfigure all services globally with a ``config`` dict. See + :attr:`~pygithub3.services.base.Service` + + Example:: + + gh = Github(user='kennethreitz', token='ABC...', repo='requests') + """ + + def __init__(self, **config): + from pygithub3.services.users import User + from pygithub3.services.repos import Repo + from pygithub3.services.gists import Gist + from pygithub3.services.events import Event + from pygithub3.services.git_data import GitData + from pygithub3.services.pull_requests import PullRequests + from pygithub3.services.orgs import Org + from pygithub3.services.issues import Issue + self._users = User(**config) + self._repos = Repo(**config) + self._gists = Gist(**config) + self._git_data = GitData(**config) + self._pull_requests = PullRequests(**config) + self._orgs = Org(**config) + self._issues = Issue(**config) + self._events = Event(**config) + + @property + def remaining_requests(self): + """ Limit of Github API v3 """ + from pygithub3.core.client import Client + return Client.remaining_requests + + @property + def users(self): + """ + :ref:`Users service ` + """ + return self._users + + @property + def repos(self): + """ + :ref:`Repos service ` + """ + return self._repos + + @property + def gists(self): + """ + :ref:`Gists service ` + """ + return self._gists + + @property + def git_data(self): + """ + :ref:`Git Data service ` + """ + return self._git_data + + @property + def pull_requests(self): + """ + :ref:`Pull Requests service ` + """ + return self._pull_requests + + @property + def orgs(self): + """ + :ref:`Orgs service ` + """ + return self._orgs + + @property + def issues(self): + """ + :ref:`Issues service ` + """ + return self._issues + + @property + def events(self): + """ + :ref:`Events service ` + """ + return self._events diff --git a/pygithub3/requests/__init__.py b/pygithub3/requests/__init__.py new file mode 100644 index 0000000..dae354a --- /dev/null +++ b/pygithub3/requests/__init__.py @@ -0,0 +1 @@ +# -*- encoding: utf-8 -*- diff --git a/pygithub3/requests/base.py b/pygithub3/requests/base.py new file mode 100644 index 0000000..7eb0ff3 --- /dev/null +++ b/pygithub3/requests/base.py @@ -0,0 +1,126 @@ +# -*- encoding: utf-8 -*- + +import re + +from pygithub3.core import json +from pygithub3.core.compat import import_module +from pygithub3.exceptions import (RequestDoesNotExist, UriInvalid, + ValidationError, InvalidBodySchema) +from pygithub3.resources.base import Raw + +ABS_IMPORT_PREFIX = 'pygithub3.requests' + + +class Body(object): + """ Input's request handler """ + + def __init__(self, content, schema, required): + self.content = content + self.schema = schema + self.required = required + + def dumps(self): + if not self.schema: + return self.content or None + return json.dumps(self.parse()) + + def parse(self): + """ Parse body with schema-required rules """ + if not hasattr(self.content, 'items'): + raise ValidationError("It needs a content dictionary (%s)" % ( + self.content, )) + parsed = dict([(key, self.content[key]) for key in self.schema + if key in self.content]) + for attr_required in self.required: + if attr_required not in parsed: + raise ValidationError("'%s' attribute is required" % + attr_required) + if parsed[attr_required] is None: + raise ValidationError("'%s' attribute can't be empty" % + attr_required) + return parsed + + +class Request(object): + + uri = '' + resource = Raw + body_schema = {} + + def __init__(self, **kwargs): + self.body = kwargs.pop('body', {}) + self.args = kwargs + self.clean() + + def __getattr__(self, name): + return self.args.get(name) + + def __str__(self): + return self.populate_uri() + + def populate_uri(self): + try: + populated_uri = self.uri.format(**self.args) + except KeyError: + raise ValidationError( + "'%s' request wasn't be able to populate the uri '%s' with " + "'%s' args" % (self.__class__.__name__, self.uri, self.args)) + return str(populated_uri).strip('/') + + def clean(self): + self.uri = self.clean_uri() or self.uri + self.body = Body(self.clean_body(), **self._clean_valid_body()) + + def clean_body(self): + return self.body + + def clean_uri(self): + return None + + def _clean_valid_body(self): + schema = set(self.body_schema.get('schema', ())) + required = set(self.body_schema.get('required', ())) + if not required.issubset(schema): + raise InvalidBodySchema( + "'%s:valid_body' attribute is invalid. " + "'%s required' isn't a subset of '%s schema'" % ( + self.__class__.__name__, required, schema)) + return dict(schema=schema, required=required) + + def get_body(self): + return self.body.dumps() + + +class Factory(object): + """ Request builder """ + + import_pattern = re.compile(r'^(\w+\.)+\w+$') + + def validate(func): + """ Decorator to check if request_uri + has valid format: 'from.path.module.class' """ + + def wrapper(self, request_uri, **kwargs): + if not Factory.import_pattern.match(request_uri): + raise UriInvalid("'%s' isn't valid form" % request_uri) + return func(self, request_uri.lower(), **kwargs) + return wrapper + + @validate + def __call__(self, request_uri, **kwargs): + module_chunk, s, request_chunk = request_uri.rpartition('.') + request_chunk = request_chunk.capitalize() + try: + # TODO: CamelCase and under_score support, now only Class Name + module = import_module('%s.%s' % (ABS_IMPORT_PREFIX, module_chunk)) + request_class = getattr(module, request_chunk) + request = request_class(**kwargs) + assert isinstance(request, Request) + return request + except ImportError: + raise RequestDoesNotExist("'%s' module does not exist" + % module_chunk) + except AttributeError: + raise RequestDoesNotExist("'%s' request does not exist in " + "'%s' module" % (request_chunk, + module_chunk)) diff --git a/pygithub3/requests/events/__init__.py b/pygithub3/requests/events/__init__.py new file mode 100644 index 0000000..fd4988f --- /dev/null +++ b/pygithub3/requests/events/__init__.py @@ -0,0 +1,10 @@ +# -*- encoding: utf-8 -*- + +from pygithub3.requests.base import Request +from pygithub3.resources.events import Event + + +class List(Request): + + uri = 'events' + resource = Event diff --git a/pygithub3/requests/events/networks.py b/pygithub3/requests/events/networks.py new file mode 100644 index 0000000..e510773 --- /dev/null +++ b/pygithub3/requests/events/networks.py @@ -0,0 +1,10 @@ +# -*- encoding: utf-8 -*- + +from . import Request +from pygithub3.resources.events import Network + + +class List(Request): + + uri = 'networks/{user}/{repo}/events' + resource = Network diff --git a/pygithub3/requests/events/orgs.py b/pygithub3/requests/events/orgs.py new file mode 100644 index 0000000..c8e9fc7 --- /dev/null +++ b/pygithub3/requests/events/orgs.py @@ -0,0 +1,10 @@ +# -*- encoding: utf-8 -*- + +from . import Request +from pygithub3.resources.events import Org + + +class List(Request): + + uri = 'orgs/{org}/events' + resource = Org diff --git a/pygithub3/requests/events/repos.py b/pygithub3/requests/events/repos.py new file mode 100644 index 0000000..6bb2f98 --- /dev/null +++ b/pygithub3/requests/events/repos.py @@ -0,0 +1,10 @@ +# -*- encoding: utf-8 -*- + +from . import Request +from pygithub3.resources.events import Repo + + +class List(Request): + + uri = 'repos/{user}/{repo}/events' + resource = Repo diff --git a/pygithub3/requests/events/users.py b/pygithub3/requests/events/users.py new file mode 100644 index 0000000..a8556ae --- /dev/null +++ b/pygithub3/requests/events/users.py @@ -0,0 +1,34 @@ +# -*- encoding: utf-8 -*- + +from . import Request +from pygithub3.resources.events import User, Org + + +class List_received(Request): + + uri = 'users/{user}/received_events' + resource = User + + +class List_received_public(Request): + + uri = 'users/{user}/received_events/public' + resource = User + + +class List_performed(Request): + + uri = 'users/{user}/events' + resource = User + + +class List_performed_public(Request): + + uri = 'users/{user}/events/public' + resource = User + + +class List_org_events(Request): + + uri = 'users/{user}/events/orgs/{org}' + resource = Org diff --git a/pygithub3/requests/gists/__init__.py b/pygithub3/requests/gists/__init__.py new file mode 100644 index 0000000..a8d92b7 --- /dev/null +++ b/pygithub3/requests/gists/__init__.py @@ -0,0 +1,78 @@ +# -*- encoding: utf-8 -*- + +from pygithub3.requests.base import Request +from pygithub3.resources.gists import Gist + + +class List(Request): + + uri = 'users/{user}/gists' + resource = Gist + + def clean_uri(self): + if not self.user: + return 'gists' + + +class Public(Request): + + uri = 'gists/public' + resource = Gist + + +class Starred(Request): + + uri = 'gists/starred' + resource = Gist + + +class Get(Request): + + uri = 'gists/{id}' + resource = Gist + + +class Create(Request): + + uri = 'gists' + resource = Gist + body_schema = { + 'schema': ('description', 'public', 'files'), + 'required': ('public', 'files') + } + + +class Update(Request): + + uri = 'gists/{id}' + resource = Gist + body_schema = { + 'schema': ('description', 'public', 'files'), + 'required': (), + } + + +class Star(Request): + + uri = 'gists/{id}/star' + + +class Unstar(Request): + + uri = 'gists/{id}/star' + + +class Is_starred(Request): + + uri = 'gists/{id}/star' + + +class Fork(Request): + + uri = 'gists/{id}/fork' + resource = Gist + + +class Delete(Request): + + uri = 'gists/{id}' diff --git a/pygithub3/requests/gists/comments.py b/pygithub3/requests/gists/comments.py new file mode 100644 index 0000000..1da78cb --- /dev/null +++ b/pygithub3/requests/gists/comments.py @@ -0,0 +1,41 @@ +# -*- encoding: utf-8 -*- + +from pygithub3.requests.base import Request +from pygithub3.resources.gists import Comment + + +class List(Request): + + uri = 'gists/{gist_id}/comments' + resource = Comment + + +class Get(Request): + + uri = 'gists/comments/{id}' + resource = Comment + + +class Create(Request): + + uri = 'gists/{gist_id}/comments' + resource = Comment + body_schema = { + 'schema': ('body', ), + 'required': ('body', ) + } + + +class Update(Request): + + uri = 'gists/comments/{id}' + resource = Comment + body_schema = { + 'schema': ('body', ), + 'required': ('body', ) + } + + +class Delete(Request): + + uri = 'gists/comments/{id}' diff --git a/pygithub3/requests/git_data/__init__.py b/pygithub3/requests/git_data/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/pygithub3/requests/git_data/blobs.py b/pygithub3/requests/git_data/blobs.py new file mode 100644 index 0000000..a4bddd6 --- /dev/null +++ b/pygithub3/requests/git_data/blobs.py @@ -0,0 +1,18 @@ +# -*- encoding: utf-8 -*- + +from pygithub3.requests.base import Request +from pygithub3.resources.git_data import Blob + + +class Get(Request): + uri = 'repos/{user}/{repo}/git/blobs/{sha}' + resource = Blob + + +class Create(Request): + uri = 'repos/{user}/{repo}/git/blobs' + resource = Blob + body_schema = { + 'schema': ('content', 'encoding'), + 'required': ('content', 'encoding'), # TODO: is enc really required? + } diff --git a/pygithub3/requests/git_data/commits.py b/pygithub3/requests/git_data/commits.py new file mode 100644 index 0000000..a26e07d --- /dev/null +++ b/pygithub3/requests/git_data/commits.py @@ -0,0 +1,18 @@ +# -*- encoding: utf-8 -*- + +from pygithub3.requests.base import Request +from pygithub3.resources.repos import Commit + + +class Get(Request): + uri = 'repos/{user}/{repo}/git/commits/{sha}' + resource = Commit + + +class Create(Request): + uri = 'repos/{user}/{repo}/git/commits' + resource = Commit + body_schema = { + 'schema': ('message', 'tree', 'parents', 'author', 'committer'), + 'required': ('message', 'tree', 'parents'), + } diff --git a/pygithub3/requests/git_data/references.py b/pygithub3/requests/git_data/references.py new file mode 100644 index 0000000..9824bdb --- /dev/null +++ b/pygithub3/requests/git_data/references.py @@ -0,0 +1,36 @@ +# -*- encoding: utf-8 -*- + +from pygithub3.requests.base import Request +from pygithub3.resources.git_data import Reference + + +class Get(Request): + uri = 'repos/{user}/{repo}/git/refs/{ref}' + resource = Reference + + +class List(Request): + uri = 'repos/{user}/{repo}/git/refs/{namespace}' + resource = Reference + + +class Create(Request): + uri = 'repos/{user}/{repo}/git/refs' + resource = Reference + body_schema = { + 'schema': ('ref', 'sha'), + 'required': ('ref', 'sha'), + } + + +class Update(Request): + uri = 'repos/{user}/{repo}/git/refs/{ref}' + resource = Reference + body_schema = { + 'schema': ('sha', 'force'), + 'required': ('sha',), + } + + +class Delete(Request): + uri = 'repos/{user}/{repo}/git/refs/{ref}' diff --git a/pygithub3/requests/git_data/tags.py b/pygithub3/requests/git_data/tags.py new file mode 100644 index 0000000..88a79c0 --- /dev/null +++ b/pygithub3/requests/git_data/tags.py @@ -0,0 +1,18 @@ +# -*- encoding: utf-8 -*- + +from pygithub3.requests.base import Request +from pygithub3.resources.git_data import Tag + + +class Get(Request): + uri = 'repos/{user}/{repo}/git/tags/{sha}' + resource = Tag + + +class Create(Request): + uri = 'repos/{user}/{repo}/git/tags' + resource = Tag + body_schema = { + 'schema': ('tag', 'message', 'object', 'type', 'tagger'), + 'required': ('type',), + } diff --git a/pygithub3/requests/git_data/trees.py b/pygithub3/requests/git_data/trees.py new file mode 100644 index 0000000..11d6409 --- /dev/null +++ b/pygithub3/requests/git_data/trees.py @@ -0,0 +1,16 @@ +from pygithub3.requests.base import Request +from pygithub3.resources.git_data import Tree + + +class Get(Request): + uri = 'repos/{user}/{repo}/git/trees/{sha}' + resource = Tree + + +class Create(Request): + uri = 'repos/{user}/{repo}/git/trees' + resource = Tree + body_schema = { + 'schema': ('tree', 'base_tree'), + 'required': ('tree',), + } diff --git a/pygithub3/requests/issues/__init__.py b/pygithub3/requests/issues/__init__.py new file mode 100644 index 0000000..d6c7b06 --- /dev/null +++ b/pygithub3/requests/issues/__init__.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- + +from pygithub3.requests.base import Request +from pygithub3.resources.issues import Issue + + +class List(Request): + + uri = 'issues' + resource = Issue + + +class List_by_repo(Request): + + uri = 'repos/{user}/{repo}/issues' + resource = Issue + + +class Get(Request): + + uri = 'repos/{user}/{repo}/issues/{number}' + resource = Issue + + +class Create(Request): + + uri = 'repos/{user}/{repo}/issues' + resource = Issue + body_schema = { + 'schema': ('title', 'body', 'assignee', 'milestone', 'labels'), + 'required': ('title', ) + } + + +class Update(Request): + + uri = 'repos/{user}/{repo}/issues/{number}' + resource = Issue + body_schema = { + 'schema': ('title', 'body', 'assignee', 'state', 'milestone', + 'lables'), + 'required': () + } diff --git a/pygithub3/requests/issues/comments.py b/pygithub3/requests/issues/comments.py new file mode 100644 index 0000000..c9618a8 --- /dev/null +++ b/pygithub3/requests/issues/comments.py @@ -0,0 +1,42 @@ +# -*- encoding: utf-8 -*- + +from pygithub3.requests.base import Request +from pygithub3.resources.issues import Comment + + +class List(Request): + + uri = 'repos/{user}/{repo}/issues/{number}/comments' + resource = Comment + + +class Get(Request): + + uri = 'repos/{user}/{repo}/issues/comments/{id}' + resource = Comment + + +class Create(Request): + + uri = 'repos/{user}/{repo}/issues/{number}/comments' + resource = Comment + body_schema = { + 'schema': ('body', ), + 'required': ('body', ) + } + + +class Edit(Request): + + uri = 'repos/{user}/{repo}/issues/comments/{id}' + resource = Comment + body_schema = { + 'schema': ('body', ), + 'required': ('body', ) + } + + +class Delete(Request): + + uri = 'repos/{user}/{repo}/issues/comments/{id}' + resource = Comment diff --git a/pygithub3/requests/issues/events.py b/pygithub3/requests/issues/events.py new file mode 100644 index 0000000..d284681 --- /dev/null +++ b/pygithub3/requests/issues/events.py @@ -0,0 +1,22 @@ +# -*- encoding: utf-8 -*- + +from pygithub3.requests.base import Request +from pygithub3.resources.issues import Event + + +class List_by_issue(Request): + + uri = 'repos/{user}/{repo}/issues/{number}/events' + resource = Event + + +class List_by_repo(Request): + + uri = 'repos/{user}/{repo}/issues/events' + resource = Event + + +class Get(Request): + + uri = 'repos/{user}/{repo}/issues/events/{id}' + resource = Event diff --git a/pygithub3/requests/issues/labels.py b/pygithub3/requests/issues/labels.py new file mode 100644 index 0000000..7ba6c7a --- /dev/null +++ b/pygithub3/requests/issues/labels.py @@ -0,0 +1,77 @@ +# -*- encoding: utf-8 -*- + +from pygithub3.requests.base import Request, ValidationError +from pygithub3.resources.issues import Label + + +class List(Request): + + uri = 'repos/{user}/{repo}/labels' + resource = Label + + +class Get(Request): + uri = 'repos/{user}/{repo}/labels/{name}' + resource = Label + + +class Create(Request): + uri = 'repos/{user}/{repo}/labels' + resource = Label + body_schema = { + 'schema': ('name', 'color'), + 'required': ('name', 'color') + } + + def clean_body(self): + color = self.body.get('color', '') + if not Label.is_valid_color(color): + raise ValidationError('colors must have 6 hexadecimal characters, ' + 'without # in the beggining') + else: + return self.body + + +class Update(Create): + + uri = 'repos/{user}/{repo}/labels/{name}' + resource = Label + body_schema = { + 'schema': ('name', 'color'), + 'required': ('name', 'color') + } + + +class Delete(Request): + uri = 'repos/{user}/{repo}/labels/{name}' + resource = Label + + +class List_by_issue(Request): + uri = 'repos/{user}/{repo}/issues/{number}/labels' + resource = Label + + +class Add_to_issue(Request): + uri = 'repos/{user}/{repo}/issues/{number}/labels' + resource = Label + + +class Remove_from_issue(Request): + uri = 'repos/{user}/{repo}/issues/{number}/labels/{name}' + resource = Label + + +class Replace_all(Request): + uri = 'repos/{user}/{repo}/issues/{number}/labels' + resource = Label + + +class Remove_all(Request): + uri = 'repos/{user}/{repo}/issues/{number}/labels' + resource = Label + + +class List_by_milestone(Request): + uri = 'repos/{user}/{repo}/milestones/{number}/labels' + resource = Label diff --git a/pygithub3/requests/issues/milestones.py b/pygithub3/requests/issues/milestones.py new file mode 100644 index 0000000..4093c7e --- /dev/null +++ b/pygithub3/requests/issues/milestones.py @@ -0,0 +1,39 @@ +# -*- encoding: utf-8 -*- + +from pygithub3.requests.base import Request, ValidationError +from pygithub3.resources.issues import Milestone + + +class List(Request): + uri = 'repos/{user}/{repo}/milestones' + resource = Milestone + + +class Get(Request): + uri = 'repos/{user}/{repo}/milestones/{number}' + resource = Milestone + + +class Create(Request): + uri = 'repos/{user}/{repo}/milestones' + resource = Milestone + body_schema = { + 'schema': ('title', 'state', 'description', 'due_on'), + 'required': ('title',) + } + + def clean_body(self): # Test if API normalize it + state = self.body.get('state', '') + if state and state.lower() not in ('open', 'closed'): + raise ValidationError("'state' must be 'open' or 'closed'") + return self.body + + +class Update(Create): + + uri = 'repos/{user}/{repo}/milestones/{number}' + + +class Delete(Request): + uri = 'repos/{user}/{repo}/milestones/{number}' + resource = Milestone diff --git a/pygithub3/requests/orgs/__init__.py b/pygithub3/requests/orgs/__init__.py new file mode 100644 index 0000000..deba5ef --- /dev/null +++ b/pygithub3/requests/orgs/__init__.py @@ -0,0 +1,27 @@ +# -*- encoding: utf-8 -*- + +from pygithub3.requests.base import Request +from pygithub3.resources.orgs import Org + + +class List(Request): + uri = 'users/{user}/orgs' + resource = Org + + def clean_uri(self): + if not self.user: + return 'user/orgs' + + +class Get(Request): + uri = 'orgs/{org}' + resource = Org + + +class Update(Request): + uri = 'orgs/{org}' + resource = Org + body_schema = { + 'schema': ('billing_email', 'company', 'email', 'location', 'name'), + 'required': (), + } diff --git a/pygithub3/requests/orgs/members.py b/pygithub3/requests/orgs/members.py new file mode 100644 index 0000000..a6b05c2 --- /dev/null +++ b/pygithub3/requests/orgs/members.py @@ -0,0 +1,34 @@ +# -*- encoding: utf-8 -*- + +from pygithub3.resources.orgs import Member +from . import Request + + +class List(Request): + uri = 'orgs/{org}/members' + resource = Member + + +class Is_member(Request): + uri = 'orgs/{org}/members/{user}' + + +class Delete(Request): + uri = 'orgs/{org}/members/{user}' + + +class Listpublic(Request): + uri = 'orgs/{org}/public_members' + resource = Member + + +class Is_public_member(Request): + uri = 'orgs/{org}/public_members/{user}' + + +class Publicize(Request): + uri = 'orgs/{org}/public_members/{user}' + + +class Conceal(Request): + uri = 'orgs/{org}/public_members/{user}' diff --git a/pygithub3/requests/orgs/teams.py b/pygithub3/requests/orgs/teams.py new file mode 100644 index 0000000..cc92f9c --- /dev/null +++ b/pygithub3/requests/orgs/teams.py @@ -0,0 +1,74 @@ +# -*- encoding: utf-8 -*- + +from pygithub3.resources.orgs import Member, Team +from pygithub3.resources.repos import Repo +from . import Request + + +class List(Request): + uri = 'orgs/{org}/teams' + resource = Team + + +class Get(Request): + uri = 'teams/{id}' + resource = Team + + +class Create(Request): + uri = 'orgs/{org}/teams' + resource = Team + body_schema = { + 'schema': ('name', 'repo_names', 'permission',), + 'required': ('name',), + } + + # TODO: Check if this request fails with invalid permission + #def clean_body(self): + + +class Update(Request): + uri = 'teams/{id}' + resource = Team + body_schema = { + 'schema': ('name', 'permission',), + 'required': ('name',), + } + + +class Delete(Request): + uri = 'teams/{id}' + + +class List_members(Request): + uri = 'teams/{id}/members' + resource = Member + + +class Is_member(Request): + uri = 'teams/{id}/members/{user}' + + +class Add_member(Request): + uri = 'teams/{id}/members/{user}' + + +class Remove_member(Request): + uri = 'teams/{id}/members/{user}' + + +class List_repos(Request): + uri = 'teams/{id}/repos' + resource = Repo + + +class Contains_repo(Request): + uri = 'teams/{id}/repos/{user}/{repo}' + + +class Add_repo(Request): + uri = 'teams/{id}/repos/{user}/{repo}' + + +class Remove_repo(Request): + uri = 'teams/{id}/repos/{user}/{repo}' diff --git a/pygithub3/requests/pull_requests/__init__.py b/pygithub3/requests/pull_requests/__init__.py new file mode 100644 index 0000000..5845dd7 --- /dev/null +++ b/pygithub3/requests/pull_requests/__init__.py @@ -0,0 +1,69 @@ +# -*- encoding: utf-8 -*- + +from pygithub3.requests.base import Request, ValidationError +from pygithub3.resources.pull_requests import PullRequest, File +from pygithub3.resources.repos import Commit + + +class List(Request): + uri = 'repos/{user}/{repo}/pulls' + resource = PullRequest + + +class Get(Request): + uri = 'repos/{user}/{repo}/pulls/{number}' + resource = PullRequest + + +class Create(Request): + uri = 'repos/{user}/{repo}/pulls' + resource = PullRequest + body_schema = { + 'schema': ('title', 'body', 'base', 'head', 'issue'), + 'required': ('base', 'head'), + } + + def clean_body(self): + if (not ('title' in self.body and 'body' in self.body) and + not 'issue' in self.body): + raise ValidationError('pull request creation requires either an ' + 'issue number or a title and body') + return self.body + + +class Update(Request): + uri = 'repos/{user}/{repo}/pulls/{number}' + resource = PullRequest + body_schema = { + 'schema': ('title', 'body', 'state'), + 'required': (), + } + + def clean_body(self): + if ('state' in self.body and + self.body['state'] not in ['open', 'closed']): + raise ValidationError('If a state is specified, it must be one ' + 'of "open" or "closed"') + return self.body + + +class List_commits(Request): + uri = 'repos/{user}/{repo}/pulls/{number}/commits' + resource = Commit + + +class List_files(Request): + uri = 'repos/{user}/{repo}/pulls/{number}/files' + resource = File + + +class Is_merged(Request): + uri = 'repos/{user}/{repo}/pulls/{number}/merge' + + +class Merge(Request): + uri = 'repos/{user}/{repo}/pulls/{number}/merge' + body_schema = { + 'schema': ('commit_message',), + 'required': (), + } diff --git a/pygithub3/requests/pull_requests/comments.py b/pygithub3/requests/pull_requests/comments.py new file mode 100644 index 0000000..1904f6c --- /dev/null +++ b/pygithub3/requests/pull_requests/comments.py @@ -0,0 +1,46 @@ +# -*- encoding: utf-8 -*- + +from pygithub3.requests.base import Request, ValidationError +from pygithub3.resources.pull_requests import Comment + + +class List(Request): + uri = 'repos/{user}/{repo}/pulls/{number}/comments' + resource = Comment + + +class Get(Request): + uri = 'repos/{user}/{repo}/pulls/comments/{number}' + resource = Comment + + +class Create(Request): + uri = 'repos/{user}/{repo}/pulls/{number}/comments' + resource = Comment + body_schema = { + 'schema': ('body', 'commit_id', 'path', 'position', 'in_reply_to'), + 'required': ('body',), + } + + def clean_body(self): + if (not ('commit_id' in self.body and + 'path' in self.body and + 'position' in self.body) and + not 'in_reply_to' in self.body): + raise ValidationError('supply either in_reply_to or commit_id, ' + 'path, and position') + return self.body + + +class Update(Request): + uri = 'repos/{user}/{repo}/pulls/comments/{number}' + resource = Comment + body_schema = { + 'schema': ('body',), + 'required': ('body',), + } + + +class Delete(Request): + uri = 'repos/{user}/{repo}/pulls/comments/{number}' + resource = Comment diff --git a/pygithub3/requests/repos/__init__.py b/pygithub3/requests/repos/__init__.py new file mode 100644 index 0000000..3e48865 --- /dev/null +++ b/pygithub3/requests/repos/__init__.py @@ -0,0 +1,95 @@ +# -*- encoding: utf-8 -*- + +from pygithub3.requests.base import Request +from pygithub3.resources.orgs import Team +from pygithub3.resources.repos import Repo, Tag, Branch +from pygithub3.resources.users import User + + +class List(Request): + + uri = 'users/{user}/repos' + resource = Repo + + def clean_uri(self): + if not self.user: + return 'user/repos' + + +class List_by_org(Request): + + uri = 'orgs/{org}/repos' + resource = Repo + + +class Create(Request): + + uri = 'orgs/{org}/repos' + resource = Repo + body_schema = { + 'schema': ('name', 'description', 'homepage', 'private', 'has_issues', + 'has_wiki', 'has_downloads', 'team_id'), + 'required': ('name', ) + } + + def clean_uri(self): + if not self.org: + return 'user/repos' + + +class Get(Request): + + uri = 'repos/{user}/{repo}' + resource = Repo + + +class Delete(Request): + + uri = 'repos/{user}/{repo}' + resource = Repo + + +class Update(Request): + + uri = 'repos/{user}/{repo}' + resource = Repo + body_schema = { + 'schema': ('name', 'description', 'homepage', 'private', 'has_issues', + 'has_wiki', 'has_downloads', 'team_id'), + 'required': ('name', ) + } + + +class List_contributors(Request): + + uri = 'repos/{user}/{repo}/contributors' + resource = User + + +class List_languages(Request): + + uri = 'repos/{user}/{repo}/languages' + + +class List_teams(Request): + + uri = 'repos/{user}/{repo}/teams' + resource = Team + + +class List_tags(Request): + + uri = 'repos/{user}/{repo}/tags' + resource = Tag + + +class List_branches(Request): + + uri = 'repos/{user}/{repo}/branches' + resource = Branch + + +class Get_branch(Request): + + uri = 'repos/{user}/{repo}/branches/{branch}' + resource = Branch diff --git a/pygithub3/requests/repos/collaborators.py b/pygithub3/requests/repos/collaborators.py new file mode 100644 index 0000000..068a9dc --- /dev/null +++ b/pygithub3/requests/repos/collaborators.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- + +from . import Request +from pygithub3.resources.users import User + + +class List(Request): + + uri = 'repos/{user}/{repo}/collaborators' + resource = User + + +class Is_collaborator(Request): + + uri = 'repos/{user}/{repo}/collaborators/{collaborator}' + + +class Add(Request): + + uri = 'repos/{user}/{repo}/collaborators/{collaborator}' + + +class Delete(Request): + + uri = 'repos/{user}/{repo}/collaborators/{collaborator}' diff --git a/pygithub3/requests/repos/commits.py b/pygithub3/requests/repos/commits.py new file mode 100644 index 0000000..c31ad04 --- /dev/null +++ b/pygithub3/requests/repos/commits.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- + +from . import Request +from pygithub3.resources.repos import GitCommit, Comment, Diff + + +class List(Request): + + uri = 'repos/{user}/{repo}/commits' + resource = GitCommit + + +class Get(Request): + + uri = 'repos/{user}/{repo}/commits/{sha}' + resource = GitCommit + + +class List_comments(Request): + + uri = 'repos/{user}/{repo}/comments' + resource = Comment + + def clean_uri(self): + if self.sha: + return 'repos/{user}/{repo}/commits/{sha}/comments' + + +class Create_comment(Request): + + uri = 'repos/{user}/{repo}/commits/{sha}/comments' + resource = Comment + body_schema = { + 'schema': ('body', 'commit_id', 'line', 'path', 'position'), + 'required': ('body', 'commit_id', 'line', 'path', 'position'), + } + + +class Get_comment(Request): + + uri = 'repos/{user}/{repo}/comments/{comment_id}' + resource = Comment + + +class Update_comment(Request): + + uri = 'repos/{user}/{repo}/comments/{comment_id}' + resource = Comment + body_schema = { + 'schema': ('body', ), + 'required': ('body', ), + } + + +class Compare(Request): + + uri = 'repos/{user}/{repo}/compare/{base}...{head}' + resource = Diff + + +class Delete_comment(Request): + + uri = 'repos/{user}/{repo}/comments/{comment_id}' diff --git a/pygithub3/requests/repos/downloads.py b/pygithub3/requests/repos/downloads.py new file mode 100644 index 0000000..8a9dd91 --- /dev/null +++ b/pygithub3/requests/repos/downloads.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- + +from . import Request + +from pygithub3.resources.repos import Download + + +class List(Request): + + uri = '/repos/{user}/{repo}/downloads' + resource = Download + + +class Get(Request): + + uri = '/repos/{user}/{repo}/downloads/{id}' + resource = Download + + +class Create(Request): + + uri = '/repos/{user}/{repo}/downloads' + resource = Download + body_schema = { + 'schema': ('name', 'size', 'description', 'content_type'), + 'required': ('name', 'size') + } + + +class Delete(Request): + + uri = '/repos/{user}/{repo}/downloads/{id}' + resource = Download diff --git a/pygithub3/requests/repos/forks.py b/pygithub3/requests/repos/forks.py new file mode 100644 index 0000000..b27dde3 --- /dev/null +++ b/pygithub3/requests/repos/forks.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- + +from . import Request + +from pygithub3.resources.repos import Repo + + +class List(Request): + + uri = 'repos/{user}/{repo}/forks' + resource = Repo + + +class Create(Request): + + uri = '/repos/{user}/{repo}/forks' + resource = Repo diff --git a/pygithub3/requests/repos/hooks.py b/pygithub3/requests/repos/hooks.py new file mode 100644 index 0000000..28fbc18 --- /dev/null +++ b/pygithub3/requests/repos/hooks.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- + +from . import Request +from pygithub3.resources.repos import Hook + + +class List(Request): + + uri = 'repos/{user}/{repo}/hooks' + resource = Hook + + +class Get(Request): + + uri = 'repos/{user}/{repo}/hooks/{id}' + resource = Hook + + +class Create(Request): + + uri = 'repos/{user}/{repo}/hooks' + resource = Hook + body_schema = { + 'schema': ('name', 'config', 'events', 'active'), + 'required': ('name', 'config'), + } + + +class Update(Request): + + uri = 'repos/{user}/{repo}/hooks/{id}' + resource = Hook + body_schema = { + 'schema': ('name', 'config', 'events', 'add_events', 'remove_events', + 'active'), + 'required': (), + } + + +class Test(Request): + + uri = 'repos/{user}/{repo}/hooks/{id}/test' + + +class Delete(Request): + + uri = 'repos/{user}/{repo}/hooks/{id}' diff --git a/pygithub3/requests/repos/keys.py b/pygithub3/requests/repos/keys.py new file mode 100644 index 0000000..9a73d05 --- /dev/null +++ b/pygithub3/requests/repos/keys.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- + +from . import Request + +from pygithub3.resources.users import Key + + +class List(Request): + + uri = '/repos/{user}/{repo}/keys' + resource = Key + + +class Get(Request): + + uri = '/repos/{user}/{repo}/keys/{id}' + resource = Key + + +class Create(Request): + + uri = 'repos/{user}/{repo}/keys' + resource = Key + body_schema = { + 'schema': ('title', 'key'), + 'required': ('title', 'key') + } + + +class Update(Request): + + uri = 'repos/{user}/{repo}/keys/{id}' + resource = Key + body_schema = { + 'schema': ('title', 'key'), + 'required': (), + } + + +class Delete(Request): + + uri = 'repos/{user}/{repo}/keys/{id}' + resource = Key diff --git a/pygithub3/requests/repos/stargazers.py b/pygithub3/requests/repos/stargazers.py new file mode 100644 index 0000000..b1feb2a --- /dev/null +++ b/pygithub3/requests/repos/stargazers.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- + +from . import Request +from pygithub3.resources.users import User +from pygithub3.resources.repos import Repo + + +class List(Request): + + uri = 'repos/{user}/{repo}/stargazers' + resource = User + + +class List_repos(Request): + + uri = 'users/{user}/starred' + resource = Repo + + def clean_uri(self): + if not self.user: + return 'user/starred' + + +class Is_starring(Request): + + uri = 'user/starred/{user}/{repo}' + + +class Star(Request): + + uri = 'user/starred/{user}/{repo}' + + +class Unstar(Request): + + uri = 'user/starred/{user}/{repo}' diff --git a/pygithub3/requests/repos/statuses.py b/pygithub3/requests/repos/statuses.py new file mode 100644 index 0000000..eaf307d --- /dev/null +++ b/pygithub3/requests/repos/statuses.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- + +from . import Request + +from pygithub3.resources.repos import Status + + +class List(Request): + + uri = 'repos/{user}/{repo}/statuses/{sha}' + resource = Status + + +class Create(Request): + + uri = '/repos/{user}/{repo}/statuses/{sha}' + resource = Status + body_schema = { + 'schema': ('state', 'target_url', 'description'), + 'required': ('state',)} diff --git a/pygithub3/requests/repos/watchers.py b/pygithub3/requests/repos/watchers.py new file mode 100644 index 0000000..0889847 --- /dev/null +++ b/pygithub3/requests/repos/watchers.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- + +from . import Request +from pygithub3.resources.users import User +from pygithub3.resources.repos import Repo + + +class List(Request): + + uri = 'repos/{user}/{repo}/subscribers' + resource = User + + +class List_repos(Request): + + uri = 'users/{user}/subscriptions' + resource = Repo + + def clean_uri(self): + if not self.user: + return 'user/subscriptions' + + +class Is_watching(Request): + + uri = 'user/subscriptions/{user}/{repo}' + + +class Watch(Request): + + uri = 'user/subscriptions/{user}/{repo}' + + +class Unwatch(Request): + + uri = 'user/subscriptions/{user}/{repo}' diff --git a/pygithub3/requests/users/__init__.py b/pygithub3/requests/users/__init__.py new file mode 100644 index 0000000..3335bc8 --- /dev/null +++ b/pygithub3/requests/users/__init__.py @@ -0,0 +1,32 @@ +# -*- encoding: utf-8 -*- + +from pygithub3.requests.base import Request, ValidationError +from pygithub3.resources.users import User + + +class Get(Request): + + resource = User + uri = 'users/{user}' + + def clean_uri(self): + if not self.user: + return 'user' + + +class Update(Request): + + resource = User + uri = 'user' + body_schema = { + 'schema': ('name', 'email', 'blog', 'company', 'location', 'hireable', + 'bio'), + 'required': (), + } + + def clean_body(self): + if not self.body: + raise ValidationError("'%s' request needs data. You can use " + "'%s' keys" % (self.__class__.__name__, + self.body_schema)) + return self.body diff --git a/pygithub3/requests/users/emails.py b/pygithub3/requests/users/emails.py new file mode 100644 index 0000000..ff89b62 --- /dev/null +++ b/pygithub3/requests/users/emails.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- + +import re + +from . import Request, ValidationError + +# Src: http://code.djangoproject.com/svn/django/trunk/django/core/validators.py +email_re = re.compile( + r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom + # quoted-string, see also http://tools.ietf.org/html/rfc2822#section-3.2.5 + r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"' + r')@((?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$)' # domain + r'|\[(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\]$', re.IGNORECASE) # literal form, ipv4 address (SMTP 4.1.3) + + +class List(Request): + + uri = 'user/emails' + + +class Add(Request): + + uri = 'user/emails' + + def clean_body(self): + def is_email(email): + return bool(email_re.match(email)) + if not self.body: + raise ValidationError("'%s' request needs emails" + % (self.__class__.__name__)) + + return filter(is_email, self.body) + + +class Delete(Request): + + uri = 'user/emails' + + def clean_body(self): + if not self.body: + raise ValidationError("'%s' request needs emails" + % (self.__class__.__name__)) + return self.body diff --git a/pygithub3/requests/users/followers.py b/pygithub3/requests/users/followers.py new file mode 100644 index 0000000..5f59032 --- /dev/null +++ b/pygithub3/requests/users/followers.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- + +from . import Request +from pygithub3.resources.users import User + + +class List(Request): + + resource = User + uri = 'users/{user}/followers' + + def clean_uri(self): + if not self.user: + return 'user/followers' + + +class Listfollowing(Request): + + resource = User + uri = 'users/{user}/following' + + def clean_uri(self): + if not self.user: + return 'user/following' + + +class Isfollowing(Request): + + uri = 'user/following/{user}' + + +class Follow(Request): + + uri = 'user/following/{user}' + + +class Unfollow(Request): + + uri = 'user/following/{user}' diff --git a/pygithub3/requests/users/keys.py b/pygithub3/requests/users/keys.py new file mode 100644 index 0000000..23a30d9 --- /dev/null +++ b/pygithub3/requests/users/keys.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- + +from . import Request +from pygithub3.resources.users import Key + + +class List(Request): + + resource = Key + uri = 'user/key' + + +class Get(Request): + + resource = Key + uri = 'user/keys/{key_id}' + + +class Add(Request): + + resource = Key + uri = 'user/keys' + body_schema = { + 'schema': ('title', 'key'), + 'required': ('title', 'key') + } + + +class Update(Request): + + resource = Key + body_schema = { + 'schema': ('title', 'key'), + 'required': ('title', 'key') + } + uri = 'user/keys/{key_id}' + + +class Delete(Request): + + uri = 'user/keys/{key_id}' diff --git a/pygithub3/resources/__init__.py b/pygithub3/resources/__init__.py new file mode 100644 index 0000000..dae354a --- /dev/null +++ b/pygithub3/resources/__init__.py @@ -0,0 +1 @@ +# -*- encoding: utf-8 -*- diff --git a/pygithub3/resources/base.py b/pygithub3/resources/base.py new file mode 100644 index 0000000..25b045c --- /dev/null +++ b/pygithub3/resources/base.py @@ -0,0 +1,79 @@ +# -*- coding: utf-8 -*- + +from pygithub3.core import json + + +class Resource(object): + + _dates = () + _maps = {} + _collection_maps = {} + + def __init__(self, attrs): + self._attrs = attrs + self.__set_attrs() + + def __set_attrs(self): + for attr in self._attrs: + setattr(self, attr, self._attrs[attr]) + + def __str__(self): + return "<%s>" % self.__class__.__name__ + + def __repr__(self): + return self.__str__() + + @classmethod + def loads(self, json_content): + resource_chunk = json.loads(json_content) + if not hasattr(resource_chunk, 'items'): + return [self.__load(raw_resource) + for raw_resource in resource_chunk] + else: + return self.__load(resource_chunk) + + @classmethod + def __load(self, raw_resource): + def self_resource(func): + def wrapper(resource, raw_resource): + if resource == 'self': + resource = self + return func(resource, raw_resource) + return wrapper + + @self_resource + def parse_map(resource, raw_resource): + if hasattr(raw_resource, 'items'): + return resource.__load(raw_resource) + + @self_resource + def parse_collection_map(resource, raw_resources): + # Dict of resources (Ex: Gist file) + if hasattr(raw_resources, 'items'): + dict_map = {} + for key, raw_resource in raw_resources.items(): + dict_map[key] = resource.__load(raw_resource) + return dict_map + # list of resources + elif hasattr(raw_resources, '__iter__'): + return [resource.__load(raw_resource) + for raw_resource in raw_resources] + + new_resource = raw_resource.copy() + new_resource.update(dict([ + (attr, parse_map(resource, raw_resource[attr])) + for attr, resource in self._maps.items() + if attr in raw_resource])) + new_resource.update(dict([ + (attr, parse_collection_map(resource, raw_resource[attr])) + for attr, resource in self._collection_maps.items() + if attr in raw_resource])) + + return self(new_resource) + + +class Raw(Resource): + + @classmethod + def loads(self, json_content): + return json.loads(json_content) diff --git a/pygithub3/resources/events.py b/pygithub3/resources/events.py new file mode 100644 index 0000000..d779c23 --- /dev/null +++ b/pygithub3/resources/events.py @@ -0,0 +1,49 @@ +# -*- encoding: utf-8 -*- + +from pygithub3.resources.base import Resource +from pygithub3.resources import users, repos, orgs + + +class Event(Resource): + + _dates = ('created_at', ) + _maps = {'actor': users.User, 'repo': repos.Repo, 'org': orgs.Org} + + def __str__(self): + return '<(%s)>' % getattr(self, 'type', '') + + +class Repo(Resource): + + _dates = ('created_at', ) + _maps = {'actor': users.User, 'repo': repos.Repo, 'org': orgs.Org} + + def __str__(self): + return '<(%s)>' % getattr(self, 'type', '') + + +class Network(Resource): + + _dates = ('created_at', ) + _maps = {'actor': users.User, 'repo': repos.Repo, 'org': orgs.Org} + + def __str__(self): + return '<(%s)>' % getattr(self, 'type', '') + + +class Org(Resource): + + _dates = ('created_at', ) + _maps = {'actor': users.User, 'repo': repos.Repo, 'org': orgs.Org} + + def __str__(self): + return '<(%s)>' % getattr(self, 'type', '') + + +class User(Resource): + + _dates = ('created_at', ) + _maps = {'actor': users.User, 'repo': repos.Repo, 'org': orgs.Org} + + def __str__(self): + return '<(%s)>' % getattr(self, 'type', '') diff --git a/pygithub3/resources/gists.py b/pygithub3/resources/gists.py new file mode 100644 index 0000000..feb39c1 --- /dev/null +++ b/pygithub3/resources/gists.py @@ -0,0 +1,47 @@ +# -*- encoding: utf-8 -*- + +from .base import Resource +from .users import User + + +class File(Resource): + + def __str__(self): + return '' % getattr(self, 'filename', '') + + +class Fork(Resource): + + _dates = ('created_at', ) + _maps = {'user': User} + + def __str__(self): + return '' + + +class History(Resource): + + _dates = ('committed_at', ) + _maps = {'user': User} + + def __str__(self): + return '' % getattr(self, 'version', '') + + +class Gist(Resource): + + _dates = ('created_at', ) + _maps = {'user': User} + _collection_maps = {'files': File, 'forks': Fork, 'history': History} + + def __str__(self): + return '' % getattr(self, 'description', '') + + +class Comment(Resource): + + _dates = ('created_at', ) + _maps = {'user': User} + + def __str__(self): + return '' % getattr(self, 'user', '') diff --git a/pygithub3/resources/git_data.py b/pygithub3/resources/git_data.py new file mode 100644 index 0000000..4d12e01 --- /dev/null +++ b/pygithub3/resources/git_data.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- + +from .base import Resource +from .repos import Author, Commit + + +class Blob(Resource): + def __str__(self): + return "" % getattr(self, 'content', '') + + +class Reference(Resource): + def __str__(self): + return '' % getattr(self, 'ref', '') + + +class Tag(Resource): + _maps = {'object': Commit, + 'tagger': Author} # committer? tagger? + + def __str__(self): + return '' % getattr(self, 'tag', '') + + +class Tree(Resource): + def __str__(self): + return '' % getattr(self, 'sha', '') diff --git a/pygithub3/resources/issues.py b/pygithub3/resources/issues.py new file mode 100644 index 0000000..b2301a6 --- /dev/null +++ b/pygithub3/resources/issues.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- + +import re + +from .base import Resource +from .users import User +from .pull_requests import PullRequest + + +class Label(Resource): + + @staticmethod + def is_valid_color(color): + valid_color = re.compile(r'[0-9abcdefABCDEF]{6}') + match = valid_color.match(color) + if match is None: + return False + return match.start() == 0 and match.end() == len(color) + + def __str__(self): + return '