From 0db422065ca6d52c40d0e10ca6cfbd8459f6f51b Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Wed, 22 Feb 2023 11:18:14 -0800 Subject: [PATCH 01/28] CLN: removing run_tests.py Performed by pcds-migration-tools DeleteFiles --- run_tests.py | 51 --------------------------------------------------- 1 file changed, 51 deletions(-) delete mode 100644 run_tests.py diff --git a/run_tests.py b/run_tests.py deleted file mode 100644 index d872ec89..00000000 --- a/run_tests.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -import logging -import os -import sys -from logging.handlers import RotatingFileHandler -from pathlib import Path - -import pytest - -if __name__ == '__main__': - # Show output results from every test function - # Show the message output for skipped and expected failures - args = ['-v', '-vrxs'] - - # Add extra arguments - if len(sys.argv) > 1: - args.extend(sys.argv[1:]) - - txt = 'pytest arguments: {}'.format(args) - print(txt) - - # Setup logger and log everything to a file - root_logger = logging.getLogger() - root_logger.setLevel(logging.DEBUG) - log_dir = Path(os.path.dirname(__file__)) / 'logs' - log_file = log_dir / 'run_tests_log.txt' - - if not log_dir.exists(): - log_dir.mkdir(parents=True) - if log_file.exists(): - do_rollover = True - else: - do_rollover = False - - handler = RotatingFileHandler(str(log_file), backupCount=5, - encoding=None, delay=0) - if do_rollover: - handler.doRollover() - formatter = logging.Formatter(fmt=('%(asctime)s.%(msecs)03d ' - '%(module)-15s ' - '%(levelname)-8s ' - '%(threadName)-10s ' - '%(message)s'), - datefmt='%H:%M:%S') - handler.setFormatter(formatter) - root_logger.addHandler(handler) - - logger = logging.getLogger(__name__) - logger.info(txt) - - sys.exit(pytest.main(args)) From 27ca94960cbd5787d946927e337fcfa0dca8764a Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Wed, 22 Feb 2023 11:18:14 -0800 Subject: [PATCH 02/28] MNT: updating LICENSE from template Performed by pcds-migration-tools AddFileFromTemplate --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index 948f6382..e14da2c1 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2017, The Board of Trustees of the Leland Stanford Junior +Copyright (c) 2023, The Board of Trustees of the Leland Stanford Junior University, through SLAC National Accelerator Laboratory (subject to receipt of any required approvals from the U.S. Dept. of Energy). All rights reserved. Redistribution and use in source and binary forms, with or without From ac42470f4b673d43ae5dfe40f5ed4900a2ba7504 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Wed, 22 Feb 2023 11:18:14 -0800 Subject: [PATCH 03/28] MNT: updating AUTHORS.rst from template Performed by pcds-migration-tools AddFileFromTemplate --- AUTHORS.rst | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 AUTHORS.rst diff --git a/AUTHORS.rst b/AUTHORS.rst new file mode 100644 index 00000000..a99ffb48 --- /dev/null +++ b/AUTHORS.rst @@ -0,0 +1,13 @@ +======= +Credits +======= + +Maintainer +---------- + +* SLAC National Accelerator Laboratory <> + +Contributors +------------ + +Interested? See: `CONTRIBUTING.rst `_ From 0159035e26e5776285a0413811d889dafc75a4e3 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Wed, 22 Feb 2023 11:18:14 -0800 Subject: [PATCH 04/28] MNT: updating CONTRIBUTING.rst from template Performed by pcds-migration-tools AddFileFromTemplate --- CONTRIBUTING.rst | 103 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 CONTRIBUTING.rst diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst new file mode 100644 index 00000000..4217a449 --- /dev/null +++ b/CONTRIBUTING.rst @@ -0,0 +1,103 @@ +============ +Contributing +============ + +Contributions are welcome, and they are greatly appreciated! Every little bit +helps, and credit will always be given. + +You can contribute in many ways: + +Types of Contributions +---------------------- + +Report Bugs +~~~~~~~~~~~ + +Report bugs at https://github.com/pcdshub/hutch_python/issues. + +If you are reporting a bug, please include: + +* Any details about your local setup that might be helpful in troubleshooting. +* Detailed steps to reproduce the bug. + +Fix Bugs +~~~~~~~~ + +Look through the GitHub issues for bugs. Anything tagged with "bug" +is open to whoever wants to implement it. + +Implement Features +~~~~~~~~~~~~~~~~~~ + +Look through the GitHub issues for features. Anything tagged with "feature" +is open to whoever wants to implement it. + +Write Documentation +~~~~~~~~~~~~~~~~~~~ + +hutch-python could always use more documentation, whether +as part of the official hutch-python docs, in docstrings, +or even on the web in blog posts, articles, and such. + +Submit Feedback +~~~~~~~~~~~~~~~ + +The best way to send feedback is to file an issue at https://github.com/pcdshub/hutch_python/issues. + +If you are proposing a feature: + +* Explain in detail how it would work. +* Keep the scope as narrow as possible, to make it easier to implement. +* Remember that this is a volunteer-driven project, and that contributions + are welcome :) + +Get Started! +------------ + +Ready to contribute? Here's how to set up `hutch_python` for local development. + +1. Fork the `hutch_python` repo on GitHub. +2. Clone your fork locally:: + + $ git clone git@github.com:your_name_here/hutch_python.git + +3. Install your local copy into a new conda environment. Assuming you have conda installed, this is how you set up your fork for local development:: + + $ conda create -n hutch_python python=3.9 pip + $ cd hutch_python/ + $ pip install -e . + +4. Create a branch for local development:: + + $ git checkout -b name-of-your-bugfix-or-feature + + Now you can make your changes locally. + +5. Install and enable ``pre-commit`` for this repository:: + + $ pip install pre-commit + $ pre-commit install + +6. Add new tests for any additional functionality or bugs you may have discovered. And, of course, be sure that all previous tests still pass by running:: + + $ pytest -v + +7. Commit your changes and push your branch to GitHub:: + + $ git add . + $ git commit -m "Your detailed description of your changes." + $ git push origin name-of-your-bugfix-or-feature + +8. Submit a pull request through the GitHub website. + +Pull Request Guidelines +----------------------- + +Before you submit a pull request, check that it meets these guidelines: + +1. The pull request should include tests. +2. If the pull request adds functionality, the docs should be updated. Put your + new functionality into a function with a docstring, and add the feature to + the list in README.rst. +3. The pull request should work for Python 3.9 and up. Check the GitHub Actions status + and make sure that the tests pass for all supported Python versions. From 0585a5e1b2a12a30d71cb3d3ff55bf561913de6b Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Wed, 22 Feb 2023 11:18:15 -0800 Subject: [PATCH 05/28] MNT: updating .pre-commit-config.yaml from template Performed by pcds-migration-tools AddFileFromTemplate --- .pre-commit-config.yaml | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 56d2812e..814e228a 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,11 +1,10 @@ # See https://pre-commit.com for more information # See https://pre-commit.com/hooks.html for more hooks exclude: | - (?x)^( - versioneer.py| - docs/source/conf.py| - hutch_python/_version.py| - )$ + (?x)^( + hutch_python/_version.py| + )$ + repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.4.0 @@ -20,11 +19,7 @@ repos: - id: check-symlinks - id: check-xml - id: check-yaml - exclude: | - (?x)^( - conda-recipe/meta.yaml| - hutch_python/cookiecutter/.*/conf.yml - )$ + exclude: '^(conda-recipe/meta.yaml)$' - id: debug-statements - repo: https://github.com/pycqa/flake8.git @@ -33,6 +28,6 @@ repos: - id: flake8 - repo: https://github.com/timothycrosley/isort - rev: 5.12.0 + rev: 5.11.4 hooks: - id: isort From 6d7bdf69aef8e264d1c6944de5d2924e7ce9a3bd Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Wed, 22 Feb 2023 11:18:15 -0800 Subject: [PATCH 06/28] MNT: updating .flake8 from template Performed by pcds-migration-tools AddFileFromTemplate --- .flake8 | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 .flake8 diff --git a/.flake8 b/.flake8 new file mode 100644 index 00000000..817f04d3 --- /dev/null +++ b/.flake8 @@ -0,0 +1,23 @@ +[flake8] +exclude = .git,__pycache__,build,dist,hutch_python/_version.py +max-line-length = 88 +select = C,E,F,W,B,B950 +extend-ignore = E203, E501, E226, W503, W504 + +# Explanation section: +# B950 +# This takes into account max-line-length but only triggers when the value +# has been exceeded by more than 10% (96 characters). +# E203: Whitespace before ':' +# This is recommended by black in relation to slice formatting. +# E501: Line too long (82 > 79 characters) +# Our line length limit is 88 (above 79 defined in E501). Ignore it. +# E226: Missing whitespace around arithmetic operator +# This is a stylistic choice which you'll find everywhere in pcdsdevices, for +# example. Formulas can be easier to read when operators and operands +# have no whitespace between them. +# +# W503: Line break occurred before a binary operator +# W504: Line break occurred after a binary operator +# flake8 wants us to choose one of the above two. Our choice +# is to make no decision. From 6f7dd8a3e7faa573ddc32ee8472a134fad571e01 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Wed, 22 Feb 2023 11:18:15 -0800 Subject: [PATCH 07/28] MNT: updating .coveragerc from template Performed by pcds-migration-tools AddFileFromTemplate --- .coveragerc | 1 - 1 file changed, 1 deletion(-) diff --git a/.coveragerc b/.coveragerc index e9ce6d19..f435959c 100644 --- a/.coveragerc +++ b/.coveragerc @@ -9,4 +9,3 @@ omit = #tests *test* hutch_python/tests/* - hutch_python/cookiecutter/* From 2b0323137e32c289efa4236bdd762b1e7ce85e70 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Wed, 22 Feb 2023 11:18:15 -0800 Subject: [PATCH 08/28] MNT: updating .git_archival.txt from template Performed by pcds-migration-tools AddFileFromTemplate --- .git_archival.txt | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 .git_archival.txt diff --git a/.git_archival.txt b/.git_archival.txt new file mode 100644 index 00000000..8fb235d7 --- /dev/null +++ b/.git_archival.txt @@ -0,0 +1,4 @@ +node: $Format:%H$ +node-date: $Format:%cI$ +describe-name: $Format:%(describe:tags=true,match=*[0-9]*)$ +ref-names: $Format:%D$ From 53fd09a7b803b353364b17875df3071da54636e9 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Wed, 22 Feb 2023 11:18:15 -0800 Subject: [PATCH 09/28] MNT: updating .gitattributes from template Performed by pcds-migration-tools AddFileFromTemplate --- .gitattributes | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitattributes b/.gitattributes index 59a2894c..00a7b00c 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1 @@ -hutch_python/_version.py export-subst +.git_archival.txt export-subst From d387381def7552e0cb8c1c9975843d1f457271bf Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Wed, 22 Feb 2023 11:18:15 -0800 Subject: [PATCH 10/28] CI: migrate to GitHub actions Performed by pcds-migration-tools GitHubActionsMigration --- .github/workflows/standard.yml | 24 ++++++++++++++++++++++++ .travis.yml | 33 --------------------------------- 2 files changed, 24 insertions(+), 33 deletions(-) create mode 100644 .github/workflows/standard.yml delete mode 100644 .travis.yml diff --git a/.github/workflows/standard.yml b/.github/workflows/standard.yml new file mode 100644 index 00000000..6065bbb6 --- /dev/null +++ b/.github/workflows/standard.yml @@ -0,0 +1,24 @@ +name: PCDS Standard Testing + +on: + push: + pull_request: + release: + types: + - created + +jobs: + standard: + uses: pcdshub/pcds-ci-helpers/.github/workflows/python-standard.yml@master + with: + # The workflow needs to know the package name. This can be determined + # automatically if the repository name is the same as the import name. + package-name: "hutch-python" + # Extras that will be installed for both conda/pip: + testing-extras: "" + # Extras to be installed only for conda-based testing: + conda-testing-extras: "ipython=8.4.0 pandoc pypandoc" + # Extras to be installed only for pip-based testing: + pip-testing-extras: "ipython==8.4.0 lightpath" + # Set if using setuptools-scm for the conda-build workflow + use-setuptools-scm: true diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 6e3a1eb2..00000000 --- a/.travis.yml +++ /dev/null @@ -1,33 +0,0 @@ -version: ~> 1.0 - -env: - global: - - secure: "eE1+WNZb3WjsSlxkf5zDM9PmuVvfFW4rGCF6F2SzVPLXcQP/F27isFmFA8apkbXDp6nr7QTCOItcVccsJ6X+J2UmgrQGw/da/CuTHR5SXN4nOpfBbtuIr3nfy8ubBvZUG55s32eYBPhZo/Z2u9eFQGqQla1agK4E37rm2FymP9y7vmcRAMEhr8w8kOvmCIyDL6uKNQXhUBM7WKk3gOk9UDTtrRFHLP4GR5WcoFZJnAa4Jyc0ttR48rJBuDPgEGL8B7H2YVGT1ttaV0gnM3SMOGnECskRzotZZ3dIISHhnn5kQNJ4BfgDUasHua2rXXQ7BuT6eaGw0nudYFPQ2sUq4iCqV9yoXWtSIHfZ46S+rMeazcZcPl6mQBMjhVBoboWAC7q/AJWuHw+3kR8RUcvLQorgeIMwY7/O8Ri8WCOkccKvNTf5DrHBwrQFmt7+PEh3t/fflUzPQmCgmuWoov6rj5wxb11u4CGVb4mnIJ1Ocq8sZERe+JHMpXokBGQ1jE0qOAG/Og2T7E7yy7MFnjZUJD3j6PfAiVZip3KUAWWG5BQOY7LZ3JhmAp/OVQSRM7jS/HW0VF0P8d5ak39ouZ1Bvzi02bsHbsktbiA6LCo8Wif74gjNV5z7pn8C7x2Ir5nSzw/auva1kOapx96NwNDO+d0+F5qeg4vaH5aOBnq6Kts=" - - # enable the usage of versions menu which allow versioning of the docs - # pages and not only the master branch - - DOCTR_VERSIONS_MENU="1" - # Dependency files used to build the documentation (space separated) - - DOCS_REQUIREMENTS="dev-requirements.txt" - # Options to be passed to flake8 for package linting. Usually this is just - # the package name but you can enable other flake8 options via this config - - PYTHON_LINT_OPTIONS="hutch_python" - - # The name of the conda package - - CONDA_PACKAGE="hutch-python" - # The folder containing the conda recipe (meta.yaml) - - CONDA_RECIPE_FOLDER="conda-recipe" - # Extra dependencies needed to run the tests which are not included - # at the recipe and dev-requirements.txt. E.g. PyQt - # pandoc/pypandoc - used to translate README.md for sphinx - - CONDA_EXTRAS="pip pandoc pypandoc ipython=8.4.0" - # Requirements file with contents for tests dependencies - - CONDA_REQUIREMENTS="dev-requirements.txt" - - # Extra dependencies needed to run the test with Pip (similar to - # CONDA_EXTRAS) but for pip - - PIP_EXTRAS="lightpath ipython==8.4.0 ." - -import: - - pcdshub/pcds-ci-helpers:travis/shared_configs/setup-env-ui.yml - - pcdshub/pcds-ci-helpers:travis/shared_configs/standard-python-conda-latest.yml From 3097be7209de4884877e065c677a00679ba3551b Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Wed, 22 Feb 2023 11:18:15 -0800 Subject: [PATCH 11/28] DOC: update Sphinx configuration Performed by pcds-migration-tools UpdateSphinx --- dev-requirements.txt | 1 + docs/source/conf.py | 79 +++++++++++++++++++++++++++----------------- 2 files changed, 49 insertions(+), 31 deletions(-) diff --git a/dev-requirements.txt b/dev-requirements.txt index 343784bb..02a49654 100644 --- a/dev-requirements.txt +++ b/dev-requirements.txt @@ -6,3 +6,4 @@ packaging pytest pytest-timeout flake8 +sphinxcontrib-jquery diff --git a/docs/source/conf.py b/docs/source/conf.py index 0225c1a9..333eeae2 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -14,8 +14,9 @@ import os import sys import sphinx_rtd_theme -module_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'../../') -sys.path.insert(0,module_path) + +module_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../") +sys.path.insert(0, module_path) # 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 @@ -29,30 +30,33 @@ # 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.autosummary', - 'IPython.sphinxext.ipython_directive', - 'IPython.sphinxext.ipython_console_highlighting', - 'sphinx.ext.napoleon', - 'nbsphinx', - 'sphinx.ext.mathjax'] +extensions = [ + "sphinxcontrib.jquery", + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "IPython.sphinxext.ipython_directive", + "IPython.sphinxext.ipython_console_highlighting", + "sphinx.ext.napoleon", + "nbsphinx", + "sphinx.ext.mathjax", +] # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] autosummary_generate = True # 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'hutch-python' +project = "hutch-python" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -60,13 +64,14 @@ # # The short X.Y version. import hutch_python -version = hutch_python.__version__ + +version = str(hutch_python.__version__) # The full version, including alpha/beta/rc tags. -release = hutch_python.__version__ +release = str(hutch_python.__version__) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. -# language = None +# language = "en" # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: @@ -76,10 +81,10 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ['_build', '**.ipynb_checkpoints'] +exclude_patterns = ["_build", "**.ipynb_checkpoints"] # The reST default role (used for this markup: `text`) to use for all documents. -default_role = 'any' +default_role = "any" # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True @@ -93,7 +98,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 = [] @@ -176,7 +181,7 @@ # html_file_suffix = None # Output file base name for HTML help builder. -htmlhelp_basename = 'hutch-pythondoc' +htmlhelp_basename = "hutch-pythondoc" # -- Options for LaTeX output -------------------------------------------------- @@ -184,10 +189,8 @@ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. # 'preamble': '', } @@ -195,10 +198,13 @@ # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ - ('index', - 'hutch-python.tex', - u'hutch-python Documentation', - u"SLAC National Accelerator Laboratories", 'manual'), + ( + "index", + "hutch-python.tex", + "hutch-python Documentation", + "SLAC National Accelerator Laboratories", + "manual", + ), ] # The name of an image file (relative to this directory) to place at the top of @@ -227,8 +233,13 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - ('index', 'hutch-python', u'hutch-python Documentation', - [u"SLAC National Accelerator Laboratories"], 1) + ( + "index", + "hutch-python", + "hutch-python Documentation", + ["SLAC National Accelerator Laboratories"], + 1, + ) ] # If true, show URL addresses after external links. @@ -241,9 +252,15 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - ('index', 'hutch-python', u'hutch-python Documentation', - u"SLAC National Accelerator Laboratories", 'hutch-python', - 'Laucher and Config Reader for LCLS Python 3 Interactive IPython Sessions', 'Miscellaneous'), + ( + "index", + "hutch-python", + "hutch-python Documentation", + "SLAC National Accelerator Laboratories", + "hutch-python", + "Laucher and Config Reader for LCLS Python 3 Interactive IPython Sessions", + "Miscellaneous", + ), ] # Documents to append as an appendix to all manuals. From 62b051c108945c88078028dd0b3b00ffeb01fdff Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Wed, 22 Feb 2023 11:18:19 -0800 Subject: [PATCH 12/28] STY: update repository to Python 3.9+ standards Performed by pcds-migration-tools RunPyupgrade --- docs/source/conf.py | 1 - hutch_python/cache.py | 2 +- hutch_python/cam_load.py | 2 +- hutch_python/env_version.py | 6 +++--- hutch_python/epics_arch.py | 4 ++-- hutch_python/happi.py | 4 ++-- hutch_python/ipython_log.py | 2 +- hutch_python/load_conf.py | 22 +++++++++++----------- hutch_python/log_setup.py | 17 ++++++++--------- hutch_python/namespace.py | 4 ++-- hutch_python/obj_config.py | 4 ++-- hutch_python/print_hint_banner.py | 2 +- hutch_python/tests/test_bug.py | 2 +- hutch_python/tests/test_ipython_log.py | 8 ++++---- hutch_python/utils.py | 4 ++-- 15 files changed, 41 insertions(+), 43 deletions(-) diff --git a/docs/source/conf.py b/docs/source/conf.py index 333eeae2..16eef05c 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # hutch-python documentation build configuration file, created by # sphinx-quickstart. diff --git a/hutch_python/cache.py b/hutch_python/cache.py index 623f5e7d..bb75e0bb 100644 --- a/hutch_python/cache.py +++ b/hutch_python/cache.py @@ -89,7 +89,7 @@ def write_file(self): text = (header.format(parts[0]) + body.format(datetime.datetime.now())) for name, obj in self.objs.__dict__.items(): - text += '{:<20} {}\n'.format(name, obj.__class__) + text += f'{name:<20} {obj.__class__}\n' if not db_path.exists(): db_path.touch() db_path.chmod(0o666) diff --git a/hutch_python/cam_load.py b/hutch_python/cam_load.py index 5dbefdd1..95245090 100644 --- a/hutch_python/cam_load.py +++ b/hutch_python/cam_load.py @@ -49,7 +49,7 @@ def interpret_cfg(filename, pvnames=None): info: ``list of str`` Valid inputs for build_cam """ - with open(filename, 'r') as f: + with open(filename) as f: lines = f.readlines() if pvnames is None: diff --git a/hutch_python/env_version.py b/hutch_python/env_version.py index 462af824..f8d4bcaf 100644 --- a/hutch_python/env_version.py +++ b/hutch_python/env_version.py @@ -19,7 +19,7 @@ def not_ignored(path: list[str], ignores: list[str] = None) -> bool: """ Return True if _dev_ignore_list isn't in path or empty """ if ignores is None: ignores = _dev_ignore_list - return bool(path and not any((s in path for s in ignores))) + return bool(path and not any(s in path for s in ignores)) def log_env() -> None: @@ -61,9 +61,9 @@ def get_standard_dev_pkgs() -> set[str]: return set() paths = pythonpath.split(os.pathsep) valid_paths = filter(not_ignored, paths) - pkg_names = set(n.name for n in + pkg_names = {n.name for n in pkgutil.iter_modules(path=valid_paths) - if n.ispkg) + if n.ispkg} return pkg_names diff --git a/hutch_python/epics_arch.py b/hutch_python/epics_arch.py index 89f5b0b8..24936073 100644 --- a/hutch_python/epics_arch.py +++ b/hutch_python/epics_arch.py @@ -89,7 +89,7 @@ def create_arch_file(experiment, hutch=None, path=None, dry_run=False): # set the path to write the epicsArch file to. if path: if path and not os.path.exists(path): - raise IOError('Invalid path: %s' % path) + raise OSError('Invalid path: %s' % path) file_path = path elif hutch: file_path = EPICS_ARCH_FILE_PATH.format(hutch.lower()) @@ -184,7 +184,7 @@ def create_file(exp_name, path): """ data_list = get_questionnaire_data(exp_name) if not os.path.exists(path): - raise IOError('Invalid path: %s' % path) + raise OSError('Invalid path: %s' % path) exp_name = str(exp_name) file_path = ''.join((path, 'epicsArch_', exp_name, '.txt')) diff --git a/hutch_python/happi.py b/hutch_python/happi.py index 996d9142..2bac6eca 100644 --- a/hutch_python/happi.py +++ b/hutch_python/happi.py @@ -22,7 +22,7 @@ def get_happi_objs( db: str, light_ctrl: LightController, endstation: str, -) -> Dict[str, ophyd.Device]: +) -> dict[str, ophyd.Device]: """ Get the relevant items for ``endstation`` from the happi database ``db``. @@ -76,7 +76,7 @@ def get_happi_objs( # also any device with the same beamline name # since lightpath only grabs lightpath-active devices - beamlines = set(it.beamline for it in containers) + beamlines = {it.beamline for it in containers} beamlines.add(endstation.upper()) for line in beamlines: diff --git a/hutch_python/ipython_log.py b/hutch_python/ipython_log.py index c521fac1..3ae19519 100644 --- a/hutch_python/ipython_log.py +++ b/hutch_python/ipython_log.py @@ -46,7 +46,7 @@ def _get_file_and_line_from_traceback( tb: types.TracebackType, *, on_error: str = "unknown" -) -> Tuple[str, int]: +) -> tuple[str, int]: """ Get the last source filename and line number from the traceback. diff --git a/hutch_python/load_conf.py b/hutch_python/load_conf.py index 5a617887..58ee3e30 100644 --- a/hutch_python/load_conf.py +++ b/hutch_python/load_conf.py @@ -79,7 +79,7 @@ def load(cfg=None, args=None): conf = {} hutch_dir = None else: - with open(cfg, 'r') as f: + with open(cfg) as f: conf = yaml.safe_load(f) conf_path = Path(cfg) hutch_dir = conf_path.parent @@ -182,8 +182,8 @@ def load_conf(conf, hutch_dir=None, args=None): hutch = None except KeyError: hutch = None - logger.info(('Missing hutch from conf. Will skip elog ' - 'and cameras.')) + logger.info('Missing hutch from conf. Will skip elog ' + 'and cameras.') # Display the banner if hutch is None: @@ -203,8 +203,8 @@ def load_conf(conf, hutch_dir=None, args=None): db = None except KeyError: db = None - logger.info(('Missing db from conf. Will skip loading from shared ' - 'database.')) + logger.info('Missing db from conf. Will skip loading from shared ' + 'database.') try: load = conf['load'] if not isinstance(load, (str, list)): @@ -223,9 +223,9 @@ def load_conf(conf, hutch_dir=None, args=None): except KeyError: experiment = None if hutch is None: - logger.info(('Missing hutch and experiment from conf. Will not ' + logger.info('Missing hutch and experiment from conf. Will not ' 'load objects from questionnaire or experiment ' - 'file.')) + 'file.') try: obj_config = conf['obj_config'] @@ -240,8 +240,8 @@ def load_conf(conf, hutch_dir=None, args=None): obj_config = None except KeyError: obj_config = None - logger.info(('Missing obj_config from conf. Will skip applying ' - 'user settings to devices.')) + logger.info('Missing obj_config from conf. Will skip applying ' + 'user settings to devices.') try: # Configure whether we use the LCLS-I or LCLS-II daq daq_type = conf['daq_type'] @@ -405,7 +405,7 @@ def load_conf(conf, hutch_dir=None, args=None): # Scan PVs if hutch is not None: with safe_load('scan_pvs'): - scan_pvs = ScanVars('{}:SCAN'.format(hutch.upper()), + scan_pvs = ScanVars(f'{hutch.upper()}:SCAN', name='scan_pvs', RE=RE) scan_pvs.enable() cache(scan_pvs=scan_pvs) @@ -446,7 +446,7 @@ def load_conf(conf, hutch_dir=None, args=None): # create and store beampath if lc is not None: bp = lc.active_path(hutch.upper()) - beampath_name = "{}_beampath".format(hutch.lower()) + beampath_name = f"{hutch.lower()}_beampath" cache(**{beampath_name: bp}) cache.doc(**{beampath_name: 'Lightpath beam path object.'}) diff --git a/hutch_python/log_setup.py b/hutch_python/log_setup.py index 098321cf..94e91e39 100644 --- a/hutch_python/log_setup.py +++ b/hutch_python/log_setup.py @@ -123,7 +123,7 @@ def get_log_filename(extension: str = '.log') -> Path: def _read_logging_config() -> dict: """Read the logging configuration file into a dictionary.""" - with open(constants.FILE_YAML, 'rt') as f: + with open(constants.FILE_YAML) as f: return yaml.safe_load(f.read()) @@ -361,19 +361,19 @@ def _count_update_thread(self) -> None: def _count_update(self) -> None: """Log count update - every second.""" - noisy_loggers = set( + noisy_loggers = { name for name, count in tuple(self.name_to_log_count_1s.items()) if count > self.noisy_threshold_1s > 0 - ) | set( + } | { name for name, count in tuple(self.name_to_log_count_10s.items()) if count > self.noisy_threshold_10s > 0 - ) | set( + } | { name for name, count in tuple(self.name_to_log_count_60s.items()) if count > self.noisy_threshold_60s > 0 - ) + } for noisy_logger in sorted(noisy_loggers): if noisy_logger in self.whitelist: @@ -525,7 +525,7 @@ def whitelist_all_level(self, value: Union[int, str]): @property def object_names(self) -> set[str]: """The names of all contained objects.""" - return set(obj.name for obj in self.objects) + return {obj.name for obj in self.objects} def filter(self, record: logging.LogRecord) -> bool: name: Optional[str] = getattr(record, "ophyd_object_name", None) @@ -732,7 +732,7 @@ def get_handler(name): for handler in root.handlers: if handler.name == name: return handler - raise RuntimeError('No {} handler'.format(name)) + raise RuntimeError(f'No {name} handler') def get_console_level(): @@ -881,7 +881,6 @@ def log_exception_to_central_server( message = message or f'[{context}] {exc_value}' kwargs = dict() - if sys.version_info >= (3, 8): - kwargs = dict(stacklevel=stacklevel + 1) + kwargs = dict(stacklevel=stacklevel + 1) central_logger.log(level, message, exc_info=exc_info, **kwargs) diff --git a/hutch_python/namespace.py b/hutch_python/namespace.py index f801032c..65ee4f27 100644 --- a/hutch_python/namespace.py +++ b/hutch_python/namespace.py @@ -148,9 +148,9 @@ def tree_namespace(scope=None): setattr(upper_space, key, IterableNamespace()) upper_space = getattr(upper_space, key) if hasattr(upper_space, name): - logger.warning(('Tried to add {} to {}, but something was ' + logger.warning('Tried to add {} to {}, but something was ' 'already there. Two devices share the same ' - 'name!'.format(name, upper_space))) + 'name!'.format(name, upper_space)) else: setattr(upper_space, name, obj) logger.debug('Created tree namespace %s', tree_space) diff --git a/hutch_python/obj_config.py b/hutch_python/obj_config.py index 9abc4709..efc23244 100644 --- a/hutch_python/obj_config.py +++ b/hutch_python/obj_config.py @@ -174,7 +174,7 @@ def update_kind(dev: Device, attrs: dict) -> None: def configure_objects( obj_config: Union[str, Path], objs: utils.HelpfulNamespace, - mod_list: list[Tuple[str, Callable]] = None + mod_list: list[tuple[str, Callable]] = None ) -> utils.HelpfulNamespace: """ Configure objects based on user provided settings. @@ -197,7 +197,7 @@ def configure_objects( Modified objects """ with utils.safe_load('user object configuration'): - with open(obj_config, 'r') as f: + with open(obj_config) as f: cfg = yaml.safe_load(f) if mod_list is None: mod_list = mods diff --git a/hutch_python/print_hint_banner.py b/hutch_python/print_hint_banner.py index 563c0b64..6c8b9d31 100644 --- a/hutch_python/print_hint_banner.py +++ b/hutch_python/print_hint_banner.py @@ -21,7 +21,7 @@ default_objects = ['RE', 'daq', 'elog', 'archive'] -def gather_hint_table(namespace: List[str]) -> str: +def gather_hint_table(namespace: list[str]) -> str: """ Gather variable name and short description into a table if the variable name is in the current global namespace diff --git a/hutch_python/tests/test_bug.py b/hutch_python/tests/test_bug.py index 3c474098..a04ba388 100644 --- a/hutch_python/tests/test_bug.py +++ b/hutch_python/tests/test_bug.py @@ -81,7 +81,7 @@ def test_bug_report(monkeypatch, temporary_config): # Post report report_bug(captured_output='A printed message', description='A description of the bug') - bug = simplejson.load(open(tmp.name, 'r')) + bug = simplejson.load(open(tmp.name)) # Check GitHub authentication assert FakeSession.past_auth == {'github_user': 'github_pw'} # Test proxy host information diff --git a/hutch_python/tests/test_ipython_log.py b/hutch_python/tests/test_ipython_log.py index f1e88c98..05318592 100644 --- a/hutch_python/tests/test_ipython_log.py +++ b/hutch_python/tests/test_ipython_log.py @@ -55,7 +55,7 @@ class FakeExecutionResult: class FakeIPython: """A fake replacement of IPython's ``TerminalInteractiveShell``.""" - user_ns: Dict[str, Any] + user_ns: dict[str, Any] events: FakeIPythonEvents def __init__(self): @@ -89,7 +89,7 @@ def ipylog(log_queue, fake_ipython) -> IPythonLogger: def next_pertinent_log_record( queue: Queue, - pertinent_loggers: Optional[List[str]] = None + pertinent_loggers: Optional[list[str]] = None ) -> logging.LogRecord: """ Get the next relevant log record from the queue. @@ -127,7 +127,7 @@ def next_pertinent_log_record( def next_pertinent_log_message( queue: Queue, - pertinent_loggers: Optional[List[str]] = None + pertinent_loggers: Optional[list[str]] = None ) -> str: """ Get the next relevant log message from the queue. @@ -162,7 +162,7 @@ def next_pertinent_log_message( def assert_no_more_messages( queue: Queue, - pertinent_loggers: Optional[List[str]] = None + pertinent_loggers: Optional[list[str]] = None ) -> None: """ Assert that no more relevant messages are available from a queue. diff --git a/hutch_python/utils.py b/hutch_python/utils.py index 899baf1c..7bc4fe16 100644 --- a/hutch_python/utils.py +++ b/hutch_python/utils.py @@ -348,7 +348,7 @@ def find_class(class_path, check_defaults=True): check_defaults=False) except AttributeError: pass - raise ImportError('Could not find_class for {}'.format(class_path)) + raise ImportError(f'Could not find_class for {class_path}') def strip_prefix(name, strip_text): @@ -420,7 +420,7 @@ def hutch_banner(hutch_name='Hutch '): f = pyfiglet.Figlet(font='big') banner = f.renderText(text) if hutch_name in HUTCH_COLORS: - banner = '\x1b[{}m'.format(HUTCH_COLORS[hutch_name]) + banner + banner = f'\x1b[{HUTCH_COLORS[hutch_name]}m' + banner print(banner) From 4a7fa310efa89b5c5fcf83ee937d9f4b22013897 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Wed, 22 Feb 2023 11:18:19 -0800 Subject: [PATCH 13/28] BLD: migrate to pyproject.toml Performed by pcds-migration-tools PyprojectTomlMigration --- pyproject.toml | 44 ++++++++++++++++++++++++++++++++++++++++++++ setup.cfg | 9 --------- setup.py | 30 ------------------------------ 3 files changed, 44 insertions(+), 39 deletions(-) create mode 100644 pyproject.toml delete mode 100644 setup.cfg delete mode 100644 setup.py diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 00000000..3f9be392 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,44 @@ +[build-system] +build-backend = "setuptools.build_meta" +requires = [ "setuptools>=45", "setuptools_scm[toml]>=6.2",] + +[project] +classifiers = [ "Development Status :: 2 - Pre-Alpha", "Natural Language :: English", "Programming Language :: Python :: 3",] +description = "Launcher and Config Reader for LCLS Interactive IPython Sessions" +dynamic = [ "version", "readme", "dependencies", "optional-dependencies", "optional-dependencies",] +keywords = [] +name = "hutch-python" +requires-python = ">=3.9" +[[project.authors]] +name = "SLAC National Accelerator Laboratory" + +[options] +zip_safe = false +include_package_data = true + +[project.license] +file = "LICENSE" + +[project.scripts] +hutch-python = "hutch_python.cli:main" +epicsarch-qs = "hutch_python.epics_arch:main" + +[tool.setuptools_scm] +write_to = "hutch_python/_version.py" + +[tool.isort] +skip = "load_conf.py" + +[tool.setuptools.packages.find] +where = [ ".",] +include = [ "hutch_python*",] +namespaces = false + +[tool.setuptools.dynamic.readme] +file = "README.rst" + +[tool.setuptools.dynamic.dependencies] +file = [ "requirements.txt",] + +[tool.setuptools.dynamic.optional-dependencies.test] +file = "dev-requirements.txt" diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 23adc7af..00000000 --- a/setup.cfg +++ /dev/null @@ -1,9 +0,0 @@ -[versioneer] -VCS = git -style = pep440 -versionfile_source = hutch_python/_version.py -versionfile_build = hutch_python/_version.py -tag_prefix = v - -[isort] -skip = load_conf.py diff --git a/setup.py b/setup.py deleted file mode 100644 index 94923001..00000000 --- a/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -from setuptools import find_packages, setup - -import versioneer - -with open("requirements.txt", "rt") as fp: - install_requires = [ - line for line in fp.read().splitlines() - if line and not line.startswith("#") - ] - -setup( - name="hutch-python", - version=versioneer.get_version(), - cmdclass=versioneer.get_cmdclass(), - license="BSD", - author="SLAC National Accelerator Laboratory", - packages=find_packages(), - include_package_data=True, - description=( - "Launcher and Config Reader for LCLS Interactive IPython Sessions" - ), - entry_points={ - "console_scripts": [ - "hutch-python=hutch_python.cli:main", - "epicsarch-qs=hutch_python.epics_arch:main", - ] - }, - install_requires=install_requires, - python_requires=">=3.6", -) From 7d3884f03cd66e36bc250acc9e241e7a07b67089 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Wed, 22 Feb 2023 11:18:19 -0800 Subject: [PATCH 14/28] BLD: migrate to setuptools-scm Performed by pcds-migration-tools SetuptoolsScmMigration --- hutch_python/__init__.py | 4 +- hutch_python/_version.py | 658 ------------ hutch_python/version.py | 59 ++ versioneer.py | 2140 -------------------------------------- 4 files changed, 60 insertions(+), 2801 deletions(-) delete mode 100644 hutch_python/_version.py create mode 100644 hutch_python/version.py delete mode 100644 versioneer.py diff --git a/hutch_python/__init__.py b/hutch_python/__init__.py index 877d20d7..1ef0c9f3 100644 --- a/hutch_python/__init__.py +++ b/hutch_python/__init__.py @@ -1,7 +1,5 @@ +from .version import __version__ # noqa: F401 import logging -from . import _version logger = logging.getLogger(__name__) - -__version__ = _version.get_versions()['version'] diff --git a/hutch_python/_version.py b/hutch_python/_version.py deleted file mode 100644 index 6144ebb1..00000000 --- a/hutch_python/_version.py +++ /dev/null @@ -1,658 +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.22 (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 Callable, Dict -import functools - - -def get_keywords(): - """Get the keywords needed to look up the version information.""" - # these strings will be replaced by git during git-archive. - # setup.py/versioneer.py will grep for the variable names, so they must - # each be defined on a line of their own. _version.py will just call - # get_keywords(). - git_refnames = "$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.""" - - -def get_config(): - """Create, populate and return the VersioneerConfig() object.""" - # these strings are filled in when 'setup.py versioneer' creates - # _version.py - cfg = VersioneerConfig() - cfg.VCS = "git" - cfg.style = "pep440" - cfg.tag_prefix = "v" - cfg.parentdir_prefix = "None" - cfg.versionfile_source = "hutch_python/_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, method): # decorator - """Create decorator to mark a method as the handler of a VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - process = None - - popen_kwargs = {} - 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: - e = sys.exc_info()[1] - 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, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for _ 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): - """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 = {} - 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, tag_prefix, verbose): - """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, root, verbose, runner=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - # 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=True) - if rc != 0: - if verbose: - print("Directory %s not under git control" % root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - MATCH_ARGS = ["--match", "%s*" % tag_prefix] if tag_prefix else [] - - # 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_ARGS], - 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 = {} - 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 - count_out, rc = runner(GITS, ["rev-list", "HEAD", "--count"], cwd=root) - pieces["distance"] = int(count_out) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = 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): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_branch(pieces): - """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): - """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): - """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): - """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): - """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): - """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): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-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(): - """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/hutch_python/version.py b/hutch_python/version.py new file mode 100644 index 00000000..da8a5d52 --- /dev/null +++ b/hutch_python/version.py @@ -0,0 +1,59 @@ +from collections import UserString +from pathlib import Path +from typing import Optional + + +class VersionProxy(UserString): + """ + Version handling helper that pairs with setuptools-scm. + + This allows for pkg.__version__ to be dynamically retrieved on request by + way of setuptools-scm. + + This deferred evaluation of the version until it is checked saves time on + package import. + + This supports the following scenarios: + + 1. A git checkout (.git exists) + 2. A git archive / a tarball release from GitHub that includes version + information in .git_archival.txt. + 3. An existing _version.py generated by setuptools_scm + 4. A fallback in case none of the above match - resulting in a version of + 0.0.unknown + """ + def __init__(self): + self._version = None + + def _get_version(self) -> Optional[str]: + # Checking for directory is faster than failing out of get_version + repo_root = Path(__file__).resolve().parent.parent + if (repo_root / ".git").exists() or (repo_root / ".git_archival.txt").exists(): + try: + # Git checkout + from setuptools_scm import get_version + return get_version(root="..", relative_to=__file__) + except (ImportError, LookupError): + ... + + # Check this second because it can exist in a git repo if we've + # done a build at least once. + try: + from ._version import version # noqa: F401 + return version + except ImportError: + ... + + return None + + @property + def data(self) -> str: + # This is accessed by UserString to allow us to lazily fill in the + # information + if self._version is None: + self._version = self._get_version() or '0.0.unknown' + + return self._version + + +__version__ = version = VersionProxy() diff --git a/versioneer.py b/versioneer.py deleted file mode 100644 index a142bf53..00000000 --- a/versioneer.py +++ /dev/null @@ -1,2140 +0,0 @@ - -# Version: 0.22 - -"""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 -* Compatible with: Python 3.6, 3.7, 3.8, 3.9, 3.10 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 distutils/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 - -* `pip install versioneer` to somewhere in your $PATH -* add a `[versioneer]` section to your setup.cfg (see [Install](INSTALL.md)) -* run `versioneer install` 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`, if necessary, to include any new configuration settings - indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details. -* re-run `versioneer install` in your source tree, to replace - `SRC/_version.py` -* commit any changed files - -## 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 Creative Commons "Public Domain -Dedication" license (CC0-1.0), as described in -https://creativecommons.org/publicdomain/zero/1.0/ . - -[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 typing import Callable, Dict -import functools - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - -def get_root(): - """Get the project root directory. - - We require that all commands are run from the project root, i.e. the - directory that contains setup.py, setup.cfg, and versioneer.py . - """ - root = os.path.realpath(os.path.abspath(os.getcwd())) - setup_py = os.path.join(root, "setup.py") - versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): - # allow 'python path/to/setup.py COMMAND' - root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) - setup_py = os.path.join(root, "setup.py") - versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): - err = ("Versioneer was unable to run the project root directory. " - "Versioneer requires setup.py to be executed from " - "its immediate directory (like 'python setup.py COMMAND'), " - "or in a way that lets it use sys.argv[0] to find the root " - "(like 'python path/to/setup.py COMMAND').") - raise VersioneerBadRootError(err) - try: - # Certain runtime workflows (setup.py install/develop in a setuptools - # tree) execute all dependencies in a single python process, so - # "versioneer" may be imported multiple times, and python's shared - # module-import table will cache the first one. So we can't use - # os.path.dirname(__file__), as that will find whichever - # versioneer.py was first imported, even in later projects. - 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: - 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): - """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 . - setup_cfg = os.path.join(root, "setup.cfg") - parser = configparser.ConfigParser() - with open(setup_cfg, "r") as cfg_file: - parser.read_file(cfg_file) - VCS = parser.get("versioneer", "VCS") # mandatory - - # Dict-like interface for non-mandatory entries - section = parser["versioneer"] - - cfg = VersioneerConfig() - cfg.VCS = VCS - cfg.style = section.get("style", "") - cfg.versionfile_source = section.get("versionfile_source") - cfg.versionfile_build = section.get("versionfile_build") - cfg.tag_prefix = section.get("tag_prefix") - if cfg.tag_prefix in ("''", '""'): - cfg.tag_prefix = "" - cfg.parentdir_prefix = section.get("parentdir_prefix") - 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, method): # decorator - """Create decorator to mark a method as the handler of a VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - HANDLERS.setdefault(vcs, {})[method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - process = None - - popen_kwargs = {} - 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: - e = sys.exc_info()[1] - 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.22 (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 Callable, Dict -import functools - - -def get_keywords(): - """Get the keywords needed to look up the version information.""" - # these strings will be replaced by git during git-archive. - # setup.py/versioneer.py will grep for the variable names, so they must - # each be defined on a line of their own. _version.py will just call - # get_keywords(). - git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" - git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" - git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" - keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} - return keywords - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - -def get_config(): - """Create, populate and return the VersioneerConfig() object.""" - # these strings are filled in when 'setup.py versioneer' creates - # _version.py - cfg = VersioneerConfig() - cfg.VCS = "git" - cfg.style = "%(STYLE)s" - cfg.tag_prefix = "%(TAG_PREFIX)s" - cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" - cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" - cfg.verbose = False - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -LONG_VERSION_PY: Dict[str, str] = {} -HANDLERS: Dict[str, Dict[str, Callable]] = {} - - -def register_vcs_handler(vcs, method): # decorator - """Create decorator to mark a method as the handler of a VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - process = None - - popen_kwargs = {} - 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: - e = sys.exc_info()[1] - 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, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for _ 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): - """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 = {} - 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, tag_prefix, verbose): - """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, root, verbose, runner=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - # 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=True) - if rc != 0: - if verbose: - print("Directory %%s not under git control" %% root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - MATCH_ARGS = ["--match", "%%s*" %% tag_prefix] if tag_prefix else [] - - # 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_ARGS], - 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 = {} - 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 - count_out, rc = runner(GITS, ["rev-list", "HEAD", "--count"], cwd=root) - pieces["distance"] = int(count_out) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = 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): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_branch(pieces): - """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): - """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): - """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): - """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): - """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): - """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): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-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(): - """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): - """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 = {} - 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, tag_prefix, verbose): - """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, root, verbose, runner=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - # 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=True) - if rc != 0: - if verbose: - print("Directory %s not under git control" % root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - MATCH_ARGS = ["--match", "%s*" % tag_prefix] if tag_prefix else [] - - # 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_ARGS], - 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 = {} - 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 - count_out, rc = runner(GITS, ["rev-list", "HEAD", "--count"], cwd=root) - pieces["distance"] = int(count_out) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = 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(manifest_in, versionfile_source, ipy): - """Git-specific installation logic for Versioneer. - - For Git, this means creating/changing .gitattributes to mark _version.py - for export-subst keyword substitution. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - files = [manifest_in, versionfile_source] - if ipy: - files.append(ipy) - try: - my_path = __file__ - if my_path.endswith(".pyc") or my_path.endswith(".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, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for _ 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.22) 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): - """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, versions): - """Write the given version number to the given _version.py file.""" - os.unlink(filename) - contents = json.dumps(versions, sort_keys=True, - indent=1, separators=(",", ": ")) - with open(filename, "w") as f: - f.write(SHORT_VERSION_PY % contents) - - print("set %s to '%s'" % (filename, versions["version"])) - - -def plus_or_dot(pieces): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_branch(pieces): - """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): - """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): - """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): - """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): - """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): - """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): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-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=False): - """Get the project version from whatever source is available. - - Returns dict with two keys: 'version' and 'full'. - """ - if "versioneer" in sys.modules: - # see the discussion in cmdclass.py:get_cmdclass() - del sys.modules["versioneer"] - - root = get_root() - cfg = get_config_from_root(root) - - assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" - handlers = HANDLERS.get(cfg.VCS) - assert handlers, "unrecognized VCS '%s'" % cfg.VCS - verbose = verbose or cfg.verbose - assert cfg.versionfile_source is not None, \ - "please set versioneer.versionfile_source" - assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" - - 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(): - """Get the short version string for this project.""" - return get_versions()["version"] - - -def get_cmdclass(cmdclass=None): - """Get the custom setuptools/distutils 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 both distutils and setuptools - try: - from setuptools import Command - except ImportError: - from distutils.core import Command - - class cmd_version(Command): - description = "report generated version string" - user_options = [] - boolean_options = [] - - def initialize_options(self): - pass - - def finalize_options(self): - pass - - def run(self): - vers = get_versions(verbose=True) - print("Version: %s" % vers["version"]) - print(" full-revisionid: %s" % vers.get("full-revisionid")) - print(" dirty: %s" % vers.get("dirty")) - print(" date: %s" % vers.get("date")) - if vers["error"]: - print(" error: %s" % vers["error"]) - cmds["version"] = cmd_version - - # we override "build_py" in both distutils and setuptools - # - # most invocation pathways end up running build_py: - # distutils/build -> build_py - # distutils/install -> distutils/build ->.. - # setuptools/bdist_wheel -> distutils/install ->.. - # setuptools/bdist_egg -> distutils/install_lib -> build_py - # setuptools/install -> bdist_egg ->.. - # setuptools/develop -> ? - # pip install: - # copies source tree to a tempdir before running egg_info/etc - # if .git isn't copied too, 'git describe' will fail - # then does setup.py bdist_wheel, or sometimes setup.py install - # setup.py egg_info -> ? - - # we override different "build_py" commands for both environments - if 'build_py' in cmds: - _build_py = cmds['build_py'] - elif "setuptools" in sys.modules: - from setuptools.command.build_py import build_py as _build_py - else: - from distutils.command.build_py import build_py as _build_py - - class cmd_build_py(_build_py): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - _build_py.run(self) - # now locate _version.py in the new build/ directory and replace - # it with an updated value - if cfg.versionfile_build: - target_versionfile = os.path.join(self.build_lib, - cfg.versionfile_build) - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - cmds["build_py"] = cmd_build_py - - if 'build_ext' in cmds: - _build_ext = cmds['build_ext'] - elif "setuptools" in sys.modules: - from setuptools.command.build_ext import build_ext as _build_ext - else: - from distutils.command.build_ext import build_ext as _build_ext - - class cmd_build_ext(_build_ext): - def run(self): - 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 - 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_ext"] = cmd_build_ext - - if "cx_Freeze" in sys.modules: # cx_freeze enabled? - from cx_Freeze.dist import build_exe as _build_exe - # nczeczulin reports that py2exe won't like the pep440-style string - # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. - # setup(console=[{ - # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION - # "product_version": versioneer.get_version(), - # ... - - class cmd_build_exe(_build_exe): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - target_versionfile = cfg.versionfile_source - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - _build_exe.run(self) - os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % - {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - cmds["build_exe"] = cmd_build_exe - del cmds["build_py"] - - if 'py2exe' in sys.modules: # py2exe enabled? - from py2exe.distutils_buildexe import py2exe as _py2exe - - class cmd_py2exe(_py2exe): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - target_versionfile = cfg.versionfile_source - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - _py2exe.run(self) - os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % - {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - cmds["py2exe"] = cmd_py2exe - - # we override different "sdist" commands for both environments - if 'sdist' in cmds: - _sdist = cmds['sdist'] - elif "setuptools" in sys.modules: - from setuptools.command.sdist import sdist as _sdist - else: - from distutils.command.sdist import sdist as _sdist - - class cmd_sdist(_sdist): - def run(self): - versions = get_versions() - self._versioneer_generated_versions = versions - # unless we update this, the command will keep using the old - # version - self.distribution.metadata.version = versions["version"] - return _sdist.run(self) - - def make_release_tree(self, base_dir, files): - root = get_root() - cfg = get_config_from_root(root) - _sdist.make_release_tree(self, base_dir, files) - # now locate _version.py in the new base_dir directory - # (remembering that it may be a hardlink) and replace it with an - # updated value - target_versionfile = os.path.join(base_dir, cfg.versionfile_source) - print("UPDATING %s" % target_versionfile) - 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(): - """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") - 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) - ipy = None - - # Make sure both the top-level "versioneer.py" and versionfile_source - # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so - # they'll be copied into source distributions. Pip won't be able to - # install the package without this. - manifest_in = os.path.join(root, "MANIFEST.in") - simple_includes = set() - try: - with open(manifest_in, "r") as f: - for line in f: - if line.startswith("include "): - for include in line.split()[1:]: - simple_includes.add(include) - except OSError: - pass - # That doesn't cover everything MANIFEST.in can do - # (http://docs.python.org/2/distutils/sourcedist.html#commands), so - # it might give some false negatives. Appending redundant 'include' - # lines is safe, though. - if "versioneer.py" not in simple_includes: - print(" appending 'versioneer.py' to MANIFEST.in") - with open(manifest_in, "a") as f: - f.write("include versioneer.py\n") - else: - print(" 'versioneer.py' already in MANIFEST.in") - if cfg.versionfile_source not in simple_includes: - print(" appending versionfile_source ('%s') to MANIFEST.in" % - cfg.versionfile_source) - with open(manifest_in, "a") as f: - f.write("include %s\n" % cfg.versionfile_source) - else: - print(" versionfile_source already in MANIFEST.in") - - # Make VCS-specific changes. For git, this means creating/changing - # .gitattributes to mark _version.py for export-subst keyword - # substitution. - do_vcs_install(manifest_in, cfg.versionfile_source, ipy) - return 0 - - -def scan_setup_py(): - """Validate the contents of setup.py against Versioneer's expectations.""" - found = set() - setters = False - errors = 0 - with open("setup.py", "r") as f: - for line in f.readlines(): - if "import versioneer" in line: - found.add("import") - if "versioneer.get_cmdclass()" in line: - found.add("cmdclass") - if "versioneer.get_version()" in line: - found.add("get_version") - if "versioneer.VCS" in line: - setters = True - if "versioneer.versionfile_source" in line: - setters = True - if len(found) != 3: - print("") - print("Your setup.py appears to be missing some important items") - print("(but I might be wrong). Please make sure it has something") - print("roughly like the following:") - print("") - print(" import versioneer") - print(" setup( version=versioneer.get_version(),") - print(" cmdclass=versioneer.get_cmdclass(), ...)") - print("") - errors += 1 - if setters: - print("You should remove lines like 'versioneer.VCS = ' and") - print("'versioneer.versionfile_source = ' . This configuration") - print("now lives in setup.cfg, and should be removed from setup.py") - print("") - errors += 1 - return errors - - -if __name__ == "__main__": - cmd = sys.argv[1] - if cmd == "setup": - errors = do_setup() - errors += scan_setup_py() - if errors: - sys.exit(1) From 1285f6592ceebc233dfadc67953d0ca2ef47bed6 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Wed, 22 Feb 2023 11:18:19 -0800 Subject: [PATCH 15/28] BLD: update conda-recipe Performed by pcds-migration-tools UpdateCondaRecipe --- conda-recipe/build.sh | 1 - conda-recipe/meta.yaml | 77 +++++++++++++++++++++++------------------- 2 files changed, 43 insertions(+), 35 deletions(-) delete mode 100644 conda-recipe/build.sh diff --git a/conda-recipe/build.sh b/conda-recipe/build.sh deleted file mode 100644 index a6609066..00000000 --- a/conda-recipe/build.sh +++ /dev/null @@ -1 +0,0 @@ -$PYTHON setup.py install --single-version-externally-managed --record=record.txt diff --git a/conda-recipe/meta.yaml b/conda-recipe/meta.yaml index abfaa4a9..bc46a7a7 100644 --- a/conda-recipe/meta.yaml +++ b/conda-recipe/meta.yaml @@ -1,52 +1,61 @@ -{% set data = load_setup_py_data() %} +{% set package_name = "hutch_python" %} +{% set import_name = "hutch_python" %} +{% set version = load_file_regex(load_file=os.path.join(import_name, "_version.py"), regex_pattern=".*version = '(\S+)'").group(1) %} package: - name: hutch-python - version : {{ data.get('version') }} + name: {{ package_name }} + version: {{ version }} source: path: .. build: - number: 1 + number: 0 noarch: python + script: {{ PYTHON }} -m pip install . -vv + + requirements: build: - - python >=3.9 - - setuptools - + - python >=3.9 + - setuptools_scm + - pip run: - - python >=3.9 - - archapp >=1.0.2 - - bluesky >=1.8.0 - - coloredlogs >=15.0.0 - - cookiecutter >=1.7.0 - - elog >=1.1.0 - - happi >=1.9.0 - - ipython >=7.26.0 - - jinja2 >=2.11.0 - - lightpath >=1.0.1 - - matplotlib >=3.4.0 - - nabs >=1.5.0 - - pcdscalc >=0.3.0 - - pcdsdaq >=2.3.0 - - pcdsdevices >=7.0.0 - - pcdsutils >=0.6.0 - - psdaq-control-minimal >=3.3.19 - - psdm_qs_cli >=0.3.1 - - pyfiglet >=0.8.0 - - pyqt <5.15.0 - - pyyaml >=5.4.0 - - requests >=2.26.0 - - simplejson >=3.17.0 + - python >=3.9 + - archapp >=1.0.2 + - bluesky >=1.8.0 + - coloredlogs >=15.0.0 + - cookiecutter >=1.7.0 + - elog >=1.1.0 + - happi >=1.9.0 + - ipython >=7.26.0 + - jinja2 >=2.11.0 + - lightpath >=1.0.1 + - matplotlib >=3.4.0 + - nabs >=1.5.0 + - pcdscalc >=0.3.0 + - pcdsdaq >=2.3.0 + - pcdsdevices >=7.0.0 + - pcdsutils >=0.6.0 + - psdaq-control-minimal >=3.3.19 + - psdm_qs_cli >=0.3.1 + - pyfiglet >=0.8.0 + - pyqt <5.15.0 + - pyyaml >=5.4.0 + - requests >=2.26.0 + - simplejson >=3.17.0 + + test: - imports: - - hutch_python commands: - - hutch-python --help - - epicsarch-qs --help + - hutch-python --help + - epicsarch-qs --help + imports: + - hutch_python + + about: home: https://github.com/pcdshub/hutch-python From d4835ff62fa3462bd2f36ce41837135f3e97c770 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Wed, 22 Feb 2023 11:18:22 -0800 Subject: [PATCH 16/28] MNT: cleaning code with pycln Performed by pcds-migration-tools RunPycln --- hutch_python/happi.py | 1 - hutch_python/ipython_log.py | 1 - hutch_python/log_setup.py | 1 - hutch_python/obj_config.py | 2 +- hutch_python/print_hint_banner.py | 1 - hutch_python/tests/test_ipython_log.py | 2 +- 6 files changed, 2 insertions(+), 6 deletions(-) diff --git a/hutch_python/happi.py b/hutch_python/happi.py index 2bac6eca..fc8fcb92 100644 --- a/hutch_python/happi.py +++ b/hutch_python/happi.py @@ -1,6 +1,5 @@ import inspect import logging -from typing import Dict import happi import ophyd diff --git a/hutch_python/ipython_log.py b/hutch_python/ipython_log.py index 3ae19519..1fd66cae 100644 --- a/hutch_python/ipython_log.py +++ b/hutch_python/ipython_log.py @@ -10,7 +10,6 @@ import threading import traceback import types -from typing import Tuple from .constants import INPUT_LEVEL from .log_setup import log_exception_to_central_server diff --git a/hutch_python/log_setup.py b/hutch_python/log_setup.py index 94e91e39..ad541a6e 100644 --- a/hutch_python/log_setup.py +++ b/hutch_python/log_setup.py @@ -36,7 +36,6 @@ import logging import logging.config import os -import sys import textwrap import threading import time diff --git a/hutch_python/obj_config.py b/hutch_python/obj_config.py index efc23244..ccd00eb9 100644 --- a/hutch_python/obj_config.py +++ b/hutch_python/obj_config.py @@ -1,6 +1,6 @@ import logging from pathlib import Path -from typing import Callable, Tuple, Union +from typing import Callable, Union import yaml from ophyd import Device, Kind diff --git a/hutch_python/print_hint_banner.py b/hutch_python/print_hint_banner.py index 6c8b9d31..04d39fb1 100644 --- a/hutch_python/print_hint_banner.py +++ b/hutch_python/print_hint_banner.py @@ -12,7 +12,6 @@ imported from. """ -from typing import List from hutch_python.env_version import get_env_info diff --git a/hutch_python/tests/test_ipython_log.py b/hutch_python/tests/test_ipython_log.py index 05318592..8dc35752 100644 --- a/hutch_python/tests/test_ipython_log.py +++ b/hutch_python/tests/test_ipython_log.py @@ -2,7 +2,7 @@ import logging import sys from queue import Empty, Queue -from typing import Any, Dict, List, Optional +from typing import Any, Optional import pytest From 0c6f190b69ded9fdfa5e9f46695d0adc97f012d3 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Wed, 22 Feb 2023 11:18:26 -0800 Subject: [PATCH 17/28] DEV: 'pre-commit autoupdate' Performed by pcds-migration-tools PrecommitAutoupdate --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 814e228a..37c02121 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -28,6 +28,6 @@ repos: - id: flake8 - repo: https://github.com/timothycrosley/isort - rev: 5.11.4 + rev: 5.12.0 hooks: - id: isort From 921ad6df04ce27d9e3bbf3a2e16e7e95d567e094 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Wed, 22 Feb 2023 11:25:11 -0800 Subject: [PATCH 18/28] STY: fix flake8 issues manually --- .pre-commit-config.yaml | 6 +++++- docs/source/conf.py | 5 +++-- hutch_python/__init__.py | 2 +- hutch_python/calc_defaults.py | 2 +- hutch_python/cli.py | 6 +++--- hutch_python/debug.py | 10 ++++----- hutch_python/env_version.py | 7 +++--- hutch_python/lcls.py | 10 ++++----- hutch_python/load_conf.py | 31 ++++++++++++++------------- hutch_python/namespace.py | 8 ++++--- hutch_python/ophyd_settings.py | 2 +- hutch_python/tests/conftest.py | 2 +- hutch_python/tests/test_epics_arch.py | 2 +- 13 files changed, 51 insertions(+), 42 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 37c02121..d21aff89 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -19,7 +19,11 @@ repos: - id: check-symlinks - id: check-xml - id: check-yaml - exclude: '^(conda-recipe/meta.yaml)$' + exclude: | + (?x)^( + conda-recipe/meta.yaml| + hutch_python/cookiecutter/.*/conf.yml + )$ - id: debug-statements - repo: https://github.com/pycqa/flake8.git diff --git a/docs/source/conf.py b/docs/source/conf.py index 16eef05c..6ae3ee43 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -12,11 +12,14 @@ import os import sys + import sphinx_rtd_theme module_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../") sys.path.insert(0, module_path) +import hutch_python # noqa: E402 + # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. @@ -62,8 +65,6 @@ # built documents. # # The short X.Y version. -import hutch_python - version = str(hutch_python.__version__) # The full version, including alpha/beta/rc tags. release = str(hutch_python.__version__) diff --git a/hutch_python/__init__.py b/hutch_python/__init__.py index 1ef0c9f3..76b1dcde 100644 --- a/hutch_python/__init__.py +++ b/hutch_python/__init__.py @@ -1,5 +1,5 @@ -from .version import __version__ # noqa: F401 import logging +from .version import __version__ # noqa: F401 logger = logging.getLogger(__name__) diff --git a/hutch_python/calc_defaults.py b/hutch_python/calc_defaults.py index 326609e5..36838924 100644 --- a/hutch_python/calc_defaults.py +++ b/hutch_python/calc_defaults.py @@ -36,4 +36,4 @@ def collect_functions(modules): be_lens=collect_functions(['pcdscalc.be_lens_calcs']), common=collect_functions(['pcdscalc.common']), diffraction=collect_functions(['pcdscalc.diffraction']), - ) +) diff --git a/hutch_python/cli.py b/hutch_python/cli.py index e5a53074..efe3004c 100644 --- a/hutch_python/cli.py +++ b/hutch_python/cli.py @@ -104,9 +104,9 @@ def configure_ipython_session(): # Run startup hook code, print banner after startup hook files files = [ - str(DIR_MODULE / 'startup_script.py'), - str(DIR_MODULE / 'print_hint_banner.py') - ] + str(DIR_MODULE / "startup_script.py"), + str(DIR_MODULE / "print_hint_banner.py"), + ] ipy_config.InteractiveShellApp.exec_files = files return ipy_config diff --git a/hutch_python/debug.py b/hutch_python/debug.py index 88d361ea..5614b246 100644 --- a/hutch_python/debug.py +++ b/hutch_python/debug.py @@ -5,11 +5,11 @@ set_console_level) debug_tools = { - 'debug_console_level': set_console_level, - 'debug_mode': debug_mode, - 'debug_context': debug_context, - 'debug_wrapper': debug_wrapper, - } + "debug_console_level": set_console_level, + "debug_mode": debug_mode, + "debug_context": debug_context, + "debug_wrapper": debug_wrapper, +} def load_debug(cache): diff --git a/hutch_python/env_version.py b/hutch_python/env_version.py index f8d4bcaf..e109c2a9 100644 --- a/hutch_python/env_version.py +++ b/hutch_python/env_version.py @@ -61,9 +61,10 @@ def get_standard_dev_pkgs() -> set[str]: return set() paths = pythonpath.split(os.pathsep) valid_paths = filter(not_ignored, paths) - pkg_names = {n.name for n in - pkgutil.iter_modules(path=valid_paths) - if n.ispkg} + pkg_names = { + n.name for n in pkgutil.iter_modules(path=valid_paths) + if n.ispkg + } return pkg_names diff --git a/hutch_python/lcls.py b/hutch_python/lcls.py index f23c9f5d..5267eb6d 100644 --- a/hutch_python/lcls.py +++ b/hutch_python/lcls.py @@ -7,11 +7,11 @@ def global_devices(): """ return dict( beam_stats=BeamStats(), - lcls=LCLS() - ) + lcls=LCLS(), + ) global_device_docs = { - 'beam_stats': 'Summary of the most important beam statistics.', - 'lcls': 'Collection of all upstream x-ray diagnostics.', - } + "beam_stats": "Summary of the most important beam statistics.", + "lcls": "Collection of all upstream x-ray diagnostics.", +} diff --git a/hutch_python/load_conf.py b/hutch_python/load_conf.py index 58ee3e30..72cdb3f2 100644 --- a/hutch_python/load_conf.py +++ b/hutch_python/load_conf.py @@ -182,8 +182,7 @@ def load_conf(conf, hutch_dir=None, args=None): hutch = None except KeyError: hutch = None - logger.info('Missing hutch from conf. Will skip elog ' - 'and cameras.') + logger.info("Missing hutch from conf. Will skip elog and cameras.") # Display the banner if hutch is None: @@ -203,8 +202,7 @@ def load_conf(conf, hutch_dir=None, args=None): db = None except KeyError: db = None - logger.info('Missing db from conf. Will skip loading from shared ' - 'database.') + logger.info('Missing db from conf. Will skip loading from shared database.') try: load = conf['load'] if not isinstance(load, (str, list)): @@ -223,9 +221,11 @@ def load_conf(conf, hutch_dir=None, args=None): except KeyError: experiment = None if hutch is None: - logger.info('Missing hutch and experiment from conf. Will not ' - 'load objects from questionnaire or experiment ' - 'file.') + logger.info( + "Missing hutch and experiment from conf. Will not " + "load objects from questionnaire or experiment " + "file." + ) try: obj_config = conf['obj_config'] @@ -240,8 +240,9 @@ def load_conf(conf, hutch_dir=None, args=None): obj_config = None except KeyError: obj_config = None - logger.info('Missing obj_config from conf. Will skip applying ' - 'user settings to devices.') + logger.info( + 'Missing obj_config from conf. Will skip applying user settings to devices.' + ) try: # Configure whether we use the LCLS-I or LCLS-II daq daq_type = conf['daq_type'] @@ -327,7 +328,7 @@ def load_conf(conf, hutch_dir=None, args=None): logger.warning( 'Disabling bluesky scan plots. Matplotlib config must ' 'be set up for qt5 for bluesky scans to work!' - ) + ) bec.disable_plots() RE.subscribe(bec) @@ -337,7 +338,7 @@ def load_conf(conf, hutch_dir=None, args=None): cache.doc( RE='Bluesky plan executor.', bec='Bluesky best-effort callback for visualization settings.', - ) + ) # Inline calculations with safe_load('calc utils'): @@ -394,13 +395,13 @@ def load_conf(conf, hutch_dir=None, args=None): bpp=plan_defaults.preprocessors, re=run_namespace, register_plan=register_plan, - ) + ) cache.doc( bp='Namespace of full bluesky plans.', bps='Namespace of bluesky plan building blocks (stubs).', bpp='Namespace of bluesky plan preprocessors.', - re='Wrapped plans for quick running.' - ) + re='Wrapped plans for quick running.', + ) # Scan PVs if hutch is not None: @@ -532,7 +533,7 @@ def load_conf(conf, hutch_dir=None, args=None): slits='Namespace of all slits objects.', detectors='Namespace of all ami detector objects.', all_objects='Namespace of all loaded objects.', - ) + ) # Install Presets if hutch_dir is not None: diff --git a/hutch_python/namespace.py b/hutch_python/namespace.py index 65ee4f27..76268475 100644 --- a/hutch_python/namespace.py +++ b/hutch_python/namespace.py @@ -148,9 +148,11 @@ def tree_namespace(scope=None): setattr(upper_space, key, IterableNamespace()) upper_space = getattr(upper_space, key) if hasattr(upper_space, name): - logger.warning('Tried to add {} to {}, but something was ' - 'already there. Two devices share the same ' - 'name!'.format(name, upper_space)) + logger.warning( + f"Tried to add {name} to {upper_space}, but something was " + f"already there. Two devices share the same " + f"name!" + ) else: setattr(upper_space, name, obj) logger.debug('Created tree namespace %s', tree_space) diff --git a/hutch_python/ophyd_settings.py b/hutch_python/ophyd_settings.py index c94e4d77..17566e18 100644 --- a/hutch_python/ophyd_settings.py +++ b/hutch_python/ophyd_settings.py @@ -44,4 +44,4 @@ def setup_ophyd(): timeout=float(os.environ.get(READ_VAR, 2.0)), write_timeout=float(os.environ.get(WRITE_VAR, 5.0)), auto_monitor=os.environ.get(AUTO_VAR, 'false').lower() in AUTO_TRUE, - ) + ) diff --git a/hutch_python/tests/conftest.py b/hutch_python/tests/conftest.py index 6627b1e9..b4d44194 100644 --- a/hutch_python/tests/conftest.py +++ b/hutch_python/tests/conftest.py @@ -48,7 +48,7 @@ skip_if_win32_generic = pytest.mark.skipif( sys.platform == 'win32', reason='Does not run on Windows', - ) +) skip_if_win32_pcdsdaq = pytest.mark.skipif( sys.platform == 'win32', reason='Fails on Windows (pcdsdaq)', diff --git a/hutch_python/tests/test_epics_arch.py b/hutch_python/tests/test_epics_arch.py index 5cf5ba4e..efbb5465 100644 --- a/hutch_python/tests/test_epics_arch.py +++ b/hutch_python/tests/test_epics_arch.py @@ -64,7 +64,7 @@ def test_print_dry_run(items, capsys): '* tape_x', 'XPP:LBL:MMN:04', '* transducer_y', 'XPP:LBL:MMN:05', '* xes_y', 'XPP:LBL:MMN:06', '* lbl', 'XPP:USR:EVR:TRIG0', '* acromag', 'XPP:USR:ao1' - ] + ] expected_str = '' for m in expected_list: expected_str += m + '\n' From 172d42f877d4fc0d426ffc88bc8b59b4fda0c1a3 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Wed, 22 Feb 2023 11:25:33 -0800 Subject: [PATCH 19/28] CLN: deploy key no longer required --- github_deploy_key_pcdshub_hutch_python.enc | 1 - 1 file changed, 1 deletion(-) delete mode 100644 github_deploy_key_pcdshub_hutch_python.enc diff --git a/github_deploy_key_pcdshub_hutch_python.enc b/github_deploy_key_pcdshub_hutch_python.enc deleted file mode 100644 index a227b70e..00000000 --- a/github_deploy_key_pcdshub_hutch_python.enc +++ /dev/null @@ -1 +0,0 @@ -gAAAAABgeLONbvU6R2hwb0WjBdEukWAPayBIAdruAOEX9dK9VMgDdcb2D3807Mf9E3Q0wsCUffIzRd7LqmecfOCJu0m3x4LMPf0duIDfPEahrbN2yoWbRrolw_62YO4zO-haGR3rEYWgq5LNZ_zSDRdozxgNuy1Vkk1cBAwYW-0scAx0A4YRod6OzHSciTknZpQwD4KgOjr5faoUKXXD4OzkWXs0nHMmIuigMBgC2Q83P385vDMeBIsOBfntIC4MA7WvsPenS6OEhtxutUZjYrv5zbB9c_cNBH1LNE3yltt2Nsq1YTq4IBTtMIOMtmq0pt-nSR1EB-IfXtbqNO1mOoCHjk4aHu6CqOv4Nd0vw-0iGfxxtPJX25_9-J6F7C9eNHy4K3sXTtNdsJMhbUU8bNY7byHkjvcwe6uZJe3DLdnfy1VoEZwztY-cjA_QPnkI-9lqVR1g0kyWTPgN-9NcCCK2ca5KlXuegyJ4R4P_8gC6gPEEIBsUd-1YIUL2y8Ax8J4Hok5LXvdFiqNqYZrjyoOv3WqMFNp8MDJFydjzi39I_qb12kSxbb7BIcsBdPUanNR5KKF7sLC708D_2dnXqGEoASMqXWDCsdkdSHlaanfxqEqKqLJ4QB83HE00ULXSlLZmOMcF8q31JkRNqXIVzPyQ6b3k1maLd6yoBnbWAHh4GmkZJh8Ysfd6lL1jTzex4Anew06ibVbhU3Rt32N_hHpc8AQrJ2Apho72qb9rNfCpLDIiLjmFY0ZN2I3VwADbX9TlOkjFGkCdVCeIj5gKax9O_44AVtVrbw3RwcByisJZB8zwRmP5S7fCrOn-U_E95Nd5q_PXWgOHuRaXvSN-6r6Da4sHcg72sjNN6ECsNXqsb9DM3vDbalPEFrVnhvL4EnmsHd39_QWvp9t-RKmD-O5J1phiwif1TwVjE0iGOrLItob2M4BUFPXqXVdMyLKS0rqsFd54deL8E24ADrfHJ8dygNrorwMHnGokF_oTBXcPCWYEpw7anv1BB54PlUkbrR0rQDHSqIlLbdzyCUx1-7NJ99GhUhMifW0xhKla13HgPwbRWiJ2DxqOS_3DPyiDKt_Tra0rP8vY32-iImz-EQ8-dy5Fz0ZjEXW807HcW7B1OQM-s2aGUezSAWGAUV09p-60rdkXU90Q4sH6Q5YEcWawaCVL_rFCYOy57twKA4y1kVhJFPRyNkJSAoIRsTJbmtJVAkV-I-Q8MrzSmjAoN7855ZTFozCeJduoCxdD-PT0rL4GETgCcKQq6Gg5wobL5PPCTp6EoMStewB2rqjcWgHwj72liQbz-9JJHiUQs4jWqj7ew4Fv-stEfFMd1eASRoV3tRYJDD0BuEmhKM08FDVOuVq_A0NqPgVMTkMNvRfb_i0NaQdS_9R_cyJVsa7rB04cSSRf8fXbzygf_xnw9wyeiadNph1EnWzKaP3UxdVPCTGCBG9ieM-kns64ETi1HijPa4KuhJFs5AUH9t4hXBGQtl07PuspmrCw3xVtnh1sZrv7g503kclQkfAKkMXShvG2vU5hs1A2VgLlzGT1gCBc-JPYWfZDDwRlUzsn34-7uGa0i2sGejo9Y0F6iiNOw-bno1IciIw5BjaZIRjvtHJBySmjmBl3TRV-IIOOfxCSZyki1X9JL3ftpmyq-s6LozbXkJ72ukoZ0ef4VH7HOX2mSqc0bz_5-CuJHuB0UC-oDKvpshJVkhtTrKcgMIRiOV3ry8hrtBrS91GTFJIWeS1UEbsgfkfgGkM4JFnRU5OYNnN1BI28vEbwyzGJYrvZ2Lef_2PxWoUyV6TN2p9DE3x9NmcyHUCiQYe8ZypxVFgrdp2mXgZ32ivNnDp9lDPzhJoRPVlUg4C5n17tNijapF6P_nsex7NvzB3JuP06jXRoDcFWPVtZSDEV7qQD9yk0tK0SPsqMDxA-7VE5XoMnFzGiWAuvAqxn-E6PrpRjVoqXXycQZP-I2Ec1dI5X6ip3EVu0dDaK4fZXHHA-689lpEotQAnE43GhsL5KYoaT235CAHDg-NaPY3RxbtvAHbCJjLsE4iMPA3Iu9h68kxcREyqpVkAkh4XoTPvgVROa83YeamyYUkKcaGRrpgHmXFeMGiLHnr9R5IGqNkhkuS9ptlwH2lhIIBHsvVBYB4AfOgP-hY3yWEdzpX_bn4601UL4Bw-i3LWwZ5S74s8zp1sf5bYPOckV4jdTChLi1-I6L9hVZFtqxVo4BThrHUqS0vfgK58dtlHuB9ZKTYaTKGTQMOCds6QHRbiv-ly0xY0iKRpKKEys5ZlU-vkY_j19oOuHS7bUeb461IzxQIBqhNNMMGYs0Sv-35Hj3Q2nHxUgp-F7SsHS9ma53pFVbGpu_QsnAuZRQz_BVvKklP1JAQUvH1g7EoMyd0fo553Pb9jAZRXF5YMAozwZAyXlNjjD-BpCCdoZN4KjPmj6sQdsE6qhpUqHkuYGcMNNVN-AoobRx6Buu-ERXaDrlw-t9W9Ah1JuvrHttpTetHSkg2K6alE9QGqsI5qnBFDkWLGfUbdAo6lLM9CoWowdA6aLLp9M0zv2mwAYejMJWQBgKjeVygT43BbScCJKsBEQPkw8ZwWPOyCOkxWBN3v9KbYTE2Bj0GnxLICMQP3zbriscCTzDp1BRMA20IYauzYRSjv1lwkBuLeu_sGYCWfuCX_omCuVbUhU-Io1WNpUaUi_ZgLzwTCieJEEcKZ3zs0FNoGnA8LRZo5ovPK5wowg5x4MFRCN3nCgpgg35eCpKJ_u4OrJr9iTokPZxg9bxKnISewahXqnZvZJuPbf6mZyOBfsfdx9e-wN40HE1ej7LmhSKPWCyMNKmTi7mtBp6p04K-0EFq6SPxmUK2IkRia0JzR_0ACgkQHidCOgOIUXbH874dpUNDO4Umlat7xb9fl0PL-Hw59XHKDNT2awfV_2ZNTjtUDaSf4t5X75w2bcF6J7XduHK7gtjt__ekUzYNWjLa9bfG16P0l7mmTn0d811lYAkVYel8t9jDI2b1mCyAcdjtPk_9xCAAd3d5YQsQJkkJ8leVlWAsRfrERynzmCoxZKLTkO3W3C9q8uDAcMasK7qKTSFAvmMvmQfgipwKpYUUGJa8tUso_cz_cHcZWMwgLP1up2vjvtr40_Cl539HDfJprR6B9XYCG2_FPafCboq3fGu-CCKDh-JiaLSLrGbYT1zmQNF3NRK4oJxaEVJiy7Q4ilbN8M5gBiVK8lpP27vg35yBck109SA9XS54fSAQcgNk7vl2kSAmqYWOn_AQ955Or2SiexN6yRpOw2NZIFEVs9i9eS6Bpbr-x8b7sNxavrd86mU519qLqsCnUz3FjgZC5se0xa9nQIdVo97RTtTcZYnPxDHp2JLnd4OXJA8cETZyEVomLzztZEdp1oxlrINJE5lSNNkz4ErDynEvPX9AZCM3G8jnPpYs3_q5eQV8e5sapuJ1U29bWpwhksMTPtoRVrf8U45Dh-Ui9rJ9oAnzVA-2fQMFh1u5mIF0Qqc-QbiJ77jpZge1uQ2tEdLHf1JnIE6sPQ56myItfX0R8ZAXvbA1WWY8RZv6c7uEShauDU98oFkcPciWh3hkXBJIOY8clMZcQ_SJHt8d76ftUT1gmeygdXnNMwcoyiRiC1fzm-Z_useH26lH27BxadKvyAVOpF5cVMgz7azBbYb2ytslQY1sL98Ql-MrG6GAr6AOKvCsIXLDdQkp-F97X5WIYmS2FjRYPVP1OKZfD0Lp1vGzPSqK0Fn5KtIzp4SuRlgBEFSIMiZxOejwYGKuprOnySb7vjAKN8fka2JygLLTLNmDg3Frhtrrp0n8E5ihhwxfhKg0KcEWx-VHHNmSSCqoE4hhT9wfZp8rOaE4z18NLKWjjKmWfWFS1Q69J1BzkjDrLGgjxUN5UVT1QNnpTuoL3KNfykjmPoHmO4dhoaSw6im1WLoSZWktmqSLaIW-PNzw3HunpAy0poyAx07w57IGTaXNRDeikQUpcT1AikW9KzQCn4wyn44Bv5g0mrEbxNePeUP-USHzANHOWNW2IJ3Lb61yGI3VjseQ_l7c6mjCPm5wbFsNt0-apStSawMOpwNPlFwvM1CanUudvqtpBqkC08uY4HZ3wNveYDmj9Qt4NJBmcNTIT-TTt__U1WjFoCa0Om1g9c6_BhNovm1snKA3agrs_d4MDgsvW8IdrzTcsi_xThz_uFGn9CikZUu8EQ4zQmGA8VTRBzLKYia3SGXa3R0DrU9SzGo0uWD6tNFdc3_y1z1xiiMB-TMpllOEie_YcNCY39fPpvyKhl_G9ofid72IFRyIy00Q1QH8YgmR1QecrbtUoi5XSAtQPWF5ve-KknGhRL5y2CDT9CULQy_VqUDKZ379-SZMefVZuzp7kmBSsw-EBpkCk24FrclkvnwRZF_z4HnUY9Z3FI0-R67I-TcdvTgMJTK--ZPMWWfgfikQ== From 8bf2c5a3e29a4564cfc766c7671c3776b4c36205 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Wed, 22 Feb 2023 11:27:22 -0800 Subject: [PATCH 20/28] BLD: fix up dev/docs requirements --- conda-recipe/meta.yaml | 10 ++++------ dev-requirements.txt | 6 ------ docs-requirements.txt | 4 ++++ 3 files changed, 8 insertions(+), 12 deletions(-) create mode 100644 docs-requirements.txt diff --git a/conda-recipe/meta.yaml b/conda-recipe/meta.yaml index bc46a7a7..bbbe0b91 100644 --- a/conda-recipe/meta.yaml +++ b/conda-recipe/meta.yaml @@ -14,8 +14,6 @@ build: noarch: python script: {{ PYTHON }} -m pip install . -vv - - requirements: build: - python >=3.9 @@ -46,16 +44,16 @@ requirements: - requests >=2.26.0 - simplejson >=3.17.0 - - test: commands: - hutch-python --help - epicsarch-qs --help imports: - hutch_python - - + requires: + - packaging + - pytest + - pytest-timeout about: home: https://github.com/pcdshub/hutch-python diff --git a/dev-requirements.txt b/dev-requirements.txt index 02a49654..0cd18b96 100644 --- a/dev-requirements.txt +++ b/dev-requirements.txt @@ -1,9 +1,3 @@ -sphinx -sphinx_rtd_theme -nbsphinx -doctr packaging pytest pytest-timeout -flake8 -sphinxcontrib-jquery diff --git a/docs-requirements.txt b/docs-requirements.txt new file mode 100644 index 00000000..0647bc4b --- /dev/null +++ b/docs-requirements.txt @@ -0,0 +1,4 @@ +nbsphinx +sphinx +sphinx_rtd_theme +sphinxcontrib-jquery From 84940880ae85b7a1795884c43f71aaf529ab5b95 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Wed, 22 Feb 2023 11:28:55 -0800 Subject: [PATCH 21/28] MNT: fix up pyproject.toml --- pyproject.toml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 3f9be392..f453e223 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,12 +3,13 @@ build-backend = "setuptools.build_meta" requires = [ "setuptools>=45", "setuptools_scm[toml]>=6.2",] [project] -classifiers = [ "Development Status :: 2 - Pre-Alpha", "Natural Language :: English", "Programming Language :: Python :: 3",] +classifiers = [ "Development Status :: 5 - Production/Stable", "Natural Language :: English", "Programming Language :: Python :: 3",] description = "Launcher and Config Reader for LCLS Interactive IPython Sessions" -dynamic = [ "version", "readme", "dependencies", "optional-dependencies", "optional-dependencies",] +dynamic = [ "version", "readme", "dependencies", "optional-dependencies",] keywords = [] name = "hutch-python" requires-python = ">=3.9" + [[project.authors]] name = "SLAC National Accelerator Laboratory" @@ -42,3 +43,6 @@ file = [ "requirements.txt",] [tool.setuptools.dynamic.optional-dependencies.test] file = "dev-requirements.txt" + +[tool.setuptools.dynamic.optional-dependencies.docs] +file = "docs-requirements.txt" From 6d8ed396bda6343670f4bb3e4cdce071fe502cf2 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Wed, 22 Feb 2023 11:34:22 -0800 Subject: [PATCH 22/28] DOC: add pre-release notes --- .../358-migrate-to-gha.rst | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 docs/source/upcoming_release_notes/358-migrate-to-gha.rst diff --git a/docs/source/upcoming_release_notes/358-migrate-to-gha.rst b/docs/source/upcoming_release_notes/358-migrate-to-gha.rst new file mode 100644 index 00000000..06950c45 --- /dev/null +++ b/docs/source/upcoming_release_notes/358-migrate-to-gha.rst @@ -0,0 +1,35 @@ +358 Migrate to GHA +################## + +API Changes +----------- +- N/A + +Features +-------- +- N/A + +Bugfixes +-------- +- N/A + +Maintenance +----------- +- hutch-python no longer uses Travis CI and has migrated to GitHub Actions for + continuous integration, testing, and documentation deployment. +- hutch-python has been migrated to use setuptools-scm, replacing versioneer, as its + version-string management tool of choice. +- hutch-python has been migrated to use the modern ``pyproject.toml``, replacing + ``setup.py`` and related files. +- Older language features and syntax found in the repository have been updated + to Python 3.9+ standards by way of ``pyupgrade``. +- Sphinx 6.0 is now supported for documentation building. + ``docs-versions-menu`` replaces ``doctr-versions-menu`` and ``doctr`` usage + for documentation deployment on GitHub Actions. The deployment key is now no + longer required. +- pyupgrade was used to update annotations, and pycln was used to clean up + imports. + +Contributors +------------ +- klauer From 2e5ec6b54e69bd488b36de343c310d2e7308a361 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Wed, 22 Feb 2023 11:46:41 -0800 Subject: [PATCH 23/28] CI: hutch_python is the import name --- .github/workflows/standard.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/standard.yml b/.github/workflows/standard.yml index 6065bbb6..ed345bc9 100644 --- a/.github/workflows/standard.yml +++ b/.github/workflows/standard.yml @@ -13,7 +13,7 @@ jobs: with: # The workflow needs to know the package name. This can be determined # automatically if the repository name is the same as the import name. - package-name: "hutch-python" + package-name: "hutch_python" # Extras that will be installed for both conda/pip: testing-extras: "" # Extras to be installed only for conda-based testing: From b557ba618973db74e13798d4af3a92ea31acb51c Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Wed, 22 Feb 2023 11:49:16 -0800 Subject: [PATCH 24/28] BLD: lightpath for pip testing, pandoc/pypandoc for docs --- .github/workflows/standard.yml | 10 ++++++++-- dev-requirements.txt | 1 + docs-requirements.txt | 1 + 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/.github/workflows/standard.yml b/.github/workflows/standard.yml index ed345bc9..fb8ffb2f 100644 --- a/.github/workflows/standard.yml +++ b/.github/workflows/standard.yml @@ -17,8 +17,14 @@ jobs: # Extras that will be installed for both conda/pip: testing-extras: "" # Extras to be installed only for conda-based testing: - conda-testing-extras: "ipython=8.4.0 pandoc pypandoc" + conda-testing-extras: "ipython=8.4.0" # Extras to be installed only for pip-based testing: - pip-testing-extras: "ipython==8.4.0 lightpath" + pip-testing-extras: "ipython==8.4.0" + # System packages to be installed only for conda-based testing: + conda-system-packages: "" + # System packages to be installed only for pip-based testing: + pip-system-packages: "" + # System packages to be installed only for documentation: + docs-system-packages: "pandoc" # Set if using setuptools-scm for the conda-build workflow use-setuptools-scm: true diff --git a/dev-requirements.txt b/dev-requirements.txt index 0cd18b96..f51528b2 100644 --- a/dev-requirements.txt +++ b/dev-requirements.txt @@ -1,3 +1,4 @@ +lightpath packaging pytest pytest-timeout diff --git a/docs-requirements.txt b/docs-requirements.txt index 0647bc4b..5b33be5f 100644 --- a/docs-requirements.txt +++ b/docs-requirements.txt @@ -2,3 +2,4 @@ nbsphinx sphinx sphinx_rtd_theme sphinxcontrib-jquery +pypandoc From 6a709a606460e2d43971e398895fb1af8463cafe Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Wed, 22 Feb 2023 13:39:22 -0800 Subject: [PATCH 25/28] MNT: revert path removal from coveragerc --- .coveragerc | 1 + 1 file changed, 1 insertion(+) diff --git a/.coveragerc b/.coveragerc index f435959c..e9ce6d19 100644 --- a/.coveragerc +++ b/.coveragerc @@ -9,3 +9,4 @@ omit = #tests *test* hutch_python/tests/* + hutch_python/cookiecutter/* From 80232515d80350b73ab231cc3b8e1a7d4ac8525f Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Thu, 23 Feb 2023 09:13:30 -0800 Subject: [PATCH 26/28] CLN: remove top-level Makefile --- Makefile | 39 --------------------------------------- 1 file changed, 39 deletions(-) delete mode 100644 Makefile diff --git a/Makefile b/Makefile deleted file mode 100644 index 29b31eb2..00000000 --- a/Makefile +++ /dev/null @@ -1,39 +0,0 @@ -.PHONY: clean lint requirements versioneer - -################################################################################# -# GLOBALS # -################################################################################# - -PROJECT_DIR := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST)))) -PROJECT_NAME = hutch-python -PYTHON_INTERPRETER = python3 - -ifeq (,$(shell which conda)) -HAS_CONDA=False -else -HAS_CONDA=True -endif - -################################################################################# -# COMMANDS # -################################################################################# - -## Install Python Dependencies -requirements: test_environment - pip install -r requirements.txt - -## Delete all compiled Python files -clean: - find . -name "*.pyc" -exec rm {} \; - -## Lint using flake8 -lint: - flake8 --exclude=lib/,bin/,docs/conf.py . - -## Setup versioneer -versioneer: - versioneer install - -################################################################################# -# PROJECT RULES # -################################################################################# From 046cdd154c203a7b6482a30b7c8f5f8bc15d3e25 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Thu, 23 Feb 2023 09:13:46 -0800 Subject: [PATCH 27/28] CLN: remove top-level test script --- test-conda.sh | 2 -- 1 file changed, 2 deletions(-) delete mode 100755 test-conda.sh diff --git a/test-conda.sh b/test-conda.sh deleted file mode 100755 index 971d11cb..00000000 --- a/test-conda.sh +++ /dev/null @@ -1,2 +0,0 @@ -mkdir -p conda-bld-tst -conda build conda-recipe --output-folder conda-bld-tst From 4a8999f91f6fbe1ae571019f9a13fb77e1a47658 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Thu, 23 Feb 2023 09:14:08 -0800 Subject: [PATCH 28/28] BLD/FIX: update manifest for repo root files --- MANIFEST.in | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/MANIFEST.in b/MANIFEST.in index 92ab1d36..4b5af2f7 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,11 +1,16 @@ -include versioneer.py +include AUTHORS.rst +include CONTRIBUTING.rst +include LICENSE +include MANIFEST.in +include README.rst + +include dev-requirements.txt +include docs-requirements.txt +include requirements.txt + include hutch_python/_version.py include hutch_python/templates/* include hutch_python/logging.yml include hutch_python/cookiecutter/* include hutch_python/cookiecutter/*/* include hutch_python/cookiecutter/*/*/* - -include requirements.txt -include dev-requirements.txt -include LICENSE