django-api-versioning 0.3.7__tar.gz → 0.3.8__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/CHANGELOG.md +14 -0
  2. django_api_versioning-0.3.8/MANIFEST.in +27 -0
  3. {django_api_versioning-0.3.7/django_api_versioning.egg-info → django_api_versioning-0.3.8}/PKG-INFO +24 -16
  4. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/README.md +21 -14
  5. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/django_api_versioning/channels.py +18 -21
  6. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/django_api_versioning/decorators.py +6 -0
  7. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/django_api_versioning/lifecycle.py +42 -26
  8. django_api_versioning-0.3.8/django_api_versioning/management/commands/migrate_endpoints.py +249 -0
  9. django_api_versioning-0.3.8/django_api_versioning/py.typed +1 -0
  10. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/django_api_versioning/registry.py +18 -17
  11. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/django_api_versioning/reverse.py +32 -3
  12. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/django_api_versioning/settings.py +26 -6
  13. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/django_api_versioning/testing.py +18 -2
  14. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8/django_api_versioning.egg-info}/PKG-INFO +24 -16
  15. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/django_api_versioning.egg-info/SOURCES.txt +2 -0
  16. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/django_api_versioning.egg-info/requires.txt +3 -0
  17. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/django_api_versioning.egg-info/top_level.txt +0 -2
  18. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/pyproject.toml +14 -4
  19. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/requirements-dev.txt +1 -1
  20. django_api_versioning-0.3.8/tests/test_channels_extra.py +69 -0
  21. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/tests/test_decorators.py +30 -0
  22. django_api_versioning-0.3.8/tests/test_distribution_contents.py +160 -0
  23. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/tests/test_lifecycle.py +65 -0
  24. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/tests/test_management_commands.py +269 -14
  25. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/tests/test_registry.py +5 -4
  26. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/tests/test_reverse.py +64 -2
  27. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/tests/test_settings.py +36 -0
  28. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/tests/test_testing_utils.py +26 -1
  29. django_api_versioning-0.3.7/MANIFEST.in +0 -9
  30. django_api_versioning-0.3.7/django_api_versioning/management/commands/migrate_endpoints.py +0 -78
  31. django_api_versioning-0.3.7/tests/test_channels_extra.py +0 -33
  32. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/LICENSE +0 -0
  33. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/django_api_versioning/__init__.py +0 -0
  34. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/django_api_versioning/exceptions.py +0 -0
  35. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/django_api_versioning/management/__init__.py +0 -0
  36. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/django_api_versioning/management/commands/__init__.py +0 -0
  37. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/django_api_versioning/management/commands/check_versions.py +0 -0
  38. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/django_api_versioning/urls.py +0 -0
  39. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/django_api_versioning.egg-info/dependency_links.txt +0 -0
  40. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/pytest.ini +0 -0
  41. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/requirements.txt +0 -0
  42. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/setup.cfg +0 -0
  43. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/tests/__init__.py +0 -0
  44. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/tests/conftest.py +0 -0
  45. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/tests/settings.py +0 -0
  46. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/tests/test_channels.py +0 -0
  47. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/tests/test_exceptions.py +0 -0
  48. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/tests/test_segment_model.py +0 -0
  49. {django_api_versioning-0.3.7 → django_api_versioning-0.3.8}/tests/test_urls.py +0 -0
@@ -8,6 +8,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [0.3.8] - 2026-11-16
12
+
13
+ ### Fixed
14
+
15
+ - Ignore invalid lifecycle sunset values instead of emitting invalid `Sunset` headers; normalize timezone-aware sunset timestamps to UTC before enforcement and formatting.
16
+ - Return a class-specific actionable error when a DRF ViewSet class is registered without its required action map.
17
+ - Validate `API_BASE_PATH` as exactly one plain `{version}` format field, and reject malformed templates, non-string `ROOT_URLCONF` values, and non-string versioning-channel entries with configuration errors.
18
+ - Avoid emitting no-op or unsafe `migrate_endpoints` rewrites when legacy flags are missing a literal value or use dynamic expressions; make the command preview-only by default and require `--write` before modifying source files.
19
+ - Make the standalone channel extraction helper fall back from an invalid path match to `request.version` and reject repeated `v` prefixes.
20
+
21
+ ### Verified
22
+
23
+ - All 15 Python/Django tox environments passed: 247 unit tests and 260 integration tests in each environment. The lint environment and tox/workflow matrix validator also passed.
24
+
11
25
  ## [0.3.7] - 2026-11-14
