Skip to content

Commit

Permalink
Initial release
Browse files Browse the repository at this point in the history
  • Loading branch information
DarkLight1337 committed Mar 28, 2024
0 parents commit 2adedd7
Show file tree
Hide file tree
Showing 9 changed files with 722 additions and 0 deletions.
29 changes: 29 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Enforce Unix line endings
* text=auto eol=lf

# Explicitly declare text files you want to always be normalized and converted
# to native line endings on checkout.
*.css text
*.js text
*.html text
*.py text
*.c text
*.h text
*.cpp text
*.hpp text
*.cu text
*.sh text

# Denote all files that are truly binary and should not be modified.
*.bin binary
*.npy binary
*.npz binary
*.pkl binary
*.pth binary
*.cu.o binary
*.so binary
*.png binary
*.jpg binary
*.zip binary
*.7z binary
*.gz binary
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__pycache__/
19 changes: 19 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2024 Cyrus Leung

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
55 changes: 55 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Python Compatibility Matrix

`pycm` is a command-line tool for checking which versions of Python are supported by a given package.

## Installation

### Requirements

- [Python](https://www.python.org/) 3.8+

### Procedure

1. Run `python -m pip install git+https://github.com/DarkLight1337/pycm.git` to install the package from this repository.

## Usage

### Syntax

```
pycm <package> --python=<versions>
```

### Example

Show the versions of [TensorFlow](https://tensorflow.org/) that can be used with Python 3.8-3.11:

```
> pycm tensorflow --python=3.8,3.9,3.10,3.11
tensorflow (→) 2.2.3 2.3.4 2.4.4 2.5.3 2.6.5 2.7.4 2.8.4 2.9.3 2.10.1 2.11.1 2.12.1 2.13.1 2.14.1 2.15.1 2.16.1
Python (↓)
3.8 Y Y Y Y Y Y Y Y Y Y Y Y
3.9 Y Y Y Y Y Y Y Y Y Y Y Y
3.10 Y Y Y Y Y Y Y Y Y
3.11 Y Y Y Y Y
```

(You can cross-check this table against [the official compatibility matrix](https://www.tensorflow.org/install/source#tested_build_configurations).)

## Development

### Requirements

- [Python](https://www.python.org/) 3.8+
- [Poetry](https://python-poetry.org/) 1.4+

### Setup

1. Clone this repository to your machine.
2. Run `poetry lock --no-update && poetry install --with dev` to setup the Python enviroment.

### Lint

1. [Setup](#setup) the development environment.
2. Run `poetry run deptry . && poetry run ruff check . && poetry run pyright .` to lint the code.

351 changes: 351 additions & 0 deletions poetry.lock

Large diffs are not rendered by default.

78 changes: 78 additions & 0 deletions pycm/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
from __future__ import annotations

from collections import defaultdict
from collections.abc import Collection
from itertools import groupby
import json
import re
from urllib.request import urlopen

import click
import pandas as pd
from pkg_resources import Requirement, parse_version

__all__ = ['cli']

# Dummy requirement that cannot be satisfied
BAD_REQUIREMENT = Requirement.parse('python<0,>0')

def _get_requires_python_constraint(dist_data: dict[str, str]) -> Requirement | None:
requires_python_data: str | None = dist_data.get('requires_python')
if requires_python_data is None:
return None

return Requirement.parse(f'python{requires_python_data}')

def _get_python_requirements(dist_data: dict[str, str]) -> Collection[Requirement]:
requires_python_constraint = _get_requires_python_constraint(dist_data)

python_version_data: str | None = dist_data.get('python_version')
if python_version_data is None or python_version_data == 'source':
return [] if requires_python_constraint is None else [requires_python_constraint]

m = re.match(r'[a-z]{2}([0-9])([0-9]*)', python_version_data)
if m is None:
return [BAD_REQUIREMENT] if requires_python_constraint is None else [requires_python_constraint]

major, minor = m.groups()
if minor:
bdist_constraint = Requirement.parse(f'python=={major}.{minor}.*')
else:
bdist_constraint = Requirement.parse(f'python=={major}.*')

if requires_python_constraint is None:
return [bdist_constraint]
else:
return [requires_python_constraint, bdist_constraint]

@click.command()
@click.argument('package_name', type=str)
@click.option('--python', 'python_versions', metavar='<VERSIONS>', type=str, required=True, help='A comma-separated list of Python versions to check against')
def cli(package_name: str, python_versions: str) -> None:
"""Show the versions of a PyPI package that are compatible with each Python version."""
python_versions_lst = python_versions.split(',')
output = defaultdict(lambda: defaultdict(lambda: ''))

data = json.load(urlopen(f'https://pypi.org/pypi/{package_name}/json'))
for package_version, release_data in data['releases'].items():
for dist_data in release_data:
python_requirements = _get_python_requirements(dist_data)

for python_version in python_versions_lst:
if all(python_version in r for r in python_requirements):
output[python_version][package_version] = 'Y'

output_df = pd.DataFrame.from_dict(data=output, orient='index').fillna('')

# We only care about the latest patch version for each minor version
output_columns = tuple(str(c) for c in output_df.columns)
latest_patches = [
max(columns, key=parse_version)
for _, columns in groupby(output_columns, key=lambda s: parse_version(s).release[:2])
]

formatted_output_df = output_df \
.loc[sorted(output_df.index, key=parse_version), sorted(latest_patches, key=parse_version)] \
.rename_axis(index='Python (↓)', columns=f'{package_name} (→)')

click.echo(formatted_output_df)
3 changes: 3 additions & 0 deletions pycm/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from . import cli

cli()
Empty file added pycm/py.typed
Empty file.
186 changes: 186 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

[tool.poetry]
name = "pycm"
version = "1.0.0"
description = "Command-line tool for checking Python compatibility"
license = "MIT"
authors = [
"Cyrus Leung <[email protected]>",
]
homepage = "https://github.com/DarkLight1337/pycm"
repository = "https://github.com/DarkLight1337/pycm"
keywords = [
"cli", "dependencies"
]
classifiers = [
"License :: OSI Approved :: MIT License",
"Software Development :: Libraries :: Python Modules",
]

[tool.poetry.scripts]
pycm = "pycm:cli"

[tool.poetry.dependencies]
python = "^3.8"

click = ">=8.1"
pandas = ">=2.0"

[tool.poetry.group.dev]
optional = true

[tool.poetry.group.dev.dependencies]
deptry = ">=0.14"
ruff = ">=0.3"
pyright = ">=1.1.354"

[tool.deptry]
extend_exclude = ["__pycache__"]

[tool.deptry.per_rule_ignores]
DEP001 = ["_typeshed", "pkg_resources"]

[tool.ruff]
line-length = 100
target-version = "py38"

[tool.ruff.lint]
select = [
# Pyflakes
"F",
# pycodestyle
"E", "W",
# flake8-boolean-trap
"FBT",
# flake8-bugbear
"B",
# flake8-builtins
"A",
# flake8-commas
"COM",
# flake8-comprehensions
"C4",
# flake8-datetimez
"DTZ",
# flake8-debugger
"T10",
# flake8-errmsg
"EM",
# flake8-future-annotations
"FA",
# flake8-implicit-str-concat
"ISC",
# flake8-import-conventions
"ICN",
# flake8-logging
"LOG",
# flake8-logging-format
"G",
# flake8-no-pep420
"INP",
# flake8-pie
"PIE",
# flake8-print
"T20",
# flake8-raise
"RSE",
# flake8-simplify
"SIM",
# flake8-use-pathlib
"PTH",
# NumPy-specific rules
"NPY",
# Pandas-specific rules
"PD",
# Ruff-specific rules
"RUF",
# isort
"I",
# pydocstyle
"D",
# pyupgrade
"UP",
]
ignore = [
"F403", "F405",
"E501",
"SIM102", "SIM117", "SIM118",
"PIE790",
"D1", "D205", "D401",
]

[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["F401"]

[tool.ruff.lint.flake8-builtins]
builtins-ignorelist = ["copyright", "hash", "id", "type"]

[tool.ruff.lint.flake8-comprehensions]
allow-dict-calls-with-keyword-arguments = true

[tool.ruff.lint.isort]
classes = [
# Standard library
"ABC", "IO",
]
extra-standard-library = ["typing_extensions"]

section-order = ["future", "standard-library", "third-party", "first-party", "local-folder"]
combine-as-imports = true
force-sort-within-sections = true

[tool.ruff.lint.pydocstyle]
convention = "numpy"

[tool.ruff.lint.pyupgrade]
keep-runtime-typing = true

[tool.pyright]
# These are set to "error" in "strict" mode
reportConstantRedefinition = "warning"
reportDeprecated = "warning"
reportDuplicateImport = "warning"
reportFunctionMemberAccess = "warning"
reportIncompatibleMethodOverride = "warning"
reportIncompatibleVariableOverride = "warning"
reportIncompleteStub = "warning"
reportInconsistentConstructor = "warning"
reportInvalidStubStatement = "warning"
reportMatchNotExhaustive = "warning"
reportMissingParameterType = "warning"
reportMissingTypeArgument = "warning"
reportOverlappingOverload = "warning"
reportPrivateUsage = "warning"
reportTypeCommentUsage = "warning"
# reportUnknownArgumentType = "warning"
# reportUnknownLambdaType = "warning"
# reportUnknownMemberType = "warning"
# reportUnknownParameterType = "warning"
# reportUnknownVariableType = "warning"
reportUnnecessaryCast = "warning"
reportUnnecessaryComparison = "warning"
reportUnnecessaryContains = "warning"
reportUnnecessaryIsInstance = "warning"
# reportUnusedClass = "warning"
reportUnusedImport = "warning"
# reportUnusedFunction = "warning"
reportUnusedVariable = "warning"
reportUntypedBaseClass = "warning"
reportUntypedClassDecorator = "warning"
reportUntypedFunctionDecorator = "warning"
reportUntypedNamedTuple = "warning"

# These are set to "none" even in "strict" mode
reportCallInDefaultInitializer = "warning"
# reportImplicitOverride = "warning"
reportImplicitStringConcatenation = "warning"
# reportImportCycles = "warning"
reportMissingSuperCall = "warning"
reportPropertyTypeMismatch = "warning"
reportShadowedImports = "warning"
reportUninitializedInstanceVariable = "warning"
reportUnnecessaryTypeIgnoreComment = "information"
# reportUnusedCallResult = "warning"

0 comments on commit 2adedd7

Please sign in to comment.