diff --git a/.codeclimate.yml b/.codeclimate.yml deleted file mode 100644 index 99a7b1a0..00000000 --- a/.codeclimate.yml +++ /dev/null @@ -1,27 +0,0 @@ ---- -engines: - duplication: - enabled: true - config: - languages: - - python - fixme: - enabled: true - radon: - enabled: true - pep8: - enabled: true - -ratings: - paths: - - "**.inc" - - "**.js" - - "**.jsx" - - "**.module" - - "**.php" - - "**.py" - - "**.rb" - -exclude_paths: -- tests/ -- optlang/_version.py \ No newline at end of file diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..38a57686 --- /dev/null +++ b/.github/CODE_OF_CONDUCT.md @@ -0,0 +1,130 @@ + +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +[niko.sonnenschein@gmail.com](mailto:niko.sonnenschein@gmail.com). +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. + diff --git a/.github/CONTRIBUTING.rst b/.github/CONTRIBUTING.rst new file mode 100644 index 00000000..65d8d367 --- /dev/null +++ b/.github/CONTRIBUTING.rst @@ -0,0 +1,115 @@ +============ +Contributing +============ + +Contributions are welcome, and they are greatly appreciated! Every +little bit helps, and credit will always be given. + +You can contribute in many ways: + +Report Bugs +=========== + +Report bugs at https://github.com/opencobra/optlang/issues. + +If you are reporting a bug, please follow the template guidelines. The more +detailed your report, the easier and thus faster we can help you. + +Fix Bugs +======== + +Look through the GitHub issues for bugs. Anything tagged with "bug" +and "help wanted" is open to whoever wants to implement it. + +Implement Features +================== + +Look through the GitHub issues for features. Anything tagged with "enhancement" +and "help wanted" is open to whoever wants to implement it. + +Write Documentation +=================== + +optlang could always use more documentation, whether as part of the +official documentation, in docstrings, or even on the web in blog posts, +articles, and such. + +Submit Feedback +=============== + +The best way to send feedback is to file an issue at +https://github.com/opencobra/optlang/issues. + +If you are proposing a feature: + +* Explain in detail how it would work. +* Keep the scope as narrow as possible, to make it easier to implement. +* Remember that this is a volunteer-driven project, and that contributions + are welcome :) + +Get Started! +============ + +Ready to contribute? Here's how to set up optlang for +local development. + +1. Fork the https://github.com/opencobra/optlang + repository on GitHub. +2. Clone your fork locally + + .. code-block:: console + + git clone git@github.com:your_name_here/optlang.git + +3. Install your local copy into a a Python virtual environment. + You can `read this guide to learn more + `_ + about them and how to create one. Alternatively, particularly if you are a + Windows or Mac user, you can also use + `Anaconda `_. Assuming you have + virtualenvwrapper installed, this is how you set up your fork for local development + + .. code-block:: console + + mkvirtualenv my-env + cd optlang/ + pip install -e .[development] + +4. Create a branch for local development using the ``devel`` branch as a + starting point. Use ``fix`` or ``feat`` as a prefix + + .. code-block:: console + + git checkout devel + git checkout -b fix-name-of-your-bugfix + + Now you can make your changes locally. + +5. When you're done making changes, apply the quality assurance tools and check + that your changes pass our test suite. This is all included with tox + + .. code-block:: console + + make qa + tox + +6. Commit your changes and push your branch to GitHub. Please use `semantic + commit messages `_. + + .. code-block:: console + + git add . + git commit -m "fix: Your summary of changes" + git push origin fix-name-of-your-bugfix + +7. Open the link displayed in the message when pushing your new branch + in order to submit a pull request. + +Pull Request Guidelines +======================= + +Before you submit a pull request, check that it meets these guidelines: + +1. The pull request should include tests. +2. If the pull request adds functionality, the docs should be updated. Put + your new functionality into a function with a docstring. diff --git a/.github/ISSUE_TEMPLATE/01-bug-report.md b/.github/ISSUE_TEMPLATE/01-bug-report.md new file mode 100644 index 00000000..12d94b7f --- /dev/null +++ b/.github/ISSUE_TEMPLATE/01-bug-report.md @@ -0,0 +1,49 @@ +--- +name: Bug report +about: Report a bug to help improve this project +--- + + + +#### Problem description + +Please explain: +* **what** you tried to achieve, +* **how** you went about it (referring to the code sample), and +* **why** the current behaviour is a problem and what output + you expected instead. + +#### Code Sample + +Create a [minimal, complete, verifiable example](https://stackoverflow.com/help/mcve). + + +```python +``` + + +``` +``` + +### Context + + + +
+ +``` +``` + +
diff --git a/.github/ISSUE_TEMPLATE/02-question.md b/.github/ISSUE_TEMPLATE/02-question.md new file mode 100644 index 00000000..6b50051a --- /dev/null +++ b/.github/ISSUE_TEMPLATE/02-question.md @@ -0,0 +1,17 @@ +--- +name: Question +about: Ask a question +--- + +### Checklist + + + +- [ ] I searched the [documentation](https://optlang.readthedocs.io). +- [ ] I looked through [similar issues on GitHub](https://github.com/opencobra/optlang/issues). +- [ ] I looked up "How to do ... in optlang" on a search engine. + +### Question + + diff --git a/.github/ISSUE_TEMPLATE/03-feature-request.md b/.github/ISSUE_TEMPLATE/03-feature-request.md new file mode 100644 index 00000000..751095f1 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/03-feature-request.md @@ -0,0 +1,36 @@ +--- +name: Feature request +about: Suggest an idea for this project +--- + +### Checklist + + + +- [ ] There are [no similar issues or pull requests](https://github.com/opencobra/optlang/issues) for this yet. + +### Is your feature related to a problem? Please describe it. + + + +## Describe the solution you would like. + + + +## Describe alternatives you considered + + + +## Additional context + + diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..64fe0f56 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,4 @@ +* [ ] fix #(issue number) +* [ ] description of feature/fix +* [ ] tests added/passed +* [ ] add an entry to the [next release](../CHANGELOG.rst) diff --git a/.github/SUPPORT.rst b/.github/SUPPORT.rst new file mode 100644 index 00000000..7e238793 --- /dev/null +++ b/.github/SUPPORT.rst @@ -0,0 +1,6 @@ +======= +Support +======= + +* optlang `gitter chat `_ + diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 00000000..cacfca76 --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,91 @@ +name: CI-CD + +on: + push: + branches: + - master + - devel + tags: + - '[0-9]+.[0-9]+.[0-9]+' + - '[0-9]+.[0-9]+.[0-9]+rc[0-9]+' + pull_request: + branches: + - master + - devel + +jobs: + test: + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + python-version: [2.7, 3.5, 3.6, 3.7, 3.8] + exclude: + # Lacking swiglpk wheels for this combination. + - os: macos-latest + python-version: '3.5' + + steps: + - uses: actions/checkout@v2 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip setuptools wheel + python -m pip install tox tox-gh-actions codecov + - name: Test with tox + run: tox -- --cov-report=xml + - name: Report coverage + run: codecov +# uses: codecov/codecov-action@v1 +# with: +# fail_ci_if_error: true + + release: + needs: test + if: startsWith(github.ref, 'refs/tags') + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest] + python-version: [3.8] + + steps: + - uses: actions/checkout@v2 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + - name: Get tag + id: tag + run: echo "::set-output name=version::${GITHUB_REF#refs/tags/}" + - name: Install dependencies + run: | + python -m pip install --upgrade pip setuptools wheel + python -m pip install twine + - name: Build package + run: python setup.py sdist bdist_wheel + - name: Check the package + run: twine check dist/* + - name: Publish to PyPI + env: + TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} + TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} + run: + twine upload --skip-existing --non-interactive dist/* + - name: Create GitHub release + uses: actions/create-release@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag_name: ${{ github.ref }} + release_name: ${{ github.ref }} + body: > + Please see + https://github.com/${{ github.repository }}/blob/${{ steps.tag.outputs.version }}/CHANGELOG.rst + for the full release notes. + draft: false + prerelease: false diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 8762c9a4..00000000 --- a/.travis.yml +++ /dev/null @@ -1,65 +0,0 @@ -language: python -sudo: false -git: - depth: 2 -python: - - "2.7" - - "3.4" - - "3.5" - - "3.6" -branches: - only: - - master - - devel - - "/^\\d+\\.\\d+\\.\\d+[a]?\\d*$/" -env: - global: - - GITHUB_REPO=biosustain/optlang - - secure: PBcwrLg4ZwVi9Gw25Q2adNd0uK+NCqFSiYl+ZuumkEXs4NQBbSXVd719wrWKUFdIqBy+h9ETo4Vsz/QsTZzI2mSG4zqTkm+oUxMW1tJxYEeKZvCo7GfZ883VlKFgdqvh6iouEvHSjfGbwc5cUp98CbjgI5ni01vGpDQh2hgokkI= - matrix: - - OPTLANG_USE_SYMENGINE=False - - OPTLANG_USE_SYMENGINE=True -matrix: - fast_finish: true -cache: - - pip: true -before_install: - - export SYMPY_USE_CACHE=no - - pip install pip --upgrade - - 'echo "this is a build for: $TRAVIS_BRANCH"' - - 'if [[ "$TRAVIS_PYTHON_VERSION" < "3.5" ]]; then bash ./.travis/install_cplex.sh; fi' -install: - - pip install nose nose-progressive colorama==0.3.9 rednose coverage docutils flake8 codecov jsonschema - - pip install -r requirements.txt - - pip install scipy - - 'if [[ "$OPTLANG_USE_SYMENGINE" = "True" ]]; then pip install symengine; fi' - - python setup.py install -before_script: - - flake8 . -script: nosetests -after_success: - - codecov -notifications: - slack: - secure: s8Dj0MFreNwZ3Zhb0+5yJiHPL33JsxLjmoRo8f0ohLdD15L//E4VjkCsYkNEcLzid6HarEL/1JSmzAuGl40fCdLqTAoDRy01shT1zmfWQPXQlaALh5f8ExBAlyDHxKhd/B2SytYu6uhe0WOuxu/oo4c33a7pKhuV1piNcevPZew= -deploy: - - provider: releases - api_key: - secure: u4aJv+5YoH3gjJpyiVoq33SqKIUtx8LWPp15pIh8hKHmUgJNyjGm7ELXOeczfQ5W7ZpnWj+ogewaes2oA0NLxBB1/MBPL7kr77hmzp+XhZomh73DzFKegbpBTgqpioBRxvPlq3HYNIWqrLkeg/HYlBW1WM6mKifFUwqbIaL+++4= - skip_cleanup: true - on: - tags: true - repo: $GITHUB_REPO - python: "3.6" - condition: $OPTLANG_USE_SYMENGINE = False - - provider: pypi - skip_cleanup: true - distributions: sdist bdist_wheel - user: Nikolaus.Sonnenschein - password: - secure: Gn23MUvzP1DPJXxRXUOXGBJjyMamawxey5ByrOd+JT90roljHKSk8v1wdBMH7+s1DB/ygUJqB2Zy0cBC3mr0waY6HmxKpXhddgzQzG56Eua/npTxpz58Y8xfSYF+5QqS3gcyBrYEXmeHWuEURERy0b7uYKMx/QcHAHYhTaVy4zE= - on: - tags: true - repo: $GITHUB_REPO - python: "3.6" - condition: $OPTLANG_USE_SYMENGINE = False diff --git a/.travis/install_cplex.sh b/.travis/install_cplex.sh deleted file mode 100644 index 6fa3c1ca..00000000 --- a/.travis/install_cplex.sh +++ /dev/null @@ -1,10 +0,0 @@ -curl -L $SECRET_CPLEX_LINK -o cplex.tar.gz -tar xvf cplex.tar.gz -if [[ $TRAVIS_PYTHON_VERSION == "3.4" ]]; then - cd "cplex/python/3.4/x86-64_linux/"; -fi -if [[ $TRAVIS_PYTHON_VERSION == "2.7" ]]; then - cd "cplex/python/2.6/x86-64_linux/"; -fi -pip install . -cd $TRAVIS_BUILD_DIR diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 959d4a0e..00000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,6 +0,0 @@ -Contribute -========== - -Contributions to optlang are very welcome. Fork optlang at [github](http://github.com/biosustain/optlang), implement your feature and send us -a pull request. Also, please use the GitHub [issue tracker](https://github.com/biosustain/optlang/issues) -to let us know about bugs or feature requests, or if you have problems or questions regarding optlang. diff --git a/MANIFEST.in b/MANIFEST.in index 1ab86cd4..0dafca9d 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,7 +1,5 @@ include LICENSE -include README.md include README.rst -include requirements.txt include versioneer.py -include optlang/_version.py +include src/optlang/_version.py recursive-exclude slow_tests * diff --git a/NOTES.md b/NOTES.md deleted file mode 100644 index c841850f..00000000 --- a/NOTES.md +++ /dev/null @@ -1,13 +0,0 @@ -### Notes - -Supporting heuristic optimization too? Only objectives and variables would be needed and constraints would be superfluous. Objectives would probably have to support non-mathematical evaluation functions. - -Objective and Constraint could probably inherit from a common base class. - -use `pyreverse -my -o pdf optlang` to generate a UML diagram - -Looks like it is [not ok](https://code.google.com/p/sympy/issues/detail?id=3680#c7) to change sympy Symbol's name attribute (doesn't raise an error though). -Checkout [http://www.cuter.rl.ac.uk/](http://www.cuter.rl.ac.uk/) -Should Variables be singletons? - -http://jamie.curle.io/blog/my-first-experience-adding-package-pypi/ diff --git a/README.rst b/README.rst index 7ba457c7..e1566f13 100644 --- a/README.rst +++ b/README.rst @@ -3,7 +3,7 @@ optlang *Sympy based mathematical programming language* -|PyPI| |License| |Travis| |Appveyor| |Coverage Status| |Documentation Status| |Gitter| |JOSS| |DOI| +|PyPI| |Python Versions| |License| |Code of Conduct| |GitHub Actions| |Coverage Status| |Documentation Status| |Gitter| |JOSS| |DOI| Optlang is a Python package for solving mathematical optimization problems, i.e. maximizing or minimizing an objective function over a set @@ -139,23 +139,34 @@ Future outlook `CPLEX `__ etc.) -.. |PyPI| image:: https://img.shields.io/pypi/v/optlang.svg?maxAge=2592000 - :target: https://pypi.python.org/pypi/optlang -.. |License| image:: http://img.shields.io/badge/license-APACHE2-blue.svg - :target: http://img.shields.io/badge/license-APACHE2-blue.svg -.. |Travis| image:: https://img.shields.io/travis/biosustain/optlang/master.svg - :target: https://travis-ci.org/biosustain/optlang -.. |Coverage Status| image:: https://img.shields.io/codecov/c/github/biosustain/optlang/master.svg - :target: https://codecov.io/gh/biosustain/optlang/branch/master +.. |PyPI| image:: https://img.shields.io/pypi/v/optlang.svg + :target: https://pypi.org/project/optlang/ + :alt: Current PyPI Version +.. |Python Versions| image:: https://img.shields.io/pypi/pyversions/optlang.svg + :target: https://pypi.org/project/optlang/ + :alt: Supported Python Versions +.. |License| image:: https://img.shields.io/pypi/l/optlang.svg + :target: https://www.apache.org/licenses/LICENSE-2.0 + :alt: Apache Software License Version 2.0 +.. |Code of Conduct| image:: https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg + :target: .github/CODE_OF_CONDUCT.md + :alt: Code of Conduct +.. |GitHub Actions| image:: https://github.com/opencobra/optlang/workflows/CI-CD/badge.svg + :target: https://github.com/opencobra/optlang/workflows/CI-CD + :alt: GitHub Actions +.. |Coverage Status| image:: https://codecov.io/gh/opencobra/optlang/branch/master/graph/badge.svg + :target: https://codecov.io/gh/opencobra/optlang + :alt: Codecov .. |Documentation Status| image:: https://readthedocs.org/projects/optlang/badge/?version=latest :target: https://readthedocs.org/projects/optlang/?badge=latest + :alt: Documentation Status .. |JOSS| image:: http://joss.theoj.org/papers/cd848071a664d696e214a3950c840e15/status.svg :target: http://joss.theoj.org/papers/cd848071a664d696e214a3950c840e15 + :alt: Publication .. |DOI| image:: https://zenodo.org/badge/5031/biosustain/optlang.svg :target: https://zenodo.org/badge/latestdoi/5031/biosustain/optlang -.. |AppVeyor| image:: https://ci.appveyor.com/api/projects/status/443yp8hf25c6748h/branch/master?svg=true - :target: https://ci.appveyor.com/project/phantomas1234/optlang/branch/master + :alt: Zenodo Source Code .. |Gitter| image:: https://badges.gitter.im/biosustain/optlang.svg - :alt: Join the chat at https://gitter.im/biosustain/optlang :target: https://gitter.im/biosustain/optlang?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge + :alt: Join the chat at https://gitter.im/biosustain/optlang diff --git a/appveyor.yml b/appveyor.yml deleted file mode 100644 index 1f1e1a02..00000000 --- a/appveyor.yml +++ /dev/null @@ -1,44 +0,0 @@ -branches: - only: - - master - - devel - - "/^\\d+\\.\\d+\\.\\d+[a]?\\d*$/" - -environment: - global: - # SDK v7.0 MSVC Express 2008's SetEnv.cmd script will fail if the - # /E:ON and /V:ON options are not enabled in the batch script intepreter - # See: http://stackoverflow.com/a/13751649/163740 - WITH_COMPILER: "cmd /E:ON /V:ON /C .\\appveyor\\run_with_env.cmd" - PIP_CACHE_DIR: "pip_cache" - - matrix: - - PYTHON: "C:\\Python27-x64" - PYTHON_VERSION: "2.7.12" - PYTHON_ARCH: "64" - - - PYTHON: "C:\\Python34-x64" - PYTHON_VERSION: "3.4.5" - PYTHON_ARCH: "64" - - - PYTHON: "C:\\Python35-x64" - PYTHON_VERSION: "3.5.2" - PYTHON_ARCH: "64" - -clone_depth: 2 - -init: - - "ECHO %PYTHON% %PYTHON_VERSION% %PYTHON_ARCH%bit" - -cache: - - pip_cache -> appveyor.yml - -install: - - "powershell appveyor\\install.ps1" - - "%PYTHON%/python -m pip install pip setuptools wheel --upgrade" - - "%PYTHON%/python -m pip install nose colorama==0.3.9 rednose swiglpk coverage jsonschema numpy" - -build: off - -test_script: - - "%WITH_COMPILER% %PYTHON%/python setup.py test" diff --git a/appveyor/install.ps1 b/appveyor/install.ps1 deleted file mode 100644 index 3f056282..00000000 --- a/appveyor/install.ps1 +++ /dev/null @@ -1,85 +0,0 @@ -# Sample script to install Python and pip under Windows -# Authors: Olivier Grisel and Kyle Kastner -# License: CC0 1.0 Universal: http://creativecommons.org/publicdomain/zero/1.0/ - -$BASE_URL = "https://www.python.org/ftp/python/" -$GET_PIP_URL = "https://bootstrap.pypa.io/get-pip.py" -$GET_PIP_PATH = "C:\get-pip.py" - - -function DownloadPython ($python_version, $platform_suffix) { - $webclient = New-Object System.Net.WebClient - $filename = "python-" + $python_version + $platform_suffix + ".msi" - $url = $BASE_URL + $python_version + "/" + $filename - - $basedir = $pwd.Path + "\" - $filepath = $basedir + $filename - if (Test-Path $filename) { - Write-Host "Reusing" $filepath - return $filepath - } - - # Download and retry up to 5 times in case of network transient errors. - Write-Host "Downloading" $filename "from" $url - $retry_attempts = 3 - for($i=0; $i -lt $retry_attempts; $i++){ - try { - $webclient.DownloadFile($url, $filepath) - break - } - Catch [Exception]{ - Start-Sleep 1 - } - } - Write-Host "File saved at" $filepath - return $filepath -} - - -function InstallPython ($python_version, $architecture, $python_home) { - Write-Host "Installing Python" $python_version "for" $architecture "bit architecture to" $python_home - if (Test-Path $python_home) { - Write-Host $python_home "already exists, skipping." - return $false - } - if ($architecture -eq "32") { - $platform_suffix = "" - } else { - $platform_suffix = ".amd64" - } - $filepath = DownloadPython $python_version $platform_suffix - Write-Host "Installing" $filepath "to" $python_home - $args = "/qn /i $filepath TARGETDIR=$python_home" - Write-Host "msiexec.exe" $args - Start-Process -FilePath "msiexec.exe" -ArgumentList $args -Wait -Passthru - Write-Host "Python $python_version ($architecture) installation complete" - return $true -} - - -function InstallPip ($python_home) { - $pip_path = $python_home + "/Scripts/pip.exe" - $python_path = $python_home + "/python.exe" - if (-not(Test-Path $pip_path)) { - Write-Host "Installing pip..." - $webclient = New-Object System.Net.WebClient - $webclient.DownloadFile($GET_PIP_URL, $GET_PIP_PATH) - Write-Host "Executing:" $python_path $GET_PIP_PATH - Start-Process -FilePath "$python_path" -ArgumentList "$GET_PIP_PATH" -Wait -Passthru - } else { - Write-Host "pip already installed." - } -} - -function InstallPackage ($python_home, $pkg) { - $pip_path = $python_home + "/Scripts/pip.exe" - & $pip_path install $pkg -} - -function main () { - InstallPython $env:PYTHON_VERSION $env:PYTHON_ARCH $env:PYTHON - InstallPip $env:PYTHON - InstallPackage $env:PYTHON wheel -} - -main diff --git a/appveyor/run_with_env.cmd b/appveyor/run_with_env.cmd deleted file mode 100644 index 5da547c4..00000000 --- a/appveyor/run_with_env.cmd +++ /dev/null @@ -1,88 +0,0 @@ -:: To build extensions for 64 bit Python 3, we need to configure environment -:: variables to use the MSVC 2010 C++ compilers from GRMSDKX_EN_DVD.iso of: -:: MS Windows SDK for Windows 7 and .NET Framework 4 (SDK v7.1) -:: -:: To build extensions for 64 bit Python 2, we need to configure environment -:: variables to use the MSVC 2008 C++ compilers from GRMSDKX_EN_DVD.iso of: -:: MS Windows SDK for Windows 7 and .NET Framework 3.5 (SDK v7.0) -:: -:: 32 bit builds, and 64-bit builds for 3.5 and beyond, do not require specific -:: environment configurations. -:: -:: Note: this script needs to be run with the /E:ON and /V:ON flags for the -:: cmd interpreter, at least for (SDK v7.0) -:: -:: More details at: -:: https://github.com/cython/cython/wiki/64BitCythonExtensionsOnWindows -:: http://stackoverflow.com/a/13751649/163740 -:: -:: Author: Olivier Grisel -:: License: CC0 1.0 Universal: http://creativecommons.org/publicdomain/zero/1.0/ -:: -:: Notes about batch files for Python people: -:: -:: Quotes in values are literally part of the values: -:: SET FOO="bar" -:: FOO is now five characters long: " b a r " -:: If you don't want quotes, don't include them on the right-hand side. -:: -:: The CALL lines at the end of this file look redundant, but if you move them -:: outside of the IF clauses, they do not run properly in the SET_SDK_64==Y -:: case, I don't know why. -@ECHO OFF - -SET COMMAND_TO_RUN=%* -SET WIN_SDK_ROOT=C:\Program Files\Microsoft SDKs\Windows -SET WIN_WDK=c:\Program Files (x86)\Windows Kits\10\Include\wdf - -:: Extract the major and minor versions, and allow for the minor version to be -:: more than 9. This requires the version number to have two dots in it. -SET MAJOR_PYTHON_VERSION=%PYTHON_VERSION:~0,1% -IF "%PYTHON_VERSION:~3,1%" == "." ( - SET MINOR_PYTHON_VERSION=%PYTHON_VERSION:~2,1% -) ELSE ( - SET MINOR_PYTHON_VERSION=%PYTHON_VERSION:~2,2% -) - -:: Based on the Python version, determine what SDK version to use, and whether -:: to set the SDK for 64-bit. -IF %MAJOR_PYTHON_VERSION% == 2 ( - SET WINDOWS_SDK_VERSION="v7.0" - SET SET_SDK_64=Y -) ELSE ( - IF %MAJOR_PYTHON_VERSION% == 3 ( - SET WINDOWS_SDK_VERSION="v7.1" - IF %MINOR_PYTHON_VERSION% LEQ 4 ( - SET SET_SDK_64=Y - ) ELSE ( - SET SET_SDK_64=N - IF EXIST "%WIN_WDK%" ( - :: See: https://connect.microsoft.com/VisualStudio/feedback/details/1610302/ - REN "%WIN_WDK%" 0wdf - ) - ) - ) ELSE ( - ECHO Unsupported Python version: "%MAJOR_PYTHON_VERSION%" - EXIT 1 - ) -) - -IF %PYTHON_ARCH% == 64 ( - IF %SET_SDK_64% == Y ( - ECHO Configuring Windows SDK %WINDOWS_SDK_VERSION% for Python %MAJOR_PYTHON_VERSION% on a 64 bit architecture - SET DISTUTILS_USE_SDK=1 - SET MSSdk=1 - "%WIN_SDK_ROOT%\%WINDOWS_SDK_VERSION%\Setup\WindowsSdkVer.exe" -q -version:%WINDOWS_SDK_VERSION% - "%WIN_SDK_ROOT%\%WINDOWS_SDK_VERSION%\Bin\SetEnv.cmd" /x64 /release - ECHO Executing: %COMMAND_TO_RUN% - call %COMMAND_TO_RUN% || EXIT 1 - ) ELSE ( - ECHO Using default MSVC build environment for 64 bit architecture - ECHO Executing: %COMMAND_TO_RUN% - call %COMMAND_TO_RUN% || EXIT 1 - ) -) ELSE ( - ECHO Using default MSVC build environment for 32 bit architecture - ECHO Executing: %COMMAND_TO_RUN% - call %COMMAND_TO_RUN% || EXIT 1 -) diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index e3990af9..00000000 --- a/requirements.txt +++ /dev/null @@ -1,3 +0,0 @@ -sympy>=1.0.0 -six>=1.9.0 -swiglpk>=1.4.3 diff --git a/setup.cfg b/setup.cfg index f5c7cb1c..99ed9c6e 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,18 +1,75 @@ -[nosetests] -detailed-errors=1 -verbosity=2 -rednose=1 -with-coverage=1 -cover-package=optlang - [metadata] -description-file = README.md +name = optlang +url = https://github.com/opencobra/optlang +download_url = https://pypi.org/project/optlang/ +project_urls = + Source Code = https://github.com/opencobra/optlang + Documentation = https://optlang.readthedocs.io + Bug Tracker = https://github.com/opencobra/optlang/issues +author = Nikolaus Sonnenschein +author_email = niko.sonnenschein@gmail.com +# Please consult https://pypi.org/classifiers/ for a full list. +classifiers = + Development Status :: 5 - Production/Stable + Intended Audience :: Science/Research + License :: OSI Approved :: Apache Software License + Natural Language :: English + Operating System :: OS Independent + Programming Language :: Python :: 2.7 + Programming Language :: Python :: 3.5 + Programming Language :: Python :: 3.6 + Programming Language :: Python :: 3.7 + Programming Language :: Python :: 3.8 + Topic :: Scientific/Engineering :: Mathematics +license = Apache-2.0 +description = Formulate optimization problems using sympy expressions and solve them using interfaces to third-party optimization software (e.g. GLPK). +long_description = file: README.rst +long_description_content_type = text/x-rst +keywords = + optimization + mathematical programming + heuristic optimization + sympy + +[options] +zip_safe = True +install_requires = + six >=1.9 + swiglpk >=1.4.3 + sympy >=1.0 +python_requires = >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.* +tests_require = + tox +packages = find: +package_dir = + = src + +[options.packages.find] +where = src -[flake8] -ignore = E402,E303,E122,F401,F812,E251,E123,W504 -max-line-length = 160 -exclude = optlang/tests/*,versioneer.py,__init__.py,_version.py,plotting_old.py,cplex/*,docs/notebooks,.tox,build,slow_tests -max-complexity = 20 +[options.extras_require] +development = + black + isort + tox +;test = +; 'nose>=1.3.7', +; 'colorama==0.3.9', +; 'rednose>=0.4.3', +; 'coverage>=4.0.3', +; 'jsonschema>=2.5' [bdist_wheel] universal = 1 + +# See the docstring in versioneer.py for instructions. Note that you must +# re-run 'versioneer.py setup' after changing this section, and commit the +# resulting files. + +[versioneer] +VCS = git +style = pep440 +versionfile_source = src/optlang/_version.py +versionfile_build = optlang/_version.py +tag_prefix = +parentdir_prefix = optlang- diff --git a/setup.py b/setup.py index dd4c7d3a..8dbc20ab 100644 --- a/setup.py +++ b/setup.py @@ -13,66 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. -import os -from setuptools import setup, find_packages -from itertools import chain +"""Set up the optlang package.""" -import versioneer - -versioneer.VCS = 'git' -versioneer.versionfile_source = 'optlang/_version.py' -versioneer.versionfile_build = 'optlang/_version.py' -versioneer.tag_prefix = '' # tags are like 1.2.0 -versioneer.parentdir_prefix = 'optlang-' # dirname like 'myproject-1.2.0' - -# Run -# pandoc --from=markdown --to=rst README.md -o README.rst -# from time to time, to keep README.rst updated -with open('README.rst', 'r') as f: - description = f.read() - -on_rtd = os.environ.get('READTHEDOCS', None) == 'True' -if on_rtd: - requirements = [] -else: - # requirements = ['sympy>=1.0.0', 'six>=1.9.0'] - with open("requirements.txt") as infile: - requirements = infile.read().splitlines() +import versioneer +from setuptools import setup -extra_requirements = { - 'test': [ - 'nose>=1.3.7', - 'colorama==0.3.9', - 'rednose>=0.4.3', - 'coverage>=4.0.3', - 'jsonschema>=2.5' - ], -} -extra_requirements['all'] = list(set(chain(*extra_requirements.values()))) -setup( - name='optlang', - version=versioneer.get_version(), - cmdclass=versioneer.get_cmdclass(), - packages=find_packages(), - install_requires=requirements, # from requirements.txt - extras_require=extra_requirements, - test_suite='nose.collector', - author='Nikolaus Sonnenschein', - author_email='niko.sonnenschein@gmail.com', - description='Formulate optimization problems using sympy expressions and solve them using interfaces to third-party optimization software (e.g. GLPK).', - license='Apache License Version 2.0', - url='https://github.com/biosustain/optlang', - long_description=description, - keywords=['optimization', 'sympy', 'mathematical programming', 'heuristic optimization'], - classifiers=[ - 'Development Status :: 5 - Production/Stable', - 'Topic :: Scientific/Engineering :: Mathematics', - 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3.4', - 'Programming Language :: Python :: 3.5', - 'License :: OSI Approved :: Apache Software License', - ], -) +# All other arguments are defined in `setup.cfg`. +setup(version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass()) diff --git a/optlang/__init__.py b/src/optlang/__init__.py similarity index 100% rename from optlang/__init__.py rename to src/optlang/__init__.py diff --git a/optlang/_version.py b/src/optlang/_version.py similarity index 100% rename from optlang/_version.py rename to src/optlang/_version.py diff --git a/optlang/container.py b/src/optlang/container.py similarity index 100% rename from optlang/container.py rename to src/optlang/container.py diff --git a/optlang/cplex_interface.py b/src/optlang/cplex_interface.py similarity index 100% rename from optlang/cplex_interface.py rename to src/optlang/cplex_interface.py diff --git a/optlang/duality.py b/src/optlang/duality.py similarity index 100% rename from optlang/duality.py rename to src/optlang/duality.py diff --git a/optlang/exceptions.py b/src/optlang/exceptions.py similarity index 100% rename from optlang/exceptions.py rename to src/optlang/exceptions.py diff --git a/optlang/expression_parsing.py b/src/optlang/expression_parsing.py similarity index 100% rename from optlang/expression_parsing.py rename to src/optlang/expression_parsing.py diff --git a/optlang/glpk_exact_interface.py b/src/optlang/glpk_exact_interface.py similarity index 100% rename from optlang/glpk_exact_interface.py rename to src/optlang/glpk_exact_interface.py diff --git a/optlang/glpk_interface.py b/src/optlang/glpk_interface.py similarity index 100% rename from optlang/glpk_interface.py rename to src/optlang/glpk_interface.py diff --git a/optlang/gurobi_interface.py b/src/optlang/gurobi_interface.py similarity index 100% rename from optlang/gurobi_interface.py rename to src/optlang/gurobi_interface.py diff --git a/optlang/inspyred_interface.py b/src/optlang/inspyred_interface.py similarity index 100% rename from optlang/inspyred_interface.py rename to src/optlang/inspyred_interface.py diff --git a/optlang/interface.py b/src/optlang/interface.py similarity index 100% rename from optlang/interface.py rename to src/optlang/interface.py diff --git a/optlang/scipy_interface.py b/src/optlang/scipy_interface.py similarity index 100% rename from optlang/scipy_interface.py rename to src/optlang/scipy_interface.py diff --git a/optlang/symbolics.py b/src/optlang/symbolics.py similarity index 95% rename from optlang/symbolics.py rename to src/optlang/symbolics.py index 228eda86..4d51f165 100644 --- a/optlang/symbolics.py +++ b/src/optlang/symbolics.py @@ -41,8 +41,6 @@ except ImportError as e: if SYMENGINE_PREFERENCE.lower() in ("true", "yes", "on"): logger.warn("Symengine could not be imported: " + str(e)) - if os.getenv('TRAVIS', None) is not None: # Travis should error here # pragma: no cover - raise RuntimeError("Symengine should be used but could not be!") USE_SYMENGINE = False else: USE_SYMENGINE = True diff --git a/optlang/tests/__init__.py b/src/optlang/tests/__init__.py similarity index 100% rename from optlang/tests/__init__.py rename to src/optlang/tests/__init__.py diff --git a/optlang/tests/abstract_test_cases.py b/src/optlang/tests/abstract_test_cases.py similarity index 100% rename from optlang/tests/abstract_test_cases.py rename to src/optlang/tests/abstract_test_cases.py diff --git a/optlang/tests/data/__init__.py b/src/optlang/tests/data/__init__.py similarity index 100% rename from optlang/tests/data/__init__.py rename to src/optlang/tests/data/__init__.py diff --git a/optlang/tests/data/alternative_model.lp b/src/optlang/tests/data/alternative_model.lp similarity index 100% rename from optlang/tests/data/alternative_model.lp rename to src/optlang/tests/data/alternative_model.lp diff --git a/optlang/tests/data/coli_core.json b/src/optlang/tests/data/coli_core.json similarity index 100% rename from optlang/tests/data/coli_core.json rename to src/optlang/tests/data/coli_core.json diff --git a/optlang/tests/data/model.json b/src/optlang/tests/data/model.json similarity index 100% rename from optlang/tests/data/model.json rename to src/optlang/tests/data/model.json diff --git a/optlang/tests/data/model.lp b/src/optlang/tests/data/model.lp similarity index 100% rename from optlang/tests/data/model.lp rename to src/optlang/tests/data/model.lp diff --git a/optlang/tests/data/netlib_lp_problems.tar.gz b/src/optlang/tests/data/netlib_lp_problems.tar.gz similarity index 100% rename from optlang/tests/data/netlib_lp_problems.tar.gz rename to src/optlang/tests/data/netlib_lp_problems.tar.gz diff --git a/optlang/tests/data/netlib_reference_results/NOTES.txt b/src/optlang/tests/data/netlib_reference_results/NOTES.txt similarity index 100% rename from optlang/tests/data/netlib_reference_results/NOTES.txt rename to src/optlang/tests/data/netlib_reference_results/NOTES.txt diff --git a/optlang/tests/data/parse_the_final_netlib_results.py b/src/optlang/tests/data/parse_the_final_netlib_results.py similarity index 100% rename from optlang/tests/data/parse_the_final_netlib_results.py rename to src/optlang/tests/data/parse_the_final_netlib_results.py diff --git a/optlang/tests/data/qp.lp b/src/optlang/tests/data/qp.lp similarity index 100% rename from optlang/tests/data/qp.lp rename to src/optlang/tests/data/qp.lp diff --git a/optlang/tests/data/qplib_1832.lp b/src/optlang/tests/data/qplib_1832.lp similarity index 100% rename from optlang/tests/data/qplib_1832.lp rename to src/optlang/tests/data/qplib_1832.lp diff --git a/optlang/tests/data/qplib_3256.lp b/src/optlang/tests/data/qplib_3256.lp similarity index 100% rename from optlang/tests/data/qplib_3256.lp rename to src/optlang/tests/data/qplib_3256.lp diff --git a/optlang/tests/data/simple_milp.json b/src/optlang/tests/data/simple_milp.json similarity index 100% rename from optlang/tests/data/simple_milp.json rename to src/optlang/tests/data/simple_milp.json diff --git a/optlang/tests/data/simple_milp.lp b/src/optlang/tests/data/simple_milp.lp similarity index 100% rename from optlang/tests/data/simple_milp.lp rename to src/optlang/tests/data/simple_milp.lp diff --git a/optlang/tests/data/the_final_netlib_results.pcl b/src/optlang/tests/data/the_final_netlib_results.pcl similarity index 100% rename from optlang/tests/data/the_final_netlib_results.pcl rename to src/optlang/tests/data/the_final_netlib_results.pcl diff --git a/optlang/tests/test_change_solver.py b/src/optlang/tests/test_change_solver.py similarity index 100% rename from optlang/tests/test_change_solver.py rename to src/optlang/tests/test_change_solver.py diff --git a/optlang/tests/test_container.py b/src/optlang/tests/test_container.py similarity index 100% rename from optlang/tests/test_container.py rename to src/optlang/tests/test_container.py diff --git a/optlang/tests/test_cplex_interface.py b/src/optlang/tests/test_cplex_interface.py similarity index 100% rename from optlang/tests/test_cplex_interface.py rename to src/optlang/tests/test_cplex_interface.py diff --git a/optlang/tests/test_duality.py b/src/optlang/tests/test_duality.py similarity index 100% rename from optlang/tests/test_duality.py rename to src/optlang/tests/test_duality.py diff --git a/optlang/tests/test_elements.py b/src/optlang/tests/test_elements.py similarity index 100% rename from optlang/tests/test_elements.py rename to src/optlang/tests/test_elements.py diff --git a/optlang/tests/test_expression_parsing.py b/src/optlang/tests/test_expression_parsing.py similarity index 100% rename from optlang/tests/test_expression_parsing.py rename to src/optlang/tests/test_expression_parsing.py diff --git a/optlang/tests/test_glpk_exact_interface.py b/src/optlang/tests/test_glpk_exact_interface.py similarity index 100% rename from optlang/tests/test_glpk_exact_interface.py rename to src/optlang/tests/test_glpk_exact_interface.py diff --git a/optlang/tests/test_glpk_interface.py b/src/optlang/tests/test_glpk_interface.py similarity index 100% rename from optlang/tests/test_glpk_interface.py rename to src/optlang/tests/test_glpk_interface.py diff --git a/optlang/tests/test_gurobi_interface.py b/src/optlang/tests/test_gurobi_interface.py similarity index 100% rename from optlang/tests/test_gurobi_interface.py rename to src/optlang/tests/test_gurobi_interface.py diff --git a/optlang/tests/test_inspyred_interface.py b/src/optlang/tests/test_inspyred_interface.py similarity index 100% rename from optlang/tests/test_inspyred_interface.py rename to src/optlang/tests/test_inspyred_interface.py diff --git a/optlang/tests/test_interface.py b/src/optlang/tests/test_interface.py similarity index 100% rename from optlang/tests/test_interface.py rename to src/optlang/tests/test_interface.py diff --git a/optlang/tests/test_io.py b/src/optlang/tests/test_io.py similarity index 100% rename from optlang/tests/test_io.py rename to src/optlang/tests/test_io.py diff --git a/optlang/tests/test_netlib_cplex_interface.py b/src/optlang/tests/test_netlib_cplex_interface.py similarity index 99% rename from optlang/tests/test_netlib_cplex_interface.py rename to src/optlang/tests/test_netlib_cplex_interface.py index 045a5eec..34b545ff 100644 --- a/optlang/tests/test_netlib_cplex_interface.py +++ b/src/optlang/tests/test_netlib_cplex_interface.py @@ -123,7 +123,7 @@ def test_netlib(netlib_tar_path=os.path.join(os.path.dirname(__file__), 'data/ne netlib_id, os.path.basename(str(__file__))) yield func - if not os.getenv('TRAVIS', False): + if os.getenv('CI', 'false') != 'true': # check that a cloned model also gives the correct result model = Model.clone(model, use_json=False, use_lp=False) model.optimize() diff --git a/optlang/tests/test_netlib_glpk_exact_interface.py b/src/optlang/tests/test_netlib_glpk_exact_interface.py similarity index 90% rename from optlang/tests/test_netlib_glpk_exact_interface.py rename to src/optlang/tests/test_netlib_glpk_exact_interface.py index 56257f7c..f57a9087 100644 --- a/optlang/tests/test_netlib_glpk_exact_interface.py +++ b/src/optlang/tests/test_netlib_glpk_exact_interface.py @@ -22,8 +22,8 @@ def test_netlib(netlib_tar_path=os.path.join(os.path.dirname(__file__), 'data/ne """ if six.PY3: nose.SkipTest('Skipping because py3') - elif os.getenv('TRAVIS'): - nose.SkipTest('Skipping because travis (solving problems exactly takes very long.)') + elif os.getenv('CI', 'false') == 'true': + nose.SkipTest('Skipping because solving problems exactly takes very long.') else: with open(os.path.join(os.path.dirname(__file__), 'data/the_final_netlib_results.pcl'), 'rb') as fhandle: THE_FINAL_NETLIB_RESULTS = pickle.load(fhandle) @@ -95,7 +95,7 @@ def check_objval_against_the_final_netlib_results(netlib_id, model_objval): netlib_id, os.path.basename(str(__file__))) yield func - if not os.getenv('TRAVIS', False): + if os.getenv('CI', 'false') != 'true': # check that a cloned model also gives the correct result model = Model.clone(model, use_json=False, use_lp=False) model.optimize() @@ -104,11 +104,10 @@ def check_objval_against_the_final_netlib_results(netlib_id, model_objval): else: raise Exception('No optimal solution found for netlib model %s' % netlib_id) - if not os.getenv('TRAVIS', False): - func = partial(check_objval_against_the_final_netlib_results, netlib_id, model_objval) - func.description = "test_netlib_check_objective_value__against_the_final_netlib_results_after_cloning_%s (%s)" % ( - netlib_id, os.path.basename(str(__file__))) - yield func + func = partial(check_objval_against_the_final_netlib_results, netlib_id, model_objval) + func.description = "test_netlib_check_objective_value__against_the_final_netlib_results_after_cloning_%s (%s)" % ( + netlib_id, os.path.basename(str(__file__))) + yield func if __name__ == '__main__': diff --git a/optlang/tests/test_netlib_glpk_interface.py b/src/optlang/tests/test_netlib_glpk_interface.py similarity index 92% rename from optlang/tests/test_netlib_glpk_interface.py rename to src/optlang/tests/test_netlib_glpk_interface.py index 1e171401..eda9129d 100644 --- a/optlang/tests/test_netlib_glpk_interface.py +++ b/src/optlang/tests/test_netlib_glpk_interface.py @@ -111,7 +111,7 @@ def check_objval_against_the_final_netlib_results(netlib_id, model_objval): netlib_id, os.path.basename(str(__file__))) yield func - if not os.getenv('TRAVIS', False): + if os.getenv('CI', 'false') != 'true': # check that a cloned model also gives the correct result model = Model.clone(model, use_json=False, use_lp=False) model.optimize() @@ -120,11 +120,10 @@ def check_objval_against_the_final_netlib_results(netlib_id, model_objval): else: raise Exception('No optimal solution found for netlib model %s' % netlib_id) - if not os.getenv('TRAVIS', False): - func = partial(check_objval_against_the_final_netlib_results, netlib_id, model_objval) - func.description = "test_netlib_check_objective_value__against_the_final_netlib_results_after_cloning_%s (%s)" % ( - netlib_id, os.path.basename(str(__file__))) - yield func + func = partial(check_objval_against_the_final_netlib_results, netlib_id, model_objval) + func.description = "test_netlib_check_objective_value__against_the_final_netlib_results_after_cloning_%s (%s)" % ( + netlib_id, os.path.basename(str(__file__))) + yield func if __name__ == '__main__': diff --git a/optlang/tests/test_netlib_gurobi_interface.py b/src/optlang/tests/test_netlib_gurobi_interface.py similarity index 99% rename from optlang/tests/test_netlib_gurobi_interface.py rename to src/optlang/tests/test_netlib_gurobi_interface.py index 23488b65..389a6a2b 100644 --- a/optlang/tests/test_netlib_gurobi_interface.py +++ b/src/optlang/tests/test_netlib_gurobi_interface.py @@ -126,7 +126,7 @@ def test_netlib(netlib_tar_path=os.path.join(os.path.dirname(__file__), 'data/ne netlib_id, os.path.basename(str(__file__))) yield func - if not os.getenv('TRAVIS', False): + if os.getenv('CI', 'false') != 'true': # check that a cloned model also gives the correct result model = Model.clone(model, use_json=False, use_lp=False) model.optimize() diff --git a/optlang/tests/test_scipy_interface.py b/src/optlang/tests/test_scipy_interface.py similarity index 100% rename from optlang/tests/test_scipy_interface.py rename to src/optlang/tests/test_scipy_interface.py diff --git a/optlang/tests/test_symbolics.py b/src/optlang/tests/test_symbolics.py similarity index 100% rename from optlang/tests/test_symbolics.py rename to src/optlang/tests/test_symbolics.py diff --git a/optlang/tests/test_util.py b/src/optlang/tests/test_util.py similarity index 100% rename from optlang/tests/test_util.py rename to src/optlang/tests/test_util.py diff --git a/optlang/util.py b/src/optlang/util.py similarity index 100% rename from optlang/util.py rename to src/optlang/util.py diff --git a/tox.ini b/tox.ini index 0bd3539a..0fa92550 100644 --- a/tox.ini +++ b/tox.ini @@ -1,17 +1,151 @@ -# content of: tox.ini , put in same dir as setup.py [tox] -envlist = py27,py35 +envlist = isort, black, flake8, safety, docs, py27, py3{5,6,7,8}-symengine -[testenv:flake8] -deps=flake8 -commands=flake8 . +[gh-actions] +python = + 2.7: safety, py27 + 3.5: safety, py35, py35-symengine + 3.6: safety, py36, py36-symengine + 3.7: safety, py37, py37-symengine + 3.8: safety, py38, py38-symengine + +;[testenv] +;deps = +; pytest +; pytest-cov +; pytest-raises +;commands = +; pytest --cov=optlang --cov-report=term {posargs} [testenv] -deps=nose +deps = colorama ~= 0.3.9 - rednose - swiglpk coverage + docutils jsonschema - numpy -commands=nosetests + nose + nose-progressive + rednose + scipy + symengine: symengine +passenv = CI +commands = + nosetests src/optlang/tests -vv + +[testenv:isort] +skip_install = True +deps= + isort +commands= + isort --check-only --diff {toxinidir}/src/optlang {toxinidir}/tests {toxinidir}/setup.py + +[testenv:black] +skip_install = True +deps= + black +commands= + black --check --diff {toxinidir}/src/optlang {toxinidir}/tests {toxinidir}/setup.py + +[testenv:flake8] +skip_install = True +deps= + flake8 + flake8-docstrings + flake8-bugbear +commands= + flake8 {toxinidir}/src/optlang {toxinidir}/tests {toxinidir}/setup.py + +[testenv:safety] +deps= + safety +commands= + safety check --full-report + +[testenv:mypy] +skip_install = True +deps= + mypy +commands= + mypy {toxinidir}/src/optlang + +[testenv:docs] +skip_install = True +deps= + -r{toxinidir}/docs/requirements.txt +whitelist_externals = + make +commands= + make -C {toxinidir}/docs html + make -C {toxinidir}/docs linkcheck + +################################################################################ +# Testing tools configuration # +################################################################################ + +[pytest] +testpaths = + src/optlang/tests +markers = + raises + +;[coverage:paths] +;source = +; src/optlang +; */site-packages/optlang + +;[coverage:run] +;branch = true +;parallel = true +;omit = +; src/optlang/_version.py + +;[coverage:report] +;exclude_lines = +;# Have to re-enable the standard pragma +; pragma: no cover +;precision = 2 +;omit = +; src/optlang/_version.py + +[flake8] +max-line-length = 130 +exclude = + __init__.py + _version.py + src/optlang/tests/* +# The following conflict with `black` which is the more pedantic. +ignore = + E203 + W503 + D202 +max-complexity = 20 + +[isort] +skip = + __init__.py + _version.py +line_length = 130 +indent = 4 +multi_line_output = 3 +include_trailing_comma = true +force_grid_wrap = 0 +use_parentheses = true +lines_after_imports = 2 +known_first_party = optlang +known_third_party = + pytest + setuptools + versioneer + +[nosetests] +detailed-errors=1 +verbosity=2 +rednose=1 +with-coverage=1 +cover-package=optlang + +;[flake8] +;ignore = E402,E303,E122,F401,F812,E251,E123,W504 +;max-line-length = 160 +;exclude = optlang/tests/*,versioneer.py,__init__.py,_version.py,plotting_old.py,cplex/*,docs/notebooks,.tox,build,slow_tests +;max-complexity = 20 diff --git a/versioneer.py b/versioneer.py index d3fe56ce..64fea1c8 100644 --- a/versioneer.py +++ b/versioneer.py @@ -1,7 +1,8 @@ -# Version: 0.13 +# Version: 0.18 + +"""The Versioneer - like a rocketeer, but for versions. -""" The Versioneer ============== @@ -9,9 +10,13 @@ * https://github.com/warner/python-versioneer * Brian Warner * License: Public Domain -* Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, and pypy -* [![Latest Version](https://pypip.in/version/versioneer/badge.svg?style=flat)](https://pypi.python.org/pypi/versioneer/) -* [![Build Status](https://travis-ci.org/warner/python-versioneer.png?branch=master)](https://travis-ci.org/warner/python-versioneer) +* Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, 3.5, 3.6, and pypy +* [![Latest Version] +(https://pypip.in/version/versioneer/badge.svg?style=flat) +](https://pypi.python.org/pypi/versioneer/) +* [![Build Status] +(https://travis-ci.org/warner/python-versioneer.png?branch=master) +](https://travis-ci.org/warner/python-versioneer) This is a tool for managing a recorded version number in distutils-based python projects. The goal is to remove the tedious and error-prone "update @@ -23,8 +28,8 @@ ## Quick Install * `pip install versioneer` to somewhere to your $PATH -* run `versioneer-installer` in your source tree: this installs `versioneer.py` -* follow the instructions below (also in the `versioneer.py` docstring) +* add a `[versioneer]` section to your setup.cfg (see below) +* run `versioneer install` in your source tree, commit the results ## Version Identifiers @@ -53,7 +58,7 @@ enough information to help developers recreate the same tree, while also giving them an idea of roughly how old the tree is (after version 1.2, before version 1.3). Many VCS systems can report a description that captures this, -for example 'git describe --tags --dirty --always' reports things like +for example `git describe --tags --dirty --always` reports things like "0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the 0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has uncommitted changes. @@ -67,189 +72,186 @@ Versioneer works by adding a special `_version.py` file into your source tree, where your `__init__.py` can import it. This `_version.py` knows how to -dynamically ask the VCS tool for version information at import time. However, -when you use "setup.py build" or "setup.py sdist", `_version.py` in the new -copy is replaced by a small static file that contains just the generated -version data. +dynamically ask the VCS tool for version information at import time. `_version.py` also contains `$Revision$` markers, and the installation process marks `_version.py` to have this marker rewritten with a tag name -during the "git archive" command. As a result, generated tarballs will +during the `git archive` command. As a result, generated tarballs will contain enough information to get the proper version. +To allow `setup.py` to compute a version too, a `versioneer.py` is added to +the top level of your source tree, next to `setup.py` and the `setup.cfg` +that configures it. This overrides several distutils/setuptools commands to +compute the version when invoked, and changes `setup.py build` and `setup.py +sdist` to replace `_version.py` with a small static file that contains just +the generated version data. ## Installation -First, decide on values for the following configuration variables: +See [INSTALL.md](./INSTALL.md) for detailed installation instructions. -* `VCS`: the version control system you use. Currently accepts "git". +## Version-String Flavors -* `versionfile_source`: +Code which uses Versioneer can learn about its version string at runtime by +importing `_version` from your main `__init__.py` file and running the +`get_versions()` function. From the "outside" (e.g. in `setup.py`), you can +import the top-level `versioneer.py` and run `get_versions()`. - A project-relative pathname into which the generated version strings should - be written. This is usually a `_version.py` next to your project's main - `__init__.py` file, so it can be imported at runtime. If your project uses - `src/myproject/__init__.py`, this should be `src/myproject/_version.py`. - This file should be checked in to your VCS as usual: the copy created below - by `setup.py versioneer` will include code that parses expanded VCS - keywords in generated tarballs. The 'build' and 'sdist' commands will - replace it with a copy that has just the calculated version string. +Both functions return a dictionary with different flavors of version +information: - This must be set even if your project does not have any modules (and will - therefore never import `_version.py`), since "setup.py sdist" -based trees - still need somewhere to record the pre-calculated version strings. Anywhere - in the source tree should do. If there is a `__init__.py` next to your - `_version.py`, the `setup.py versioneer` command (described below) will - append some `__version__`-setting assignments, if they aren't already - present. +* `['version']`: A condensed version string, rendered using the selected + style. This is the most commonly used value for the project's version + string. The default "pep440" style yields strings like `0.11`, + `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section + below for alternative styles. -* `versionfile_build`: +* `['full-revisionid']`: detailed revision identifier. For Git, this is the + full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". - Like `versionfile_source`, but relative to the build directory instead of - the source directory. These will differ when your setup.py uses - 'package_dir='. If you have `package_dir={'myproject': 'src/myproject'}`, - then you will probably have `versionfile_build='myproject/_version.py'` and - `versionfile_source='src/myproject/_version.py'`. +* `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the + commit date in ISO 8601 format. This will be None if the date is not + available. - If this is set to None, then `setup.py build` will not attempt to rewrite - any `_version.py` in the built tree. If your project does not have any - libraries (e.g. if it only builds a script), then you should use - `versionfile_build = None` and override `distutils.command.build_scripts` - to explicitly insert a copy of `versioneer.get_version()` into your - generated script. +* `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that + this is only accurate if run in a VCS checkout, otherwise it is likely to + be False or None -* `tag_prefix`: +* `['error']`: if the version string could not be computed, this will be set + to a string describing the problem, otherwise it will be None. It may be + useful to throw an exception in setup.py if this is set, to avoid e.g. + creating tarballs with a version string of "unknown". - a string, like 'PROJECTNAME-', which appears at the start of all VCS tags. - If your tags look like 'myproject-1.2.0', then you should use - tag_prefix='myproject-'. If you use unprefixed tags like '1.2.0', this - should be an empty string. +Some variants are more useful than others. Including `full-revisionid` in a +bug report should allow developers to reconstruct the exact code being tested +(or indicate the presence of local changes that should be shared with the +developers). `version` is suitable for display in an "about" box or a CLI +`--version` output: it can be easily compared against release notes and lists +of bugs fixed in various releases. -* `parentdir_prefix`: +The installer adds the following text to your `__init__.py` to place a basic +version in `YOURPROJECT.__version__`: - a string, frequently the same as tag_prefix, which appears at the start of - all unpacked tarball filenames. If your tarball unpacks into - 'myproject-1.2.0', this should be 'myproject-'. + from ._version import get_versions + __version__ = get_versions()['version'] + del get_versions -This tool provides one script, named `versioneer-installer`. That script does -one thing: write a copy of `versioneer.py` into the current directory. +## Styles + +The setup.cfg `style=` configuration controls how the VCS information is +rendered into a version string. -To versioneer-enable your project: +The default style, "pep440", produces a PEP440-compliant string, equal to the +un-prefixed tag name for actual releases, and containing an additional "local +version" section with more detail for in-between builds. For Git, this is +TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags +--dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the +tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and +that this commit is two revisions ("+2") beyond the "0.11" tag. For released +software (exactly equal to a known tag), the identifier will only contain the +stripped tag, e.g. "0.11". -* 1: Run `versioneer-installer` to copy `versioneer.py` into the top of your - source tree. +Other styles are available. See [details.md](details.md) in the Versioneer +source tree for descriptions. -* 2: add the following lines to the top of your `setup.py`, with the - configuration values you decided earlier: +## Debugging - import versioneer - versioneer.VCS = 'git' - versioneer.versionfile_source = 'src/myproject/_version.py' - versioneer.versionfile_build = 'myproject/_version.py' - versioneer.tag_prefix = '' # tags are like 1.2.0 - versioneer.parentdir_prefix = 'myproject-' # dirname like 'myproject-1.2.0' +Versioneer tries to avoid fatal errors: if something goes wrong, it will tend +to return a version of "0+unknown". To investigate the problem, run `setup.py +version`, which will run the version-lookup code in a verbose mode, and will +display the full contents of `get_versions()` (including the `error` string, +which may help identify what went wrong). -* 3: add the following arguments to the setup() call in your setup.py: +## Known Limitations - version=versioneer.get_version(), - cmdclass=versioneer.get_cmdclass(), +Some situations are known to cause problems for Versioneer. This details the +most significant ones. More can be found on Github +[issues page](https://github.com/warner/python-versioneer/issues). -* 4: now run `setup.py versioneer`, which will create `_version.py`, and will - modify your `__init__.py` (if one exists next to `_version.py`) to define - `__version__` (by calling a function from `_version.py`). It will also - modify your `MANIFEST.in` to include both `versioneer.py` and the generated - `_version.py` in sdist tarballs. +### Subprojects -* 5: commit these changes to your VCS. To make sure you won't forget, - `setup.py versioneer` will mark everything it touched for addition. +Versioneer has limited support for source trees in which `setup.py` is not in +the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are +two common reasons why `setup.py` might not be in the root: -## Post-Installation Usage +* Source trees which contain multiple subprojects, such as + [Buildbot](https://github.com/buildbot/buildbot), which contains both + "master" and "slave" subprojects, each with their own `setup.py`, + `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI + distributions (and upload multiple independently-installable tarballs). +* Source trees whose main purpose is to contain a C library, but which also + provide bindings to Python (and perhaps other langauges) in subdirectories. -Once established, all uses of your tree from a VCS checkout should get the -current version string. All generated tarballs should include an embedded -version string (so users who unpack them will not need a VCS tool installed). +Versioneer will look for `.git` in parent directories, and most operations +should get the right version string. However `pip` and `setuptools` have bugs +and implementation details which frequently cause `pip install .` from a +subproject directory to fail to find a correct version string (so it usually +defaults to `0+unknown`). -If you distribute your project through PyPI, then the release process should -boil down to two steps: +`pip install --editable .` should work correctly. `setup.py install` might +work too. -* 1: git tag 1.0 -* 2: python setup.py register sdist upload +Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in +some later version. -If you distribute it through github (i.e. users use github to generate -tarballs with `git archive`), the process is: +[Bug #38](https://github.com/warner/python-versioneer/issues/38) is tracking +this issue. The discussion in +[PR #61](https://github.com/warner/python-versioneer/pull/61) describes the +issue from the Versioneer side in more detail. +[pip PR#3176](https://github.com/pypa/pip/pull/3176) and +[pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve +pip to let Versioneer work correctly. -* 1: git tag 1.0 -* 2: git push; git push --tags +Versioneer-0.16 and earlier only looked for a `.git` directory next to the +`setup.cfg`, so subprojects were completely unsupported with those releases. -Currently, all version strings must be based upon a tag. Versioneer will -report "unknown" until your tree has at least one tag in its history. This -restriction will be fixed eventually (see issue #12). +### Editable installs with setuptools <= 18.5 -## Version-String Flavors +`setup.py develop` and `pip install --editable .` allow you to install a +project into a virtualenv once, then continue editing the source code (and +test) without re-installing after every change. -Code which uses Versioneer can learn about its version string at runtime by -importing `_version` from your main `__init__.py` file and running the -`get_versions()` function. From the "outside" (e.g. in `setup.py`), you can -import the top-level `versioneer.py` and run `get_versions()`. - -Both functions return a dictionary with different keys for different flavors -of the version string: +"Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a +convenient way to specify executable scripts that should be installed along +with the python package. -* `['version']`: condensed tag+distance+shortid+dirty identifier. For git, - this uses the output of `git describe --tags --dirty --always` but strips - the tag_prefix. For example "0.11-2-g1076c97-dirty" indicates that the tree - is like the "1076c97" commit but has uncommitted changes ("-dirty"), and - that this commit is two revisions ("-2-") beyond the "0.11" tag. For - released software (exactly equal to a known tag), the identifier will only - contain the stripped tag, e.g. "0.11". +These both work as expected when using modern setuptools. When using +setuptools-18.5 or earlier, however, certain operations will cause +`pkg_resources.DistributionNotFound` errors when running the entrypoint +script, which must be resolved by re-installing the package. This happens +when the install happens with one version, then the egg_info data is +regenerated while a different version is checked out. Many setup.py commands +cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into +a different virtualenv), so this can be surprising. -* `['full']`: detailed revision identifier. For Git, this is the full SHA1 - commit id, followed by "-dirty" if the tree contains uncommitted changes, - e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac-dirty". - -Some variants are more useful than others. Including `full` in a bug report -should allow developers to reconstruct the exact code being tested (or -indicate the presence of local changes that should be shared with the -developers). `version` is suitable for display in an "about" box or a CLI -`--version` output: it can be easily compared against release notes and lists -of bugs fixed in various releases. +[Bug #83](https://github.com/warner/python-versioneer/issues/83) describes +this one, but upgrading to a newer version of setuptools should probably +resolve it. -In the future, this will also include a -[PEP-0440](http://legacy.python.org/dev/peps/pep-0440/) -compatible flavor -(e.g. `1.2.post0.dev123`). This loses a lot of information (and has no room -for a hash-based revision id), but is safe to use in a `setup.py` -"`version=`" argument. It also enables tools like *pip* to compare version -strings and evaluate compatibility constraint declarations. +### Unicode version strings -The `setup.py versioneer` command adds the following text to your -`__init__.py` to place a basic version in `YOURPROJECT.__version__`: +While Versioneer works (and is continually tested) with both Python 2 and +Python 3, it is not entirely consistent with bytes-vs-unicode distinctions. +Newer releases probably generate unicode version strings on py2. It's not +clear that this is wrong, but it may be surprising for applications when then +write these strings to a network connection or include them in bytes-oriented +APIs like cryptographic checksums. + +[Bug #71](https://github.com/warner/python-versioneer/issues/71) investigates +this question. - from ._version import get_versions - __version__ = get_versions()['version'] - del get_versions ## Updating Versioneer To upgrade your project to a new release of Versioneer, do the following: * install the new Versioneer (`pip install -U versioneer` or equivalent) -* re-run `versioneer-installer` in your source tree to replace your copy of - `versioneer.py` -* edit `setup.py`, if necessary, to include any new configuration settings - indicated by the release notes -* re-run `setup.py versioneer` to replace `SRC/_version.py` +* edit `setup.cfg`, if necessary, to include any new configuration settings + indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details. +* re-run `versioneer install` in your source tree, to replace + `SRC/_version.py` * commit any changed files -### Upgrading from 0.10 to 0.11 - -You must add a `versioneer.VCS = "git"` to your `setup.py` before re-running -`setup.py versioneer`. This will enable the use of additional version-control -systems (SVN, etc) in the future. - -### Upgrading from 0.11 to 0.12 - -Nothing special. - ## Future Directions This tool is designed to make it easily extended to other version-control @@ -266,36 +268,130 @@ ## License -To make Versioneer easier to embed, all its code is hereby released into the -public domain. The `_version.py` that it creates is also in the public -domain. +To make Versioneer easier to embed, all its code is dedicated to the public +domain. The `_version.py` that it creates is also in the public domain. +Specifically, both are released under the Creative Commons "Public Domain +Dedication" license (CC0-1.0), as described in +https://creativecommons.org/publicdomain/zero/1.0/ . """ -import os, sys, re, subprocess, errno -from distutils.core import Command -from distutils.command.sdist import sdist as _sdist -from distutils.command.build import build as _build +from __future__ import print_function +try: + import configparser +except ImportError: + import ConfigParser as configparser +import errno +import json +import os +import re +import subprocess +import sys + + +class VersioneerConfig: + """Container for Versioneer configuration parameters.""" + + +def get_root(): + """Get the project root directory. + + We require that all commands are run from the project root, i.e. the + directory that contains setup.py, setup.cfg, and versioneer.py . + """ + root = os.path.realpath(os.path.abspath(os.getcwd())) + setup_py = os.path.join(root, "setup.py") + versioneer_py = os.path.join(root, "versioneer.py") + if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): + # allow 'python path/to/setup.py COMMAND' + root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) + setup_py = os.path.join(root, "setup.py") + versioneer_py = os.path.join(root, "versioneer.py") + if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): + err = ("Versioneer was unable to run the project root directory. " + "Versioneer requires setup.py to be executed from " + "its immediate directory (like 'python setup.py COMMAND'), " + "or in a way that lets it use sys.argv[0] to find the root " + "(like 'python path/to/setup.py COMMAND').") + raise VersioneerBadRootError(err) + try: + # Certain runtime workflows (setup.py install/develop in a setuptools + # tree) execute all dependencies in a single python process, so + # "versioneer" may be imported multiple times, and python's shared + # module-import table will cache the first one. So we can't use + # os.path.dirname(__file__), as that will find whichever + # versioneer.py was first imported, even in later projects. + me = os.path.realpath(os.path.abspath(__file__)) + me_dir = os.path.normcase(os.path.splitext(me)[0]) + vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) + if me_dir != vsr_dir: + print("Warning: build in %s is using versioneer.py from %s" + % (os.path.dirname(me), versioneer_py)) + except NameError: + pass + return root + + +def get_config_from_root(root): + """Read the project setup.cfg file to determine Versioneer config.""" + # This might raise EnvironmentError (if setup.cfg is missing), or + # configparser.NoSectionError (if it lacks a [versioneer] section), or + # configparser.NoOptionError (if it lacks "VCS="). See the docstring at + # the top of versioneer.py for instructions on writing your setup.cfg . + setup_cfg = os.path.join(root, "setup.cfg") + parser = configparser.SafeConfigParser() + with open(setup_cfg, "r") as f: + parser.readfp(f) + VCS = parser.get("versioneer", "VCS") # mandatory + + def get(parser, name): + if parser.has_option("versioneer", name): + return parser.get("versioneer", name) + return None + cfg = VersioneerConfig() + cfg.VCS = VCS + cfg.style = get(parser, "style") or "" + cfg.versionfile_source = get(parser, "versionfile_source") + cfg.versionfile_build = get(parser, "versionfile_build") + cfg.tag_prefix = get(parser, "tag_prefix") + if cfg.tag_prefix in ("''", '""'): + cfg.tag_prefix = "" + cfg.parentdir_prefix = get(parser, "parentdir_prefix") + cfg.verbose = get(parser, "verbose") + return cfg + + +class NotThisMethod(Exception): + """Exception raised if a method is not valid for the current scenario.""" -# these configuration settings will be overridden by setup.py after it -# imports us -versionfile_source = None -versionfile_build = None -tag_prefix = None -parentdir_prefix = None -VCS = None # these dictionaries contain VCS-specific tools LONG_VERSION_PY = {} +HANDLERS = {} + + +def register_vcs_handler(vcs, method): # decorator + """Decorator to mark a method as the handler for a particular VCS.""" + def decorate(f): + """Store f in HANDLERS[vcs][method].""" + if vcs not in HANDLERS: + HANDLERS[vcs] = {} + HANDLERS[vcs][method] = f + return f + return decorate -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): +def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, + env=None): + """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: + dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE, + p = subprocess.Popen([c] + args, cwd=cwd, env=env, + stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break @@ -304,21 +400,23 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): if e.errno == errno.ENOENT: continue if verbose: - print("unable to run %s" % args[0]) + print("unable to run %s" % dispcmd) print(e) - return None + return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) - return None + return None, None stdout = p.communicate()[0].strip() - if sys.version >= '3': + if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: - print("unable to run %s (error)" % args[0]) - return None - return stdout + print("unable to run %s (error)" % dispcmd) + print("stdout was %s" % stdout) + return None, p.returncode + return stdout, p.returncode + LONG_VERSION_PY['git'] = ''' # This file helps to compute a version number in source trees obtained from @@ -328,16 +426,9 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): # that just contains the computed version number. # This file is released into the public domain. Generated by -# versioneer-0.13 (https://github.com/warner/python-versioneer) +# versioneer-0.18 (https://github.com/warner/python-versioneer) -# these strings will be replaced by git during git-archive -git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" -git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" - -# these strings are filled in when 'setup.py versioneer' creates _version.py -tag_prefix = "%(TAG_PREFIX)s" -parentdir_prefix = "%(PARENTDIR_PREFIX)s" -versionfile_source = "%(VERSIONFILE_SOURCE)s" +"""Git implementation of _version.py.""" import errno import os @@ -346,13 +437,67 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): import sys -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): +def get_keywords(): + """Get the keywords needed to look up the version information.""" + # these strings will be replaced by git during git-archive. + # setup.py/versioneer.py will grep for the variable names, so they must + # each be defined on a line of their own. _version.py will just call + # get_keywords(). + git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" + git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" + git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" + keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} + return keywords + + +class VersioneerConfig: + """Container for Versioneer configuration parameters.""" + + +def get_config(): + """Create, populate and return the VersioneerConfig() object.""" + # these strings are filled in when 'setup.py versioneer' creates + # _version.py + cfg = VersioneerConfig() + cfg.VCS = "git" + cfg.style = "%(STYLE)s" + cfg.tag_prefix = "%(TAG_PREFIX)s" + cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" + cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" + cfg.verbose = False + return cfg + + +class NotThisMethod(Exception): + """Exception raised if a method is not valid for the current scenario.""" + + +LONG_VERSION_PY = {} +HANDLERS = {} + + +def register_vcs_handler(vcs, method): # decorator + """Decorator to mark a method as the handler for a particular VCS.""" + def decorate(f): + """Store f in HANDLERS[vcs][method].""" + if vcs not in HANDLERS: + HANDLERS[vcs] = {} + HANDLERS[vcs][method] = f + return f + return decorate + + +def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, + env=None): + """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: + dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE, + p = subprocess.Popen([c] + args, cwd=cwd, env=env, + stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break @@ -361,36 +506,52 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): if e.errno == errno.ENOENT: continue if verbose: - print("unable to run %%s" %% args[0]) + print("unable to run %%s" %% dispcmd) print(e) - return None + return None, None else: if verbose: print("unable to find command, tried %%s" %% (commands,)) - return None + return None, None stdout = p.communicate()[0].strip() - if sys.version >= '3': + if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: - print("unable to run %%s (error)" %% args[0]) - return None - return stdout - + print("unable to run %%s (error)" %% dispcmd) + print("stdout was %%s" %% stdout) + return None, p.returncode + return stdout, p.returncode + + +def versions_from_parentdir(parentdir_prefix, root, verbose): + """Try to determine the version from the parent directory name. + + Source tarballs conventionally unpack into a directory that includes both + the project name and a version string. We will also support searching up + two directory levels for an appropriately named parent directory + """ + rootdirs = [] + + for i in range(3): + dirname = os.path.basename(root) + if dirname.startswith(parentdir_prefix): + return {"version": dirname[len(parentdir_prefix):], + "full-revisionid": None, + "dirty": False, "error": None, "date": None} + else: + rootdirs.append(root) + root = os.path.dirname(root) # up a level -def versions_from_parentdir(parentdir_prefix, root, verbose=False): - # Source tarballs conventionally unpack into a directory that includes - # both the project name and a version string. - dirname = os.path.basename(root) - if not dirname.startswith(parentdir_prefix): - if verbose: - print("guessing rootdir is '%%s', but '%%s' doesn't start with " - "prefix '%%s'" %% (root, dirname, parentdir_prefix)) - return None - return {"version": dirname[len(parentdir_prefix):], "full": ""} + if verbose: + print("Tried directories %%s but none started with prefix %%s" %% + (str(rootdirs), parentdir_prefix)) + raise NotThisMethod("rootdir doesn't start with parentdir_prefix") +@register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): + """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from @@ -407,20 +568,35 @@ def git_get_keywords(versionfile_abs): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) + if line.strip().startswith("git_date ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["date"] = mo.group(1) f.close() except EnvironmentError: pass return keywords -def git_versions_from_keywords(keywords, tag_prefix, verbose=False): +@register_vcs_handler("git", "keywords") +def git_versions_from_keywords(keywords, tag_prefix, verbose): + """Get version information from git keywords.""" if not keywords: - return {} # keyword-finding function failed to find keywords + raise NotThisMethod("no keywords at all, weird") + date = keywords.get("date") + if date is not None: + # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant + # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 + # -like" string, which we must then edit to make compliant), because + # it's been around since git-1.5.3, and it's too difficult to + # discover which version we're using, or to work around using an + # older one. + date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") - return {} # unexpanded, so not in an unpacked git-archive tarball + raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. @@ -436,7 +612,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose=False): # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: - print("discarding '%%s', no digits" %% ",".join(refs-tags)) + print("discarding '%%s', no digits" %% ",".join(refs - tags)) if verbose: print("likely tags: %%s" %% ",".join(sorted(tags))) for ref in sorted(tags): @@ -446,75 +622,328 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose=False): if verbose: print("picking %%s" %% r) return {"version": r, - "full": keywords["full"].strip()} - # no suitable tags, so we use the full revision id + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": None, + "date": date} + # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: - print("no suitable tags, using full revision id") - return {"version": keywords["full"].strip(), - "full": keywords["full"].strip()} + print("no suitable tags, using unknown + full revision id") + return {"version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": "no suitable tags", "date": None} -def git_versions_from_vcs(tag_prefix, root, verbose=False): - # this runs 'git' from the root of the source tree. This only gets called - # if the git-archive 'subst' keywords were *not* expanded, and - # _version.py hasn't already been rewritten with a short version string, - # meaning we're inside a checked out source tree. - - if not os.path.exists(os.path.join(root, ".git")): - if verbose: - print("no .git in %%s" %% root) - return {} +@register_vcs_handler("git", "pieces_from_vcs") +def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): + """Get version from 'git describe' in the root of the source tree. + This only gets called if the git-archive 'subst' keywords were *not* + expanded, and _version.py hasn't already been rewritten with a short + version string, meaning we're inside a checked out source tree. + """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] - stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always"], - cwd=root) - if stdout is None: - return {} - if not stdout.startswith(tag_prefix): + + out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, + hide_stderr=True) + if rc != 0: if verbose: - fmt = "tag '%%s' doesn't start with prefix '%%s'" - print(fmt %% (stdout, tag_prefix)) - return {} - tag = stdout[len(tag_prefix):] - stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) - if stdout is None: - return {} - full = stdout.strip() - if tag.endswith("-dirty"): - full += "-dirty" - return {"version": tag, "full": full} - - -def get_versions(default={"version": "unknown", "full": ""}, verbose=False): + print("Directory %%s not under git control" %% root) + raise NotThisMethod("'git rev-parse --git-dir' returned error") + + # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] + # if there isn't one, this yields HEX[-dirty] (no NUM) + describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", + "--always", "--long", + "--match", "%%s*" %% tag_prefix], + cwd=root) + # --long was added in git-1.5.5 + if describe_out is None: + raise NotThisMethod("'git describe' failed") + describe_out = describe_out.strip() + full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + if full_out is None: + raise NotThisMethod("'git rev-parse' failed") + full_out = full_out.strip() + + pieces = {} + pieces["long"] = full_out + pieces["short"] = full_out[:7] # maybe improved later + pieces["error"] = None + + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] + # TAG might have hyphens. + git_describe = describe_out + + # look for -dirty suffix + dirty = git_describe.endswith("-dirty") + pieces["dirty"] = dirty + if dirty: + git_describe = git_describe[:git_describe.rindex("-dirty")] + + # now we have TAG-NUM-gHEX or HEX + + if "-" in git_describe: + # TAG-NUM-gHEX + mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + if not mo: + # unparseable. Maybe git-describe is misbehaving? + pieces["error"] = ("unable to parse git-describe output: '%%s'" + %% describe_out) + return pieces + + # tag + full_tag = mo.group(1) + if not full_tag.startswith(tag_prefix): + if verbose: + fmt = "tag '%%s' doesn't start with prefix '%%s'" + print(fmt %% (full_tag, tag_prefix)) + pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" + %% (full_tag, tag_prefix)) + return pieces + pieces["closest-tag"] = full_tag[len(tag_prefix):] + + # distance: number of commits since tag + pieces["distance"] = int(mo.group(2)) + + # commit: short hex revision ID + pieces["short"] = mo.group(3) + + else: + # HEX: no tags + pieces["closest-tag"] = None + count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], + cwd=root) + pieces["distance"] = int(count_out) # total number of commits + + # commit date: see ISO-8601 comment in git_versions_from_keywords() + date = run_command(GITS, ["show", "-s", "--format=%%ci", "HEAD"], + cwd=root)[0].strip() + pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) + + return pieces + + +def plus_or_dot(pieces): + """Return a + if we don't already have one, else return a .""" + if "+" in pieces.get("closest-tag", ""): + return "." + return "+" + + +def render_pep440(pieces): + """Build up version string, with post-release "local version identifier". + + Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you + get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty + + Exceptions: + 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += plus_or_dot(pieces) + rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], + pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_pre(pieces): + """TAG[.post.devDISTANCE] -- No -dirty. + + Exceptions: + 1: no tags. 0.post.devDISTANCE + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += ".post.dev%%d" %% pieces["distance"] + else: + # exception #1 + rendered = "0.post.dev%%d" %% pieces["distance"] + return rendered + + +def render_pep440_post(pieces): + """TAG[.postDISTANCE[.dev0]+gHEX] . + + The ".dev0" means dirty. Note that .dev0 sorts backwards + (a dirty tree will appear "older" than the corresponding clean one), + but you shouldn't be releasing software with -dirty anyways. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%%d" %% pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%%s" %% pieces["short"] + else: + # exception #1 + rendered = "0.post%%d" %% pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += "+g%%s" %% pieces["short"] + return rendered + + +def render_pep440_old(pieces): + """TAG[.postDISTANCE[.dev0]] . + + The ".dev0" means dirty. + + Eexceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%%d" %% pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + else: + # exception #1 + rendered = "0.post%%d" %% pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + return rendered + + +def render_git_describe(pieces): + """TAG[-DISTANCE-gHEX][-dirty]. + + Like 'git describe --tags --dirty --always'. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render_git_describe_long(pieces): + """TAG-DISTANCE-gHEX[-dirty]. + + Like 'git describe --tags --dirty --always -long'. + The distance/hash is unconditional. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render(pieces, style): + """Render the given version pieces into the requested style.""" + if pieces["error"]: + return {"version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"], + "date": None} + + if not style or style == "default": + style = "pep440" # the default + + if style == "pep440": + rendered = render_pep440(pieces) + elif style == "pep440-pre": + rendered = render_pep440_pre(pieces) + elif style == "pep440-post": + rendered = render_pep440_post(pieces) + elif style == "pep440-old": + rendered = render_pep440_old(pieces) + elif style == "git-describe": + rendered = render_git_describe(pieces) + elif style == "git-describe-long": + rendered = render_git_describe_long(pieces) + else: + raise ValueError("unknown style '%%s'" %% style) + + return {"version": rendered, "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], "error": None, + "date": pieces.get("date")} + + +def get_versions(): + """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. - keywords = {"refnames": git_refnames, "full": git_full} - ver = git_versions_from_keywords(keywords, tag_prefix, verbose) - if ver: - return ver + cfg = get_config() + verbose = cfg.verbose + + try: + return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, + verbose) + except NotThisMethod: + pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. - for i in range(len(versionfile_source.split('/'))): + for i in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: - return default + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, + "error": "unable to find root of source tree", + "date": None} + + try: + pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) + return render(pieces, cfg.style) + except NotThisMethod: + pass - return (git_versions_from_vcs(tag_prefix, root, verbose) - or versions_from_parentdir(parentdir_prefix, root, verbose) - or default) + try: + if cfg.parentdir_prefix: + return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) + except NotThisMethod: + pass + + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, + "error": "unable to compute version", "date": None} ''' +@register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): + """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from @@ -531,20 +960,35 @@ def git_get_keywords(versionfile_abs): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) + if line.strip().startswith("git_date ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["date"] = mo.group(1) f.close() except EnvironmentError: pass return keywords -def git_versions_from_keywords(keywords, tag_prefix, verbose=False): +@register_vcs_handler("git", "keywords") +def git_versions_from_keywords(keywords, tag_prefix, verbose): + """Get version information from git keywords.""" if not keywords: - return {} # keyword-finding function failed to find keywords + raise NotThisMethod("no keywords at all, weird") + date = keywords.get("date") + if date is not None: + # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant + # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 + # -like" string, which we must then edit to make compliant), because + # it's been around since git-1.5.3, and it's too difficult to + # discover which version we're using, or to work around using an + # older one. + date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") - return {} # unexpanded, so not in an unpacked git-archive tarball + raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. @@ -560,7 +1004,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose=False): # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: - print("discarding '%s', no digits" % ",".join(refs-tags)) + print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): @@ -570,48 +1014,115 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose=False): if verbose: print("picking %s" % r) return {"version": r, - "full": keywords["full"].strip()} - # no suitable tags, so we use the full revision id + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": None, + "date": date} + # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: - print("no suitable tags, using full revision id") - return {"version": keywords["full"].strip(), - "full": keywords["full"].strip()} - + print("no suitable tags, using unknown + full revision id") + return {"version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": "no suitable tags", "date": None} -def git_versions_from_vcs(tag_prefix, root, verbose=False): - # this runs 'git' from the root of the source tree. This only gets called - # if the git-archive 'subst' keywords were *not* expanded, and - # _version.py hasn't already been rewritten with a short version string, - # meaning we're inside a checked out source tree. - if not os.path.exists(os.path.join(root, ".git")): - if verbose: - print("no .git in %s" % root) - return {} +@register_vcs_handler("git", "pieces_from_vcs") +def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): + """Get version from 'git describe' in the root of the source tree. + This only gets called if the git-archive 'subst' keywords were *not* + expanded, and _version.py hasn't already been rewritten with a short + version string, meaning we're inside a checked out source tree. + """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] - stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always"], - cwd=root) - if stdout is None: - return {} - if not stdout.startswith(tag_prefix): + + out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, + hide_stderr=True) + if rc != 0: if verbose: - fmt = "tag '%s' doesn't start with prefix '%s'" - print(fmt % (stdout, tag_prefix)) - return {} - tag = stdout[len(tag_prefix):] - stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) - if stdout is None: - return {} - full = stdout.strip() - if tag.endswith("-dirty"): - full += "-dirty" - return {"version": tag, "full": full} + print("Directory %s not under git control" % root) + raise NotThisMethod("'git rev-parse --git-dir' returned error") + + # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] + # if there isn't one, this yields HEX[-dirty] (no NUM) + describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", + "--always", "--long", + "--match", "%s*" % tag_prefix], + cwd=root) + # --long was added in git-1.5.5 + if describe_out is None: + raise NotThisMethod("'git describe' failed") + describe_out = describe_out.strip() + full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + if full_out is None: + raise NotThisMethod("'git rev-parse' failed") + full_out = full_out.strip() + + pieces = {} + pieces["long"] = full_out + pieces["short"] = full_out[:7] # maybe improved later + pieces["error"] = None + + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] + # TAG might have hyphens. + git_describe = describe_out + + # look for -dirty suffix + dirty = git_describe.endswith("-dirty") + pieces["dirty"] = dirty + if dirty: + git_describe = git_describe[:git_describe.rindex("-dirty")] + + # now we have TAG-NUM-gHEX or HEX + + if "-" in git_describe: + # TAG-NUM-gHEX + mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + if not mo: + # unparseable. Maybe git-describe is misbehaving? + pieces["error"] = ("unable to parse git-describe output: '%s'" + % describe_out) + return pieces + + # tag + full_tag = mo.group(1) + if not full_tag.startswith(tag_prefix): + if verbose: + fmt = "tag '%s' doesn't start with prefix '%s'" + print(fmt % (full_tag, tag_prefix)) + pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" + % (full_tag, tag_prefix)) + return pieces + pieces["closest-tag"] = full_tag[len(tag_prefix):] + + # distance: number of commits since tag + pieces["distance"] = int(mo.group(2)) + + # commit: short hex revision ID + pieces["short"] = mo.group(3) + + else: + # HEX: no tags + pieces["closest-tag"] = None + count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], + cwd=root) + pieces["distance"] = int(count_out) # total number of commits + + # commit date: see ISO-8601 comment in git_versions_from_keywords() + date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], + cwd=root)[0].strip() + pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) + + return pieces def do_vcs_install(manifest_in, versionfile_source, ipy): + """Git-specific installation logic for Versioneer. + + For Git, this means creating/changing .gitattributes to mark _version.py + for export-subst keyword substitution. + """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] @@ -643,183 +1154,538 @@ def do_vcs_install(manifest_in, versionfile_source, ipy): files.append(".gitattributes") run_command(GITS, ["add", "--"] + files) -def versions_from_parentdir(parentdir_prefix, root, verbose=False): - # Source tarballs conventionally unpack into a directory that includes - # both the project name and a version string. - dirname = os.path.basename(root) - if not dirname.startswith(parentdir_prefix): - if verbose: - print("guessing rootdir is '%s', but '%s' doesn't start with " - "prefix '%s'" % (root, dirname, parentdir_prefix)) - return None - return {"version": dirname[len(parentdir_prefix):], "full": ""} + +def versions_from_parentdir(parentdir_prefix, root, verbose): + """Try to determine the version from the parent directory name. + + Source tarballs conventionally unpack into a directory that includes both + the project name and a version string. We will also support searching up + two directory levels for an appropriately named parent directory + """ + rootdirs = [] + + for i in range(3): + dirname = os.path.basename(root) + if dirname.startswith(parentdir_prefix): + return {"version": dirname[len(parentdir_prefix):], + "full-revisionid": None, + "dirty": False, "error": None, "date": None} + else: + rootdirs.append(root) + root = os.path.dirname(root) # up a level + + if verbose: + print("Tried directories %s but none started with prefix %s" % + (str(rootdirs), parentdir_prefix)) + raise NotThisMethod("rootdir doesn't start with parentdir_prefix") + SHORT_VERSION_PY = """ -# This file was generated by 'versioneer.py' (0.13) from +# This file was generated by 'versioneer.py' (0.18) from # revision-control system data, or from the parent directory name of an # unpacked source archive. Distribution tarballs contain a pre-generated copy # of this file. -version_version = '%(version)s' -version_full = '%(full)s' -def get_versions(default={}, verbose=False): - return {'version': version_version, 'full': version_full} +import json + +version_json = ''' +%s +''' # END VERSION_JSON + +def get_versions(): + return json.loads(version_json) """ -DEFAULT = {"version": "unknown", "full": "unknown"} def versions_from_file(filename): - versions = {} + """Try to determine the version from _version.py if present.""" try: with open(filename) as f: - for line in f.readlines(): - mo = re.match("version_version = '([^']+)'", line) - if mo: - versions["version"] = mo.group(1) - mo = re.match("version_full = '([^']+)'", line) - if mo: - versions["full"] = mo.group(1) + contents = f.read() except EnvironmentError: - return {} + raise NotThisMethod("unable to read _version.py") + mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", + contents, re.M | re.S) + if not mo: + mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", + contents, re.M | re.S) + if not mo: + raise NotThisMethod("no version_json in _version.py") + return json.loads(mo.group(1)) - return versions def write_to_version_file(filename, versions): + """Write the given version number to the given _version.py file.""" + os.unlink(filename) + contents = json.dumps(versions, sort_keys=True, + indent=1, separators=(",", ": ")) with open(filename, "w") as f: - f.write(SHORT_VERSION_PY % versions) + f.write(SHORT_VERSION_PY % contents) print("set %s to '%s'" % (filename, versions["version"])) -def get_root(): - try: - return os.path.dirname(os.path.abspath(__file__)) - except NameError: - return os.path.dirname(os.path.abspath(sys.argv[0])) - -def vcs_function(vcs, suffix): - return getattr(sys.modules[__name__], '%s_%s' % (vcs, suffix), None) - -def get_versions(default=DEFAULT, verbose=False): - # returns dict with two keys: 'version' and 'full' - assert versionfile_source is not None, "please set versioneer.versionfile_source" - assert tag_prefix is not None, "please set versioneer.tag_prefix" - assert parentdir_prefix is not None, "please set versioneer.parentdir_prefix" - assert VCS is not None, "please set versioneer.VCS" - - # I am in versioneer.py, which must live at the top of the source tree, - # which we use to compute the root directory. py2exe/bbfreeze/non-CPython - # don't have __file__, in which case we fall back to sys.argv[0] (which - # ought to be the setup.py script). We prefer __file__ since that's more - # robust in cases where setup.py was invoked in some weird way (e.g. pip) +def plus_or_dot(pieces): + """Return a + if we don't already have one, else return a .""" + if "+" in pieces.get("closest-tag", ""): + return "." + return "+" + + +def render_pep440(pieces): + """Build up version string, with post-release "local version identifier". + + Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you + get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty + + Exceptions: + 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += plus_or_dot(pieces) + rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0+untagged.%d.g%s" % (pieces["distance"], + pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_pre(pieces): + """TAG[.post.devDISTANCE] -- No -dirty. + + Exceptions: + 1: no tags. 0.post.devDISTANCE + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += ".post.dev%d" % pieces["distance"] + else: + # exception #1 + rendered = "0.post.dev%d" % pieces["distance"] + return rendered + + +def render_pep440_post(pieces): + """TAG[.postDISTANCE[.dev0]+gHEX] . + + The ".dev0" means dirty. Note that .dev0 sorts backwards + (a dirty tree will appear "older" than the corresponding clean one), + but you shouldn't be releasing software with -dirty anyways. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%s" % pieces["short"] + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += "+g%s" % pieces["short"] + return rendered + + +def render_pep440_old(pieces): + """TAG[.postDISTANCE[.dev0]] . + + The ".dev0" means dirty. + + Eexceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + return rendered + + +def render_git_describe(pieces): + """TAG[-DISTANCE-gHEX][-dirty]. + + Like 'git describe --tags --dirty --always'. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render_git_describe_long(pieces): + """TAG-DISTANCE-gHEX[-dirty]. + + Like 'git describe --tags --dirty --always -long'. + The distance/hash is unconditional. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render(pieces, style): + """Render the given version pieces into the requested style.""" + if pieces["error"]: + return {"version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"], + "date": None} + + if not style or style == "default": + style = "pep440" # the default + + if style == "pep440": + rendered = render_pep440(pieces) + elif style == "pep440-pre": + rendered = render_pep440_pre(pieces) + elif style == "pep440-post": + rendered = render_pep440_post(pieces) + elif style == "pep440-old": + rendered = render_pep440_old(pieces) + elif style == "git-describe": + rendered = render_git_describe(pieces) + elif style == "git-describe-long": + rendered = render_git_describe_long(pieces) + else: + raise ValueError("unknown style '%s'" % style) + + return {"version": rendered, "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], "error": None, + "date": pieces.get("date")} + + +class VersioneerBadRootError(Exception): + """The project root directory is unknown or missing key files.""" + + +def get_versions(verbose=False): + """Get the project version from whatever source is available. + + Returns dict with two keys: 'version' and 'full'. + """ + if "versioneer" in sys.modules: + # see the discussion in cmdclass.py:get_cmdclass() + del sys.modules["versioneer"] + root = get_root() - versionfile_abs = os.path.join(root, versionfile_source) + cfg = get_config_from_root(root) + + assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" + handlers = HANDLERS.get(cfg.VCS) + assert handlers, "unrecognized VCS '%s'" % cfg.VCS + verbose = verbose or cfg.verbose + assert cfg.versionfile_source is not None, \ + "please set versioneer.versionfile_source" + assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" - # extract version from first of _version.py, VCS command (e.g. 'git + versionfile_abs = os.path.join(root, cfg.versionfile_source) + + # extract version from first of: _version.py, VCS command (e.g. 'git # describe'), parentdir. This is meant to work for developers using a # source checkout, for users of a tarball created by 'setup.py sdist', # and for users of a tarball/zipball created by 'git archive' or github's # download-from-tag feature or the equivalent in other VCSes. - get_keywords_f = vcs_function(VCS, "get_keywords") - versions_from_keywords_f = vcs_function(VCS, "versions_from_keywords") - if get_keywords_f and versions_from_keywords_f: - vcs_keywords = get_keywords_f(versionfile_abs) - ver = versions_from_keywords_f(vcs_keywords, tag_prefix) - if ver: - if verbose: print("got version from expanded keyword %s" % ver) + get_keywords_f = handlers.get("get_keywords") + from_keywords_f = handlers.get("keywords") + if get_keywords_f and from_keywords_f: + try: + keywords = get_keywords_f(versionfile_abs) + ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) + if verbose: + print("got version from expanded keyword %s" % ver) return ver + except NotThisMethod: + pass - ver = versions_from_file(versionfile_abs) - if ver: - if verbose: print("got version from file %s %s" % (versionfile_abs,ver)) + try: + ver = versions_from_file(versionfile_abs) + if verbose: + print("got version from file %s %s" % (versionfile_abs, ver)) return ver + except NotThisMethod: + pass - versions_from_vcs_f = vcs_function(VCS, "versions_from_vcs") - if versions_from_vcs_f: - ver = versions_from_vcs_f(tag_prefix, root, verbose) - if ver: - if verbose: print("got version from VCS %s" % ver) + from_vcs_f = handlers.get("pieces_from_vcs") + if from_vcs_f: + try: + pieces = from_vcs_f(cfg.tag_prefix, root, verbose) + ver = render(pieces, cfg.style) + if verbose: + print("got version from VCS %s" % ver) return ver + except NotThisMethod: + pass - ver = versions_from_parentdir(parentdir_prefix, root, verbose) - if ver: - if verbose: print("got version from parentdir %s" % ver) - return ver + try: + if cfg.parentdir_prefix: + ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) + if verbose: + print("got version from parentdir %s" % ver) + return ver + except NotThisMethod: + pass - if verbose: print("got version from default %s" % default) - return default + if verbose: + print("unable to compute version") -def get_version(verbose=False): - return get_versions(verbose=verbose)["version"] + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, "error": "unable to compute version", + "date": None} -class cmd_version(Command): - description = "report generated version string" - user_options = [] - boolean_options = [] - def initialize_options(self): - pass - def finalize_options(self): - pass - def run(self): - ver = get_version(verbose=True) - print("Version is currently: %s" % ver) - - -class cmd_build(_build): - def run(self): - versions = get_versions(verbose=True) - _build.run(self) - # now locate _version.py in the new build/ directory and replace it - # with an updated value - if versionfile_build: - target_versionfile = os.path.join(self.build_lib, versionfile_build) - print("UPDATING %s" % target_versionfile) - os.unlink(target_versionfile) - with open(target_versionfile, "w") as f: - f.write(SHORT_VERSION_PY % versions) -if 'cx_Freeze' in sys.modules: # cx_freeze enabled? - from cx_Freeze.dist import build_exe as _build_exe +def get_version(): + """Get the short version string for this project.""" + return get_versions()["version"] + - class cmd_build_exe(_build_exe): +def get_cmdclass(): + """Get the custom setuptools/distutils subclasses used by Versioneer.""" + if "versioneer" in sys.modules: + del sys.modules["versioneer"] + # this fixes the "python setup.py develop" case (also 'install' and + # 'easy_install .'), in which subdependencies of the main project are + # built (using setup.py bdist_egg) in the same python process. Assume + # a main project A and a dependency B, which use different versions + # of Versioneer. A's setup.py imports A's Versioneer, leaving it in + # sys.modules by the time B's setup.py is executed, causing B to run + # with the wrong versioneer. Setuptools wraps the sub-dep builds in a + # sandbox that restores sys.modules to it's pre-build state, so the + # parent is protected against the child's "import versioneer". By + # removing ourselves from sys.modules here, before the child build + # happens, we protect the child from the parent's versioneer too. + # Also see https://github.com/warner/python-versioneer/issues/52 + + cmds = {} + + # we add "version" to both distutils and setuptools + from distutils.core import Command + + class cmd_version(Command): + description = "report generated version string" + user_options = [] + boolean_options = [] + + def initialize_options(self): + pass + + def finalize_options(self): + pass + + def run(self): + vers = get_versions(verbose=True) + print("Version: %s" % vers["version"]) + print(" full-revisionid: %s" % vers.get("full-revisionid")) + print(" dirty: %s" % vers.get("dirty")) + print(" date: %s" % vers.get("date")) + if vers["error"]: + print(" error: %s" % vers["error"]) + cmds["version"] = cmd_version + + # we override "build_py" in both distutils and setuptools + # + # most invocation pathways end up running build_py: + # distutils/build -> build_py + # distutils/install -> distutils/build ->.. + # setuptools/bdist_wheel -> distutils/install ->.. + # setuptools/bdist_egg -> distutils/install_lib -> build_py + # setuptools/install -> bdist_egg ->.. + # setuptools/develop -> ? + # pip install: + # copies source tree to a tempdir before running egg_info/etc + # if .git isn't copied too, 'git describe' will fail + # then does setup.py bdist_wheel, or sometimes setup.py install + # setup.py egg_info -> ? + + # we override different "build_py" commands for both environments + if "setuptools" in sys.modules: + from setuptools.command.build_py import build_py as _build_py + else: + from distutils.command.build_py import build_py as _build_py + + class cmd_build_py(_build_py): def run(self): - versions = get_versions(verbose=True) - target_versionfile = versionfile_source + root = get_root() + cfg = get_config_from_root(root) + versions = get_versions() + _build_py.run(self) + # now locate _version.py in the new build/ directory and replace + # it with an updated value + if cfg.versionfile_build: + target_versionfile = os.path.join(self.build_lib, + cfg.versionfile_build) + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, versions) + cmds["build_py"] = cmd_build_py + + if "cx_Freeze" in sys.modules: # cx_freeze enabled? + from cx_Freeze.dist import build_exe as _build_exe + # nczeczulin reports that py2exe won't like the pep440-style string + # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. + # setup(console=[{ + # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION + # "product_version": versioneer.get_version(), + # ... + + class cmd_build_exe(_build_exe): + def run(self): + root = get_root() + cfg = get_config_from_root(root) + versions = get_versions() + target_versionfile = cfg.versionfile_source + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, versions) + + _build_exe.run(self) + os.unlink(target_versionfile) + with open(cfg.versionfile_source, "w") as f: + LONG = LONG_VERSION_PY[cfg.VCS] + f.write(LONG % + {"DOLLAR": "$", + "STYLE": cfg.style, + "TAG_PREFIX": cfg.tag_prefix, + "PARENTDIR_PREFIX": cfg.parentdir_prefix, + "VERSIONFILE_SOURCE": cfg.versionfile_source, + }) + cmds["build_exe"] = cmd_build_exe + del cmds["build_py"] + + if 'py2exe' in sys.modules: # py2exe enabled? + try: + from py2exe.distutils_buildexe import py2exe as _py2exe # py3 + except ImportError: + from py2exe.build_exe import py2exe as _py2exe # py2 + + class cmd_py2exe(_py2exe): + def run(self): + root = get_root() + cfg = get_config_from_root(root) + versions = get_versions() + target_versionfile = cfg.versionfile_source + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, versions) + + _py2exe.run(self) + os.unlink(target_versionfile) + with open(cfg.versionfile_source, "w") as f: + LONG = LONG_VERSION_PY[cfg.VCS] + f.write(LONG % + {"DOLLAR": "$", + "STYLE": cfg.style, + "TAG_PREFIX": cfg.tag_prefix, + "PARENTDIR_PREFIX": cfg.parentdir_prefix, + "VERSIONFILE_SOURCE": cfg.versionfile_source, + }) + cmds["py2exe"] = cmd_py2exe + + # we override different "sdist" commands for both environments + if "setuptools" in sys.modules: + from setuptools.command.sdist import sdist as _sdist + else: + from distutils.command.sdist import sdist as _sdist + + class cmd_sdist(_sdist): + def run(self): + versions = get_versions() + self._versioneer_generated_versions = versions + # unless we update this, the command will keep using the old + # version + self.distribution.metadata.version = versions["version"] + return _sdist.run(self) + + def make_release_tree(self, base_dir, files): + root = get_root() + cfg = get_config_from_root(root) + _sdist.make_release_tree(self, base_dir, files) + # now locate _version.py in the new base_dir directory + # (remembering that it may be a hardlink) and replace it with an + # updated value + target_versionfile = os.path.join(base_dir, cfg.versionfile_source) print("UPDATING %s" % target_versionfile) - os.unlink(target_versionfile) - with open(target_versionfile, "w") as f: - f.write(SHORT_VERSION_PY % versions) - - _build_exe.run(self) - os.unlink(target_versionfile) - with open(versionfile_source, "w") as f: - assert VCS is not None, "please set versioneer.VCS" - LONG = LONG_VERSION_PY[VCS] - f.write(LONG % {"DOLLAR": "$", - "TAG_PREFIX": tag_prefix, - "PARENTDIR_PREFIX": parentdir_prefix, - "VERSIONFILE_SOURCE": versionfile_source, - }) - -class cmd_sdist(_sdist): - def run(self): - versions = get_versions(verbose=True) - self._versioneer_generated_versions = versions - # unless we update this, the command will keep using the old version - self.distribution.metadata.version = versions["version"] - return _sdist.run(self) - - def make_release_tree(self, base_dir, files): - _sdist.make_release_tree(self, base_dir, files) - # now locate _version.py in the new base_dir directory (remembering - # that it may be a hardlink) and replace it with an updated value - target_versionfile = os.path.join(base_dir, versionfile_source) - print("UPDATING %s" % target_versionfile) - os.unlink(target_versionfile) - with open(target_versionfile, "w") as f: - f.write(SHORT_VERSION_PY % self._versioneer_generated_versions) + write_to_version_file(target_versionfile, + self._versioneer_generated_versions) + cmds["sdist"] = cmd_sdist + + return cmds + + +CONFIG_ERROR = """ +setup.cfg is missing the necessary Versioneer configuration. You need +a section like: + + [versioneer] + VCS = git + style = pep440 + versionfile_source = src/myproject/_version.py + versionfile_build = myproject/_version.py + tag_prefix = + parentdir_prefix = myproject- + +You will also need to edit your setup.py to use the results: + + import versioneer + setup(version=versioneer.get_version(), + cmdclass=versioneer.get_cmdclass(), ...) + +Please read the docstring in ./versioneer.py for configuration instructions, +edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. +""" + +SAMPLE_CONFIG = """ +# See the docstring in versioneer.py for instructions. Note that you must +# re-run 'versioneer.py setup' after changing this section, and commit the +# resulting files. + +[versioneer] +#VCS = git +#style = pep440 +#versionfile_source = +#versionfile_build = +#tag_prefix = +#parentdir_prefix = + +""" INIT_PY_SNIPPET = """ from ._version import get_versions @@ -827,87 +1693,130 @@ def make_release_tree(self, base_dir, files): del get_versions """ -class cmd_update_files(Command): - description = "install/upgrade Versioneer files: __init__.py SRC/_version.py" - user_options = [] - boolean_options = [] - def initialize_options(self): - pass - def finalize_options(self): - pass - def run(self): - print(" creating %s" % versionfile_source) - with open(versionfile_source, "w") as f: - assert VCS is not None, "please set versioneer.VCS" - LONG = LONG_VERSION_PY[VCS] - f.write(LONG % {"DOLLAR": "$", - "TAG_PREFIX": tag_prefix, - "PARENTDIR_PREFIX": parentdir_prefix, - "VERSIONFILE_SOURCE": versionfile_source, - }) - - ipy = os.path.join(os.path.dirname(versionfile_source), "__init__.py") - if os.path.exists(ipy): - try: - with open(ipy, "r") as f: - old = f.read() - except EnvironmentError: - old = "" - if INIT_PY_SNIPPET not in old: - print(" appending to %s" % ipy) - with open(ipy, "a") as f: - f.write(INIT_PY_SNIPPET) - else: - print(" %s unmodified" % ipy) - else: - print(" %s doesn't exist, ok" % ipy) - ipy = None - - # Make sure both the top-level "versioneer.py" and versionfile_source - # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so - # they'll be copied into source distributions. Pip won't be able to - # install the package without this. - manifest_in = os.path.join(get_root(), "MANIFEST.in") - simple_includes = set() + +def do_setup(): + """Main VCS-independent setup function for installing Versioneer.""" + root = get_root() + try: + cfg = get_config_from_root(root) + except (EnvironmentError, configparser.NoSectionError, + configparser.NoOptionError) as e: + if isinstance(e, (EnvironmentError, configparser.NoSectionError)): + print("Adding sample versioneer config to setup.cfg", + file=sys.stderr) + with open(os.path.join(root, "setup.cfg"), "a") as f: + f.write(SAMPLE_CONFIG) + print(CONFIG_ERROR, file=sys.stderr) + return 1 + + print(" creating %s" % cfg.versionfile_source) + with open(cfg.versionfile_source, "w") as f: + LONG = LONG_VERSION_PY[cfg.VCS] + f.write(LONG % {"DOLLAR": "$", + "STYLE": cfg.style, + "TAG_PREFIX": cfg.tag_prefix, + "PARENTDIR_PREFIX": cfg.parentdir_prefix, + "VERSIONFILE_SOURCE": cfg.versionfile_source, + }) + + ipy = os.path.join(os.path.dirname(cfg.versionfile_source), + "__init__.py") + if os.path.exists(ipy): try: - with open(manifest_in, "r") as f: - for line in f: - if line.startswith("include "): - for include in line.split()[1:]: - simple_includes.add(include) + with open(ipy, "r") as f: + old = f.read() except EnvironmentError: - pass - # That doesn't cover everything MANIFEST.in can do - # (http://docs.python.org/2/distutils/sourcedist.html#commands), so - # it might give some false negatives. Appending redundant 'include' - # lines is safe, though. - if "versioneer.py" not in simple_includes: - print(" appending 'versioneer.py' to MANIFEST.in") - with open(manifest_in, "a") as f: - f.write("include versioneer.py\n") + old = "" + if INIT_PY_SNIPPET not in old: + print(" appending to %s" % ipy) + with open(ipy, "a") as f: + f.write(INIT_PY_SNIPPET) else: - print(" 'versioneer.py' already in MANIFEST.in") - if versionfile_source not in simple_includes: - print(" appending versionfile_source ('%s') to MANIFEST.in" % - versionfile_source) - with open(manifest_in, "a") as f: - f.write("include %s\n" % versionfile_source) - else: - print(" versionfile_source already in MANIFEST.in") + print(" %s unmodified" % ipy) + else: + print(" %s doesn't exist, ok" % ipy) + ipy = None + + # Make sure both the top-level "versioneer.py" and versionfile_source + # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so + # they'll be copied into source distributions. Pip won't be able to + # install the package without this. + manifest_in = os.path.join(root, "MANIFEST.in") + simple_includes = set() + try: + with open(manifest_in, "r") as f: + for line in f: + if line.startswith("include "): + for include in line.split()[1:]: + simple_includes.add(include) + except EnvironmentError: + pass + # That doesn't cover everything MANIFEST.in can do + # (http://docs.python.org/2/distutils/sourcedist.html#commands), so + # it might give some false negatives. Appending redundant 'include' + # lines is safe, though. + if "versioneer.py" not in simple_includes: + print(" appending 'versioneer.py' to MANIFEST.in") + with open(manifest_in, "a") as f: + f.write("include versioneer.py\n") + else: + print(" 'versioneer.py' already in MANIFEST.in") + if cfg.versionfile_source not in simple_includes: + print(" appending versionfile_source ('%s') to MANIFEST.in" % + cfg.versionfile_source) + with open(manifest_in, "a") as f: + f.write("include %s\n" % cfg.versionfile_source) + else: + print(" versionfile_source already in MANIFEST.in") - # Make VCS-specific changes. For git, this means creating/changing - # .gitattributes to mark _version.py for export-time keyword - # substitution. - do_vcs_install(manifest_in, versionfile_source, ipy) + # Make VCS-specific changes. For git, this means creating/changing + # .gitattributes to mark _version.py for export-subst keyword + # substitution. + do_vcs_install(manifest_in, cfg.versionfile_source, ipy) + return 0 -def get_cmdclass(): - cmds = {'version': cmd_version, - 'versioneer': cmd_update_files, - 'build': cmd_build, - 'sdist': cmd_sdist, - } - if 'cx_Freeze' in sys.modules: # cx_freeze enabled? - cmds['build_exe'] = cmd_build_exe - del cmds['build'] - return cmds +def scan_setup_py(): + """Validate the contents of setup.py against Versioneer's expectations.""" + found = set() + setters = False + errors = 0 + with open("setup.py", "r") as f: + for line in f.readlines(): + if "import versioneer" in line: + found.add("import") + if "versioneer.get_cmdclass()" in line: + found.add("cmdclass") + if "versioneer.get_version()" in line: + found.add("get_version") + if "versioneer.VCS" in line: + setters = True + if "versioneer.versionfile_source" in line: + setters = True + if len(found) != 3: + print("") + print("Your setup.py appears to be missing some important items") + print("(but I might be wrong). Please make sure it has something") + print("roughly like the following:") + print("") + print(" import versioneer") + print(" setup( version=versioneer.get_version(),") + print(" cmdclass=versioneer.get_cmdclass(), ...)") + print("") + errors += 1 + if setters: + print("You should remove lines like 'versioneer.VCS = ' and") + print("'versioneer.versionfile_source = ' . This configuration") + print("now lives in setup.cfg, and should be removed from setup.py") + print("") + errors += 1 + return errors + + +if __name__ == "__main__": + cmd = sys.argv[1] + if cmd == "setup": + errors = do_setup() + errors += scan_setup_py() + if errors: + sys.exit(1)