├── docs ├── readme.rst ├── environment.yml ├── usage.rst ├── index.rst ├── Makefile ├── make.bat └── conf.py ├── tests ├── __init__.py ├── test_cluster.py └── test_reporter.py ├── .gitattributes ├── MANIFEST.in ├── README.rst ├── readthedocs.yml ├── requirements_dev.txt ├── postlearn ├── __init__.py ├── templates │ └── report.tpl ├── utils.py ├── cluster.py ├── reporter.py └── _version.py ├── setup.cfg ├── .travis.yml ├── .gitignore ├── LICENSE ├── setup.py ├── Makefile └── versioneer.py /docs/readme.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.rst 2 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | postlearn/_version.py export-subst 2 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include versioneer.py 2 | include postlearn/_version.py 3 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | Postlearn 2 | ========= 3 | 4 | Common post-estimation tasks for scikit-learn. 5 | -------------------------------------------------------------------------------- /readthedocs.yml: -------------------------------------------------------------------------------- 1 | conda: 2 | file: docs/environment.yml 3 | python: 4 | version: 3.5 5 | setup_py_install: true 6 | -------------------------------------------------------------------------------- /requirements_dev.txt: -------------------------------------------------------------------------------- 1 | bumpversion==0.5.3 2 | wheel==0.23.0 3 | watchdog==0.8.3 4 | flake8==2.4.1 5 | tox==2.1.1 6 | coverage==4.0 7 | Sphinx==1.3.1 8 | 9 | -------------------------------------------------------------------------------- /docs/environment.yml: -------------------------------------------------------------------------------- 1 | name: env 2 | dependencies: 3 | - python=3.5 4 | - nomkl=1.0 5 | - matplotlib=1.5.1 6 | - numpy=1.10.4 7 | - pandas=0.18.0 8 | - pip=8.1.1 9 | - python=3.5.1 10 | - scikit-learn=0.17.1 11 | - scipy=0.17.0 12 | - seaborn=0.7.0 13 | - numpydoc 14 | 15 | -------------------------------------------------------------------------------- /postlearn/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from .reporter import * # noqa 4 | from . import utils # noqa 5 | 6 | __author__ = 'Tom Augspurger' 7 | __email__ = 'tom.augspurger88@gmail.com' 8 | __version__ = '0.1.0' 9 | 10 | from ._version import get_versions # noqa 11 | __version__ = get_versions()['version'] 12 | del get_versions 13 | -------------------------------------------------------------------------------- /postlearn/templates/report.tpl: -------------------------------------------------------------------------------- 1 | --- 2 | title: 3 | - {{ title }} 4 | date: 5 | - {{ date }} 6 | --- 7 | 8 | Predicting the discrete variable {{ response }} with {{ predictors|length }} predictors. 9 | 10 | # Response Distribution 11 | 12 | {{ resposne_distribution }} 13 | 14 | # Important Predictors 15 | 16 | {{ important_predictors }} 17 | 18 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [wheel] 2 | universal = 1 3 | 4 | 5 | # See the docstring in versioneer.py for instructions. Note that you must 6 | # re-run 'versioneer.py setup' after changing this section, and commit the 7 | # resulting files. 8 | 9 | [versioneer] 10 | VCS = git 11 | style = pep440 12 | versionfile_source = postlearn/_version.py 13 | tag_prefix = 14 | parentdir_prefix = 15 | 16 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # Config file for automatic testing at travis-ci.org 2 | # This file will be regenerated if you run travis_pypi_setup.py 3 | 4 | language: python 5 | python: 3.5 6 | 7 | env: 8 | - TOXENV=py35 9 | - TOXENV=py34 10 | - TOXENV=py33 11 | - TOXENV=py27 12 | - TOXENV=py26 13 | - TOXENV=pypy 14 | 15 | # command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors 16 | install: pip install -U tox 17 | 18 | # command to run tests, e.g. python setup.py test 19 | script: tox 20 | 21 | 22 | -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | ===== 2 | Usage 3 | ===== 4 | 5 | There are two interfaces to the library. 6 | Anything that actually does something useful, like plotting the grid 7 | scores or a learning curve, is available as a top-level function. 8 | 9 | There are convenience classes built on top of these functions, 10 | These classes take a fit estimator, and the training data (optionally test data). 11 | The classes provide caching of predicted values and a few other conveniences. 12 | 13 | 14 | .. automodule:: postlearn.reporter 15 | :members: 16 | 17 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. postlearn documentation master file, created by 2 | sphinx-quickstart on Tue Jul 9 22:26:36 2013. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Postlearn 7 | ========= 8 | 9 | A collection of useful post-estimation diagnostics for scikit-learn 10 | models. 11 | 12 | Contents: 13 | 14 | .. toctree:: 15 | :maxdepth: 2 16 | 17 | readme 18 | usage 19 | 20 | Indices and tables 21 | ================== 22 | 23 | * :ref:`genindex` 24 | * :ref:`modindex` 25 | * :ref:`search` 26 | 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | 55 | # Sphinx documentation 56 | docs/_build/ 57 | 58 | # PyBuilder 59 | target/ 60 | wheels/ 61 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016 Tom Augspurger 2 | 3 | 4 | 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: 5 | 6 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 7 | 8 | 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. 9 | 10 | -------------------------------------------------------------------------------- /tests/test_cluster.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from sklearn.datasets import make_blobs 3 | from sklearn import cluster 4 | from sklearn.decomposition import PCA 5 | 6 | from postlearn.cluster import compute_centers, plot_decision_boundry 7 | 8 | 9 | @pytest.fixture 10 | def data_labels(): 11 | return make_blobs(random_state=2) 12 | 13 | 14 | class TestCluster: 15 | 16 | def test_compute_centers(self, data_labels): 17 | data, _ = data_labels 18 | ac = cluster.AgglomerativeClustering() 19 | fit = ac.fit(data) 20 | result = compute_centers(fit, data) 21 | 22 | assert result.shape == (data.shape[1], len(set(fit.labels_))) 23 | 24 | 25 | class TestPlotDecisionBoundry: 26 | 27 | @pytest.mark.parametrize('method', [ 28 | cluster.KMeans, cluster.AffinityPropagation, 29 | cluster.AgglomerativeClustering, cluster.MeanShift, 30 | cluster.SpectralClustering, 31 | ]) 32 | def test_smoke(self, data_labels, method): 33 | data, _ = data_labels 34 | est = method() 35 | est.fit(data) 36 | plot_decision_boundry(data, est) 37 | 38 | def test_reducer_instance3(self, data_labels): 39 | data, _ = data_labels 40 | red = PCA(n_components=2) 41 | est = cluster.KMeans() 42 | est.fit(data) 43 | plot_decision_boundry(data, est, reducer=red) 44 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from setuptools import setup 4 | 5 | import versioneer 6 | 7 | with open('README.rst', encoding='utf-8') as readme_file: 8 | readme = readme_file.read() 9 | 10 | requirements = [ 11 | 'pandas', 12 | 'scikit-learn' 13 | ] 14 | 15 | test_requirements = [ 16 | 'pytest' 17 | ] 18 | 19 | setup( 20 | name='postlearn', 21 | version=versioneer.get_version(), 22 | cmdclass=versioneer.get_cmdclass(), 23 | description="After fitting", 24 | long_description=readme, 25 | author="Tom Augspurger", 26 | author_email='tom.augspurger88@gmail.com', 27 | url='https://github.com/TomAugspurger/postlearn', 28 | packages=[ 29 | 'postlearn', 30 | ], 31 | package_dir={'postlearn': 32 | 'postlearn'}, 33 | include_package_data=True, 34 | install_requires=requirements, 35 | license="MIT", 36 | zip_safe=False, 37 | keywords='postlearn', 38 | classifiers=[ 39 | 'Development Status :: 2 - Pre-Alpha', 40 | 'Intended Audience :: Developers', 41 | 'License :: OSI Approved :: MIT License', 42 | 'Natural Language :: English', 43 | 'Programming Language :: Python :: 3', 44 | 'Programming Language :: Python :: 3.3', 45 | 'Programming Language :: Python :: 3.4', 46 | 'Programming Language :: Python :: 3.5', 47 | ], 48 | test_suite='tests', 49 | tests_require=test_requirements 50 | ) 51 | -------------------------------------------------------------------------------- /postlearn/utils.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib as mpl 3 | import matplotlib.pyplot as plt 4 | import matplotlib.cm as cm 5 | from sklearn.pipeline import Pipeline 6 | 7 | 8 | def model_from_pipeline(pipe): 9 | ''' 10 | Extract the model from the last stage of a pipeline. 11 | 12 | Parameters 13 | ---------- 14 | pipe : Pipeline or Estimator 15 | 16 | Returns 17 | ------- 18 | 19 | model: Estimator 20 | ''' 21 | if isinstance(pipe, Pipeline): 22 | return pipe[-1][1] 23 | else: 24 | return pipe 25 | 26 | 27 | def discrete_cmap(N, base_cmap=None): 28 | base = plt.cm.get_cmap(base_cmap) 29 | color_list = base(np.linspace(0, 1, N)) 30 | cmap_name = base.name + str(N) 31 | return base.from_list(cmap_name, color_list, N) 32 | 33 | 34 | def rediscretize_cmap(N, base_cmap=None): 35 | base = plt.cm.get_cmap(base_cmap) 36 | step = base.N // N 37 | 38 | if hasattr(base, 'colors'): 39 | colors = base.colors[0:base.N, step] 40 | else: 41 | colors = base(np.arange(0, base.N, step)) 42 | name = base.name + str(N) 43 | return mpl.colors.ListedColormap(colors, name, N) 44 | 45 | 46 | def colorbar_index(ncolors, cmap): 47 | # http://stackoverflow.com/a/18707445/1889400 48 | mappable = cm.ScalarMappable(cmap=cmap) 49 | mappable.set_array([]) 50 | mappable.set_clim(-0.5, ncolors + 0.5) 51 | colorbar = plt.colorbar(mappable) 52 | colorbar.set_ticks(np.linspace(0, ncolors, ncolors)) 53 | colorbar.set_ticklabels(range(ncolors)) 54 | 55 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: clean-pyc clean-build docs clean wheels 2 | help: 3 | @echo "clean - remove all build, test, coverage and Python artifacts" 4 | @echo "clean-build - remove build artifacts" 5 | @echo "clean-pyc - remove Python file artifacts" 6 | @echo "clean-test - remove test and coverage artifacts" 7 | @echo "lint - check style with flake8" 8 | @echo "test - run tests quickly with the default Python" 9 | @echo "test-all - run tests on every Python version with tox" 10 | @echo "coverage - check code coverage quickly with the default Python" 11 | @echo "docs - generate Sphinx HTML documentation, including API docs" 12 | @echo "release - package and upload a release" 13 | @echo "dist - package" 14 | @echo "install - install the package to the active Python's site-packages" 15 | 16 | clean: clean-build clean-pyc clean-test 17 | 18 | clean-build: 19 | rm -fr build/ 20 | rm -fr dist/ 21 | rm -fr .eggs/ 22 | find . -name '*.egg-info' -exec rm -fr {} + 23 | find . -name '*.egg' -exec rm -f {} + 24 | 25 | clean-pyc: 26 | find . -name '*.pyc' -exec rm -f {} + 27 | find . -name '*.pyo' -exec rm -f {} + 28 | find . -name '*~' -exec rm -f {} + 29 | find . -name '__pycache__' -exec rm -fr {} + 30 | 31 | clean-test: 32 | rm -fr .tox/ 33 | rm -f .coverage 34 | rm -fr htmlcov/ 35 | 36 | lint: 37 | flake8 postlearn tests 38 | 39 | test: 40 | python setup.py test 41 | 42 | test-all: 43 | tox 44 | 45 | coverage: 46 | coverage run --source postlearn setup.py test 47 | coverage report -m 48 | coverage html 49 | 50 | docs: 51 | rm -f docs/postlearn.rst 52 | rm -f docs/modules.rst 53 | sphinx-apidoc -o docs/ postlearn 54 | $(MAKE) -C docs clean 55 | $(MAKE) -C docs html 56 | 57 | release: clean 58 | python setup.py sdist upload 59 | python setup.py bdist_wheel upload 60 | 61 | dist: clean 62 | python setup.py sdist 63 | python setup.py bdist_wheel 64 | ls -l dist 65 | 66 | install: clean 67 | python setup.py install 68 | 69 | wheel: clean 70 | pip wheel --no-deps --wheel-dir=wheels . 71 | -------------------------------------------------------------------------------- /tests/test_reporter.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import string 3 | 4 | import pytest 5 | import numpy as np 6 | from sklearn.linear_model import LinearRegression, LogisticRegression 7 | from sklearn.preprocessing import StandardScaler 8 | from sklearn.pipeline import make_pipeline 9 | 10 | import postlearn as pl 11 | 12 | @pytest.fixture 13 | def X(): 14 | np.random.seed(42) 15 | return np.random.randn(10, 2) 16 | 17 | @pytest.fixture 18 | def y(): 19 | np.random.seed(32) 20 | return np.random.uniform(0, 1, size=10) 21 | 22 | @pytest.fixture 23 | def y_discrete(): 24 | np.random.seed(32) 25 | return np.random.randint(0, 2, size=10) 26 | 27 | 28 | @pytest.fixture 29 | def regression_model(): 30 | return LinearRegression() 31 | 32 | @pytest.fixture 33 | def classification_model(): 34 | return LogisticRegression() 35 | 36 | 37 | @pytest.fixture 38 | def regression_pipeline(regression_model): 39 | return make_pipeline([StandardScaler(), regression_model]) 40 | 41 | 42 | @pytest.fixture 43 | def fit_regression_model(regression_model, X, y): 44 | return regression_model.fit(X, y) 45 | 46 | 47 | @pytest.fixture 48 | def fit_classification_model(classification_model, X, y_discrete): 49 | return classification_model.fit(X, y_discrete) 50 | 51 | 52 | @pytest.fixture 53 | def result(fit_classification_model, X, y_discrete): 54 | return pl.ClassificationResults(fit_classification_model, X, y_discrete) 55 | 56 | 57 | @pytest.mark.parametrize("arg", [regression_model, regression_pipeline]) 58 | def test_model_from_pipeline(arg, regression_model): 59 | result = pl.utils.model_from_pipeline(regression_model) 60 | assert result == regression_model 61 | 62 | 63 | def test_confusion_matrix(result): 64 | cm = result.confusion_matrix() 65 | assert cm.index.name == 'actual' 66 | assert cm.columns.name == 'predicted' 67 | 68 | 69 | def test_plot_roc_curve(result): 70 | result.plot_roc_curve(y_true=result.y_train) 71 | 72 | def test_plot_feature_importance(fit_classification_model, X): 73 | pl.plot_feature_importance(fit_classification_model, 74 | labels=list(string.ascii_letters[X.shape[1]])) 75 | pl.plot_feature_importance(fit_classification_model, None) 76 | 77 | -------------------------------------------------------------------------------- /postlearn/cluster.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | from sklearn.neighbors import KDTree 4 | from sklearn.pipeline import Pipeline 5 | from sklearn.decomposition import PCA 6 | 7 | from postlearn.utils import rediscretize_cmap, colorbar_index 8 | 9 | 10 | def compute_centers(km, X): 11 | centers = [] 12 | for label in sorted(set(km.labels_)): 13 | centers.append(X[km.labels_ == label].mean(0)) 14 | 15 | return np.array(centers) 16 | 17 | 18 | def plot_decision_boundry(data, pipe, reducer=PCA): 19 | fig, ax = plt.subplots(figsize=(16, 12)) 20 | if callable(reducer): 21 | reducer = reducer(n_components=2) 22 | # else assume it's already been instantiated... 23 | 24 | if isinstance(pipe, Pipeline) and len(pipe.steps) > 1: 25 | prepipe = Pipeline(pipe.steps[:-1]) 26 | km = pipe.steps[-1][1] 27 | data_ = prepipe.transform(data) 28 | elif isinstance(pipe, Pipeline): 29 | prepipe = None 30 | km = pipe.steps[0][1] 31 | data_ = data 32 | else: 33 | prepipe = None 34 | km = pipe 35 | data_ = data 36 | 37 | X_reduced = reducer.fit_transform(data_) 38 | 39 | cluster_centers = getattr(km, 'cluster_centers_', 40 | compute_centers(km, data_)) 41 | 42 | mu_reduced = reducer.transform(cluster_centers) 43 | n_clusters = len(np.unique(km.labels_)) 44 | tree = KDTree(mu_reduced) 45 | 46 | cmap = rediscretize_cmap(n_clusters, 'Set1') 47 | ax.scatter(mu_reduced[:, 0], mu_reduced[:, 1], 48 | c=np.arange(n_clusters), cmap=cmap, 49 | s=300) 50 | colorbar_index(ncolors=n_clusters, cmap=cmap) 51 | 52 | ax.scatter(X_reduced[:, 0], X_reduced[:, 1], c=km.labels_, 53 | cmap=cmap, alpha=.95) 54 | 55 | xmin, xmax = ax.get_xlim() 56 | ymin, ymax = ax.get_ylim() 57 | 58 | xx, yy = np.meshgrid(np.linspace(xmin, xmax, 100), 59 | np.linspace(ymin, ymax, 100)) 60 | T = np.c_[xx.ravel(), yy.ravel()] 61 | _, group = tree.query(T) 62 | 63 | Z = group.ravel().reshape(xx.shape) 64 | ax.pcolormesh(xx, yy, Z, alpha=.25, cmap=cmap) 65 | ax.set_xlim(xmin, xmax) 66 | ax.set_ylim(ymin, ymax) 67 | 68 | for label, xy in enumerate(mu_reduced[:, :2]): 69 | ax.annotate(label, xy, fontsize=28, fontweight="bold") 70 | return ax 71 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(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/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/postlearn.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/postlearn.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/postlearn" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/postlearn" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | goto end 41 | ) 42 | 43 | if "%1" == "clean" ( 44 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 45 | del /q /s %BUILDDIR%\* 46 | goto end 47 | ) 48 | 49 | 50 | %SPHINXBUILD% 2> nul 51 | if errorlevel 9009 ( 52 | echo. 53 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 54 | echo.installed, then set the SPHINXBUILD environment variable to point 55 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 56 | echo.may add the Sphinx directory to PATH. 57 | echo. 58 | echo.If you don't have Sphinx installed, grab it from 59 | echo.http://sphinx-doc.org/ 60 | exit /b 1 61 | ) 62 | 63 | if "%1" == "html" ( 64 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 68 | goto end 69 | ) 70 | 71 | if "%1" == "dirhtml" ( 72 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 76 | goto end 77 | ) 78 | 79 | if "%1" == "singlehtml" ( 80 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 84 | goto end 85 | ) 86 | 87 | if "%1" == "pickle" ( 88 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can process the pickle files. 92 | goto end 93 | ) 94 | 95 | if "%1" == "json" ( 96 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 97 | if errorlevel 1 exit /b 1 98 | echo. 99 | echo.Build finished; now you can process the JSON files. 100 | goto end 101 | ) 102 | 103 | if "%1" == "htmlhelp" ( 104 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 105 | if errorlevel 1 exit /b 1 106 | echo. 107 | echo.Build finished; now you can run HTML Help Workshop with the ^ 108 | .hhp project file in %BUILDDIR%/htmlhelp. 109 | goto end 110 | ) 111 | 112 | if "%1" == "qthelp" ( 113 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 117 | .qhcp project file in %BUILDDIR%/qthelp, like this: 118 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\postlearn.qhcp 119 | echo.To view the help file: 120 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\postlearn.ghc 121 | goto end 122 | ) 123 | 124 | if "%1" == "devhelp" ( 125 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished. 129 | goto end 130 | ) 131 | 132 | if "%1" == "epub" ( 133 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 137 | goto end 138 | ) 139 | 140 | if "%1" == "latex" ( 141 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 145 | goto end 146 | ) 147 | 148 | if "%1" == "latexpdf" ( 149 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 150 | cd %BUILDDIR%/latex 151 | make all-pdf 152 | cd %BUILDDIR%/.. 153 | echo. 154 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 155 | goto end 156 | ) 157 | 158 | if "%1" == "latexpdfja" ( 159 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 160 | cd %BUILDDIR%/latex 161 | make all-pdf-ja 162 | cd %BUILDDIR%/.. 163 | echo. 164 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 165 | goto end 166 | ) 167 | 168 | if "%1" == "text" ( 169 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 170 | if errorlevel 1 exit /b 1 171 | echo. 172 | echo.Build finished. The text files are in %BUILDDIR%/text. 173 | goto end 174 | ) 175 | 176 | if "%1" == "man" ( 177 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 178 | if errorlevel 1 exit /b 1 179 | echo. 180 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 181 | goto end 182 | ) 183 | 184 | if "%1" == "texinfo" ( 185 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 186 | if errorlevel 1 exit /b 1 187 | echo. 188 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 189 | goto end 190 | ) 191 | 192 | if "%1" == "gettext" ( 193 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 194 | if errorlevel 1 exit /b 1 195 | echo. 196 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 197 | goto end 198 | ) 199 | 200 | if "%1" == "changes" ( 201 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 202 | if errorlevel 1 exit /b 1 203 | echo. 204 | echo.The overview file is in %BUILDDIR%/changes. 205 | goto end 206 | ) 207 | 208 | if "%1" == "linkcheck" ( 209 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 210 | if errorlevel 1 exit /b 1 211 | echo. 212 | echo.Link check complete; look for any errors in the above output ^ 213 | or in %BUILDDIR%/linkcheck/output.txt. 214 | goto end 215 | ) 216 | 217 | if "%1" == "doctest" ( 218 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 219 | if errorlevel 1 exit /b 1 220 | echo. 221 | echo.Testing of doctests in the sources finished, look at the ^ 222 | results in %BUILDDIR%/doctest/output.txt. 223 | goto end 224 | ) 225 | 226 | if "%1" == "xml" ( 227 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 228 | if errorlevel 1 exit /b 1 229 | echo. 230 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 231 | goto end 232 | ) 233 | 234 | if "%1" == "pseudoxml" ( 235 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 236 | if errorlevel 1 exit /b 1 237 | echo. 238 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 239 | goto end 240 | ) 241 | 242 | :end 243 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # 4 | # postlearn documentation build configuration file, created by 5 | # sphinx-quickstart on Tue Jul 9 22:26:36 2013. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | import sys 17 | import os 18 | import sphinx_rtd_theme 19 | 20 | # If extensions (or modules to document with autodoc) are in another 21 | # directory, add these directories to sys.path here. If the directory is 22 | # relative to the documentation root, use os.path.abspath to make it 23 | # absolute, like shown here. 24 | #sys.path.insert(0, os.path.abspath('.')) 25 | 26 | # Get the project root dir, which is the parent dir of this 27 | cwd = os.getcwd() 28 | project_root = os.path.dirname(cwd) 29 | 30 | # Insert the project root dir as the first element in the PYTHONPATH. 31 | # This lets us ensure that the source package is imported, and that its 32 | # version is used. 33 | sys.path.insert(0, project_root) 34 | 35 | import postlearn 36 | 37 | # -- General configuration --------------------------------------------- 38 | 39 | # If your documentation needs a minimal Sphinx version, state it here. 40 | #needs_sphinx = '1.0' 41 | 42 | # Add any Sphinx extension module names here, as strings. They can be 43 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 44 | extensions = ['sphinx.ext.autodoc', 'numpydoc'] 45 | 46 | numpydoc_show_class_members = False 47 | 48 | # Add any paths that contain templates here, relative to this directory. 49 | templates_path = ['_templates'] 50 | 51 | # The suffix of source filenames. 52 | source_suffix = '.rst' 53 | 54 | # The encoding of source files. 55 | #source_encoding = 'utf-8-sig' 56 | 57 | # The master toctree document. 58 | master_doc = 'index' 59 | 60 | # General information about the project. 61 | project = u'postlearn' 62 | copyright = u'2016, Tom Augspurger' 63 | 64 | # The version info for the project you're documenting, acts as replacement 65 | # for |version| and |release|, also used in various other places throughout 66 | # the built documents. 67 | # 68 | # The short X.Y version. 69 | version = postlearn.__version__ 70 | # The full version, including alpha/beta/rc tags. 71 | release = postlearn.__version__ 72 | 73 | # The language for content autogenerated by Sphinx. Refer to documentation 74 | # for a list of supported languages. 75 | #language = None 76 | 77 | # There are two options for replacing |today|: either, you set today to 78 | # some non-false value, then it is used: 79 | #today = '' 80 | # Else, today_fmt is used as the format for a strftime call. 81 | #today_fmt = '%B %d, %Y' 82 | 83 | # List of patterns, relative to source directory, that match files and 84 | # directories to ignore when looking for source files. 85 | exclude_patterns = ['_build'] 86 | 87 | # The reST default role (used for this markup: `text`) to use for all 88 | # documents. 89 | #default_role = None 90 | 91 | # If true, '()' will be appended to :func: etc. cross-reference text. 92 | #add_function_parentheses = True 93 | 94 | # If true, the current module name will be prepended to all description 95 | # unit titles (such as .. function::). 96 | #add_module_names = True 97 | 98 | # If true, sectionauthor and moduleauthor directives will be shown in the 99 | # output. They are ignored by default. 100 | #show_authors = False 101 | 102 | # The name of the Pygments (syntax highlighting) style to use. 103 | pygments_style = 'sphinx' 104 | 105 | # A list of ignored prefixes for module index sorting. 106 | #modindex_common_prefix = [] 107 | 108 | # If true, keep warnings as "system message" paragraphs in the built 109 | # documents. 110 | #keep_warnings = False 111 | 112 | 113 | # -- Options for HTML output ------------------------------------------- 114 | 115 | # The theme to use for HTML and HTML Help pages. See the documentation for 116 | # a list of builtin themes. 117 | html_theme = 'sphinx_rtd_theme' 118 | html_theme_path =['_themes'] 119 | 120 | # Theme options are theme-specific and customize the look and feel of a 121 | # theme further. For a list of options available for each theme, see the 122 | # documentation. 123 | #html_theme_options = {} 124 | 125 | # Add any paths that contain custom themes here, relative to this directory. 126 | #html_theme_path = [] 127 | 128 | # The name for this set of Sphinx documents. If None, it defaults to 129 | # " v documentation". 130 | #html_title = None 131 | 132 | # A shorter title for the navigation bar. Default is the same as 133 | # html_title. 134 | #html_short_title = None 135 | 136 | # The name of an image file (relative to this directory) to place at the 137 | # top of the sidebar. 138 | #html_logo = None 139 | 140 | # The name of an image file (within the static path) to use as favicon 141 | # of the docs. This file should be a Windows icon file (.ico) being 142 | # 16x16 or 32x32 pixels large. 143 | #html_favicon = None 144 | 145 | # Add any paths that contain custom static files (such as style sheets) 146 | # here, relative to this directory. They are copied after the builtin 147 | # static files, so a file named "default.css" will overwrite the builtin 148 | # "default.css". 149 | html_static_path = ['_static'] 150 | 151 | # If not '', a 'Last updated on:' timestamp is inserted at every page 152 | # bottom, using the given strftime format. 153 | #html_last_updated_fmt = '%b %d, %Y' 154 | 155 | # If true, SmartyPants will be used to convert quotes and dashes to 156 | # typographically correct entities. 157 | #html_use_smartypants = True 158 | 159 | # Custom sidebar templates, maps document names to template names. 160 | #html_sidebars = {} 161 | 162 | # Additional templates that should be rendered to pages, maps page names 163 | # to template names. 164 | #html_additional_pages = {} 165 | 166 | # If false, no module index is generated. 167 | #html_domain_indices = True 168 | 169 | # If false, no index is generated. 170 | #html_use_index = True 171 | 172 | # If true, the index is split into individual pages for each letter. 173 | #html_split_index = False 174 | 175 | # If true, links to the reST sources are added to the pages. 176 | #html_show_sourcelink = True 177 | 178 | # If true, "Created using Sphinx" is shown in the HTML footer. 179 | # Default is True. 180 | #html_show_sphinx = True 181 | 182 | # If true, "(C) Copyright ..." is shown in the HTML footer. 183 | # Default is True. 184 | #html_show_copyright = True 185 | 186 | # If true, an OpenSearch description file will be output, and all pages 187 | # will contain a tag referring to it. The value of this option 188 | # must be the base URL from which the finished HTML is served. 189 | #html_use_opensearch = '' 190 | 191 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 192 | #html_file_suffix = None 193 | 194 | # Output file base name for HTML help builder. 195 | htmlhelp_basename = 'postlearndoc' 196 | 197 | 198 | # -- Options for LaTeX output ------------------------------------------ 199 | 200 | latex_elements = { 201 | # The paper size ('letterpaper' or 'a4paper'). 202 | #'papersize': 'letterpaper', 203 | 204 | # The font size ('10pt', '11pt' or '12pt'). 205 | #'pointsize': '10pt', 206 | 207 | # Additional stuff for the LaTeX preamble. 208 | #'preamble': '', 209 | } 210 | 211 | # Grouping the document tree into LaTeX files. List of tuples 212 | # (source start file, target name, title, author, documentclass 213 | # [howto/manual]). 214 | latex_documents = [ 215 | ('index', 'postlearn.tex', 216 | u'postlearn Documentation', 217 | u'Tom Augspurger', 'manual'), 218 | ] 219 | 220 | # The name of an image file (relative to this directory) to place at 221 | # the top of the title page. 222 | #latex_logo = None 223 | 224 | # For "manual" documents, if this is true, then toplevel headings 225 | # are parts, not chapters. 226 | #latex_use_parts = False 227 | 228 | # If true, show page references after internal links. 229 | #latex_show_pagerefs = False 230 | 231 | # If true, show URL addresses after external links. 232 | #latex_show_urls = False 233 | 234 | # Documents to append as an appendix to all manuals. 235 | #latex_appendices = [] 236 | 237 | # If false, no module index is generated. 238 | #latex_domain_indices = True 239 | 240 | 241 | # -- Options for manual page output ------------------------------------ 242 | 243 | # One entry per manual page. List of tuples 244 | # (source start file, name, description, authors, manual section). 245 | man_pages = [ 246 | ('index', 'postlearn', 247 | u'postlearn Documentation', 248 | [u'Tom Augspurger'], 1) 249 | ] 250 | 251 | # If true, show URL addresses after external links. 252 | #man_show_urls = False 253 | 254 | 255 | # -- Options for Texinfo output ---------------------------------------- 256 | 257 | # Grouping the document tree into Texinfo files. List of tuples 258 | # (source start file, target name, title, author, 259 | # dir menu entry, description, category) 260 | texinfo_documents = [ 261 | ('index', 'postlearn', 262 | u'postlearn Documentation', 263 | u'Tom Augspurger', 264 | 'postlearn', 265 | 'One line description of project.', 266 | 'Miscellaneous'), 267 | ] 268 | 269 | # Documents to append as an appendix to all manuals. 270 | #texinfo_appendices = [] 271 | 272 | # If false, no module index is generated. 273 | #texinfo_domain_indices = True 274 | 275 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 276 | #texinfo_show_urls = 'footnote' 277 | 278 | # If true, do not generate a @detailmenu in the "Top" node's menu. 279 | #texinfo_no_detailmenu = False 280 | -------------------------------------------------------------------------------- /postlearn/reporter.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | ''' 3 | Post-estimation reporting methods. 4 | ''' 5 | import inspect 6 | from functools import wraps 7 | 8 | import numpy as np 9 | import pandas as pd 10 | import seaborn as sns 11 | from sklearn import metrics 12 | from sklearn.model_selection import learning_curve 13 | import matplotlib.pyplot as plt 14 | 15 | from . import utils 16 | 17 | try: 18 | from ipywidgets import interact 19 | has_widgets = True 20 | except ImportError: 21 | has_widgets = False 22 | 23 | 24 | def extract_grid_scores(model): 25 | ''' 26 | Extract grid scores from a model or pipeline. 27 | 28 | Parameters 29 | ---------- 30 | model : Estimator or Pipeline 31 | must end in sklearn.model_selection.GridSearchCV 32 | 33 | Returns 34 | ------- 35 | scores : list 36 | 37 | See Also 38 | -------- 39 | unpack_grid_scores 40 | ''' 41 | model = utils.model_from_pipeline(model) 42 | return model.grid_scores_ 43 | 44 | 45 | def unpack_grid_scores(model=None): 46 | ''' 47 | Unpack mean grid scores into a DataFrame 48 | 49 | Parameters 50 | ---------- 51 | model : Estimator or Pipeline 52 | must end in sklearn.model_selection.GridSearchCV 53 | 54 | Returns 55 | ------- 56 | scores : DataFrame 57 | 58 | Examples 59 | -------- 60 | >>> from sklearn.ensemble import RandomForestClassifier 61 | >>> from sklearn import datasets 62 | >>> from sklearn.model_selection import GridSearchCV 63 | >>> from sklearn.preprocessing import StandardScaler 64 | >>> X, y =datasets.make_classification() 65 | >>> model = GridSearchCV(RandomForestClassifier(), 66 | ... param_grid={ 67 | ... 'n_estimators': [10, 20, 30], 68 | ... 'max_features': [.1, .5, 1] 69 | ... }) 70 | >>> model.fit(X, y) 71 | >>> unpack_grid_scores(model) 72 | mean_ std_ max_features n_estimators 73 | 0 0.88 0.062416 0.1 10 74 | 1 0.88 0.046536 0.1 20 75 | 2 0.85 0.095309 0.1 30 76 | 3 0.88 0.062686 0.5 10 77 | 4 0.91 0.072044 0.5 20 78 | 5 0.90 0.073366 0.5 30 79 | 6 0.78 0.032929 1.0 10 80 | 7 0.86 0.048224 1.0 20 81 | 8 0.85 0.072174 1.0 30 82 | 83 | See Also 84 | -------- 85 | plot_grid_scores 86 | ''' 87 | model = utils.model_from_pipeline(model) 88 | scores = model.grid_scores_ 89 | rows = [] 90 | params = sorted(scores[0].parameters) 91 | for row in scores: 92 | mean = row.mean_validation_score 93 | std = row.cv_validation_scores.std() 94 | rows.append([mean, std] + [row.parameters[k] for k in params]) 95 | return pd.DataFrame(rows, columns=['mean_', 'std_'] + params) 96 | 97 | 98 | def plot_grid_scores(model, x, y=None, hue=None, row=None, col=None, col_wrap=None, 99 | **kwargs): 100 | ''' 101 | Wrapper around seaborn.factorplot. 102 | 103 | Parameters 104 | ---------- 105 | model : Pipeline or Estimator 106 | x, hue, row, col : str 107 | parameters grid searched over 108 | y : str 109 | the target of interest, default `'mean_'` 110 | 111 | Returns 112 | ------- 113 | g : seaborn.FacetGrid 114 | ''' 115 | scores = unpack_grid_scores(model) 116 | y = y or 'mean_' 117 | return sns.factorplot(x=x, y=y, hue=hue, row=row, col=col, data=scores, 118 | col_wrap=col_wrap, **kwargs) 119 | 120 | 121 | def plot_roc_curve(y_true, y_score, ax=None): 122 | ''' 123 | Plot the Receiving Operator Characteristic curved, including the 124 | Area under the Curve (AUC) score. 125 | 126 | Parameters 127 | ---------- 128 | y_true : array 129 | y_score : array 130 | ax : matplotlib.axes, defaults to new axes 131 | 132 | Returns 133 | ------- 134 | ax : matplotlib.axes 135 | ''' 136 | ax = ax or plt.axes() 137 | auc = metrics.roc_auc_score(y_true, y_score) 138 | fpr, tpr, _ = metrics.roc_curve(y_true, y_score) 139 | ax.plot(fpr, tpr) 140 | ax.annotate('AUC: {:.2f}'.format(auc), (.8, .2)) 141 | ax.plot([0, 1], [0, 1], linestyle='--', color='k') 142 | return ax 143 | 144 | 145 | def plot_regularization_path(model): 146 | ''' 147 | Plot the regularization path of coefficients from e.g. a Lasso 148 | ''' 149 | raise ValueError 150 | 151 | 152 | def plot_learning_curve(estimator, X, y, train_sizes=np.linspace(.1, 1.0, 5), 153 | cv=None, n_jobs=1, ax=None): 154 | ''' 155 | Plot the learning curve for `estimator`. 156 | 157 | Parameters 158 | ---------- 159 | estimator : sklearn.Estimator 160 | X : array-like 161 | y : array-like 162 | train_sizes : array-like 163 | list of floats between 0 and 1 164 | cv : int 165 | n_jobs : int 166 | ax : matplotlib.axes 167 | ''' 168 | # http://scikit-learn.org/stable/auto_examples/model_selection/plot_learning_curve.html 169 | if ax is None: 170 | fig, ax = plt.subplots() 171 | ax.set_xlabel("Training examples") 172 | ax.set_ylabel("Score") 173 | train_sizes, train_scores, test_scores = learning_curve( 174 | estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes 175 | ) 176 | train_scores_mean = np.mean(train_scores, axis=1) 177 | train_scores_std = np.std(train_scores, axis=1) 178 | test_scores_mean = np.mean(test_scores, axis=1) 179 | test_scores_std = np.std(test_scores, axis=1) 180 | plt.grid() 181 | 182 | plt.fill_between(train_sizes, train_scores_mean - train_scores_std, 183 | train_scores_mean + train_scores_std, alpha=0.1, 184 | color="r") 185 | plt.fill_between(train_sizes, test_scores_mean - test_scores_std, 186 | test_scores_mean + test_scores_std, alpha=0.1, color="g") 187 | plt.plot(train_sizes, train_scores_mean, 'o-', color="r", 188 | label="Training score") 189 | plt.plot(train_sizes, test_scores_mean, 'o-', color="g", 190 | label="Cross-validation score") 191 | 192 | plt.legend(loc="best") 193 | return ax 194 | 195 | 196 | def _get_feature_importance(model): 197 | ''' 198 | LinearModels: `.coef_` 199 | ensemble: `feature_importances_` 200 | ''' 201 | order = ['coef_', 'feature_importances_'] 202 | for attr in order: 203 | if hasattr(model, attr): 204 | return getattr(model, attr) 205 | else: 206 | raise ValueError("The model does not have any of {}".format(order)) 207 | 208 | 209 | def _magsort(s): 210 | '''Sort a Series by magnitude, ignoring direction (sign).''' 211 | return s[np.abs(s).argsort()] 212 | 213 | 214 | def plot_feature_importance(model, labels, n=10, orient='h'): 215 | ''' 216 | Bar plot of feature importance. 217 | 218 | Parameters 219 | ---------- 220 | model : Pipeline or Estimator 221 | labels : list-like 222 | n : int 223 | number of features to include 224 | orient : {'h', 'v'} 225 | horizontal or vertical barplot 226 | 227 | Returns 228 | ------- 229 | ax : matplotlib.axes 230 | 231 | Notes 232 | ----- 233 | Works with Regression, coefs_, or ensembes with feature_importances_ 234 | 235 | ''' 236 | model = utils.model_from_pipeline(model) 237 | if orient.lower().startswith('h'): 238 | kind = 'barh' 239 | elif orient.lower().startswith('v'): 240 | kind = 'bar' 241 | else: 242 | raise ValueError("`orient` should be 'v' or 'h', got %s instead" % 243 | orient) 244 | features = _get_feature_importance(model) 245 | if labels: 246 | features = features.reshape(len(labels), -1) 247 | features = (pd.DataFrame(features, index=labels) 248 | .squeeze() 249 | .pipe(_magsort) 250 | .tail(n) 251 | .plot(kind=kind)) 252 | return features 253 | 254 | 255 | def confusion_matrix(y_true=None, y_pred=None, labels=None): 256 | ''' 257 | Dataframe of confusion matrix. Rows are actual, and columns are predicted. 258 | 259 | Parameters 260 | ---------- 261 | y_true : array 262 | y_pred : array 263 | labels : list-like 264 | 265 | Returns 266 | ------- 267 | confusion_matrix : DataFrame 268 | ''' 269 | df = (pd.DataFrame(metrics.confusion_matrix(y_true, y_pred), 270 | index=labels, columns=labels) 271 | .rename_axis("actual") 272 | .rename_axis("predicted", axis=1)) 273 | return df 274 | 275 | 276 | def default_args(**attrs): 277 | ''' 278 | Pull the defaults for a method from `self`. 279 | 280 | Parameters 281 | ---------- 282 | attrs : dict 283 | mapping parameter name to attribute name 284 | Attributes with the same name need not be included. 285 | 286 | Returns 287 | ------- 288 | deco: new function, injecting the `attrs` into `kwargs` 289 | 290 | Notes 291 | ----- 292 | Only usable with keyword-only arguments. 293 | 294 | Examples 295 | -------- 296 | 297 | @default_args({'y': 'y_train'}) 298 | def printer(self, *, y=None, y_pred=None): 299 | print('y: ', y) 300 | print('y_pred: ', y_pred) 301 | ''' 302 | def deco(func): 303 | @wraps(func) 304 | def wrapper(self, **kwargs): 305 | sig = inspect.signature(func) 306 | keys = {k for k in sig.parameters if k != 'self'} 307 | for kw in keys: 308 | # TODO: Broken 309 | if kwargs.get(kw) is None: 310 | kwargs[kw] = getattr(self, attrs.get(kw, kw), 311 | sig.parameters[kw].default) 312 | return func(self, **kwargs) 313 | return wrapper 314 | return deco 315 | 316 | 317 | class GridSearchMixin: 318 | ''' 319 | Helper methods appropriate for estimators fit with a GridSearch. 320 | ''' 321 | 322 | def plot_grid_scores(self, x, hue=None, row=None, col=None, col_wrap=None, 323 | **kwargs): 324 | def none_if_none(x): 325 | return None if x == 'None' else x 326 | 327 | if has_widgets: 328 | choices = ['None'] + list(unpack_grid_scores(self.model) 329 | .columns.drop(['mean_', 'std_'])) 330 | 331 | @interact(x=choices, hue=choices, row=choices, col=choices) 332 | def wrapper(x=x, hue=None, row=None, col=None): 333 | return plot_grid_scores(self.model, 334 | none_if_none(x), 335 | 'mean_', 336 | hue=none_if_none(hue), 337 | row=none_if_none(row), 338 | col=none_if_none(col), 339 | col_wrap=none_if_none(col_wrap), 340 | **kwargs) 341 | return wrapper 342 | else: 343 | return plot_grid_scores(self.model, x, 'mean_', hue=hue, row=row, 344 | col=col, col_wrap=col_wrap, **kwargs) 345 | 346 | 347 | class ClassificationResults(GridSearchMixin): 348 | ''' 349 | A convinience class, wrapping all the reporting methods and 350 | caching intermediate calculations. 351 | ''' 352 | 353 | def __init__(self, model, X_train, y_train, X_test=None, y_test=None, 354 | labels=None): 355 | ''' 356 | Parameters 357 | ---------- 358 | model : Pipeline or Estimator 359 | X_train : np.array 360 | y_train : np.array 361 | X_test : np.array 362 | y_test : np.array 363 | labels : list of str 364 | ''' 365 | self.model = model 366 | self.X_train = X_train 367 | self.y_train = y_train 368 | self.X_test = X_test 369 | self.y_test = y_test 370 | self._y_score_train = None 371 | self._y_score_test = None 372 | self._y_pred_train = None 373 | self._y_pred_test = None 374 | self._proba_train = None 375 | self._proba_test = None 376 | 377 | if labels is None: 378 | labels = sorted(np.unique(y_train)) 379 | self.labels = labels 380 | 381 | @property 382 | def y_pred_train(self): 383 | 'Predicted values for the training set' 384 | if self._y_pred_train is None: 385 | self._y_pred_train = self.model.predict(self.X_train) 386 | return self._y_pred_train 387 | 388 | @property 389 | def y_pred_test(self): 390 | 'Predicted values for the test set' 391 | if self._y_pred_test is None: 392 | self._y_pred_test = self.model.predict(self.X_test) 393 | return self._y_pred_test 394 | 395 | @property 396 | def proba_train(self): 397 | 'Predicted probabilities for the training set' 398 | if self._proba_train is None: 399 | self._proba_train = self.model.predict_proba(self.X_train) 400 | return self._proba_train 401 | 402 | @property 403 | def proba_test(self): 404 | 'Predicted probabilities for the test set' 405 | if self._proba_test is None: 406 | self._proba_test = self.model.predict_proba(self.X_test) 407 | return self._proba_test 408 | 409 | @property 410 | def y_score_train(self): 411 | 'Predicted positive score (column 1) for the training set' 412 | if self._y_score_train is None: 413 | self._y_score_train = self.proba_train[:, 1] 414 | return self._y_score_train 415 | 416 | @property 417 | def y_score_test(self): 418 | 'Predicted positive score (column 1) for the test set' 419 | if self._y_score_test is None: 420 | self._y_score_test = self.proba_test[:, 1] 421 | return self._y_score_test 422 | 423 | @default_args(y_true='y_train', y_pred='y_pred_train') 424 | def confusion_matrix(self, y_true=None, y_pred=None, labels=None): 425 | return confusion_matrix(y_true=y_true, 426 | y_pred=y_pred, 427 | labels=labels) 428 | 429 | @default_args(y_true='y_train', y_pred='y_pred_train') 430 | def accuracy_score(self, y_true=None, y_pred=None, labels=None, 431 | normalize=True, sample_weight=None): 432 | return metrics.accuracy_score(y_true=y_true, 433 | y_pred=y_pred, 434 | normalize=normalize, 435 | sample_weight=sample_weight) 436 | 437 | @default_args(y_true='y_train', y_score='y_score_train') 438 | def plot_roc_curve(self, *, ax=None, y_true=None, y_score=None): 439 | ''' 440 | Plot the ROC. 441 | ''' 442 | return plot_roc_curve(y_true=y_true, y_score=y_score, ax=ax) 443 | 444 | def make_report(self): 445 | pass 446 | 447 | @default_args(X='X_train', y='y_train') 448 | def plot_learning_curve(self, *, X=None, y=None, 449 | train_sizes=np.linspace(.1, 1.0, 5), 450 | cv=None, 451 | n_jobs=1, 452 | ax=None): 453 | return plot_learning_curve(self.model, X=X, y=y, cv=cv, 454 | train_sizes=train_sizes, 455 | n_jobs=n_jobs, 456 | ax=ax) 457 | 458 | -------------------------------------------------------------------------------- /postlearn/_version.py: -------------------------------------------------------------------------------- 1 | 2 | # This file helps to compute a version number in source trees obtained from 3 | # git-archive tarball (such as those provided by githubs download-from-tag 4 | # feature). Distribution tarballs (built by setup.py sdist) and build 5 | # directories (produced by setup.py build) will contain a much shorter file 6 | # that just contains the computed version number. 7 | 8 | # This file is released into the public domain. Generated by 9 | # versioneer-0.15 (https://github.com/warner/python-versioneer) 10 | 11 | import errno 12 | import os 13 | import re 14 | import subprocess 15 | import sys 16 | 17 | 18 | def get_keywords(): 19 | # these strings will be replaced by git during git-archive. 20 | # setup.py/versioneer.py will grep for the variable names, so they must 21 | # each be defined on a line of their own. _version.py will just call 22 | # get_keywords(). 23 | git_refnames = " (HEAD -> master, tag: 0.4.0)" 24 | git_full = "14c63045d46990802408fc1082b5488b454e74e4" 25 | keywords = {"refnames": git_refnames, "full": git_full} 26 | return keywords 27 | 28 | 29 | class VersioneerConfig: 30 | pass 31 | 32 | 33 | def get_config(): 34 | # these strings are filled in when 'setup.py versioneer' creates 35 | # _version.py 36 | cfg = VersioneerConfig() 37 | cfg.VCS = "git" 38 | cfg.style = "pep440" 39 | cfg.tag_prefix = "" 40 | cfg.parentdir_prefix = "" 41 | cfg.versionfile_source = "postlearn/_version.py" 42 | cfg.verbose = False 43 | return cfg 44 | 45 | 46 | class NotThisMethod(Exception): 47 | pass 48 | 49 | 50 | LONG_VERSION_PY = {} 51 | HANDLERS = {} 52 | 53 | 54 | def register_vcs_handler(vcs, method): # decorator 55 | def decorate(f): 56 | if vcs not in HANDLERS: 57 | HANDLERS[vcs] = {} 58 | HANDLERS[vcs][method] = f 59 | return f 60 | return decorate 61 | 62 | 63 | def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): 64 | assert isinstance(commands, list) 65 | p = None 66 | for c in commands: 67 | try: 68 | dispcmd = str([c] + args) 69 | # remember shell=False, so use git.cmd on windows, not just git 70 | p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE, 71 | stderr=(subprocess.PIPE if hide_stderr 72 | else None)) 73 | break 74 | except EnvironmentError: 75 | e = sys.exc_info()[1] 76 | if e.errno == errno.ENOENT: 77 | continue 78 | if verbose: 79 | print("unable to run %s" % dispcmd) 80 | print(e) 81 | return None 82 | else: 83 | if verbose: 84 | print("unable to find command, tried %s" % (commands,)) 85 | return None 86 | stdout = p.communicate()[0].strip() 87 | if sys.version_info[0] >= 3: 88 | stdout = stdout.decode() 89 | if p.returncode != 0: 90 | if verbose: 91 | print("unable to run %s (error)" % dispcmd) 92 | return None 93 | return stdout 94 | 95 | 96 | def versions_from_parentdir(parentdir_prefix, root, verbose): 97 | # Source tarballs conventionally unpack into a directory that includes 98 | # both the project name and a version string. 99 | dirname = os.path.basename(root) 100 | if not dirname.startswith(parentdir_prefix): 101 | if verbose: 102 | print("guessing rootdir is '%s', but '%s' doesn't start with " 103 | "prefix '%s'" % (root, dirname, parentdir_prefix)) 104 | raise NotThisMethod("rootdir doesn't start with parentdir_prefix") 105 | return {"version": dirname[len(parentdir_prefix):], 106 | "full-revisionid": None, 107 | "dirty": False, "error": None} 108 | 109 | 110 | @register_vcs_handler("git", "get_keywords") 111 | def git_get_keywords(versionfile_abs): 112 | # the code embedded in _version.py can just fetch the value of these 113 | # keywords. When used from setup.py, we don't want to import _version.py, 114 | # so we do it with a regexp instead. This function is not used from 115 | # _version.py. 116 | keywords = {} 117 | try: 118 | f = open(versionfile_abs, "r") 119 | for line in f.readlines(): 120 | if line.strip().startswith("git_refnames ="): 121 | mo = re.search(r'=\s*"(.*)"', line) 122 | if mo: 123 | keywords["refnames"] = mo.group(1) 124 | if line.strip().startswith("git_full ="): 125 | mo = re.search(r'=\s*"(.*)"', line) 126 | if mo: 127 | keywords["full"] = mo.group(1) 128 | f.close() 129 | except EnvironmentError: 130 | pass 131 | return keywords 132 | 133 | 134 | @register_vcs_handler("git", "keywords") 135 | def git_versions_from_keywords(keywords, tag_prefix, verbose): 136 | if not keywords: 137 | raise NotThisMethod("no keywords at all, weird") 138 | refnames = keywords["refnames"].strip() 139 | if refnames.startswith("$Format"): 140 | if verbose: 141 | print("keywords are unexpanded, not using") 142 | raise NotThisMethod("unexpanded keywords, not a git-archive tarball") 143 | refs = set([r.strip() for r in refnames.strip("()").split(",")]) 144 | # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of 145 | # just "foo-1.0". If we see a "tag: " prefix, prefer those. 146 | TAG = "tag: " 147 | tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) 148 | if not tags: 149 | # Either we're using git < 1.8.3, or there really are no tags. We use 150 | # a heuristic: assume all version tags have a digit. The old git %d 151 | # expansion behaves like git log --decorate=short and strips out the 152 | # refs/heads/ and refs/tags/ prefixes that would let us distinguish 153 | # between branches and tags. By ignoring refnames without digits, we 154 | # filter out many common branch names like "release" and 155 | # "stabilization", as well as "HEAD" and "master". 156 | tags = set([r for r in refs if re.search(r'\d', r)]) 157 | if verbose: 158 | print("discarding '%s', no digits" % ",".join(refs-tags)) 159 | if verbose: 160 | print("likely tags: %s" % ",".join(sorted(tags))) 161 | for ref in sorted(tags): 162 | # sorting will prefer e.g. "2.0" over "2.0rc1" 163 | if ref.startswith(tag_prefix): 164 | r = ref[len(tag_prefix):] 165 | if verbose: 166 | print("picking %s" % r) 167 | return {"version": r, 168 | "full-revisionid": keywords["full"].strip(), 169 | "dirty": False, "error": None 170 | } 171 | # no suitable tags, so version is "0+unknown", but full hex is still there 172 | if verbose: 173 | print("no suitable tags, using unknown + full revision id") 174 | return {"version": "0+unknown", 175 | "full-revisionid": keywords["full"].strip(), 176 | "dirty": False, "error": "no suitable tags"} 177 | 178 | 179 | @register_vcs_handler("git", "pieces_from_vcs") 180 | def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): 181 | # this runs 'git' from the root of the source tree. This only gets called 182 | # if the git-archive 'subst' keywords were *not* expanded, and 183 | # _version.py hasn't already been rewritten with a short version string, 184 | # meaning we're inside a checked out source tree. 185 | 186 | if not os.path.exists(os.path.join(root, ".git")): 187 | if verbose: 188 | print("no .git in %s" % root) 189 | raise NotThisMethod("no .git directory") 190 | 191 | GITS = ["git"] 192 | if sys.platform == "win32": 193 | GITS = ["git.cmd", "git.exe"] 194 | # if there is a tag, this yields TAG-NUM-gHEX[-dirty] 195 | # if there are no tags, this yields HEX[-dirty] (no NUM) 196 | describe_out = run_command(GITS, ["describe", "--tags", "--dirty", 197 | "--always", "--long"], 198 | cwd=root) 199 | # --long was added in git-1.5.5 200 | if describe_out is None: 201 | raise NotThisMethod("'git describe' failed") 202 | describe_out = describe_out.strip() 203 | full_out = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) 204 | if full_out is None: 205 | raise NotThisMethod("'git rev-parse' failed") 206 | full_out = full_out.strip() 207 | 208 | pieces = {} 209 | pieces["long"] = full_out 210 | pieces["short"] = full_out[:7] # maybe improved later 211 | pieces["error"] = None 212 | 213 | # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] 214 | # TAG might have hyphens. 215 | git_describe = describe_out 216 | 217 | # look for -dirty suffix 218 | dirty = git_describe.endswith("-dirty") 219 | pieces["dirty"] = dirty 220 | if dirty: 221 | git_describe = git_describe[:git_describe.rindex("-dirty")] 222 | 223 | # now we have TAG-NUM-gHEX or HEX 224 | 225 | if "-" in git_describe: 226 | # TAG-NUM-gHEX 227 | mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) 228 | if not mo: 229 | # unparseable. Maybe git-describe is misbehaving? 230 | pieces["error"] = ("unable to parse git-describe output: '%s'" 231 | % describe_out) 232 | return pieces 233 | 234 | # tag 235 | full_tag = mo.group(1) 236 | if not full_tag.startswith(tag_prefix): 237 | if verbose: 238 | fmt = "tag '%s' doesn't start with prefix '%s'" 239 | print(fmt % (full_tag, tag_prefix)) 240 | pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" 241 | % (full_tag, tag_prefix)) 242 | return pieces 243 | pieces["closest-tag"] = full_tag[len(tag_prefix):] 244 | 245 | # distance: number of commits since tag 246 | pieces["distance"] = int(mo.group(2)) 247 | 248 | # commit: short hex revision ID 249 | pieces["short"] = mo.group(3) 250 | 251 | else: 252 | # HEX: no tags 253 | pieces["closest-tag"] = None 254 | count_out = run_command(GITS, ["rev-list", "HEAD", "--count"], 255 | cwd=root) 256 | pieces["distance"] = int(count_out) # total number of commits 257 | 258 | return pieces 259 | 260 | 261 | def plus_or_dot(pieces): 262 | if "+" in pieces.get("closest-tag", ""): 263 | return "." 264 | return "+" 265 | 266 | 267 | def render_pep440(pieces): 268 | # now build up version string, with post-release "local version 269 | # identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you 270 | # get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty 271 | 272 | # exceptions: 273 | # 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] 274 | 275 | if pieces["closest-tag"]: 276 | rendered = pieces["closest-tag"] 277 | if pieces["distance"] or pieces["dirty"]: 278 | rendered += plus_or_dot(pieces) 279 | rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) 280 | if pieces["dirty"]: 281 | rendered += ".dirty" 282 | else: 283 | # exception #1 284 | rendered = "0+untagged.%d.g%s" % (pieces["distance"], 285 | pieces["short"]) 286 | if pieces["dirty"]: 287 | rendered += ".dirty" 288 | return rendered 289 | 290 | 291 | def render_pep440_pre(pieces): 292 | # TAG[.post.devDISTANCE] . No -dirty 293 | 294 | # exceptions: 295 | # 1: no tags. 0.post.devDISTANCE 296 | 297 | if pieces["closest-tag"]: 298 | rendered = pieces["closest-tag"] 299 | if pieces["distance"]: 300 | rendered += ".post.dev%d" % pieces["distance"] 301 | else: 302 | # exception #1 303 | rendered = "0.post.dev%d" % pieces["distance"] 304 | return rendered 305 | 306 | 307 | def render_pep440_post(pieces): 308 | # TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that 309 | # .dev0 sorts backwards (a dirty tree will appear "older" than the 310 | # corresponding clean one), but you shouldn't be releasing software with 311 | # -dirty anyways. 312 | 313 | # exceptions: 314 | # 1: no tags. 0.postDISTANCE[.dev0] 315 | 316 | if pieces["closest-tag"]: 317 | rendered = pieces["closest-tag"] 318 | if pieces["distance"] or pieces["dirty"]: 319 | rendered += ".post%d" % pieces["distance"] 320 | if pieces["dirty"]: 321 | rendered += ".dev0" 322 | rendered += plus_or_dot(pieces) 323 | rendered += "g%s" % pieces["short"] 324 | else: 325 | # exception #1 326 | rendered = "0.post%d" % pieces["distance"] 327 | if pieces["dirty"]: 328 | rendered += ".dev0" 329 | rendered += "+g%s" % pieces["short"] 330 | return rendered 331 | 332 | 333 | def render_pep440_old(pieces): 334 | # TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. 335 | 336 | # exceptions: 337 | # 1: no tags. 0.postDISTANCE[.dev0] 338 | 339 | if pieces["closest-tag"]: 340 | rendered = pieces["closest-tag"] 341 | if pieces["distance"] or pieces["dirty"]: 342 | rendered += ".post%d" % pieces["distance"] 343 | if pieces["dirty"]: 344 | rendered += ".dev0" 345 | else: 346 | # exception #1 347 | rendered = "0.post%d" % pieces["distance"] 348 | if pieces["dirty"]: 349 | rendered += ".dev0" 350 | return rendered 351 | 352 | 353 | def render_git_describe(pieces): 354 | # TAG[-DISTANCE-gHEX][-dirty], like 'git describe --tags --dirty 355 | # --always' 356 | 357 | # exceptions: 358 | # 1: no tags. HEX[-dirty] (note: no 'g' prefix) 359 | 360 | if pieces["closest-tag"]: 361 | rendered = pieces["closest-tag"] 362 | if pieces["distance"]: 363 | rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) 364 | else: 365 | # exception #1 366 | rendered = pieces["short"] 367 | if pieces["dirty"]: 368 | rendered += "-dirty" 369 | return rendered 370 | 371 | 372 | def render_git_describe_long(pieces): 373 | # TAG-DISTANCE-gHEX[-dirty], like 'git describe --tags --dirty 374 | # --always -long'. The distance/hash is unconditional. 375 | 376 | # exceptions: 377 | # 1: no tags. HEX[-dirty] (note: no 'g' prefix) 378 | 379 | if pieces["closest-tag"]: 380 | rendered = pieces["closest-tag"] 381 | rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) 382 | else: 383 | # exception #1 384 | rendered = pieces["short"] 385 | if pieces["dirty"]: 386 | rendered += "-dirty" 387 | return rendered 388 | 389 | 390 | def render(pieces, style): 391 | if pieces["error"]: 392 | return {"version": "unknown", 393 | "full-revisionid": pieces.get("long"), 394 | "dirty": None, 395 | "error": pieces["error"]} 396 | 397 | if not style or style == "default": 398 | style = "pep440" # the default 399 | 400 | if style == "pep440": 401 | rendered = render_pep440(pieces) 402 | elif style == "pep440-pre": 403 | rendered = render_pep440_pre(pieces) 404 | elif style == "pep440-post": 405 | rendered = render_pep440_post(pieces) 406 | elif style == "pep440-old": 407 | rendered = render_pep440_old(pieces) 408 | elif style == "git-describe": 409 | rendered = render_git_describe(pieces) 410 | elif style == "git-describe-long": 411 | rendered = render_git_describe_long(pieces) 412 | else: 413 | raise ValueError("unknown style '%s'" % style) 414 | 415 | return {"version": rendered, "full-revisionid": pieces["long"], 416 | "dirty": pieces["dirty"], "error": None} 417 | 418 | 419 | def get_versions(): 420 | # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have 421 | # __file__, we can work backwards from there to the root. Some 422 | # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which 423 | # case we can only use expanded keywords. 424 | 425 | cfg = get_config() 426 | verbose = cfg.verbose 427 | 428 | try: 429 | return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, 430 | verbose) 431 | except NotThisMethod: 432 | pass 433 | 434 | try: 435 | root = os.path.realpath(__file__) 436 | # versionfile_source is the relative path from the top of the source 437 | # tree (where the .git directory might live) to this file. Invert 438 | # this to find the root from __file__. 439 | for i in cfg.versionfile_source.split('/'): 440 | root = os.path.dirname(root) 441 | except NameError: 442 | return {"version": "0+unknown", "full-revisionid": None, 443 | "dirty": None, 444 | "error": "unable to find root of source tree"} 445 | 446 | try: 447 | pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) 448 | return render(pieces, cfg.style) 449 | except NotThisMethod: 450 | pass 451 | 452 | try: 453 | if cfg.parentdir_prefix: 454 | return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) 455 | except NotThisMethod: 456 | pass 457 | 458 | return {"version": "0+unknown", "full-revisionid": None, 459 | "dirty": None, 460 | "error": "unable to compute version"} 461 | -------------------------------------------------------------------------------- /versioneer.py: -------------------------------------------------------------------------------- 1 | 2 | # Version: 0.15 3 | 4 | """ 5 | The Versioneer 6 | ============== 7 | 8 | * like a rocketeer, but for versions! 9 | * https://github.com/warner/python-versioneer 10 | * Brian Warner 11 | * License: Public Domain 12 | * Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, and pypy 13 | * [![Latest Version] 14 | (https://pypip.in/version/versioneer/badge.svg?style=flat) 15 | ](https://pypi.python.org/pypi/versioneer/) 16 | * [![Build Status] 17 | (https://travis-ci.org/warner/python-versioneer.png?branch=master) 18 | ](https://travis-ci.org/warner/python-versioneer) 19 | 20 | This is a tool for managing a recorded version number in distutils-based 21 | python projects. The goal is to remove the tedious and error-prone "update 22 | the embedded version string" step from your release process. Making a new 23 | release should be as easy as recording a new tag in your version-control 24 | system, and maybe making new tarballs. 25 | 26 | 27 | ## Quick Install 28 | 29 | * `pip install versioneer` to somewhere to your $PATH 30 | * add a `[versioneer]` section to your setup.cfg (see below) 31 | * run `versioneer install` in your source tree, commit the results 32 | 33 | ## Version Identifiers 34 | 35 | Source trees come from a variety of places: 36 | 37 | * a version-control system checkout (mostly used by developers) 38 | * a nightly tarball, produced by build automation 39 | * a snapshot tarball, produced by a web-based VCS browser, like github's 40 | "tarball from tag" feature 41 | * a release tarball, produced by "setup.py sdist", distributed through PyPI 42 | 43 | Within each source tree, the version identifier (either a string or a number, 44 | this tool is format-agnostic) can come from a variety of places: 45 | 46 | * ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows 47 | about recent "tags" and an absolute revision-id 48 | * the name of the directory into which the tarball was unpacked 49 | * an expanded VCS keyword ($Id$, etc) 50 | * a `_version.py` created by some earlier build step 51 | 52 | For released software, the version identifier is closely related to a VCS 53 | tag. Some projects use tag names that include more than just the version 54 | string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool 55 | needs to strip the tag prefix to extract the version identifier. For 56 | unreleased software (between tags), the version identifier should provide 57 | enough information to help developers recreate the same tree, while also 58 | giving them an idea of roughly how old the tree is (after version 1.2, before 59 | version 1.3). Many VCS systems can report a description that captures this, 60 | for example `git describe --tags --dirty --always` reports things like 61 | "0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the 62 | 0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has 63 | uncommitted changes. 64 | 65 | The version identifier is used for multiple purposes: 66 | 67 | * to allow the module to self-identify its version: `myproject.__version__` 68 | * to choose a name and prefix for a 'setup.py sdist' tarball 69 | 70 | ## Theory of Operation 71 | 72 | Versioneer works by adding a special `_version.py` file into your source 73 | tree, where your `__init__.py` can import it. This `_version.py` knows how to 74 | dynamically ask the VCS tool for version information at import time. 75 | 76 | `_version.py` also contains `$Revision$` markers, and the installation 77 | process marks `_version.py` to have this marker rewritten with a tag name 78 | during the `git archive` command. As a result, generated tarballs will 79 | contain enough information to get the proper version. 80 | 81 | To allow `setup.py` to compute a version too, a `versioneer.py` is added to 82 | the top level of your source tree, next to `setup.py` and the `setup.cfg` 83 | that configures it. This overrides several distutils/setuptools commands to 84 | compute the version when invoked, and changes `setup.py build` and `setup.py 85 | sdist` to replace `_version.py` with a small static file that contains just 86 | the generated version data. 87 | 88 | ## Installation 89 | 90 | First, decide on values for the following configuration variables: 91 | 92 | * `VCS`: the version control system you use. Currently accepts "git". 93 | 94 | * `style`: the style of version string to be produced. See "Styles" below for 95 | details. Defaults to "pep440", which looks like 96 | `TAG[+DISTANCE.gSHORTHASH[.dirty]]`. 97 | 98 | * `versionfile_source`: 99 | 100 | A project-relative pathname into which the generated version strings should 101 | be written. This is usually a `_version.py` next to your project's main 102 | `__init__.py` file, so it can be imported at runtime. If your project uses 103 | `src/myproject/__init__.py`, this should be `src/myproject/_version.py`. 104 | This file should be checked in to your VCS as usual: the copy created below 105 | by `setup.py setup_versioneer` will include code that parses expanded VCS 106 | keywords in generated tarballs. The 'build' and 'sdist' commands will 107 | replace it with a copy that has just the calculated version string. 108 | 109 | This must be set even if your project does not have any modules (and will 110 | therefore never import `_version.py`), since "setup.py sdist" -based trees 111 | still need somewhere to record the pre-calculated version strings. Anywhere 112 | in the source tree should do. If there is a `__init__.py` next to your 113 | `_version.py`, the `setup.py setup_versioneer` command (described below) 114 | will append some `__version__`-setting assignments, if they aren't already 115 | present. 116 | 117 | * `versionfile_build`: 118 | 119 | Like `versionfile_source`, but relative to the build directory instead of 120 | the source directory. These will differ when your setup.py uses 121 | 'package_dir='. If you have `package_dir={'myproject': 'src/myproject'}`, 122 | then you will probably have `versionfile_build='myproject/_version.py'` and 123 | `versionfile_source='src/myproject/_version.py'`. 124 | 125 | If this is set to None, then `setup.py build` will not attempt to rewrite 126 | any `_version.py` in the built tree. If your project does not have any 127 | libraries (e.g. if it only builds a script), then you should use 128 | `versionfile_build = None` and override `distutils.command.build_scripts` 129 | to explicitly insert a copy of `versioneer.get_version()` into your 130 | generated script. 131 | 132 | * `tag_prefix`: 133 | 134 | a string, like 'PROJECTNAME-', which appears at the start of all VCS tags. 135 | If your tags look like 'myproject-1.2.0', then you should use 136 | tag_prefix='myproject-'. If you use unprefixed tags like '1.2.0', this 137 | should be an empty string. 138 | 139 | * `parentdir_prefix`: 140 | 141 | a optional string, frequently the same as tag_prefix, which appears at the 142 | start of all unpacked tarball filenames. If your tarball unpacks into 143 | 'myproject-1.2.0', this should be 'myproject-'. To disable this feature, 144 | just omit the field from your `setup.cfg`. 145 | 146 | This tool provides one script, named `versioneer`. That script has one mode, 147 | "install", which writes a copy of `versioneer.py` into the current directory 148 | and runs `versioneer.py setup` to finish the installation. 149 | 150 | To versioneer-enable your project: 151 | 152 | * 1: Modify your `setup.cfg`, adding a section named `[versioneer]` and 153 | populating it with the configuration values you decided earlier (note that 154 | the option names are not case-sensitive): 155 | 156 | ```` 157 | [versioneer] 158 | VCS = git 159 | style = pep440 160 | versionfile_source = src/myproject/_version.py 161 | versionfile_build = myproject/_version.py 162 | tag_prefix = "" 163 | parentdir_prefix = myproject- 164 | ```` 165 | 166 | * 2: Run `versioneer install`. This will do the following: 167 | 168 | * copy `versioneer.py` into the top of your source tree 169 | * create `_version.py` in the right place (`versionfile_source`) 170 | * modify your `__init__.py` (if one exists next to `_version.py`) to define 171 | `__version__` (by calling a function from `_version.py`) 172 | * modify your `MANIFEST.in` to include both `versioneer.py` and the 173 | generated `_version.py` in sdist tarballs 174 | 175 | `versioneer install` will complain about any problems it finds with your 176 | `setup.py` or `setup.cfg`. Run it multiple times until you have fixed all 177 | the problems. 178 | 179 | * 3: add a `import versioneer` to your setup.py, and add the following 180 | arguments to the setup() call: 181 | 182 | version=versioneer.get_version(), 183 | cmdclass=versioneer.get_cmdclass(), 184 | 185 | * 4: commit these changes to your VCS. To make sure you won't forget, 186 | `versioneer install` will mark everything it touched for addition using 187 | `git add`. Don't forget to add `setup.py` and `setup.cfg` too. 188 | 189 | ## Post-Installation Usage 190 | 191 | Once established, all uses of your tree from a VCS checkout should get the 192 | current version string. All generated tarballs should include an embedded 193 | version string (so users who unpack them will not need a VCS tool installed). 194 | 195 | If you distribute your project through PyPI, then the release process should 196 | boil down to two steps: 197 | 198 | * 1: git tag 1.0 199 | * 2: python setup.py register sdist upload 200 | 201 | If you distribute it through github (i.e. users use github to generate 202 | tarballs with `git archive`), the process is: 203 | 204 | * 1: git tag 1.0 205 | * 2: git push; git push --tags 206 | 207 | Versioneer will report "0+untagged.NUMCOMMITS.gHASH" until your tree has at 208 | least one tag in its history. 209 | 210 | ## Version-String Flavors 211 | 212 | Code which uses Versioneer can learn about its version string at runtime by 213 | importing `_version` from your main `__init__.py` file and running the 214 | `get_versions()` function. From the "outside" (e.g. in `setup.py`), you can 215 | import the top-level `versioneer.py` and run `get_versions()`. 216 | 217 | Both functions return a dictionary with different flavors of version 218 | information: 219 | 220 | * `['version']`: A condensed version string, rendered using the selected 221 | style. This is the most commonly used value for the project's version 222 | string. The default "pep440" style yields strings like `0.11`, 223 | `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section 224 | below for alternative styles. 225 | 226 | * `['full-revisionid']`: detailed revision identifier. For Git, this is the 227 | full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". 228 | 229 | * `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that 230 | this is only accurate if run in a VCS checkout, otherwise it is likely to 231 | be False or None 232 | 233 | * `['error']`: if the version string could not be computed, this will be set 234 | to a string describing the problem, otherwise it will be None. It may be 235 | useful to throw an exception in setup.py if this is set, to avoid e.g. 236 | creating tarballs with a version string of "unknown". 237 | 238 | Some variants are more useful than others. Including `full-revisionid` in a 239 | bug report should allow developers to reconstruct the exact code being tested 240 | (or indicate the presence of local changes that should be shared with the 241 | developers). `version` is suitable for display in an "about" box or a CLI 242 | `--version` output: it can be easily compared against release notes and lists 243 | of bugs fixed in various releases. 244 | 245 | The installer adds the following text to your `__init__.py` to place a basic 246 | version in `YOURPROJECT.__version__`: 247 | 248 | from ._version import get_versions 249 | __version__ = get_versions()['version'] 250 | del get_versions 251 | 252 | ## Styles 253 | 254 | The setup.cfg `style=` configuration controls how the VCS information is 255 | rendered into a version string. 256 | 257 | The default style, "pep440", produces a PEP440-compliant string, equal to the 258 | un-prefixed tag name for actual releases, and containing an additional "local 259 | version" section with more detail for in-between builds. For Git, this is 260 | TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags 261 | --dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the 262 | tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and 263 | that this commit is two revisions ("+2") beyond the "0.11" tag. For released 264 | software (exactly equal to a known tag), the identifier will only contain the 265 | stripped tag, e.g. "0.11". 266 | 267 | Other styles are available. See details.md in the Versioneer source tree for 268 | descriptions. 269 | 270 | ## Debugging 271 | 272 | Versioneer tries to avoid fatal errors: if something goes wrong, it will tend 273 | to return a version of "0+unknown". To investigate the problem, run `setup.py 274 | version`, which will run the version-lookup code in a verbose mode, and will 275 | display the full contents of `get_versions()` (including the `error` string, 276 | which may help identify what went wrong). 277 | 278 | ## Updating Versioneer 279 | 280 | To upgrade your project to a new release of Versioneer, do the following: 281 | 282 | * install the new Versioneer (`pip install -U versioneer` or equivalent) 283 | * edit `setup.cfg`, if necessary, to include any new configuration settings 284 | indicated by the release notes 285 | * re-run `versioneer install` in your source tree, to replace 286 | `SRC/_version.py` 287 | * commit any changed files 288 | 289 | ### Upgrading to 0.15 290 | 291 | Starting with this version, Versioneer is configured with a `[versioneer]` 292 | section in your `setup.cfg` file. Earlier versions required the `setup.py` to 293 | set attributes on the `versioneer` module immediately after import. The new 294 | version will refuse to run (raising an exception during import) until you 295 | have provided the necessary `setup.cfg` section. 296 | 297 | In addition, the Versioneer package provides an executable named 298 | `versioneer`, and the installation process is driven by running `versioneer 299 | install`. In 0.14 and earlier, the executable was named 300 | `versioneer-installer` and was run without an argument. 301 | 302 | ### Upgrading to 0.14 303 | 304 | 0.14 changes the format of the version string. 0.13 and earlier used 305 | hyphen-separated strings like "0.11-2-g1076c97-dirty". 0.14 and beyond use a 306 | plus-separated "local version" section strings, with dot-separated 307 | components, like "0.11+2.g1076c97". PEP440-strict tools did not like the old 308 | format, but should be ok with the new one. 309 | 310 | ### Upgrading from 0.11 to 0.12 311 | 312 | Nothing special. 313 | 314 | ### Upgrading from 0.10 to 0.11 315 | 316 | You must add a `versioneer.VCS = "git"` to your `setup.py` before re-running 317 | `setup.py setup_versioneer`. This will enable the use of additional 318 | version-control systems (SVN, etc) in the future. 319 | 320 | ## Future Directions 321 | 322 | This tool is designed to make it easily extended to other version-control 323 | systems: all VCS-specific components are in separate directories like 324 | src/git/ . The top-level `versioneer.py` script is assembled from these 325 | components by running make-versioneer.py . In the future, make-versioneer.py 326 | will take a VCS name as an argument, and will construct a version of 327 | `versioneer.py` that is specific to the given VCS. It might also take the 328 | configuration arguments that are currently provided manually during 329 | installation by editing setup.py . Alternatively, it might go the other 330 | direction and include code from all supported VCS systems, reducing the 331 | number of intermediate scripts. 332 | 333 | 334 | ## License 335 | 336 | To make Versioneer easier to embed, all its code is hereby released into the 337 | public domain. The `_version.py` that it creates is also in the public 338 | domain. 339 | 340 | """ 341 | 342 | from __future__ import print_function 343 | try: 344 | import configparser 345 | except ImportError: 346 | import ConfigParser as configparser 347 | import errno 348 | import json 349 | import os 350 | import re 351 | import subprocess 352 | import sys 353 | 354 | 355 | class VersioneerConfig: 356 | pass 357 | 358 | 359 | def get_root(): 360 | # we require that all commands are run from the project root, i.e. the 361 | # directory that contains setup.py, setup.cfg, and versioneer.py . 362 | root = os.path.realpath(os.path.abspath(os.getcwd())) 363 | setup_py = os.path.join(root, "setup.py") 364 | versioneer_py = os.path.join(root, "versioneer.py") 365 | if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): 366 | # allow 'python path/to/setup.py COMMAND' 367 | root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) 368 | setup_py = os.path.join(root, "setup.py") 369 | versioneer_py = os.path.join(root, "versioneer.py") 370 | if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): 371 | err = ("Versioneer was unable to run the project root directory. " 372 | "Versioneer requires setup.py to be executed from " 373 | "its immediate directory (like 'python setup.py COMMAND'), " 374 | "or in a way that lets it use sys.argv[0] to find the root " 375 | "(like 'python path/to/setup.py COMMAND').") 376 | raise VersioneerBadRootError(err) 377 | try: 378 | # Certain runtime workflows (setup.py install/develop in a setuptools 379 | # tree) execute all dependencies in a single python process, so 380 | # "versioneer" may be imported multiple times, and python's shared 381 | # module-import table will cache the first one. So we can't use 382 | # os.path.dirname(__file__), as that will find whichever 383 | # versioneer.py was first imported, even in later projects. 384 | me = os.path.realpath(os.path.abspath(__file__)) 385 | if os.path.splitext(me)[0] != os.path.splitext(versioneer_py)[0]: 386 | print("Warning: build in %s is using versioneer.py from %s" 387 | % (os.path.dirname(me), versioneer_py)) 388 | except NameError: 389 | pass 390 | return root 391 | 392 | 393 | def get_config_from_root(root): 394 | # This might raise EnvironmentError (if setup.cfg is missing), or 395 | # configparser.NoSectionError (if it lacks a [versioneer] section), or 396 | # configparser.NoOptionError (if it lacks "VCS="). See the docstring at 397 | # the top of versioneer.py for instructions on writing your setup.cfg . 398 | setup_cfg = os.path.join(root, "setup.cfg") 399 | parser = configparser.SafeConfigParser() 400 | with open(setup_cfg, "r") as f: 401 | parser.readfp(f) 402 | VCS = parser.get("versioneer", "VCS") # mandatory 403 | 404 | def get(parser, name): 405 | if parser.has_option("versioneer", name): 406 | return parser.get("versioneer", name) 407 | return None 408 | cfg = VersioneerConfig() 409 | cfg.VCS = VCS 410 | cfg.style = get(parser, "style") or "" 411 | cfg.versionfile_source = get(parser, "versionfile_source") 412 | cfg.versionfile_build = get(parser, "versionfile_build") 413 | cfg.tag_prefix = get(parser, "tag_prefix") 414 | cfg.parentdir_prefix = get(parser, "parentdir_prefix") 415 | cfg.verbose = get(parser, "verbose") 416 | return cfg 417 | 418 | 419 | class NotThisMethod(Exception): 420 | pass 421 | 422 | # these dictionaries contain VCS-specific tools 423 | LONG_VERSION_PY = {} 424 | HANDLERS = {} 425 | 426 | 427 | def register_vcs_handler(vcs, method): # decorator 428 | def decorate(f): 429 | if vcs not in HANDLERS: 430 | HANDLERS[vcs] = {} 431 | HANDLERS[vcs][method] = f 432 | return f 433 | return decorate 434 | 435 | 436 | def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): 437 | assert isinstance(commands, list) 438 | p = None 439 | for c in commands: 440 | try: 441 | dispcmd = str([c] + args) 442 | # remember shell=False, so use git.cmd on windows, not just git 443 | p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE, 444 | stderr=(subprocess.PIPE if hide_stderr 445 | else None)) 446 | break 447 | except EnvironmentError: 448 | e = sys.exc_info()[1] 449 | if e.errno == errno.ENOENT: 450 | continue 451 | if verbose: 452 | print("unable to run %s" % dispcmd) 453 | print(e) 454 | return None 455 | else: 456 | if verbose: 457 | print("unable to find command, tried %s" % (commands,)) 458 | return None 459 | stdout = p.communicate()[0].strip() 460 | if sys.version_info[0] >= 3: 461 | stdout = stdout.decode() 462 | if p.returncode != 0: 463 | if verbose: 464 | print("unable to run %s (error)" % dispcmd) 465 | return None 466 | return stdout 467 | LONG_VERSION_PY['git'] = ''' 468 | # This file helps to compute a version number in source trees obtained from 469 | # git-archive tarball (such as those provided by githubs download-from-tag 470 | # feature). Distribution tarballs (built by setup.py sdist) and build 471 | # directories (produced by setup.py build) will contain a much shorter file 472 | # that just contains the computed version number. 473 | 474 | # This file is released into the public domain. Generated by 475 | # versioneer-0.15 (https://github.com/warner/python-versioneer) 476 | 477 | import errno 478 | import os 479 | import re 480 | import subprocess 481 | import sys 482 | 483 | 484 | def get_keywords(): 485 | # these strings will be replaced by git during git-archive. 486 | # setup.py/versioneer.py will grep for the variable names, so they must 487 | # each be defined on a line of their own. _version.py will just call 488 | # get_keywords(). 489 | git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" 490 | git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" 491 | keywords = {"refnames": git_refnames, "full": git_full} 492 | return keywords 493 | 494 | 495 | class VersioneerConfig: 496 | pass 497 | 498 | 499 | def get_config(): 500 | # these strings are filled in when 'setup.py versioneer' creates 501 | # _version.py 502 | cfg = VersioneerConfig() 503 | cfg.VCS = "git" 504 | cfg.style = "%(STYLE)s" 505 | cfg.tag_prefix = "%(TAG_PREFIX)s" 506 | cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" 507 | cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" 508 | cfg.verbose = False 509 | return cfg 510 | 511 | 512 | class NotThisMethod(Exception): 513 | pass 514 | 515 | 516 | LONG_VERSION_PY = {} 517 | HANDLERS = {} 518 | 519 | 520 | def register_vcs_handler(vcs, method): # decorator 521 | def decorate(f): 522 | if vcs not in HANDLERS: 523 | HANDLERS[vcs] = {} 524 | HANDLERS[vcs][method] = f 525 | return f 526 | return decorate 527 | 528 | 529 | def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): 530 | assert isinstance(commands, list) 531 | p = None 532 | for c in commands: 533 | try: 534 | dispcmd = str([c] + args) 535 | # remember shell=False, so use git.cmd on windows, not just git 536 | p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE, 537 | stderr=(subprocess.PIPE if hide_stderr 538 | else None)) 539 | break 540 | except EnvironmentError: 541 | e = sys.exc_info()[1] 542 | if e.errno == errno.ENOENT: 543 | continue 544 | if verbose: 545 | print("unable to run %%s" %% dispcmd) 546 | print(e) 547 | return None 548 | else: 549 | if verbose: 550 | print("unable to find command, tried %%s" %% (commands,)) 551 | return None 552 | stdout = p.communicate()[0].strip() 553 | if sys.version_info[0] >= 3: 554 | stdout = stdout.decode() 555 | if p.returncode != 0: 556 | if verbose: 557 | print("unable to run %%s (error)" %% dispcmd) 558 | return None 559 | return stdout 560 | 561 | 562 | def versions_from_parentdir(parentdir_prefix, root, verbose): 563 | # Source tarballs conventionally unpack into a directory that includes 564 | # both the project name and a version string. 565 | dirname = os.path.basename(root) 566 | if not dirname.startswith(parentdir_prefix): 567 | if verbose: 568 | print("guessing rootdir is '%%s', but '%%s' doesn't start with " 569 | "prefix '%%s'" %% (root, dirname, parentdir_prefix)) 570 | raise NotThisMethod("rootdir doesn't start with parentdir_prefix") 571 | return {"version": dirname[len(parentdir_prefix):], 572 | "full-revisionid": None, 573 | "dirty": False, "error": None} 574 | 575 | 576 | @register_vcs_handler("git", "get_keywords") 577 | def git_get_keywords(versionfile_abs): 578 | # the code embedded in _version.py can just fetch the value of these 579 | # keywords. When used from setup.py, we don't want to import _version.py, 580 | # so we do it with a regexp instead. This function is not used from 581 | # _version.py. 582 | keywords = {} 583 | try: 584 | f = open(versionfile_abs, "r") 585 | for line in f.readlines(): 586 | if line.strip().startswith("git_refnames ="): 587 | mo = re.search(r'=\s*"(.*)"', line) 588 | if mo: 589 | keywords["refnames"] = mo.group(1) 590 | if line.strip().startswith("git_full ="): 591 | mo = re.search(r'=\s*"(.*)"', line) 592 | if mo: 593 | keywords["full"] = mo.group(1) 594 | f.close() 595 | except EnvironmentError: 596 | pass 597 | return keywords 598 | 599 | 600 | @register_vcs_handler("git", "keywords") 601 | def git_versions_from_keywords(keywords, tag_prefix, verbose): 602 | if not keywords: 603 | raise NotThisMethod("no keywords at all, weird") 604 | refnames = keywords["refnames"].strip() 605 | if refnames.startswith("$Format"): 606 | if verbose: 607 | print("keywords are unexpanded, not using") 608 | raise NotThisMethod("unexpanded keywords, not a git-archive tarball") 609 | refs = set([r.strip() for r in refnames.strip("()").split(",")]) 610 | # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of 611 | # just "foo-1.0". If we see a "tag: " prefix, prefer those. 612 | TAG = "tag: " 613 | tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) 614 | if not tags: 615 | # Either we're using git < 1.8.3, or there really are no tags. We use 616 | # a heuristic: assume all version tags have a digit. The old git %%d 617 | # expansion behaves like git log --decorate=short and strips out the 618 | # refs/heads/ and refs/tags/ prefixes that would let us distinguish 619 | # between branches and tags. By ignoring refnames without digits, we 620 | # filter out many common branch names like "release" and 621 | # "stabilization", as well as "HEAD" and "master". 622 | tags = set([r for r in refs if re.search(r'\d', r)]) 623 | if verbose: 624 | print("discarding '%%s', no digits" %% ",".join(refs-tags)) 625 | if verbose: 626 | print("likely tags: %%s" %% ",".join(sorted(tags))) 627 | for ref in sorted(tags): 628 | # sorting will prefer e.g. "2.0" over "2.0rc1" 629 | if ref.startswith(tag_prefix): 630 | r = ref[len(tag_prefix):] 631 | if verbose: 632 | print("picking %%s" %% r) 633 | return {"version": r, 634 | "full-revisionid": keywords["full"].strip(), 635 | "dirty": False, "error": None 636 | } 637 | # no suitable tags, so version is "0+unknown", but full hex is still there 638 | if verbose: 639 | print("no suitable tags, using unknown + full revision id") 640 | return {"version": "0+unknown", 641 | "full-revisionid": keywords["full"].strip(), 642 | "dirty": False, "error": "no suitable tags"} 643 | 644 | 645 | @register_vcs_handler("git", "pieces_from_vcs") 646 | def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): 647 | # this runs 'git' from the root of the source tree. This only gets called 648 | # if the git-archive 'subst' keywords were *not* expanded, and 649 | # _version.py hasn't already been rewritten with a short version string, 650 | # meaning we're inside a checked out source tree. 651 | 652 | if not os.path.exists(os.path.join(root, ".git")): 653 | if verbose: 654 | print("no .git in %%s" %% root) 655 | raise NotThisMethod("no .git directory") 656 | 657 | GITS = ["git"] 658 | if sys.platform == "win32": 659 | GITS = ["git.cmd", "git.exe"] 660 | # if there is a tag, this yields TAG-NUM-gHEX[-dirty] 661 | # if there are no tags, this yields HEX[-dirty] (no NUM) 662 | describe_out = run_command(GITS, ["describe", "--tags", "--dirty", 663 | "--always", "--long"], 664 | cwd=root) 665 | # --long was added in git-1.5.5 666 | if describe_out is None: 667 | raise NotThisMethod("'git describe' failed") 668 | describe_out = describe_out.strip() 669 | full_out = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) 670 | if full_out is None: 671 | raise NotThisMethod("'git rev-parse' failed") 672 | full_out = full_out.strip() 673 | 674 | pieces = {} 675 | pieces["long"] = full_out 676 | pieces["short"] = full_out[:7] # maybe improved later 677 | pieces["error"] = None 678 | 679 | # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] 680 | # TAG might have hyphens. 681 | git_describe = describe_out 682 | 683 | # look for -dirty suffix 684 | dirty = git_describe.endswith("-dirty") 685 | pieces["dirty"] = dirty 686 | if dirty: 687 | git_describe = git_describe[:git_describe.rindex("-dirty")] 688 | 689 | # now we have TAG-NUM-gHEX or HEX 690 | 691 | if "-" in git_describe: 692 | # TAG-NUM-gHEX 693 | mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) 694 | if not mo: 695 | # unparseable. Maybe git-describe is misbehaving? 696 | pieces["error"] = ("unable to parse git-describe output: '%%s'" 697 | %% describe_out) 698 | return pieces 699 | 700 | # tag 701 | full_tag = mo.group(1) 702 | if not full_tag.startswith(tag_prefix): 703 | if verbose: 704 | fmt = "tag '%%s' doesn't start with prefix '%%s'" 705 | print(fmt %% (full_tag, tag_prefix)) 706 | pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" 707 | %% (full_tag, tag_prefix)) 708 | return pieces 709 | pieces["closest-tag"] = full_tag[len(tag_prefix):] 710 | 711 | # distance: number of commits since tag 712 | pieces["distance"] = int(mo.group(2)) 713 | 714 | # commit: short hex revision ID 715 | pieces["short"] = mo.group(3) 716 | 717 | else: 718 | # HEX: no tags 719 | pieces["closest-tag"] = None 720 | count_out = run_command(GITS, ["rev-list", "HEAD", "--count"], 721 | cwd=root) 722 | pieces["distance"] = int(count_out) # total number of commits 723 | 724 | return pieces 725 | 726 | 727 | def plus_or_dot(pieces): 728 | if "+" in pieces.get("closest-tag", ""): 729 | return "." 730 | return "+" 731 | 732 | 733 | def render_pep440(pieces): 734 | # now build up version string, with post-release "local version 735 | # identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you 736 | # get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty 737 | 738 | # exceptions: 739 | # 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] 740 | 741 | if pieces["closest-tag"]: 742 | rendered = pieces["closest-tag"] 743 | if pieces["distance"] or pieces["dirty"]: 744 | rendered += plus_or_dot(pieces) 745 | rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) 746 | if pieces["dirty"]: 747 | rendered += ".dirty" 748 | else: 749 | # exception #1 750 | rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], 751 | pieces["short"]) 752 | if pieces["dirty"]: 753 | rendered += ".dirty" 754 | return rendered 755 | 756 | 757 | def render_pep440_pre(pieces): 758 | # TAG[.post.devDISTANCE] . No -dirty 759 | 760 | # exceptions: 761 | # 1: no tags. 0.post.devDISTANCE 762 | 763 | if pieces["closest-tag"]: 764 | rendered = pieces["closest-tag"] 765 | if pieces["distance"]: 766 | rendered += ".post.dev%%d" %% pieces["distance"] 767 | else: 768 | # exception #1 769 | rendered = "0.post.dev%%d" %% pieces["distance"] 770 | return rendered 771 | 772 | 773 | def render_pep440_post(pieces): 774 | # TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that 775 | # .dev0 sorts backwards (a dirty tree will appear "older" than the 776 | # corresponding clean one), but you shouldn't be releasing software with 777 | # -dirty anyways. 778 | 779 | # exceptions: 780 | # 1: no tags. 0.postDISTANCE[.dev0] 781 | 782 | if pieces["closest-tag"]: 783 | rendered = pieces["closest-tag"] 784 | if pieces["distance"] or pieces["dirty"]: 785 | rendered += ".post%%d" %% pieces["distance"] 786 | if pieces["dirty"]: 787 | rendered += ".dev0" 788 | rendered += plus_or_dot(pieces) 789 | rendered += "g%%s" %% pieces["short"] 790 | else: 791 | # exception #1 792 | rendered = "0.post%%d" %% pieces["distance"] 793 | if pieces["dirty"]: 794 | rendered += ".dev0" 795 | rendered += "+g%%s" %% pieces["short"] 796 | return rendered 797 | 798 | 799 | def render_pep440_old(pieces): 800 | # TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. 801 | 802 | # exceptions: 803 | # 1: no tags. 0.postDISTANCE[.dev0] 804 | 805 | if pieces["closest-tag"]: 806 | rendered = pieces["closest-tag"] 807 | if pieces["distance"] or pieces["dirty"]: 808 | rendered += ".post%%d" %% pieces["distance"] 809 | if pieces["dirty"]: 810 | rendered += ".dev0" 811 | else: 812 | # exception #1 813 | rendered = "0.post%%d" %% pieces["distance"] 814 | if pieces["dirty"]: 815 | rendered += ".dev0" 816 | return rendered 817 | 818 | 819 | def render_git_describe(pieces): 820 | # TAG[-DISTANCE-gHEX][-dirty], like 'git describe --tags --dirty 821 | # --always' 822 | 823 | # exceptions: 824 | # 1: no tags. HEX[-dirty] (note: no 'g' prefix) 825 | 826 | if pieces["closest-tag"]: 827 | rendered = pieces["closest-tag"] 828 | if pieces["distance"]: 829 | rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) 830 | else: 831 | # exception #1 832 | rendered = pieces["short"] 833 | if pieces["dirty"]: 834 | rendered += "-dirty" 835 | return rendered 836 | 837 | 838 | def render_git_describe_long(pieces): 839 | # TAG-DISTANCE-gHEX[-dirty], like 'git describe --tags --dirty 840 | # --always -long'. The distance/hash is unconditional. 841 | 842 | # exceptions: 843 | # 1: no tags. HEX[-dirty] (note: no 'g' prefix) 844 | 845 | if pieces["closest-tag"]: 846 | rendered = pieces["closest-tag"] 847 | rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) 848 | else: 849 | # exception #1 850 | rendered = pieces["short"] 851 | if pieces["dirty"]: 852 | rendered += "-dirty" 853 | return rendered 854 | 855 | 856 | def render(pieces, style): 857 | if pieces["error"]: 858 | return {"version": "unknown", 859 | "full-revisionid": pieces.get("long"), 860 | "dirty": None, 861 | "error": pieces["error"]} 862 | 863 | if not style or style == "default": 864 | style = "pep440" # the default 865 | 866 | if style == "pep440": 867 | rendered = render_pep440(pieces) 868 | elif style == "pep440-pre": 869 | rendered = render_pep440_pre(pieces) 870 | elif style == "pep440-post": 871 | rendered = render_pep440_post(pieces) 872 | elif style == "pep440-old": 873 | rendered = render_pep440_old(pieces) 874 | elif style == "git-describe": 875 | rendered = render_git_describe(pieces) 876 | elif style == "git-describe-long": 877 | rendered = render_git_describe_long(pieces) 878 | else: 879 | raise ValueError("unknown style '%%s'" %% style) 880 | 881 | return {"version": rendered, "full-revisionid": pieces["long"], 882 | "dirty": pieces["dirty"], "error": None} 883 | 884 | 885 | def get_versions(): 886 | # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have 887 | # __file__, we can work backwards from there to the root. Some 888 | # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which 889 | # case we can only use expanded keywords. 890 | 891 | cfg = get_config() 892 | verbose = cfg.verbose 893 | 894 | try: 895 | return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, 896 | verbose) 897 | except NotThisMethod: 898 | pass 899 | 900 | try: 901 | root = os.path.realpath(__file__) 902 | # versionfile_source is the relative path from the top of the source 903 | # tree (where the .git directory might live) to this file. Invert 904 | # this to find the root from __file__. 905 | for i in cfg.versionfile_source.split('/'): 906 | root = os.path.dirname(root) 907 | except NameError: 908 | return {"version": "0+unknown", "full-revisionid": None, 909 | "dirty": None, 910 | "error": "unable to find root of source tree"} 911 | 912 | try: 913 | pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) 914 | return render(pieces, cfg.style) 915 | except NotThisMethod: 916 | pass 917 | 918 | try: 919 | if cfg.parentdir_prefix: 920 | return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) 921 | except NotThisMethod: 922 | pass 923 | 924 | return {"version": "0+unknown", "full-revisionid": None, 925 | "dirty": None, 926 | "error": "unable to compute version"} 927 | ''' 928 | 929 | 930 | @register_vcs_handler("git", "get_keywords") 931 | def git_get_keywords(versionfile_abs): 932 | # the code embedded in _version.py can just fetch the value of these 933 | # keywords. When used from setup.py, we don't want to import _version.py, 934 | # so we do it with a regexp instead. This function is not used from 935 | # _version.py. 936 | keywords = {} 937 | try: 938 | f = open(versionfile_abs, "r") 939 | for line in f.readlines(): 940 | if line.strip().startswith("git_refnames ="): 941 | mo = re.search(r'=\s*"(.*)"', line) 942 | if mo: 943 | keywords["refnames"] = mo.group(1) 944 | if line.strip().startswith("git_full ="): 945 | mo = re.search(r'=\s*"(.*)"', line) 946 | if mo: 947 | keywords["full"] = mo.group(1) 948 | f.close() 949 | except EnvironmentError: 950 | pass 951 | return keywords 952 | 953 | 954 | @register_vcs_handler("git", "keywords") 955 | def git_versions_from_keywords(keywords, tag_prefix, verbose): 956 | if not keywords: 957 | raise NotThisMethod("no keywords at all, weird") 958 | refnames = keywords["refnames"].strip() 959 | if refnames.startswith("$Format"): 960 | if verbose: 961 | print("keywords are unexpanded, not using") 962 | raise NotThisMethod("unexpanded keywords, not a git-archive tarball") 963 | refs = set([r.strip() for r in refnames.strip("()").split(",")]) 964 | # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of 965 | # just "foo-1.0". If we see a "tag: " prefix, prefer those. 966 | TAG = "tag: " 967 | tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) 968 | if not tags: 969 | # Either we're using git < 1.8.3, or there really are no tags. We use 970 | # a heuristic: assume all version tags have a digit. The old git %d 971 | # expansion behaves like git log --decorate=short and strips out the 972 | # refs/heads/ and refs/tags/ prefixes that would let us distinguish 973 | # between branches and tags. By ignoring refnames without digits, we 974 | # filter out many common branch names like "release" and 975 | # "stabilization", as well as "HEAD" and "master". 976 | tags = set([r for r in refs if re.search(r'\d', r)]) 977 | if verbose: 978 | print("discarding '%s', no digits" % ",".join(refs-tags)) 979 | if verbose: 980 | print("likely tags: %s" % ",".join(sorted(tags))) 981 | for ref in sorted(tags): 982 | # sorting will prefer e.g. "2.0" over "2.0rc1" 983 | if ref.startswith(tag_prefix): 984 | r = ref[len(tag_prefix):] 985 | if verbose: 986 | print("picking %s" % r) 987 | return {"version": r, 988 | "full-revisionid": keywords["full"].strip(), 989 | "dirty": False, "error": None 990 | } 991 | # no suitable tags, so version is "0+unknown", but full hex is still there 992 | if verbose: 993 | print("no suitable tags, using unknown + full revision id") 994 | return {"version": "0+unknown", 995 | "full-revisionid": keywords["full"].strip(), 996 | "dirty": False, "error": "no suitable tags"} 997 | 998 | 999 | @register_vcs_handler("git", "pieces_from_vcs") 1000 | def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): 1001 | # this runs 'git' from the root of the source tree. This only gets called 1002 | # if the git-archive 'subst' keywords were *not* expanded, and 1003 | # _version.py hasn't already been rewritten with a short version string, 1004 | # meaning we're inside a checked out source tree. 1005 | 1006 | if not os.path.exists(os.path.join(root, ".git")): 1007 | if verbose: 1008 | print("no .git in %s" % root) 1009 | raise NotThisMethod("no .git directory") 1010 | 1011 | GITS = ["git"] 1012 | if sys.platform == "win32": 1013 | GITS = ["git.cmd", "git.exe"] 1014 | # if there is a tag, this yields TAG-NUM-gHEX[-dirty] 1015 | # if there are no tags, this yields HEX[-dirty] (no NUM) 1016 | describe_out = run_command(GITS, ["describe", "--tags", "--dirty", 1017 | "--always", "--long"], 1018 | cwd=root) 1019 | # --long was added in git-1.5.5 1020 | if describe_out is None: 1021 | raise NotThisMethod("'git describe' failed") 1022 | describe_out = describe_out.strip() 1023 | full_out = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) 1024 | if full_out is None: 1025 | raise NotThisMethod("'git rev-parse' failed") 1026 | full_out = full_out.strip() 1027 | 1028 | pieces = {} 1029 | pieces["long"] = full_out 1030 | pieces["short"] = full_out[:7] # maybe improved later 1031 | pieces["error"] = None 1032 | 1033 | # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] 1034 | # TAG might have hyphens. 1035 | git_describe = describe_out 1036 | 1037 | # look for -dirty suffix 1038 | dirty = git_describe.endswith("-dirty") 1039 | pieces["dirty"] = dirty 1040 | if dirty: 1041 | git_describe = git_describe[:git_describe.rindex("-dirty")] 1042 | 1043 | # now we have TAG-NUM-gHEX or HEX 1044 | 1045 | if "-" in git_describe: 1046 | # TAG-NUM-gHEX 1047 | mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) 1048 | if not mo: 1049 | # unparseable. Maybe git-describe is misbehaving? 1050 | pieces["error"] = ("unable to parse git-describe output: '%s'" 1051 | % describe_out) 1052 | return pieces 1053 | 1054 | # tag 1055 | full_tag = mo.group(1) 1056 | if not full_tag.startswith(tag_prefix): 1057 | if verbose: 1058 | fmt = "tag '%s' doesn't start with prefix '%s'" 1059 | print(fmt % (full_tag, tag_prefix)) 1060 | pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" 1061 | % (full_tag, tag_prefix)) 1062 | return pieces 1063 | pieces["closest-tag"] = full_tag[len(tag_prefix):] 1064 | 1065 | # distance: number of commits since tag 1066 | pieces["distance"] = int(mo.group(2)) 1067 | 1068 | # commit: short hex revision ID 1069 | pieces["short"] = mo.group(3) 1070 | 1071 | else: 1072 | # HEX: no tags 1073 | pieces["closest-tag"] = None 1074 | count_out = run_command(GITS, ["rev-list", "HEAD", "--count"], 1075 | cwd=root) 1076 | pieces["distance"] = int(count_out) # total number of commits 1077 | 1078 | return pieces 1079 | 1080 | 1081 | def do_vcs_install(manifest_in, versionfile_source, ipy): 1082 | GITS = ["git"] 1083 | if sys.platform == "win32": 1084 | GITS = ["git.cmd", "git.exe"] 1085 | files = [manifest_in, versionfile_source] 1086 | if ipy: 1087 | files.append(ipy) 1088 | try: 1089 | me = __file__ 1090 | if me.endswith(".pyc") or me.endswith(".pyo"): 1091 | me = os.path.splitext(me)[0] + ".py" 1092 | versioneer_file = os.path.relpath(me) 1093 | except NameError: 1094 | versioneer_file = "versioneer.py" 1095 | files.append(versioneer_file) 1096 | present = False 1097 | try: 1098 | f = open(".gitattributes", "r") 1099 | for line in f.readlines(): 1100 | if line.strip().startswith(versionfile_source): 1101 | if "export-subst" in line.strip().split()[1:]: 1102 | present = True 1103 | f.close() 1104 | except EnvironmentError: 1105 | pass 1106 | if not present: 1107 | f = open(".gitattributes", "a+") 1108 | f.write("%s export-subst\n" % versionfile_source) 1109 | f.close() 1110 | files.append(".gitattributes") 1111 | run_command(GITS, ["add", "--"] + files) 1112 | 1113 | 1114 | def versions_from_parentdir(parentdir_prefix, root, verbose): 1115 | # Source tarballs conventionally unpack into a directory that includes 1116 | # both the project name and a version string. 1117 | dirname = os.path.basename(root) 1118 | if not dirname.startswith(parentdir_prefix): 1119 | if verbose: 1120 | print("guessing rootdir is '%s', but '%s' doesn't start with " 1121 | "prefix '%s'" % (root, dirname, parentdir_prefix)) 1122 | raise NotThisMethod("rootdir doesn't start with parentdir_prefix") 1123 | return {"version": dirname[len(parentdir_prefix):], 1124 | "full-revisionid": None, 1125 | "dirty": False, "error": None} 1126 | 1127 | SHORT_VERSION_PY = """ 1128 | # This file was generated by 'versioneer.py' (0.15) from 1129 | # revision-control system data, or from the parent directory name of an 1130 | # unpacked source archive. Distribution tarballs contain a pre-generated copy 1131 | # of this file. 1132 | 1133 | import json 1134 | import sys 1135 | 1136 | version_json = ''' 1137 | %s 1138 | ''' # END VERSION_JSON 1139 | 1140 | 1141 | def get_versions(): 1142 | return json.loads(version_json) 1143 | """ 1144 | 1145 | 1146 | def versions_from_file(filename): 1147 | try: 1148 | with open(filename) as f: 1149 | contents = f.read() 1150 | except EnvironmentError: 1151 | raise NotThisMethod("unable to read _version.py") 1152 | mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", 1153 | contents, re.M | re.S) 1154 | if not mo: 1155 | raise NotThisMethod("no version_json in _version.py") 1156 | return json.loads(mo.group(1)) 1157 | 1158 | 1159 | def write_to_version_file(filename, versions): 1160 | os.unlink(filename) 1161 | contents = json.dumps(versions, sort_keys=True, 1162 | indent=1, separators=(",", ": ")) 1163 | with open(filename, "w") as f: 1164 | f.write(SHORT_VERSION_PY % contents) 1165 | 1166 | print("set %s to '%s'" % (filename, versions["version"])) 1167 | 1168 | 1169 | def plus_or_dot(pieces): 1170 | if "+" in pieces.get("closest-tag", ""): 1171 | return "." 1172 | return "+" 1173 | 1174 | 1175 | def render_pep440(pieces): 1176 | # now build up version string, with post-release "local version 1177 | # identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you 1178 | # get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty 1179 | 1180 | # exceptions: 1181 | # 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] 1182 | 1183 | if pieces["closest-tag"]: 1184 | rendered = pieces["closest-tag"] 1185 | if pieces["distance"] or pieces["dirty"]: 1186 | rendered += plus_or_dot(pieces) 1187 | rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) 1188 | if pieces["dirty"]: 1189 | rendered += ".dirty" 1190 | else: 1191 | # exception #1 1192 | rendered = "0+untagged.%d.g%s" % (pieces["distance"], 1193 | pieces["short"]) 1194 | if pieces["dirty"]: 1195 | rendered += ".dirty" 1196 | return rendered 1197 | 1198 | 1199 | def render_pep440_pre(pieces): 1200 | # TAG[.post.devDISTANCE] . No -dirty 1201 | 1202 | # exceptions: 1203 | # 1: no tags. 0.post.devDISTANCE 1204 | 1205 | if pieces["closest-tag"]: 1206 | rendered = pieces["closest-tag"] 1207 | if pieces["distance"]: 1208 | rendered += ".post.dev%d" % pieces["distance"] 1209 | else: 1210 | # exception #1 1211 | rendered = "0.post.dev%d" % pieces["distance"] 1212 | return rendered 1213 | 1214 | 1215 | def render_pep440_post(pieces): 1216 | # TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that 1217 | # .dev0 sorts backwards (a dirty tree will appear "older" than the 1218 | # corresponding clean one), but you shouldn't be releasing software with 1219 | # -dirty anyways. 1220 | 1221 | # exceptions: 1222 | # 1: no tags. 0.postDISTANCE[.dev0] 1223 | 1224 | if pieces["closest-tag"]: 1225 | rendered = pieces["closest-tag"] 1226 | if pieces["distance"] or pieces["dirty"]: 1227 | rendered += ".post%d" % pieces["distance"] 1228 | if pieces["dirty"]: 1229 | rendered += ".dev0" 1230 | rendered += plus_or_dot(pieces) 1231 | rendered += "g%s" % pieces["short"] 1232 | else: 1233 | # exception #1 1234 | rendered = "0.post%d" % pieces["distance"] 1235 | if pieces["dirty"]: 1236 | rendered += ".dev0" 1237 | rendered += "+g%s" % pieces["short"] 1238 | return rendered 1239 | 1240 | 1241 | def render_pep440_old(pieces): 1242 | # TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. 1243 | 1244 | # exceptions: 1245 | # 1: no tags. 0.postDISTANCE[.dev0] 1246 | 1247 | if pieces["closest-tag"]: 1248 | rendered = pieces["closest-tag"] 1249 | if pieces["distance"] or pieces["dirty"]: 1250 | rendered += ".post%d" % pieces["distance"] 1251 | if pieces["dirty"]: 1252 | rendered += ".dev0" 1253 | else: 1254 | # exception #1 1255 | rendered = "0.post%d" % pieces["distance"] 1256 | if pieces["dirty"]: 1257 | rendered += ".dev0" 1258 | return rendered 1259 | 1260 | 1261 | def render_git_describe(pieces): 1262 | # TAG[-DISTANCE-gHEX][-dirty], like 'git describe --tags --dirty 1263 | # --always' 1264 | 1265 | # exceptions: 1266 | # 1: no tags. HEX[-dirty] (note: no 'g' prefix) 1267 | 1268 | if pieces["closest-tag"]: 1269 | rendered = pieces["closest-tag"] 1270 | if pieces["distance"]: 1271 | rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) 1272 | else: 1273 | # exception #1 1274 | rendered = pieces["short"] 1275 | if pieces["dirty"]: 1276 | rendered += "-dirty" 1277 | return rendered 1278 | 1279 | 1280 | def render_git_describe_long(pieces): 1281 | # TAG-DISTANCE-gHEX[-dirty], like 'git describe --tags --dirty 1282 | # --always -long'. The distance/hash is unconditional. 1283 | 1284 | # exceptions: 1285 | # 1: no tags. HEX[-dirty] (note: no 'g' prefix) 1286 | 1287 | if pieces["closest-tag"]: 1288 | rendered = pieces["closest-tag"] 1289 | rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) 1290 | else: 1291 | # exception #1 1292 | rendered = pieces["short"] 1293 | if pieces["dirty"]: 1294 | rendered += "-dirty" 1295 | return rendered 1296 | 1297 | 1298 | def render(pieces, style): 1299 | if pieces["error"]: 1300 | return {"version": "unknown", 1301 | "full-revisionid": pieces.get("long"), 1302 | "dirty": None, 1303 | "error": pieces["error"]} 1304 | 1305 | if not style or style == "default": 1306 | style = "pep440" # the default 1307 | 1308 | if style == "pep440": 1309 | rendered = render_pep440(pieces) 1310 | elif style == "pep440-pre": 1311 | rendered = render_pep440_pre(pieces) 1312 | elif style == "pep440-post": 1313 | rendered = render_pep440_post(pieces) 1314 | elif style == "pep440-old": 1315 | rendered = render_pep440_old(pieces) 1316 | elif style == "git-describe": 1317 | rendered = render_git_describe(pieces) 1318 | elif style == "git-describe-long": 1319 | rendered = render_git_describe_long(pieces) 1320 | else: 1321 | raise ValueError("unknown style '%s'" % style) 1322 | 1323 | return {"version": rendered, "full-revisionid": pieces["long"], 1324 | "dirty": pieces["dirty"], "error": None} 1325 | 1326 | 1327 | class VersioneerBadRootError(Exception): 1328 | pass 1329 | 1330 | 1331 | def get_versions(verbose=False): 1332 | # returns dict with two keys: 'version' and 'full' 1333 | 1334 | if "versioneer" in sys.modules: 1335 | # see the discussion in cmdclass.py:get_cmdclass() 1336 | del sys.modules["versioneer"] 1337 | 1338 | root = get_root() 1339 | cfg = get_config_from_root(root) 1340 | 1341 | assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" 1342 | handlers = HANDLERS.get(cfg.VCS) 1343 | assert handlers, "unrecognized VCS '%s'" % cfg.VCS 1344 | verbose = verbose or cfg.verbose 1345 | assert cfg.versionfile_source is not None, \ 1346 | "please set versioneer.versionfile_source" 1347 | assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" 1348 | 1349 | versionfile_abs = os.path.join(root, cfg.versionfile_source) 1350 | 1351 | # extract version from first of: _version.py, VCS command (e.g. 'git 1352 | # describe'), parentdir. This is meant to work for developers using a 1353 | # source checkout, for users of a tarball created by 'setup.py sdist', 1354 | # and for users of a tarball/zipball created by 'git archive' or github's 1355 | # download-from-tag feature or the equivalent in other VCSes. 1356 | 1357 | get_keywords_f = handlers.get("get_keywords") 1358 | from_keywords_f = handlers.get("keywords") 1359 | if get_keywords_f and from_keywords_f: 1360 | try: 1361 | keywords = get_keywords_f(versionfile_abs) 1362 | ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) 1363 | if verbose: 1364 | print("got version from expanded keyword %s" % ver) 1365 | return ver 1366 | except NotThisMethod: 1367 | pass 1368 | 1369 | try: 1370 | ver = versions_from_file(versionfile_abs) 1371 | if verbose: 1372 | print("got version from file %s %s" % (versionfile_abs, ver)) 1373 | return ver 1374 | except NotThisMethod: 1375 | pass 1376 | 1377 | from_vcs_f = handlers.get("pieces_from_vcs") 1378 | if from_vcs_f: 1379 | try: 1380 | pieces = from_vcs_f(cfg.tag_prefix, root, verbose) 1381 | ver = render(pieces, cfg.style) 1382 | if verbose: 1383 | print("got version from VCS %s" % ver) 1384 | return ver 1385 | except NotThisMethod: 1386 | pass 1387 | 1388 | try: 1389 | if cfg.parentdir_prefix: 1390 | ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) 1391 | if verbose: 1392 | print("got version from parentdir %s" % ver) 1393 | return ver 1394 | except NotThisMethod: 1395 | pass 1396 | 1397 | if verbose: 1398 | print("unable to compute version") 1399 | 1400 | return {"version": "0+unknown", "full-revisionid": None, 1401 | "dirty": None, "error": "unable to compute version"} 1402 | 1403 | 1404 | def get_version(): 1405 | return get_versions()["version"] 1406 | 1407 | 1408 | def get_cmdclass(): 1409 | if "versioneer" in sys.modules: 1410 | del sys.modules["versioneer"] 1411 | # this fixes the "python setup.py develop" case (also 'install' and 1412 | # 'easy_install .'), in which subdependencies of the main project are 1413 | # built (using setup.py bdist_egg) in the same python process. Assume 1414 | # a main project A and a dependency B, which use different versions 1415 | # of Versioneer. A's setup.py imports A's Versioneer, leaving it in 1416 | # sys.modules by the time B's setup.py is executed, causing B to run 1417 | # with the wrong versioneer. Setuptools wraps the sub-dep builds in a 1418 | # sandbox that restores sys.modules to it's pre-build state, so the 1419 | # parent is protected against the child's "import versioneer". By 1420 | # removing ourselves from sys.modules here, before the child build 1421 | # happens, we protect the child from the parent's versioneer too. 1422 | # Also see https://github.com/warner/python-versioneer/issues/52 1423 | 1424 | cmds = {} 1425 | 1426 | # we add "version" to both distutils and setuptools 1427 | from distutils.core import Command 1428 | 1429 | class cmd_version(Command): 1430 | description = "report generated version string" 1431 | user_options = [] 1432 | boolean_options = [] 1433 | 1434 | def initialize_options(self): 1435 | pass 1436 | 1437 | def finalize_options(self): 1438 | pass 1439 | 1440 | def run(self): 1441 | vers = get_versions(verbose=True) 1442 | print("Version: %s" % vers["version"]) 1443 | print(" full-revisionid: %s" % vers.get("full-revisionid")) 1444 | print(" dirty: %s" % vers.get("dirty")) 1445 | if vers["error"]: 1446 | print(" error: %s" % vers["error"]) 1447 | cmds["version"] = cmd_version 1448 | 1449 | # we override "build_py" in both distutils and setuptools 1450 | # 1451 | # most invocation pathways end up running build_py: 1452 | # distutils/build -> build_py 1453 | # distutils/install -> distutils/build ->.. 1454 | # setuptools/bdist_wheel -> distutils/install ->.. 1455 | # setuptools/bdist_egg -> distutils/install_lib -> build_py 1456 | # setuptools/install -> bdist_egg ->.. 1457 | # setuptools/develop -> ? 1458 | 1459 | from distutils.command.build_py import build_py as _build_py 1460 | 1461 | class cmd_build_py(_build_py): 1462 | def run(self): 1463 | root = get_root() 1464 | cfg = get_config_from_root(root) 1465 | versions = get_versions() 1466 | _build_py.run(self) 1467 | # now locate _version.py in the new build/ directory and replace 1468 | # it with an updated value 1469 | if cfg.versionfile_build: 1470 | target_versionfile = os.path.join(self.build_lib, 1471 | cfg.versionfile_build) 1472 | print("UPDATING %s" % target_versionfile) 1473 | write_to_version_file(target_versionfile, versions) 1474 | cmds["build_py"] = cmd_build_py 1475 | 1476 | if "cx_Freeze" in sys.modules: # cx_freeze enabled? 1477 | from cx_Freeze.dist import build_exe as _build_exe 1478 | 1479 | class cmd_build_exe(_build_exe): 1480 | def run(self): 1481 | root = get_root() 1482 | cfg = get_config_from_root(root) 1483 | versions = get_versions() 1484 | target_versionfile = cfg.versionfile_source 1485 | print("UPDATING %s" % target_versionfile) 1486 | write_to_version_file(target_versionfile, versions) 1487 | 1488 | _build_exe.run(self) 1489 | os.unlink(target_versionfile) 1490 | with open(cfg.versionfile_source, "w") as f: 1491 | LONG = LONG_VERSION_PY[cfg.VCS] 1492 | f.write(LONG % 1493 | {"DOLLAR": "$", 1494 | "STYLE": cfg.style, 1495 | "TAG_PREFIX": cfg.tag_prefix, 1496 | "PARENTDIR_PREFIX": cfg.parentdir_prefix, 1497 | "VERSIONFILE_SOURCE": cfg.versionfile_source, 1498 | }) 1499 | cmds["build_exe"] = cmd_build_exe 1500 | del cmds["build_py"] 1501 | 1502 | # we override different "sdist" commands for both environments 1503 | if "setuptools" in sys.modules: 1504 | from setuptools.command.sdist import sdist as _sdist 1505 | else: 1506 | from distutils.command.sdist import sdist as _sdist 1507 | 1508 | class cmd_sdist(_sdist): 1509 | def run(self): 1510 | versions = get_versions() 1511 | self._versioneer_generated_versions = versions 1512 | # unless we update this, the command will keep using the old 1513 | # version 1514 | self.distribution.metadata.version = versions["version"] 1515 | return _sdist.run(self) 1516 | 1517 | def make_release_tree(self, base_dir, files): 1518 | root = get_root() 1519 | cfg = get_config_from_root(root) 1520 | _sdist.make_release_tree(self, base_dir, files) 1521 | # now locate _version.py in the new base_dir directory 1522 | # (remembering that it may be a hardlink) and replace it with an 1523 | # updated value 1524 | target_versionfile = os.path.join(base_dir, cfg.versionfile_source) 1525 | print("UPDATING %s" % target_versionfile) 1526 | write_to_version_file(target_versionfile, 1527 | self._versioneer_generated_versions) 1528 | cmds["sdist"] = cmd_sdist 1529 | 1530 | return cmds 1531 | 1532 | 1533 | CONFIG_ERROR = """ 1534 | setup.cfg is missing the necessary Versioneer configuration. You need 1535 | a section like: 1536 | 1537 | [versioneer] 1538 | VCS = git 1539 | style = pep440 1540 | versionfile_source = src/myproject/_version.py 1541 | versionfile_build = myproject/_version.py 1542 | tag_prefix = "" 1543 | parentdir_prefix = myproject- 1544 | 1545 | You will also need to edit your setup.py to use the results: 1546 | 1547 | import versioneer 1548 | setup(version=versioneer.get_version(), 1549 | cmdclass=versioneer.get_cmdclass(), ...) 1550 | 1551 | Please read the docstring in ./versioneer.py for configuration instructions, 1552 | edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. 1553 | """ 1554 | 1555 | SAMPLE_CONFIG = """ 1556 | # See the docstring in versioneer.py for instructions. Note that you must 1557 | # re-run 'versioneer.py setup' after changing this section, and commit the 1558 | # resulting files. 1559 | 1560 | [versioneer] 1561 | #VCS = git 1562 | #style = pep440 1563 | #versionfile_source = 1564 | #versionfile_build = 1565 | #tag_prefix = 1566 | #parentdir_prefix = 1567 | 1568 | """ 1569 | 1570 | INIT_PY_SNIPPET = """ 1571 | from ._version import get_versions 1572 | __version__ = get_versions()['version'] 1573 | del get_versions 1574 | """ 1575 | 1576 | 1577 | def do_setup(): 1578 | root = get_root() 1579 | try: 1580 | cfg = get_config_from_root(root) 1581 | except (EnvironmentError, configparser.NoSectionError, 1582 | configparser.NoOptionError) as e: 1583 | if isinstance(e, (EnvironmentError, configparser.NoSectionError)): 1584 | print("Adding sample versioneer config to setup.cfg", 1585 | file=sys.stderr) 1586 | with open(os.path.join(root, "setup.cfg"), "a") as f: 1587 | f.write(SAMPLE_CONFIG) 1588 | print(CONFIG_ERROR, file=sys.stderr) 1589 | return 1 1590 | 1591 | print(" creating %s" % cfg.versionfile_source) 1592 | with open(cfg.versionfile_source, "w") as f: 1593 | LONG = LONG_VERSION_PY[cfg.VCS] 1594 | f.write(LONG % {"DOLLAR": "$", 1595 | "STYLE": cfg.style, 1596 | "TAG_PREFIX": cfg.tag_prefix, 1597 | "PARENTDIR_PREFIX": cfg.parentdir_prefix, 1598 | "VERSIONFILE_SOURCE": cfg.versionfile_source, 1599 | }) 1600 | 1601 | ipy = os.path.join(os.path.dirname(cfg.versionfile_source), 1602 | "__init__.py") 1603 | if os.path.exists(ipy): 1604 | try: 1605 | with open(ipy, "r") as f: 1606 | old = f.read() 1607 | except EnvironmentError: 1608 | old = "" 1609 | if INIT_PY_SNIPPET not in old: 1610 | print(" appending to %s" % ipy) 1611 | with open(ipy, "a") as f: 1612 | f.write(INIT_PY_SNIPPET) 1613 | else: 1614 | print(" %s unmodified" % ipy) 1615 | else: 1616 | print(" %s doesn't exist, ok" % ipy) 1617 | ipy = None 1618 | 1619 | # Make sure both the top-level "versioneer.py" and versionfile_source 1620 | # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so 1621 | # they'll be copied into source distributions. Pip won't be able to 1622 | # install the package without this. 1623 | manifest_in = os.path.join(root, "MANIFEST.in") 1624 | simple_includes = set() 1625 | try: 1626 | with open(manifest_in, "r") as f: 1627 | for line in f: 1628 | if line.startswith("include "): 1629 | for include in line.split()[1:]: 1630 | simple_includes.add(include) 1631 | except EnvironmentError: 1632 | pass 1633 | # That doesn't cover everything MANIFEST.in can do 1634 | # (http://docs.python.org/2/distutils/sourcedist.html#commands), so 1635 | # it might give some false negatives. Appending redundant 'include' 1636 | # lines is safe, though. 1637 | if "versioneer.py" not in simple_includes: 1638 | print(" appending 'versioneer.py' to MANIFEST.in") 1639 | with open(manifest_in, "a") as f: 1640 | f.write("include versioneer.py\n") 1641 | else: 1642 | print(" 'versioneer.py' already in MANIFEST.in") 1643 | if cfg.versionfile_source not in simple_includes: 1644 | print(" appending versionfile_source ('%s') to MANIFEST.in" % 1645 | cfg.versionfile_source) 1646 | with open(manifest_in, "a") as f: 1647 | f.write("include %s\n" % cfg.versionfile_source) 1648 | else: 1649 | print(" versionfile_source already in MANIFEST.in") 1650 | 1651 | # Make VCS-specific changes. For git, this means creating/changing 1652 | # .gitattributes to mark _version.py for export-time keyword 1653 | # substitution. 1654 | do_vcs_install(manifest_in, cfg.versionfile_source, ipy) 1655 | return 0 1656 | 1657 | 1658 | def scan_setup_py(): 1659 | found = set() 1660 | setters = False 1661 | errors = 0 1662 | with open("setup.py", "r") as f: 1663 | for line in f.readlines(): 1664 | if "import versioneer" in line: 1665 | found.add("import") 1666 | if "versioneer.get_cmdclass()" in line: 1667 | found.add("cmdclass") 1668 | if "versioneer.get_version()" in line: 1669 | found.add("get_version") 1670 | if "versioneer.VCS" in line: 1671 | setters = True 1672 | if "versioneer.versionfile_source" in line: 1673 | setters = True 1674 | if len(found) != 3: 1675 | print("") 1676 | print("Your setup.py appears to be missing some important items") 1677 | print("(but I might be wrong). Please make sure it has something") 1678 | print("roughly like the following:") 1679 | print("") 1680 | print(" import versioneer") 1681 | print(" setup( version=versioneer.get_version(),") 1682 | print(" cmdclass=versioneer.get_cmdclass(), ...)") 1683 | print("") 1684 | errors += 1 1685 | if setters: 1686 | print("You should remove lines like 'versioneer.VCS = ' and") 1687 | print("'versioneer.versionfile_source = ' . This configuration") 1688 | print("now lives in setup.cfg, and should be removed from setup.py") 1689 | print("") 1690 | errors += 1 1691 | return errors 1692 | 1693 | if __name__ == "__main__": 1694 | cmd = sys.argv[1] 1695 | if cmd == "setup": 1696 | errors = do_setup() 1697 | errors += scan_setup_py() 1698 | if errors: 1699 | sys.exit(1) 1700 | --------------------------------------------------------------------------------