diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..68bc17f --- /dev/null +++ b/.gitignore @@ -0,0 +1,160 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..c55305a --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2023-present Marcelo Trylesinski + +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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..6f7f476 --- /dev/null +++ b/README.md @@ -0,0 +1,29 @@ +# bump-pydantic + +[![PyPI - Version](https://img.shields.io/pypi/v/bump-pydantic.svg)](https://pypi.org/project/bump-pydantic) +[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/bump-pydantic.svg)](https://pypi.org/project/bump-pydantic) + +----- + +**Table of Contents** + +- [bump-pydantic](#bump-pydantic) + - [Installation](#installation) + - [Checklist](#checklist) + - [License](#license) + +## Installation + +```console +pip install bump-pydantic +``` + +## Checklist + +- [X] `Config` class to `model_config` attribute on `BaseModel`. +- [ ] Removed Constrained" - raise warning. +- [X] Replace imports that changed location. + +## License + +`bump-pydantic` is distributed under the terms of the [MIT](https://spdx.org/licenses/MIT.html) license. diff --git a/bump_pydantic/__about__.py b/bump_pydantic/__about__.py new file mode 100644 index 0000000..22ca937 --- /dev/null +++ b/bump_pydantic/__about__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: 2023-present Marcelo Trylesinski +# +# SPDX-License-Identifier: MIT +__version__ = "0.0.1" diff --git a/bump_pydantic/__init__.py b/bump_pydantic/__init__.py new file mode 100644 index 0000000..c6fc431 --- /dev/null +++ b/bump_pydantic/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2023-present Marcelo Trylesinski +# +# SPDX-License-Identifier: MIT diff --git a/bump_pydantic/command.py b/bump_pydantic/command.py new file mode 100644 index 0000000..d612931 --- /dev/null +++ b/bump_pydantic/command.py @@ -0,0 +1,150 @@ +import libcst as cst +from libcst import matchers as m +from libcst.codemod import CodemodContext, VisitorBasedCodemodCommand +from libcst.codemod.visitors import AddImportsVisitor + + +class BumpPydanticCodemodCommand(VisitorBasedCodemodCommand): + DESCRIPTION = "Bump pydantic from 1.x to 2.x." + + def __init__(self, context: CodemodContext) -> None: + super().__init__(context) + self.config_args = [] + + @m.visit(m.ClassDef(name=m.Name(value="Config"))) + def visit_config_class(self, node: cst.ClassDef) -> None: + """Collect the arguments from the `Config` class.""" + for statement in node.body.body: + if m.matches(statement, m.SimpleStatementLine()): + statement = cst.ensure_type(statement, cst.SimpleStatementLine) + for child in statement.body: + if m.matches(child, m.Assign()): + assignment = cst.ensure_type(child, cst.Assign) + assign_target = cst.ensure_type( + assignment.targets[0], cst.AssignTarget + ) + keyword = cst.ensure_type(assign_target.target, cst.Name) + keyword = keyword.with_changes( + value=replace_config_attribute(keyword.value) + ) + arg = cst.Arg( + value=assignment.value, + keyword=keyword, + equal=cst.AssignEqual( + whitespace_before=cst.SimpleWhitespace(""), + whitespace_after=cst.SimpleWhitespace(""), + ), + ) + self.config_args.append(arg) + + @m.leave( + m.ClassDef( + bases=[ + m.ZeroOrMore(), + m.Arg(), + m.ZeroOrMore(), + ], + body=m.IndentedBlock( + body=[ + m.ZeroOrMore(), + m.ClassDef(name=m.Name(value="Config")), + m.ZeroOrMore(), + ] + ), + ) + ) + def leave_config_class( + self, original_node: cst.ClassDef, updated_node: cst.ClassDef + ) -> cst.ClassDef: + """Replace the `Config` class with a `model_config` attribute. + + Any class that contains a `Config` class will have that class replaced + with a `model_config` attribute. The `model_config` attribute will be + assigned a `ConfigDict` object with the same arguments as the attributes + from `Config` class. + """ + AddImportsVisitor.add_needed_import( + context=self.context, module="pydantic", obj="ConfigDict" + ) + block = cst.ensure_type(original_node.body, cst.IndentedBlock) + body = [ + statement + if not m.matches(statement, m.ClassDef(name=m.Name(value="Config"))) + else cst.SimpleStatementLine( + body=[ + cst.Assign( + targets=[cst.AssignTarget(target=cst.Name("model_config"))], + value=cst.Call( + func=cst.Name("ConfigDict"), + args=self.config_args, + ), + ) + ], + ) + for statement in block.body + ] + self.config_args = [] + return updated_node.with_changes(body=updated_node.body.with_changes(body=body)) + + @m.leave( + m.ImportFrom( + module=m.Attribute( + value=m.Name(value="pydantic"), + attr=m.Name(value=m.MatchIfTrue(lambda value: value in MODULE_CHANGES)), + ), + ) + ) + def replace_full_imports( + self, _: cst.ImportFrom, updated_node: cst.ImportFrom + ) -> cst.ImportFrom: + module = cst.ensure_type(updated_node.module, cst.Attribute) + return updated_node.with_changes( + module=module.with_changes( + value=cst.Attribute( + value=cst.Name("pydantic"), attr=cst.Name("deprecated") + ), + attr=cst.Name(value=module.attr.value), + ) + ) + + @m.leave( + m.ImportFrom( + module=m.Name("pydantic"), + names=[ + m.ImportAlias( + name=m.Name( + value=m.MatchIfTrue(lambda value: value in MODULE_CHANGES) + ) + ) + ], + ) + ) + def replace_partial_imports( + self, _: cst.ImportFrom, updated_node: cst.ImportFrom + ) -> cst.ImportFrom: + return updated_node.with_changes( + module=cst.Attribute( + value=cst.Name("pydantic"), attr=cst.Name("deprecated") + ) + ) + + +CONFIG_ATTRS_REPLACEMENT = { + "allow_population_by_field_name": "populate_by_name", + "anystr_lower": "str_to_lower", + "anystr_strip_whitespace": "str_strip_whitespace", + "anystr_upper": "str_to_upper", + "keep_untouched": "ignored_types", + "max_anystr_length": "str_max_length", + "min_anystr_length": "str_min_length", + "orm_mode": "from_attributes", + "validate_all": "validate_default", +} + + +def replace_config_attribute(old_name: str) -> str: + return CONFIG_ATTRS_REPLACEMENT.get(old_name, old_name) + + +MODULE_CHANGES = {"tools", "json", "parse", "decorator"} +MODULE_CHANGES = {"tools", "json", "parse", "decorator"} diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..af947e3 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,131 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "bump-pydantic" +dynamic = ["version"] +description = '' +readme = "README.md" +requires-python = ">=3.7" +license = "MIT" +keywords = [] +authors = [{ name = "Marcelo Trylesinski", email = "marcelotryle@gmail.com" }] +classifiers = [ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", +] +dependencies = ["libcst>=0.4.9"] + +[project.urls] +Documentation = "https://github.com/unknown/bump-pydantic#readme" +Issues = "https://github.com/unknown/bump-pydantic/issues" +Source = "https://github.com/unknown/bump-pydantic" + +[tool.hatch.version] +path = "bump_pydantic/__about__.py" + +[tool.hatch.envs.default] +dependencies = ["coverage[toml]>=6.5", "pytest"] +[tool.hatch.envs.default.scripts] +test = "pytest {args:tests}" +test-cov = "coverage run -m pytest {args:tests}" +cov-report = ["- coverage combine", "coverage report"] +cov = ["test-cov", "cov-report"] + +[[tool.hatch.envs.all.matrix]] +python = ["3.7", "3.8", "3.9", "3.10", "3.11"] + +[tool.hatch.envs.lint] +detached = true +dependencies = ["black>=23.1.0", "mypy>=1.0.0", "ruff>=0.0.243"] +[tool.hatch.envs.lint.scripts] +typing = "mypy --install-types --non-interactive {args:bump_pydantic tests}" +style = ["ruff {args:.}", "black --check --diff {args:.}"] +fmt = ["black {args:.}", "ruff --fix {args:.}", "style"] +all = ["style", "typing"] + +[tool.black] +target-version = ["py37"] +skip-string-normalization = true + +[tool.ruff] +target-version = "py37" +line-length = 88 +select = [ + "A", + "ARG", + "B", + "C", + "DTZ", + "E", + "EM", + "F", + "FBT", + "I", + "ICN", + "ISC", + "N", + "PLC", + "PLE", + "PLR", + "PLW", + "Q", + "RUF", + "S", + "T", + "TID", + "UP", + "W", + "YTT", +] +ignore = [ + # Allow non-abstract empty methods in abstract base classes + "B027", + # Allow boolean positional values in function calls, like `dict.get(... True)` + "FBT003", + # Ignore checks for possible passwords + "S105", + "S106", + "S107", + # Ignore complexity + "C901", + "PLR0911", + "PLR0912", + "PLR0913", + "PLR0915", +] +unfixable = [ + # Don't touch unused imports + "F401", +] + +[tool.ruff.isort] +known-first-party = ["bump_pydantic"] + +[tool.ruff.flake8-tidy-imports] +ban-relative-imports = "all" + +[tool.ruff.per-file-ignores] +# Tests can use magic values, assertions, and relative imports +"tests/**/*" = ["PLR2004", "S101", "TID252"] + +[tool.coverage.run] +source_pkgs = ["bump_pydantic", "tests"] +branch = true +parallel = true +omit = ["bump_pydantic/__about__.py"] + +[tool.coverage.paths] +bump_pydantic = ["bump_pydantic", "*/bump-pydantic/bump_pydantic"] +tests = ["tests", "*/bump-pydantic/tests"] + +[tool.coverage.report] +exclude_lines = ["no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:"] diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..c6fc431 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2023-present Marcelo Trylesinski +# +# SPDX-License-Identifier: MIT diff --git a/tests/test_codemod.py b/tests/test_codemod.py new file mode 100644 index 0000000..5f061cd --- /dev/null +++ b/tests/test_codemod.py @@ -0,0 +1,165 @@ +from __future__ import annotations + +import pytest +from libcst.codemod import CodemodTest + +from bump_pydantic.command import BumpPydanticCodemodCommand + + +class TestAutotype(CodemodTest): + TRANSFORM = BumpPydanticCodemodCommand + + def test_config_class_noop(self) -> None: + before = """ + class Model: + a: int + b: int + + class Config: + arbitrary_types_allowed = True + """ + self.assertCodemod(before, before) + + def test_config_class(self) -> None: + before = """ + from pydantic import BaseModel + + class Model(BaseModel): + a: int + b: int + + class Config: + arbitrary_types_allowed = True + """ + after = """ + from pydantic import ConfigDict, BaseModel + + class Model(BaseModel): + a: int + b: int + model_config = ConfigDict(arbitrary_types_allowed=True) + """ + self.assertCodemod(before, after) + + def test_config_class_at_beginning(self) -> None: + before = """ + from pydantic import BaseModel + + class Model(BaseModel): + class Config: + arbitrary_types_allowed = True + + a: int + b: int + """ + after = """ + from pydantic import ConfigDict, BaseModel + + class Model(BaseModel): + model_config = ConfigDict(arbitrary_types_allowed=True) + + a: int + b: int + """ + self.assertCodemod(before, after) + + def test_config_class_with_base_model_as_alias(self) -> None: + before = """ + from pydantic import BaseModel as BM + + class Model(BM): + a: int + b: int + + class Config: + arbitrary_types_allowed = True + """ + after = """ + from pydantic import ConfigDict, BaseModel as BM + + class Model(BM): + a: int + b: int + model_config = ConfigDict(arbitrary_types_allowed=True) + """ + self.assertCodemod(before, after) + + def test_config_class_with_pydantic_dot_base_model(self) -> None: + before = """ + import pydantic + + class Model(pydantic.BaseModel): + a: int + b: int + + class Config: + arbitrary_types_allowed = True + """ + after = """ + import pydantic + from pydantic import ConfigDict + + class Model(pydantic.BaseModel): + a: int + b: int + model_config = ConfigDict(arbitrary_types_allowed=True) + """ + self.assertCodemod(before, after) + + def test_config_new_attributes(self) -> None: + before = """ + from pydantic import BaseModel + + class Model(BaseModel): + a: int + b: int + + class Config: + allow_population_by_field_name = True + anystr_lower = True + anystr_strip_whitespace = True + anystr_upper = True + keep_untouched = (int,) + max_anystr_length = 10 + min_anystr_length = 1 + orm_mode = True + validate_all = True + """ + after = """ + from pydantic import ConfigDict, BaseModel + + class Model(BaseModel): + a: int + b: int + model_config = ConfigDict(populate_by_name=True, str_to_lower=True, str_strip_whitespace=True, str_to_upper=True, ignored_types=(int,), str_max_length=10, str_min_length=1, from_attributes=True, validate_default=True) + """ + self.assertCodemod(before, after) + + IMPORTS = [ + *[ + ( + f"from pydantic.{module} import {func}", + f"from pydantic.deprecated.{module} import {func}", + ) + for module, func in [ + ("tools", "schema_of"), + ("tools", "schema_json_of"), + ("tools", "parse_obj_as"), + ("json", "pydantic_encoder"), + ("json", "custom_pydantic_decoder"), + ("json", "timedelta_isoformat"), + ("decorator", "validate_arguments"), + ("parse", "load_str_bytes"), + ("parse", "load_file"), + ] + ], + ("from pydantic import tools", "from pydantic.deprecated import tools"), + ("from pydantic import json", "from pydantic.deprecated import json"), + ("from pydantic import parse", "from pydantic.deprecated import parse"), + ("from pydantic import decorator", "from pydantic.deprecated import decorator"), + ("from pydantic.tools import *", "from pydantic.deprecated.tools import *"), + ] + + def test_import_changed(self) -> None: + for before, after in self.IMPORTS: + self.assertCodemod(before, after)