├── rtctools_diagnostics
├── utils
│ ├── __init__.py
│ └── casadi_to_lp.py
├── __init__.py
├── export_results.py
├── get_linear_problem.py
└── _version.py
├── .gitattributes
├── examples
└── export_each_priority
│ ├── input
│ ├── initial_state.csv
│ └── timeseries_import.csv
│ ├── output
│ ├── timeseries_export.csv
│ ├── priority_001
│ │ └── timeseries_export.csv
│ ├── priority_002
│ │ └── timeseries_export.csv
│ └── priority_003
│ │ └── timeseries_export.csv
│ ├── model
│ └── Example.mo
│ └── src
│ └── example.py
├── tox.ini
├── .gitignore
├── setup.cfg
├── setup.py
├── README.md
├── .github
└── workflows
│ └── ci.yml
├── tests
└── test_examples.py
├── COPYING.LESSER
├── COPYING
└── versioneer.py
/rtctools_diagnostics/utils/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | rtctools_diagnostics/_version.py export-subst
2 |
--------------------------------------------------------------------------------
/examples/export_each_priority/input/initial_state.csv:
--------------------------------------------------------------------------------
1 | storage.V,Q_pump,Q_orifice
2 | 400000.0,0.0,0.0
3 |
--------------------------------------------------------------------------------
/rtctools_diagnostics/__init__.py:
--------------------------------------------------------------------------------
1 | from . import _version
2 |
3 | __version__ = _version.get_versions()["version"]
4 |
--------------------------------------------------------------------------------
/tox.ini:
--------------------------------------------------------------------------------
1 | [tox]
2 | envlist =
3 | {py}{39}
4 |
5 | [testenv]
6 | deps = pytest
7 | extras = all
8 | install_command = pip install rtc-tools {packages}
9 | commands =
10 | py{39}: pytest {posargs} tests
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__
3 | *.py[cod]
4 |
5 | # C extensions
6 | *.c
7 | *.so
8 |
9 | # Distribution & Packaging
10 | .eggs
11 | build
12 | dist
13 |
14 | # Testing & Coverage
15 | .pytest_cache
16 | .tox
17 | .coverage
18 | *.egg-info
19 |
20 | # Model caches
21 | *.pymoca_cache
22 |
23 | # Editors
24 | .idea
25 | .ipynb_checkpoints
26 | .vscode
27 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [metadata]
2 | license_file = COPYING.LESSER
3 |
4 | # See the docstring in versioneer.py for instructions. Note that you must
5 | # re-run 'versioneer.py setup' after changing this section, and commit the
6 | # resulting files.
7 |
8 | [versioneer]
9 | VCS = git
10 | style = pep440
11 | versionfile_source = rtctools_diagnostics/_version.py
12 | parentdir_prefix = rtctools_diagnostics-
13 |
14 | [flake8]
15 | max-line-length = 120
--------------------------------------------------------------------------------
/examples/export_each_priority/input/timeseries_import.csv:
--------------------------------------------------------------------------------
1 | UTC,H_sea,Q_in
2 | 2013-05-19 22:00:00,0.0,5.0
3 | 2013-05-19 23:00:00,0.1,5.0
4 | 2013-05-20 00:00:00,0.2,5.0
5 | 2013-05-20 01:00:00,0.3,5.0
6 | 2013-05-20 02:00:00,0.4,5.0
7 | 2013-05-20 03:00:00,0.5,5.0
8 | 2013-05-20 04:00:00,0.6,5.0
9 | 2013-05-20 05:00:00,0.7,5.0
10 | 2013-05-20 06:00:00,0.8,5.0
11 | 2013-05-20 07:00:00,0.9,5.0
12 | 2013-05-20 08:00:00,1.0,5.0
13 | 2013-05-20 09:00:00,0.9,5.0
14 | 2013-05-20 10:00:00,0.8,5.0
15 | 2013-05-20 11:00:00,0.7,5.0
16 | 2013-05-20 12:00:00,0.6,5.0
17 | 2013-05-20 13:00:00,0.5,5.0
18 | 2013-05-20 14:00:00,0.4,5.0
19 | 2013-05-20 15:00:00,0.3,5.0
20 | 2013-05-20 16:00:00,0.2,5.0
21 | 2013-05-20 17:00:00,0.1,5.0
22 | 2013-05-20 18:00:00,0.0,5.0
23 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | """Toolbox for diagnostics for RTC-Tools
2 |
3 | This toolbox includes several utilities to analyze the results of an RTC-Tools optimization run.
4 | """
5 | from setuptools import setup, find_packages
6 | import versioneer
7 |
8 | DOCLINES = __doc__.split("\n")
9 |
10 |
11 | setup(
12 | name="rtc-tools-diagnostics",
13 | version=versioneer.get_version(),
14 | maintainer="Deltares",
15 | author="Deltares",
16 | packages=find_packages("."),
17 | description=DOCLINES[0],
18 | long_description="\n".join(DOCLINES[2:]),
19 | platforms=["Windows", "Linux", "Mac OS-X", "Unix"],
20 | install_requires=["rtc-tools >= 2.5.0", "tabulate", "casadi != 3.6.6", "numpy", "pandas"],
21 | tests_require=["pytest", "pytest-runner"],
22 | python_requires=">=3.5",
23 | cmdclass=versioneer.get_cmdclass(),
24 | )
25 |
--------------------------------------------------------------------------------
/examples/export_each_priority/output/timeseries_export.csv:
--------------------------------------------------------------------------------
1 | time,Q_orifice,Q_pump,is_downhill,sea_level,storage_level
2 | 2013-05-19 22:00:00,0.000000,0.000000,1.000000,0.000000,0.400000
3 | 2013-05-19 23:00:00,0.000000,0.000000,1.000000,0.100000,0.418000
4 | 2013-05-20 00:00:00,1.669399,0.000000,1.000000,0.200000,0.429990
5 | 2013-05-20 01:00:00,3.889316,0.000000,1.000000,0.300000,0.433989
6 | 2013-05-20 02:00:00,2.125113,1.204408,1.000000,0.400000,0.440002
7 | 2013-05-20 03:00:00,0.000000,5.040501,0.000000,0.500000,0.439857
8 | 2013-05-20 04:00:00,0.000000,5.422989,0.000000,0.600000,0.438334
9 | 2013-05-20 05:00:00,0.000000,5.426251,0.000000,0.700000,0.436799
10 | 2013-05-20 06:00:00,0.000000,5.341813,0.000000,0.800000,0.435569
11 | 2013-05-20 07:00:00,0.000000,5.264897,0.000000,0.900000,0.434615
12 | 2013-05-20 08:00:00,0.000000,5.222827,0.000000,1.000000,0.433813
13 | 2013-05-20 09:00:00,0.000000,5.202957,0.000000,0.900000,0.433082
14 | 2013-05-20 10:00:00,0.000000,5.156391,0.000000,0.800000,0.432519
15 | 2013-05-20 11:00:00,0.000000,4.993552,0.000000,0.700000,0.432542
16 | 2013-05-20 12:00:00,0.000000,4.575792,0.000000,0.600000,0.434070
17 | 2013-05-20 13:00:00,0.000000,3.753908,0.000000,0.500000,0.438556
18 | 2013-05-20 14:00:00,2.125107,2.473083,1.000000,0.400000,0.440002
19 | 2013-05-20 15:00:00,3.975632,1.024427,1.000000,0.300000,0.440002
20 | 2013-05-20 16:00:00,5.105256,0.000000,1.000000,0.200000,0.439623
21 | 2013-05-20 17:00:00,5.544215,0.000000,1.000000,0.100000,0.437664
22 | 2013-05-20 18:00:00,5.286805,0.000000,1.000000,0.000000,0.436631
23 |
--------------------------------------------------------------------------------
/examples/export_each_priority/output/priority_001/timeseries_export.csv:
--------------------------------------------------------------------------------
1 | time,Q_orifice,Q_pump,is_downhill,sea_level,storage_level
2 | 2013-05-19 22:00:00,0.000000,0.000000,1.000000,0.000000,0.400000
3 | 2013-05-19 23:00:00,0.000000,0.000000,1.000000,0.100000,0.418000
4 | 2013-05-20 00:00:00,0.613550,0.325402,1.000000,0.200000,0.432620
5 | 2013-05-20 01:00:00,2.164193,2.163171,1.000000,0.300000,0.435041
6 | 2013-05-20 02:00:00,1.342531,3.531629,1.000000,0.400000,0.435494
7 | 2013-05-20 03:00:00,0.000000,5.030138,0.000000,0.500000,0.435386
8 | 2013-05-20 04:00:00,0.000000,4.996147,0.000000,0.600000,0.435400
9 | 2013-05-20 05:00:00,0.000000,5.001876,0.000000,0.700000,0.435393
10 | 2013-05-20 06:00:00,0.000000,5.004186,0.000000,0.800000,0.435378
11 | 2013-05-20 07:00:00,0.000000,5.004915,0.000000,0.900000,0.435360
12 | 2013-05-20 08:00:00,0.000000,5.005852,0.000000,1.000000,0.435339
13 | 2013-05-20 09:00:00,0.000000,5.006691,0.000000,0.900000,0.435315
14 | 2013-05-20 10:00:00,0.000000,5.006500,0.000000,0.800000,0.435292
15 | 2013-05-20 11:00:00,0.000000,5.004270,0.000000,0.700000,0.435276
16 | 2013-05-20 12:00:00,0.000000,4.987953,0.000000,0.600000,0.435320
17 | 2013-05-20 13:00:00,0.000000,4.870236,0.000000,0.500000,0.435787
18 | 2013-05-20 14:00:00,1.367578,3.527208,1.000000,0.400000,0.436166
19 | 2013-05-20 15:00:00,2.339319,2.813997,1.000000,0.300000,0.435614
20 | 2013-05-20 16:00:00,2.661535,2.389947,1.000000,0.200000,0.435428
21 | 2013-05-20 17:00:00,2.809958,2.221038,1.000000,0.100000,0.435317
22 | 2013-05-20 18:00:00,2.949955,2.210643,1.000000,0.000000,0.434738
23 |
--------------------------------------------------------------------------------
/examples/export_each_priority/output/priority_002/timeseries_export.csv:
--------------------------------------------------------------------------------
1 | time,Q_orifice,Q_pump,is_downhill,sea_level,storage_level
2 | 2013-05-19 22:00:00,0.000000,0.000000,1.000000,0.000000,0.400000
3 | 2013-05-19 23:00:00,0.000000,0.000000,1.000000,0.100000,0.418000
4 | 2013-05-20 00:00:00,1.669399,0.000000,1.000000,0.200000,0.429990
5 | 2013-05-20 01:00:00,3.889316,0.000000,1.000000,0.300000,0.433989
6 | 2013-05-20 02:00:00,2.125113,1.204408,1.000000,0.400000,0.440002
7 | 2013-05-20 03:00:00,0.000000,6.044425,0.000000,0.500000,0.436242
8 | 2013-05-20 04:00:00,0.000000,5.316950,0.000000,0.600000,0.435101
9 | 2013-05-20 05:00:00,0.000000,5.061337,0.000000,0.700000,0.434881
10 | 2013-05-20 06:00:00,0.000000,5.008735,0.000000,0.800000,0.434849
11 | 2013-05-20 07:00:00,0.000000,4.999888,0.000000,0.900000,0.434850
12 | 2013-05-20 08:00:00,0.000000,4.999072,0.000000,1.000000,0.434853
13 | 2013-05-20 09:00:00,0.000000,5.000901,0.000000,0.900000,0.434850
14 | 2013-05-20 10:00:00,0.000000,5.000362,0.000000,0.800000,0.434848
15 | 2013-05-20 11:00:00,0.000000,4.992790,0.000000,0.700000,0.434874
16 | 2013-05-20 12:00:00,0.000000,4.944605,0.000000,0.600000,0.435074
17 | 2013-05-20 13:00:00,0.000000,4.624344,0.000000,0.500000,0.436426
18 | 2013-05-20 14:00:00,2.125107,1.881552,1.000000,0.400000,0.440002
19 | 2013-05-20 15:00:00,3.975632,1.024427,1.000000,0.300000,0.440002
20 | 2013-05-20 16:00:00,5.105242,0.000000,1.000000,0.200000,0.439623
21 | 2013-05-20 17:00:00,5.544215,0.000000,1.000000,0.100000,0.437664
22 | 2013-05-20 18:00:00,5.286829,0.000000,1.000000,0.000000,0.436631
23 |
--------------------------------------------------------------------------------
/examples/export_each_priority/output/priority_003/timeseries_export.csv:
--------------------------------------------------------------------------------
1 | time,Q_orifice,Q_pump,is_downhill,sea_level,storage_level
2 | 2013-05-19 22:00:00,0.000000,0.000000,1.000000,0.000000,0.400000
3 | 2013-05-19 23:00:00,0.000000,0.000000,1.000000,0.100000,0.418000
4 | 2013-05-20 00:00:00,1.669399,0.000000,1.000000,0.200000,0.429990
5 | 2013-05-20 01:00:00,3.889316,0.000000,1.000000,0.300000,0.433989
6 | 2013-05-20 02:00:00,2.125113,1.204408,1.000000,0.400000,0.440002
7 | 2013-05-20 03:00:00,0.000000,5.040501,0.000000,0.500000,0.439857
8 | 2013-05-20 04:00:00,0.000000,5.422989,0.000000,0.600000,0.438334
9 | 2013-05-20 05:00:00,0.000000,5.426251,0.000000,0.700000,0.436799
10 | 2013-05-20 06:00:00,0.000000,5.341813,0.000000,0.800000,0.435569
11 | 2013-05-20 07:00:00,0.000000,5.264897,0.000000,0.900000,0.434615
12 | 2013-05-20 08:00:00,0.000000,5.222827,0.000000,1.000000,0.433813
13 | 2013-05-20 09:00:00,0.000000,5.202957,0.000000,0.900000,0.433082
14 | 2013-05-20 10:00:00,0.000000,5.156391,0.000000,0.800000,0.432519
15 | 2013-05-20 11:00:00,0.000000,4.993552,0.000000,0.700000,0.432542
16 | 2013-05-20 12:00:00,0.000000,4.575792,0.000000,0.600000,0.434070
17 | 2013-05-20 13:00:00,0.000000,3.753908,0.000000,0.500000,0.438556
18 | 2013-05-20 14:00:00,2.125107,2.473083,1.000000,0.400000,0.440002
19 | 2013-05-20 15:00:00,3.975632,1.024427,1.000000,0.300000,0.440002
20 | 2013-05-20 16:00:00,5.105256,0.000000,1.000000,0.200000,0.439623
21 | 2013-05-20 17:00:00,5.544215,0.000000,1.000000,0.100000,0.437664
22 | 2013-05-20 18:00:00,5.286805,0.000000,1.000000,0.000000,0.436631
23 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # rtc-tools-diagnostics
2 |
3 | This is rtc-tools-diagnostics, a toolbox to analyse results from [rtc-tools](https://github.com/Deltares/rtc-tools).
4 |
5 | ## Install
6 |
7 | ```bash
8 | pip install rtc-tools-diagnostics
9 | ```
10 | ## Features
11 | ### Export results after each priority
12 | The `ExportResultsEachPriorityMixin` enables RTC-Tools to save the timeseries export after solving each priority. In addition to the usual final timeseries_export file (.csv or .xml) found in the output folder, a separate folder
13 | will be created for each priority. Each priority folder will contain the results for the problem considering all goals up to and including that priority. To use this functionality, import the mixin with the following code:
14 | ```python
15 | from rtctools_diagnostics.export_results import ExportResultsEachPriorityMixin
16 | ```
17 | and add the `ExportResultsEachPriorityMixin` to you optimization problem class, before the other rtc-tools classes and mixins included in optimization problem class.
18 |
19 | You can disable this functionality by setting the class variable `export_results_each_priority` to `False` from your optimization problem class.
20 |
21 | ### Get optimization problem formulation and active constraints
22 | By using the `GetLinearProblemMixin`, you can generate a file that indicates the active constraints and bounds for each priority. To utilize this functionality, import the mixin as follows:
23 | ```python
24 | from rtctools_diagnostics.get_linear_problem import GetLinearProblemMixin
25 | ```
26 | Then, add the `GetLinearProblemMixin` to your optimization problem class, before the other rtc-tools classes and mixins included in optimization problem class. After running the model, a file named `active_constraints.md` will be available in your output folder.
27 |
28 | #### Notes
29 | - MIP and non-linear problems are not supported (yet) by `GetLinearProblemMixin`.
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 | tags:
8 | - '*'
9 | pull_request:
10 | branches:
11 | - main
12 |
13 | jobs:
14 | style:
15 | runs-on: ubuntu-latest
16 | steps:
17 | - name: Checkout code
18 | uses: actions/checkout@v3
19 | - name: Set up Python
20 | uses: actions/setup-python@v4
21 | with:
22 | python-version: 3.9
23 | - name: Install flake8
24 | run: pip install --upgrade flake8==5
25 | - name: Run flake8
26 | run: flake8 --exclude=_version.py rtctools_diagnostics --max-line-length 120
27 |
28 | build:
29 | runs-on: ubuntu-latest
30 | steps:
31 | - name: Checkout code
32 | uses: actions/checkout@v3
33 | - name: Set up Python
34 | uses: actions/setup-python@v4
35 | with:
36 | python-version: 3.9
37 | - name: Install wheel
38 | run: pip install wheel
39 | - name: Build package
40 | run: python setup.py sdist bdist_wheel
41 | - name: Upload artifact
42 | uses: actions/upload-artifact@v4
43 | with:
44 | name: dist
45 | path: dist/
46 |
47 | test:
48 | runs-on: ubuntu-latest
49 | steps:
50 | - name: Checkout code
51 | uses: actions/checkout@v3
52 | - name: Set up Python
53 | uses: actions/setup-python@v4
54 | with:
55 | python-version: 3.9
56 | - name: Install tox
57 | run: pip install tox
58 | - name: Run tests
59 | run: tox -vv
60 |
61 | deploy:
62 | runs-on: ubuntu-latest
63 | needs: build
64 | if: startsWith(github.ref, 'refs/tags/')
65 | steps:
66 | - name: Checkout code
67 | uses: actions/checkout@v3
68 | - name: Set up Python
69 | uses: actions/setup-python@v4
70 | with:
71 | python-version: 3.9
72 | - name: Install twine
73 | run: pip install -U twine
74 | - name: Download dist artifact
75 | uses: actions/download-artifact@v4
76 | with:
77 | name: dist
78 | path: dist/
79 | - name: Upload to PyPI
80 | env:
81 | TWINE_USERNAME: ${{ secrets.PYPI_USER }}
82 | TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }}
83 | run: twine upload dist/*
84 |
85 |
--------------------------------------------------------------------------------
/tests/test_examples.py:
--------------------------------------------------------------------------------
1 | import fnmatch
2 | import inspect
3 | import os
4 | import subprocess
5 | import sys
6 | from unittest import TestCase
7 | import unittest
8 |
9 |
10 | class ExamplesCollection:
11 | def __init__(self):
12 | self.errors_detected = {}
13 | for example_folder in self.examples_folders:
14 | for example in self.subexamples(example_folder):
15 | # initialize with failures
16 | example_path = os.path.join(self.examples_path, example_folder, "src", example)
17 | self.errors_detected[example_path] = True
18 |
19 | def local_function(self):
20 | pass
21 |
22 | @property
23 | def examples_path(self):
24 | return os.path.join(
25 | os.path.dirname(os.path.abspath(inspect.getsourcefile(self.local_function))),
26 | "..",
27 | "examples",
28 | )
29 |
30 | @property
31 | def examples_folders(self):
32 | return [f.name for f in os.scandir(self.examples_path) if f.is_dir()]
33 |
34 | def subexamples(self, example_folder):
35 | example_folder = os.path.join(self.examples_path, example_folder, "src")
36 | return [f for f in os.listdir(example_folder) if fnmatch.fnmatch(f, "*example*.py")]
37 |
38 |
39 | class TestExamples(TestCase):
40 | """
41 | src subfolders of examples in the example folder are searched for files
42 | containing 'example' in their filename.
43 | """
44 |
45 | def run_examples(self, ec):
46 | env = sys.executable
47 | for example_path in ec.errors_detected.keys():
48 | try:
49 | subprocess.check_output([env, example_path])
50 | except Exception:
51 | ec.errors_detected[example_path] = True
52 | else:
53 | ec.errors_detected[example_path] = False
54 |
55 | def test_examples(self):
56 | ec = ExamplesCollection()
57 |
58 | self.run_examples(ec)
59 |
60 | for example_path, error_detected in ec.errors_detected.items():
61 | path = os.path.normpath(example_path)
62 | file = os.path.basename(path)
63 | folder = os.path.relpath(example_path, ec.examples_path).split(os.sep)[0]
64 | if error_detected:
65 | print("An error occured while running '{}' in example folder '{}'.".format(file, folder))
66 | else:
67 | print("No errors occured while running '{}' in example folder '{}'.".format(file, folder))
68 |
69 | self.assertFalse(any(ec.errors_detected.values()))
70 |
71 |
72 | if __name__ == "__main__":
73 | unittest.main()
74 |
--------------------------------------------------------------------------------
/examples/export_each_priority/model/Example.mo:
--------------------------------------------------------------------------------
1 | model Example
2 | // Declare Model Elements
3 | Deltares.ChannelFlow.Hydraulic.Storage.Linear storage(A=1.0e6, H_b=0.0, HQ.H(min=0.0, max=0.5)) annotation(Placement(visible = true, transformation(origin = {32.022, -0}, extent = {{-10, -10}, {10, 10}}, rotation = -270)));
4 | Deltares.ChannelFlow.Hydraulic.BoundaryConditions.Discharge discharge annotation(Placement(visible = true, transformation(origin = {60, -0}, extent = {{10, -10}, {-10, 10}}, rotation = 270)));
5 | Deltares.ChannelFlow.Hydraulic.BoundaryConditions.Level level annotation(Placement(visible = true, transformation(origin = {-52.7, 0}, extent = {{-10, -10}, {10, 10}}, rotation = -270)));
6 | Deltares.ChannelFlow.Hydraulic.Structures.Pump pump annotation(Placement(visible = true, transformation(origin = {0, -20}, extent = {{10, -10}, {-10, 10}}, rotation = 0)));
7 | Deltares.ChannelFlow.Hydraulic.Structures.Pump orifice annotation(Placement(visible = true, transformation(origin = {0, 20}, extent = {{10, -10}, {-10, 10}}, rotation = 0)));
8 |
9 | // Define Input/Output Variables and set them equal to model variables
10 | input Modelica.SIunits.VolumeFlowRate Q_pump(fixed=false, min=0.0, max=7.0) = pump.Q;
11 | input Boolean is_downhill;
12 | input Modelica.SIunits.VolumeFlowRate Q_in(fixed=true) = discharge.Q;
13 | input Modelica.SIunits.Position H_sea(fixed=true) = level.H;
14 | input Modelica.SIunits.VolumeFlowRate Q_orifice(fixed=false, min=0.0, max=10.0) = orifice.Q;
15 | output Modelica.SIunits.Position storage_level = storage.HQ.H;
16 | output Modelica.SIunits.Position sea_level = level.H;
17 | equation
18 | // Connect Model Elements
19 | connect(orifice.HQDown, level.HQ) annotation(Line(visible = true, origin = {-33.025, 10}, points = {{25.025, 10}, {-6.675, 10}, {-6.675, -10}, {-11.675, -10}}, color = {0, 0, 255}));
20 | connect(storage.HQ, orifice.HQUp) annotation(Line(visible = true, origin = {43.737, 48.702}, points = {{-3.715, -48.702}, {-3.737, -28.702}, {-35.737, -28.702}}, color = {0, 0, 255}));
21 | connect(storage.HQ, pump.HQUp) annotation(Line(visible = true, origin = {4.669, -31.115}, points = {{35.353, 31.115}, {35.331, 11.115}, {3.331, 11.115}}, color = {0, 0, 255}));
22 | connect(discharge.HQ, storage.HQ) annotation(Line(visible = true, origin = {46.011, -0}, points = {{5.989, 0}, {-5.989, -0}}, color = {0, 0, 255}));
23 | connect(pump.HQDown, level.HQ) annotation(Line(visible = true, origin = {-33.025, -10}, points = {{25.025, -10}, {-6.675, -10}, {-6.675, 10}, {-11.675, 10}}, color = {0, 0, 255}));
24 | annotation(Diagram(coordinateSystem(extent = {{-148.5, -105}, {148.5, 105}}, preserveAspectRatio = true, initialScale = 0.1, grid = {5, 5})));
25 | end Example;
26 |
--------------------------------------------------------------------------------
/rtctools_diagnostics/export_results.py:
--------------------------------------------------------------------------------
1 | import glob
2 | import logging
3 | import os
4 | import shutil
5 |
6 | import numpy as np
7 |
8 | logger = logging.getLogger("rtctools")
9 |
10 |
11 | def copy_files_in_folder(path_to_file, new_folder):
12 | """Expects 'path_to_file' to be a path with filename, but
13 | without extension. The function then copies all files with that
14 | name to the new_folder."""
15 | for output_file in glob.glob(path_to_file + ".*"):
16 | output_file_name = os.path.basename(output_file)
17 | shutil.copyfile(output_file, os.path.join(new_folder, output_file_name))
18 |
19 |
20 | class ExportResultsEachPriorityMixin:
21 | """Include this mixin in your optimization problem class to
22 | write the results for the optimization run for each priority."""
23 |
24 | # By setting this to False in a parent class, you can disable the export of results
25 | export_results_each_priority = True
26 |
27 | def priority_completed(self, priority):
28 | super().priority_completed(priority)
29 |
30 | if self.export_results_each_priority:
31 | self.write()
32 | # Move all output files to a priority-specific folder
33 | num_len = 3
34 | subfolder_name = "priority_{:0{}}".format(priority, num_len)
35 | if getattr(self, "csv_ensemble_mode", False):
36 | ensemble = np.genfromtxt(
37 | os.path.join(self._input_folder, self.csv_ensemble_basename + ".csv"),
38 | delimiter=",",
39 | deletechars="",
40 | dtype=None,
41 | names=True,
42 | encoding=None,
43 | )
44 | for ensemble_member in ensemble["name"]:
45 | new_output_folder = os.path.join(self._output_folder, ensemble_member, subfolder_name)
46 | os.makedirs(new_output_folder, exist_ok=True)
47 | file_to_copy_stem = os.path.join(
48 | self._output_folder,
49 | ensemble_member,
50 | self.timeseries_export_basename,
51 | )
52 | copy_files_in_folder(file_to_copy_stem, new_output_folder)
53 | else:
54 | new_output_folder = os.path.join(self._output_folder, subfolder_name)
55 | os.makedirs(new_output_folder, exist_ok=True)
56 | file_to_copy_stem = os.path.join(self._output_folder, self.timeseries_export_basename)
57 | copy_files_in_folder(file_to_copy_stem, new_output_folder)
58 | else:
59 | logger.debug(
60 | "Exporting results for each priority is disabled with class variable 'export_results_each_priority'."
61 | )
62 |
--------------------------------------------------------------------------------
/examples/export_each_priority/src/example.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 | from rtctools.optimization.collocated_integrated_optimization_problem import (
4 | CollocatedIntegratedOptimizationProblem,
5 | )
6 | from rtctools.optimization.csv_mixin import CSVMixin
7 | from rtctools.optimization.goal_programming_mixin import (
8 | Goal,
9 | GoalProgrammingMixin,
10 | StateGoal,
11 | )
12 | from rtctools.optimization.modelica_mixin import ModelicaMixin
13 | from rtctools.util import run_optimization_problem
14 | from rtctools_diagnostics.export_results import ExportResultsEachPriorityMixin
15 |
16 |
17 | class WaterLevelRangeGoal(StateGoal):
18 | # Applying a state goal to every time step is easily done by defining a goal
19 | # that inherits StateGoal. StateGoal is a helper class that uses the state
20 | # to determine the function, function range, and function nominal
21 | # automatically.
22 | state = "storage.HQ.H"
23 | # One goal can introduce a single or two constraints (min and/or max). Our
24 | # target water level range is 0.43 - 0.44. We might not always be able to
25 | # realize this, but we want to try.
26 | target_min = 0.43
27 | target_max = 0.44
28 |
29 | # Because we want to satisfy our water level target first, this has a
30 | # higher priority (=lower number).
31 | priority = 1
32 |
33 |
34 | class MinimizeQpumpGoal(Goal):
35 | # This goal does not use a helper class, so we have to define the function
36 | # method, range and nominal explicitly. We do not specify a target_min or
37 | # target_max in this class, so the goal programming mixin will try to
38 | # minimize the expression returned by the function method.
39 | def function(self, optimization_problem, ensemble_member):
40 | return optimization_problem.integral("Q_pump")
41 |
42 | # The nominal is used to scale the value returned by
43 | # the function method so that the value is on the order of 1.
44 | function_nominal = 100.0
45 | # The lower the number returned by this function, the higher the priority.
46 | priority = 2
47 | # The penalty variable is taken to the order'th power.
48 | order = 1
49 |
50 |
51 | class MinimizeChangeInQpumpGoal(Goal):
52 | # To reduce pump power cycles, we add a third goal to minimize changes in
53 | # Q_pump. This will be passed into the optimization problem as a path goal
54 | # because it is an an individual goal that should be applied at every time
55 | # step.
56 | def function(self, optimization_problem, ensemble_member):
57 | return optimization_problem.der("Q_pump")
58 |
59 | function_nominal = 5.0
60 | priority = 3
61 | # Default order is 2, but we want to be explicit
62 | order = 2
63 |
64 |
65 | # In the class, we include ExportResultsEachPriorityMixin to save the results after each priority.
66 | class Example(
67 | ExportResultsEachPriorityMixin,
68 | GoalProgrammingMixin,
69 | CSVMixin,
70 | ModelicaMixin,
71 | CollocatedIntegratedOptimizationProblem,
72 | ):
73 | """
74 | An introductory example to goal programming in RTC-Tools
75 | """
76 |
77 | def path_constraints(self, ensemble_member):
78 | # We want to add a few hard constraints to our problem. The goal
79 | # programming mixin however also generates constraints (and objectives)
80 | # from on our goals, so we have to call super() here.
81 | constraints = super().path_constraints(ensemble_member)
82 |
83 | # Release through orifice downhill only. This constraint enforces the
84 | # fact that water only flows downhill
85 | constraints.append((self.state("Q_orifice") + (1 - self.state("is_downhill")) * 10, 0.0, 10.0))
86 |
87 | # Make sure is_downhill is true only when the sea is lower than the
88 | # water level in the storage.
89 | M = 2 # The so-called "big-M"
90 | constraints.append(
91 | (
92 | self.state("H_sea") - self.state("storage.HQ.H") - (1 - self.state("is_downhill")) * M,
93 | -np.inf,
94 | 0.0,
95 | )
96 | )
97 | constraints.append(
98 | (
99 | self.state("H_sea") - self.state("storage.HQ.H") + self.state("is_downhill") * M,
100 | 0.0,
101 | np.inf,
102 | )
103 | )
104 |
105 | # Orifice flow constraint. Uses the equation:
106 | # Q(HUp, HDown, d) = width * C * d * (2 * g * (HUp - HDown)) ^ 0.5
107 | # Note that this equation is only valid for orifices that are submerged
108 | # units: description:
109 | w = 3.0 # m width of orifice
110 | d = 0.8 # m hight of orifice
111 | C = 1.0 # none orifice constant
112 | g = 9.8 # m/s^2 gravitational acceleration
113 | constraints.append(
114 | (
115 | ((self.state("Q_orifice") / (w * C * d)) ** 2) / (2 * g)
116 | + self.state("orifice.HQDown.H")
117 | - self.state("orifice.HQUp.H")
118 | - M * (1 - self.state("is_downhill")),
119 | -np.inf,
120 | 0.0,
121 | )
122 | )
123 |
124 | return constraints
125 |
126 | def goals(self):
127 | return [MinimizeQpumpGoal()]
128 |
129 | def path_goals(self):
130 | # Sorting goals on priority is done in the goal programming mixin. We
131 | # do not have to worry about order here.
132 | return [WaterLevelRangeGoal(self), MinimizeChangeInQpumpGoal()]
133 |
134 | # Any solver options can be set here
135 | def solver_options(self):
136 | options = super().solver_options()
137 | solver = options["solver"]
138 | options[solver]["print_level"] = 1
139 | return options
140 |
141 |
142 | # Run
143 | run_optimization_problem(Example)
144 |
--------------------------------------------------------------------------------
/rtctools_diagnostics/utils/casadi_to_lp.py:
--------------------------------------------------------------------------------
1 | import copy
2 | import logging
3 | import textwrap
4 |
5 | import casadi as ca
6 |
7 | import numpy as np
8 |
9 |
10 | logger = logging.getLogger("rtctools")
11 |
12 |
13 | def convert_constraints(constraints, lbg, ubg, b, n_dec):
14 | # lbg = np.array(ca.veccat(*lbg))[:, 0]
15 | # ubg = np.array(ca.veccat(*ubg))[:, 0]
16 | b = np.array(b)[:, 0]
17 | ca.veccat(*lbg)
18 | lbg = np.array(ca.veccat(*lbg))[:, 0]
19 | ubg = np.array(ca.veccat(*ubg))[:, 0]
20 | constraints_converted = copy.deepcopy(constraints)
21 | for i, _ in enumerate(constraints_converted):
22 | cur_constr = constraints_converted[i]
23 | lower, upper, b_i = (
24 | round(lbg[i], n_dec),
25 | round(ubg[i], n_dec),
26 | round(b[i], n_dec),
27 | )
28 |
29 | if len(cur_constr) > 0:
30 | if cur_constr[0] == "-":
31 | cur_constr[1] = "-" + cur_constr[1]
32 | cur_constr.pop(0)
33 |
34 | c_str = " ".join(cur_constr)
35 |
36 | if np.isfinite(lower) and np.isfinite(upper) and lower == upper:
37 | constraints_converted[i] = "{} = {}".format(c_str, lower - b_i)
38 | elif np.isfinite(lower) and np.isfinite(upper):
39 | constraints_converted[i] = "{} <= {} <= {}".format(lower - b_i, c_str, upper - b_i)
40 | elif np.isfinite(lower):
41 | constraints_converted[i] = "{} >= {}".format(c_str, lower - b_i)
42 | elif np.isfinite(upper):
43 | constraints_converted[i] = "{} <= {}".format(c_str, upper - b_i)
44 | else:
45 | raise ValueError(lower, b, constraints_converted[i])
46 | return constraints_converted
47 |
48 |
49 | def get_varnames(casadi_equations):
50 | indices = casadi_equations["indices"][0]
51 | expand_f_g = casadi_equations["func"]
52 |
53 | var_names = []
54 | for k, v in indices.items():
55 | if isinstance(v, int):
56 | var_names.append("{}__{}".format(k, v))
57 | else:
58 | for i in range(0, v.stop - v.start, 1 if v.step is None else v.step):
59 | var_names.append("{}__{}".format(k, i))
60 |
61 | n_derivatives = expand_f_g.nnz_in() - len(var_names)
62 | for i in range(n_derivatives):
63 | var_names.append("DERIVATIVE__{}".format(i))
64 |
65 | # CPLEX does not like [] in variable names
66 | for i, v in enumerate(var_names):
67 | v = v.replace("[", "_I")
68 | v = v.replace("]", "I_")
69 | var_names[i] = v
70 |
71 | return var_names
72 |
73 |
74 | def get_systems_of_equations(casadi_equations):
75 | expand_f_g = casadi_equations["func"]
76 | X = ca.SX.sym("X", expand_f_g.nnz_in())
77 | f, g = expand_f_g(X)
78 | eq_systems = []
79 | for o in [f, g]:
80 | Af = ca.Function("Af", [X], [ca.jacobian(o, X)])
81 | bf = ca.Function("bf", [X], [o])
82 |
83 | A = Af(0)
84 | A = ca.sparsify(A)
85 |
86 | b = bf(0)
87 | b = ca.sparsify(b)
88 | eq_systems.append((A, b))
89 |
90 | return {key: value for key, value in zip(["objective", "constraints"], eq_systems)}
91 |
92 |
93 | def casadi_to_lp(casadi_equations, lp_name=None):
94 | """Convert the model as formulated with casadi types to a human-readable
95 | format.
96 | """
97 | n_dec = 4 # number of decimals
98 | try:
99 | lbx, ubx, lbg, ubg, x0 = casadi_equations["other"]
100 | eq_systems = get_systems_of_equations(casadi_equations)
101 | var_names = get_varnames(casadi_equations)
102 |
103 | # OBJECTIVE
104 | try:
105 | A, b = eq_systems["objective"]
106 | objective = []
107 | ind = np.array(A)[0, :]
108 |
109 | for v, c in zip(var_names, ind):
110 | if c != 0:
111 | objective.extend(["+" if c > 0 else "-", str(abs(c)), v])
112 |
113 | if objective[0] == "-":
114 | objective[1] = "-" + objective[1]
115 |
116 | objective.pop(0)
117 | objective_str = " ".join(objective)
118 | objective_str = " " + objective_str
119 | except IndexError:
120 | logger.warning("Cannot convert non-linear objective! Objective string is set to 1")
121 | objective_str = "1"
122 |
123 | # CONSTRAINTS
124 | A, b = eq_systems["constraints"]
125 |
126 | A_csc = A.tocsc()
127 | A_coo = A_csc.tocoo()
128 |
129 | constraints = [[] for i in range(A.shape[0])]
130 |
131 | for i, j, c in zip(A_coo.row, A_coo.col, A_coo.data):
132 | constraints[i].extend(["+" if c > 0 else "-", str(abs(round(c, n_dec))), var_names[j]])
133 |
134 | converted_constraints = convert_constraints(constraints, lbg, ubg, b, n_dec)
135 | constraints_str = " " + "\n ".join(converted_constraints)
136 |
137 | # Bounds
138 | bounds = []
139 | for v, lower, upper in zip(var_names, lbx, ubx):
140 | bounds.append("{} <= {} <= {}".format(lower, v, upper))
141 | bounds_str = " " + "\n ".join(bounds)
142 | if lp_name:
143 | with open("myproblem_{}.lp".format(lp_name), "w") as o:
144 | o.write("Minimize\n")
145 | for x in textwrap.wrap(objective_str, width=255): # lp-format has max length of 255 chars
146 | o.write(x + "\n")
147 | o.write("Subject To\n")
148 | o.write(constraints_str + "\n")
149 | o.write("Bounds\n")
150 | o.write(bounds_str + "\n")
151 | o.write("End")
152 | with open("constraints.lp", "w") as o:
153 | o.write(constraints_str + "\n")
154 |
155 | return constraints
156 |
157 | except Exception as e:
158 | message = (
159 | "Error occured while generating lp file! {}".format(e)
160 | + "\n Does the problem contain non-linear constraints?"
161 | )
162 | logger.error(message)
163 | raise Exception(message)
164 |
--------------------------------------------------------------------------------
/COPYING.LESSER:
--------------------------------------------------------------------------------
1 | GNU LESSER GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 |
9 | This version of the GNU Lesser General Public License incorporates
10 | the terms and conditions of version 3 of the GNU General Public
11 | License, supplemented by the additional permissions listed below.
12 |
13 | 0. Additional Definitions.
14 |
15 | As used herein, "this License" refers to version 3 of the GNU Lesser
16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU
17 | General Public License.
18 |
19 | "The Library" refers to a covered work governed by this License,
20 | other than an Application or a Combined Work as defined below.
21 |
22 | An "Application" is any work that makes use of an interface provided
23 | by the Library, but which is not otherwise based on the Library.
24 | Defining a subclass of a class defined by the Library is deemed a mode
25 | of using an interface provided by the Library.
26 |
27 | A "Combined Work" is a work produced by combining or linking an
28 | Application with the Library. The particular version of the Library
29 | with which the Combined Work was made is also called the "Linked
30 | Version".
31 |
32 | The "Minimal Corresponding Source" for a Combined Work means the
33 | Corresponding Source for the Combined Work, excluding any source code
34 | for portions of the Combined Work that, considered in isolation, are
35 | based on the Application, and not on the Linked Version.
36 |
37 | The "Corresponding Application Code" for a Combined Work means the
38 | object code and/or source code for the Application, including any data
39 | and utility programs needed for reproducing the Combined Work from the
40 | Application, but excluding the System Libraries of the Combined Work.
41 |
42 | 1. Exception to Section 3 of the GNU GPL.
43 |
44 | You may convey a covered work under sections 3 and 4 of this License
45 | without being bound by section 3 of the GNU GPL.
46 |
47 | 2. Conveying Modified Versions.
48 |
49 | If you modify a copy of the Library, and, in your modifications, a
50 | facility refers to a function or data to be supplied by an Application
51 | that uses the facility (other than as an argument passed when the
52 | facility is invoked), then you may convey a copy of the modified
53 | version:
54 |
55 | a) under this License, provided that you make a good faith effort to
56 | ensure that, in the event an Application does not supply the
57 | function or data, the facility still operates, and performs
58 | whatever part of its purpose remains meaningful, or
59 |
60 | b) under the GNU GPL, with none of the additional permissions of
61 | this License applicable to that copy.
62 |
63 | 3. Object Code Incorporating Material from Library Header Files.
64 |
65 | The object code form of an Application may incorporate material from
66 | a header file that is part of the Library. You may convey such object
67 | code under terms of your choice, provided that, if the incorporated
68 | material is not limited to numerical parameters, data structure
69 | layouts and accessors, or small macros, inline functions and templates
70 | (ten or fewer lines in length), you do both of the following:
71 |
72 | a) Give prominent notice with each copy of the object code that the
73 | Library is used in it and that the Library and its use are
74 | covered by this License.
75 |
76 | b) Accompany the object code with a copy of the GNU GPL and this license
77 | document.
78 |
79 | 4. Combined Works.
80 |
81 | You may convey a Combined Work under terms of your choice that,
82 | taken together, effectively do not restrict modification of the
83 | portions of the Library contained in the Combined Work and reverse
84 | engineering for debugging such modifications, if you also do each of
85 | the following:
86 |
87 | a) Give prominent notice with each copy of the Combined Work that
88 | the Library is used in it and that the Library and its use are
89 | covered by this License.
90 |
91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license
92 | document.
93 |
94 | c) For a Combined Work that displays copyright notices during
95 | execution, include the copyright notice for the Library among
96 | these notices, as well as a reference directing the user to the
97 | copies of the GNU GPL and this license document.
98 |
99 | d) Do one of the following:
100 |
101 | 0) Convey the Minimal Corresponding Source under the terms of this
102 | License, and the Corresponding Application Code in a form
103 | suitable for, and under terms that permit, the user to
104 | recombine or relink the Application with a modified version of
105 | the Linked Version to produce a modified Combined Work, in the
106 | manner specified by section 6 of the GNU GPL for conveying
107 | Corresponding Source.
108 |
109 | 1) Use a suitable shared library mechanism for linking with the
110 | Library. A suitable mechanism is one that (a) uses at run time
111 | a copy of the Library already present on the user's computer
112 | system, and (b) will operate properly with a modified version
113 | of the Library that is interface-compatible with the Linked
114 | Version.
115 |
116 | e) Provide Installation Information, but only if you would otherwise
117 | be required to provide such information under section 6 of the
118 | GNU GPL, and only to the extent that such information is
119 | necessary to install and execute a modified version of the
120 | Combined Work produced by recombining or relinking the
121 | Application with a modified version of the Linked Version. (If
122 | you use option 4d0, the Installation Information must accompany
123 | the Minimal Corresponding Source and Corresponding Application
124 | Code. If you use option 4d1, you must provide the Installation
125 | Information in the manner specified by section 6 of the GNU GPL
126 | for conveying Corresponding Source.)
127 |
128 | 5. Combined Libraries.
129 |
130 | You may place library facilities that are a work based on the
131 | Library side by side in a single library together with other library
132 | facilities that are not Applications and are not covered by this
133 | License, and convey such a combined library under terms of your
134 | choice, if you do both of the following:
135 |
136 | a) Accompany the combined library with a copy of the same work based
137 | on the Library, uncombined with any other library facilities,
138 | conveyed under the terms of this License.
139 |
140 | b) Give prominent notice with the combined library that part of it
141 | is a work based on the Library, and explaining where to find the
142 | accompanying uncombined form of the same work.
143 |
144 | 6. Revised Versions of the GNU Lesser General Public License.
145 |
146 | The Free Software Foundation may publish revised and/or new versions
147 | of the GNU Lesser General Public License from time to time. Such new
148 | versions will be similar in spirit to the present version, but may
149 | differ in detail to address new problems or concerns.
150 |
151 | Each version is given a distinguishing version number. If the
152 | Library as you received it specifies that a certain numbered version
153 | of the GNU Lesser General Public License "or any later version"
154 | applies to it, you have the option of following the terms and
155 | conditions either of that published version or of any later version
156 | published by the Free Software Foundation. If the Library as you
157 | received it does not specify a version number of the GNU Lesser
158 | General Public License, you may choose any version of the GNU Lesser
159 | General Public License ever published by the Free Software Foundation.
160 |
161 | If the Library as you received it specifies that a proxy can decide
162 | whether future versions of the GNU Lesser General Public License shall
163 | apply, that proxy's public statement of acceptance of any version is
164 | permanent authorization for you to choose that version for the
165 | Library.
166 |
--------------------------------------------------------------------------------
/rtctools_diagnostics/get_linear_problem.py:
--------------------------------------------------------------------------------
1 | import copy
2 | import logging
3 | import os
4 |
5 | import casadi as ca
6 |
7 | import numpy as np
8 |
9 | import pandas as pd
10 |
11 | from rtctools_diagnostics.utils.casadi_to_lp import (
12 | casadi_to_lp,
13 | convert_constraints,
14 | get_systems_of_equations,
15 | get_varnames,
16 | )
17 |
18 | logger = logging.getLogger("rtctools")
19 |
20 |
21 | def get_constraints(casadi_equations):
22 | """Get constraints in human-readable format"""
23 | return casadi_to_lp(casadi_equations)
24 |
25 |
26 | def evaluate_constraints(results, nlp):
27 | """Evaluate the constraints wrt to the optimized solution"""
28 | x_optimized = results["x_ravel"]
29 | X_sx = ca.SX.sym("X", *nlp["x"].shape)
30 | expand_fg = ca.Function("f_g", [nlp["x"]], [nlp["f"], nlp["g"]]).expand()
31 | _f_sx, g_sx = expand_fg(X_sx)
32 | eval_g = ca.Function("g_eval", [X_sx], [g_sx]).expand()
33 | evaluated_g = [x[0] for x in np.array(eval_g(x_optimized))]
34 | return evaluated_g
35 |
36 |
37 | def print_evaluated_constraints(results, nlp):
38 | """Print the actual constraints, showing the actual value of each
39 | variable between brackets."""
40 | raise NotImplementedError
41 |
42 |
43 | def get_lagrange_mult(results):
44 | """Get the lagrange multipliers for the constraints (g) and bounds (x)"""
45 | lam_g = [x[0] for x in np.array(results["lam_g"])]
46 | lam_x = [x[0] for x in np.array(results["lam_x"])]
47 | if np.isnan(lam_x).any() or np.isnan(lam_x).any():
48 | raise ValueError("List of lagrange multipliers contains NaNs!!")
49 | return lam_g, lam_x
50 |
51 |
52 | def extract_var_name_timestep(variable):
53 | """Split the variable name into its original name and its timestep"""
54 | var_name, _, timestep_str = variable.partition("__")
55 | return var_name, int(timestep_str.split("_")[-1])
56 |
57 |
58 | def add_to_dict(new_dict, var_name, timestep, sign="+"):
59 | """Add variable to dict grouped by variable names"""
60 | if var_name not in new_dict:
61 | new_dict[var_name] = {"timesteps": [timestep], "effect_direction": sign}
62 | else:
63 | if new_dict[var_name]["effect_direction"] == "sign":
64 | new_dict[var_name]["timesteps"].append(timestep)
65 | else:
66 | new_dict[var_name + sign] = {
67 | "timesteps": [timestep],
68 | "effect_direction": sign,
69 | }
70 | return new_dict
71 |
72 |
73 | def convert_to_dict_per_var(constrain_list):
74 | """Convert list of ungrouped variables to a dict per variable name,
75 | with as values the time-indices where the variable was active"""
76 | new_dict = {}
77 | for constrain in constrain_list:
78 | if isinstance(constrain, list):
79 | for i, variable in enumerate(constrain[2::3]):
80 | var_name, timestep = extract_var_name_timestep(variable)
81 | add_to_dict(new_dict, var_name, timestep, constrain[i * 3])
82 | else:
83 | var_name, timestep = extract_var_name_timestep(constrain)
84 | add_to_dict(new_dict, var_name, timestep)
85 | # Sort values and remove duplicates
86 | for var_name in new_dict:
87 | new_dict[var_name]["timesteps"] = sorted(set(new_dict[var_name]["timesteps"]))
88 | return new_dict
89 |
90 |
91 | def get_tol_exceedance(in_list, tolerance):
92 | return [x > tolerance for x in in_list], [x < -tolerance for x in in_list]
93 |
94 |
95 | def find_variable_hits(exceedance_list, lowers, uppers, variable_names, variable_values, lam):
96 | """Returns the elements of variable_names corresponding to the elements
97 | that are True in the exceedance list."""
98 | variable_hits = []
99 | for i, hit in enumerate(exceedance_list):
100 | if hit:
101 | logger.debug("Bound for variable {}={} was hit! Lam={}".format(variable_names[i], variable_values[i], lam))
102 | logger.debug("{} < {} < {}".format(lowers[i], variable_values[i], uppers[i]))
103 | variable_hits.append(variable_names[i])
104 | return variable_hits
105 |
106 |
107 | def get_variables_in_active_constr(results, nlp, casadi_equations, lam_tol):
108 | """ "
109 | This function determines all active constraints/bounds and extracts the
110 | variables that are in those active constraints/bounds. It returns dictionaries
111 | with keys indicating the active variable and with values the timestep(s) at which
112 | that variable is active.
113 | """
114 | constraints = get_constraints(casadi_equations)
115 | lbx, ubx, lbg, ubg, _x0 = casadi_equations["other"]
116 | variable_names = get_varnames(casadi_equations)
117 |
118 | lam_g, lam_x = get_lagrange_mult(results)
119 |
120 | # Upper and lower bounds
121 | lam_x_larger_than_zero, lam_x_smaller_than_zero = get_tol_exceedance(lam_x, lam_tol)
122 | upper_bound_variable_hits = find_variable_hits(
123 | lam_x_larger_than_zero,
124 | lbx,
125 | ubx,
126 | variable_names,
127 | results["x_ravel"],
128 | lam_x,
129 | )
130 | lower_bound_variable_hits = find_variable_hits(
131 | lam_x_smaller_than_zero,
132 | lbx,
133 | ubx,
134 | variable_names,
135 | results["x_ravel"],
136 | lam_x,
137 | )
138 | upper_bound_dict = convert_to_dict_per_var(upper_bound_variable_hits)
139 | lower_bound_dict = convert_to_dict_per_var(lower_bound_variable_hits)
140 |
141 | # Upper and lower constraints
142 | lam_g_larger_than_zero, lam_g_smaller_than_zero = get_tol_exceedance(lam_g, lam_tol)
143 |
144 | evaluated_g = evaluate_constraints(results, nlp)
145 | upper_constraint_variable_hits = find_variable_hits(
146 | lam_g_larger_than_zero, lbg, ubg, constraints, evaluated_g, lam_g
147 | )
148 | lower_constraint_variable_hits = find_variable_hits(
149 | lam_g_smaller_than_zero, lbg, ubg, constraints, evaluated_g, lam_g
150 | )
151 | upper_constraint_dict = convert_to_dict_per_var(upper_constraint_variable_hits)
152 | lower_constraint_dict = convert_to_dict_per_var(lower_constraint_variable_hits)
153 |
154 | return (
155 | upper_bound_dict,
156 | lower_bound_dict,
157 | upper_constraint_dict,
158 | lower_constraint_dict,
159 | )
160 |
161 |
162 | def get_active_constraints(results, casadi_equations, lam_tol=0.1, n_dec=4):
163 | """Get all constraints that are active in a human-radable format."""
164 | constraints = get_constraints(casadi_equations)
165 | _lbx, _ubx, lbg, ubg, _x0 = casadi_equations["other"]
166 | eq_systems = get_systems_of_equations(casadi_equations)
167 | _A, b = eq_systems["constraints"]
168 | converted_constraints = convert_constraints(constraints, lbg, ubg, b, n_dec)
169 | lam_g, _lam_x = get_lagrange_mult(results)
170 | lam_g_larger_than_zero, lam_g_smaller_than_zero = get_tol_exceedance(lam_g, lam_tol)
171 | active_upper_constraints = [
172 | constraint for i, constraint in enumerate(converted_constraints) if lam_g_larger_than_zero[i]
173 | ]
174 | active_lower_constraints = [
175 | constraint for i, constraint in enumerate(converted_constraints) if lam_g_smaller_than_zero[i]
176 | ]
177 | return active_lower_constraints, active_upper_constraints
178 |
179 |
180 | def list_to_ranges(lst):
181 | """Given a list with integers, returns a list of closed ranges
182 | present in the input-list."""
183 | if not lst:
184 | return []
185 | ranges = []
186 | start = end = lst[0]
187 | for i in range(1, len(lst)):
188 | if lst[i] == end + 1:
189 | end = lst[i]
190 | else:
191 | ranges.append((start, end))
192 | start = end = lst[i]
193 | ranges.append((start, end))
194 | return ranges
195 |
196 |
197 | def convert_lists_in_dict(dic):
198 | """Converts all lists in a dictionairy to lists of ranges.
199 | See list_to_ranges."""
200 | new_dic = copy.deepcopy(dic)
201 | for key, val in dic.items():
202 | new_dic[key]["timesteps"] = list_to_ranges(val["timesteps"])
203 | return new_dic
204 |
205 |
206 | def strip_timestep(s):
207 | parts = []
208 | for part in s.split():
209 | if "__" in part:
210 | name, _ = part.split("__")
211 | name += "__"
212 | parts.append(name)
213 | else:
214 | parts.append(part)
215 | return " ".join(parts)
216 |
217 |
218 | def add_symbol_before_line(lines, symbol):
219 | """For markdown formatting"""
220 | return "\n".join([f"{symbol} {line}" for line in lines.split("\n")])
221 |
222 |
223 | def add_blockquote(lines):
224 | """For markdown formatting"""
225 | return add_symbol_before_line(lines, ">")
226 |
227 |
228 | def group_equations(equations):
229 | """Group identical equations for different timesteps."""
230 | unique_equations = {}
231 | for equation in equations:
232 | variables = {}
233 | # Get all variables in equation
234 | for var in equation.split():
235 | if "__" in var:
236 | var_name, var_suffix = var.split("__")
237 | if var_name in variables:
238 | if variables[var_name] != var_suffix:
239 | variables[var_name] = None
240 | else:
241 | variables[var_name] = var_suffix
242 | variables_equal = {k: v for k, v in variables.items() if v is not None}
243 | variables_none = {k: v for k, v in variables.items() if v is None}
244 | timesteps = list(variables_equal.values())
245 | if len(variables_none) > 0 or not all(x == timesteps[0] for x in timesteps):
246 | unique_equations[equation] = "Equation depends on >1 timestep"
247 | else:
248 | key = strip_timestep(equation)
249 | # Add equation to dict of unique equations
250 | if key in unique_equations:
251 | unique_suffixes = unique_equations[key]
252 | for var_suffix in variables_equal.values():
253 | if var_suffix not in unique_suffixes:
254 | unique_suffixes.append(var_suffix)
255 | else:
256 | if len(variables_equal.values()) > 0:
257 | unique_equations[key] = [list(variables_equal.values())[0]]
258 |
259 | return unique_equations
260 |
261 |
262 | def get_debug_markdown_per_prio(
263 | lowerconstr_range_dict,
264 | upperconstr_range_dict,
265 | lowerbound_range_dict,
266 | upperbound_range_dict,
267 | active_lower_constraints,
268 | active_upper_constraints,
269 | priority="unknown",
270 | ):
271 | upper_constraints_df = pd.DataFrame.from_dict(upperconstr_range_dict, orient="index")
272 | lower_constraints_df = pd.DataFrame.from_dict(lowerconstr_range_dict, orient="index")
273 | lowerbounds_df = pd.DataFrame.from_dict(lowerbound_range_dict, orient="index")
274 | upperbounds_df = pd.DataFrame.from_dict(upperbound_range_dict, orient="index")
275 | result_text = "\n# Priority {}\n".format(priority)
276 | result_text += "## Lower constraints:\n"
277 | if len(lower_constraints_df):
278 | result_text += ">### Active variables:\n"
279 | result_text += add_blockquote(lower_constraints_df.to_markdown()) + "\n"
280 | result_text += ">### from active constraints:\n"
281 | for eq, timesteps in group_equations(active_lower_constraints).items():
282 | result_text += f">- `{eq}`: {timesteps}\n"
283 | else:
284 | result_text += ">No active lower constraints\n"
285 |
286 | result_text += "\n## Upper constraints:\n"
287 | if len(upper_constraints_df):
288 | result_text += ">### Active variables:\n"
289 | result_text += add_blockquote(upper_constraints_df.to_markdown()) + "\n"
290 | result_text += ">### from active constraints:\n"
291 | for eq, timesteps in group_equations(active_upper_constraints).items():
292 | result_text += f">- `{eq}`: {timesteps}\n"
293 | else:
294 | result_text += ">No active upper constraints\n"
295 |
296 | result_text += "\n ## Lower bounds:\n"
297 | if len(lowerbounds_df):
298 | result_text += add_blockquote(lowerbounds_df.to_markdown()) + "\n"
299 | else:
300 | result_text += ">No active lower bounds\n"
301 | result_text += "\n ## Upper bounds:\n"
302 | if len(upperbounds_df):
303 | result_text += add_blockquote(upperbounds_df.to_markdown()) + "\n"
304 | else:
305 | result_text += ">No active upper bounds\n"
306 | return result_text
307 |
308 |
309 | class GetLinearProblemMixin:
310 | """By including this class in your (linear) optimization problem class,
311 | the linear problem of your problem will be written to a markdown file. The
312 | file will indicate which constraints/bounds are active at each particular
313 | priority."""
314 |
315 | lam_tol = 0.1
316 | manual_expansion = True
317 |
318 | def __init__(self, **kwargs):
319 | super().__init__(**kwargs)
320 | self.problem_and_results_list = []
321 |
322 | def priority_completed(self, priority):
323 | super().priority_completed(priority)
324 | lbx, ubx, lbg, ubg, x0, nlp = self.transcribed_problem.values()
325 | expand_f_g = ca.Function("f_g", [nlp["x"]], [nlp["f"], nlp["g"]]).expand()
326 | casadi_equations = {}
327 | casadi_equations["indices"] = self._CollocatedIntegratedOptimizationProblem__indices
328 | casadi_equations["func"] = expand_f_g
329 | casadi_equations["other"] = (lbx, ubx, lbg, ubg, x0)
330 | lam_g, lam_x = self.lagrange_multipliers
331 | x_ravel = self.solver_output
332 | results = {"lam_g": lam_g, "lam_x": lam_x, "x_ravel": x_ravel}
333 | self.problem_and_results_list.append((priority, results, nlp, casadi_equations))
334 |
335 | def post(self):
336 | super().post()
337 |
338 | result_text = ""
339 | if len(self.problem_and_results_list) == 0:
340 | result_text += "No completed priorities... Is the problem infeasible?"
341 |
342 | for problem_and_results in self.problem_and_results_list:
343 | priority, results, nlp, casadi_equations = problem_and_results
344 | (
345 | upper_bound_dict,
346 | lower_bound_dict,
347 | upper_constraint_dict,
348 | lower_constraint_dict,
349 | ) = get_variables_in_active_constr(results, nlp, casadi_equations, self.lam_tol)
350 | upperconstr_range_dict = convert_lists_in_dict(upper_constraint_dict)
351 | lowerconstr_range_dict = convert_lists_in_dict(lower_constraint_dict)
352 | lowerbound_range_dict = convert_lists_in_dict(upper_bound_dict)
353 | upperbound_range_dict = convert_lists_in_dict(lower_bound_dict)
354 |
355 | (
356 | active_lower_constraints,
357 | active_upper_constraints,
358 | ) = get_active_constraints(results, casadi_equations, self.lam_tol)
359 |
360 | result_text += get_debug_markdown_per_prio(
361 | lowerconstr_range_dict,
362 | upperconstr_range_dict,
363 | lowerbound_range_dict,
364 | upperbound_range_dict,
365 | active_lower_constraints,
366 | active_upper_constraints,
367 | priority=priority,
368 | )
369 |
370 | with open(os.path.join(self._output_folder, "active_constraints.md"), "w") as f:
371 | f.write(result_text)
372 |
--------------------------------------------------------------------------------
/rtctools_diagnostics/_version.py:
--------------------------------------------------------------------------------
1 | # This file helps to compute a version number in source trees obtained from
2 | # git-archive tarball (such as those provided by githubs download-from-tag
3 | # feature). Distribution tarballs (built by setup.py sdist) and build
4 | # directories (produced by setup.py build) will contain a much shorter file
5 | # that just contains the computed version number.
6 |
7 | # This file is released into the public domain.
8 | # Generated by versioneer-0.28
9 | # https://github.com/python-versioneer/python-versioneer
10 |
11 | """Git implementation of _version.py."""
12 |
13 | import errno
14 | import os
15 | import re
16 | import subprocess
17 | import sys
18 | from typing import Callable, Dict
19 | import functools
20 |
21 |
22 | def get_keywords():
23 | """Get the keywords needed to look up the version information."""
24 | # these strings will be replaced by git during git-archive.
25 | # setup.py/versioneer.py will grep for the variable names, so they must
26 | # each be defined on a line of their own. _version.py will just call
27 | # get_keywords().
28 | git_refnames = " (HEAD -> main)"
29 | git_full = "dad6bff74b70a582f181c3023cf247be04c3b0f7"
30 | git_date = "2025-06-13 15:27:19 +0200"
31 | keywords = {"refnames": git_refnames, "full": git_full, "date": git_date}
32 | return keywords
33 |
34 |
35 | class VersioneerConfig:
36 | """Container for Versioneer configuration parameters."""
37 |
38 |
39 | def get_config():
40 | """Create, populate and return the VersioneerConfig() object."""
41 | # these strings are filled in when 'setup.py versioneer' creates
42 | # _version.py
43 | cfg = VersioneerConfig()
44 | cfg.VCS = "git"
45 | cfg.style = "pep440"
46 | cfg.tag_prefix = ""
47 | cfg.parentdir_prefix = "rtctools_diagnostics-"
48 | cfg.versionfile_source = "rtctools_diagnostics/_version.py"
49 | cfg.verbose = False
50 | return cfg
51 |
52 |
53 | class NotThisMethod(Exception):
54 | """Exception raised if a method is not valid for the current scenario."""
55 |
56 |
57 | LONG_VERSION_PY: Dict[str, str] = {}
58 | HANDLERS: Dict[str, Dict[str, Callable]] = {}
59 |
60 |
61 | def register_vcs_handler(vcs, method): # decorator
62 | """Create decorator to mark a method as the handler of a VCS."""
63 |
64 | def decorate(f):
65 | """Store f in HANDLERS[vcs][method]."""
66 | if vcs not in HANDLERS:
67 | HANDLERS[vcs] = {}
68 | HANDLERS[vcs][method] = f
69 | return f
70 |
71 | return decorate
72 |
73 |
74 | def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None):
75 | """Call the given command(s)."""
76 | assert isinstance(commands, list)
77 | process = None
78 |
79 | popen_kwargs = {}
80 | if sys.platform == "win32":
81 | # This hides the console window if pythonw.exe is used
82 | startupinfo = subprocess.STARTUPINFO()
83 | startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
84 | popen_kwargs["startupinfo"] = startupinfo
85 |
86 | for command in commands:
87 | try:
88 | dispcmd = str([command] + args)
89 | # remember shell=False, so use git.cmd on windows, not just git
90 | process = subprocess.Popen(
91 | [command] + args,
92 | cwd=cwd,
93 | env=env,
94 | stdout=subprocess.PIPE,
95 | stderr=(subprocess.PIPE if hide_stderr else None),
96 | **popen_kwargs,
97 | )
98 | break
99 | except OSError:
100 | e = sys.exc_info()[1]
101 | if e.errno == errno.ENOENT:
102 | continue
103 | if verbose:
104 | print("unable to run %s" % dispcmd)
105 | print(e)
106 | return None, None
107 | else:
108 | if verbose:
109 | print("unable to find command, tried %s" % (commands,))
110 | return None, None
111 | stdout = process.communicate()[0].strip().decode()
112 | if process.returncode != 0:
113 | if verbose:
114 | print("unable to run %s (error)" % dispcmd)
115 | print("stdout was %s" % stdout)
116 | return None, process.returncode
117 | return stdout, process.returncode
118 |
119 |
120 | def versions_from_parentdir(parentdir_prefix, root, verbose):
121 | """Try to determine the version from the parent directory name.
122 |
123 | Source tarballs conventionally unpack into a directory that includes both
124 | the project name and a version string. We will also support searching up
125 | two directory levels for an appropriately named parent directory
126 | """
127 | rootdirs = []
128 |
129 | for _ in range(3):
130 | dirname = os.path.basename(root)
131 | if dirname.startswith(parentdir_prefix):
132 | return {
133 | "version": dirname[len(parentdir_prefix) :],
134 | "full-revisionid": None,
135 | "dirty": False,
136 | "error": None,
137 | "date": None,
138 | }
139 | rootdirs.append(root)
140 | root = os.path.dirname(root) # up a level
141 |
142 | if verbose:
143 | print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix))
144 | raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
145 |
146 |
147 | @register_vcs_handler("git", "get_keywords")
148 | def git_get_keywords(versionfile_abs):
149 | """Extract version information from the given file."""
150 | # the code embedded in _version.py can just fetch the value of these
151 | # keywords. When used from setup.py, we don't want to import _version.py,
152 | # so we do it with a regexp instead. This function is not used from
153 | # _version.py.
154 | keywords = {}
155 | try:
156 | with open(versionfile_abs, "r") as fobj:
157 | for line in fobj:
158 | if line.strip().startswith("git_refnames ="):
159 | mo = re.search(r'=\s*"(.*)"', line)
160 | if mo:
161 | keywords["refnames"] = mo.group(1)
162 | if line.strip().startswith("git_full ="):
163 | mo = re.search(r'=\s*"(.*)"', line)
164 | if mo:
165 | keywords["full"] = mo.group(1)
166 | if line.strip().startswith("git_date ="):
167 | mo = re.search(r'=\s*"(.*)"', line)
168 | if mo:
169 | keywords["date"] = mo.group(1)
170 | except OSError:
171 | pass
172 | return keywords
173 |
174 |
175 | @register_vcs_handler("git", "keywords")
176 | def git_versions_from_keywords(keywords, tag_prefix, verbose):
177 | """Get version information from git keywords."""
178 | if "refnames" not in keywords:
179 | raise NotThisMethod("Short version file found")
180 | date = keywords.get("date")
181 | if date is not None:
182 | # Use only the last line. Previous lines may contain GPG signature
183 | # information.
184 | date = date.splitlines()[-1]
185 |
186 | # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant
187 | # datestamp. However we prefer "%ci" (which expands to an "ISO-8601
188 | # -like" string, which we must then edit to make compliant), because
189 | # it's been around since git-1.5.3, and it's too difficult to
190 | # discover which version we're using, or to work around using an
191 | # older one.
192 | date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
193 | refnames = keywords["refnames"].strip()
194 | if refnames.startswith("$Format"):
195 | if verbose:
196 | print("keywords are unexpanded, not using")
197 | raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
198 | refs = {r.strip() for r in refnames.strip("()").split(",")}
199 | # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
200 | # just "foo-1.0". If we see a "tag: " prefix, prefer those.
201 | TAG = "tag: "
202 | tags = {r[len(TAG) :] for r in refs if r.startswith(TAG)}
203 | if not tags:
204 | # Either we're using git < 1.8.3, or there really are no tags. We use
205 | # a heuristic: assume all version tags have a digit. The old git %d
206 | # expansion behaves like git log --decorate=short and strips out the
207 | # refs/heads/ and refs/tags/ prefixes that would let us distinguish
208 | # between branches and tags. By ignoring refnames without digits, we
209 | # filter out many common branch names like "release" and
210 | # "stabilization", as well as "HEAD" and "master".
211 | tags = {r for r in refs if re.search(r"\d", r)}
212 | if verbose:
213 | print("discarding '%s', no digits" % ",".join(refs - tags))
214 | if verbose:
215 | print("likely tags: %s" % ",".join(sorted(tags)))
216 | for ref in sorted(tags):
217 | # sorting will prefer e.g. "2.0" over "2.0rc1"
218 | if ref.startswith(tag_prefix):
219 | r = ref[len(tag_prefix) :]
220 | # Filter out refs that exactly match prefix or that don't start
221 | # with a number once the prefix is stripped (mostly a concern
222 | # when prefix is '')
223 | if not re.match(r"\d", r):
224 | continue
225 | if verbose:
226 | print("picking %s" % r)
227 | return {
228 | "version": r,
229 | "full-revisionid": keywords["full"].strip(),
230 | "dirty": False,
231 | "error": None,
232 | "date": date,
233 | }
234 | # no suitable tags, so version is "0+unknown", but full hex is still there
235 | if verbose:
236 | print("no suitable tags, using unknown + full revision id")
237 | return {
238 | "version": "0+unknown",
239 | "full-revisionid": keywords["full"].strip(),
240 | "dirty": False,
241 | "error": "no suitable tags",
242 | "date": None,
243 | }
244 |
245 |
246 | @register_vcs_handler("git", "pieces_from_vcs")
247 | def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command):
248 | """Get version from 'git describe' in the root of the source tree.
249 |
250 | This only gets called if the git-archive 'subst' keywords were *not*
251 | expanded, and _version.py hasn't already been rewritten with a short
252 | version string, meaning we're inside a checked out source tree.
253 | """
254 | GITS = ["git"]
255 | if sys.platform == "win32":
256 | GITS = ["git.cmd", "git.exe"]
257 |
258 | # GIT_DIR can interfere with correct operation of Versioneer.
259 | # It may be intended to be passed to the Versioneer-versioned project,
260 | # but that should not change where we get our version from.
261 | env = os.environ.copy()
262 | env.pop("GIT_DIR", None)
263 | runner = functools.partial(runner, env=env)
264 |
265 | _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=not verbose)
266 | if rc != 0:
267 | if verbose:
268 | print("Directory %s not under git control" % root)
269 | raise NotThisMethod("'git rev-parse --git-dir' returned error")
270 |
271 | # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
272 | # if there isn't one, this yields HEX[-dirty] (no NUM)
273 | describe_out, rc = runner(
274 | GITS,
275 | [
276 | "describe",
277 | "--tags",
278 | "--dirty",
279 | "--always",
280 | "--long",
281 | "--match",
282 | f"{tag_prefix}[[:digit:]]*",
283 | ],
284 | cwd=root,
285 | )
286 | # --long was added in git-1.5.5
287 | if describe_out is None:
288 | raise NotThisMethod("'git describe' failed")
289 | describe_out = describe_out.strip()
290 | full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root)
291 | if full_out is None:
292 | raise NotThisMethod("'git rev-parse' failed")
293 | full_out = full_out.strip()
294 |
295 | pieces = {}
296 | pieces["long"] = full_out
297 | pieces["short"] = full_out[:7] # maybe improved later
298 | pieces["error"] = None
299 |
300 | branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root)
301 | # --abbrev-ref was added in git-1.6.3
302 | if rc != 0 or branch_name is None:
303 | raise NotThisMethod("'git rev-parse --abbrev-ref' returned error")
304 | branch_name = branch_name.strip()
305 |
306 | if branch_name == "HEAD":
307 | # If we aren't exactly on a branch, pick a branch which represents
308 | # the current commit. If all else fails, we are on a branchless
309 | # commit.
310 | branches, rc = runner(GITS, ["branch", "--contains"], cwd=root)
311 | # --contains was added in git-1.5.4
312 | if rc != 0 or branches is None:
313 | raise NotThisMethod("'git branch --contains' returned error")
314 | branches = branches.split("\n")
315 |
316 | # Remove the first line if we're running detached
317 | if "(" in branches[0]:
318 | branches.pop(0)
319 |
320 | # Strip off the leading "* " from the list of branches.
321 | branches = [branch[2:] for branch in branches]
322 | if "master" in branches:
323 | branch_name = "master"
324 | elif not branches:
325 | branch_name = None
326 | else:
327 | # Pick the first branch that is returned. Good or bad.
328 | branch_name = branches[0]
329 |
330 | pieces["branch"] = branch_name
331 |
332 | # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
333 | # TAG might have hyphens.
334 | git_describe = describe_out
335 |
336 | # look for -dirty suffix
337 | dirty = git_describe.endswith("-dirty")
338 | pieces["dirty"] = dirty
339 | if dirty:
340 | git_describe = git_describe[: git_describe.rindex("-dirty")]
341 |
342 | # now we have TAG-NUM-gHEX or HEX
343 |
344 | if "-" in git_describe:
345 | # TAG-NUM-gHEX
346 | mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe)
347 | if not mo:
348 | # unparsable. Maybe git-describe is misbehaving?
349 | pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out
350 | return pieces
351 |
352 | # tag
353 | full_tag = mo.group(1)
354 | if not full_tag.startswith(tag_prefix):
355 | if verbose:
356 | fmt = "tag '%s' doesn't start with prefix '%s'"
357 | print(fmt % (full_tag, tag_prefix))
358 | pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % (
359 | full_tag,
360 | tag_prefix,
361 | )
362 | return pieces
363 | pieces["closest-tag"] = full_tag[len(tag_prefix) :]
364 |
365 | # distance: number of commits since tag
366 | pieces["distance"] = int(mo.group(2))
367 |
368 | # commit: short hex revision ID
369 | pieces["short"] = mo.group(3)
370 |
371 | else:
372 | # HEX: no tags
373 | pieces["closest-tag"] = None
374 | out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root)
375 | pieces["distance"] = len(out.split()) # total number of commits
376 |
377 | # commit date: see ISO-8601 comment in git_versions_from_keywords()
378 | date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip()
379 | # Use only the last line. Previous lines may contain GPG signature
380 | # information.
381 | date = date.splitlines()[-1]
382 | pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
383 |
384 | return pieces
385 |
386 |
387 | def plus_or_dot(pieces):
388 | """Return a + if we don't already have one, else return a ."""
389 | if "+" in pieces.get("closest-tag", ""):
390 | return "."
391 | return "+"
392 |
393 |
394 | def render_pep440(pieces):
395 | """Build up version string, with post-release "local version identifier".
396 |
397 | Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
398 | get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
399 |
400 | Exceptions:
401 | 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
402 | """
403 | if pieces["closest-tag"]:
404 | rendered = pieces["closest-tag"]
405 | if pieces["distance"] or pieces["dirty"]:
406 | rendered += plus_or_dot(pieces)
407 | rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
408 | if pieces["dirty"]:
409 | rendered += ".dirty"
410 | else:
411 | # exception #1
412 | rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
413 | if pieces["dirty"]:
414 | rendered += ".dirty"
415 | return rendered
416 |
417 |
418 | def render_pep440_branch(pieces):
419 | """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] .
420 |
421 | The ".dev0" means not master branch. Note that .dev0 sorts backwards
422 | (a feature branch will appear "older" than the master branch).
423 |
424 | Exceptions:
425 | 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty]
426 | """
427 | if pieces["closest-tag"]:
428 | rendered = pieces["closest-tag"]
429 | if pieces["distance"] or pieces["dirty"]:
430 | if pieces["branch"] != "master":
431 | rendered += ".dev0"
432 | rendered += plus_or_dot(pieces)
433 | rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
434 | if pieces["dirty"]:
435 | rendered += ".dirty"
436 | else:
437 | # exception #1
438 | rendered = "0"
439 | if pieces["branch"] != "master":
440 | rendered += ".dev0"
441 | rendered += "+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
442 | if pieces["dirty"]:
443 | rendered += ".dirty"
444 | return rendered
445 |
446 |
447 | def pep440_split_post(ver):
448 | """Split pep440 version string at the post-release segment.
449 |
450 | Returns the release segments before the post-release and the
451 | post-release version number (or -1 if no post-release segment is present).
452 | """
453 | vc = str.split(ver, ".post")
454 | return vc[0], int(vc[1] or 0) if len(vc) == 2 else None
455 |
456 |
457 | def render_pep440_pre(pieces):
458 | """TAG[.postN.devDISTANCE] -- No -dirty.
459 |
460 | Exceptions:
461 | 1: no tags. 0.post0.devDISTANCE
462 | """
463 | if pieces["closest-tag"]:
464 | if pieces["distance"]:
465 | # update the post release segment
466 | tag_version, post_version = pep440_split_post(pieces["closest-tag"])
467 | rendered = tag_version
468 | if post_version is not None:
469 | rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"])
470 | else:
471 | rendered += ".post0.dev%d" % (pieces["distance"])
472 | else:
473 | # no commits, use the tag as the version
474 | rendered = pieces["closest-tag"]
475 | else:
476 | # exception #1
477 | rendered = "0.post0.dev%d" % pieces["distance"]
478 | return rendered
479 |
480 |
481 | def render_pep440_post(pieces):
482 | """TAG[.postDISTANCE[.dev0]+gHEX] .
483 |
484 | The ".dev0" means dirty. Note that .dev0 sorts backwards
485 | (a dirty tree will appear "older" than the corresponding clean one),
486 | but you shouldn't be releasing software with -dirty anyways.
487 |
488 | Exceptions:
489 | 1: no tags. 0.postDISTANCE[.dev0]
490 | """
491 | if pieces["closest-tag"]:
492 | rendered = pieces["closest-tag"]
493 | if pieces["distance"] or pieces["dirty"]:
494 | rendered += ".post%d" % pieces["distance"]
495 | if pieces["dirty"]:
496 | rendered += ".dev0"
497 | rendered += plus_or_dot(pieces)
498 | rendered += "g%s" % pieces["short"]
499 | else:
500 | # exception #1
501 | rendered = "0.post%d" % pieces["distance"]
502 | if pieces["dirty"]:
503 | rendered += ".dev0"
504 | rendered += "+g%s" % pieces["short"]
505 | return rendered
506 |
507 |
508 | def render_pep440_post_branch(pieces):
509 | """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] .
510 |
511 | The ".dev0" means not master branch.
512 |
513 | Exceptions:
514 | 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty]
515 | """
516 | if pieces["closest-tag"]:
517 | rendered = pieces["closest-tag"]
518 | if pieces["distance"] or pieces["dirty"]:
519 | rendered += ".post%d" % pieces["distance"]
520 | if pieces["branch"] != "master":
521 | rendered += ".dev0"
522 | rendered += plus_or_dot(pieces)
523 | rendered += "g%s" % pieces["short"]
524 | if pieces["dirty"]:
525 | rendered += ".dirty"
526 | else:
527 | # exception #1
528 | rendered = "0.post%d" % pieces["distance"]
529 | if pieces["branch"] != "master":
530 | rendered += ".dev0"
531 | rendered += "+g%s" % pieces["short"]
532 | if pieces["dirty"]:
533 | rendered += ".dirty"
534 | return rendered
535 |
536 |
537 | def render_pep440_old(pieces):
538 | """TAG[.postDISTANCE[.dev0]] .
539 |
540 | The ".dev0" means dirty.
541 |
542 | Exceptions:
543 | 1: no tags. 0.postDISTANCE[.dev0]
544 | """
545 | if pieces["closest-tag"]:
546 | rendered = pieces["closest-tag"]
547 | if pieces["distance"] or pieces["dirty"]:
548 | rendered += ".post%d" % pieces["distance"]
549 | if pieces["dirty"]:
550 | rendered += ".dev0"
551 | else:
552 | # exception #1
553 | rendered = "0.post%d" % pieces["distance"]
554 | if pieces["dirty"]:
555 | rendered += ".dev0"
556 | return rendered
557 |
558 |
559 | def render_git_describe(pieces):
560 | """TAG[-DISTANCE-gHEX][-dirty].
561 |
562 | Like 'git describe --tags --dirty --always'.
563 |
564 | Exceptions:
565 | 1: no tags. HEX[-dirty] (note: no 'g' prefix)
566 | """
567 | if pieces["closest-tag"]:
568 | rendered = pieces["closest-tag"]
569 | if pieces["distance"]:
570 | rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
571 | else:
572 | # exception #1
573 | rendered = pieces["short"]
574 | if pieces["dirty"]:
575 | rendered += "-dirty"
576 | return rendered
577 |
578 |
579 | def render_git_describe_long(pieces):
580 | """TAG-DISTANCE-gHEX[-dirty].
581 |
582 | Like 'git describe --tags --dirty --always -long'.
583 | The distance/hash is unconditional.
584 |
585 | Exceptions:
586 | 1: no tags. HEX[-dirty] (note: no 'g' prefix)
587 | """
588 | if pieces["closest-tag"]:
589 | rendered = pieces["closest-tag"]
590 | rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
591 | else:
592 | # exception #1
593 | rendered = pieces["short"]
594 | if pieces["dirty"]:
595 | rendered += "-dirty"
596 | return rendered
597 |
598 |
599 | def render(pieces, style):
600 | """Render the given version pieces into the requested style."""
601 | if pieces["error"]:
602 | return {
603 | "version": "unknown",
604 | "full-revisionid": pieces.get("long"),
605 | "dirty": None,
606 | "error": pieces["error"],
607 | "date": None,
608 | }
609 |
610 | if not style or style == "default":
611 | style = "pep440" # the default
612 |
613 | if style == "pep440":
614 | rendered = render_pep440(pieces)
615 | elif style == "pep440-branch":
616 | rendered = render_pep440_branch(pieces)
617 | elif style == "pep440-pre":
618 | rendered = render_pep440_pre(pieces)
619 | elif style == "pep440-post":
620 | rendered = render_pep440_post(pieces)
621 | elif style == "pep440-post-branch":
622 | rendered = render_pep440_post_branch(pieces)
623 | elif style == "pep440-old":
624 | rendered = render_pep440_old(pieces)
625 | elif style == "git-describe":
626 | rendered = render_git_describe(pieces)
627 | elif style == "git-describe-long":
628 | rendered = render_git_describe_long(pieces)
629 | else:
630 | raise ValueError("unknown style '%s'" % style)
631 |
632 | return {
633 | "version": rendered,
634 | "full-revisionid": pieces["long"],
635 | "dirty": pieces["dirty"],
636 | "error": None,
637 | "date": pieces.get("date"),
638 | }
639 |
640 |
641 | def get_versions():
642 | """Get version information or return default if unable to do so."""
643 | # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
644 | # __file__, we can work backwards from there to the root. Some
645 | # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
646 | # case we can only use expanded keywords.
647 |
648 | cfg = get_config()
649 | verbose = cfg.verbose
650 |
651 | try:
652 | return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose)
653 | except NotThisMethod:
654 | pass
655 |
656 | try:
657 | root = os.path.realpath(__file__)
658 | # versionfile_source is the relative path from the top of the source
659 | # tree (where the .git directory might live) to this file. Invert
660 | # this to find the root from __file__.
661 | for _ in cfg.versionfile_source.split("/"):
662 | root = os.path.dirname(root)
663 | except NameError:
664 | return {
665 | "version": "0+unknown",
666 | "full-revisionid": None,
667 | "dirty": None,
668 | "error": "unable to find root of source tree",
669 | "date": None,
670 | }
671 |
672 | try:
673 | pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)
674 | return render(pieces, cfg.style)
675 | except NotThisMethod:
676 | pass
677 |
678 | try:
679 | if cfg.parentdir_prefix:
680 | return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
681 | except NotThisMethod:
682 | pass
683 |
684 | return {
685 | "version": "0+unknown",
686 | "full-revisionid": None,
687 | "dirty": None,
688 | "error": "unable to compute version",
689 | "date": None,
690 | }
691 |
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/versioneer.py:
--------------------------------------------------------------------------------
1 | # Version: 0.28
2 |
3 | """The Versioneer - like a rocketeer, but for versions.
4 |
5 | The Versioneer
6 | ==============
7 |
8 | * like a rocketeer, but for versions!
9 | * https://github.com/python-versioneer/python-versioneer
10 | * Brian Warner
11 | * License: Public Domain (Unlicense)
12 | * Compatible with: Python 3.7, 3.8, 3.9, 3.10 and pypy3
13 | * [![Latest Version][pypi-image]][pypi-url]
14 | * [![Build Status][travis-image]][travis-url]
15 |
16 | This is a tool for managing a recorded version number in setuptools-based
17 | python projects. The goal is to remove the tedious and error-prone "update
18 | the embedded version string" step from your release process. Making a new
19 | release should be as easy as recording a new tag in your version-control
20 | system, and maybe making new tarballs.
21 |
22 |
23 | ## Quick Install
24 |
25 | Versioneer provides two installation modes. The "classic" vendored mode installs
26 | a copy of versioneer into your repository. The experimental build-time dependency mode
27 | is intended to allow you to skip this step and simplify the process of upgrading.
28 |
29 | ### Vendored mode
30 |
31 | * `pip install versioneer` to somewhere in your $PATH
32 | * A [conda-forge recipe](https://github.com/conda-forge/versioneer-feedstock) is
33 | available, so you can also use `conda install -c conda-forge versioneer`
34 | * add a `[tool.versioneer]` section to your `pyproject.toml` or a
35 | `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md))
36 | * Note that you will need to add `tomli; python_version < "3.11"` to your
37 | build-time dependencies if you use `pyproject.toml`
38 | * run `versioneer install --vendor` in your source tree, commit the results
39 | * verify version information with `python setup.py version`
40 |
41 | ### Build-time dependency mode
42 |
43 | * `pip install versioneer` to somewhere in your $PATH
44 | * A [conda-forge recipe](https://github.com/conda-forge/versioneer-feedstock) is
45 | available, so you can also use `conda install -c conda-forge versioneer`
46 | * add a `[tool.versioneer]` section to your `pyproject.toml` or a
47 | `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md))
48 | * add `versioneer` (with `[toml]` extra, if configuring in `pyproject.toml`)
49 | to the `requires` key of the `build-system` table in `pyproject.toml`:
50 | ```toml
51 | [build-system]
52 | requires = ["setuptools", "versioneer[toml]"]
53 | build-backend = "setuptools.build_meta"
54 | ```
55 | * run `versioneer install --no-vendor` in your source tree, commit the results
56 | * verify version information with `python setup.py version`
57 |
58 | ## Version Identifiers
59 |
60 | Source trees come from a variety of places:
61 |
62 | * a version-control system checkout (mostly used by developers)
63 | * a nightly tarball, produced by build automation
64 | * a snapshot tarball, produced by a web-based VCS browser, like github's
65 | "tarball from tag" feature
66 | * a release tarball, produced by "setup.py sdist", distributed through PyPI
67 |
68 | Within each source tree, the version identifier (either a string or a number,
69 | this tool is format-agnostic) can come from a variety of places:
70 |
71 | * ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows
72 | about recent "tags" and an absolute revision-id
73 | * the name of the directory into which the tarball was unpacked
74 | * an expanded VCS keyword ($Id$, etc)
75 | * a `_version.py` created by some earlier build step
76 |
77 | For released software, the version identifier is closely related to a VCS
78 | tag. Some projects use tag names that include more than just the version
79 | string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool
80 | needs to strip the tag prefix to extract the version identifier. For
81 | unreleased software (between tags), the version identifier should provide
82 | enough information to help developers recreate the same tree, while also
83 | giving them an idea of roughly how old the tree is (after version 1.2, before
84 | version 1.3). Many VCS systems can report a description that captures this,
85 | for example `git describe --tags --dirty --always` reports things like
86 | "0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the
87 | 0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has
88 | uncommitted changes).
89 |
90 | The version identifier is used for multiple purposes:
91 |
92 | * to allow the module to self-identify its version: `myproject.__version__`
93 | * to choose a name and prefix for a 'setup.py sdist' tarball
94 |
95 | ## Theory of Operation
96 |
97 | Versioneer works by adding a special `_version.py` file into your source
98 | tree, where your `__init__.py` can import it. This `_version.py` knows how to
99 | dynamically ask the VCS tool for version information at import time.
100 |
101 | `_version.py` also contains `$Revision$` markers, and the installation
102 | process marks `_version.py` to have this marker rewritten with a tag name
103 | during the `git archive` command. As a result, generated tarballs will
104 | contain enough information to get the proper version.
105 |
106 | To allow `setup.py` to compute a version too, a `versioneer.py` is added to
107 | the top level of your source tree, next to `setup.py` and the `setup.cfg`
108 | that configures it. This overrides several distutils/setuptools commands to
109 | compute the version when invoked, and changes `setup.py build` and `setup.py
110 | sdist` to replace `_version.py` with a small static file that contains just
111 | the generated version data.
112 |
113 | ## Installation
114 |
115 | See [INSTALL.md](./INSTALL.md) for detailed installation instructions.
116 |
117 | ## Version-String Flavors
118 |
119 | Code which uses Versioneer can learn about its version string at runtime by
120 | importing `_version` from your main `__init__.py` file and running the
121 | `get_versions()` function. From the "outside" (e.g. in `setup.py`), you can
122 | import the top-level `versioneer.py` and run `get_versions()`.
123 |
124 | Both functions return a dictionary with different flavors of version
125 | information:
126 |
127 | * `['version']`: A condensed version string, rendered using the selected
128 | style. This is the most commonly used value for the project's version
129 | string. The default "pep440" style yields strings like `0.11`,
130 | `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section
131 | below for alternative styles.
132 |
133 | * `['full-revisionid']`: detailed revision identifier. For Git, this is the
134 | full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac".
135 |
136 | * `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the
137 | commit date in ISO 8601 format. This will be None if the date is not
138 | available.
139 |
140 | * `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that
141 | this is only accurate if run in a VCS checkout, otherwise it is likely to
142 | be False or None
143 |
144 | * `['error']`: if the version string could not be computed, this will be set
145 | to a string describing the problem, otherwise it will be None. It may be
146 | useful to throw an exception in setup.py if this is set, to avoid e.g.
147 | creating tarballs with a version string of "unknown".
148 |
149 | Some variants are more useful than others. Including `full-revisionid` in a
150 | bug report should allow developers to reconstruct the exact code being tested
151 | (or indicate the presence of local changes that should be shared with the
152 | developers). `version` is suitable for display in an "about" box or a CLI
153 | `--version` output: it can be easily compared against release notes and lists
154 | of bugs fixed in various releases.
155 |
156 | The installer adds the following text to your `__init__.py` to place a basic
157 | version in `YOURPROJECT.__version__`:
158 |
159 | from ._version import get_versions
160 | __version__ = get_versions()['version']
161 | del get_versions
162 |
163 | ## Styles
164 |
165 | The setup.cfg `style=` configuration controls how the VCS information is
166 | rendered into a version string.
167 |
168 | The default style, "pep440", produces a PEP440-compliant string, equal to the
169 | un-prefixed tag name for actual releases, and containing an additional "local
170 | version" section with more detail for in-between builds. For Git, this is
171 | TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags
172 | --dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the
173 | tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and
174 | that this commit is two revisions ("+2") beyond the "0.11" tag. For released
175 | software (exactly equal to a known tag), the identifier will only contain the
176 | stripped tag, e.g. "0.11".
177 |
178 | Other styles are available. See [details.md](details.md) in the Versioneer
179 | source tree for descriptions.
180 |
181 | ## Debugging
182 |
183 | Versioneer tries to avoid fatal errors: if something goes wrong, it will tend
184 | to return a version of "0+unknown". To investigate the problem, run `setup.py
185 | version`, which will run the version-lookup code in a verbose mode, and will
186 | display the full contents of `get_versions()` (including the `error` string,
187 | which may help identify what went wrong).
188 |
189 | ## Known Limitations
190 |
191 | Some situations are known to cause problems for Versioneer. This details the
192 | most significant ones. More can be found on Github
193 | [issues page](https://github.com/python-versioneer/python-versioneer/issues).
194 |
195 | ### Subprojects
196 |
197 | Versioneer has limited support for source trees in which `setup.py` is not in
198 | the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are
199 | two common reasons why `setup.py` might not be in the root:
200 |
201 | * Source trees which contain multiple subprojects, such as
202 | [Buildbot](https://github.com/buildbot/buildbot), which contains both
203 | "master" and "slave" subprojects, each with their own `setup.py`,
204 | `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI
205 | distributions (and upload multiple independently-installable tarballs).
206 | * Source trees whose main purpose is to contain a C library, but which also
207 | provide bindings to Python (and perhaps other languages) in subdirectories.
208 |
209 | Versioneer will look for `.git` in parent directories, and most operations
210 | should get the right version string. However `pip` and `setuptools` have bugs
211 | and implementation details which frequently cause `pip install .` from a
212 | subproject directory to fail to find a correct version string (so it usually
213 | defaults to `0+unknown`).
214 |
215 | `pip install --editable .` should work correctly. `setup.py install` might
216 | work too.
217 |
218 | Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in
219 | some later version.
220 |
221 | [Bug #38](https://github.com/python-versioneer/python-versioneer/issues/38) is tracking
222 | this issue. The discussion in
223 | [PR #61](https://github.com/python-versioneer/python-versioneer/pull/61) describes the
224 | issue from the Versioneer side in more detail.
225 | [pip PR#3176](https://github.com/pypa/pip/pull/3176) and
226 | [pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve
227 | pip to let Versioneer work correctly.
228 |
229 | Versioneer-0.16 and earlier only looked for a `.git` directory next to the
230 | `setup.cfg`, so subprojects were completely unsupported with those releases.
231 |
232 | ### Editable installs with setuptools <= 18.5
233 |
234 | `setup.py develop` and `pip install --editable .` allow you to install a
235 | project into a virtualenv once, then continue editing the source code (and
236 | test) without re-installing after every change.
237 |
238 | "Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a
239 | convenient way to specify executable scripts that should be installed along
240 | with the python package.
241 |
242 | These both work as expected when using modern setuptools. When using
243 | setuptools-18.5 or earlier, however, certain operations will cause
244 | `pkg_resources.DistributionNotFound` errors when running the entrypoint
245 | script, which must be resolved by re-installing the package. This happens
246 | when the install happens with one version, then the egg_info data is
247 | regenerated while a different version is checked out. Many setup.py commands
248 | cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into
249 | a different virtualenv), so this can be surprising.
250 |
251 | [Bug #83](https://github.com/python-versioneer/python-versioneer/issues/83) describes
252 | this one, but upgrading to a newer version of setuptools should probably
253 | resolve it.
254 |
255 |
256 | ## Updating Versioneer
257 |
258 | To upgrade your project to a new release of Versioneer, do the following:
259 |
260 | * install the new Versioneer (`pip install -U versioneer` or equivalent)
261 | * edit `setup.cfg` and `pyproject.toml`, if necessary,
262 | to include any new configuration settings indicated by the release notes.
263 | See [UPGRADING](./UPGRADING.md) for details.
264 | * re-run `versioneer install --[no-]vendor` in your source tree, to replace
265 | `SRC/_version.py`
266 | * commit any changed files
267 |
268 | ## Future Directions
269 |
270 | This tool is designed to make it easily extended to other version-control
271 | systems: all VCS-specific components are in separate directories like
272 | src/git/ . The top-level `versioneer.py` script is assembled from these
273 | components by running make-versioneer.py . In the future, make-versioneer.py
274 | will take a VCS name as an argument, and will construct a version of
275 | `versioneer.py` that is specific to the given VCS. It might also take the
276 | configuration arguments that are currently provided manually during
277 | installation by editing setup.py . Alternatively, it might go the other
278 | direction and include code from all supported VCS systems, reducing the
279 | number of intermediate scripts.
280 |
281 | ## Similar projects
282 |
283 | * [setuptools_scm](https://github.com/pypa/setuptools_scm/) - a non-vendored build-time
284 | dependency
285 | * [minver](https://github.com/jbweston/miniver) - a lightweight reimplementation of
286 | versioneer
287 | * [versioningit](https://github.com/jwodder/versioningit) - a PEP 518-based setuptools
288 | plugin
289 |
290 | ## License
291 |
292 | To make Versioneer easier to embed, all its code is dedicated to the public
293 | domain. The `_version.py` that it creates is also in the public domain.
294 | Specifically, both are released under the "Unlicense", as described in
295 | https://unlicense.org/.
296 |
297 | [pypi-image]: https://img.shields.io/pypi/v/versioneer.svg
298 | [pypi-url]: https://pypi.python.org/pypi/versioneer/
299 | [travis-image]:
300 | https://img.shields.io/travis/com/python-versioneer/python-versioneer.svg
301 | [travis-url]: https://travis-ci.com/github/python-versioneer/python-versioneer
302 |
303 | """
304 | # pylint:disable=invalid-name,import-outside-toplevel,missing-function-docstring
305 | # pylint:disable=missing-class-docstring,too-many-branches,too-many-statements
306 | # pylint:disable=raise-missing-from,too-many-lines,too-many-locals,import-error
307 | # pylint:disable=too-few-public-methods,redefined-outer-name,consider-using-with
308 | # pylint:disable=attribute-defined-outside-init,too-many-arguments
309 |
310 | import configparser
311 | import errno
312 | import json
313 | import os
314 | import re
315 | import subprocess
316 | import sys
317 | from pathlib import Path
318 | from typing import Callable, Dict
319 | import functools
320 |
321 | have_tomllib = True
322 | if sys.version_info >= (3, 11):
323 | import tomllib
324 | else:
325 | try:
326 | import tomli as tomllib
327 | except ImportError:
328 | have_tomllib = False
329 |
330 |
331 | class VersioneerConfig:
332 | """Container for Versioneer configuration parameters."""
333 |
334 |
335 | def get_root():
336 | """Get the project root directory.
337 |
338 | We require that all commands are run from the project root, i.e. the
339 | directory that contains setup.py, setup.cfg, and versioneer.py .
340 | """
341 | root = os.path.realpath(os.path.abspath(os.getcwd()))
342 | setup_py = os.path.join(root, "setup.py")
343 | versioneer_py = os.path.join(root, "versioneer.py")
344 | if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):
345 | # allow 'python path/to/setup.py COMMAND'
346 | root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0])))
347 | setup_py = os.path.join(root, "setup.py")
348 | versioneer_py = os.path.join(root, "versioneer.py")
349 | if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):
350 | err = (
351 | "Versioneer was unable to run the project root directory. "
352 | "Versioneer requires setup.py to be executed from "
353 | "its immediate directory (like 'python setup.py COMMAND'), "
354 | "or in a way that lets it use sys.argv[0] to find the root "
355 | "(like 'python path/to/setup.py COMMAND')."
356 | )
357 | raise VersioneerBadRootError(err)
358 | try:
359 | # Certain runtime workflows (setup.py install/develop in a setuptools
360 | # tree) execute all dependencies in a single python process, so
361 | # "versioneer" may be imported multiple times, and python's shared
362 | # module-import table will cache the first one. So we can't use
363 | # os.path.dirname(__file__), as that will find whichever
364 | # versioneer.py was first imported, even in later projects.
365 | my_path = os.path.realpath(os.path.abspath(__file__))
366 | me_dir = os.path.normcase(os.path.splitext(my_path)[0])
367 | vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0])
368 | if me_dir != vsr_dir and "VERSIONEER_PEP518" not in globals():
369 | print("Warning: build in %s is using versioneer.py from %s" % (os.path.dirname(my_path), versioneer_py))
370 | except NameError:
371 | pass
372 | return root
373 |
374 |
375 | def get_config_from_root(root):
376 | """Read the project setup.cfg file to determine Versioneer config."""
377 | # This might raise OSError (if setup.cfg is missing), or
378 | # configparser.NoSectionError (if it lacks a [versioneer] section), or
379 | # configparser.NoOptionError (if it lacks "VCS="). See the docstring at
380 | # the top of versioneer.py for instructions on writing your setup.cfg .
381 | root = Path(root)
382 | pyproject_toml = root / "pyproject.toml"
383 | setup_cfg = root / "setup.cfg"
384 | section = None
385 | if pyproject_toml.exists() and have_tomllib:
386 | try:
387 | with open(pyproject_toml, "rb") as fobj:
388 | pp = tomllib.load(fobj)
389 | section = pp["tool"]["versioneer"]
390 | except (tomllib.TOMLDecodeError, KeyError):
391 | pass
392 | if not section:
393 | parser = configparser.ConfigParser()
394 | with open(setup_cfg) as cfg_file:
395 | parser.read_file(cfg_file)
396 | parser.get("versioneer", "VCS") # raise error if missing
397 |
398 | section = parser["versioneer"]
399 |
400 | cfg = VersioneerConfig()
401 | cfg.VCS = section["VCS"]
402 | cfg.style = section.get("style", "")
403 | cfg.versionfile_source = section.get("versionfile_source")
404 | cfg.versionfile_build = section.get("versionfile_build")
405 | cfg.tag_prefix = section.get("tag_prefix")
406 | if cfg.tag_prefix in ("''", '""', None):
407 | cfg.tag_prefix = ""
408 | cfg.parentdir_prefix = section.get("parentdir_prefix")
409 | cfg.verbose = section.get("verbose")
410 | return cfg
411 |
412 |
413 | class NotThisMethod(Exception):
414 | """Exception raised if a method is not valid for the current scenario."""
415 |
416 |
417 | # these dictionaries contain VCS-specific tools
418 | LONG_VERSION_PY: Dict[str, str] = {}
419 | HANDLERS: Dict[str, Dict[str, Callable]] = {}
420 |
421 |
422 | def register_vcs_handler(vcs, method): # decorator
423 | """Create decorator to mark a method as the handler of a VCS."""
424 |
425 | def decorate(f):
426 | """Store f in HANDLERS[vcs][method]."""
427 | HANDLERS.setdefault(vcs, {})[method] = f
428 | return f
429 |
430 | return decorate
431 |
432 |
433 | def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None):
434 | """Call the given command(s)."""
435 | assert isinstance(commands, list)
436 | process = None
437 |
438 | popen_kwargs = {}
439 | if sys.platform == "win32":
440 | # This hides the console window if pythonw.exe is used
441 | startupinfo = subprocess.STARTUPINFO()
442 | startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
443 | popen_kwargs["startupinfo"] = startupinfo
444 |
445 | for command in commands:
446 | try:
447 | dispcmd = str([command] + args)
448 | # remember shell=False, so use git.cmd on windows, not just git
449 | process = subprocess.Popen(
450 | [command] + args,
451 | cwd=cwd,
452 | env=env,
453 | stdout=subprocess.PIPE,
454 | stderr=(subprocess.PIPE if hide_stderr else None),
455 | **popen_kwargs,
456 | )
457 | break
458 | except OSError:
459 | e = sys.exc_info()[1]
460 | if e.errno == errno.ENOENT:
461 | continue
462 | if verbose:
463 | print("unable to run %s" % dispcmd)
464 | print(e)
465 | return None, None
466 | else:
467 | if verbose:
468 | print("unable to find command, tried %s" % (commands,))
469 | return None, None
470 | stdout = process.communicate()[0].strip().decode()
471 | if process.returncode != 0:
472 | if verbose:
473 | print("unable to run %s (error)" % dispcmd)
474 | print("stdout was %s" % stdout)
475 | return None, process.returncode
476 | return stdout, process.returncode
477 |
478 |
479 | LONG_VERSION_PY[
480 | "git"
481 | ] = r'''
482 | # This file helps to compute a version number in source trees obtained from
483 | # git-archive tarball (such as those provided by githubs download-from-tag
484 | # feature). Distribution tarballs (built by setup.py sdist) and build
485 | # directories (produced by setup.py build) will contain a much shorter file
486 | # that just contains the computed version number.
487 |
488 | # This file is released into the public domain.
489 | # Generated by versioneer-0.28
490 | # https://github.com/python-versioneer/python-versioneer
491 |
492 | """Git implementation of _version.py."""
493 |
494 | import errno
495 | import os
496 | import re
497 | import subprocess
498 | import sys
499 | from typing import Callable, Dict
500 | import functools
501 |
502 |
503 | def get_keywords():
504 | """Get the keywords needed to look up the version information."""
505 | # these strings will be replaced by git during git-archive.
506 | # setup.py/versioneer.py will grep for the variable names, so they must
507 | # each be defined on a line of their own. _version.py will just call
508 | # get_keywords().
509 | git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s"
510 | git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s"
511 | git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s"
512 | keywords = {"refnames": git_refnames, "full": git_full, "date": git_date}
513 | return keywords
514 |
515 |
516 | class VersioneerConfig:
517 | """Container for Versioneer configuration parameters."""
518 |
519 |
520 | def get_config():
521 | """Create, populate and return the VersioneerConfig() object."""
522 | # these strings are filled in when 'setup.py versioneer' creates
523 | # _version.py
524 | cfg = VersioneerConfig()
525 | cfg.VCS = "git"
526 | cfg.style = "%(STYLE)s"
527 | cfg.tag_prefix = "%(TAG_PREFIX)s"
528 | cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s"
529 | cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s"
530 | cfg.verbose = False
531 | return cfg
532 |
533 |
534 | class NotThisMethod(Exception):
535 | """Exception raised if a method is not valid for the current scenario."""
536 |
537 |
538 | LONG_VERSION_PY: Dict[str, str] = {}
539 | HANDLERS: Dict[str, Dict[str, Callable]] = {}
540 |
541 |
542 | def register_vcs_handler(vcs, method): # decorator
543 | """Create decorator to mark a method as the handler of a VCS."""
544 | def decorate(f):
545 | """Store f in HANDLERS[vcs][method]."""
546 | if vcs not in HANDLERS:
547 | HANDLERS[vcs] = {}
548 | HANDLERS[vcs][method] = f
549 | return f
550 | return decorate
551 |
552 |
553 | def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
554 | env=None):
555 | """Call the given command(s)."""
556 | assert isinstance(commands, list)
557 | process = None
558 |
559 | popen_kwargs = {}
560 | if sys.platform == "win32":
561 | # This hides the console window if pythonw.exe is used
562 | startupinfo = subprocess.STARTUPINFO()
563 | startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
564 | popen_kwargs["startupinfo"] = startupinfo
565 |
566 | for command in commands:
567 | try:
568 | dispcmd = str([command] + args)
569 | # remember shell=False, so use git.cmd on windows, not just git
570 | process = subprocess.Popen([command] + args, cwd=cwd, env=env,
571 | stdout=subprocess.PIPE,
572 | stderr=(subprocess.PIPE if hide_stderr
573 | else None), **popen_kwargs)
574 | break
575 | except OSError:
576 | e = sys.exc_info()[1]
577 | if e.errno == errno.ENOENT:
578 | continue
579 | if verbose:
580 | print("unable to run %%s" %% dispcmd)
581 | print(e)
582 | return None, None
583 | else:
584 | if verbose:
585 | print("unable to find command, tried %%s" %% (commands,))
586 | return None, None
587 | stdout = process.communicate()[0].strip().decode()
588 | if process.returncode != 0:
589 | if verbose:
590 | print("unable to run %%s (error)" %% dispcmd)
591 | print("stdout was %%s" %% stdout)
592 | return None, process.returncode
593 | return stdout, process.returncode
594 |
595 |
596 | def versions_from_parentdir(parentdir_prefix, root, verbose):
597 | """Try to determine the version from the parent directory name.
598 |
599 | Source tarballs conventionally unpack into a directory that includes both
600 | the project name and a version string. We will also support searching up
601 | two directory levels for an appropriately named parent directory
602 | """
603 | rootdirs = []
604 |
605 | for _ in range(3):
606 | dirname = os.path.basename(root)
607 | if dirname.startswith(parentdir_prefix):
608 | return {"version": dirname[len(parentdir_prefix):],
609 | "full-revisionid": None,
610 | "dirty": False, "error": None, "date": None}
611 | rootdirs.append(root)
612 | root = os.path.dirname(root) # up a level
613 |
614 | if verbose:
615 | print("Tried directories %%s but none started with prefix %%s" %%
616 | (str(rootdirs), parentdir_prefix))
617 | raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
618 |
619 |
620 | @register_vcs_handler("git", "get_keywords")
621 | def git_get_keywords(versionfile_abs):
622 | """Extract version information from the given file."""
623 | # the code embedded in _version.py can just fetch the value of these
624 | # keywords. When used from setup.py, we don't want to import _version.py,
625 | # so we do it with a regexp instead. This function is not used from
626 | # _version.py.
627 | keywords = {}
628 | try:
629 | with open(versionfile_abs, "r") as fobj:
630 | for line in fobj:
631 | if line.strip().startswith("git_refnames ="):
632 | mo = re.search(r'=\s*"(.*)"', line)
633 | if mo:
634 | keywords["refnames"] = mo.group(1)
635 | if line.strip().startswith("git_full ="):
636 | mo = re.search(r'=\s*"(.*)"', line)
637 | if mo:
638 | keywords["full"] = mo.group(1)
639 | if line.strip().startswith("git_date ="):
640 | mo = re.search(r'=\s*"(.*)"', line)
641 | if mo:
642 | keywords["date"] = mo.group(1)
643 | except OSError:
644 | pass
645 | return keywords
646 |
647 |
648 | @register_vcs_handler("git", "keywords")
649 | def git_versions_from_keywords(keywords, tag_prefix, verbose):
650 | """Get version information from git keywords."""
651 | if "refnames" not in keywords:
652 | raise NotThisMethod("Short version file found")
653 | date = keywords.get("date")
654 | if date is not None:
655 | # Use only the last line. Previous lines may contain GPG signature
656 | # information.
657 | date = date.splitlines()[-1]
658 |
659 | # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant
660 | # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601
661 | # -like" string, which we must then edit to make compliant), because
662 | # it's been around since git-1.5.3, and it's too difficult to
663 | # discover which version we're using, or to work around using an
664 | # older one.
665 | date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
666 | refnames = keywords["refnames"].strip()
667 | if refnames.startswith("$Format"):
668 | if verbose:
669 | print("keywords are unexpanded, not using")
670 | raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
671 | refs = {r.strip() for r in refnames.strip("()").split(",")}
672 | # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
673 | # just "foo-1.0". If we see a "tag: " prefix, prefer those.
674 | TAG = "tag: "
675 | tags = {r[len(TAG):] for r in refs if r.startswith(TAG)}
676 | if not tags:
677 | # Either we're using git < 1.8.3, or there really are no tags. We use
678 | # a heuristic: assume all version tags have a digit. The old git %%d
679 | # expansion behaves like git log --decorate=short and strips out the
680 | # refs/heads/ and refs/tags/ prefixes that would let us distinguish
681 | # between branches and tags. By ignoring refnames without digits, we
682 | # filter out many common branch names like "release" and
683 | # "stabilization", as well as "HEAD" and "master".
684 | tags = {r for r in refs if re.search(r'\d', r)}
685 | if verbose:
686 | print("discarding '%%s', no digits" %% ",".join(refs - tags))
687 | if verbose:
688 | print("likely tags: %%s" %% ",".join(sorted(tags)))
689 | for ref in sorted(tags):
690 | # sorting will prefer e.g. "2.0" over "2.0rc1"
691 | if ref.startswith(tag_prefix):
692 | r = ref[len(tag_prefix):]
693 | # Filter out refs that exactly match prefix or that don't start
694 | # with a number once the prefix is stripped (mostly a concern
695 | # when prefix is '')
696 | if not re.match(r'\d', r):
697 | continue
698 | if verbose:
699 | print("picking %%s" %% r)
700 | return {"version": r,
701 | "full-revisionid": keywords["full"].strip(),
702 | "dirty": False, "error": None,
703 | "date": date}
704 | # no suitable tags, so version is "0+unknown", but full hex is still there
705 | if verbose:
706 | print("no suitable tags, using unknown + full revision id")
707 | return {"version": "0+unknown",
708 | "full-revisionid": keywords["full"].strip(),
709 | "dirty": False, "error": "no suitable tags", "date": None}
710 |
711 |
712 | @register_vcs_handler("git", "pieces_from_vcs")
713 | def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command):
714 | """Get version from 'git describe' in the root of the source tree.
715 |
716 | This only gets called if the git-archive 'subst' keywords were *not*
717 | expanded, and _version.py hasn't already been rewritten with a short
718 | version string, meaning we're inside a checked out source tree.
719 | """
720 | GITS = ["git"]
721 | if sys.platform == "win32":
722 | GITS = ["git.cmd", "git.exe"]
723 |
724 | # GIT_DIR can interfere with correct operation of Versioneer.
725 | # It may be intended to be passed to the Versioneer-versioned project,
726 | # but that should not change where we get our version from.
727 | env = os.environ.copy()
728 | env.pop("GIT_DIR", None)
729 | runner = functools.partial(runner, env=env)
730 |
731 | _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root,
732 | hide_stderr=not verbose)
733 | if rc != 0:
734 | if verbose:
735 | print("Directory %%s not under git control" %% root)
736 | raise NotThisMethod("'git rev-parse --git-dir' returned error")
737 |
738 | # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
739 | # if there isn't one, this yields HEX[-dirty] (no NUM)
740 | describe_out, rc = runner(GITS, [
741 | "describe", "--tags", "--dirty", "--always", "--long",
742 | "--match", f"{tag_prefix}[[:digit:]]*"
743 | ], cwd=root)
744 | # --long was added in git-1.5.5
745 | if describe_out is None:
746 | raise NotThisMethod("'git describe' failed")
747 | describe_out = describe_out.strip()
748 | full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root)
749 | if full_out is None:
750 | raise NotThisMethod("'git rev-parse' failed")
751 | full_out = full_out.strip()
752 |
753 | pieces = {}
754 | pieces["long"] = full_out
755 | pieces["short"] = full_out[:7] # maybe improved later
756 | pieces["error"] = None
757 |
758 | branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
759 | cwd=root)
760 | # --abbrev-ref was added in git-1.6.3
761 | if rc != 0 or branch_name is None:
762 | raise NotThisMethod("'git rev-parse --abbrev-ref' returned error")
763 | branch_name = branch_name.strip()
764 |
765 | if branch_name == "HEAD":
766 | # If we aren't exactly on a branch, pick a branch which represents
767 | # the current commit. If all else fails, we are on a branchless
768 | # commit.
769 | branches, rc = runner(GITS, ["branch", "--contains"], cwd=root)
770 | # --contains was added in git-1.5.4
771 | if rc != 0 or branches is None:
772 | raise NotThisMethod("'git branch --contains' returned error")
773 | branches = branches.split("\n")
774 |
775 | # Remove the first line if we're running detached
776 | if "(" in branches[0]:
777 | branches.pop(0)
778 |
779 | # Strip off the leading "* " from the list of branches.
780 | branches = [branch[2:] for branch in branches]
781 | if "master" in branches:
782 | branch_name = "master"
783 | elif not branches:
784 | branch_name = None
785 | else:
786 | # Pick the first branch that is returned. Good or bad.
787 | branch_name = branches[0]
788 |
789 | pieces["branch"] = branch_name
790 |
791 | # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
792 | # TAG might have hyphens.
793 | git_describe = describe_out
794 |
795 | # look for -dirty suffix
796 | dirty = git_describe.endswith("-dirty")
797 | pieces["dirty"] = dirty
798 | if dirty:
799 | git_describe = git_describe[:git_describe.rindex("-dirty")]
800 |
801 | # now we have TAG-NUM-gHEX or HEX
802 |
803 | if "-" in git_describe:
804 | # TAG-NUM-gHEX
805 | mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
806 | if not mo:
807 | # unparsable. Maybe git-describe is misbehaving?
808 | pieces["error"] = ("unable to parse git-describe output: '%%s'"
809 | %% describe_out)
810 | return pieces
811 |
812 | # tag
813 | full_tag = mo.group(1)
814 | if not full_tag.startswith(tag_prefix):
815 | if verbose:
816 | fmt = "tag '%%s' doesn't start with prefix '%%s'"
817 | print(fmt %% (full_tag, tag_prefix))
818 | pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'"
819 | %% (full_tag, tag_prefix))
820 | return pieces
821 | pieces["closest-tag"] = full_tag[len(tag_prefix):]
822 |
823 | # distance: number of commits since tag
824 | pieces["distance"] = int(mo.group(2))
825 |
826 | # commit: short hex revision ID
827 | pieces["short"] = mo.group(3)
828 |
829 | else:
830 | # HEX: no tags
831 | pieces["closest-tag"] = None
832 | out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root)
833 | pieces["distance"] = len(out.split()) # total number of commits
834 |
835 | # commit date: see ISO-8601 comment in git_versions_from_keywords()
836 | date = runner(GITS, ["show", "-s", "--format=%%ci", "HEAD"], cwd=root)[0].strip()
837 | # Use only the last line. Previous lines may contain GPG signature
838 | # information.
839 | date = date.splitlines()[-1]
840 | pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
841 |
842 | return pieces
843 |
844 |
845 | def plus_or_dot(pieces):
846 | """Return a + if we don't already have one, else return a ."""
847 | if "+" in pieces.get("closest-tag", ""):
848 | return "."
849 | return "+"
850 |
851 |
852 | def render_pep440(pieces):
853 | """Build up version string, with post-release "local version identifier".
854 |
855 | Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
856 | get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
857 |
858 | Exceptions:
859 | 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
860 | """
861 | if pieces["closest-tag"]:
862 | rendered = pieces["closest-tag"]
863 | if pieces["distance"] or pieces["dirty"]:
864 | rendered += plus_or_dot(pieces)
865 | rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"])
866 | if pieces["dirty"]:
867 | rendered += ".dirty"
868 | else:
869 | # exception #1
870 | rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"],
871 | pieces["short"])
872 | if pieces["dirty"]:
873 | rendered += ".dirty"
874 | return rendered
875 |
876 |
877 | def render_pep440_branch(pieces):
878 | """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] .
879 |
880 | The ".dev0" means not master branch. Note that .dev0 sorts backwards
881 | (a feature branch will appear "older" than the master branch).
882 |
883 | Exceptions:
884 | 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty]
885 | """
886 | if pieces["closest-tag"]:
887 | rendered = pieces["closest-tag"]
888 | if pieces["distance"] or pieces["dirty"]:
889 | if pieces["branch"] != "master":
890 | rendered += ".dev0"
891 | rendered += plus_or_dot(pieces)
892 | rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"])
893 | if pieces["dirty"]:
894 | rendered += ".dirty"
895 | else:
896 | # exception #1
897 | rendered = "0"
898 | if pieces["branch"] != "master":
899 | rendered += ".dev0"
900 | rendered += "+untagged.%%d.g%%s" %% (pieces["distance"],
901 | pieces["short"])
902 | if pieces["dirty"]:
903 | rendered += ".dirty"
904 | return rendered
905 |
906 |
907 | def pep440_split_post(ver):
908 | """Split pep440 version string at the post-release segment.
909 |
910 | Returns the release segments before the post-release and the
911 | post-release version number (or -1 if no post-release segment is present).
912 | """
913 | vc = str.split(ver, ".post")
914 | return vc[0], int(vc[1] or 0) if len(vc) == 2 else None
915 |
916 |
917 | def render_pep440_pre(pieces):
918 | """TAG[.postN.devDISTANCE] -- No -dirty.
919 |
920 | Exceptions:
921 | 1: no tags. 0.post0.devDISTANCE
922 | """
923 | if pieces["closest-tag"]:
924 | if pieces["distance"]:
925 | # update the post release segment
926 | tag_version, post_version = pep440_split_post(pieces["closest-tag"])
927 | rendered = tag_version
928 | if post_version is not None:
929 | rendered += ".post%%d.dev%%d" %% (post_version + 1, pieces["distance"])
930 | else:
931 | rendered += ".post0.dev%%d" %% (pieces["distance"])
932 | else:
933 | # no commits, use the tag as the version
934 | rendered = pieces["closest-tag"]
935 | else:
936 | # exception #1
937 | rendered = "0.post0.dev%%d" %% pieces["distance"]
938 | return rendered
939 |
940 |
941 | def render_pep440_post(pieces):
942 | """TAG[.postDISTANCE[.dev0]+gHEX] .
943 |
944 | The ".dev0" means dirty. Note that .dev0 sorts backwards
945 | (a dirty tree will appear "older" than the corresponding clean one),
946 | but you shouldn't be releasing software with -dirty anyways.
947 |
948 | Exceptions:
949 | 1: no tags. 0.postDISTANCE[.dev0]
950 | """
951 | if pieces["closest-tag"]:
952 | rendered = pieces["closest-tag"]
953 | if pieces["distance"] or pieces["dirty"]:
954 | rendered += ".post%%d" %% pieces["distance"]
955 | if pieces["dirty"]:
956 | rendered += ".dev0"
957 | rendered += plus_or_dot(pieces)
958 | rendered += "g%%s" %% pieces["short"]
959 | else:
960 | # exception #1
961 | rendered = "0.post%%d" %% pieces["distance"]
962 | if pieces["dirty"]:
963 | rendered += ".dev0"
964 | rendered += "+g%%s" %% pieces["short"]
965 | return rendered
966 |
967 |
968 | def render_pep440_post_branch(pieces):
969 | """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] .
970 |
971 | The ".dev0" means not master branch.
972 |
973 | Exceptions:
974 | 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty]
975 | """
976 | if pieces["closest-tag"]:
977 | rendered = pieces["closest-tag"]
978 | if pieces["distance"] or pieces["dirty"]:
979 | rendered += ".post%%d" %% pieces["distance"]
980 | if pieces["branch"] != "master":
981 | rendered += ".dev0"
982 | rendered += plus_or_dot(pieces)
983 | rendered += "g%%s" %% pieces["short"]
984 | if pieces["dirty"]:
985 | rendered += ".dirty"
986 | else:
987 | # exception #1
988 | rendered = "0.post%%d" %% pieces["distance"]
989 | if pieces["branch"] != "master":
990 | rendered += ".dev0"
991 | rendered += "+g%%s" %% pieces["short"]
992 | if pieces["dirty"]:
993 | rendered += ".dirty"
994 | return rendered
995 |
996 |
997 | def render_pep440_old(pieces):
998 | """TAG[.postDISTANCE[.dev0]] .
999 |
1000 | The ".dev0" means dirty.
1001 |
1002 | Exceptions:
1003 | 1: no tags. 0.postDISTANCE[.dev0]
1004 | """
1005 | if pieces["closest-tag"]:
1006 | rendered = pieces["closest-tag"]
1007 | if pieces["distance"] or pieces["dirty"]:
1008 | rendered += ".post%%d" %% pieces["distance"]
1009 | if pieces["dirty"]:
1010 | rendered += ".dev0"
1011 | else:
1012 | # exception #1
1013 | rendered = "0.post%%d" %% pieces["distance"]
1014 | if pieces["dirty"]:
1015 | rendered += ".dev0"
1016 | return rendered
1017 |
1018 |
1019 | def render_git_describe(pieces):
1020 | """TAG[-DISTANCE-gHEX][-dirty].
1021 |
1022 | Like 'git describe --tags --dirty --always'.
1023 |
1024 | Exceptions:
1025 | 1: no tags. HEX[-dirty] (note: no 'g' prefix)
1026 | """
1027 | if pieces["closest-tag"]:
1028 | rendered = pieces["closest-tag"]
1029 | if pieces["distance"]:
1030 | rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"])
1031 | else:
1032 | # exception #1
1033 | rendered = pieces["short"]
1034 | if pieces["dirty"]:
1035 | rendered += "-dirty"
1036 | return rendered
1037 |
1038 |
1039 | def render_git_describe_long(pieces):
1040 | """TAG-DISTANCE-gHEX[-dirty].
1041 |
1042 | Like 'git describe --tags --dirty --always -long'.
1043 | The distance/hash is unconditional.
1044 |
1045 | Exceptions:
1046 | 1: no tags. HEX[-dirty] (note: no 'g' prefix)
1047 | """
1048 | if pieces["closest-tag"]:
1049 | rendered = pieces["closest-tag"]
1050 | rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"])
1051 | else:
1052 | # exception #1
1053 | rendered = pieces["short"]
1054 | if pieces["dirty"]:
1055 | rendered += "-dirty"
1056 | return rendered
1057 |
1058 |
1059 | def render(pieces, style):
1060 | """Render the given version pieces into the requested style."""
1061 | if pieces["error"]:
1062 | return {"version": "unknown",
1063 | "full-revisionid": pieces.get("long"),
1064 | "dirty": None,
1065 | "error": pieces["error"],
1066 | "date": None}
1067 |
1068 | if not style or style == "default":
1069 | style = "pep440" # the default
1070 |
1071 | if style == "pep440":
1072 | rendered = render_pep440(pieces)
1073 | elif style == "pep440-branch":
1074 | rendered = render_pep440_branch(pieces)
1075 | elif style == "pep440-pre":
1076 | rendered = render_pep440_pre(pieces)
1077 | elif style == "pep440-post":
1078 | rendered = render_pep440_post(pieces)
1079 | elif style == "pep440-post-branch":
1080 | rendered = render_pep440_post_branch(pieces)
1081 | elif style == "pep440-old":
1082 | rendered = render_pep440_old(pieces)
1083 | elif style == "git-describe":
1084 | rendered = render_git_describe(pieces)
1085 | elif style == "git-describe-long":
1086 | rendered = render_git_describe_long(pieces)
1087 | else:
1088 | raise ValueError("unknown style '%%s'" %% style)
1089 |
1090 | return {"version": rendered, "full-revisionid": pieces["long"],
1091 | "dirty": pieces["dirty"], "error": None,
1092 | "date": pieces.get("date")}
1093 |
1094 |
1095 | def get_versions():
1096 | """Get version information or return default if unable to do so."""
1097 | # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
1098 | # __file__, we can work backwards from there to the root. Some
1099 | # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
1100 | # case we can only use expanded keywords.
1101 |
1102 | cfg = get_config()
1103 | verbose = cfg.verbose
1104 |
1105 | try:
1106 | return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,
1107 | verbose)
1108 | except NotThisMethod:
1109 | pass
1110 |
1111 | try:
1112 | root = os.path.realpath(__file__)
1113 | # versionfile_source is the relative path from the top of the source
1114 | # tree (where the .git directory might live) to this file. Invert
1115 | # this to find the root from __file__.
1116 | for _ in cfg.versionfile_source.split('/'):
1117 | root = os.path.dirname(root)
1118 | except NameError:
1119 | return {"version": "0+unknown", "full-revisionid": None,
1120 | "dirty": None,
1121 | "error": "unable to find root of source tree",
1122 | "date": None}
1123 |
1124 | try:
1125 | pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)
1126 | return render(pieces, cfg.style)
1127 | except NotThisMethod:
1128 | pass
1129 |
1130 | try:
1131 | if cfg.parentdir_prefix:
1132 | return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
1133 | except NotThisMethod:
1134 | pass
1135 |
1136 | return {"version": "0+unknown", "full-revisionid": None,
1137 | "dirty": None,
1138 | "error": "unable to compute version", "date": None}
1139 | '''
1140 |
1141 |
1142 | @register_vcs_handler("git", "get_keywords")
1143 | def git_get_keywords(versionfile_abs):
1144 | """Extract version information from the given file."""
1145 | # the code embedded in _version.py can just fetch the value of these
1146 | # keywords. When used from setup.py, we don't want to import _version.py,
1147 | # so we do it with a regexp instead. This function is not used from
1148 | # _version.py.
1149 | keywords = {}
1150 | try:
1151 | with open(versionfile_abs, "r") as fobj:
1152 | for line in fobj:
1153 | if line.strip().startswith("git_refnames ="):
1154 | mo = re.search(r'=\s*"(.*)"', line)
1155 | if mo:
1156 | keywords["refnames"] = mo.group(1)
1157 | if line.strip().startswith("git_full ="):
1158 | mo = re.search(r'=\s*"(.*)"', line)
1159 | if mo:
1160 | keywords["full"] = mo.group(1)
1161 | if line.strip().startswith("git_date ="):
1162 | mo = re.search(r'=\s*"(.*)"', line)
1163 | if mo:
1164 | keywords["date"] = mo.group(1)
1165 | except OSError:
1166 | pass
1167 | return keywords
1168 |
1169 |
1170 | @register_vcs_handler("git", "keywords")
1171 | def git_versions_from_keywords(keywords, tag_prefix, verbose):
1172 | """Get version information from git keywords."""
1173 | if "refnames" not in keywords:
1174 | raise NotThisMethod("Short version file found")
1175 | date = keywords.get("date")
1176 | if date is not None:
1177 | # Use only the last line. Previous lines may contain GPG signature
1178 | # information.
1179 | date = date.splitlines()[-1]
1180 |
1181 | # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant
1182 | # datestamp. However we prefer "%ci" (which expands to an "ISO-8601
1183 | # -like" string, which we must then edit to make compliant), because
1184 | # it's been around since git-1.5.3, and it's too difficult to
1185 | # discover which version we're using, or to work around using an
1186 | # older one.
1187 | date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
1188 | refnames = keywords["refnames"].strip()
1189 | if refnames.startswith("$Format"):
1190 | if verbose:
1191 | print("keywords are unexpanded, not using")
1192 | raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
1193 | refs = {r.strip() for r in refnames.strip("()").split(",")}
1194 | # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
1195 | # just "foo-1.0". If we see a "tag: " prefix, prefer those.
1196 | TAG = "tag: "
1197 | tags = {r[len(TAG) :] for r in refs if r.startswith(TAG)}
1198 | if not tags:
1199 | # Either we're using git < 1.8.3, or there really are no tags. We use
1200 | # a heuristic: assume all version tags have a digit. The old git %d
1201 | # expansion behaves like git log --decorate=short and strips out the
1202 | # refs/heads/ and refs/tags/ prefixes that would let us distinguish
1203 | # between branches and tags. By ignoring refnames without digits, we
1204 | # filter out many common branch names like "release" and
1205 | # "stabilization", as well as "HEAD" and "master".
1206 | tags = {r for r in refs if re.search(r"\d", r)}
1207 | if verbose:
1208 | print("discarding '%s', no digits" % ",".join(refs - tags))
1209 | if verbose:
1210 | print("likely tags: %s" % ",".join(sorted(tags)))
1211 | for ref in sorted(tags):
1212 | # sorting will prefer e.g. "2.0" over "2.0rc1"
1213 | if ref.startswith(tag_prefix):
1214 | r = ref[len(tag_prefix) :]
1215 | # Filter out refs that exactly match prefix or that don't start
1216 | # with a number once the prefix is stripped (mostly a concern
1217 | # when prefix is '')
1218 | if not re.match(r"\d", r):
1219 | continue
1220 | if verbose:
1221 | print("picking %s" % r)
1222 | return {
1223 | "version": r,
1224 | "full-revisionid": keywords["full"].strip(),
1225 | "dirty": False,
1226 | "error": None,
1227 | "date": date,
1228 | }
1229 | # no suitable tags, so version is "0+unknown", but full hex is still there
1230 | if verbose:
1231 | print("no suitable tags, using unknown + full revision id")
1232 | return {
1233 | "version": "0+unknown",
1234 | "full-revisionid": keywords["full"].strip(),
1235 | "dirty": False,
1236 | "error": "no suitable tags",
1237 | "date": None,
1238 | }
1239 |
1240 |
1241 | @register_vcs_handler("git", "pieces_from_vcs")
1242 | def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command):
1243 | """Get version from 'git describe' in the root of the source tree.
1244 |
1245 | This only gets called if the git-archive 'subst' keywords were *not*
1246 | expanded, and _version.py hasn't already been rewritten with a short
1247 | version string, meaning we're inside a checked out source tree.
1248 | """
1249 | GITS = ["git"]
1250 | if sys.platform == "win32":
1251 | GITS = ["git.cmd", "git.exe"]
1252 |
1253 | # GIT_DIR can interfere with correct operation of Versioneer.
1254 | # It may be intended to be passed to the Versioneer-versioned project,
1255 | # but that should not change where we get our version from.
1256 | env = os.environ.copy()
1257 | env.pop("GIT_DIR", None)
1258 | runner = functools.partial(runner, env=env)
1259 |
1260 | _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=not verbose)
1261 | if rc != 0:
1262 | if verbose:
1263 | print("Directory %s not under git control" % root)
1264 | raise NotThisMethod("'git rev-parse --git-dir' returned error")
1265 |
1266 | # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
1267 | # if there isn't one, this yields HEX[-dirty] (no NUM)
1268 | describe_out, rc = runner(
1269 | GITS,
1270 | [
1271 | "describe",
1272 | "--tags",
1273 | "--dirty",
1274 | "--always",
1275 | "--long",
1276 | "--match",
1277 | f"{tag_prefix}[[:digit:]]*",
1278 | ],
1279 | cwd=root,
1280 | )
1281 | # --long was added in git-1.5.5
1282 | if describe_out is None:
1283 | raise NotThisMethod("'git describe' failed")
1284 | describe_out = describe_out.strip()
1285 | full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root)
1286 | if full_out is None:
1287 | raise NotThisMethod("'git rev-parse' failed")
1288 | full_out = full_out.strip()
1289 |
1290 | pieces = {}
1291 | pieces["long"] = full_out
1292 | pieces["short"] = full_out[:7] # maybe improved later
1293 | pieces["error"] = None
1294 |
1295 | branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root)
1296 | # --abbrev-ref was added in git-1.6.3
1297 | if rc != 0 or branch_name is None:
1298 | raise NotThisMethod("'git rev-parse --abbrev-ref' returned error")
1299 | branch_name = branch_name.strip()
1300 |
1301 | if branch_name == "HEAD":
1302 | # If we aren't exactly on a branch, pick a branch which represents
1303 | # the current commit. If all else fails, we are on a branchless
1304 | # commit.
1305 | branches, rc = runner(GITS, ["branch", "--contains"], cwd=root)
1306 | # --contains was added in git-1.5.4
1307 | if rc != 0 or branches is None:
1308 | raise NotThisMethod("'git branch --contains' returned error")
1309 | branches = branches.split("\n")
1310 |
1311 | # Remove the first line if we're running detached
1312 | if "(" in branches[0]:
1313 | branches.pop(0)
1314 |
1315 | # Strip off the leading "* " from the list of branches.
1316 | branches = [branch[2:] for branch in branches]
1317 | if "master" in branches:
1318 | branch_name = "master"
1319 | elif not branches:
1320 | branch_name = None
1321 | else:
1322 | # Pick the first branch that is returned. Good or bad.
1323 | branch_name = branches[0]
1324 |
1325 | pieces["branch"] = branch_name
1326 |
1327 | # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
1328 | # TAG might have hyphens.
1329 | git_describe = describe_out
1330 |
1331 | # look for -dirty suffix
1332 | dirty = git_describe.endswith("-dirty")
1333 | pieces["dirty"] = dirty
1334 | if dirty:
1335 | git_describe = git_describe[: git_describe.rindex("-dirty")]
1336 |
1337 | # now we have TAG-NUM-gHEX or HEX
1338 |
1339 | if "-" in git_describe:
1340 | # TAG-NUM-gHEX
1341 | mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe)
1342 | if not mo:
1343 | # unparsable. Maybe git-describe is misbehaving?
1344 | pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out
1345 | return pieces
1346 |
1347 | # tag
1348 | full_tag = mo.group(1)
1349 | if not full_tag.startswith(tag_prefix):
1350 | if verbose:
1351 | fmt = "tag '%s' doesn't start with prefix '%s'"
1352 | print(fmt % (full_tag, tag_prefix))
1353 | pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % (
1354 | full_tag,
1355 | tag_prefix,
1356 | )
1357 | return pieces
1358 | pieces["closest-tag"] = full_tag[len(tag_prefix) :]
1359 |
1360 | # distance: number of commits since tag
1361 | pieces["distance"] = int(mo.group(2))
1362 |
1363 | # commit: short hex revision ID
1364 | pieces["short"] = mo.group(3)
1365 |
1366 | else:
1367 | # HEX: no tags
1368 | pieces["closest-tag"] = None
1369 | out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root)
1370 | pieces["distance"] = len(out.split()) # total number of commits
1371 |
1372 | # commit date: see ISO-8601 comment in git_versions_from_keywords()
1373 | date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip()
1374 | # Use only the last line. Previous lines may contain GPG signature
1375 | # information.
1376 | date = date.splitlines()[-1]
1377 | pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
1378 |
1379 | return pieces
1380 |
1381 |
1382 | def do_vcs_install(versionfile_source, ipy):
1383 | """Git-specific installation logic for Versioneer.
1384 |
1385 | For Git, this means creating/changing .gitattributes to mark _version.py
1386 | for export-subst keyword substitution.
1387 | """
1388 | GITS = ["git"]
1389 | if sys.platform == "win32":
1390 | GITS = ["git.cmd", "git.exe"]
1391 | files = [versionfile_source]
1392 | if ipy:
1393 | files.append(ipy)
1394 | if "VERSIONEER_PEP518" not in globals():
1395 | try:
1396 | my_path = __file__
1397 | if my_path.endswith((".pyc", ".pyo")):
1398 | my_path = os.path.splitext(my_path)[0] + ".py"
1399 | versioneer_file = os.path.relpath(my_path)
1400 | except NameError:
1401 | versioneer_file = "versioneer.py"
1402 | files.append(versioneer_file)
1403 | present = False
1404 | try:
1405 | with open(".gitattributes", "r") as fobj:
1406 | for line in fobj:
1407 | if line.strip().startswith(versionfile_source):
1408 | if "export-subst" in line.strip().split()[1:]:
1409 | present = True
1410 | break
1411 | except OSError:
1412 | pass
1413 | if not present:
1414 | with open(".gitattributes", "a+") as fobj:
1415 | fobj.write(f"{versionfile_source} export-subst\n")
1416 | files.append(".gitattributes")
1417 | run_command(GITS, ["add", "--"] + files)
1418 |
1419 |
1420 | def versions_from_parentdir(parentdir_prefix, root, verbose):
1421 | """Try to determine the version from the parent directory name.
1422 |
1423 | Source tarballs conventionally unpack into a directory that includes both
1424 | the project name and a version string. We will also support searching up
1425 | two directory levels for an appropriately named parent directory
1426 | """
1427 | rootdirs = []
1428 |
1429 | for _ in range(3):
1430 | dirname = os.path.basename(root)
1431 | if dirname.startswith(parentdir_prefix):
1432 | return {
1433 | "version": dirname[len(parentdir_prefix) :],
1434 | "full-revisionid": None,
1435 | "dirty": False,
1436 | "error": None,
1437 | "date": None,
1438 | }
1439 | rootdirs.append(root)
1440 | root = os.path.dirname(root) # up a level
1441 |
1442 | if verbose:
1443 | print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix))
1444 | raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
1445 |
1446 |
1447 | SHORT_VERSION_PY = """
1448 | # This file was generated by 'versioneer.py' (0.28) from
1449 | # revision-control system data, or from the parent directory name of an
1450 | # unpacked source archive. Distribution tarballs contain a pre-generated copy
1451 | # of this file.
1452 |
1453 | import json
1454 |
1455 | version_json = '''
1456 | %s
1457 | ''' # END VERSION_JSON
1458 |
1459 |
1460 | def get_versions():
1461 | return json.loads(version_json)
1462 | """
1463 |
1464 |
1465 | def versions_from_file(filename):
1466 | """Try to determine the version from _version.py if present."""
1467 | try:
1468 | with open(filename) as f:
1469 | contents = f.read()
1470 | except OSError:
1471 | raise NotThisMethod("unable to read _version.py")
1472 | mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", contents, re.M | re.S)
1473 | if not mo:
1474 | mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", contents, re.M | re.S)
1475 | if not mo:
1476 | raise NotThisMethod("no version_json in _version.py")
1477 | return json.loads(mo.group(1))
1478 |
1479 |
1480 | def write_to_version_file(filename, versions):
1481 | """Write the given version number to the given _version.py file."""
1482 | os.unlink(filename)
1483 | contents = json.dumps(versions, sort_keys=True, indent=1, separators=(",", ": "))
1484 | with open(filename, "w") as f:
1485 | f.write(SHORT_VERSION_PY % contents)
1486 |
1487 | print("set %s to '%s'" % (filename, versions["version"]))
1488 |
1489 |
1490 | def plus_or_dot(pieces):
1491 | """Return a + if we don't already have one, else return a ."""
1492 | if "+" in pieces.get("closest-tag", ""):
1493 | return "."
1494 | return "+"
1495 |
1496 |
1497 | def render_pep440(pieces):
1498 | """Build up version string, with post-release "local version identifier".
1499 |
1500 | Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
1501 | get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
1502 |
1503 | Exceptions:
1504 | 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
1505 | """
1506 | if pieces["closest-tag"]:
1507 | rendered = pieces["closest-tag"]
1508 | if pieces["distance"] or pieces["dirty"]:
1509 | rendered += plus_or_dot(pieces)
1510 | rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
1511 | if pieces["dirty"]:
1512 | rendered += ".dirty"
1513 | else:
1514 | # exception #1
1515 | rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
1516 | if pieces["dirty"]:
1517 | rendered += ".dirty"
1518 | return rendered
1519 |
1520 |
1521 | def render_pep440_branch(pieces):
1522 | """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] .
1523 |
1524 | The ".dev0" means not master branch. Note that .dev0 sorts backwards
1525 | (a feature branch will appear "older" than the master branch).
1526 |
1527 | Exceptions:
1528 | 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty]
1529 | """
1530 | if pieces["closest-tag"]:
1531 | rendered = pieces["closest-tag"]
1532 | if pieces["distance"] or pieces["dirty"]:
1533 | if pieces["branch"] != "master":
1534 | rendered += ".dev0"
1535 | rendered += plus_or_dot(pieces)
1536 | rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
1537 | if pieces["dirty"]:
1538 | rendered += ".dirty"
1539 | else:
1540 | # exception #1
1541 | rendered = "0"
1542 | if pieces["branch"] != "master":
1543 | rendered += ".dev0"
1544 | rendered += "+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
1545 | if pieces["dirty"]:
1546 | rendered += ".dirty"
1547 | return rendered
1548 |
1549 |
1550 | def pep440_split_post(ver):
1551 | """Split pep440 version string at the post-release segment.
1552 |
1553 | Returns the release segments before the post-release and the
1554 | post-release version number (or -1 if no post-release segment is present).
1555 | """
1556 | vc = str.split(ver, ".post")
1557 | return vc[0], int(vc[1] or 0) if len(vc) == 2 else None
1558 |
1559 |
1560 | def render_pep440_pre(pieces):
1561 | """TAG[.postN.devDISTANCE] -- No -dirty.
1562 |
1563 | Exceptions:
1564 | 1: no tags. 0.post0.devDISTANCE
1565 | """
1566 | if pieces["closest-tag"]:
1567 | if pieces["distance"]:
1568 | # update the post release segment
1569 | tag_version, post_version = pep440_split_post(pieces["closest-tag"])
1570 | rendered = tag_version
1571 | if post_version is not None:
1572 | rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"])
1573 | else:
1574 | rendered += ".post0.dev%d" % (pieces["distance"])
1575 | else:
1576 | # no commits, use the tag as the version
1577 | rendered = pieces["closest-tag"]
1578 | else:
1579 | # exception #1
1580 | rendered = "0.post0.dev%d" % pieces["distance"]
1581 | return rendered
1582 |
1583 |
1584 | def render_pep440_post(pieces):
1585 | """TAG[.postDISTANCE[.dev0]+gHEX] .
1586 |
1587 | The ".dev0" means dirty. Note that .dev0 sorts backwards
1588 | (a dirty tree will appear "older" than the corresponding clean one),
1589 | but you shouldn't be releasing software with -dirty anyways.
1590 |
1591 | Exceptions:
1592 | 1: no tags. 0.postDISTANCE[.dev0]
1593 | """
1594 | if pieces["closest-tag"]:
1595 | rendered = pieces["closest-tag"]
1596 | if pieces["distance"] or pieces["dirty"]:
1597 | rendered += ".post%d" % pieces["distance"]
1598 | if pieces["dirty"]:
1599 | rendered += ".dev0"
1600 | rendered += plus_or_dot(pieces)
1601 | rendered += "g%s" % pieces["short"]
1602 | else:
1603 | # exception #1
1604 | rendered = "0.post%d" % pieces["distance"]
1605 | if pieces["dirty"]:
1606 | rendered += ".dev0"
1607 | rendered += "+g%s" % pieces["short"]
1608 | return rendered
1609 |
1610 |
1611 | def render_pep440_post_branch(pieces):
1612 | """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] .
1613 |
1614 | The ".dev0" means not master branch.
1615 |
1616 | Exceptions:
1617 | 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty]
1618 | """
1619 | if pieces["closest-tag"]:
1620 | rendered = pieces["closest-tag"]
1621 | if pieces["distance"] or pieces["dirty"]:
1622 | rendered += ".post%d" % pieces["distance"]
1623 | if pieces["branch"] != "master":
1624 | rendered += ".dev0"
1625 | rendered += plus_or_dot(pieces)
1626 | rendered += "g%s" % pieces["short"]
1627 | if pieces["dirty"]:
1628 | rendered += ".dirty"
1629 | else:
1630 | # exception #1
1631 | rendered = "0.post%d" % pieces["distance"]
1632 | if pieces["branch"] != "master":
1633 | rendered += ".dev0"
1634 | rendered += "+g%s" % pieces["short"]
1635 | if pieces["dirty"]:
1636 | rendered += ".dirty"
1637 | return rendered
1638 |
1639 |
1640 | def render_pep440_old(pieces):
1641 | """TAG[.postDISTANCE[.dev0]] .
1642 |
1643 | The ".dev0" means dirty.
1644 |
1645 | Exceptions:
1646 | 1: no tags. 0.postDISTANCE[.dev0]
1647 | """
1648 | if pieces["closest-tag"]:
1649 | rendered = pieces["closest-tag"]
1650 | if pieces["distance"] or pieces["dirty"]:
1651 | rendered += ".post%d" % pieces["distance"]
1652 | if pieces["dirty"]:
1653 | rendered += ".dev0"
1654 | else:
1655 | # exception #1
1656 | rendered = "0.post%d" % pieces["distance"]
1657 | if pieces["dirty"]:
1658 | rendered += ".dev0"
1659 | return rendered
1660 |
1661 |
1662 | def render_git_describe(pieces):
1663 | """TAG[-DISTANCE-gHEX][-dirty].
1664 |
1665 | Like 'git describe --tags --dirty --always'.
1666 |
1667 | Exceptions:
1668 | 1: no tags. HEX[-dirty] (note: no 'g' prefix)
1669 | """
1670 | if pieces["closest-tag"]:
1671 | rendered = pieces["closest-tag"]
1672 | if pieces["distance"]:
1673 | rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
1674 | else:
1675 | # exception #1
1676 | rendered = pieces["short"]
1677 | if pieces["dirty"]:
1678 | rendered += "-dirty"
1679 | return rendered
1680 |
1681 |
1682 | def render_git_describe_long(pieces):
1683 | """TAG-DISTANCE-gHEX[-dirty].
1684 |
1685 | Like 'git describe --tags --dirty --always -long'.
1686 | The distance/hash is unconditional.
1687 |
1688 | Exceptions:
1689 | 1: no tags. HEX[-dirty] (note: no 'g' prefix)
1690 | """
1691 | if pieces["closest-tag"]:
1692 | rendered = pieces["closest-tag"]
1693 | rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
1694 | else:
1695 | # exception #1
1696 | rendered = pieces["short"]
1697 | if pieces["dirty"]:
1698 | rendered += "-dirty"
1699 | return rendered
1700 |
1701 |
1702 | def render(pieces, style):
1703 | """Render the given version pieces into the requested style."""
1704 | if pieces["error"]:
1705 | return {
1706 | "version": "unknown",
1707 | "full-revisionid": pieces.get("long"),
1708 | "dirty": None,
1709 | "error": pieces["error"],
1710 | "date": None,
1711 | }
1712 |
1713 | if not style or style == "default":
1714 | style = "pep440" # the default
1715 |
1716 | if style == "pep440":
1717 | rendered = render_pep440(pieces)
1718 | elif style == "pep440-branch":
1719 | rendered = render_pep440_branch(pieces)
1720 | elif style == "pep440-pre":
1721 | rendered = render_pep440_pre(pieces)
1722 | elif style == "pep440-post":
1723 | rendered = render_pep440_post(pieces)
1724 | elif style == "pep440-post-branch":
1725 | rendered = render_pep440_post_branch(pieces)
1726 | elif style == "pep440-old":
1727 | rendered = render_pep440_old(pieces)
1728 | elif style == "git-describe":
1729 | rendered = render_git_describe(pieces)
1730 | elif style == "git-describe-long":
1731 | rendered = render_git_describe_long(pieces)
1732 | else:
1733 | raise ValueError("unknown style '%s'" % style)
1734 |
1735 | return {
1736 | "version": rendered,
1737 | "full-revisionid": pieces["long"],
1738 | "dirty": pieces["dirty"],
1739 | "error": None,
1740 | "date": pieces.get("date"),
1741 | }
1742 |
1743 |
1744 | class VersioneerBadRootError(Exception):
1745 | """The project root directory is unknown or missing key files."""
1746 |
1747 |
1748 | def get_versions(verbose=False):
1749 | """Get the project version from whatever source is available.
1750 |
1751 | Returns dict with two keys: 'version' and 'full'.
1752 | """
1753 | if "versioneer" in sys.modules:
1754 | # see the discussion in cmdclass.py:get_cmdclass()
1755 | del sys.modules["versioneer"]
1756 |
1757 | root = get_root()
1758 | cfg = get_config_from_root(root)
1759 |
1760 | assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg"
1761 | handlers = HANDLERS.get(cfg.VCS)
1762 | assert handlers, "unrecognized VCS '%s'" % cfg.VCS
1763 | verbose = verbose or cfg.verbose
1764 | assert cfg.versionfile_source is not None, "please set versioneer.versionfile_source"
1765 | assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix"
1766 |
1767 | versionfile_abs = os.path.join(root, cfg.versionfile_source)
1768 |
1769 | # extract version from first of: _version.py, VCS command (e.g. 'git
1770 | # describe'), parentdir. This is meant to work for developers using a
1771 | # source checkout, for users of a tarball created by 'setup.py sdist',
1772 | # and for users of a tarball/zipball created by 'git archive' or github's
1773 | # download-from-tag feature or the equivalent in other VCSes.
1774 |
1775 | get_keywords_f = handlers.get("get_keywords")
1776 | from_keywords_f = handlers.get("keywords")
1777 | if get_keywords_f and from_keywords_f:
1778 | try:
1779 | keywords = get_keywords_f(versionfile_abs)
1780 | ver = from_keywords_f(keywords, cfg.tag_prefix, verbose)
1781 | if verbose:
1782 | print("got version from expanded keyword %s" % ver)
1783 | return ver
1784 | except NotThisMethod:
1785 | pass
1786 |
1787 | try:
1788 | ver = versions_from_file(versionfile_abs)
1789 | if verbose:
1790 | print("got version from file %s %s" % (versionfile_abs, ver))
1791 | return ver
1792 | except NotThisMethod:
1793 | pass
1794 |
1795 | from_vcs_f = handlers.get("pieces_from_vcs")
1796 | if from_vcs_f:
1797 | try:
1798 | pieces = from_vcs_f(cfg.tag_prefix, root, verbose)
1799 | ver = render(pieces, cfg.style)
1800 | if verbose:
1801 | print("got version from VCS %s" % ver)
1802 | return ver
1803 | except NotThisMethod:
1804 | pass
1805 |
1806 | try:
1807 | if cfg.parentdir_prefix:
1808 | ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
1809 | if verbose:
1810 | print("got version from parentdir %s" % ver)
1811 | return ver
1812 | except NotThisMethod:
1813 | pass
1814 |
1815 | if verbose:
1816 | print("unable to compute version")
1817 |
1818 | return {
1819 | "version": "0+unknown",
1820 | "full-revisionid": None,
1821 | "dirty": None,
1822 | "error": "unable to compute version",
1823 | "date": None,
1824 | }
1825 |
1826 |
1827 | def get_version():
1828 | """Get the short version string for this project."""
1829 | return get_versions()["version"]
1830 |
1831 |
1832 | def get_cmdclass(cmdclass=None):
1833 | """Get the custom setuptools subclasses used by Versioneer.
1834 |
1835 | If the package uses a different cmdclass (e.g. one from numpy), it
1836 | should be provide as an argument.
1837 | """
1838 | if "versioneer" in sys.modules:
1839 | del sys.modules["versioneer"]
1840 | # this fixes the "python setup.py develop" case (also 'install' and
1841 | # 'easy_install .'), in which subdependencies of the main project are
1842 | # built (using setup.py bdist_egg) in the same python process. Assume
1843 | # a main project A and a dependency B, which use different versions
1844 | # of Versioneer. A's setup.py imports A's Versioneer, leaving it in
1845 | # sys.modules by the time B's setup.py is executed, causing B to run
1846 | # with the wrong versioneer. Setuptools wraps the sub-dep builds in a
1847 | # sandbox that restores sys.modules to it's pre-build state, so the
1848 | # parent is protected against the child's "import versioneer". By
1849 | # removing ourselves from sys.modules here, before the child build
1850 | # happens, we protect the child from the parent's versioneer too.
1851 | # Also see https://github.com/python-versioneer/python-versioneer/issues/52
1852 |
1853 | cmds = {} if cmdclass is None else cmdclass.copy()
1854 |
1855 | # we add "version" to setuptools
1856 | from setuptools import Command
1857 |
1858 | class cmd_version(Command):
1859 | description = "report generated version string"
1860 | user_options = []
1861 | boolean_options = []
1862 |
1863 | def initialize_options(self):
1864 | pass
1865 |
1866 | def finalize_options(self):
1867 | pass
1868 |
1869 | def run(self):
1870 | vers = get_versions(verbose=True)
1871 | print("Version: %s" % vers["version"])
1872 | print(" full-revisionid: %s" % vers.get("full-revisionid"))
1873 | print(" dirty: %s" % vers.get("dirty"))
1874 | print(" date: %s" % vers.get("date"))
1875 | if vers["error"]:
1876 | print(" error: %s" % vers["error"])
1877 |
1878 | cmds["version"] = cmd_version
1879 |
1880 | # we override "build_py" in setuptools
1881 | #
1882 | # most invocation pathways end up running build_py:
1883 | # distutils/build -> build_py
1884 | # distutils/install -> distutils/build ->..
1885 | # setuptools/bdist_wheel -> distutils/install ->..
1886 | # setuptools/bdist_egg -> distutils/install_lib -> build_py
1887 | # setuptools/install -> bdist_egg ->..
1888 | # setuptools/develop -> ?
1889 | # pip install:
1890 | # copies source tree to a tempdir before running egg_info/etc
1891 | # if .git isn't copied too, 'git describe' will fail
1892 | # then does setup.py bdist_wheel, or sometimes setup.py install
1893 | # setup.py egg_info -> ?
1894 |
1895 | # pip install -e . and setuptool/editable_wheel will invoke build_py
1896 | # but the build_py command is not expected to copy any files.
1897 |
1898 | # we override different "build_py" commands for both environments
1899 | if "build_py" in cmds:
1900 | _build_py = cmds["build_py"]
1901 | else:
1902 | from setuptools.command.build_py import build_py as _build_py
1903 |
1904 | class cmd_build_py(_build_py):
1905 | def run(self):
1906 | root = get_root()
1907 | cfg = get_config_from_root(root)
1908 | versions = get_versions()
1909 | _build_py.run(self)
1910 | if getattr(self, "editable_mode", False):
1911 | # During editable installs `.py` and data files are
1912 | # not copied to build_lib
1913 | return
1914 | # now locate _version.py in the new build/ directory and replace
1915 | # it with an updated value
1916 | if cfg.versionfile_build:
1917 | target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build)
1918 | print("UPDATING %s" % target_versionfile)
1919 | write_to_version_file(target_versionfile, versions)
1920 |
1921 | cmds["build_py"] = cmd_build_py
1922 |
1923 | if "build_ext" in cmds:
1924 | _build_ext = cmds["build_ext"]
1925 | else:
1926 | from setuptools.command.build_ext import build_ext as _build_ext
1927 |
1928 | class cmd_build_ext(_build_ext):
1929 | def run(self):
1930 | root = get_root()
1931 | cfg = get_config_from_root(root)
1932 | versions = get_versions()
1933 | _build_ext.run(self)
1934 | if self.inplace:
1935 | # build_ext --inplace will only build extensions in
1936 | # build/lib<..> dir with no _version.py to write to.
1937 | # As in place builds will already have a _version.py
1938 | # in the module dir, we do not need to write one.
1939 | return
1940 | # now locate _version.py in the new build/ directory and replace
1941 | # it with an updated value
1942 | if not cfg.versionfile_build:
1943 | return
1944 | target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build)
1945 | if not os.path.exists(target_versionfile):
1946 | print(
1947 | f"Warning: {target_versionfile} does not exist, skipping "
1948 | "version update. This can happen if you are running build_ext "
1949 | "without first running build_py."
1950 | )
1951 | return
1952 | print("UPDATING %s" % target_versionfile)
1953 | write_to_version_file(target_versionfile, versions)
1954 |
1955 | cmds["build_ext"] = cmd_build_ext
1956 |
1957 | if "cx_Freeze" in sys.modules: # cx_freeze enabled?
1958 | from cx_Freeze.dist import build_exe as _build_exe
1959 |
1960 | # nczeczulin reports that py2exe won't like the pep440-style string
1961 | # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g.
1962 | # setup(console=[{
1963 | # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION
1964 | # "product_version": versioneer.get_version(),
1965 | # ...
1966 |
1967 | class cmd_build_exe(_build_exe):
1968 | def run(self):
1969 | root = get_root()
1970 | cfg = get_config_from_root(root)
1971 | versions = get_versions()
1972 | target_versionfile = cfg.versionfile_source
1973 | print("UPDATING %s" % target_versionfile)
1974 | write_to_version_file(target_versionfile, versions)
1975 |
1976 | _build_exe.run(self)
1977 | os.unlink(target_versionfile)
1978 | with open(cfg.versionfile_source, "w") as f:
1979 | LONG = LONG_VERSION_PY[cfg.VCS]
1980 | f.write(
1981 | LONG
1982 | % {
1983 | "DOLLAR": "$",
1984 | "STYLE": cfg.style,
1985 | "TAG_PREFIX": cfg.tag_prefix,
1986 | "PARENTDIR_PREFIX": cfg.parentdir_prefix,
1987 | "VERSIONFILE_SOURCE": cfg.versionfile_source,
1988 | }
1989 | )
1990 |
1991 | cmds["build_exe"] = cmd_build_exe
1992 | del cmds["build_py"]
1993 |
1994 | if "py2exe" in sys.modules: # py2exe enabled?
1995 | try:
1996 | from py2exe.setuptools_buildexe import py2exe as _py2exe
1997 | except ImportError:
1998 | from py2exe.distutils_buildexe import py2exe as _py2exe
1999 |
2000 | class cmd_py2exe(_py2exe):
2001 | def run(self):
2002 | root = get_root()
2003 | cfg = get_config_from_root(root)
2004 | versions = get_versions()
2005 | target_versionfile = cfg.versionfile_source
2006 | print("UPDATING %s" % target_versionfile)
2007 | write_to_version_file(target_versionfile, versions)
2008 |
2009 | _py2exe.run(self)
2010 | os.unlink(target_versionfile)
2011 | with open(cfg.versionfile_source, "w") as f:
2012 | LONG = LONG_VERSION_PY[cfg.VCS]
2013 | f.write(
2014 | LONG
2015 | % {
2016 | "DOLLAR": "$",
2017 | "STYLE": cfg.style,
2018 | "TAG_PREFIX": cfg.tag_prefix,
2019 | "PARENTDIR_PREFIX": cfg.parentdir_prefix,
2020 | "VERSIONFILE_SOURCE": cfg.versionfile_source,
2021 | }
2022 | )
2023 |
2024 | cmds["py2exe"] = cmd_py2exe
2025 |
2026 | # sdist farms its file list building out to egg_info
2027 | if "egg_info" in cmds:
2028 | _egg_info = cmds["egg_info"]
2029 | else:
2030 | from setuptools.command.egg_info import egg_info as _egg_info
2031 |
2032 | class cmd_egg_info(_egg_info):
2033 | def find_sources(self):
2034 | # egg_info.find_sources builds the manifest list and writes it
2035 | # in one shot
2036 | super().find_sources()
2037 |
2038 | # Modify the filelist and normalize it
2039 | root = get_root()
2040 | cfg = get_config_from_root(root)
2041 | self.filelist.append("versioneer.py")
2042 | if cfg.versionfile_source:
2043 | # There are rare cases where versionfile_source might not be
2044 | # included by default, so we must be explicit
2045 | self.filelist.append(cfg.versionfile_source)
2046 | self.filelist.sort()
2047 | self.filelist.remove_duplicates()
2048 |
2049 | # The write method is hidden in the manifest_maker instance that
2050 | # generated the filelist and was thrown away
2051 | # We will instead replicate their final normalization (to unicode,
2052 | # and POSIX-style paths)
2053 | from setuptools import unicode_utils
2054 |
2055 | normalized = [unicode_utils.filesys_decode(f).replace(os.sep, "/") for f in self.filelist.files]
2056 |
2057 | manifest_filename = os.path.join(self.egg_info, "SOURCES.txt")
2058 | with open(manifest_filename, "w") as fobj:
2059 | fobj.write("\n".join(normalized))
2060 |
2061 | cmds["egg_info"] = cmd_egg_info
2062 |
2063 | # we override different "sdist" commands for both environments
2064 | if "sdist" in cmds:
2065 | _sdist = cmds["sdist"]
2066 | else:
2067 | from setuptools.command.sdist import sdist as _sdist
2068 |
2069 | class cmd_sdist(_sdist):
2070 | def run(self):
2071 | versions = get_versions()
2072 | self._versioneer_generated_versions = versions
2073 | # unless we update this, the command will keep using the old
2074 | # version
2075 | self.distribution.metadata.version = versions["version"]
2076 | return _sdist.run(self)
2077 |
2078 | def make_release_tree(self, base_dir, files):
2079 | root = get_root()
2080 | cfg = get_config_from_root(root)
2081 | _sdist.make_release_tree(self, base_dir, files)
2082 | # now locate _version.py in the new base_dir directory
2083 | # (remembering that it may be a hardlink) and replace it with an
2084 | # updated value
2085 | target_versionfile = os.path.join(base_dir, cfg.versionfile_source)
2086 | print("UPDATING %s" % target_versionfile)
2087 | write_to_version_file(target_versionfile, self._versioneer_generated_versions)
2088 |
2089 | cmds["sdist"] = cmd_sdist
2090 |
2091 | return cmds
2092 |
2093 |
2094 | CONFIG_ERROR = """
2095 | setup.cfg is missing the necessary Versioneer configuration. You need
2096 | a section like:
2097 |
2098 | [versioneer]
2099 | VCS = git
2100 | style = pep440
2101 | versionfile_source = src/myproject/_version.py
2102 | versionfile_build = myproject/_version.py
2103 | tag_prefix =
2104 | parentdir_prefix = myproject-
2105 |
2106 | You will also need to edit your setup.py to use the results:
2107 |
2108 | import versioneer
2109 | setup(version=versioneer.get_version(),
2110 | cmdclass=versioneer.get_cmdclass(), ...)
2111 |
2112 | Please read the docstring in ./versioneer.py for configuration instructions,
2113 | edit setup.cfg, and re-run the installer or 'python versioneer.py setup'.
2114 | """
2115 |
2116 | SAMPLE_CONFIG = """
2117 | # See the docstring in versioneer.py for instructions. Note that you must
2118 | # re-run 'versioneer.py setup' after changing this section, and commit the
2119 | # resulting files.
2120 |
2121 | [versioneer]
2122 | #VCS = git
2123 | #style = pep440
2124 | #versionfile_source =
2125 | #versionfile_build =
2126 | #tag_prefix =
2127 | #parentdir_prefix =
2128 |
2129 | """
2130 |
2131 | OLD_SNIPPET = """
2132 | from ._version import get_versions
2133 | __version__ = get_versions()['version']
2134 | del get_versions
2135 | """
2136 |
2137 | INIT_PY_SNIPPET = """
2138 | from . import {0}
2139 | __version__ = {0}.get_versions()['version']
2140 | """
2141 |
2142 |
2143 | def do_setup():
2144 | """Do main VCS-independent setup function for installing Versioneer."""
2145 | root = get_root()
2146 | try:
2147 | cfg = get_config_from_root(root)
2148 | except (OSError, configparser.NoSectionError, configparser.NoOptionError) as e:
2149 | if isinstance(e, (OSError, configparser.NoSectionError)):
2150 | print("Adding sample versioneer config to setup.cfg", file=sys.stderr)
2151 | with open(os.path.join(root, "setup.cfg"), "a") as f:
2152 | f.write(SAMPLE_CONFIG)
2153 | print(CONFIG_ERROR, file=sys.stderr)
2154 | return 1
2155 |
2156 | print(" creating %s" % cfg.versionfile_source)
2157 | with open(cfg.versionfile_source, "w") as f:
2158 | LONG = LONG_VERSION_PY[cfg.VCS]
2159 | f.write(
2160 | LONG
2161 | % {
2162 | "DOLLAR": "$",
2163 | "STYLE": cfg.style,
2164 | "TAG_PREFIX": cfg.tag_prefix,
2165 | "PARENTDIR_PREFIX": cfg.parentdir_prefix,
2166 | "VERSIONFILE_SOURCE": cfg.versionfile_source,
2167 | }
2168 | )
2169 |
2170 | ipy = os.path.join(os.path.dirname(cfg.versionfile_source), "__init__.py")
2171 | if os.path.exists(ipy):
2172 | try:
2173 | with open(ipy, "r") as f:
2174 | old = f.read()
2175 | except OSError:
2176 | old = ""
2177 | module = os.path.splitext(os.path.basename(cfg.versionfile_source))[0]
2178 | snippet = INIT_PY_SNIPPET.format(module)
2179 | if OLD_SNIPPET in old:
2180 | print(" replacing boilerplate in %s" % ipy)
2181 | with open(ipy, "w") as f:
2182 | f.write(old.replace(OLD_SNIPPET, snippet))
2183 | elif snippet not in old:
2184 | print(" appending to %s" % ipy)
2185 | with open(ipy, "a") as f:
2186 | f.write(snippet)
2187 | else:
2188 | print(" %s unmodified" % ipy)
2189 | else:
2190 | print(" %s doesn't exist, ok" % ipy)
2191 | ipy = None
2192 |
2193 | # Make VCS-specific changes. For git, this means creating/changing
2194 | # .gitattributes to mark _version.py for export-subst keyword
2195 | # substitution.
2196 | do_vcs_install(cfg.versionfile_source, ipy)
2197 | return 0
2198 |
2199 |
2200 | def scan_setup_py():
2201 | """Validate the contents of setup.py against Versioneer's expectations."""
2202 | found = set()
2203 | setters = False
2204 | errors = 0
2205 | with open("setup.py", "r") as f:
2206 | for line in f.readlines():
2207 | if "import versioneer" in line:
2208 | found.add("import")
2209 | if "versioneer.get_cmdclass()" in line:
2210 | found.add("cmdclass")
2211 | if "versioneer.get_version()" in line:
2212 | found.add("get_version")
2213 | if "versioneer.VCS" in line:
2214 | setters = True
2215 | if "versioneer.versionfile_source" in line:
2216 | setters = True
2217 | if len(found) != 3:
2218 | print("")
2219 | print("Your setup.py appears to be missing some important items")
2220 | print("(but I might be wrong). Please make sure it has something")
2221 | print("roughly like the following:")
2222 | print("")
2223 | print(" import versioneer")
2224 | print(" setup( version=versioneer.get_version(),")
2225 | print(" cmdclass=versioneer.get_cmdclass(), ...)")
2226 | print("")
2227 | errors += 1
2228 | if setters:
2229 | print("You should remove lines like 'versioneer.VCS = ' and")
2230 | print("'versioneer.versionfile_source = ' . This configuration")
2231 | print("now lives in setup.cfg, and should be removed from setup.py")
2232 | print("")
2233 | errors += 1
2234 | return errors
2235 |
2236 |
2237 | def setup_command():
2238 | """Set up Versioneer and exit with appropriate error code."""
2239 | errors = do_setup()
2240 | errors += scan_setup_py()
2241 | sys.exit(1 if errors else 0)
2242 |
2243 |
2244 | if __name__ == "__main__":
2245 | cmd = sys.argv[1]
2246 | if cmd == "setup":
2247 | setup_command()
2248 |
--------------------------------------------------------------------------------