Skip to content

Commit

Permalink
Modernize (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
flying-sheep authored Oct 5, 2023
1 parent acf1b21 commit c654cec
Show file tree
Hide file tree
Showing 13 changed files with 188 additions and 155 deletions.
56 changes: 56 additions & 0 deletions .github/workflows/run_tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
name: Unit Tests

on:
push:
branches:
- main
pull_request:
branches:
- "*"

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

defaults:
run:
shell: bash -e {0} # -e to fail on error

jobs:
run_tester:
runs-on: ${{ matrix.config.os }}

strategy:
fail-fast: false
matrix:
config:
- { name: "3.9", os: ubuntu-latest, python: "3.9" }
- { name: "3.10", os: ubuntu-latest, python: "3.10" }
- { name: "3.11", os: ubuntu-latest, python: "3.11" }
- { name: "3.12", os: ubuntu-latest, python: "3.12" }

steps:
- name: Clone repo
uses: actions/checkout@v4
with:
fetch-depth: 0
filter: blob:none

- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.config.python }}
cache: pip

- name: Install Python tools
run: |
python -m pip install --upgrade pip wheel
- name: Install Python package and dependencies
run: pip install .[test] coverage coveralls

- name: Run tests
run: coverage run --source=get_version -m pytest --verbose --color=yes

- name: Coveralls
uses: coverallsapp/github-action@v2
3 changes: 1 addition & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# Caches
__pycache__/
/.pytest_cache/
/.mypy_cache/
/.*cache/
/.coverage

