From d7c51db2a1c180b1a08001388d665a9f8ff0be20 Mon Sep 17 00:00:00 2001 From: Derrick Gilland Date: Tue, 26 May 2015 22:03:22 -0400 Subject: [PATCH] First commit. --- .gitignore | 48 ++++++++ .travis.yml | 21 ++++ AUTHORS.rst | 14 +++ CHANGES.rst | 10 ++ CONTRIBUTING.rst | 196 +++++++++++++++++++++++++++++ LICENSE.rst | 24 ++++ MANIFEST.in | 11 ++ Makefile | 114 +++++++++++++++++ README.rst | 46 +++++++ docs/Makefile | 177 ++++++++++++++++++++++++++ docs/api.rst | 11 ++ docs/authors.rst | 1 + docs/changes.rst | 1 + docs/conf.py | 280 ++++++++++++++++++++++++++++++++++++++++++ docs/contributing.rst | 1 + docs/index.rst | 33 +++++ docs/installation.rst | 10 ++ docs/license.rst | 1 + docs/versioning.rst | 12 ++ requirements.txt | 8 ++ setup.cfg | 16 +++ setup.py | 75 +++++++++++ shed/__init__.py | 17 +++ shed/__meta__.py | 17 +++ shed/_compat.py | 27 ++++ shed/shed.py | 211 +++++++++++++++++++++++++++++++ shed/utils.py | 49 ++++++++ tests/__init__.py | 1 + tests/test_shed.py | 105 ++++++++++++++++ tox.ini | 13 ++ 30 files changed, 1550 insertions(+) create mode 100644 .gitignore create mode 100644 .travis.yml create mode 100644 AUTHORS.rst create mode 100644 CHANGES.rst create mode 100644 CONTRIBUTING.rst create mode 100644 LICENSE.rst create mode 100644 MANIFEST.in create mode 100644 Makefile create mode 100644 README.rst create mode 100644 docs/Makefile create mode 100644 docs/api.rst create mode 100644 docs/authors.rst create mode 100644 docs/changes.rst create mode 100755 docs/conf.py create mode 100644 docs/contributing.rst create mode 100644 docs/index.rst create mode 100644 docs/installation.rst create mode 100644 docs/license.rst create mode 100644 docs/versioning.rst create mode 100644 requirements.txt create mode 100644 setup.cfg create mode 100644 setup.py create mode 100644 shed/__init__.py create mode 100644 shed/__meta__.py create mode 100644 shed/_compat.py create mode 100644 shed/shed.py create mode 100644 shed/utils.py create mode 100755 tests/__init__.py create mode 100755 tests/test_shed.py create mode 100644 tox.ini diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4bedd31 --- /dev/null +++ b/.gitignore @@ -0,0 +1,48 @@ +*.py[cod] + +# C extensions +*.so + +# Packages +*.egg +*.egg-info +dist +build +eggs +parts +bin +var +sdist +develop-eggs +.installed.cfg +lib +lib64 +__pycache__ + +# Installer logs +pip-log.txt + +# Unit test / coverage reports +.coverage +.tox +nosetests.xml +htmlcov + +# Translations +*.mo + +# Mr Developer +.mr.developer.cfg +.project +.pydevproject +.idea + +# Complexity +output/*.html +output/*/index.html + +# Sphinx +docs/_build + +# virtualenv +/env* diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..81a5b36 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,21 @@ +# Config file for automatic testing at travis-ci.org + +language: python + +python: + - "2.7" + - "3.3" + - "3.4" + +# command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors +install: + - make travisci-install + +# command to run tests, e.g. python setup.py test +script: + - make travisci-test + +# tasks to execute after successful test +after_success: + - pip install python-coveralls --use-mirrors + - coveralls diff --git a/AUTHORS.rst b/AUTHORS.rst new file mode 100644 index 0000000..b29912f --- /dev/null +++ b/AUTHORS.rst @@ -0,0 +1,14 @@ +Authors +======= + + +Lead +---- + +- Derrick Gilland, dgilland@gmail.com, `dgilland@github `_ + + +Contributors +------------ + +None diff --git a/CHANGES.rst b/CHANGES.rst new file mode 100644 index 0000000..5c1ccc8 --- /dev/null +++ b/CHANGES.rst @@ -0,0 +1,10 @@ +.. _changelog: + +Changelog +========= + + +v0.0.0 (xxxx-xx-xx) +------------------- + +- First release. diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst new file mode 100644 index 0000000..d3fe5e3 --- /dev/null +++ b/CONTRIBUTING.rst @@ -0,0 +1,196 @@ +Contributing +============ + +Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given. + +You can contribute in many ways: + + +Types of Contributions +---------------------- + +Report Bugs ++++++++++++ + +Report bugs at https://github.com/dgilland/shed/issues. + +If you are reporting a bug, please include: + +- Your operating system name and version. +- Any details about your local setup that might be helpful in troubleshooting. +- Detailed steps to reproduce the bug. + + +Fix Bugs +++++++++ + +Look through the GitHub issues for bugs. Anything tagged with "bug" is open to whoever wants to implement it. + + +Implement Features +++++++++++++++++++ + +Look through the GitHub issues for features. Anything tagged with "enhancement" or "help wanted" is open to whoever wants to implement it. + + +Write Documentation ++++++++++++++++++++ + +Shed could always use more documentation, whether as part of the official Shed docs, in docstrings, or even on the web in blog posts, articles, and such. + + +Submit Feedback ++++++++++++++++ + +The best way to send feedback is to file an issue at https://github.com/dgilland/shed/issues. + +If you are proposing a feature: + +- Explain in detail how it would work. +- Keep the scope as narrow as possible, to make it easier to implement. +- Remember that this is a volunteer-driven project, and that contributions are welcome :) + + +Get Started! +------------ + +Ready to contribute? Here's how to set up ``shed`` for local development. + +1. Fork the ``shed`` repo on GitHub. +2. Clone your fork locally:: + + $ git clone git@github.com:your_name_here/shed.git + +3. Install your local copy into a virtualenv. Assuming you have virtualenv installed, this is how you set up your fork for local development:: + + $ cd shed + $ make build + +4. Create a branch for local development:: + + $ git checkout -b name-of-your-bugfix-or-feature + + Now you can make your changes locally. + +5. When you're done making changes, check that your changes pass linting (`PEP8`_ and pylint) and the tests, including testing other Python versions with tox:: + + $ make test-full + +6. Add yourself to ``AUTHORS.rst``. + +7. Commit your changes and push your branch to GitHub:: + + $ git add . + $ git commit -m "Your detailed description of your changes." + $ git push origin name-of-your-bugfix-or-feature + +8. Submit a pull request through the GitHub website. + + +Pull Request Guidelines +----------------------- + +Before you submit a pull request, check that it meets these guidelines: + +1. The pull request should include tests. +2. If the pull request adds functionality, the docs should be updated. Put your new functionality into a function with a docstring, and add the feature to the README.rst. +3. The pull request should work for Python 2.7, 3.3, and 3.4. Check https://travis-ci.org/dgilland/shed/pull_requests and make sure that the tests pass for all supported Python versions. + + +Project CLI +----------- + +Some useful CLI commands when working on the project are below. **NOTE:** All commands are run from the root of the project and require ``make``. + +make build +++++++++++ + +Run the ``clean`` and ``install`` commands. + +:: + + make build + + +make install +++++++++++++ + +Install Python dependencies into virtualenv located at ``env/``. + +:: + + make install + + +make clean +++++++++++ + +Remove build/test related temporary files like ``env/``, ``.tox``, ``.coverage``, and ``__pycache__``. + +:: + + make clean + + +make test ++++++++++ + +Run unittests under the virtualenv's default Python version. Does not test all support Python versions. To test all supported versions, see `make test-full`_. + +:: + + make test + + +make test-full +++++++++++++++ + +Run unittest and linting for all supported Python versions. **NOTE:** This will fail if you do not have all Python versions installed on your system. If you are on an Ubuntu based system, the `Dead Snakes PPA`_ is a good resource for easily installing multiple Python versions. If for whatever reason you're unable to have all Python versions on your development machine, note that Travis-CI will run full integration tests on all pull requests. + +:: + + make test-full + + +make lint ++++++++++ + +Run ``make pylint`` and ``make pep8`` commands. + +:: + + make lint + + +make pylint ++++++++++++ + +Run ``pylint`` compliance check on code base. + +:: + + make pylint + + +make pep8 ++++++++++ + +Run `PEP8`_ compliance check on code base. + +:: + + make pep8 + + +make docs ++++++++++ + +Build documentation to ``docs/_build/``. + +:: + + make docs + + +.. _Dead Snakes PPA: https://launchpad.net/~fkrull/+archive/deadsnakes +.. _PEP8: http://legacy.python.org/dev/peps/pep-0008/ \ No newline at end of file diff --git a/LICENSE.rst b/LICENSE.rst new file mode 100644 index 0000000..76825ba --- /dev/null +++ b/LICENSE.rst @@ -0,0 +1,24 @@ +License +======= + +The MIT License (MIT) + +Copyright (c) 2015, Derrick Gilland + +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/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..eae2b96 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,11 @@ +include AUTHORS.rst +include CONTRIBUTING.rst +include CHANGES.rst +include LICENSE.rst +include README.rst + +recursive-include tests * +recursive-exclude * __pycache__ +recursive-exclude * *.py[co] + +recursive-include docs *.rst conf.py Makefile make.bat diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..edb7d8c --- /dev/null +++ b/Makefile @@ -0,0 +1,114 @@ +## +# Variables +## + +ENV_NAME = env +ENV_ACT = . env/bin/activate; +PIP = $(ENV_NAME)/bin/pip +PYTEST_ARGS = --doctest-modules -v -s +PYTEST_TARGET = shed tests +COVERAGE_ARGS = --cov-config setup.cfg --cov-report term-missing --cov +COVERAGE_TARGET = shed + + +## +# Targets +## + +.PHONY: build +build: clean install + +.PHONY: clean +clean: clean-env clean-files + +.PHONY: clean-env +clean-env: + rm -rf $(ENV_NAME) + +.PHONY: clean-files +clean-files: + rm -rf .tox + rm -rf .coverage + find . -name \*.pyc -type f -delete + find . -name \*.test.db -type f -delete + find . -depth -name __pycache__ -type d -exec rm -rf {} \; + rm -rf dist *.egg* build + +.PHONY: install +install: + rm -rf $(ENV_NAME) + virtualenv --no-site-packages $(ENV_NAME) + $(PIP) install -r requirements.txt + +.PHONY: test +test: pylint-errors pep8 pytest + +.PHONY: pytest +pytest: + $(ENV_ACT) py.test $(PYTEST_ARGS) $(COVERAGE_ARGS) $(COVERAGE_TARGET) $(PYTEST_TARGET) + +.PHONY: test-full +test-full: pylint-errors test-setuppy clean-files + +.PHONY: test-setuppy +test-setuppy: + python setup.py test + + +.PHONY: lint +lint: pylint pep8 + +.PHONY: pep8 +pep8: + $(ENV_ACT) pep8 $(PYTEST_TARGET) + +.PHONY: pylint +pylint: + $(ENV_ACT) pylint $(COVERAGE_TARGET) + +.PHONY: pylint-errors +pylint-errors: + $(ENV_ACT) pylint -E $(COVERAGE_TARGET) + + +.PHONY: master +master: + git checkout master + git merge develop + git push origin develop master --tags + git checkout develop + +.PHONY: release +release: + $(ENV_ACT) python setup.py sdist bdist_wheel + $(ENV_ACT) twine upload dist/* + rm -rf dist *.egg* build + +.PHONY: docs +docs: + touch docs/_build + rm -r docs/_build + $(ENV_ACT) cd docs; make doctest + $(ENV_ACT) cd docs; make html + +.PHONY: serve-docs +serve-docs: + cd docs/_build/html; python2 -m SimpleHTTPServer 8000 + +.PHONY: reload-docs +reload-docs: docs serve-docs + + +## +# TravisCI +## + +.PHONY: travisci-install +travisci-install: + pip install -r requirements.txt + +.PHONY: travisci-test +travisci-test: + pep8 $(PYTEST_TARGET) + pylint -E $(COVERAGE_TARGET) + py.test $(PYTEST_ARGS) $(COVERAGE_ARGS) $(COVERAGE_TARGET) $(PYTEST_TARGET) diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..4192ce3 --- /dev/null +++ b/README.rst @@ -0,0 +1,46 @@ +**** +Shed +**** + +|version| |travis| |coveralls| |license| + + +A content-addressable file management system. + + +Links +===== + +- Project: https://github.com/dgilland/shed +- Documentation: http://shed.readthedocs.org +- PyPI: https://pypi.python.org/pypi/shed/ +- TravisCI: https://travis-ci.org/dgilland/shed + + +Quickstart +========== + +Install using pip: + + +:: + + pip install shed + + + +For more details, please see the full documentation at http://shed.readthedocs.org. + + + +.. |version| image:: http://img.shields.io/pypi/v/shed.svg?style=flat-square + :target: https://pypi.python.org/pypi/shed/ + +.. |travis| image:: http://img.shields.io/travis/dgilland/shed/master.svg?style=flat-square + :target: https://travis-ci.org/dgilland/shed + +.. |coveralls| image:: http://img.shields.io/coveralls/dgilland/shed/master.svg?style=flat-square + :target: https://coveralls.io/r/dgilland/shed + +.. |license| image:: http://img.shields.io/pypi/l/shed.svg?style=flat-square + :target: https://pypi.python.org/pypi/shed/ \ No newline at end of file diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..230a21e --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,177 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = _build + +# User-friendly check for sphinx-build +ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) +$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) +endif + +# 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 " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" + @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 " xml to make Docutils-native XML files" + @echo " pseudoxml to make pseudoxml-XML files for display purposes" + @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/shed.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/shed.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/shed" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/shed" + @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." + +latexpdfja: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through platex and dvipdfmx..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja + @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." + +xml: + $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml + @echo + @echo "Build finished. The XML files are in $(BUILDDIR)/xml." + +pseudoxml: + $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml + @echo + @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." diff --git a/docs/api.rst b/docs/api.rst new file mode 100644 index 0000000..42091ba --- /dev/null +++ b/docs/api.rst @@ -0,0 +1,11 @@ +.. _api: + +API Reference +============= + +.. testsetup:: + + from shed import * + + +.. automodule:: shed diff --git a/docs/authors.rst b/docs/authors.rst new file mode 100644 index 0000000..e122f91 --- /dev/null +++ b/docs/authors.rst @@ -0,0 +1 @@ +.. include:: ../AUTHORS.rst diff --git a/docs/changes.rst b/docs/changes.rst new file mode 100644 index 0000000..d9e113e --- /dev/null +++ b/docs/changes.rst @@ -0,0 +1 @@ +.. include:: ../CHANGES.rst diff --git a/docs/conf.py b/docs/conf.py new file mode 100755 index 0000000..9c745ce --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,280 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# shed documentation build configuration file, created by +# sphinx-quickstart on Tue Jul 9 22:26:36 2013. +# +# 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 +import os + + +# On_rtd is whether we are on readthedocs.org, this line of code grabbed from +# docs.readthedocs.org. +on_rtd = os.environ.get('READTHEDOCS', None) == 'True' + + +# 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.insert(0, os.path.abspath('..')) + +import shed + +# -- 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.doctest', + 'sphinx.ext.coverage', + 'sphinx.ext.viewcode', + 'sphinx.ext.napoleon' +] + +# 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-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'Shed' +copyright = u'2015, Derrick Gilland' + +# 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. +version = release = shed.__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' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built +# documents. +#keep_warnings = False + + +# -- Options for HTML output ------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +if on_rtd: + html_theme = 'default' +else: + import sphinx_rtd_theme + html_theme = 'sphinx_rtd_theme' + html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] + +# 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 = [] + +# 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 = 'sheddoc' + + +# -- 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', 'shed.tex', + u'Shed Documentation', + u'Derrick Gilland', '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', 'shed', + u'Shed Documentation', + [u'Derrick Gilland'], 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', 'shed', + u'Shed Documentation', + u'Derrick Gilland', + 'shed', + 'A content-addressable file management system.', + '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' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +#texinfo_no_detailmenu = False diff --git a/docs/contributing.rst b/docs/contributing.rst new file mode 100644 index 0000000..e582053 --- /dev/null +++ b/docs/contributing.rst @@ -0,0 +1 @@ +.. include:: ../CONTRIBUTING.rst diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..e82118d --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,33 @@ +.. shed documentation master file + +.. include:: ../README.rst + +Guide +===== + +.. toctree:: + :maxdepth: 3 + + installation + api + + +Project Info +============ + +.. toctree:: + :maxdepth: 1 + + license + versioning + changes + authors + contributing + + +Indices and Tables +================== + +- :ref:`genindex` +- :ref:`modindex` +- :ref:`search` diff --git a/docs/installation.rst b/docs/installation.rst new file mode 100644 index 0000000..93d7875 --- /dev/null +++ b/docs/installation.rst @@ -0,0 +1,10 @@ +Installation +============ + +shed requires Python >= 2.7 or >= 3.3. + +To install from `PyPI `_: + +:: + + pip install shed diff --git a/docs/license.rst b/docs/license.rst new file mode 100644 index 0000000..68c5792 --- /dev/null +++ b/docs/license.rst @@ -0,0 +1 @@ +.. include:: ../LICENSE.rst diff --git a/docs/versioning.rst b/docs/versioning.rst new file mode 100644 index 0000000..46b7c91 --- /dev/null +++ b/docs/versioning.rst @@ -0,0 +1,12 @@ +Versioning +========== + +This project follows `Semantic Versioning`_ with the following caveats: + +- Only the public API (i.e. the objects imported into the shed module) will maintain backwards compatibility between MINOR version bumps. +- Objects within any other parts of the library are not guaranteed to not break between MINOR version bumps. + +With that in mind, it is recommended to only use or import objects from the main module, shed. + + +.. _Semantic Versioning: http://semver.org/ diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..a7765a5 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,8 @@ +pep8 +pylint +pytest-cov +pytest +Sphinx +tox +twine +wheel diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..4870477 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,16 @@ +[pytest] +norecursedirs = env +addopts = --doctest-modules -v -s + +# pytest coverage options +[run] +omit = + */tests/* + */test_* + */_compat.py + +[pep8] +exclude = .tox,env + +[wheel] +universal = 1 diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..9f3f907 --- /dev/null +++ b/setup.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import os +import sys +from setuptools import setup, find_packages +from setuptools.command.test import test as TestCommand + + +def read(fname): + return open(os.path.join(os.path.dirname(__file__), fname)).read() + + +meta = {} +exec(read('shed/__meta__.py'), meta) + +readme = read('README.rst') +changes = read('CHANGES.rst') + + +class Tox(TestCommand): + user_options = [ + ('tox-args=', 'a', "Arguments to pass to tox") + ] + + def initialize_options(self): + TestCommand.initialize_options(self) + self.tox_args = '-c tox.ini' + + def finalize_options(self): + TestCommand.finalize_options(self) + self.test_args = [] + self.test_suite = True + + def run_tests(self): + # Import here because outside the eggs aren't loaded. + import tox + import shlex + + errno = tox.cmdline(args=shlex.split(self.tox_args)) + sys.exit(errno) + + +setup( + name=meta['__title__'], + version=meta['__version__'], + url=meta['__url__'], + license=meta['__license__'], + author=meta['__author__'], + author_email=meta['__email__'], + description=meta['__summary__'], + long_description=readme + '\n\n' + changes, + packages=find_packages(exclude=['tests']), + install_requires=meta['__install_requires__'], + tests_require=meta['__tests_require__'], + cmdclass={'test': Tox}, + test_suite='tests', + keywords='shed', + classifiers=[ + 'Development Status :: 2 - Pre-Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python', + 'License :: OSI Approved :: MIT License', + 'Topic :: Software Development :: Libraries', + 'Topic :: Software Development :: Libraries :: Python Modules', + 'Topic :: System :: Filesystems', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.3', + 'Programming Language :: Python :: 3.4', + ] +) diff --git a/shed/__init__.py b/shed/__init__.py new file mode 100644 index 0000000..93f0e81 --- /dev/null +++ b/shed/__init__.py @@ -0,0 +1,17 @@ +# -*- coding: utf-8 -*- +"""The shed library is a content addressable file management system. +""" + +from .shed import Shed + +from .__meta__ import ( + __title__, + __summary__, + __url__, + __version__, + __author__, + __email__, + __license__ +) + +__all__ = ['Shed'] diff --git a/shed/__meta__.py b/shed/__meta__.py new file mode 100644 index 0000000..ba5ac9f --- /dev/null +++ b/shed/__meta__.py @@ -0,0 +1,17 @@ +# -*- coding: utf-8 -*- +"""Define project metadata +""" + +__title__ = 'shed' +__summary__ = 'A content-addressable file management system.' +__url__ = 'https://github.com/dgilland/shed' + +__version__ = '0.0.0' + +__install_requires__ = [] +__tests_require__ = ['tox'] + +__author__ = 'Derrick Gilland' +__email__ = 'dgilland@gmail.com' + +__license__ = 'MIT License' diff --git a/shed/_compat.py b/shed/_compat.py new file mode 100644 index 0000000..d79d805 --- /dev/null +++ b/shed/_compat.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +# pylint: skip-file +"""Python 2/3 compatibility +""" + +import sys + + +PY3 = sys.version_info[0] == 3 + + +if PY3: + text_type = str + string_types = (str,) + + def to_bytes(text): + if not isinstance(text, bytes): + text = bytes(text, 'utf8') + return text +else: + text_type = unicode + string_types = (str, unicode) + + def to_bytes(text): + if not isinstance(text, string_types): + text = text_type(text) + return text diff --git a/shed/shed.py b/shed/shed.py new file mode 100644 index 0000000..8f8a453 --- /dev/null +++ b/shed/shed.py @@ -0,0 +1,211 @@ + +from collections import namedtuple +from contextlib import contextmanager, closing +from distutils.dir_util import mkpath # pylint: disable=no-name-in-module +import glob +import hashlib +import io +import os +import shutil +from tempfile import NamedTemporaryFile + +from .utils import walkfiles, compact +from ._compat import to_bytes + + +class Shed(object): + """Content addressable file manager. + + Args: + root (str): Directory path used as root of storage space. + depth (int, optional): Number of folders to create when saving a file. + Defaults to ``4``. + length (int): Number of characters each subfolder will contain. + Defaults to ``1``. + algorithm (str): Hash algorithm to use when computing file hash. + Algorithm should be available in ``hashlib`` module. Defaults to + ``'sha256'``. + fmode (int, optional): File mode permission to set when adding files to + directory. Defaults to ``0o664`` which allows owner/group to + read/write and everyone else to read. + dmode (int, optional): Directory mode permission to set for + subdirectories. Defaults to ``0o755`` which allows owner/group to + read/write and everyone else to read and everyone to execute. + """ + def __init__(self, + root, + depth=4, + length=1, + algorithm='sha256', + fmode=0o664, + dmode=0o755): + self.root = os.path.realpath(root) + self.fmode = fmode + self.dmode = dmode + self.depth = depth + self.length = length + self.algorithm = algorithm + + self.makepath(self.root) + + def put(self, obj, extension=None): + """Store contents of `obj` on disk using its content hash for the + address. + """ + stream = Stream(obj) + digest = self.computehash(stream) + + with closing(stream): + filepath = self.copy(stream, digest, extension) + + return Address(filepath, digest) + + def files(self): + """Return generator that yields all files under :attr:`root` directory. + """ + return walkfiles(self.root) + + def exists(self, digest): + """Check whether a given file digest exsists on disk.""" + path = self.filepath(digest) + # Match using exact path or glob with wildcard extension. + return os.path.isfile(path) or glob.glob(path + '.*') + + def makepath(self, path): + """Physically create the folder path on disk.""" + mkpath(path, mode=self.dmode) + + def copy(self, stream, digest, extension=None): + """Copy the contents of `stream` onto disk with an optional file + extension appended. The copy process using a temporary file to store + the initial contents and then moves this file to it's final location. + """ + filepath = self.filepath(digest, extension) + + if not os.path.isfile(filepath): + with tmpfile(stream, self.fmode) as fname: + self.makepath(os.path.dirname(filepath)) + shutil.copy(fname, filepath) + + return filepath + + def computehash(self, stream): + """Compute hash of file using :attr:`algorithm`.""" + hash = hashlib.new(self.algorithm) + for data in stream: + hash.update(to_bytes(data)) + return hash.hexdigest() + + def filepath(self, digest, extension=''): + """Build the file path for a given hash digest. Optionally, append a + file extension. + """ + paths = self.tokenize(digest) + + if extension and not extension.startswith(os.extsep): + extension = os.extsep + extension + elif not extension: + extension = '' + + return os.path.join(self.root, *paths) + extension + + def tokenize(self, id): + """Convert content ID into tokens that will become the folder tree + structure. + """ + # This creates a list of `depth` number of tokens with length + # `length` from the first part of the digest plus the remainder. + return compact([id[i * self.length:self.length * (i + 1)] + for i in range(self.depth)] + + [id[self.depth * self.length:]]) + + +class Stream(object): + """Common interface for file-like objects. + + The input `obj` can be a file-like object or a path to a file. If `obj` is + a path to a file, then it will be opened until :meth:`close` is called. + If `obj` is a file-like object, then it's original position will be + restored when :meth:`close` is called instead of closing the object + automatically. Closing of the stream is deferred to whatever process passed + the stream in. + + Successive readings of the stream is supported without having to manually + set it's position back to ``0``. + """ + def __init__(self, obj): + if hasattr(obj, 'read'): + pos = obj.tell() + elif os.path.isfile(obj): + obj = io.open(obj, 'rb') + pos = None + else: + raise ValueError(('Object must be a valid file path or ' + 'a readable object.')) + + self._obj = obj + self._pos = pos + + def __iter__(self): + """Read underlying IO object and yield results. Return object to + original position if we didn't open it originally. + """ + self._obj.seek(0) + + while True: + data = self._obj.read() + + if not data: + break + + yield data + + if self._pos is not None: + self._obj.seek(self._pos) + + def close(self): + """Close underlying IO object if we opened it, else return it to + original position. + """ + if self._pos is None: + self._obj.close() + else: + self._obj.seek(self._pos) + + +class Address(namedtuple('Address', ['path', 'digest'])): + """File Address containing file's path on disk and it's content hash.""" + pass + + +@contextmanager +def tmpfile(stream, mode=None): + """Context manager that writes a :class:`Stream` object to a named + temporary file and yield it's filename. Cleanup deletes from the temporary + file from disk. + + Args: + stream (Stream): Stream object to write to disk as temporary file. + mode (int, optional): File mode to set on temporary file. + + Returns: + str: Temporoary file name + """ + tmp = NamedTemporaryFile(delete=False) + + if mode is not None: + oldmask = os.umask(0) + + try: + os.chmod(tmp.name, mode) + finally: + os.umask(oldmask) + + for data in stream: + tmp.write(to_bytes(data)) + + tmp.close() + + yield tmp.name + + os.remove(tmp.name) diff --git a/shed/utils.py b/shed/utils.py new file mode 100644 index 0000000..bccade2 --- /dev/null +++ b/shed/utils.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- + +import os + + +def compact(items): + """Return only truthy elements of `items`.""" + return [item for item in items if item] + + +def walk(path, + folders=True, + files=True, + topdown=True, + onerror=None, + followlinks=False): + """Recursively walk `path` yielding folders and files if ``folders==True`` + and/or ``files==True`` respectively. + """ + for folder, subfolders, folder_files in os.walk(path, + topdown=topdown, + onerror=onerror, + followlinks=followlinks): + if folders: + yield os.path.abspath(folder) + + if files: + for file_ in folder_files: + yield os.path.abspath(os.path.join(folder, file_)) + + +def walkfolders(path, topdown=True, onerror=None, followlinks=False): + """Recursively walk `path` and yield folders.""" + return walk(path, + folders=True, + files=False, + topdown=True, + onerror=None, + followlinks=False) + + +def walkfiles(path, topdown=True, onerror=None, followlinks=False): + """Recursively walk `path` and yield files.""" + return walk(path, + folders=False, + files=True, + topdown=True, + onerror=None, + followlinks=False) diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100755 index 0000000..40a96af --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1 @@ +# -*- coding: utf-8 -*- diff --git a/tests/test_shed.py b/tests/test_shed.py new file mode 100755 index 0000000..87f8515 --- /dev/null +++ b/tests/test_shed.py @@ -0,0 +1,105 @@ +# -*- coding: utf-8 -*- + +from io import StringIO +import os + +import pytest + +import shed + + +@pytest.fixture +def testpath(tmpdir): + return tmpdir.mkdir('shed') + + +@pytest.fixture +def testfile(testpath): + return testpath.join('shed.txt') + + +@pytest.fixture +def stringio(): + return StringIO(u'foo') + + +@pytest.yield_fixture +def fileio(testfile): + with open(str(testfile), 'wb') as io: + io.write(b'foo') + + io = open(str(testfile), 'rb') + + yield io + + io.close() + + +@pytest.fixture +def filepath(testfile): + testfile.write(b'foo') + return testfile + + +def assert_file_put(testpath, fs, address): + path = address.path[len(fs.root):] + directory = os.path.dirname(path) + dir_parts = [part for part in directory.split(os.path.sep) if part] + + assert address.path in tuple(testpath.visit()) + assert fs.exists(address.digest) + assert os.path.splitext(path.replace(os.path.sep, ''))[0] == address.digest + assert len(dir_parts) == fs.depth + assert all(len(part) == fs.length for part in dir_parts) + + +def test_shed_put_stringio(testpath, stringio): + fs = shed.Shed(str(testpath)) + address = fs.put(stringio) + + assert_file_put(testpath, fs, address) + + with open(address.path, 'rb') as fileobj: + assert fileobj.read() == stringio.getvalue().encode('utf8') + + +def test_shed_put_fileobj(testpath, fileio): + fs = shed.Shed(str(testpath)) + address = fs.put(fileio) + + assert_file_put(testpath, fs, address) + + with open(address.path, 'rb') as fileobj: + assert fileobj.read() == fileio.read() + + +def test_shed_put_file(testpath, filepath): + fs = shed.Shed(str(testpath)) + address = fs.put(str(filepath)) + + assert_file_put(testpath, fs, address) + + with open(address.path, 'rb') as fileobj: + assert fileobj.read() == filepath.read().encode('utf8') + + +@pytest.mark.parametrize('extension', [ + 'txt', + '.txt', + 'md', + '.md' +]) +def test_shed_put_extension(testpath, stringio, extension): + fs = shed.Shed(str(testpath)) + address = fs.put(stringio, extension) + + assert_file_put(testpath, fs, address) + assert os.path.sep in address.path + assert os.path.splitext(address.path)[1].endswith(extension) + + +def test_shed_put_invalid(testpath): + fs = shed.Shed(str(testpath)) + + with pytest.raises(ValueError): + fs.put('foo') diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000..97e1cb7 --- /dev/null +++ b/tox.ini @@ -0,0 +1,13 @@ +[tox] +;envlist = pep8, py27, py33, py34 +envlist = py34 + +[testenv] +deps = + pytest + pytest-cov +commands = py.test shed tests [] + +[testenv:pep8] +deps = pep8 +commands = pep8 shed tests