diff --git a/.bandit b/.bandit index 663333a..013ea6f 100644 --- a/.bandit +++ b/.bandit @@ -1,2 +1,3 @@ [bandit] -exclude: trollsched/version.py,versioneer.py,trollsched/tests +skips: B506 +exclude: trollsched/tests diff --git a/.bumpversion.cfg b/.bumpversion.cfg deleted file mode 100644 index 80bc3aa..0000000 --- a/.bumpversion.cfg +++ /dev/null @@ -1,7 +0,0 @@ -[bumpversion] -current_version = 0.5.0 -commit = True -tag = True - -[bumpversion:file:trollsched/version.py] - diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index a5887b7..54a0336 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -6,7 +6,7 @@ ``` #### Problem description -[this should also explain **why** the current behaviour is a problem and why the +[this should also explain **why** the current behaviour is a problem and why the expected output is a better solution.] #### Expected Output diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 7a6fdf4..3687eaa 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -5,29 +5,62 @@ on: - pull_request jobs: - build: - runs-on: ubuntu-latest + test: + runs-on: ${{ matrix.os }} + continue-on-error: ${{ matrix.experimental }} strategy: fail-fast: true matrix: + os: ["windows-latest", "ubuntu-latest", "macos-latest"] python-version: ["3.10", "3.11", "3.12"] experimental: [false] + include: + - python-version: "3.12" + os: "ubuntu-latest" + experimental: true + env: + PYTHON_VERSION: ${{ matrix.python-version }} + OS: ${{ matrix.os }} + UNSTABLE: ${{ matrix.experimental }} + ACTIONS_ALLOW_UNSECURE_COMMANDS: true + steps: - name: Checkout source uses: actions/checkout@v4 - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v5 + + - name: Setup Conda Environment + uses: conda-incubator/setup-miniconda@v3 with: + environment-file: continuous_integration/environment.yaml + miniforge-version: latest python-version: ${{ matrix.python-version }} - - name: Install dependencies - run: | - pip install -U pytest pytest-cov numpy pyresample pyorbital six pyyaml defusedxml - - name: Install pytroll-collectors + activate-environment: test-environment + + - name: Install unstable dependencies + if: matrix.experimental == true + shell: bash -l {0} run: | - pip install --no-deps -e . + sudo apt-get install \ + gcc \ + python3-dev; \ + python -m pip install \ + -f https://pypi.anaconda.org/scientific-python-nightly-wheels/simple/ \ + --no-deps --pre --upgrade \ + matplotlib \ + numpy \ + pandas \ + geopandas \ + scipy; \ + python -m pip install \ + --no-deps --upgrade \ + git+https://github.com/Unidata/cftime \ + git+https://github.com/pydata/bottleneck; + - name: Run tests + shell: bash -l {0} run: | pytest --cov=trollsched trollsched/tests --cov-report=xml + - name: Upload coverage to Codecov uses: codecov/codecov-action@v5 with: diff --git a/.gitignore b/.gitignore index 9d420ef..3038b63 100644 --- a/.gitignore +++ b/.gitignore @@ -40,3 +40,7 @@ tmp .vscode .ropeproject *~ + +# Version +# this should be generated automatically when installed +trollsched/version.py diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e5fc6fa..fe36218 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,20 +1,40 @@ exclude: '^$' fail_fast: false repos: + - repo: https://github.com/astral-sh/ruff-pre-commit + # Ruff version. + rev: 'v0.7.2' + hooks: + - id: ruff - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.4.0 + rev: v5.0.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer - id: check-yaml args: [--unsafe] - - repo: https://github.com/charliermarsh/ruff-pre-commit - # Ruff version. - rev: 'v0.0.247' + - repo: https://github.com/PyCQA/bandit + rev: '1.7.10' # Update me! hooks: - - id: ruff - args: [--fix, --exit-non-zero-on-fix] + - id: bandit + args: [--ini, .bandit] + - repo: https://github.com/pre-commit/mirrors-mypy + rev: 'v1.13.0' # Use the sha / tag you want to point at + hooks: + - id: mypy + additional_dependencies: + - types-docutils + - types-setuptools + - types-PyYAML + - types-requests + args: ["--python-version", "3.10", "--ignore-missing-imports"] + - repo: https://github.com/pycqa/isort + rev: 5.13.2 + hooks: + - id: isort + language_version: python3 ci: # To trigger manually, comment on a pull request with "pre-commit.ci autofix" autofix_prs: false + autoupdate_schedule: "monthly" skip: [bandit] diff --git a/.readthedocs.yaml b/.readthedocs.yaml new file mode 100644 index 0000000..ec0cb91 --- /dev/null +++ b/.readthedocs.yaml @@ -0,0 +1,19 @@ +version: 2 + +build: + os: "ubuntu-20.04" + tools: + python: "mambaforge-4.10" + +# Build documentation in the docs/ directory with Sphinx +sphinx: + configuration: docs/conf.py + fail_on_warning: true + +conda: + environment: docs/environment.yaml + +python: + install: + - method: pip + path: . diff --git a/.stickler.yml b/.stickler.yml deleted file mode 100644 index 14ffc75..0000000 --- a/.stickler.yml +++ /dev/null @@ -1,13 +0,0 @@ -linters: - flake8: - python: 3 - config: setup.cfg - fixer: true -fixers: - enable: true - -files: - ignore: - - 'docs/Makefile' - - 'docs/make.bat' - diff --git a/LICENSE b/LICENSE index ef7e7ef..80a875c 100644 --- a/LICENSE +++ b/LICENSE @@ -1,7 +1,7 @@ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 - Copyright (C) 2007 Free Software Foundation, Inc. + Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. @@ -645,7 +645,7 @@ the "copyright" line and a pointer to where the full notice is found. GNU General Public License for more details. You should have received a copy of the GNU General Public License - along with this program. If not, see . + along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. @@ -664,11 +664,11 @@ might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see -. +. The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read -. +. diff --git a/README.md b/README.md index af2de2c..e8c44e9 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,10 @@ -pytroll-schedule -================ +# pytroll-schedule + +Reception scheduling of polar orbiting weather satellites + [![Codacy Badge](https://api.codacy.com/project/badge/Grade/9f039d7d640846ca89be8a78fa11e1f6)](https://www.codacy.com/app/adybbroe/pytroll-schedule?utm_source=github.com&utm_medium=referral&utm_content=pytroll/pytroll-schedule&utm_campaign=badger) [![Build Status](https://travis-ci.org/pytroll/pytroll-schedule.png?branch=main)](https://travis-ci.org/pytroll/pytroll-schedule) [![Coverage Status](https://coveralls.io/repos/github/pytroll/pytroll-schedule/badge.svg?branch=main)](https://coveralls.io/github/pytroll/pytroll-schedule?branch=main) [![Code Health](https://landscape.io/github/pytroll/pytroll-schedule/main/landscape.png)](https://landscape.io/github/pytroll/pytroll-schedule/main) [![PyPI version](https://badge.fury.io/py/pytroll-schedule.svg)](https://badge.fury.io/py/pytroll-schedule) - - -Reception scheduling of polar orbiting weather satellites diff --git a/changelog.rst b/changelog.rst index c30d9ef..bc6e193 100644 --- a/changelog.rst +++ b/changelog.rst @@ -401,6 +401,3 @@ v0.2.0 (2014-05-20) - Renamed a few things to avoid -_ problems. [Martin Raspaud] - Initial commit. [Martin Raspaud] - Initial commit. [Martin Raspaud] - - - diff --git a/continuous_integration/environment.yaml b/continuous_integration/environment.yaml new file mode 100644 index 0000000..22354d4 --- /dev/null +++ b/continuous_integration/environment.yaml @@ -0,0 +1,38 @@ +name: test-environment +channels: + - conda-forge +dependencies: + - xarray + - dask + - distributed + - toolz + - sphinx + - matplotlib + - cartopy + - scipy + - pyyaml + - coveralls + - coverage + - codecov + - behave + - netcdf4 + - paramiko + - oauthlib + - watchdog + - s3fs + - shapely + - pyproj + - pandas + - geopandas + - mock + - pytest + - pytest-cov + - responses + - platformdirs + - defusedxml + - pyorbital + - pyresample + - trollsift + - pip + - pip: + - posttroll diff --git a/docs/about.rst b/docs/about.rst index 2b98657..1ecc5b7 100644 --- a/docs/about.rst +++ b/docs/about.rst @@ -80,4 +80,3 @@ A is respected. This operation can be extended to more than two stations, all receiving a single-operation schedule and an individual cooperating-schedule. - diff --git a/docs/conf.py b/docs/conf.py index d1713ea..ba3d218 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -11,7 +11,6 @@ # All configuration values have a default; values that are commented out # serve to show the default. -import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the @@ -25,32 +24,32 @@ # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.pngmath'] +extensions = ["sphinx.ext.autodoc", "sphinx.ext.intersphinx", "sphinx.ext.pngmath"] # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] # The suffix of source filenames. -source_suffix = '.rst' +source_suffix = ".rst" # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = u'pytroll-schedule' -copyright = u'2014, Martin Raspaud' +project = u"pytroll-schedule" +copyright = u"2014, 2024-{}, The PyTroll Team".format(dt.datetime.utcnow().strftime("%Y")) # noqa: A001 # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. -version = '0.1.0' +version = "0.1.0" # The full version, including alpha/beta/rc tags. -release = '0.1.0' +release = "0.1.0" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -64,7 +63,7 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ['_build'] +exclude_patterns = ["_build"] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None @@ -81,7 +80,7 @@ #show_authors = False # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] @@ -91,7 +90,7 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. -html_theme = 'default' +html_theme = "default" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the @@ -120,7 +119,7 @@ # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] +html_static_path = ["_static"] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. @@ -164,7 +163,7 @@ #html_file_suffix = None # Output file base name for HTML help builder. -htmlhelp_basename = 'pytroll-scheduledoc' +htmlhelp_basename = "pytroll-scheduledoc" # -- Options for LaTeX output -------------------------------------------------- @@ -178,8 +177,8 @@ # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ - ('index', 'pytroll-schedule.tex', u'pytroll-schedule Documentation', - u'Martin Raspaud', 'manual'), + ("index", "pytroll-schedule.tex", u"pytroll-schedule Documentation", + u"Martin Raspaud", "manual"), ] # The name of an image file (relative to this directory) to place at the top of @@ -211,10 +210,10 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - ('index', 'pytroll-schedule', u'pytroll-schedule Documentation', - [u'Martin Raspaud'], 1) + ("index", "pytroll-schedule", u"pytroll-schedule Documentation", + [u"Martin Raspaud"], 1) ] # Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = {'http://docs.python.org/': None} +intersphinx_mapping = {"http://docs.python.org/": None} diff --git a/docs/environment.yaml b/docs/environment.yaml new file mode 100644 index 0000000..746b70d --- /dev/null +++ b/docs/environment.yaml @@ -0,0 +1,26 @@ +name: readthedocs +channels: + - conda-forge +dependencies: + - python=3.12 + - pip + - defusedxml + - numpy + - scipy + - pandas + - geopandas + - shapely + - pyresample + - requests + - pytest + - pyproj + - setuptools + - setuptools_scm + - sphinx + - sphinx_rtd_theme + - sphinxcontrib-apidoc + - trollsift + - xarray + - pip: + - graphviz + - .. # relative path to the pytroll-schedule project diff --git a/docs/example.rst b/docs/example.rst index b81be9d..56d2297 100644 --- a/docs/example.rst +++ b/docs/example.rst @@ -1,6 +1,9 @@ Example ======= +How to generate a local reception schedule +------------------------------------------ + This Bash-script shows an example how to use the schedule script:: #!/usr/bin/bash @@ -10,44 +13,62 @@ This Bash-script shows an example how to use the schedule script:: logp=$PYTROLL_BASE/log/scheduler.log logc=$PYTROLL_BASE/log/create.log odir=$PYTROLL_BASE/schedules - + cfgfile=$1 shift - + # report-mode with plots mode="-r -p" - + # min time-diff btwn passes delay="90" - + # create output for scisys sci="--scisys" - + # dont include aqua-dumps aqua="--no-aqua-dump" - + # write gv-files for dot graph="-g" - + # exit if no new tle (( `ls $PYTROLL_BASE/tle/*.tle 2>/dev/null|wc -l` > 0 )) || exit 0 - + # catch newest TLE-file, remove others tle=`ls -t $PYTROLL_BASE/tle/*.tle|head -1` mv $tle $tle.txt rm -f $PYTROLL_BASE/tle/*.tle - + # settings for TLE-check satlst="NOAA 15|NOAA 18|NOAA 19|METOP-A|METOP-B|AQUA|SUOMI|TERRA " satcnt=8 to_addr=pytroll@schedule - + # check if TLE-file is complete if (( `grep -P "$satlst" $tle.txt|tee .tle_grep|wc -l` != $satcnt )); then exit 0 else tle="-t $tle.txt" fi - + # start schedule script $bin -v -l $logp -c $conf/$cfgfile $tle -d $delay -o $odir $graph $mode $sci $aqua $@ + + +How to create instrument swath outlines in shapefile format for all passes scheduled +------------------------------------------------------------------------------------ + +To create instrument swath outlines in shapefile format one can run the +`create_shapefiles_from_schedule` script, e.g. like in the below example:: + + create_shapefiles_from_schedule -s "Suomi NPP" NOAA-21 -t /data/tles/tle-202409060015.txt -x /data/schedules/2024-09-06-00-45-08-acquisition-schedule-confirmation-nrk.xml -o /data/pass_outlines + +Then in the directory `/data/pass_outlines` a set of (rather small size) +shapefiles can be found, like the below one example:: + + `viirs_Suomi-NPP_202409122257_202409122309_outline.cpg` + `viirs_Suomi-NPP_202409122257_202409122309_outline.dbf` + `viirs_Suomi-NPP_202409122257_202409122309_outline.prj` + `viirs_Suomi-NPP_202409122257_202409122309_outline.shp` + `viirs_Suomi-NPP_202409122257_202409122309_outline.shx` diff --git a/docs/index.rst b/docs/index.rst index dc62c7c..f98aefa 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -12,13 +12,13 @@ Contents: .. toctree:: :maxdepth: 2 - + about miscellaneous - + .. toctree:: :maxdepth: 1 - + usage config example @@ -29,4 +29,3 @@ Indices and tables * :ref:`genindex` * :ref:`modindex` * :ref:`search` - diff --git a/docs/install.rst b/docs/install.rst index 47e90af..56687ee 100644 --- a/docs/install.rst +++ b/docs/install.rst @@ -3,7 +3,7 @@ Installation mkdir $HOME/PyTROLL cd !$ mkdir data-in data-out etc - + #dnf install pyshp python-configobj numpy numpy-f2py scipy python-numexpr \ #python-pillow proj proj-epsg proj-nad pyproj python2-matplotlib python-basemap # @@ -16,15 +16,15 @@ Installation wget https://github.com/pytroll/trollcast/archive/master.zip -O trollcast-master.zip wget https://github.com/pytroll/pytroll-schedule/archive/master.zip -O pytroll-schedule-master.zip wget https://github.com/pytroll/trollduction/archive/master.zip -O trollduction-master.zip - - + + for ff in *.zip ; do unzip -u $ff cd $(basename $ff .zip) python setup.py build python setup.py install --user done - + cat <= 1.22", + "pyorbital", + "shapely", + "geopandas", + "pandas", + "pyyaml", + "defusedxml"] +readme = "README.md" +requires-python = ">=3.10" +license = {file = "LICENSE"} +classifiers = [ + "Development Status :: 4 - Beta", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Topic :: Scientific/Engineering", + "Topic :: Scientific/Engineering :: Astronomy" +] + +[project.scripts] +schedule = "trollsched.schedule:run" +create_shapefiles_from_schedule = "trollsched.shapefiles_from_schedule:run" +compare_scheds = "trollsched.compare:run" + + +[project.urls] +"Documentation" = "https://pytroll-schedule.readthedocs.io/en/latest/" + +[project.optional-dependencies] +doc = ["sphinx", "sphinx_rtd_theme", "sphinxcontrib-apidoc"] + +[build-system] +requires = ["hatchling", "hatch-vcs"] +build-backend = "hatchling.build" + +[tool.hatch.metadata] +allow-direct-references = true + +[tool.hatch.build.targets.wheel] +packages = ["trollsched"] + +[tool.hatch.version] +source = "vcs" + +[tool.hatch.build.hooks.vcs] +version-file = "trollsched/version.py" + +[tool.isort] +sections = ["FUTURE", "STDLIB", "THIRDPARTY", "FIRSTPARTY", "LOCALFOLDER"] +profile = "black" +skip_gitignore = true +default_section = "THIRDPARTY" +known_first_party = "pytroll-schedule" +line_length = 120 + [tool.ruff] -select = ["E", "W", "F", "I", "D", "S", "B", "A", "PT", "Q", "TID"] -ignore = ["B905"] # only available from python 3.10 line-length = 120 -[tool.ruff.per-file-ignores] -"trollsched/tests/*" = ["S101"] +[tool.ruff.lint] +# See https://docs.astral.sh/ruff/rules/ +# In the future, add "B", "S", "N" +select = ["A", "D", "E", "W", "F", "I", "PT", "TID", "C90", "Q", "T10", "T20", "NPY"] -[tool.ruff.pydocstyle] +[tool.ruff.lint.per-file-ignores] +"trollsched/tests/*" = ["S101"] # assert allowed in tests +"trollsched/version.py" = ["D100", "Q000"] # automatically generated by hatch-vcs + +[tool.ruff.lint.pydocstyle] convention = "google" + +[tool.ruff.lint.mccabe] +# Unlike Flake8, default to a complexity level of 10. +max-complexity = 10 + +[tool.coverage.run] +relative_files = true +omit = ["trollsched/version.py"] diff --git a/scheduler.yaml_template b/scheduler.yaml_template index 8d7aadb..2d720b2 100644 --- a/scheduler.yaml_template +++ b/scheduler.yaml_template @@ -4,22 +4,22 @@ default: station: - nrk - bch - + # schedule starts in 2 hours and covers 7 days forward: 168 start: 2 - + # minimum observable pass length [minutes] min_pass: 4 - + # URL for Aqua/Terra dump information dump_url: "ftp://is.sci.gsfc.nasa.gov/ancillary/ephemeris/schedule/%s/downlink/" pattern: # dir/file pattern, follows rules of str.format() # pre-set names: - # {date}, {time} : date+time - # {station} : as in station->name, for combined schedules ".comb" is appended, + # {date}, {time} : date+time + # {station} : as in station->name, for combined schedules ".comb" is appended, # {mode} : request|report, # {output_dir} : as in cmd-param --output-dir dir_output: "{output_dir}/{date}-{time}" @@ -27,8 +27,8 @@ pattern: file_xml: "{dir_output}/aquisition-schedule-{mode}_{station}.xml" file_sci: "{dir_output}/scisys-schedule-{station}.txt" file_graph: "{dir_output}/graph" - -stations: + +stations: nrk: name: nrk # degrees east @@ -39,16 +39,16 @@ stations: altitude: 0.052765 area_file: /home/amaul/PyTROLL/etc/areas.def area: euron1 - satellites: - - metop-a - - metop-b - - noaa 19 - - noaa 18 - - noaa 15 - - aqua - - terra + satellites: + - metop-b + - noaa 19 + - noaa 18 + - noaa 15 + - aqua - suomi npp - + - NOAA-20 + - NOAA-21 + nrk-test: name: nrk # degrees east @@ -59,20 +59,21 @@ stations: altitude: 0.052765 area_file: /home/amaul/PyTROLL/etc/areas.def area: euron1 - satellites: - metop-a : - night: 0.1 - day: 0.6 + satellites: metop-b : night: 0.1 day: 0.6 + metop-c : + night: 0.1 + day: 0.6 noaa 19 : noaa 18 : noaa 15 : aqua : - terra : suomi npp : - + NOAA-20 : + NOAA-21 : + bch: name: bch # degrees east @@ -83,49 +84,50 @@ stations: altitude: 0.14 area_file: /home/amaul/PyTROLL/etc/areas.def area: euron1 - satellites: - - metop-a - - metop-b - - noaa 19 - - noaa 18 - - noaa 15 - - aqua - - terra + satellites: + - metop-b + - metop-c + - noaa 19 + - noaa 18 + - noaa 15 + - aqua - suomi npp + - NOAA-20 + - NOAA-21 satellites: - metop-a: + metop-b: night: 0.1 day: 0.6 - - metop-b: + + metop-c: night: 0.1 day: 0.6 - + noaa 19: night: 0.05 day: 0.3 - + noaa 18: night: 0.1 day: 0.6 - - noaa 16: - night: 0.1 - day: 0.6 - + noaa 15: night: 0.05 day: 0.3 - + aqua: night: 0.2 day: 0.8 - - terra: - night: 0.2 - day: 0.8 - + suomi npp: night: 0.25 day: 0.9 + + NOAA-20: + night: 0.25 + day: 0.9 + + NOAA-21: + night: 0.25 + day: 0.9 diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 0bc6805..0000000 --- a/setup.cfg +++ /dev/null @@ -1,29 +0,0 @@ -[bdist_rpm] -requires=numpy pyresample pyorbital pyyaml -release=1 - -# See the docstring in versioneer.py for instructions. Note that you must -# re-run 'versioneer.py setup' after changing this section, and commit the -# resulting files. - -[versioneer] -VCS = git -style = pep440 -versionfile_source = trollsched/version.py -versionfile_build = -tag_prefix = v -parentdir_prefix = - -[bdist_wheel] -universal=1 - -[flake8] -max-line-length = 120 -exclude = - trollsched/version.py - versioneer.py - -[coverage:run] -omit = - trollsched/version.py - versioneer.py diff --git a/setup.py b/setup.py deleted file mode 100644 index ee4e128..0000000 --- a/setup.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# Copyright (c) 2014 - 2019 PyTroll Community - -# Author(s): - -# Martin Raspaud -# Adam Dybbroe - -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. - -# You should have received a copy of the GNU General Public License -# along with this program. If not, see . - -"""The setup file.""" - -from setuptools import setup - -import versioneer - -requires = ["numpy", "pyresample", "pyorbital", "pyyaml", "defusedxml"] -test_requires = [] - -setup(name="pytroll-schedule", - version=versioneer.get_version(), - cmdclass=versioneer.get_cmdclass(), - description="Scheduling satellite passes in Python", - author="Martin Raspaud", - author_email="martin.raspaud@smhi.se", - classifiers=["Development Status :: 4 - Beta", - "Intended Audience :: Science/Research", - "License :: OSI Approved :: GNU General Public License v3 " + - "or later (GPLv3+)", - "Operating System :: OS Independent", - "Programming Language :: Python", - "Topic :: Scientific/Engineering", - "Topic :: Scientific/Engineering :: Astronomy"], - test_suite="trollsched.tests.suite", - entry_points={ - "console_scripts": ["schedule = trollsched.schedule:run", - "compare_scheds = trollsched.compare:run"]}, - scripts=["generate_schedule_xmlpage.py"], - packages=["trollsched"], - tests_require=test_requires, - install_requires=requires, - zip_safe=False, - ) diff --git a/trollsched/__init__.py b/trollsched/__init__.py index 60cfdc0..8ae659f 100644 --- a/trollsched/__init__.py +++ b/trollsched/__init__.py @@ -1,7 +1,7 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -# Copyright (c) 2014 - 2023 PyTroll Community +# Copyright (c) 2014 - 2024 PyTroll Community # Author(s): @@ -23,61 +23,69 @@ """Package file.""" -from . import version - -__version__ = version.get_versions()['version'] - # shortest allowed pass in minutes MIN_PASS = 4 # DRL still use the name JPSS-1 (etc) instead of NOAA-20 in the TLEs: -JPSS_TLE_NAMES = {'NOAA-20': 'JPSS-1', - 'NOAA-21': 'JPSS-2', - 'NOAA-22': 'JPSS-3'} +JPSS_TLE_NAMES = {"NOAA-20": "JPSS-1", + "NOAA-21": "JPSS-2", + "NOAA-22": "JPSS-3"} NUMBER_OF_FOVS = { - 'avhrr': 2048, - 'mhs': 90, - 'amsua': 30, - 'mwhs2': 98, - 'atms': 96, - 'ascat': 42, - 'viirs': 6400, - 'atms': 96, - 'mwhs-2': 98 + "avhrr": 2048, + "mhs": 90, + "amsua": 30, + "mwhs2": 98, + "atms": 96, + "ascat": 42, + "viirs": 6400, + "mwhs-2": 98 } -SATELLITE_NAMES = {'npp': 'Suomi NPP', - 'noaa19': 'NOAA 19', - 'noaa18': 'NOAA 18', - 'noaa15': 'NOAA 15', - 'aqua': 'Aqua', - 'terra': 'Terra', - 'metopc': 'Metop-C', - 'metopb': 'Metop-B', - 'metopa': 'Metop-A', - 'noaa20': 'NOAA-20', - 'noaa21': 'NOAA-21', - 'noaa22': 'NOAA-22', - 'fengyun3d': 'FY-3D', - 'fengyun3c': 'FY-3C' +SATELLITE_NAMES = {"npp": "Suomi NPP", + "noaa19": "NOAA 19", + "noaa18": "NOAA 18", + "noaa15": "NOAA 15", + "aqua": "Aqua", + "terra": "Terra", + "metopc": "Metop-C", + "metopb": "Metop-B", + "metopa": "Metop-A", + "noaa20": "NOAA-20", + "noaa21": "NOAA-21", + "noaa22": "NOAA-22", + "fengyun3d": "FY-3D", + "fengyun3c": "FY-3C" } -INSTRUMENT = {'Suomi NPP': 'viirs', - 'NOAA-20': 'viirs', - 'NOAA-21': 'viirs', - 'NOAA-22': 'viirs', - 'Aqua': 'modis', - 'Terra': 'modis', - 'NOAA 19': 'avhrr', - 'NOAA 18': 'avhrr', - 'NOAA 15': 'avhrr', - 'Metop-A': 'avhrr', - 'Metop-B': 'avhrr', - 'Metop-C': 'avhrr', - 'FY-3D': 'avhrr', - 'FY-3C': 'avhrr'} - -from . import version -__version__ = version.get_versions()['version'] +INSTRUMENT = {"Suomi NPP": "viirs", + "NOAA-20": "viirs", + "NOAA-21": "viirs", + "NOAA-22": "viirs", + "Aqua": "modis", + "Terra": "modis", + "NOAA 19": "avhrr", + "NOAA 18": "avhrr", + "NOAA 15": "avhrr", + "Metop-A": "avhrr", + "Metop-B": "avhrr", + "Metop-C": "avhrr", + "FY-3D": "avhrr", + "FY-3C": "avhrr"} + +VIIRS_PLATFORM_NAMES = ["SUOMI NPP", "SNPP", + "NOAA-20", "NOAA 20"] +MERSI_PLATFORM_NAMES = ["FENGYUN 3C", "FENGYUN-3C", "FY-3C"] +MERSI2_PLATFORM_NAMES = ["FENGYUN 3D", "FENGYUN-3D", "FY-3D", + "FENGYUN 3E", "FENGYUN-3E", "FY-3E"] + +SATELLITE_MEOS_TRANSLATION = {"NOAA 19": "NOAA_19", + "NOAA 18": "NOAA_18", + "NOAA 15": "NOAA_15", + "METOP-A": "M02", + "METOP-B": "M01", + "FENGYUN 3A": "FENGYUN-3A", + "FENGYUN 3B": "FENGYUN-3B", + "FENGYUN 3C": "FENGYUN-3C", + "SUOMI NPP": "NPP"} diff --git a/trollsched/combine.py b/trollsched/combine.py index 666f76d..3580715 100644 --- a/trollsched/combine.py +++ b/trollsched/combine.py @@ -1,7 +1,7 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- # -# Copyright (c) 2016, 2018 Martin Raspaud +# Copyright (c) 2016, 2018, 2024 Martin Raspaud # # Author(s): # @@ -20,17 +20,18 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -"""Combine several graphs. -""" +"""Combine several graphs.""" import logging +import sys from datetime import datetime, timedelta + from trollsched.graph import Graph logger = logging.getLogger("trollsched") def add_graphs(graphs, passes, delay=timedelta(seconds=0)): - """Add all graphs to one combined graph. """ + """Add all graphs to one combined graph.""" statlst = graphs.keys() def count_neq_passes(pl): @@ -200,9 +201,8 @@ def overlap_any(this, test_list): try: gn = g.neighbours(passes_list[statnr].index(p[0]) + 1) except Exception: - print("len(passes_list)", len(passes_list), " len(graph_set)", - len(graph_set), " statnr", statnr, " p", p) - print("passes_list", passes_list) + logger.debug(f"len(passes_list)={len(passes_list)} len(graph_set)={len(graph_set)} statnr={statnr} p={p}") + logger.debug("passes_list", passes_list) raise if gn[0] > len(passes_list[statnr]): @@ -264,7 +264,7 @@ def overlap_any(this, test_list): )) bufflist.append(cc) - elif overlap < 0: + else: # If the current parent node's pass is not overlapping # but BEFORE the pass from the recursion-return-list # the recursion-list-node gets "simulated". @@ -278,16 +278,11 @@ def overlap_any(this, test_list): ] cc.insert(0, (passes_list[statnr][n - 1], None)) bufflist.append(cc) - - else: - print("uh-oh, something curious happened ...") - except Exception: - print("\nCATCH\ngn:", gn, "-> n", n, " col:", col, - "-> cx", cx, "statnr", statnr, "statnr+i", statnr + 1) - print("len(passes_list -n -cx)", len(passes_list[statnr]), len(passes_list[statnr + 1])) + logger.debug(f"\nCATCH\ngn:{gn}->{n}, col: {col}->{cx} statnr={statnr} statnr+i: {statnr + 1}") + logger.debug(f"len(passes_list -n -cx): {len(passes_list[statnr])} {len(passes_list[statnr + 1])}") for s in range(statnr, len(passes_list)): - print("passes_list[", s, "] =>", passes_list[s]) + logger.debug(f"passes_list[{s}] => {passes_list[s]}") raise return bufflist @@ -318,21 +313,21 @@ def get_combined_sched(allgraphs, allpasses, delay_sec=60): def print_matrix(m, ly=-1, lx=-1): - """For DEBUG: Prints one of the graphs' backing matrix without - flooding the screen. + """For DEBUG: Prints one of the graphs' backing matrix without flooding the screen. It'll print the first lx columns from the first ly rows, then the last lx columns from the last ly rows. """ for i, l in zip(range(ly), m[0:ly]): - print(i, ":", l[:lx], "...") - print("[..., ...]") + logger.debug(f"{i}: {l[:lx]}...") + logger.debug("[..., ...]") for i, l in zip(range(len(m) - ly - 1, len(m) - 1), m[-ly:]): - print(i, ": ...", l[-lx:]) - + logger.debug(f"{i}: ...{l[-lx:]}") def test_folding(g): - """Test if the graphs could be "folded", or better "squished", to reduce + """Test if the graphs could be "folded". + + Test if the graphs could be "folded", or better "squished", to reduce size on cost of calculating the real x',y' from the x,y of the "unfolded" graph. """ @@ -340,22 +335,24 @@ def test_folding(g): for u in range(g.order): for n in g.neighbours(u): if n < u: - print(n, "<", u) + logger.debug(f"{n}<{u}") r = True return r def main(): + """The main script.""" import logging import logging.handlers import os import pickle - from trollsched.schedule import parse_datetime - from trollsched.schedule import combined_stations, build_filename + + from trollsched.schedule import build_filename, combined_stations, parse_datetime try: - from trollsched.schedule import read_config import argparse + + from trollsched.schedule import read_config logger = logging.getLogger("trollsched") parser = argparse.ArgumentParser() parser.add_argument("-c", "--config", default=None, @@ -394,7 +391,6 @@ def main(): } dir_output = build_filename("dir_output", pattern, pattern_args) if not os.path.exists(dir_output): - print(dir_output, "does not exist!") sys.exit(1) ph = open(os.path.join(dir_output, "opts.pkl"), "rb") opts = pickle.load(ph) @@ -425,15 +421,16 @@ def main(): from trollsched.schedule import conflicting_passes totpas = [] + for s, sp in allpasses.items(): - print("len(sp)", s, len(sp)) + logger.debug(f"s, len(sp): {s} {len(sp)}") totpas.extend(list(sp)) passes = sorted(totpas, key=lambda x: x.risetime) cpg = conflicting_passes(passes, timedelta(seconds=600)) - print("ALLPASSES", len(allpasses)) # ,allpasses - print("PASSES", len(passes)) # ,passes - print("CONFLGRPS", len(cpg)) # ,cpg - print("MAX", max([len(g) for g in cpg])) + logger.debug(f"ALLPASSES: {len(allpasses)}") + logger.debug(f"PASSES: {len(passes)}") + logger.debug(f"CONFLGRPS: {len(cpg)}") + logger.debug(f"MAX: {max([len(g) for g in cpg])}") combined_stations(opts, pattern, station_list, graph, allpasses, start_time, start, forward) @@ -442,5 +439,5 @@ def main(): raise -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/trollsched/drawing.py b/trollsched/drawing.py index 8876746..33a3d74 100644 --- a/trollsched/drawing.py +++ b/trollsched/drawing.py @@ -1,7 +1,7 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -# Copyright (c) 2018 - 2020 Pytroll Community +# Copyright (c) 2018 - 2020, 2024 Pytroll Community # Author(s): @@ -20,14 +20,15 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -"""Drawing satellite overpass outlines on maps -""" +"""Drawing satellite overpass outlines on maps.""" -import os import logging import logging.handlers -import numpy as np +import os + import matplotlib as mpl +import numpy as np + MPL_BACKEND = mpl.get_backend() logger = logging.getLogger(__name__) @@ -42,25 +43,24 @@ if not BASEMAP_NOT_CARTOPY: import cartopy - cartopy.config['pre_existing_data_dir'] = os.environ.get( - "CARTOPY_PRE_EXISTING_DATA_DIR", cartopy.config['pre_existing_data_dir']) + cartopy.config["pre_existing_data_dir"] = os.environ.get( + "CARTOPY_PRE_EXISTING_DATA_DIR", cartopy.config["pre_existing_data_dir"]) class MapperBasemap(object): - """A class to generate nice plots with basemap. - """ + """A class to generate nice plots with basemap.""" def __init__(self, **proj_info): - + """Initialize the class object.""" from mpl_toolkits.basemap import Basemap if not proj_info: proj_info = { - 'projection': 'nsper', - 'lat_0': 58, - 'lon_0': 16, - 'resolution': 'l', - 'area_thresh': 1000. + "projection": "nsper", + "lat_0": 58, + "lon_0": 16, + "resolution": "l", + "area_thresh": 1000. } self.map = Basemap(**proj_info) @@ -68,7 +68,7 @@ def __init__(self, **proj_info): self.map.drawcoastlines() self.map.drawcountries() - self.map.drawmapboundary(fill_color='white') + self.map.drawmapboundary(fill_color="white") self.map.drawmeridians(np.arange(0, 360, 30)) self.map.drawparallels(np.arange(-90, 90, 30)) @@ -81,22 +81,21 @@ def __exit__(self, etype, value, tb): class MapperCartopy(object): - """A class to generate nice plots with Cartopy. - """ + """A class to generate nice plots with Cartopy.""" def __init__(self, **proj_info): - + """Initialize the Cartopy Mapper object.""" mpl.use(MPL_BACKEND) import matplotlib.pyplot as plt if not proj_info: proj_info = { - 'central_latitude': 58, - 'central_longitude': 16, - 'satellite_height': 35785831, - 'false_easting': 0, - 'false_northing': 0, - 'globe': None + "central_latitude": 58, + "central_longitude": 16, + "satellite_height": 35785831, + "false_easting": 0, + "false_northing": 0, + "globe": None } fig = plt.figure(figsize=(8, 6)) @@ -105,25 +104,26 @@ def __init__(self, **proj_info): 1, 1, 1, projection=ccrs.NearsidePerspective(**proj_info)) self._ax.add_feature(cfeature.OCEAN, zorder=0) - self._ax.add_feature(cfeature.LAND, zorder=0, edgecolor='black') + self._ax.add_feature(cfeature.LAND, zorder=0, edgecolor="black") self._ax.add_feature(cfeature.BORDERS, zorder=0) self._ax.set_global() self._ax.gridlines() def plot(self, *args, **kwargs): + """Make the matplotlib plot.""" mpl.use(MPL_BACKEND) import matplotlib.pyplot as plt - kwargs['transform'] = ccrs.Geodetic() + kwargs["transform"] = ccrs.Geodetic() return plt.plot(*args, **kwargs) def nightshade(self, utctime, **kwargs): - + """Create a night shade to the map.""" from trollsched.helper_functions import fill_dark_side - color = kwargs.get('color', 'black') - alpha = kwargs.get('alpha', 0.4) + color = kwargs.get("color", "black") + alpha = kwargs.get("alpha", 0.4) fill_dark_side(self._ax, time=utctime, color=color, alpha=alpha) def __call__(self, *args): @@ -148,12 +148,11 @@ def save_fig(pass_obj, overwrite=False, labels=None, extension=".png", - outline='-r', + outline="-r", plot_parameters=None, plot_title=None, poly_color=None): - """Save the pass as a figure. Filename is automatically generated. - """ + """Save the pass as a figure. Filename is automatically generated.""" poly = poly or [] poly_color = poly_color or [] if not isinstance(poly, (list, tuple)): @@ -161,7 +160,7 @@ def save_fig(pass_obj, if not isinstance(poly_color, (list, tuple)): poly_color = [poly_color] - mpl.use('Agg') + mpl.use("Agg") import matplotlib.pyplot as plt plt.clf() @@ -172,7 +171,7 @@ def save_fig(pass_obj, logger.debug("Create plot dir " + directory) os.makedirs(directory) - filename = '{rise}_{satname}_{instrument}_{fall}{extension}'.format(rise=rise, + filename = "{rise}_{satname}_{instrument}_{fall}{extension}".format(rise=rise, satname=pass_obj.satellite.name.replace( " ", "_"), instrument=pass_obj.instrument.replace( @@ -191,7 +190,7 @@ def save_fig(pass_obj, try: col = poly_color[i] except IndexError: - col = '-b' + col = "-b" draw(polygon, mapper, col) logger.debug("Draw: outline = <%s>", outline) draw(pass_obj.boundary.contour_poly, mapper, outline) @@ -214,9 +213,8 @@ def show(pass_obj, labels=None, other_poly=None, proj=None, - outline='-r'): - """Show the current pass on screen (matplotlib, basemap). - """ + outline="-r"): + """Show the current pass on screen (matplotlib, basemap).""" mpl.use(MPL_BACKEND) import matplotlib.pyplot as plt @@ -235,6 +233,7 @@ def show(pass_obj, def draw(poly, mapper, options, **more_options): + """Draw the polygon onto the mapper object.""" lons = np.rad2deg(poly.lon.take(np.arange(len(poly.lon) + 1), mode="wrap")) lats = np.rad2deg(poly.lat.take(np.arange(len(poly.lat) + 1), mode="wrap")) rx, ry = mapper(lons, lats) @@ -242,13 +241,15 @@ def draw(poly, mapper, options, **more_options): def main(): - from trollsched.satpass import get_next_passes + """A main function as a how-to example.""" from datetime import datetime + from trollsched.satpass import get_next_passes + passes = get_next_passes(["noaa 19", "suomi npp"], datetime.now(), 24, (16, 58, 0)) for p in passes: save_fig(p, directory="/tmp/plots/") -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/trollsched/graph.py b/trollsched/graph.py index c567cce..9ee5589 100644 --- a/trollsched/graph.py +++ b/trollsched/graph.py @@ -131,7 +131,12 @@ def load(self, filename): self.vertices = np.arange(self.order) def export(self, filename="./sched.gv", labels=None): - """dot sched.gv -Tpdf -otruc.pdf.""" + """Export the schedule to gv format for visualization. + + To generate a pdf out of it:: + + dot sched.gv -Tpdf -otruc.pdf. + """ with open(filename, "w") as fd_: fd_.write('digraph schedule { \n size="80, 10";\n center="1";\n') for v1 in range(1, self.order - 1): diff --git a/trollsched/helper_functions.py b/trollsched/helper_functions.py index f63712f..55b1548 100644 --- a/trollsched/helper_functions.py +++ b/trollsched/helper_functions.py @@ -1,7 +1,7 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -# Copyright (c) 2018 Adam.Dybbroe +# Copyright (c) 2018, 2024 Adam.Dybbroe # Author(s): @@ -20,17 +20,20 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -"""Helper functions for the pytroll-schedule methods. E.g. nightshade method -for Cartopy as available in Basemap +"""Helper functions for the pytroll-schedule methods. +E.g. nightshade method for Cartopy as available in Basemap. """ -import numpy as np from datetime import datetime +import numpy as np + def sun_pos(dt=None): - """This function computes a rough estimate of the coordinates for + """Get location on earth where the sun is in zenith at time *dt*. + + This function computes a rough estimate of the coordinates for the point on the surface of the Earth where the Sun is directly overhead at the time dt. Precision is down to a few degrees. This means that the equinoxes (when the sign of the latitude changes) @@ -47,7 +50,7 @@ def sun_pos(dt=None): dt: datetime Defaults to datetime.utcnow() - Returns + Returns: ------- lat, lng: tuple of floats Approximate coordinates of the point where the sun is @@ -70,8 +73,7 @@ def sun_pos(dt=None): def fill_dark_side(ax, time=None, **kwargs): - """ - Plot a fill on the dark side of the planet (without refraction). + """Plot a fill on the dark side of the planet (without refraction). Parameters ---------- @@ -83,7 +85,6 @@ def fill_dark_side(ax, time=None, **kwargs): Passed on to Matplotlib's ax.fill() """ - import cartopy.crs as ccrs lat, lng = sun_pos(time) diff --git a/trollsched/logger.py b/trollsched/logger.py new file mode 100644 index 0000000..b0d945e --- /dev/null +++ b/trollsched/logger.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright (c) 2024 Adam.Dybbroe + +# Author(s): + +# Adam.Dybbroe + +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +"""The log handling.""" + +import logging +import logging.config +import logging.handlers + +import yaml + +LOG_FORMAT = "[%(asctime)s %(levelname)-8s] %(message)s" + +log_levels = { + 0: logging.WARN, + 1: logging.INFO, + 2: logging.DEBUG, +} + + +def setup_logging(cmd_args): + """Set up logging.""" + if cmd_args.log_config is not None: + with open(cmd_args.log_config) as fd: + log_dict = yaml.safe_load(fd.read()) + logging.config.dictConfig(log_dict) + return + + root = logging.getLogger("") + root.setLevel(log_levels[cmd_args.verbosity]) + + fh_ = logging.StreamHandler() + + formatter = logging.Formatter(LOG_FORMAT) + fh_.setFormatter(formatter) + + root.addHandler(fh_) diff --git a/trollsched/pass_scheduling_utils.py b/trollsched/pass_scheduling_utils.py new file mode 100644 index 0000000..ec8bf4d --- /dev/null +++ b/trollsched/pass_scheduling_utils.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright (c) 2024 Pytroll developers + +# Author(s): + +# Adam Dybbroe + +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +"""Common utilities for satellite pass and schedule calculations.""" + + +class SatScore: + """Container for the score parameter deciding which satellite pass to take.""" + + def __init__(self, day, night): + """Initialize the score.""" + self.day = day + self.night = night + + +class Satellite: + """The Satellite class holding information on its score, name and designator.""" + + def __init__(self, name, day, night, + schedule_name=None, international_designator=None): + """Initialize the satellite.""" + self.name = name + self.international_designator = international_designator + self.score = SatScore(day, night) + self.schedule_name = schedule_name or name diff --git a/trollsched/satpass.py b/trollsched/satpass.py index fbce8f8..55a6910 100644 --- a/trollsched/satpass.py +++ b/trollsched/satpass.py @@ -1,7 +1,7 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -# Copyright (c) 2014 - 2019, 2023 PyTroll Community +# Copyright (c) 2014 - 2024 Pytroll Community # Author(s): # Martin Raspaud @@ -24,6 +24,7 @@ import ftplib import glob +import hashlib import logging import logging.handlers import operator @@ -40,17 +41,25 @@ from pyorbital import orbital, tlefile from pyresample.boundary import AreaDefBoundary -from trollsched import MIN_PASS, JPSS_TLE_NAMES, NUMBER_OF_FOVS +from trollsched import ( + JPSS_TLE_NAMES, + MERSI2_PLATFORM_NAMES, + MERSI_PLATFORM_NAMES, + MIN_PASS, + NUMBER_OF_FOVS, + SATELLITE_MEOS_TRANSLATION, + VIIRS_PLATFORM_NAMES, +) from trollsched.boundary import SwathBoundary +from trollsched.pass_scheduling_utils import Satellite logger = logging.getLogger(__name__) -VIIRS_PLATFORM_NAMES = ["SUOMI NPP", "SNPP", - "NOAA-20", "NOAA 20"] -MERSI_PLATFORM_NAMES = ["FENGYUN 3C", "FENGYUN-3C", "FY-3C"] -MERSI2_PLATFORM_NAMES = ["FENGYUN 3D", "FENGYUN-3D", "FY-3D", - "FENGYUN 3E", "FENGYUN-3E", "FY-3E"] +def create_pass(satname, instrument, starttime, endtime, tle_filename=None): + """Create a satellite pass given a start and an endtime.""" + tle = tlefile.Tle(satname, tle_file=tle_filename) + return Pass(satname, starttime, endtime, instrument=instrument, tle1=tle.line1, tle2=tle.line2) class SimplePass: """A pass: satellite, risetime, falltime, (orbital).""" @@ -60,7 +69,6 @@ class SimplePass: def __init__(self, satellite, risetime, falltime): """Initialize the simple pass.""" if not hasattr(satellite, "name"): - from trollsched.schedule import Satellite self.satellite = Satellite(satellite, 0, 0) else: self.satellite = satellite @@ -295,20 +303,8 @@ def print_meos(self, coords, line_no): dur_minutes, dur_seconds = divmod(dur_reminder, 60) duration = "{:0>2}:{:0>2}".format(dur_minutes, dur_seconds) - satellite_meos_translation = {"NOAA 19": "NOAA_19", - "NOAA 18": "NOAA_18", - "NOAA 15": "NOAA_15", - "METOP-A": "M02", - "METOP-B": "M01", - "FENGYUN 3A": "FENGYUN-3A", - "FENGYUN 3B": "FENGYUN-3B", - "FENGYUN 3C": "FENGYUN-3C", - "SUOMI NPP": "NPP"} - - import hashlib - pass_key = hashlib.md5(("{:s}|{:d}|{:d}|{:.3f}|{:.3f}". # noqa : md5 is insecure, but not sensitive here. - format(satellite_meos_translation.get(self.satellite.name.upper(), + format(SATELLITE_MEOS_TRANSLATION.get(self.satellite.name.upper(), self.satellite.name.upper()), int(orbit), aos_epoch, @@ -335,7 +331,7 @@ def print_meos(self, coords, line_no): # line_no=line_no, line_no=1, date=self.risetime.strftime("%Y%m%d"), - satellite=satellite_meos_translation.get(self.satellite.name.upper(), + satellite=SATELLITE_MEOS_TRANSLATION.get(self.satellite.name.upper(), self.satellite.name.upper()), orbit=orbit, elevation=max_elevation, @@ -555,7 +551,6 @@ def get_next_passes(satellites, for sat in satellites: if not hasattr(sat, "name"): - from trollsched.schedule import Satellite sat = Satellite(sat, 0, 0) satorb = orbital.Orbital(sat.name, tle_file=tle_file) diff --git a/trollsched/schedule.py b/trollsched/schedule.py index 68c82b5..48b0983 100644 --- a/trollsched/schedule.py +++ b/trollsched/schedule.py @@ -1,4 +1,4 @@ -# Copyright (c) 2013 - 2019 PyTroll +# Copyright (c) 2013 - 2024 Pytroll community # Author(s): @@ -29,21 +29,14 @@ import numpy as np from pyorbital import astronomy - -from trollsched.writers import generate_meos_file, generate_metno_xml_file, generate_sch_file, generate_xml_file - -try: - from pyresample import parse_area_file -except ImportError: - # Older versions of pyresample: - from pyresample.utils import parse_area_file - +from pyresample import parse_area_file from trollsched import MIN_PASS, utils from trollsched.combine import get_combined_sched from trollsched.graph import Graph from trollsched.satpass import SimplePass, get_next_passes from trollsched.spherical import get_twilight_poly +from trollsched.writers import generate_meos_file, generate_metno_xml_file, generate_sch_file, generate_xml_file logger = logging.getLogger(__name__) @@ -211,26 +204,6 @@ def get_next_passes(self, opts, sched, start_time, tle_file): return allpasses -class SatScore: - """docstring for SatScore.""" - - def __init__(self, day, night): - """Initialize the score.""" - self.day = day - self.night = night - - -class Satellite: - """docstring for Satellite.""" - - def __init__(self, name, day, night, - schedule_name=None, international_designator=None): - """Initialize the satellite.""" - self.name = name - self.international_designator = international_designator - self.score = SatScore(day, night) - self.schedule_name = schedule_name or name - class Scheduler: """docstring for Scheduler.""" @@ -319,7 +292,7 @@ def fermib(t): return 1 / (np.exp((t - a) / b) + 1) -combination = {} +combination: dict[SimplePass, SimplePass] = {} def combine(p1, p2, area_of_interest): @@ -442,8 +415,7 @@ def get_best_sched(overpasses, area_of_interest, delay, avoid_list=None): graph = Graph(n_vertices=n_vertices + 2) def add_arc(graph, p1, p2, hook=None): - logger.debug("Adding arc between " + str(p1) + - " and " + str(p2) + "...") + logger.debug(f"Adding arc between {p1} and {p2}...") if p1 in avoid_list or p2 in avoid_list: w = 0 logger.debug("...0 because in the avoid_list!") @@ -451,12 +423,7 @@ def add_arc(graph, p1, p2, hook=None): w = combine(p1, p2, area_of_interest) logger.debug("...with weight " + str(w)) -# with open("/tmp/schedule.gv", "a") as fp_: -# fp_.write(' "' + str(p1) + '" -> "' + str(p2) + -# '" [ label = "' + str(w) + '" ];\n') - - graph.add_arc(passes.index(p1) + 1, - passes.index(p2) + 1, w) + graph.add_arc(passes.index(p1) + 1, passes.index(p2) + 1, w) if hook is not None: hook() @@ -822,7 +789,7 @@ def parse_args(args=None): description="(additional parameter changing behaviour)") group_spec.add_argument("-a", "--avoid", default=[], - nargs='*', + nargs="*", help="xml request file(s) with passes to avoid") group_spec.add_argument("--no-aqua-terra-dump", action="store_false", help="do not consider Aqua/Terra-dumps") diff --git a/trollsched/shapefiles_from_schedule.py b/trollsched/shapefiles_from_schedule.py new file mode 100644 index 0000000..13092d8 --- /dev/null +++ b/trollsched/shapefiles_from_schedule.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright (c) 2024 Pytroll community + +# Author(s): + +# Adam Dybbroe + +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +"""Create shapefiles of satellite instrument swath outlines from an XML pass reception plan.""" + + +import argparse +import logging +from datetime import datetime +from pathlib import Path + +import defusedxml.ElementTree as ET +import geopandas as gpd +import numpy as np +import pandas as pd +import pyproj +from shapely.geometry import Polygon +from shapely.ops import transform + +from trollsched import INSTRUMENT, SATELLITE_NAMES +from trollsched.logger import setup_logging +from trollsched.satpass import create_pass + +logger = logging.getLogger(__name__) + + +def get_shapely_polygon_from_lonlat(lons, lats): + """From a arrays of lons and lats return a shapely Polygon.""" + geodata = np.vstack((lons, lats)).T + return Polygon(np.rad2deg(geodata)) + + +def create_shapefile_filename(satellite_pass_obj): + """From a trollsched.satpass instance create the shapefile filename.""" + satname = satellite_pass_obj.satellite.name.replace(" ", "-") + prefix = f"{satellite_pass_obj.instrument}_{satname}" + return f"{prefix}_{satellite_pass_obj.risetime:%Y%m%d%H%M}_{satellite_pass_obj.falltime:%Y%m%d%H%M}_outline.shp" + + +def create_shapefile_from_pass(sat_pass, output_filepath): + """From a satellite overpass (instrument scanning outline) create a shapefile and save.""" + sat_poly = get_shapely_polygon_from_lonlat(sat_pass.boundary.contour_poly.lon, + sat_pass.boundary.contour_poly.lat) + + wgs84 = pyproj.CRS("EPSG:4326") # WGS 84 + a_crs = {"init": "epsg:4326"} + + project = pyproj.Transformer.from_crs(wgs84, a_crs, always_xy=True).transform + new_shapes = transform(project, sat_poly) + + gpd.GeoDataFrame(pd.DataFrame(["p1"], columns=["geom"]), crs=a_crs, + geometry=[new_shapes]).to_file(output_filepath) + + +def shapefiles_from_schedule_xml_requests(filename, satellites, tle_file, output_dir): + """From XML file with planned satellite passes create shapefiles for each Pass outline. + + Open the XML file with the scheduled satellite pass plan, and create + shapefiles for each Pass outline assuming the instrument as provided in the + INSTRUMENTS dictionary. + """ + tree = ET.parse(filename) + root = tree.getroot() + + for child in root: + if child.tag == "pass": + platform_name = SATELLITE_NAMES.get(child.attrib["satellite"], child.attrib["satellite"]) + instrument = INSTRUMENT.get(platform_name) + if not instrument: + logger.debug("Instrument not defined for platform %s", platform_name) + continue + + if platform_name not in satellites: + logger.debug("Satellite platform name not requested: %s", platform_name) + continue + try: + overpass = create_pass(platform_name, instrument, + datetime.strptime(child.attrib["start-time"], + "%Y-%m-%d-%H:%M:%S"), + datetime.strptime(child.attrib["end-time"], + "%Y-%m-%d-%H:%M:%S"), + tle_filename=tle_file) + except KeyError: + logger.warning(("Failed creating an pass instance for the overpass, for platform " + "%s, instrument %s, and start-end times (%s,%s)"), + platform_name, instrument, child.attrib["start-time"], child.attrib["end-time"]) + continue + + output_filepath = Path(output_dir) / create_shapefile_filename(overpass) + create_shapefile_from_pass(overpass, output_filepath) + + +def parse_args(args): + """Parse command line arguments.""" + parser = argparse.ArgumentParser() + parser.add_argument("-l", "--log-config", + dest="log_config", + default=None, + required=False, + help="Log config file to use instead of the standard logging.") + parser.add_argument("-s", "--satellites", + dest="list_of_satellites", + nargs="*", + default=[], + help="Complete file path to the TLE file to use.", + required=True) + parser.add_argument("-t", "--tle_filename", + dest="tle_filepath", + help="Complete file path to the TLE file to use.", + required=True) + parser.add_argument("-x", "--xml_filename", + dest="xml_filepath", + help="Complete path to the XML satellite schedule file.", + required=True) + parser.add_argument("-o", "--output_dir", + dest="output_dir", + help="Complete path to the XML satellite schedule file.", + default="./") + parser.add_argument("-v", "--verbose", + dest="verbosity", + action="count", + default=0, + help="Verbosity (between 1 and 2 occurrences with more leading to more " + "verbose logging). WARN=0, INFO=1, " + "DEBUG=2. This is overridden by the log config file if specified.") + + return parser.parse_args(args) + + +def run(args=None): + """Create shapefiles from an XML schedule of satellite passes.""" + opts = parse_args(args) + + setup_logging(opts) + filename = opts.xml_filepath + satellites = opts.list_of_satellites + tle_filename = opts.tle_filepath + outdir = opts.output_dir + + shapefiles_from_schedule_xml_requests(filename, + satellites, + tle_filename, + outdir) diff --git a/trollsched/tests/conftest.py b/trollsched/tests/conftest.py new file mode 100644 index 0000000..6cdd7b1 --- /dev/null +++ b/trollsched/tests/conftest.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright (c) 2024 Adam.Dybbroe + +# Author(s): + +# Adam.Dybbroe + +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +"""Fixtures for unit testing.""" + + +from datetime import datetime, timedelta + +import pytest + +from trollsched.satpass import create_pass + +# Create a fake TLE file for testing. +TEST_TLEFILE1 = """NOAA-20 +1 43013U 17073A 24260.23673431 .00000000 00000+0 20543-3 0 00012 +2 43013 98.7102 196.6451 0000981 27.6583 181.3633 14.19588904353826 +""" + +FAKE_XML_SCHEDULE = """Pytrollrequestnrk2024-12-02-21:54:342024-12-02-23:54:34SMHI2024-12-02-19:55:05""" # noqa + +TEST_TLEFILE2 = """NOAA-20 +1 43013U 17073A 24336.73680280 .00000000 00000+0 21070-3 0 00017 +2 43013 98.7240 271.9468 0002361 91.7021 243.0836 14.19579317364671 +NOAA 18 +1 28654U 05018A 24336.77887833 .00000603 00000+0 34401-3 0 9991 +2 28654 98.8621 52.2610 0013351 310.3593 49.6413 14.13439071 6932 +SUOMI NPP +1 37849U 11061A 24336.86623462 .00000353 00000+0 18825-3 0 9992 +2 37849 98.7391 272.4265 0002092 106.9131 253.2275 14.19509233678657 +""" + +@pytest.fixture +def fake_tle_file(tmp_path): + """Write fake TLE file.""" + file_path = tmp_path / "sometles.txt" + with open(file_path, "w") as fpt: + fpt.write(TEST_TLEFILE1) + + return file_path + +@pytest.fixture +def fake_long_tle_file(tmp_path): + """Write fake TLE file.""" + file_path = tmp_path / "some_more_tles.txt" + with open(file_path, "w") as fpt: + fpt.write(TEST_TLEFILE2) + + return file_path + +@pytest.fixture +def fake_noaa20_viirs_pass_instance(fake_tle_file): + """Create a fake trollsched.,satpass instance for NOAA-20 VIIRS.""" + starttime = datetime(2024, 9, 17, 1, 25, 52) + endtime = starttime + timedelta(minutes=15) + return create_pass("NOAA-20", "viirs", starttime, endtime, str(fake_tle_file)) + +@pytest.fixture +def fake_xml_schedule_file(tmp_path): + """Create a fake XML schedule file.""" + file_path = tmp_path / "20241202-195434-aquisition-schedule-request-nrk.xml" + with open(file_path, "w") as fpt: + fpt.write(FAKE_XML_SCHEDULE) + + return file_path diff --git a/trollsched/tests/test_pass_outlines.py b/trollsched/tests/test_pass_outlines.py new file mode 100644 index 0000000..aae2e74 --- /dev/null +++ b/trollsched/tests/test_pass_outlines.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright (c) 2024 Pytroll Community + + +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +"""Test the creation and storing of satellite pass instrument swath outlines.""" + + +import numpy as np +import pytest +import shapely + +from trollsched.shapefiles_from_schedule import ( + create_shapefile_filename, + create_shapefile_from_pass, + get_shapely_polygon_from_lonlat, + run, +) + +CONT_POLY_LON = np.array([-2.13452262, -2.29587336, -2.71901413, 2.49884179, 1.84466852, + 1.62370346, 1.52297613, 1.46583198, 1.42884581, 1.40275172, + 1.38319053, 1.36784925, 1.35538792, 1.34497645, 1.33607268, + 1.32830685, 1.32141745, 1.31521366, 1.30955222, 1.30432275, + 1.29943799, 1.29482714, 1.29043107, 1.28619883, 1.2820848 , + 1.27804628, 1.27404108, 1.27002472, 1.26594662, 1.26174386, + 1.25732922, 1.25256377, 1.24720486, 1.01188742, 0.79409035, + 0.6071801, 0.4536726, 0.32966584, 0.22939162, 0.14748665, + -0.00471426, -0.05349142, -0.08929434, -0.11753567, -0.14089485, + -0.1608663 , -0.17837565, -0.1940391, -0.20828969, -0.2214453, + -0.23374812, -0.24538904, -0.25652346, -0.26728206, -0.27777851, + -0.28811526, -0.29838809, -0.30869016, -0.31911562, -0.32976349, + -0.34074184, -0.35217288, -0.36419961, -0.37699468, -0.39077317, + -0.40581154, -0.42247709, -0.44127621, -0.46293831, -0.48857303, + -0.5199966 , -0.56051525, -0.61729867, -0.61753171, -0.62771892, + -0.64829722, -0.68661816, -0.75917567, -0.9100173, -1.27984447], + "float64") +CONT_POLY_LAT = np.array([1.47665956, 1.5181844 , 1.54460102, 1.55163844, 1.54000093, + 1.52570241, 1.51231719, 1.50010348, 1.48891231, 1.47855701, + 1.46887101, 1.45971388, 1.45096745, 1.44253069, 1.43431507, + 1.42624067, 1.41823286, 1.41021941, 1.40212764, 1.39388163, + 1.38539899, 1.37658705, 1.36733796, 1.35752199, 1.34697812, + 1.33549993, 1.32281374, 1.30854277, 1.29214467, 1.27279422, + 1.24913883, 1.21870824, 1.17637107, 1.16993658, 1.14394582, + 1.10161427, 1.04685251, 0.98308241, 0.91287235, 0.83802526, + 0.63421758, 0.64926881, 0.65941499, 0.66689569, 0.67274331, + 0.67750383, 0.68149934, 0.68493465, 0.68794744, 0.69063434, + 0.69306561, 0.6952939 , 0.6973597 , 0.69929488, 0.7011251 , + 0.7028715 , 0.7045518 , 0.70618126, 0.70777322, 0.70933965, + 0.7108915 , 0.71243895, 0.71399159, 0.71555848, 0.71714804, + 0.71876762, 0.72042255, 0.72211402, 0.72383449, 0.72555719, + 0.72721033, 0.72860415, 0.72917251, 0.95338892, 1.04189611, + 1.12986537, 1.21694627, 1.30234019, 1.38380771, 1.45301036], + "float64") + + +def test_get_shapely_polygon_from_lonlat(): + """Test getting a polygon from a swath contour polygon.""" + sat_poly = get_shapely_polygon_from_lonlat(CONT_POLY_LON, CONT_POLY_LAT) + + assert isinstance(sat_poly, shapely.geometry.polygon.Polygon) + assert sat_poly.is_valid + assert sat_poly.is_simple + assert sat_poly.is_closed is False + np.testing.assert_almost_equal(sat_poly.length, 649.84664, decimal=5) + + +@pytest.mark.usefixtures("fake_noaa20_viirs_pass_instance") +def test_create_shapefile_filename(fake_noaa20_viirs_pass_instance): + """Test creating the shapefile filename from a NOAA-20/VIIRS trollsched.satpass instance.""" + result = create_shapefile_filename(fake_noaa20_viirs_pass_instance) + assert result == "viirs_NOAA-20_202409170125_202409170140_outline.shp" + + +@pytest.mark.usefixtures("fake_noaa20_viirs_pass_instance") +def test_create_shapefile_from_pass(fake_noaa20_viirs_pass_instance, tmp_path): + """Test create a shapefile from a fake NOAA-20/VIIRS pass.""" + tmp_filename = tmp_path / "fake_noaa20_viirs_shapefile.shp" + create_shapefile_from_pass(fake_noaa20_viirs_pass_instance, tmp_filename) + assert tmp_filename.exists() + nfiles = len([f for f in tmp_filename.parent.glob("fake_noaa20_viirs_shapefile.*")]) + assert nfiles == 5 + + +@pytest.mark.usefixtures("fake_long_tle_file") +@pytest.mark.usefixtures("fake_xml_schedule_file") +def test_create_shapefiles_from_schedule(fake_xml_schedule_file, fake_long_tle_file, tmp_path): + """Test running the script to create shapefiles from an xml schedule request file.""" + output_dir = tmp_path / "results" + output_dir.mkdir() + + args = ["-s", "Suomi NPP", "NOAA 18", "NOAA-20", "-t", str(fake_long_tle_file), + "-x", str(fake_xml_schedule_file), + "-o", str(output_dir)] + run(args) + + n18files = [str(name) for name in output_dir.glob("avhrr_NOAA-18_202412022201_202412022216_outline.*")] + assert len(n18files) == 5 + nppfiles = [str(name) for name in output_dir.glob("viirs_Suomi-NPP_202412022238_202412022249_outline.*")] + assert len(nppfiles) == 5 + n20files = [str(name) for name in output_dir.glob("viirs_NOAA-20_202412022301_202412022314_outline.*")] + assert len(n20files) == 5 diff --git a/trollsched/tests/test_satpass.py b/trollsched/tests/test_satpass.py index 59711a0..06426eb 100644 --- a/trollsched/tests/test_satpass.py +++ b/trollsched/tests/test_satpass.py @@ -1,7 +1,7 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -# Copyright (c) 2018 - 2021, 2024 Pytroll-schedule developers +# Copyright (c) 2018 - 2024 Pytroll-schedule developers # Author(s): @@ -30,9 +30,8 @@ from pyorbital.orbital import Orbital from pyresample.geometry import AreaDefinition, create_area_def -from trollsched.boundary import SwathBoundary -from trollsched.boundary import InstrumentNotSupported -from trollsched.satpass import Pass +from trollsched.boundary import InstrumentNotSupported, SwathBoundary +from trollsched.satpass import Pass, create_pass LONS1 = np.array([-122.29913729160562, -131.54385362589042, -155.788034272281, 143.1730880418349, 105.69172088208997, 93.03135571771092, @@ -168,9 +167,7 @@ def get_mb_orbital(): def get_s3a_orbital(): - """ - From 2022-06-06 - """ + """From 2022-06-06.""" tle1 = "1 41335U 16011A 22157.82164820 .00000041 00000-0 34834-4 0 9994" tle2 = "2 41335 98.6228 225.2825 0001265 95.7364 264.3961 14.26738817328255" return Orbital("Sentinel-3A", line1=tle1, line2=tle2) @@ -351,10 +348,10 @@ def test_swath_coverage_slstr_not_supported(self): tle1 = "1 41335U 16011A 22156.83983125 .00000043 00000-0 35700-4 0 9996" tle2 = "2 41335 98.6228 224.3150 0001264 95.7697 264.3627 14.26738650328113" - mypass = Pass('SENTINEL 3A', tstart, tend, instrument='slstr', tle1=tle1, tle2=tle2) + mypass = Pass("SENTINEL 3A", tstart, tend, instrument="slstr", tle1=tle1, tle2=tle2) with pytest.raises(InstrumentNotSupported) as exec_info: - cov = mypass.area_coverage(self.euron1) + mypass.area_coverage(self.euron1) assert str(exec_info.value) == "SLSTR is a conical scanner, and currently not supported!" @@ -442,3 +439,49 @@ def test_generate_metno_xml(self): def tearDown(self): """Clean up.""" pass + + +@pytest.mark.usefixtures("fake_tle_file") +def test_create_pass(fake_tle_file): + """Test creating a pass given a start and an end-time, platform, instrument and TLE-filepath.""" + starttime = datetime(2024, 9, 17, 1, 25, 52) + endtime = starttime + timedelta(minutes=15) + apass = create_pass("NOAA-20", "viirs", starttime, endtime, str(fake_tle_file)) + + assert isinstance(apass, Pass) + assert apass.risetime == datetime(2024, 9, 17, 1, 25, 52) + assert apass.falltime == datetime(2024, 9, 17, 1, 40, 52) + contours = apass.boundary.contour() + + np.testing.assert_array_almost_equal(contours[0], np.array([ + -70.36110203, -67.46084331, -37.31525344, 15.33742429, + 45.70673859, 58.20758754, 64.53232683, 68.33939709, + 70.91122142, 72.79385654, 74.25646605, 75.44689972, + 76.45347206, 77.33271412, 78.12312657, 78.85259555, + 79.5427448, 80.21178505, 80.87674043, 81.55576564, + 82.27163678, 83.05937724, 83.99111296, 84.1678927 , + 71.14095118, 59.65602344, 50.0921629 , 42.33689333, + 36.07906912, 30.99289682, 26.80566985, 23.30761782, + 17.5195915, 16.76660935, 13.3562137 , 11.05669417, + 9.31517975, 7.90416741, 6.70609822, 5.65154688, + 4.69542071, 3.80603134, 2.95939777, 2.13592964, + 1.31825077, 0.48953714, -0.3680201, -1.27496102, + -2.25693369, -3.34841058, -4.59918301, -6.08698296, + -7.94529693, -10.43647307, -14.21005445, -15.07433768, + -14.49280142, -14.53229624, -14.87821968, -15.67970647, + -17.21558546, -20.06333116, -25.60407459, -37.83432182], dtype="float64")) + + np.testing.assert_array_almost_equal(contours[1], np.array([ + 84.33463271, 84.996855, 87.51595932, 87.91311185, 87.0788011 , + 86.08609579, 85.16108707, 84.31800847, 83.54109034, 82.81224557, + 82.11521918, 81.4355823 , 80.75994129, 80.07498982, 79.36644307, + 78.61771056, 77.80801807, 76.90942731, 75.88160126, 74.66160838, + 73.14141261, 71.10852475, 68.03499509, 67.34603232, 66.29582898, + 64.22360654, 61.34855651, 57.88332007, 53.99536906, 49.80456636, + 45.39366513, 40.81954787, 30.76199763, 30.98222964, 31.91529108, + 32.48607791, 32.88793494, 33.1947272 , 33.44223661, 33.65034541, + 33.8311831 , 33.99269414, 34.14039982, 34.27835064, 34.40968082, + 34.53695383, 34.66239272, 34.78804435, 34.91590262, 35.047996 , + 35.18641366, 35.33315856, 35.48940778, 35.65238903, 35.79943487, + 35.81635723, 46.51491314, 51.61438345, 56.69722991, 61.75596299, + 66.7771717 , 71.73310959, 76.55555826, 81.03181048], dtype="float64")) diff --git a/trollsched/tests/test_schedule.py b/trollsched/tests/test_schedule.py index 7f9cf7e..322a051 100644 --- a/trollsched/tests/test_schedule.py +++ b/trollsched/tests/test_schedule.py @@ -1,7 +1,7 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -# Copyright (c) 2014 - 2019 PyTroll +# Copyright (c) 2014 - 2024 Pytroll # Author(s): @@ -31,7 +31,7 @@ import yaml from trollsched.satpass import get_aqua_terra_dumps, get_metopa_passes, get_next_passes -from trollsched.schedule import build_filename, conflicting_passes, fermia, fermib, run, get_passes_from_xml_file +from trollsched.schedule import build_filename, conflicting_passes, fermia, fermib, get_passes_from_xml_file, run class TestTools: @@ -89,7 +89,7 @@ def setup_method(self): """Set up.""" from pyorbital import orbital - from trollsched.schedule import Satellite + from trollsched.pass_scheduling_utils import Satellite self.utctime = datetime(2018, 11, 28, 10, 0) self.satellites = ["noaa-20", ] diff --git a/trollsched/utils.py b/trollsched/utils.py index f610e8c..ee18e9b 100644 --- a/trollsched/utils.py +++ b/trollsched/utils.py @@ -1,7 +1,7 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- # -# Copyright (c) 2017, 2018 Alexander Maul +# Copyright (c) 2017, 2018, 2024 Alexander Maul # # Author(s): # @@ -20,17 +20,14 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -"""Utility functions and config reading for the pytroll-scheduler -""" -import warnings - -import yaml +"""Utility functions and config reading for the pytroll-scheduler.""" import logging from collections.abc import Mapping -from configparser import ConfigParser -from trollsched import schedule +import yaml +from trollsched import schedule +from trollsched.pass_scheduling_utils import Satellite logger = logging.getLogger("trollsched") @@ -65,7 +62,7 @@ def recursive_dict_update(d, u): def read_config(filename): try: return read_config_yaml(filename) - except yaml.parser.ParserError as e: + except yaml.parser.ParserError: logger.error("INI format for scheduler config is deprecated since v0.3.4, " "please update your configuration to YAML.") raise @@ -73,22 +70,21 @@ def read_config(filename): def read_config_yaml(filename): """Read the yaml file *filename* and create a scheduler.""" - cfg = read_yaml_file(filename) - satellites = {sat_name: schedule.Satellite(sat_name, **sat_params) + satellites = {sat_name: Satellite(sat_name, **sat_params) for (sat_name, sat_params) in cfg["satellites"].items()} stations = {} for station_id, station in cfg["stations"].items(): - if isinstance(station['satellites'], dict): + if isinstance(station["satellites"], dict): sat_list = [] for (sat_name, sat_params) in station["satellites"].items(): if sat_params is None: sat_list.append(satellites[sat_name]) else: - sat_list.append(schedule.Satellite(sat_name, **sat_params)) + sat_list.append(Satellite(sat_name, **sat_params)) else: - sat_list = [satellites[sat_name] for sat_name in station['satellites']] + sat_list = [satellites[sat_name] for sat_name in station["satellites"]] new_station = schedule.Station(station_id, **station) new_station.satellites = sat_list stations[station_id] = new_station @@ -97,18 +93,18 @@ def read_config_yaml(filename): for k, v in cfg["pattern"].items(): pattern[k] = v - sched_params = cfg['default'] - plot_parameters = sched_params.get('plot_parameters', {}) - plot_title = sched_params.get('plot_title', None) + sched_params = cfg["default"] + plot_parameters = sched_params.get("plot_parameters", {}) + plot_title = sched_params.get("plot_title", None) scheduler = schedule.Scheduler(stations=[stations[st_id] - for st_id in sched_params['station']], - min_pass=sched_params.get('min_pass', 4), - forward=sched_params['forward'], - start=sched_params['start'], - dump_url=sched_params.get('dump_url'), + for st_id in sched_params["station"]], + min_pass=sched_params.get("min_pass", 4), + forward=sched_params["forward"], + start=sched_params["start"], + dump_url=sched_params.get("dump_url"), patterns=pattern, - center_id=sched_params.get('center_id', 'unknown'), + center_id=sched_params.get("center_id", "unknown"), plot_parameters=plot_parameters, plot_title=plot_title) diff --git a/trollsched/version.py b/trollsched/version.py deleted file mode 100644 index 67fd964..0000000 --- a/trollsched/version.py +++ /dev/null @@ -1,683 +0,0 @@ - -# This file helps to compute a version number in source trees obtained from -# git-archive tarball (such as those provided by githubs download-from-tag -# feature). Distribution tarballs (built by setup.py sdist) and build -# directories (produced by setup.py build) will contain a much shorter file -# that just contains the computed version number. - -# This file is released into the public domain. -# Generated by versioneer-0.29 -# https://github.com/python-versioneer/python-versioneer - -"""Git implementation of _version.py.""" - -import errno -import os -import re -import subprocess -import sys -from typing import Any, Callable, Dict, List, Optional, Tuple -import functools - - -def get_keywords() -> Dict[str, str]: - """Get the keywords needed to look up the version information.""" - # these strings will be replaced by git during git-archive. - # setup.py/versioneer.py will grep for the variable names, so they must - # each be defined on a line of their own. _version.py will just call - # get_keywords(). - git_refnames = "$Format:%d$" - git_full = "$Format:%H$" - git_date = "$Format:%ci$" - keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} - return keywords - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - VCS: str - style: str - tag_prefix: str - parentdir_prefix: str - versionfile_source: str - verbose: bool - - -def get_config() -> VersioneerConfig: - """Create, populate and return the VersioneerConfig() object.""" - # these strings are filled in when 'setup.py versioneer' creates - # _version.py - cfg = VersioneerConfig() - cfg.VCS = "git" - cfg.style = "pep440" - cfg.tag_prefix = "v" - cfg.parentdir_prefix = "" - cfg.versionfile_source = "trollsched/version.py" - cfg.verbose = False - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -LONG_VERSION_PY: Dict[str, str] = {} -HANDLERS: Dict[str, Dict[str, Callable]] = {} - - -def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator - """Create decorator to mark a method as the handler of a VCS.""" - def decorate(f: Callable) -> Callable: - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -def run_command( - commands: List[str], - args: List[str], - cwd: Optional[str] = None, - verbose: bool = False, - hide_stderr: bool = False, - env: Optional[Dict[str, str]] = None, -) -> Tuple[Optional[str], Optional[int]]: - """Call the given command(s).""" - assert isinstance(commands, list) - process = None - - popen_kwargs: Dict[str, Any] = {} - if sys.platform == "win32": - # This hides the console window if pythonw.exe is used - startupinfo = subprocess.STARTUPINFO() - startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW - popen_kwargs["startupinfo"] = startupinfo - - for command in commands: - try: - dispcmd = str([command] + args) - # remember shell=False, so use git.cmd on windows, not just git - process = subprocess.Popen([command] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None), **popen_kwargs) - break - except OSError as e: - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %s" % dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %s" % (commands,)) - return None, None - stdout = process.communicate()[0].strip().decode() - if process.returncode != 0: - if verbose: - print("unable to run %s (error)" % dispcmd) - print("stdout was %s" % stdout) - return None, process.returncode - return stdout, process.returncode - - -def versions_from_parentdir( - parentdir_prefix: str, - root: str, - verbose: bool, -) -> Dict[str, Any]: - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for _ in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %s but none started with prefix %s" % - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs: str) -> Dict[str, str]: - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords: Dict[str, str] = {} - try: - with open(versionfile_abs, "r") as fobj: - for line in fobj: - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - except OSError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords( - keywords: Dict[str, str], - tag_prefix: str, - verbose: bool, -) -> Dict[str, Any]: - """Get version information from git keywords.""" - if "refnames" not in keywords: - raise NotThisMethod("Short version file found") - date = keywords.get("date") - if date is not None: - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - - # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant - # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 - # -like" string, which we must then edit to make compliant), because - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = {r.strip() for r in refnames.strip("()").split(",")} - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = {r for r in refs if re.search(r'\d', r)} - if verbose: - print("discarding '%s', no digits" % ",".join(refs - tags)) - if verbose: - print("likely tags: %s" % ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - # Filter out refs that exactly match prefix or that don't start - # with a number once the prefix is stripped (mostly a concern - # when prefix is '') - if not re.match(r'\d', r): - continue - if verbose: - print("picking %s" % r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs( - tag_prefix: str, - root: str, - verbose: bool, - runner: Callable = run_command -) -> Dict[str, Any]: - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - # GIT_DIR can interfere with correct operation of Versioneer. - # It may be intended to be passed to the Versioneer-versioned project, - # but that should not change where we get our version from. - env = os.environ.copy() - env.pop("GIT_DIR", None) - runner = functools.partial(runner, env=env) - - _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=not verbose) - if rc != 0: - if verbose: - print("Directory %s not under git control" % root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = runner(GITS, [ - "describe", "--tags", "--dirty", "--always", "--long", - "--match", f"{tag_prefix}[[:digit:]]*" - ], cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces: Dict[str, Any] = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], - cwd=root) - # --abbrev-ref was added in git-1.6.3 - if rc != 0 or branch_name is None: - raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") - branch_name = branch_name.strip() - - if branch_name == "HEAD": - # If we aren't exactly on a branch, pick a branch which represents - # the current commit. If all else fails, we are on a branchless - # commit. - branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) - # --contains was added in git-1.5.4 - if rc != 0 or branches is None: - raise NotThisMethod("'git branch --contains' returned error") - branches = branches.split("\n") - - # Remove the first line if we're running detached - if "(" in branches[0]: - branches.pop(0) - - # Strip off the leading "* " from the list of branches. - branches = [branch[2:] for branch in branches] - if "master" in branches: - branch_name = "master" - elif not branches: - branch_name = None - else: - # Pick the first branch that is returned. Good or bad. - branch_name = branches[0] - - pieces["branch"] = branch_name - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparsable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%s' doesn't start with prefix '%s'" - print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) - pieces["distance"] = len(out.split()) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - - return pieces - - -def plus_or_dot(pieces: Dict[str, Any]) -> str: - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces: Dict[str, Any]) -> str: - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_branch(pieces: Dict[str, Any]) -> str: - """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . - - The ".dev0" means not master branch. Note that .dev0 sorts backwards - (a feature branch will appear "older" than the master branch). - - Exceptions: - 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0" - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def pep440_split_post(ver: str) -> Tuple[str, Optional[int]]: - """Split pep440 version string at the post-release segment. - - Returns the release segments before the post-release and the - post-release version number (or -1 if no post-release segment is present). - """ - vc = str.split(ver, ".post") - return vc[0], int(vc[1] or 0) if len(vc) == 2 else None - - -def render_pep440_pre(pieces: Dict[str, Any]) -> str: - """TAG[.postN.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post0.devDISTANCE - """ - if pieces["closest-tag"]: - if pieces["distance"]: - # update the post release segment - tag_version, post_version = pep440_split_post(pieces["closest-tag"]) - rendered = tag_version - if post_version is not None: - rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"]) - else: - rendered += ".post0.dev%d" % (pieces["distance"]) - else: - # no commits, use the tag as the version - rendered = pieces["closest-tag"] - else: - # exception #1 - rendered = "0.post0.dev%d" % pieces["distance"] - return rendered - - -def render_pep440_post(pieces: Dict[str, Any]) -> str: - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - return rendered - - -def render_pep440_post_branch(pieces: Dict[str, Any]) -> str: - """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . - - The ".dev0" means not master branch. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_old(pieces: Dict[str, Any]) -> str: - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces: Dict[str, Any]) -> str: - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces: Dict[str, Any]) -> str: - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]: - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-branch": - rendered = render_pep440_branch(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-post-branch": - rendered = render_pep440_post_branch(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%s'" % style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} - - -def get_versions() -> Dict[str, Any]: - """Get version information or return default if unable to do so.""" - # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have - # __file__, we can work backwards from there to the root. Some - # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which - # case we can only use expanded keywords. - - cfg = get_config() - verbose = cfg.verbose - - try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) - except NotThisMethod: - pass - - try: - root = os.path.realpath(__file__) - # versionfile_source is the relative path from the top of the source - # tree (where the .git directory might live) to this file. Invert - # this to find the root from __file__. - for _ in cfg.versionfile_source.split('/'): - root = os.path.dirname(root) - except NameError: - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree", - "date": None} - - try: - pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) - return render(pieces, cfg.style) - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - except NotThisMethod: - pass - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", "date": None} diff --git a/versioneer.py b/versioneer.py deleted file mode 100644 index 1e3753e..0000000 --- a/versioneer.py +++ /dev/null @@ -1,2277 +0,0 @@ - -# Version: 0.29 - -"""The Versioneer - like a rocketeer, but for versions. - -The Versioneer -============== - -* like a rocketeer, but for versions! -* https://github.com/python-versioneer/python-versioneer -* Brian Warner -* License: Public Domain (Unlicense) -* Compatible with: Python 3.7, 3.8, 3.9, 3.10, 3.11 and pypy3 -* [![Latest Version][pypi-image]][pypi-url] -* [![Build Status][travis-image]][travis-url] - -This is a tool for managing a recorded version number in setuptools-based -python projects. The goal is to remove the tedious and error-prone "update -the embedded version string" step from your release process. Making a new -release should be as easy as recording a new tag in your version-control -system, and maybe making new tarballs. - - -## Quick Install - -Versioneer provides two installation modes. The "classic" vendored mode installs -a copy of versioneer into your repository. The experimental build-time dependency mode -is intended to allow you to skip this step and simplify the process of upgrading. - -### Vendored mode - -* `pip install versioneer` to somewhere in your $PATH - * A [conda-forge recipe](https://github.com/conda-forge/versioneer-feedstock) is - available, so you can also use `conda install -c conda-forge versioneer` -* add a `[tool.versioneer]` section to your `pyproject.toml` or a - `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md)) - * Note that you will need to add `tomli; python_version < "3.11"` to your - build-time dependencies if you use `pyproject.toml` -* run `versioneer install --vendor` in your source tree, commit the results -* verify version information with `python setup.py version` - -### Build-time dependency mode - -* `pip install versioneer` to somewhere in your $PATH - * A [conda-forge recipe](https://github.com/conda-forge/versioneer-feedstock) is - available, so you can also use `conda install -c conda-forge versioneer` -* add a `[tool.versioneer]` section to your `pyproject.toml` or a - `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md)) -* add `versioneer` (with `[toml]` extra, if configuring in `pyproject.toml`) - to the `requires` key of the `build-system` table in `pyproject.toml`: - ```toml - [build-system] - requires = ["setuptools", "versioneer[toml]"] - build-backend = "setuptools.build_meta" - ``` -* run `versioneer install --no-vendor` in your source tree, commit the results -* verify version information with `python setup.py version` - -## Version Identifiers - -Source trees come from a variety of places: - -* a version-control system checkout (mostly used by developers) -* a nightly tarball, produced by build automation -* a snapshot tarball, produced by a web-based VCS browser, like github's - "tarball from tag" feature -* a release tarball, produced by "setup.py sdist", distributed through PyPI - -Within each source tree, the version identifier (either a string or a number, -this tool is format-agnostic) can come from a variety of places: - -* ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows - about recent "tags" and an absolute revision-id -* the name of the directory into which the tarball was unpacked -* an expanded VCS keyword ($Id$, etc) -* a `_version.py` created by some earlier build step - -For released software, the version identifier is closely related to a VCS -tag. Some projects use tag names that include more than just the version -string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool -needs to strip the tag prefix to extract the version identifier. For -unreleased software (between tags), the version identifier should provide -enough information to help developers recreate the same tree, while also -giving them an idea of roughly how old the tree is (after version 1.2, before -version 1.3). Many VCS systems can report a description that captures this, -for example `git describe --tags --dirty --always` reports things like -"0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the -0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has -uncommitted changes). - -The version identifier is used for multiple purposes: - -* to allow the module to self-identify its version: `myproject.__version__` -* to choose a name and prefix for a 'setup.py sdist' tarball - -## Theory of Operation - -Versioneer works by adding a special `_version.py` file into your source -tree, where your `__init__.py` can import it. This `_version.py` knows how to -dynamically ask the VCS tool for version information at import time. - -`_version.py` also contains `$Revision$` markers, and the installation -process marks `_version.py` to have this marker rewritten with a tag name -during the `git archive` command. As a result, generated tarballs will -contain enough information to get the proper version. - -To allow `setup.py` to compute a version too, a `versioneer.py` is added to -the top level of your source tree, next to `setup.py` and the `setup.cfg` -that configures it. This overrides several distutils/setuptools commands to -compute the version when invoked, and changes `setup.py build` and `setup.py -sdist` to replace `_version.py` with a small static file that contains just -the generated version data. - -## Installation - -See [INSTALL.md](./INSTALL.md) for detailed installation instructions. - -## Version-String Flavors - -Code which uses Versioneer can learn about its version string at runtime by -importing `_version` from your main `__init__.py` file and running the -`get_versions()` function. From the "outside" (e.g. in `setup.py`), you can -import the top-level `versioneer.py` and run `get_versions()`. - -Both functions return a dictionary with different flavors of version -information: - -* `['version']`: A condensed version string, rendered using the selected - style. This is the most commonly used value for the project's version - string. The default "pep440" style yields strings like `0.11`, - `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section - below for alternative styles. - -* `['full-revisionid']`: detailed revision identifier. For Git, this is the - full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". - -* `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the - commit date in ISO 8601 format. This will be None if the date is not - available. - -* `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that - this is only accurate if run in a VCS checkout, otherwise it is likely to - be False or None - -* `['error']`: if the version string could not be computed, this will be set - to a string describing the problem, otherwise it will be None. It may be - useful to throw an exception in setup.py if this is set, to avoid e.g. - creating tarballs with a version string of "unknown". - -Some variants are more useful than others. Including `full-revisionid` in a -bug report should allow developers to reconstruct the exact code being tested -(or indicate the presence of local changes that should be shared with the -developers). `version` is suitable for display in an "about" box or a CLI -`--version` output: it can be easily compared against release notes and lists -of bugs fixed in various releases. - -The installer adds the following text to your `__init__.py` to place a basic -version in `YOURPROJECT.__version__`: - - from ._version import get_versions - __version__ = get_versions()['version'] - del get_versions - -## Styles - -The setup.cfg `style=` configuration controls how the VCS information is -rendered into a version string. - -The default style, "pep440", produces a PEP440-compliant string, equal to the -un-prefixed tag name for actual releases, and containing an additional "local -version" section with more detail for in-between builds. For Git, this is -TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags ---dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the -tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and -that this commit is two revisions ("+2") beyond the "0.11" tag. For released -software (exactly equal to a known tag), the identifier will only contain the -stripped tag, e.g. "0.11". - -Other styles are available. See [details.md](details.md) in the Versioneer -source tree for descriptions. - -## Debugging - -Versioneer tries to avoid fatal errors: if something goes wrong, it will tend -to return a version of "0+unknown". To investigate the problem, run `setup.py -version`, which will run the version-lookup code in a verbose mode, and will -display the full contents of `get_versions()` (including the `error` string, -which may help identify what went wrong). - -## Known Limitations - -Some situations are known to cause problems for Versioneer. This details the -most significant ones. More can be found on Github -[issues page](https://github.com/python-versioneer/python-versioneer/issues). - -### Subprojects - -Versioneer has limited support for source trees in which `setup.py` is not in -the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are -two common reasons why `setup.py` might not be in the root: - -* Source trees which contain multiple subprojects, such as - [Buildbot](https://github.com/buildbot/buildbot), which contains both - "master" and "slave" subprojects, each with their own `setup.py`, - `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI - distributions (and upload multiple independently-installable tarballs). -* Source trees whose main purpose is to contain a C library, but which also - provide bindings to Python (and perhaps other languages) in subdirectories. - -Versioneer will look for `.git` in parent directories, and most operations -should get the right version string. However `pip` and `setuptools` have bugs -and implementation details which frequently cause `pip install .` from a -subproject directory to fail to find a correct version string (so it usually -defaults to `0+unknown`). - -`pip install --editable .` should work correctly. `setup.py install` might -work too. - -Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in -some later version. - -[Bug #38](https://github.com/python-versioneer/python-versioneer/issues/38) is tracking -this issue. The discussion in -[PR #61](https://github.com/python-versioneer/python-versioneer/pull/61) describes the -issue from the Versioneer side in more detail. -[pip PR#3176](https://github.com/pypa/pip/pull/3176) and -[pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve -pip to let Versioneer work correctly. - -Versioneer-0.16 and earlier only looked for a `.git` directory next to the -`setup.cfg`, so subprojects were completely unsupported with those releases. - -### Editable installs with setuptools <= 18.5 - -`setup.py develop` and `pip install --editable .` allow you to install a -project into a virtualenv once, then continue editing the source code (and -test) without re-installing after every change. - -"Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a -convenient way to specify executable scripts that should be installed along -with the python package. - -These both work as expected when using modern setuptools. When using -setuptools-18.5 or earlier, however, certain operations will cause -`pkg_resources.DistributionNotFound` errors when running the entrypoint -script, which must be resolved by re-installing the package. This happens -when the install happens with one version, then the egg_info data is -regenerated while a different version is checked out. Many setup.py commands -cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into -a different virtualenv), so this can be surprising. - -[Bug #83](https://github.com/python-versioneer/python-versioneer/issues/83) describes -this one, but upgrading to a newer version of setuptools should probably -resolve it. - - -## Updating Versioneer - -To upgrade your project to a new release of Versioneer, do the following: - -* install the new Versioneer (`pip install -U versioneer` or equivalent) -* edit `setup.cfg` and `pyproject.toml`, if necessary, - to include any new configuration settings indicated by the release notes. - See [UPGRADING](./UPGRADING.md) for details. -* re-run `versioneer install --[no-]vendor` in your source tree, to replace - `SRC/_version.py` -* commit any changed files - -## Future Directions - -This tool is designed to make it easily extended to other version-control -systems: all VCS-specific components are in separate directories like -src/git/ . The top-level `versioneer.py` script is assembled from these -components by running make-versioneer.py . In the future, make-versioneer.py -will take a VCS name as an argument, and will construct a version of -`versioneer.py` that is specific to the given VCS. It might also take the -configuration arguments that are currently provided manually during -installation by editing setup.py . Alternatively, it might go the other -direction and include code from all supported VCS systems, reducing the -number of intermediate scripts. - -## Similar projects - -* [setuptools_scm](https://github.com/pypa/setuptools_scm/) - a non-vendored build-time - dependency -* [minver](https://github.com/jbweston/miniver) - a lightweight reimplementation of - versioneer -* [versioningit](https://github.com/jwodder/versioningit) - a PEP 518-based setuptools - plugin - -## License - -To make Versioneer easier to embed, all its code is dedicated to the public -domain. The `_version.py` that it creates is also in the public domain. -Specifically, both are released under the "Unlicense", as described in -https://unlicense.org/. - -[pypi-image]: https://img.shields.io/pypi/v/versioneer.svg -[pypi-url]: https://pypi.python.org/pypi/versioneer/ -[travis-image]: -https://img.shields.io/travis/com/python-versioneer/python-versioneer.svg -[travis-url]: https://travis-ci.com/github/python-versioneer/python-versioneer - -""" -# pylint:disable=invalid-name,import-outside-toplevel,missing-function-docstring -# pylint:disable=missing-class-docstring,too-many-branches,too-many-statements -# pylint:disable=raise-missing-from,too-many-lines,too-many-locals,import-error -# pylint:disable=too-few-public-methods,redefined-outer-name,consider-using-with -# pylint:disable=attribute-defined-outside-init,too-many-arguments - -import configparser -import errno -import json -import os -import re -import subprocess -import sys -from pathlib import Path -from typing import Any, Callable, cast, Dict, List, Optional, Tuple, Union -from typing import NoReturn -import functools - -have_tomllib = True -if sys.version_info >= (3, 11): - import tomllib -else: - try: - import tomli as tomllib - except ImportError: - have_tomllib = False - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - VCS: str - style: str - tag_prefix: str - versionfile_source: str - versionfile_build: Optional[str] - parentdir_prefix: Optional[str] - verbose: Optional[bool] - - -def get_root() -> str: - """Get the project root directory. - - We require that all commands are run from the project root, i.e. the - directory that contains setup.py, setup.cfg, and versioneer.py . - """ - root = os.path.realpath(os.path.abspath(os.getcwd())) - setup_py = os.path.join(root, "setup.py") - pyproject_toml = os.path.join(root, "pyproject.toml") - versioneer_py = os.path.join(root, "versioneer.py") - if not ( - os.path.exists(setup_py) - or os.path.exists(pyproject_toml) - or os.path.exists(versioneer_py) - ): - # allow 'python path/to/setup.py COMMAND' - root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) - setup_py = os.path.join(root, "setup.py") - pyproject_toml = os.path.join(root, "pyproject.toml") - versioneer_py = os.path.join(root, "versioneer.py") - if not ( - os.path.exists(setup_py) - or os.path.exists(pyproject_toml) - or os.path.exists(versioneer_py) - ): - err = ("Versioneer was unable to run the project root directory. " - "Versioneer requires setup.py to be executed from " - "its immediate directory (like 'python setup.py COMMAND'), " - "or in a way that lets it use sys.argv[0] to find the root " - "(like 'python path/to/setup.py COMMAND').") - raise VersioneerBadRootError(err) - try: - # Certain runtime workflows (setup.py install/develop in a setuptools - # tree) execute all dependencies in a single python process, so - # "versioneer" may be imported multiple times, and python's shared - # module-import table will cache the first one. So we can't use - # os.path.dirname(__file__), as that will find whichever - # versioneer.py was first imported, even in later projects. - my_path = os.path.realpath(os.path.abspath(__file__)) - me_dir = os.path.normcase(os.path.splitext(my_path)[0]) - vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) - if me_dir != vsr_dir and "VERSIONEER_PEP518" not in globals(): - print("Warning: build in %s is using versioneer.py from %s" - % (os.path.dirname(my_path), versioneer_py)) - except NameError: - pass - return root - - -def get_config_from_root(root: str) -> VersioneerConfig: - """Read the project setup.cfg file to determine Versioneer config.""" - # This might raise OSError (if setup.cfg is missing), or - # configparser.NoSectionError (if it lacks a [versioneer] section), or - # configparser.NoOptionError (if it lacks "VCS="). See the docstring at - # the top of versioneer.py for instructions on writing your setup.cfg . - root_pth = Path(root) - pyproject_toml = root_pth / "pyproject.toml" - setup_cfg = root_pth / "setup.cfg" - section: Union[Dict[str, Any], configparser.SectionProxy, None] = None - if pyproject_toml.exists() and have_tomllib: - try: - with open(pyproject_toml, 'rb') as fobj: - pp = tomllib.load(fobj) - section = pp['tool']['versioneer'] - except (tomllib.TOMLDecodeError, KeyError) as e: - print(f"Failed to load config from {pyproject_toml}: {e}") - print("Try to load it from setup.cfg") - if not section: - parser = configparser.ConfigParser() - with open(setup_cfg) as cfg_file: - parser.read_file(cfg_file) - parser.get("versioneer", "VCS") # raise error if missing - - section = parser["versioneer"] - - # `cast`` really shouldn't be used, but its simplest for the - # common VersioneerConfig users at the moment. We verify against - # `None` values elsewhere where it matters - - cfg = VersioneerConfig() - cfg.VCS = section['VCS'] - cfg.style = section.get("style", "") - cfg.versionfile_source = cast(str, section.get("versionfile_source")) - cfg.versionfile_build = section.get("versionfile_build") - cfg.tag_prefix = cast(str, section.get("tag_prefix")) - if cfg.tag_prefix in ("''", '""', None): - cfg.tag_prefix = "" - cfg.parentdir_prefix = section.get("parentdir_prefix") - if isinstance(section, configparser.SectionProxy): - # Make sure configparser translates to bool - cfg.verbose = section.getboolean("verbose") - else: - cfg.verbose = section.get("verbose") - - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -# these dictionaries contain VCS-specific tools -LONG_VERSION_PY: Dict[str, str] = {} -HANDLERS: Dict[str, Dict[str, Callable]] = {} - - -def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator - """Create decorator to mark a method as the handler of a VCS.""" - def decorate(f: Callable) -> Callable: - """Store f in HANDLERS[vcs][method].""" - HANDLERS.setdefault(vcs, {})[method] = f - return f - return decorate - - -def run_command( - commands: List[str], - args: List[str], - cwd: Optional[str] = None, - verbose: bool = False, - hide_stderr: bool = False, - env: Optional[Dict[str, str]] = None, -) -> Tuple[Optional[str], Optional[int]]: - """Call the given command(s).""" - assert isinstance(commands, list) - process = None - - popen_kwargs: Dict[str, Any] = {} - if sys.platform == "win32": - # This hides the console window if pythonw.exe is used - startupinfo = subprocess.STARTUPINFO() - startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW - popen_kwargs["startupinfo"] = startupinfo - - for command in commands: - try: - dispcmd = str([command] + args) - # remember shell=False, so use git.cmd on windows, not just git - process = subprocess.Popen([command] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None), **popen_kwargs) - break - except OSError as e: - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %s" % dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %s" % (commands,)) - return None, None - stdout = process.communicate()[0].strip().decode() - if process.returncode != 0: - if verbose: - print("unable to run %s (error)" % dispcmd) - print("stdout was %s" % stdout) - return None, process.returncode - return stdout, process.returncode - - -LONG_VERSION_PY['git'] = r''' -# This file helps to compute a version number in source trees obtained from -# git-archive tarball (such as those provided by githubs download-from-tag -# feature). Distribution tarballs (built by setup.py sdist) and build -# directories (produced by setup.py build) will contain a much shorter file -# that just contains the computed version number. - -# This file is released into the public domain. -# Generated by versioneer-0.29 -# https://github.com/python-versioneer/python-versioneer - -"""Git implementation of _version.py.""" - -import errno -import os -import re -import subprocess -import sys -from typing import Any, Callable, Dict, List, Optional, Tuple -import functools - - -def get_keywords() -> Dict[str, str]: - """Get the keywords needed to look up the version information.""" - # these strings will be replaced by git during git-archive. - # setup.py/versioneer.py will grep for the variable names, so they must - # each be defined on a line of their own. _version.py will just call - # get_keywords(). - git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" - git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" - git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" - keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} - return keywords - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - VCS: str - style: str - tag_prefix: str - parentdir_prefix: str - versionfile_source: str - verbose: bool - - -def get_config() -> VersioneerConfig: - """Create, populate and return the VersioneerConfig() object.""" - # these strings are filled in when 'setup.py versioneer' creates - # _version.py - cfg = VersioneerConfig() - cfg.VCS = "git" - cfg.style = "%(STYLE)s" - cfg.tag_prefix = "%(TAG_PREFIX)s" - cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" - cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" - cfg.verbose = False - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -LONG_VERSION_PY: Dict[str, str] = {} -HANDLERS: Dict[str, Dict[str, Callable]] = {} - - -def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator - """Create decorator to mark a method as the handler of a VCS.""" - def decorate(f: Callable) -> Callable: - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -def run_command( - commands: List[str], - args: List[str], - cwd: Optional[str] = None, - verbose: bool = False, - hide_stderr: bool = False, - env: Optional[Dict[str, str]] = None, -) -> Tuple[Optional[str], Optional[int]]: - """Call the given command(s).""" - assert isinstance(commands, list) - process = None - - popen_kwargs: Dict[str, Any] = {} - if sys.platform == "win32": - # This hides the console window if pythonw.exe is used - startupinfo = subprocess.STARTUPINFO() - startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW - popen_kwargs["startupinfo"] = startupinfo - - for command in commands: - try: - dispcmd = str([command] + args) - # remember shell=False, so use git.cmd on windows, not just git - process = subprocess.Popen([command] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None), **popen_kwargs) - break - except OSError as e: - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %%s" %% dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %%s" %% (commands,)) - return None, None - stdout = process.communicate()[0].strip().decode() - if process.returncode != 0: - if verbose: - print("unable to run %%s (error)" %% dispcmd) - print("stdout was %%s" %% stdout) - return None, process.returncode - return stdout, process.returncode - - -def versions_from_parentdir( - parentdir_prefix: str, - root: str, - verbose: bool, -) -> Dict[str, Any]: - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for _ in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %%s but none started with prefix %%s" %% - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs: str) -> Dict[str, str]: - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords: Dict[str, str] = {} - try: - with open(versionfile_abs, "r") as fobj: - for line in fobj: - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - except OSError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords( - keywords: Dict[str, str], - tag_prefix: str, - verbose: bool, -) -> Dict[str, Any]: - """Get version information from git keywords.""" - if "refnames" not in keywords: - raise NotThisMethod("Short version file found") - date = keywords.get("date") - if date is not None: - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - - # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant - # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 - # -like" string, which we must then edit to make compliant), because - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = {r.strip() for r in refnames.strip("()").split(",")} - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %%d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = {r for r in refs if re.search(r'\d', r)} - if verbose: - print("discarding '%%s', no digits" %% ",".join(refs - tags)) - if verbose: - print("likely tags: %%s" %% ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - # Filter out refs that exactly match prefix or that don't start - # with a number once the prefix is stripped (mostly a concern - # when prefix is '') - if not re.match(r'\d', r): - continue - if verbose: - print("picking %%s" %% r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs( - tag_prefix: str, - root: str, - verbose: bool, - runner: Callable = run_command -) -> Dict[str, Any]: - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - # GIT_DIR can interfere with correct operation of Versioneer. - # It may be intended to be passed to the Versioneer-versioned project, - # but that should not change where we get our version from. - env = os.environ.copy() - env.pop("GIT_DIR", None) - runner = functools.partial(runner, env=env) - - _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=not verbose) - if rc != 0: - if verbose: - print("Directory %%s not under git control" %% root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = runner(GITS, [ - "describe", "--tags", "--dirty", "--always", "--long", - "--match", f"{tag_prefix}[[:digit:]]*" - ], cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces: Dict[str, Any] = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], - cwd=root) - # --abbrev-ref was added in git-1.6.3 - if rc != 0 or branch_name is None: - raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") - branch_name = branch_name.strip() - - if branch_name == "HEAD": - # If we aren't exactly on a branch, pick a branch which represents - # the current commit. If all else fails, we are on a branchless - # commit. - branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) - # --contains was added in git-1.5.4 - if rc != 0 or branches is None: - raise NotThisMethod("'git branch --contains' returned error") - branches = branches.split("\n") - - # Remove the first line if we're running detached - if "(" in branches[0]: - branches.pop(0) - - # Strip off the leading "* " from the list of branches. - branches = [branch[2:] for branch in branches] - if "master" in branches: - branch_name = "master" - elif not branches: - branch_name = None - else: - # Pick the first branch that is returned. Good or bad. - branch_name = branches[0] - - pieces["branch"] = branch_name - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparsable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%%s'" - %% describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%%s' doesn't start with prefix '%%s'" - print(fmt %% (full_tag, tag_prefix)) - pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" - %% (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) - pieces["distance"] = len(out.split()) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = runner(GITS, ["show", "-s", "--format=%%ci", "HEAD"], cwd=root)[0].strip() - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - - return pieces - - -def plus_or_dot(pieces: Dict[str, Any]) -> str: - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces: Dict[str, Any]) -> str: - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_branch(pieces: Dict[str, Any]) -> str: - """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . - - The ".dev0" means not master branch. Note that .dev0 sorts backwards - (a feature branch will appear "older" than the master branch). - - Exceptions: - 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0" - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+untagged.%%d.g%%s" %% (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def pep440_split_post(ver: str) -> Tuple[str, Optional[int]]: - """Split pep440 version string at the post-release segment. - - Returns the release segments before the post-release and the - post-release version number (or -1 if no post-release segment is present). - """ - vc = str.split(ver, ".post") - return vc[0], int(vc[1] or 0) if len(vc) == 2 else None - - -def render_pep440_pre(pieces: Dict[str, Any]) -> str: - """TAG[.postN.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post0.devDISTANCE - """ - if pieces["closest-tag"]: - if pieces["distance"]: - # update the post release segment - tag_version, post_version = pep440_split_post(pieces["closest-tag"]) - rendered = tag_version - if post_version is not None: - rendered += ".post%%d.dev%%d" %% (post_version + 1, pieces["distance"]) - else: - rendered += ".post0.dev%%d" %% (pieces["distance"]) - else: - # no commits, use the tag as the version - rendered = pieces["closest-tag"] - else: - # exception #1 - rendered = "0.post0.dev%%d" %% pieces["distance"] - return rendered - - -def render_pep440_post(pieces: Dict[str, Any]) -> str: - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%%s" %% pieces["short"] - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%%s" %% pieces["short"] - return rendered - - -def render_pep440_post_branch(pieces: Dict[str, Any]) -> str: - """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . - - The ".dev0" means not master branch. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%%s" %% pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+g%%s" %% pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_old(pieces: Dict[str, Any]) -> str: - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces: Dict[str, Any]) -> str: - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces: Dict[str, Any]) -> str: - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]: - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-branch": - rendered = render_pep440_branch(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-post-branch": - rendered = render_pep440_post_branch(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%%s'" %% style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} - - -def get_versions() -> Dict[str, Any]: - """Get version information or return default if unable to do so.""" - # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have - # __file__, we can work backwards from there to the root. Some - # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which - # case we can only use expanded keywords. - - cfg = get_config() - verbose = cfg.verbose - - try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) - except NotThisMethod: - pass - - try: - root = os.path.realpath(__file__) - # versionfile_source is the relative path from the top of the source - # tree (where the .git directory might live) to this file. Invert - # this to find the root from __file__. - for _ in cfg.versionfile_source.split('/'): - root = os.path.dirname(root) - except NameError: - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree", - "date": None} - - try: - pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) - return render(pieces, cfg.style) - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - except NotThisMethod: - pass - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", "date": None} -''' - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs: str) -> Dict[str, str]: - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords: Dict[str, str] = {} - try: - with open(versionfile_abs, "r") as fobj: - for line in fobj: - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - except OSError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords( - keywords: Dict[str, str], - tag_prefix: str, - verbose: bool, -) -> Dict[str, Any]: - """Get version information from git keywords.""" - if "refnames" not in keywords: - raise NotThisMethod("Short version file found") - date = keywords.get("date") - if date is not None: - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - - # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant - # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 - # -like" string, which we must then edit to make compliant), because - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = {r.strip() for r in refnames.strip("()").split(",")} - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = {r for r in refs if re.search(r'\d', r)} - if verbose: - print("discarding '%s', no digits" % ",".join(refs - tags)) - if verbose: - print("likely tags: %s" % ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - # Filter out refs that exactly match prefix or that don't start - # with a number once the prefix is stripped (mostly a concern - # when prefix is '') - if not re.match(r'\d', r): - continue - if verbose: - print("picking %s" % r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs( - tag_prefix: str, - root: str, - verbose: bool, - runner: Callable = run_command -) -> Dict[str, Any]: - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - # GIT_DIR can interfere with correct operation of Versioneer. - # It may be intended to be passed to the Versioneer-versioned project, - # but that should not change where we get our version from. - env = os.environ.copy() - env.pop("GIT_DIR", None) - runner = functools.partial(runner, env=env) - - _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=not verbose) - if rc != 0: - if verbose: - print("Directory %s not under git control" % root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = runner(GITS, [ - "describe", "--tags", "--dirty", "--always", "--long", - "--match", f"{tag_prefix}[[:digit:]]*" - ], cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces: Dict[str, Any] = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], - cwd=root) - # --abbrev-ref was added in git-1.6.3 - if rc != 0 or branch_name is None: - raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") - branch_name = branch_name.strip() - - if branch_name == "HEAD": - # If we aren't exactly on a branch, pick a branch which represents - # the current commit. If all else fails, we are on a branchless - # commit. - branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) - # --contains was added in git-1.5.4 - if rc != 0 or branches is None: - raise NotThisMethod("'git branch --contains' returned error") - branches = branches.split("\n") - - # Remove the first line if we're running detached - if "(" in branches[0]: - branches.pop(0) - - # Strip off the leading "* " from the list of branches. - branches = [branch[2:] for branch in branches] - if "master" in branches: - branch_name = "master" - elif not branches: - branch_name = None - else: - # Pick the first branch that is returned. Good or bad. - branch_name = branches[0] - - pieces["branch"] = branch_name - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparsable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%s' doesn't start with prefix '%s'" - print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) - pieces["distance"] = len(out.split()) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - - return pieces - - -def do_vcs_install(versionfile_source: str, ipy: Optional[str]) -> None: - """Git-specific installation logic for Versioneer. - - For Git, this means creating/changing .gitattributes to mark _version.py - for export-subst keyword substitution. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - files = [versionfile_source] - if ipy: - files.append(ipy) - if "VERSIONEER_PEP518" not in globals(): - try: - my_path = __file__ - if my_path.endswith((".pyc", ".pyo")): - my_path = os.path.splitext(my_path)[0] + ".py" - versioneer_file = os.path.relpath(my_path) - except NameError: - versioneer_file = "versioneer.py" - files.append(versioneer_file) - present = False - try: - with open(".gitattributes", "r") as fobj: - for line in fobj: - if line.strip().startswith(versionfile_source): - if "export-subst" in line.strip().split()[1:]: - present = True - break - except OSError: - pass - if not present: - with open(".gitattributes", "a+") as fobj: - fobj.write(f"{versionfile_source} export-subst\n") - files.append(".gitattributes") - run_command(GITS, ["add", "--"] + files) - - -def versions_from_parentdir( - parentdir_prefix: str, - root: str, - verbose: bool, -) -> Dict[str, Any]: - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for _ in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %s but none started with prefix %s" % - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -SHORT_VERSION_PY = """ -# This file was generated by 'versioneer.py' (0.29) from -# revision-control system data, or from the parent directory name of an -# unpacked source archive. Distribution tarballs contain a pre-generated copy -# of this file. - -import json - -version_json = ''' -%s -''' # END VERSION_JSON - - -def get_versions(): - return json.loads(version_json) -""" - - -def versions_from_file(filename: str) -> Dict[str, Any]: - """Try to determine the version from _version.py if present.""" - try: - with open(filename) as f: - contents = f.read() - except OSError: - raise NotThisMethod("unable to read _version.py") - mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", - contents, re.M | re.S) - if not mo: - mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", - contents, re.M | re.S) - if not mo: - raise NotThisMethod("no version_json in _version.py") - return json.loads(mo.group(1)) - - -def write_to_version_file(filename: str, versions: Dict[str, Any]) -> None: - """Write the given version number to the given _version.py file.""" - contents = json.dumps(versions, sort_keys=True, - indent=1, separators=(",", ": ")) - with open(filename, "w") as f: - f.write(SHORT_VERSION_PY % contents) - - print("set %s to '%s'" % (filename, versions["version"])) - - -def plus_or_dot(pieces: Dict[str, Any]) -> str: - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces: Dict[str, Any]) -> str: - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_branch(pieces: Dict[str, Any]) -> str: - """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . - - The ".dev0" means not master branch. Note that .dev0 sorts backwards - (a feature branch will appear "older" than the master branch). - - Exceptions: - 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0" - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def pep440_split_post(ver: str) -> Tuple[str, Optional[int]]: - """Split pep440 version string at the post-release segment. - - Returns the release segments before the post-release and the - post-release version number (or -1 if no post-release segment is present). - """ - vc = str.split(ver, ".post") - return vc[0], int(vc[1] or 0) if len(vc) == 2 else None - - -def render_pep440_pre(pieces: Dict[str, Any]) -> str: - """TAG[.postN.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post0.devDISTANCE - """ - if pieces["closest-tag"]: - if pieces["distance"]: - # update the post release segment - tag_version, post_version = pep440_split_post(pieces["closest-tag"]) - rendered = tag_version - if post_version is not None: - rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"]) - else: - rendered += ".post0.dev%d" % (pieces["distance"]) - else: - # no commits, use the tag as the version - rendered = pieces["closest-tag"] - else: - # exception #1 - rendered = "0.post0.dev%d" % pieces["distance"] - return rendered - - -def render_pep440_post(pieces: Dict[str, Any]) -> str: - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - return rendered - - -def render_pep440_post_branch(pieces: Dict[str, Any]) -> str: - """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . - - The ".dev0" means not master branch. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_old(pieces: Dict[str, Any]) -> str: - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces: Dict[str, Any]) -> str: - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces: Dict[str, Any]) -> str: - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]: - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-branch": - rendered = render_pep440_branch(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-post-branch": - rendered = render_pep440_post_branch(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%s'" % style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} - - -class VersioneerBadRootError(Exception): - """The project root directory is unknown or missing key files.""" - - -def get_versions(verbose: bool = False) -> Dict[str, Any]: - """Get the project version from whatever source is available. - - Returns dict with two keys: 'version' and 'full'. - """ - if "versioneer" in sys.modules: - # see the discussion in cmdclass.py:get_cmdclass() - del sys.modules["versioneer"] - - root = get_root() - cfg = get_config_from_root(root) - - assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" - handlers = HANDLERS.get(cfg.VCS) - assert handlers, "unrecognized VCS '%s'" % cfg.VCS - verbose = verbose or bool(cfg.verbose) # `bool()` used to avoid `None` - assert cfg.versionfile_source is not None, \ - "please set versioneer.versionfile_source" - assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" - - versionfile_abs = os.path.join(root, cfg.versionfile_source) - - # extract version from first of: _version.py, VCS command (e.g. 'git - # describe'), parentdir. This is meant to work for developers using a - # source checkout, for users of a tarball created by 'setup.py sdist', - # and for users of a tarball/zipball created by 'git archive' or github's - # download-from-tag feature or the equivalent in other VCSes. - - get_keywords_f = handlers.get("get_keywords") - from_keywords_f = handlers.get("keywords") - if get_keywords_f and from_keywords_f: - try: - keywords = get_keywords_f(versionfile_abs) - ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) - if verbose: - print("got version from expanded keyword %s" % ver) - return ver - except NotThisMethod: - pass - - try: - ver = versions_from_file(versionfile_abs) - if verbose: - print("got version from file %s %s" % (versionfile_abs, ver)) - return ver - except NotThisMethod: - pass - - from_vcs_f = handlers.get("pieces_from_vcs") - if from_vcs_f: - try: - pieces = from_vcs_f(cfg.tag_prefix, root, verbose) - ver = render(pieces, cfg.style) - if verbose: - print("got version from VCS %s" % ver) - return ver - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - if verbose: - print("got version from parentdir %s" % ver) - return ver - except NotThisMethod: - pass - - if verbose: - print("unable to compute version") - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, "error": "unable to compute version", - "date": None} - - -def get_version() -> str: - """Get the short version string for this project.""" - return get_versions()["version"] - - -def get_cmdclass(cmdclass: Optional[Dict[str, Any]] = None): - """Get the custom setuptools subclasses used by Versioneer. - - If the package uses a different cmdclass (e.g. one from numpy), it - should be provide as an argument. - """ - if "versioneer" in sys.modules: - del sys.modules["versioneer"] - # this fixes the "python setup.py develop" case (also 'install' and - # 'easy_install .'), in which subdependencies of the main project are - # built (using setup.py bdist_egg) in the same python process. Assume - # a main project A and a dependency B, which use different versions - # of Versioneer. A's setup.py imports A's Versioneer, leaving it in - # sys.modules by the time B's setup.py is executed, causing B to run - # with the wrong versioneer. Setuptools wraps the sub-dep builds in a - # sandbox that restores sys.modules to it's pre-build state, so the - # parent is protected against the child's "import versioneer". By - # removing ourselves from sys.modules here, before the child build - # happens, we protect the child from the parent's versioneer too. - # Also see https://github.com/python-versioneer/python-versioneer/issues/52 - - cmds = {} if cmdclass is None else cmdclass.copy() - - # we add "version" to setuptools - from setuptools import Command - - class cmd_version(Command): - description = "report generated version string" - user_options: List[Tuple[str, str, str]] = [] - boolean_options: List[str] = [] - - def initialize_options(self) -> None: - pass - - def finalize_options(self) -> None: - pass - - def run(self) -> None: - vers = get_versions(verbose=True) - print("Version: %s" % vers["version"]) - print(" full-revisionid: %s" % vers.get("full-revisionid")) - print(" dirty: %s" % vers.get("dirty")) - print(" date: %s" % vers.get("date")) - if vers["error"]: - print(" error: %s" % vers["error"]) - cmds["version"] = cmd_version - - # we override "build_py" in setuptools - # - # most invocation pathways end up running build_py: - # distutils/build -> build_py - # distutils/install -> distutils/build ->.. - # setuptools/bdist_wheel -> distutils/install ->.. - # setuptools/bdist_egg -> distutils/install_lib -> build_py - # setuptools/install -> bdist_egg ->.. - # setuptools/develop -> ? - # pip install: - # copies source tree to a tempdir before running egg_info/etc - # if .git isn't copied too, 'git describe' will fail - # then does setup.py bdist_wheel, or sometimes setup.py install - # setup.py egg_info -> ? - - # pip install -e . and setuptool/editable_wheel will invoke build_py - # but the build_py command is not expected to copy any files. - - # we override different "build_py" commands for both environments - if 'build_py' in cmds: - _build_py: Any = cmds['build_py'] - else: - from setuptools.command.build_py import build_py as _build_py - - class cmd_build_py(_build_py): - def run(self) -> None: - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - _build_py.run(self) - if getattr(self, "editable_mode", False): - # During editable installs `.py` and data files are - # not copied to build_lib - return - # now locate _version.py in the new build/ directory and replace - # it with an updated value - if cfg.versionfile_build: - target_versionfile = os.path.join(self.build_lib, - cfg.versionfile_build) - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - cmds["build_py"] = cmd_build_py - - if 'build_ext' in cmds: - _build_ext: Any = cmds['build_ext'] - else: - from setuptools.command.build_ext import build_ext as _build_ext - - class cmd_build_ext(_build_ext): - def run(self) -> None: - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - _build_ext.run(self) - if self.inplace: - # build_ext --inplace will only build extensions in - # build/lib<..> dir with no _version.py to write to. - # As in place builds will already have a _version.py - # in the module dir, we do not need to write one. - return - # now locate _version.py in the new build/ directory and replace - # it with an updated value - if not cfg.versionfile_build: - return - target_versionfile = os.path.join(self.build_lib, - cfg.versionfile_build) - if not os.path.exists(target_versionfile): - print(f"Warning: {target_versionfile} does not exist, skipping " - "version update. This can happen if you are running build_ext " - "without first running build_py.") - return - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - cmds["build_ext"] = cmd_build_ext - - if "cx_Freeze" in sys.modules: # cx_freeze enabled? - from cx_Freeze.dist import build_exe as _build_exe # type: ignore - # nczeczulin reports that py2exe won't like the pep440-style string - # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. - # setup(console=[{ - # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION - # "product_version": versioneer.get_version(), - # ... - - class cmd_build_exe(_build_exe): - def run(self) -> None: - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - target_versionfile = cfg.versionfile_source - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - _build_exe.run(self) - os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % - {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - cmds["build_exe"] = cmd_build_exe - del cmds["build_py"] - - if 'py2exe' in sys.modules: # py2exe enabled? - try: - from py2exe.setuptools_buildexe import py2exe as _py2exe # type: ignore - except ImportError: - from py2exe.distutils_buildexe import py2exe as _py2exe # type: ignore - - class cmd_py2exe(_py2exe): - def run(self) -> None: - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - target_versionfile = cfg.versionfile_source - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - _py2exe.run(self) - os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % - {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - cmds["py2exe"] = cmd_py2exe - - # sdist farms its file list building out to egg_info - if 'egg_info' in cmds: - _egg_info: Any = cmds['egg_info'] - else: - from setuptools.command.egg_info import egg_info as _egg_info - - class cmd_egg_info(_egg_info): - def find_sources(self) -> None: - # egg_info.find_sources builds the manifest list and writes it - # in one shot - super().find_sources() - - # Modify the filelist and normalize it - root = get_root() - cfg = get_config_from_root(root) - self.filelist.append('versioneer.py') - if cfg.versionfile_source: - # There are rare cases where versionfile_source might not be - # included by default, so we must be explicit - self.filelist.append(cfg.versionfile_source) - self.filelist.sort() - self.filelist.remove_duplicates() - - # The write method is hidden in the manifest_maker instance that - # generated the filelist and was thrown away - # We will instead replicate their final normalization (to unicode, - # and POSIX-style paths) - from setuptools import unicode_utils - normalized = [unicode_utils.filesys_decode(f).replace(os.sep, '/') - for f in self.filelist.files] - - manifest_filename = os.path.join(self.egg_info, 'SOURCES.txt') - with open(manifest_filename, 'w') as fobj: - fobj.write('\n'.join(normalized)) - - cmds['egg_info'] = cmd_egg_info - - # we override different "sdist" commands for both environments - if 'sdist' in cmds: - _sdist: Any = cmds['sdist'] - else: - from setuptools.command.sdist import sdist as _sdist - - class cmd_sdist(_sdist): - def run(self) -> None: - versions = get_versions() - self._versioneer_generated_versions = versions - # unless we update this, the command will keep using the old - # version - self.distribution.metadata.version = versions["version"] - return _sdist.run(self) - - def make_release_tree(self, base_dir: str, files: List[str]) -> None: - root = get_root() - cfg = get_config_from_root(root) - _sdist.make_release_tree(self, base_dir, files) - # now locate _version.py in the new base_dir directory - # (remembering that it may be a hardlink) and replace it with an - # updated value - target_versionfile = os.path.join(base_dir, cfg.versionfile_source) - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, - self._versioneer_generated_versions) - cmds["sdist"] = cmd_sdist - - return cmds - - -CONFIG_ERROR = """ -setup.cfg is missing the necessary Versioneer configuration. You need -a section like: - - [versioneer] - VCS = git - style = pep440 - versionfile_source = src/myproject/_version.py - versionfile_build = myproject/_version.py - tag_prefix = - parentdir_prefix = myproject- - -You will also need to edit your setup.py to use the results: - - import versioneer - setup(version=versioneer.get_version(), - cmdclass=versioneer.get_cmdclass(), ...) - -Please read the docstring in ./versioneer.py for configuration instructions, -edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. -""" - -SAMPLE_CONFIG = """ -# See the docstring in versioneer.py for instructions. Note that you must -# re-run 'versioneer.py setup' after changing this section, and commit the -# resulting files. - -[versioneer] -#VCS = git -#style = pep440 -#versionfile_source = -#versionfile_build = -#tag_prefix = -#parentdir_prefix = - -""" - -OLD_SNIPPET = """ -from ._version import get_versions -__version__ = get_versions()['version'] -del get_versions -""" - -INIT_PY_SNIPPET = """ -from . import {0} -__version__ = {0}.get_versions()['version'] -""" - - -def do_setup() -> int: - """Do main VCS-independent setup function for installing Versioneer.""" - root = get_root() - try: - cfg = get_config_from_root(root) - except (OSError, configparser.NoSectionError, - configparser.NoOptionError) as e: - if isinstance(e, (OSError, configparser.NoSectionError)): - print("Adding sample versioneer config to setup.cfg", - file=sys.stderr) - with open(os.path.join(root, "setup.cfg"), "a") as f: - f.write(SAMPLE_CONFIG) - print(CONFIG_ERROR, file=sys.stderr) - return 1 - - print(" creating %s" % cfg.versionfile_source) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - - ipy = os.path.join(os.path.dirname(cfg.versionfile_source), - "__init__.py") - maybe_ipy: Optional[str] = ipy - if os.path.exists(ipy): - try: - with open(ipy, "r") as f: - old = f.read() - except OSError: - old = "" - module = os.path.splitext(os.path.basename(cfg.versionfile_source))[0] - snippet = INIT_PY_SNIPPET.format(module) - if OLD_SNIPPET in old: - print(" replacing boilerplate in %s" % ipy) - with open(ipy, "w") as f: - f.write(old.replace(OLD_SNIPPET, snippet)) - elif snippet not in old: - print(" appending to %s" % ipy) - with open(ipy, "a") as f: - f.write(snippet) - else: - print(" %s unmodified" % ipy) - else: - print(" %s doesn't exist, ok" % ipy) - maybe_ipy = None - - # Make VCS-specific changes. For git, this means creating/changing - # .gitattributes to mark _version.py for export-subst keyword - # substitution. - do_vcs_install(cfg.versionfile_source, maybe_ipy) - return 0 - - -def scan_setup_py() -> int: - """Validate the contents of setup.py against Versioneer's expectations.""" - found = set() - setters = False - errors = 0 - with open("setup.py", "r") as f: - for line in f.readlines(): - if "import versioneer" in line: - found.add("import") - if "versioneer.get_cmdclass()" in line: - found.add("cmdclass") - if "versioneer.get_version()" in line: - found.add("get_version") - if "versioneer.VCS" in line: - setters = True - if "versioneer.versionfile_source" in line: - setters = True - if len(found) != 3: - print("") - print("Your setup.py appears to be missing some important items") - print("(but I might be wrong). Please make sure it has something") - print("roughly like the following:") - print("") - print(" import versioneer") - print(" setup( version=versioneer.get_version(),") - print(" cmdclass=versioneer.get_cmdclass(), ...)") - print("") - errors += 1 - if setters: - print("You should remove lines like 'versioneer.VCS = ' and") - print("'versioneer.versionfile_source = ' . This configuration") - print("now lives in setup.cfg, and should be removed from setup.py") - print("") - errors += 1 - return errors - - -def setup_command() -> NoReturn: - """Set up Versioneer and exit with appropriate error code.""" - errors = do_setup() - errors += scan_setup_py() - sys.exit(1 if errors else 0) - - -if __name__ == "__main__": - cmd = sys.argv[1] - if cmd == "setup": - setup_command()