# Packaging
Expand Down
33 changes: 29 additions & 4 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,30 @@
# To install the git pre-commit hooks run:
# pre-commit install --install-hooks
# To update the versions:
# pre-commit autoupdate
# Note the order is intentional to avoid multiple passes of the hooks
repos:
- repo: https://github.com/psf/black
rev: 23.7.0
hooks:
- id: black
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.292
hooks:
- id: ruff
args: [--fix, --exit-non-zero-on-fix, --show-fixes]
- repo: https://github.com/psf/black
rev: 23.9.1
hooks:
- id: black
- repo: https://github.com/pre-commit/mirrors-prettier
rev: v3.0.3
hooks:
- id: prettier
exclude: front/package-lock\.json
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: debug-statements
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.5.1
hooks:
- id: mypy
7 changes: 7 additions & 0 deletions .prettierrc.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
overrides:
# JSON with comments and trailing commas
- files: .vscode/*.json
options:
parser: json5
quoteProps: preserve
singleQuote: false
17 changes: 0 additions & 17 deletions .travis.yml

This file was deleted.

18 changes: 18 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"[python][json][jsonc][yaml]": {
"editor.formatOnSave": true,
},
"[json][jsonc][yaml]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
},
"[python]": {
"editor.defaultFormatter": "ms-python.black-formatter",
"editor.codeActionsOnSave": {
"source.fixAll": true,
"source.organizeImports": true,
},
},
"python.testing.pytestArgs": [],
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true,
}
8 changes: 4 additions & 4 deletions README.rst
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
get_version |b-pypi| |b-conda| |b-travis| |b-cover| |b-black|
=============================================================
get_version |b-pypi| |b-conda| |b-ci| |b-cover| |b-black|
=========================================================
Automatically use the latest “vX.X.X” Git tag as version in your Python package.

It also supports getting the version from Python source distributions (``sdist``) or,
Expand All @@ -19,8 +19,8 @@ contributing
------------
Use |black|_ to ensure proper code style. In order to not forget you can use |pre-commit|_.

.. |b-travis| image:: https://travis-ci.com/flying-sheep/get_version.svg?branch=master
:target: https://travis-ci.com/flying-sheep/get_version
.. |b-ci| image:: https://github.com/flying-sheep/get_version/actions/workflows/run_tests.yml/badge.svg
:target: https://github.com/flying-sheep/get_version/actions/workflows/run_tests.yml
.. |b-cover| image:: https://coveralls.io/repos/github/flying-sheep/get_version/badge.svg
:target: https://coveralls.io/github/flying-sheep/get_version
.. |b-pypi| image:: https://img.shields.io/pypi/v/get_version.svg
Expand Down
35 changes: 17 additions & 18 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,27 +1,22 @@
[build-system]
requires = ['flit-core>=2,<4', 'dunamai']
build-backend = 'flit_core.buildapi'

[tool.flit.metadata]
module = 'get_version'
author = 'Philipp Angerer'
author-email = '[email protected]'
home-page = 'https://github.com/flying-sheep/get_version'
[project]
name = 'get_version'
authors = [{ name = 'Philipp Angerer', email = '[email protected]' }]
urls.Homepage = 'https://github.com/flying-sheep/get_version'
classifiers = [
'Intended Audience :: Developers',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
]
requires-python = '>=3.7'
requires = [
'dunamai', # Version parsing
'importlib_metadata; python_version < "3.8"',
'typing_extensions; python_version < "3.8"',
readme = 'README.rst'
license = { file = 'LICENSE' } # 'GPL-3.0-or-later'
requires-python = '>=3.9'
dependencies = [
'dunamai>=1.19.0', # Version parsing
]
description-file = 'README.rst'
dynamic = ['version', 'description']

[tool.flit.metadata.requires-extra]
[project.optional-dependencies]
test = [
'pytest>=6.2.5',
'pytest-black',
Expand All @@ -32,8 +27,12 @@ test = [
[tool.black]
include = '\.pyi?$'

[tool.ruff]
select = ['E', 'F', 'W', 'I', 'UP', 'TCH']

[tool.pytest.ini_options]
addopts = '-p get_version.testing'

[tool.mypy]
mypy_path = './type-stubs'
[build-system]
requires = ['flit-core>=2,<4', 'dunamai']
build-backend = 'flit_core.buildapi'
65 changes: 19 additions & 46 deletions get_version/__init__.py → src/get_version/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,35 +7,20 @@

from __future__ import annotations

import re
import os
import typing as t
from contextlib import contextmanager
import re
from dataclasses import dataclass
from enum import Enum
from functools import partial
from importlib.metadata import Distribution, PackageNotFoundError, distribution
from pathlib import Path
from subprocess import run
from textwrap import indent
from typing import TYPE_CHECKING, Literal

try:
from typing import Literal
except ImportError:
if t.TYPE_CHECKING:
raise
else:
from typing_extensions import Literal

try:
from importlib.metadata import distribution, Distribution, PackageNotFoundError
except ImportError:
if t.TYPE_CHECKING:
raise
else:
from importlib_metadata import distribution, Distribution, PackageNotFoundError

if TYPE_CHECKING:
from collections.abc import Callable, Iterable

if t.TYPE_CHECKING:
from dunamai import Version


Expand Down Expand Up @@ -64,17 +49,6 @@
VCS = Literal["any", "git", "mercurial"] # "darcs", "subversion", "bazaar", "fossil"


@contextmanager
def working_dir(dir_: t.Optional[os.PathLike] = None):
curdir = os.getcwd()
try:
if dir_ is not None:
os.chdir(dir_)
yield
finally:
os.chdir(curdir)


class Source(Enum):
all: None = None
dirname = "Directory name"
Expand Down Expand Up @@ -142,15 +116,14 @@ def get_version_from_vcs(parent: Path, *, vcs: VCS = "any") -> str:
)


def find_vcs_root(start: Path, *, vcs: VCS = "any") -> t.Optional[Path]:
from dunamai import _detect_vcs, Vcs
def find_vcs_root(start: Path, *, vcs: VCS = "any") -> Path | None:
from dunamai import Vcs, _detect_vcs

if vcs == "any":
with working_dir(start):
try:
vcs_e = _detect_vcs()
except RuntimeError:
return None
try:
vcs_e = _detect_vcs(None, start)
except RuntimeError:
return None
else:
vcs_e = Vcs(vcs)

Expand All @@ -171,11 +144,10 @@ def find_vcs_root(start: Path, *, vcs: VCS = "any") -> t.Optional[Path]:
def dunamai_get_from_vcs(dir_: Path) -> Version:
from dunamai import Version

with working_dir(dir_):
return Version.from_any_vcs(f"(?x)v?{RE_PEP440_VERSION.pattern}")
return Version.from_any_vcs(f"(?x)v?{RE_PEP440_VERSION.pattern}", path=dir_)


def get_version_from_metadata(name: str, parent: t.Optional[Path] = None) -> str:
def get_version_from_metadata(name: str, parent: Path | None = None) -> str:
try:
pkg = distribution(name)
except PackageNotFoundError:
Expand All @@ -194,7 +166,7 @@ def get_version_from_metadata(name: str, parent: t.Optional[Path] = None) -> str
return pkg.version


def get_pkg_paths(pkg: Distribution) -> t.List[Path]:
def get_pkg_paths(pkg: Distribution) -> list[Path]:
# Some egg-info packages have e.g. src/ paths in their SOURCES.txt file,
# but they also have this:
mods = set((pkg.read_text("top_level.txt") or "").split())
Expand All @@ -213,9 +185,9 @@ def get_pkg_paths(pkg: Distribution) -> t.List[Path]:


def get_version(
package: t.Union[Path, str],
package: Path | str,
*,
dist_name: t.Optional[str] = None,
dist_name: str | None = None,
vcs: VCS = "any",
) -> str:
"""Get the version of a package or module
Expand All @@ -231,7 +203,8 @@ def get_version(
(This is the only possibility when passing a name)
Args:
package: package name or module path (``…/module.py`` or ``…/module/__init__.py``)
package: package name or module path
(``…/module.py`` or ``…/module/__init__.py``)
dist_name: If the distribution name isn’t the same as the module name,
you can specify it, e.g. in ``PIL/__init__.py``,
there would be ``get_version(__file__, 'Pillow')``
Expand Down Expand Up @@ -262,7 +235,7 @@ def get_version(
if parent.name == "src":
parent = parent.parent

methods: t.Iterable[t.Callable[[Path], str]] = (
methods: Iterable[Callable[[Path], str]] = (
get_version_from_dirname,
partial(get_version_from_vcs, vcs=vcs),
partial(get_version_from_metadata, dist_name),
Expand Down
File renamed without changes.
Loading

0 comments on commit c654cec

Please sign in to comment.