12
26
 
13
27
  ### Changed
@@ -0,0 +1,27 @@
1
+ include README.md
2
+ include LICENSE
3
+ include CHANGELOG.md
4
+ include requirements.txt
5
+ include requirements-dev.txt
6
+ include pytest.ini
7
+
8
+ recursive-include django_api_versioning *.py
9
+ recursive-include django_api_versioning py.typed
10
+ recursive-include tests *.py
11
+
12
+ # Repository-only assets: never ship the docs corpus, integration lab, or website.
13
+ prune docs
14
+ prune integration_test_project
15
+ prune website
16
+ prune .github
17
+ prune .claude
18
+
19
+ # Generated frontend and local tooling artifacts.
20
+ prune node_modules
21
+ prune dist
22
+ prune build
23
+ prune .astro
24
+ prune .netlify
25
+ global-exclude __pycache__/*
26
+ global-exclude *.py[cod]
27
+ global-exclude .DS_Store
@@ -1,9 +1,9 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: django-api-versioning
3
- Version: 0.3.7
3
+ Version: 0.3.8
4
4
  Summary: API versioning for Django and Django REST Framework (DRF), with decorator-based endpoint registration, automatic URL routing, version-specific views, and forward inheritance for backward-compatible API evolution.
5
5
  Author-email: Mojtaba Arvin <ArvinDevDay@gmail.com>
6
- License: MIT
6
+ License-Expression: MIT
7
7
  Project-URL: Source, https://github.com/mojtaba-arvin/django-api-versioning
8
8
  Project-URL: Issues, https://github.com/mojtaba-arvin/django-api-versioning/issues
9
9
  Project-URL: Documentation, https://github.com/mojtaba-arvin/django-api-versioning#readme
@@ -43,6 +43,7 @@ Requires-Dist: pre-commit>=4.6.2; extra == "dev"
43
43
  Requires-Dist: twine>=7.0.0; extra == "dev"
44
44
  Requires-Dist: build>=1.6.1; extra == "dev"
45
45
  Requires-Dist: djangorestframework>=3.18; extra == "dev"
46
+ Requires-Dist: tomli>=2.0.1; python_version < "3.11" and extra == "dev"
46
47
  Dynamic: license-file
47
48
 
48
49
  # Django API Versioning
@@ -214,7 +215,7 @@ API_MIN_VERSION = 1
214
215
  API_MAX_VERSION = 3
215
216
  ```
216
217
 
217
- `API_BASE_PATH` must contain the `{version}` placeholder.
218
+ `API_BASE_PATH` must contain exactly one plain `{version}` format field. Additional format fields, conversions, and format specifications are rejected.
218
219
 
219
220
  The default values for `API_MIN_VERSION` and `API_MAX_VERSION` are both `1`. Set `API_MAX_VERSION` to the highest route version your project intends to register.
220
221
 
@@ -783,7 +784,7 @@ This allows the middleware to identify versions from the package's static versio
783
784
 
784
785
  | Setting | Default | Description |
785
786
  | --- | --- | --- |
786
- | `API_BASE_PATH` | `"api/v{version}/"` | Base path template for versioned routes. Must contain `{version}`. |
787
+ | `API_BASE_PATH` | `"api/v{version}/"` | Base path template for versioned routes. Must contain exactly one plain `{version}` format field and no other format fields. |
787
788
  | `API_MIN_VERSION` | `1` | Lowest valid route version. |
788
789
  | `API_MAX_VERSION` | `1` | Highest valid route version. |
789
790
  | `API_VERSION_LIFECYCLE` | `{}` | Per-version lifecycle metadata. |
@@ -984,9 +985,9 @@ python manage.py migrate_endpoints --dry-run
984
985
  python manage.py migrate_endpoints
985
986
  ```
986
987
 
987
- The command scans Python files for `@endpoint` declarations containing legacy `forward` or `backward` arguments and suggests or applies textual replacements.
988
+ The command parses Python source into an AST and uses tokenizer-aware checks to identify supported `@endpoint` declarations containing legacy `forward` or `backward` arguments. It rewrites only literal integer `version` values and literal boolean flags. Dynamic expressions, comments inside a decorator, unsupported forms, and files with syntax errors are left unchanged for manual migration.
988
989
 
989
- **Review the output before accepting it.** The command uses source-text matching and rewriting; it is not an AST-based semantic migration tool. It cannot guarantee that every rewritten declaration preserves the application's intended routing behavior.
990
+ **Review every proposed change before applying it.** This syntax-aware rewrite is not a proof of semantic equivalence: confirm the intended version coverage, inspect the generated route matrix with `check_versions`, and test request behavior for every affected API version.
990
991
 
991
992
  After migration:
992
993
 
@@ -1073,18 +1074,25 @@ docker run --rm dapi:py315
1073
1074
 
1074
1075
  ### Releasing
1075
1076
 
1076
- 1. Update the `version` in `pyproject.toml` and document the release in `CHANGELOG.md`.
1077
- 2. Commit and push the release commit to `main`.
1078
- 3. Create and push a matching version tag:
1077
+ Releases are maintainer operations. Prepare the version bump and changelog
1078
+ on a dedicated release branch, run the complete compatibility and artifact
1079
+ checks, and submit the changes through a reviewed pull request to the
1080
+ project's protected default branch. Do not push directly to `main`.
1079
1081
 
1080
- ```bash
1081
- git tag vX.Y.Z
1082
- git push origin vX.Y.Z
1083
- ```
1082
+ After the reviewed release commit is present on the default branch, create
1083
+ and push the matching version tag:
1084
1084
 
1085
- Pushing a `v*` tag triggers GitHub Actions to build the package, validate
1086
- the distribution with `twine check --strict`, and publish it to PyPI
1087
- using PyPI Trusted Publishing (GitHub Actions OIDC).
1085
+ ```bash
1086
+ git tag -a vX.Y.Z -m "Release vX.Y.Z"
1087
+ git push origin vX.Y.Z
1088
+ ```
1089
+
1090
+ Pushing a `v*` tag triggers GitHub Actions to run the compatibility matrix,
1091
+ build and validate the exact distribution with `twine check --strict`,
1092
+ smoke-test the wheel, and publish it to PyPI using Trusted Publishing
1093
+ (GitHub Actions OIDC). A successful tag push alone does not prove that
1094
+ publication completed; verify the workflow and the version-specific PyPI
1095
+ release page before announcing the release.
1088
1096
 
1089
1097
  ### Reporting issues
1090
1098
 
@@ -167,7 +167,7 @@ API_MIN_VERSION = 1
167
167
  API_MAX_VERSION = 3
168
168
  ```
169
169
 
170
- `API_BASE_PATH` must contain the `{version}` placeholder.
170
+ `API_BASE_PATH` must contain exactly one plain `{version}` format field. Additional format fields, conversions, and format specifications are rejected.
171
171
 
172
172
  The default values for `API_MIN_VERSION` and `API_MAX_VERSION` are both `1`. Set `API_MAX_VERSION` to the highest route version your project intends to register.
173
173
 
@@ -736,7 +736,7 @@ This allows the middleware to identify versions from the package's static versio
736
736
 
737
737
  | Setting | Default | Description |
738
738
  | --- | --- | --- |
739
- | `API_BASE_PATH` | `"api/v{version}/"` | Base path template for versioned routes. Must contain `{version}`. |
739
+ | `API_BASE_PATH` | `"api/v{version}/"` | Base path template for versioned routes. Must contain exactly one plain `{version}` format field and no other format fields. |
740
740
  | `API_MIN_VERSION` | `1` | Lowest valid route version. |
741
741
  | `API_MAX_VERSION` | `1` | Highest valid route version. |
742
742
  | `API_VERSION_LIFECYCLE` | `{}` | Per-version lifecycle metadata. |
@@ -937,9 +937,9 @@ python manage.py migrate_endpoints --dry-run
937
937
  python manage.py migrate_endpoints
938
938
  ```
939
939
 
940
- The command scans Python files for `@endpoint` declarations containing legacy `forward` or `backward` arguments and suggests or applies textual replacements.
940
+ The command parses Python source into an AST and uses tokenizer-aware checks to identify supported `@endpoint` declarations containing legacy `forward` or `backward` arguments. It rewrites only literal integer `version` values and literal boolean flags. Dynamic expressions, comments inside a decorator, unsupported forms, and files with syntax errors are left unchanged for manual migration.
941
941
 
942
- **Review the output before accepting it.** The command uses source-text matching and rewriting; it is not an AST-based semantic migration tool. It cannot guarantee that every rewritten declaration preserves the application's intended routing behavior.
942
+ **Review every proposed change before applying it.** This syntax-aware rewrite is not a proof of semantic equivalence: confirm the intended version coverage, inspect the generated route matrix with `check_versions`, and test request behavior for every affected API version.
943
943
 
944
944
  After migration:
945
945
 
@@ -1026,18 +1026,25 @@ docker run --rm dapi:py315
1026
1026
 
1027
1027
  ### Releasing
1028
1028
 
1029
- 1. Update the `version` in `pyproject.toml` and document the release in `CHANGELOG.md`.
1030
- 2. Commit and push the release commit to `main`.
1031
- 3. Create and push a matching version tag:
1029
+ Releases are maintainer operations. Prepare the version bump and changelog
1030
+ on a dedicated release branch, run the complete compatibility and artifact
1031
+ checks, and submit the changes through a reviewed pull request to the
1032
+ project's protected default branch. Do not push directly to `main`.
1032
1033
 
1033
- ```bash
1034
- git tag vX.Y.Z
1035
- git push origin vX.Y.Z
1036
- ```
1034
+ After the reviewed release commit is present on the default branch, create
1035
+ and push the matching version tag:
1037
1036
 
1038
- Pushing a `v*` tag triggers GitHub Actions to build the package, validate
1039
- the distribution with `twine check --strict`, and publish it to PyPI
1040
- using PyPI Trusted Publishing (GitHub Actions OIDC).
1037
+ ```bash
1038
+ git tag -a vX.Y.Z -m "Release vX.Y.Z"
1039
+ git push origin vX.Y.Z
1040
+ ```
1041
+
1042
+ Pushing a `v*` tag triggers GitHub Actions to run the compatibility matrix,
1043
+ build and validate the exact distribution with `twine check --strict`,
1044
+ smoke-test the wheel, and publish it to PyPI using Trusted Publishing
1045
+ (GitHub Actions OIDC). A successful tag push alone does not prove that
1046
+ publication completed; verify the workflow and the version-specific PyPI
1047
+ release page before announcing the release.
1041
1048
 
1042
1049
  ### Reporting issues
1043
1050
 
@@ -26,35 +26,32 @@ def extract_version(request: HttpRequest, channels: list[str]) -> int | None:
26
26
 
27
27
  def _from_path(request: HttpRequest) -> int | None:
28
28
  match = getattr(request, "resolver_match", None)
29
- if match and "version" in match.kwargs:
30
- try:
31
- return int(match.kwargs["version"])
32
- except (TypeError, ValueError):
33
- return None
34
- if hasattr(request, "version") and request.version is not None:
35
- try:
36
- return int(request.version)
37
- except (TypeError, ValueError):
38
- return None
39
- return None
29
+ kwargs = getattr(match, "kwargs", {}) if match else {}
30
+ if "version" in kwargs:
31
+ version = _parse_version(kwargs["version"])
32
+ if version is not None:
33
+ return version
34
+ return _parse_version(getattr(request, "version", None))
40
35
 
41
36
 
42
37
  def _from_header(request: HttpRequest) -> int | None:
43
- raw = request.headers.get("Accept-Version")
44
- if not raw:
45
- return None
46
- raw = raw.strip().lower().lstrip("v")
47
- try:
48
- return int(raw)
49
- except ValueError:
50
- return None
38
+ return _parse_version(request.headers.get("Accept-Version"))
51
39
 
52
40
 
53
41
  def _from_query(request: HttpRequest) -> int | None:
54
- raw = request.GET.get("version")
42
+ return _parse_version(request.GET.get("version"))
43
+
44
+
45
+ def _parse_version(value: object) -> int | None:
46
+ if value is None or isinstance(value, bool):
47
+ return None
48
+
49
+ raw = str(value).strip().lower()
50
+ if raw.startswith("v"):
51
+ raw = raw[1:]
55
52
  if not raw:
56
53
  return None
57
- raw = raw.strip().lower().lstrip("v")
54
+
58
55
  try:
59
56
  return int(raw)
60
57
  except ValueError:
@@ -3,6 +3,7 @@ from typing import Callable, TypeVar
3
3
 
4
4
  from .exceptions import (
5
5
  InvalidVersionError,
6
+ VersioningError,
6
7
  VersionRangeError,
7
8
  VersionTypeError,
8
9
  )
@@ -55,8 +56,13 @@ def endpoint(
55
56
  VersionRangeError: If both ``version`` and ``versions`` are given, or
56
57
  settings are invalid, or ``ver_range`` receives an invalid range.
57
58
  VersionTypeError: If a version is not an integer.
59
+ VersioningError: If the route postfix is absolute.
58
60
  InvalidVersionError: If a version exceeds ``API_MAX_VERSION``.
59
61
  """
62
+ if not isinstance(postfix, str):
63
+ raise TypeError("postfix must be a string.")
64
+ if postfix.startswith("/"):
65
+ raise VersioningError("postfix must be relative and must not start with '/'.")
60
66
  if version is not None and versions is not None:
61
67
  raise VersionRangeError("Use either 'version' or 'versions', not both.")
62
68
 
@@ -61,7 +61,8 @@ class LifecycleMiddleware:
61
61
  return self.get_response(request)
62
62
 
63
63
  sunset = meta.get("sunset")
64
- if sunset and _is_past(sunset):
64
+ sunset_date = _parse_sunset(sunset) if sunset else None
65
+ if sunset_date and _is_past(sunset_date):
65
66
  return HttpResponseGone(
66
67
  f"API version {version} has been retired as of {sunset}."
67
68
  )
@@ -69,30 +70,37 @@ class LifecycleMiddleware:
69
70
  response = self.get_response(request)
70
71
  if meta.get("status") == "deprecated":
71
72
  response["Deprecation"] = "true"
72
- if sunset:
73
- response["Sunset"] = _to_http_date(sunset)
73
+ if sunset_date:
74
+ response["Sunset"] = _to_http_date(sunset_date)
74
75
  return response
75
76
 
76
77
 
78
+ def _coerce_version(value: Any) -> int | None:
79
+ """Accept integer versions without truncating booleans or other numeric types."""
80
+ if isinstance(value, bool):
81
+ return None
82
+ if isinstance(value, int):
83
+ return value
84
+ if isinstance(value, str) and value.isdecimal():
85
+ return int(value)
86
+ return None
87
+
88
+
77
89
  def _extract_version(request: HttpRequest) -> int | None:
78
90
  # Path-based: request.version is set by DRF or by URLPathVersioning.
79
- if hasattr(request, "version") and request.version is not None:
80
- try:
81
- return int(request.version)
82
- except (TypeError, ValueError):
83
- pass
91
+ version = _coerce_version(getattr(request, "version", None))
92
+ if version is not None:
93
+ return version
94
+
84
95
  # Fallback: parse from resolver_match kwargs.
85
96
  match = getattr(request, "resolver_match", None)
86
- if match and "version" in match.kwargs:
87
- try:
88
- return int(match.kwargs["version"])
89
- except (TypeError, ValueError):
90
- pass
97
+ if match:
98
+ version = _coerce_version(match.kwargs.get("version"))
99
+ if version is not None:
100
+ return version
101
+
91
102
  # Fallback: extract from static URL path using API_BASE_PATH pattern.
92
- version = _extract_version_from_path(request)
93
- if version is not None:
94
- return version
95
- return None
103
+ return _extract_version_from_path(request)
96
104
 
97
105
 
98
106
  def _extract_version_from_path(request: HttpRequest) -> int | None:
@@ -137,18 +145,26 @@ def _extract_version_from_path(request: HttpRequest) -> int | None:
137
145
  return None
138
146
 
139
147
 
140
- def _is_past(date_str: str) -> bool:
148
+ def _parse_sunset(value: Any) -> datetime | None:
149
+ """Parse a configured sunset value and normalize it to UTC."""
150
+ if not isinstance(value, str):
151
+ logger.warning("Invalid sunset date %r; ignoring.", value)
152
+ return None
153
+
141
154
  try:
142
- date = datetime.fromisoformat(date_str).replace(tzinfo=timezone.utc)
155
+ parsed = datetime.fromisoformat(value)
143
156
  except ValueError:
144
- logger.warning("Invalid sunset date %r; ignoring.", date_str)
145
- return False
157
+ logger.warning("Invalid sunset date %r; ignoring.", value)
158
+ return None
159
+
160
+ if parsed.tzinfo is None:
161
+ return parsed.replace(tzinfo=timezone.utc)
162
+ return parsed.astimezone(timezone.utc)
163
+
164
+
165
+ def _is_past(date: datetime) -> bool:
146
166
  return date < datetime.now(timezone.utc)
147
167
 
148
168
 
149
- def _to_http_date(date_str: str) -> str:
150
- try:
151
- date = datetime.fromisoformat(date_str).replace(tzinfo=timezone.utc)
152
- except ValueError:
153
- return date_str
169
+ def _to_http_date(date: datetime) -> str:
154
170
  return date.strftime("%a, %d %b %Y %H:%M:%S GMT")
@@ -0,0 +1,249 @@
1
+ import ast
2
+ import io
3
+ import tokenize
4
+ from pathlib import Path
5
+
6
+ from django.core.management.base import BaseCommand, CommandError
7
+
8
+ _EXCLUDED_DIRS = {
9
+ ".git",
10
+ ".venv",
11
+ "venv",
12
+ "env",
13
+ "node_modules",
14
+ "site-packages",
15
+ "__pycache__",
16
+ "migrations",
17
+ "build",
18
+ "dist",
19
+ }
20
+ _LEGACY_FLAGS = {"backward", "forward", "version"}
21
+
22
+
23
+ class Command(BaseCommand):
24
+ help = (
25
+ "Preview 0.2.0 @endpoint flag migrations. "
26
+ "Pass --write to modify source files."
27
+ )
28
+
29
+ def add_arguments(self, parser):
30
+ mode = parser.add_mutually_exclusive_group()
31
+ mode.add_argument(
32
+ "--write",
33
+ action="store_true",
34
+ help="Apply the suggested changes to source files.",
35
+ )
36
+ mode.add_argument(
37
+ "--dry-run",
38
+ action="store_true",
39
+ help="Preview changes without modifying source files (the default).",
40
+ )
41
+ parser.add_argument("--path", default=".")
42
+
43
+ def handle(self, *args, **options):
44
+ root = Path(options["path"]).expanduser().resolve()
45
+ if not root.is_dir():
46
+ raise CommandError(f"Migration path is not a directory: {root}")
47
+
48
+ for py_file in root.rglob("*.py"):
49
+ relative_parts = py_file.relative_to(root).parts
50
+ if (
51
+ py_file.is_symlink()
52
+ or py_file.name.startswith(".")
53
+ or any(
54
+ part in _EXCLUDED_DIRS or part.startswith(".")
55
+ for part in relative_parts[:-1]
56
+ )
57
+ ):
58
+ continue
59
+
60
+ raw = py_file.read_bytes()
61
+ encoding, _ = tokenize.detect_encoding(io.BytesIO(raw).readline)
62
+ text = raw.decode(encoding)
63
+ rewrites = _collect_rewrites(text)
64
+ if not rewrites:
65
+ continue
66
+
67
+ self.stdout.write(f"\n{py_file}:")
68
+ for _, _, old, new in rewrites:
69
+ self.stdout.write(f" - @{old}")
70
+ self.stdout.write(f" + @{new}")
71
+
72
+ if options["write"]:
73
+ updated = _apply_rewrites(text, rewrites)
74
+ if updated != text:
75
+ py_file.write_bytes(updated.encode(encoding))
76
+
77
+
78
+ def _is_endpoint_call(func: ast.expr) -> bool:
79
+ return (isinstance(func, ast.Name) and func.id == "endpoint") or (
80
+ isinstance(func, ast.Attribute) and func.attr == "endpoint"
81
+ )
82
+
83
+
84
+ def _has_comments(source: str) -> bool:
85
+ try:
86
+ return any(
87
+ token.type == tokenize.COMMENT
88
+ for token in tokenize.generate_tokens(io.StringIO(source).readline)
89
+ )
90
+ except tokenize.TokenError:
91
+ return True
92
+
93
+
94
+ def _literal_integer(node: ast.expr | None) -> int | None:
95
+ if isinstance(node, ast.Constant) and type(node.value) is int:
96
+ return node.value
97
+ return None
98
+
99
+
100
+ def _literal_boolean(node: ast.expr | None, default: bool) -> bool | None:
101
+ if node is None:
102
+ return default
103
+ if not isinstance(node, ast.Constant) or type(node.value) is not bool:
104
+ return None
105
+ return node.value
106
+
107
+
108
+ def _literal_forward(node: ast.expr | None) -> bool | None:
109
+ if node is None:
110
+ return True
111
+ if not isinstance(node, ast.Constant):
112
+ return None
113
+ if type(node.value) is bool:
114
+ return node.value
115
+ if node.value is None:
116
+ return False
117
+ return None
118
+
119
+
120
+ def _legacy_options(call: ast.Call) -> tuple[int, bool, bool] | None:
121
+ if any(keyword.arg == "versions" for keyword in call.keywords):
122
+ return None
123
+ if not any(keyword.arg in {"backward", "forward"} for keyword in call.keywords):
124
+ return None
125
+
126
+ keywords: dict[str, ast.expr] = {}
127
+ for keyword in call.keywords:
128
+ if keyword.arg in _LEGACY_FLAGS:
129
+ if keyword.arg in keywords:
130
+ return None
131
+ keywords[keyword.arg] = keyword.value
132
+
133
+ version = _literal_integer(keywords.get("version"))
134
+ if version is None:
135
+ return None
136
+
137
+ backward = _literal_boolean(keywords.get("backward"), default=False)
138
+ forward = _literal_forward(keywords.get("forward"))
139
+ if backward is None or forward is None:
140
+ return None
141
+ return version, backward, forward
142
+
143
+
144
+ def _legacy_version_argument(version: int, backward: bool, forward: bool) -> str:
145
+ if backward and forward:
146
+ return "version=1"
147
+ if backward:
148
+ return f"versions=list(range(1, {version + 1}))"
149
+ if not forward:
150
+ return f"versions=[{version}]"
151
+ return f"version={version}"
152
+
153
+
154
+ def _rewrite_call(text: str, call: ast.Call) -> str | None:
155
+ legacy = _legacy_options(call)
156
+ if legacy is None:
157
+ return None
158
+
159
+ call_source = ast.get_source_segment(text, call)
160
+ function_source = ast.get_source_segment(text, call.func)
161
+ if not call_source or not function_source or _has_comments(call_source):
162
+ return None
163
+
164
+ remaining = []
165
+ for argument in call.args:
166
+ segment = ast.get_source_segment(text, argument)
167
+ if segment is None:
168
+ return None
169
+ remaining.append(segment)
170
+
171
+ for keyword in call.keywords:
172
+ if keyword.arg in _LEGACY_FLAGS:
173
+ continue
174
+ segment = ast.get_source_segment(text, keyword)
175
+ if segment is None:
176
+ return None
177
+ remaining.append(segment)
178
+
179
+ remaining.append(_legacy_version_argument(*legacy))
180
+ return f"{function_source}({', '.join(remaining)})"
181
+
182
+
183
+ def _absolute_offset(text: str, lineno: int, utf8_column: int) -> int:
184
+ lines = text.splitlines(keepends=True)
185
+ prefix = sum(len(line) for line in lines[: lineno - 1])
186
+ line = lines[lineno - 1]
187
+ character_column = len(line.encode("utf-8")[:utf8_column].decode("utf-8"))
188
+ return prefix + character_column
189
+
190
+
191
+ def _collect_rewrites(text: str) -> list[tuple[int, int, str, str]]:
192
+ try:
193
+ tree = ast.parse(text)
194
+ except SyntaxError:
195
+ return []
196
+
197
+ rewrites = []
198
+ for node in ast.walk(tree):
199
+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
200
+ continue
201
+ for decorator in node.decorator_list:
202
+ if not isinstance(decorator, ast.Call) or not _is_endpoint_call(
203
+ decorator.func
204
+ ):
205
+ continue
206
+
207
+ replacement = _rewrite_call(text, decorator)
208
+ if replacement is None:
209
+ continue
210
+
211
+ old = ast.get_source_segment(text, decorator)
212
+ if old is None:
213
+ continue
214
+ start = _absolute_offset(text, decorator.lineno, decorator.col_offset)
215
+ end = _absolute_offset(text, decorator.end_lineno, decorator.end_col_offset)
216
+ if replacement != old:
217
+ rewrites.append((start, end, old, replacement))
218
+
219
+ return sorted(rewrites, key=lambda item: item[0])
220
+
221
+
222
+ def _apply_rewrites(text: str, rewrites: list[tuple[int, int, str, str]]) -> str:
223
+ updated = text
224
+ for start, end, _, replacement in reversed(rewrites):
225
+ updated = updated[:start] + replacement + updated[end:]
226
+ return updated
227
+
228
+
229
+ def _suggest(text: str) -> list[tuple[str, str]]:
230
+ return [(f"@{old}", f"@{new}") for _, _, old, new in _collect_rewrites(text)]
231
+
232
+
233
+ def _rewrite_args(args: str) -> str:
234
+ source = f"__endpoint({args})"
235
+ try:
236
+ tree = ast.parse(source, mode="eval")
237
+ except SyntaxError:
238
+ return args
239
+
240
+ call = tree.body
241
+ if not isinstance(call, ast.Call):
242
+ return args
243
+
244
+ replacement = _rewrite_call(source, call)
245
+ if replacement is None:
246
+ return args
247
+
248
+ opening = replacement.find("(")
249
+ return replacement[opening + 1 : -1]