parse-errors 0.0.0a1__tar.gz → 0.5.0__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.
- parse_errors-0.5.0/.github/workflows/build.yml +75 -0
- parse_errors-0.5.0/.gitignore +113 -0
- parse_errors-0.5.0/.vars.ini +10 -0
- parse_errors-0.5.0/LICENSE +21 -0
- parse_errors-0.5.0/MANIFEST.in +2 -0
- parse_errors-0.5.0/Makefile +37 -0
- parse_errors-0.5.0/PKG-INFO +46 -0
- parse_errors-0.5.0/README.md +18 -0
- parse_errors-0.5.0/parse_errors/__init__.py +13 -0
- parse_errors-0.5.0/parse_errors/_jsonpath.py +70 -0
- parse_errors-0.5.0/parse_errors/_version.py +34 -0
- parse_errors-0.5.0/parse_errors/context.py +83 -0
- parse_errors-0.5.0/parse_errors/json_source_map/__init__.py +25 -0
- parse_errors-0.5.0/parse_errors/json_source_map/__main__.py +7 -0
- parse_errors-0.5.0/parse_errors/py.typed +0 -0
- parse_errors-0.5.0/parse_errors/source_map.py +77 -0
- parse_errors-0.5.0/parse_errors/toml_source_map/__init__.py +194 -0
- parse_errors-0.5.0/parse_errors/toml_source_map/__main__.py +7 -0
- parse_errors-0.5.0/parse_errors/yaml_source_map/__init__.py +62 -0
- parse_errors-0.5.0/parse_errors/yaml_source_map/__main__.py +7 -0
- parse_errors-0.5.0/parse_errors.egg-info/PKG-INFO +46 -0
- parse_errors-0.5.0/parse_errors.egg-info/SOURCES.txt +33 -0
- parse_errors-0.5.0/parse_errors.egg-info/dependency_links.txt +1 -0
- parse_errors-0.5.0/parse_errors.egg-info/requires.txt +17 -0
- parse_errors-0.5.0/parse_errors.egg-info/top_level.txt +2 -0
- parse_errors-0.5.0/setup.cfg +79 -0
- parse_errors-0.5.0/setup.py +3 -0
- parse_errors-0.5.0/tests/__init__.py +1 -0
- parse_errors-0.5.0/tests/_types.py +10 -0
- parse_errors-0.5.0/tests/conftest.py +0 -0
- parse_errors-0.5.0/tests/test_parse_context_json.py +79 -0
- parse_errors-0.5.0/tests/test_parse_context_toml.py +82 -0
- parse_errors-0.5.0/tests/test_parse_context_yaml.py +48 -0
- parse_errors-0.5.0/tests/test_source_map.py +41 -0
- parse_errors-0.0.0a1/PKG-INFO +0 -5
- parse_errors-0.0.0a1/parse_errors/__init__.py +0 -1
- parse_errors-0.0.0a1/pyproject.toml +0 -11
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
name: Build
|
|
2
|
+
on:
|
|
3
|
+
push:
|
|
4
|
+
branches:
|
|
5
|
+
- master
|
|
6
|
+
- main
|
|
7
|
+
- tmp-*
|
|
8
|
+
tags:
|
|
9
|
+
- v*
|
|
10
|
+
pull_request:
|
|
11
|
+
|
|
12
|
+
env:
|
|
13
|
+
UV_SYSTEM_PYTHON: 1
|
|
14
|
+
|
|
15
|
+
jobs:
|
|
16
|
+
test:
|
|
17
|
+
runs-on: ${{ matrix.os }}
|
|
18
|
+
strategy:
|
|
19
|
+
fail-fast: false
|
|
20
|
+
matrix:
|
|
21
|
+
python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]
|
|
22
|
+
os: [macOS-latest, ubuntu-latest, windows-latest]
|
|
23
|
+
|
|
24
|
+
steps:
|
|
25
|
+
- name: Checkout
|
|
26
|
+
uses: actions/checkout@v4
|
|
27
|
+
- name: Set Up Python ${{ matrix.python-version }}
|
|
28
|
+
uses: actions/setup-python@v5
|
|
29
|
+
with:
|
|
30
|
+
python-version: ${{ matrix.python-version }}
|
|
31
|
+
allow-prereleases: true
|
|
32
|
+
- uses: astral-sh/setup-uv@v3
|
|
33
|
+
- name: Install
|
|
34
|
+
run: |
|
|
35
|
+
uv pip install -e .[test,dev]
|
|
36
|
+
- name: Test
|
|
37
|
+
run: |
|
|
38
|
+
git config --global user.name "Unit Test"
|
|
39
|
+
git config --global user.email "example@example.com"
|
|
40
|
+
make test
|
|
41
|
+
- name: Lint
|
|
42
|
+
run: |
|
|
43
|
+
make lint
|
|
44
|
+
|
|
45
|
+
build:
|
|
46
|
+
needs: test
|
|
47
|
+
runs-on: ubuntu-latest
|
|
48
|
+
steps:
|
|
49
|
+
- uses: actions/checkout@v4
|
|
50
|
+
- uses: actions/setup-python@v5
|
|
51
|
+
with:
|
|
52
|
+
python-version: "3.14"
|
|
53
|
+
- uses: astral-sh/setup-uv@v3
|
|
54
|
+
- name: Install
|
|
55
|
+
run: uv pip install build
|
|
56
|
+
- name: Build
|
|
57
|
+
run: python -m build
|
|
58
|
+
- name: Upload
|
|
59
|
+
uses: actions/upload-artifact@v4
|
|
60
|
+
with:
|
|
61
|
+
name: sdist
|
|
62
|
+
path: dist
|
|
63
|
+
|
|
64
|
+
publish:
|
|
65
|
+
needs: build
|
|
66
|
+
runs-on: ubuntu-latest
|
|
67
|
+
if: startsWith(github.ref, 'refs/tags/v')
|
|
68
|
+
permissions:
|
|
69
|
+
id-token: write
|
|
70
|
+
steps:
|
|
71
|
+
- uses: actions/download-artifact@v4
|
|
72
|
+
with:
|
|
73
|
+
name: sdist
|
|
74
|
+
path: dist
|
|
75
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# C extensions
|
|
7
|
+
*.so
|
|
8
|
+
|
|
9
|
+
# Distribution / packaging
|
|
10
|
+
.Python
|
|
11
|
+
build/
|
|
12
|
+
develop-eggs/
|
|
13
|
+
dist/
|
|
14
|
+
downloads/
|
|
15
|
+
eggs/
|
|
16
|
+
.eggs/
|
|
17
|
+
lib/
|
|
18
|
+
lib64/
|
|
19
|
+
parts/
|
|
20
|
+
sdist/
|
|
21
|
+
var/
|
|
22
|
+
wheels/
|
|
23
|
+
*.egg-info/
|
|
24
|
+
.installed.cfg
|
|
25
|
+
*.egg
|
|
26
|
+
MANIFEST
|
|
27
|
+
|
|
28
|
+
# PyInstaller
|
|
29
|
+
# Usually these files are written by a python script from a template
|
|
30
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
31
|
+
*.manifest
|
|
32
|
+
*.spec
|
|
33
|
+
|
|
34
|
+
# Installer logs
|
|
35
|
+
pip-log.txt
|
|
36
|
+
pip-delete-this-directory.txt
|
|
37
|
+
|
|
38
|
+
# Unit test / coverage reports
|
|
39
|
+
htmlcov/
|
|
40
|
+
.tox/
|
|
41
|
+
.coverage
|
|
42
|
+
.coverage.*
|
|
43
|
+
.cache
|
|
44
|
+
nosetests.xml
|
|
45
|
+
coverage.xml
|
|
46
|
+
*.cover
|
|
47
|
+
.hypothesis/
|
|
48
|
+
.pytest_cache/
|
|
49
|
+
|
|
50
|
+
# Translations
|
|
51
|
+
*.mo
|
|
52
|
+
*.pot
|
|
53
|
+
|
|
54
|
+
# Django stuff:
|
|
55
|
+
*.log
|
|
56
|
+
local_settings.py
|
|
57
|
+
db.sqlite3
|
|
58
|
+
|
|
59
|
+
# Flask stuff:
|
|
60
|
+
instance/
|
|
61
|
+
.webassets-cache
|
|
62
|
+
|
|
63
|
+
# Scrapy stuff:
|
|
64
|
+
.scrapy
|
|
65
|
+
|
|
66
|
+
# Sphinx documentation
|
|
67
|
+
docs/_build/
|
|
68
|
+
|
|
69
|
+
# PyBuilder
|
|
70
|
+
target/
|
|
71
|
+
|
|
72
|
+
# Jupyter Notebook
|
|
73
|
+
.ipynb_checkpoints
|
|
74
|
+
|
|
75
|
+
# pyenv
|
|
76
|
+
.python-version
|
|
77
|
+
|
|
78
|
+
# celery beat schedule file
|
|
79
|
+
celerybeat-schedule
|
|
80
|
+
|
|
81
|
+
# SageMath parsed files
|
|
82
|
+
*.sage.py
|
|
83
|
+
|
|
84
|
+
# Environments
|
|
85
|
+
.env
|
|
86
|
+
.venv*
|
|
87
|
+
env/
|
|
88
|
+
venv/
|
|
89
|
+
ENV/
|
|
90
|
+
env.bak/
|
|
91
|
+
venv.bak/
|
|
92
|
+
|
|
93
|
+
# Spyder project settings
|
|
94
|
+
.spyderproject
|
|
95
|
+
.spyproject
|
|
96
|
+
|
|
97
|
+
# Rope project settings
|
|
98
|
+
.ropeproject
|
|
99
|
+
|
|
100
|
+
# mkdocs documentation
|
|
101
|
+
/site
|
|
102
|
+
|
|
103
|
+
# mypy
|
|
104
|
+
.mypy_cache/
|
|
105
|
+
|
|
106
|
+
# Visual Studio Code
|
|
107
|
+
.vscode/
|
|
108
|
+
|
|
109
|
+
# Vim swapfiles
|
|
110
|
+
*.sw[op]
|
|
111
|
+
|
|
112
|
+
# Setuptools-scm
|
|
113
|
+
_version.py
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
[vars]
|
|
2
|
+
pypi_name = parse-errors
|
|
3
|
+
short_desc = re-raise parse errors with filename and line number
|
|
4
|
+
url = https://github.com/advice-animal/parse-errors/
|
|
5
|
+
author = Tim Hatch
|
|
6
|
+
author_email = tim@timhatch.com
|
|
7
|
+
package = parse_errors
|
|
8
|
+
year = 2026
|
|
9
|
+
author_website = https://timhatch.com/
|
|
10
|
+
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Tim Hatch
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
ifeq ($(OS),Windows_NT)
|
|
2
|
+
ACTIVATE:=.venv/Scripts/activate
|
|
3
|
+
else
|
|
4
|
+
ACTIVATE:=.venv/bin/activate
|
|
5
|
+
endif
|
|
6
|
+
|
|
7
|
+
UV:=$(shell uv --version)
|
|
8
|
+
ifdef UV
|
|
9
|
+
VENV:=uv venv
|
|
10
|
+
PIP:=uv pip
|
|
11
|
+
else
|
|
12
|
+
VENV:=python -m venv
|
|
13
|
+
PIP:=python -m pip
|
|
14
|
+
endif
|
|
15
|
+
|
|
16
|
+
.venv:
|
|
17
|
+
$(VENV) .venv
|
|
18
|
+
|
|
19
|
+
.PHONY: setup
|
|
20
|
+
setup: .venv
|
|
21
|
+
source $(ACTIVATE) && $(PIP) install -Ue .[dev,test]
|
|
22
|
+
|
|
23
|
+
.PHONY: test
|
|
24
|
+
test:
|
|
25
|
+
python -m coverage run -m pytest $(TESTOPTS)
|
|
26
|
+
python -m coverage report
|
|
27
|
+
|
|
28
|
+
.PHONY: format
|
|
29
|
+
format:
|
|
30
|
+
ruff format
|
|
31
|
+
ruff check --fix
|
|
32
|
+
|
|
33
|
+
.PHONY: lint
|
|
34
|
+
lint:
|
|
35
|
+
ruff check
|
|
36
|
+
python -m checkdeps --allow-names parse_errors parse_errors
|
|
37
|
+
mypy --strict --install-types --non-interactive parse_errors
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: parse-errors
|
|
3
|
+
Version: 0.5.0
|
|
4
|
+
Summary: re-raise parse errors with filename and line number
|
|
5
|
+
Home-page: https://github.com/advice-animal/parse-errors/
|
|
6
|
+
Author: Tim Hatch
|
|
7
|
+
Author-email: tim@timhatch.com
|
|
8
|
+
License: MIT
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: json-source-map
|
|
13
|
+
Requires-Dist: pyyaml
|
|
14
|
+
Requires-Dist: tree-sitter
|
|
15
|
+
Requires-Dist: tree-sitter-toml
|
|
16
|
+
Provides-Extra: dev
|
|
17
|
+
Requires-Dist: checkdeps==0.9.0; extra == "dev"
|
|
18
|
+
Requires-Dist: mypy==1.19.1; extra == "dev"
|
|
19
|
+
Requires-Dist: ruff==0.15.6; extra == "dev"
|
|
20
|
+
Requires-Dist: tox==4.50.0; extra == "dev"
|
|
21
|
+
Requires-Dist: tox-uv==1.33.4; extra == "dev"
|
|
22
|
+
Requires-Dist: types-pyyaml; extra == "dev"
|
|
23
|
+
Provides-Extra: test
|
|
24
|
+
Requires-Dist: coverage>=6; extra == "test"
|
|
25
|
+
Requires-Dist: pytest>=8; extra == "test"
|
|
26
|
+
Requires-Dist: msgspec; extra == "test"
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# parse-errors
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# Version Compat
|
|
33
|
+
|
|
34
|
+
This library is compatile with Python 3.10+, but should be linted under the
|
|
35
|
+
newest stable version.
|
|
36
|
+
|
|
37
|
+
# Versioning
|
|
38
|
+
|
|
39
|
+
This library follows [meanver](https://meanver.org/) which basically means
|
|
40
|
+
[semver](https://semver.org/) along with a promise to rename when the major
|
|
41
|
+
version changes.
|
|
42
|
+
|
|
43
|
+
# License
|
|
44
|
+
|
|
45
|
+
parse-errors is copyright [Tim Hatch](https://timhatch.com/), and licensed under
|
|
46
|
+
the MIT license. See the `LICENSE` file for details.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# parse-errors
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
# Version Compat
|
|
5
|
+
|
|
6
|
+
This library is compatile with Python 3.10+, but should be linted under the
|
|
7
|
+
newest stable version.
|
|
8
|
+
|
|
9
|
+
# Versioning
|
|
10
|
+
|
|
11
|
+
This library follows [meanver](https://meanver.org/) which basically means
|
|
12
|
+
[semver](https://semver.org/) along with a promise to rename when the major
|
|
13
|
+
version changes.
|
|
14
|
+
|
|
15
|
+
# License
|
|
16
|
+
|
|
17
|
+
parse-errors is copyright [Tim Hatch](https://timhatch.com/), and licensed under
|
|
18
|
+
the MIT license. See the `LICENSE` file for details.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""re-raise parse errors with filename and line number."""
|
|
2
|
+
|
|
3
|
+
from .context import ParseContext, ParseError
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
from ._version import __version__
|
|
7
|
+
except ImportError: # pragma: no cover
|
|
8
|
+
__version__ = "dev"
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"ParseContext",
|
|
12
|
+
"ParseError",
|
|
13
|
+
]
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Convert JSONPath expressions to JSON Pointer (RFC 6901)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
# Matches a single step in a JSONPath: .key or [index] or ['key'] or ["key"]
|
|
9
|
+
_STEP = re.compile(
|
|
10
|
+
r"\.(?P<name>[^.\[]+)" # .key
|
|
11
|
+
r"|\[(?P<idx>\d+)\]" # [0]
|
|
12
|
+
r"|\[\'(?P<sq>[^\']*)\'\]" # ['key']
|
|
13
|
+
r'|\["(?P<dq>[^"]*)"\]' # ["key"]
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
# Pattern to extract JSONPath from msgspec-style error messages: "... - at `$.foo.bar`"
|
|
17
|
+
_AT_PATH = re.compile(r" - at `(\$[^`]*)`")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def jsonpath_to_pointer(jsonpath: str) -> str:
|
|
21
|
+
"""Convert a JSONPath string like ``$.foo[0].bar`` to a JSON Pointer like ``/foo/0/bar``.
|
|
22
|
+
|
|
23
|
+
Only supports simple dot-notation and bracket-index forms as produced by
|
|
24
|
+
msgspec. Does not support filter expressions or wildcards.
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
jsonpath: A JSONPath string starting with ``$``.
|
|
28
|
+
|
|
29
|
+
Returns:
|
|
30
|
+
A JSON Pointer string (RFC 6901), e.g. ``/foo/0/bar``.
|
|
31
|
+
"""
|
|
32
|
+
if jsonpath == "$":
|
|
33
|
+
return ""
|
|
34
|
+
if not jsonpath.startswith("$"):
|
|
35
|
+
raise ValueError(f"JSONPath must start with '$', got: {jsonpath!r}")
|
|
36
|
+
|
|
37
|
+
tail = jsonpath[1:] # strip leading $
|
|
38
|
+
parts: list[str] = []
|
|
39
|
+
|
|
40
|
+
pos = 0
|
|
41
|
+
while pos < len(tail):
|
|
42
|
+
m = _STEP.match(tail, pos)
|
|
43
|
+
if m is None:
|
|
44
|
+
raise ValueError(
|
|
45
|
+
f"Cannot parse JSONPath step at position {pos}: {tail[pos:]!r}"
|
|
46
|
+
)
|
|
47
|
+
name = m.group("name") or m.group("sq") or m.group("dq") or m.group("idx")
|
|
48
|
+
parts.append(_escape(name))
|
|
49
|
+
pos = m.end()
|
|
50
|
+
|
|
51
|
+
return "/" + "/".join(parts) if parts else ""
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def extract_jsonpath(message: str) -> str | None:
|
|
55
|
+
"""Extract a JSONPath expression from an error message.
|
|
56
|
+
|
|
57
|
+
Looks for the pattern ``- at `$.path``` as used by msgspec.
|
|
58
|
+
|
|
59
|
+
Args:
|
|
60
|
+
message: The exception message string.
|
|
61
|
+
|
|
62
|
+
Returns:
|
|
63
|
+
The JSONPath string if found, otherwise ``None``.
|
|
64
|
+
"""
|
|
65
|
+
m = _AT_PATH.search(message)
|
|
66
|
+
return m.group(1) if m else None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _escape(segment: str) -> str:
|
|
70
|
+
return segment.replace("~", "~0").replace("/", "~1")
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# file generated by setuptools-scm
|
|
2
|
+
# don't change, don't track in version control
|
|
3
|
+
|
|
4
|
+
__all__ = [
|
|
5
|
+
"__version__",
|
|
6
|
+
"__version_tuple__",
|
|
7
|
+
"version",
|
|
8
|
+
"version_tuple",
|
|
9
|
+
"__commit_id__",
|
|
10
|
+
"commit_id",
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
TYPE_CHECKING = False
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from typing import Tuple
|
|
16
|
+
from typing import Union
|
|
17
|
+
|
|
18
|
+
VERSION_TUPLE = Tuple[Union[int, str], ...]
|
|
19
|
+
COMMIT_ID = Union[str, None]
|
|
20
|
+
else:
|
|
21
|
+
VERSION_TUPLE = object
|
|
22
|
+
COMMIT_ID = object
|
|
23
|
+
|
|
24
|
+
version: str
|
|
25
|
+
__version__: str
|
|
26
|
+
__version_tuple__: VERSION_TUPLE
|
|
27
|
+
version_tuple: VERSION_TUPLE
|
|
28
|
+
commit_id: COMMIT_ID
|
|
29
|
+
__commit_id__: COMMIT_ID
|
|
30
|
+
|
|
31
|
+
__version__ = version = '0.5.0'
|
|
32
|
+
__version_tuple__ = version_tuple = (0, 5, 0)
|
|
33
|
+
|
|
34
|
+
__commit_id__ = commit_id = 'g9fcc0e192'
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Context manager for better parse error messages."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import contextlib
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Iterator
|
|
9
|
+
|
|
10
|
+
from .source_map import detect_format, build_source_map, closest_entry
|
|
11
|
+
from ._jsonpath import extract_jsonpath, jsonpath_to_pointer
|
|
12
|
+
|
|
13
|
+
__all__ = ["ParseError", "ParseContext"]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ParseError(Exception):
|
|
17
|
+
"""A parse or validation error augmented with filename and line number."""
|
|
18
|
+
|
|
19
|
+
def __init__(
|
|
20
|
+
self, message: str, filename: str | os.PathLike[str], line: int, column: int = 0
|
|
21
|
+
):
|
|
22
|
+
self.filename = str(filename)
|
|
23
|
+
self.line = line
|
|
24
|
+
self.column = column
|
|
25
|
+
super().__init__(message)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@contextlib.contextmanager
|
|
29
|
+
def ParseContext(
|
|
30
|
+
filename: str | os.PathLike[str],
|
|
31
|
+
*,
|
|
32
|
+
data: str | bytes | None = None,
|
|
33
|
+
format: str | None = None,
|
|
34
|
+
) -> Iterator[None]:
|
|
35
|
+
"""Context manager that re-raises parse/validation errors with location info.
|
|
36
|
+
|
|
37
|
+
Catches exceptions whose message contains a JSONPath (e.g. as emitted by
|
|
38
|
+
msgspec) and re-raises a :class:`ParseError` with the filename and
|
|
39
|
+
1-based line number derived from the file's source map.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
filename: Path to the file being parsed.
|
|
43
|
+
data: The file contents as a string or bytes (UTF-8). If provided, the
|
|
44
|
+
file is not read from disk. Regardless of type, reported
|
|
45
|
+
locations (line, column) are always in characters, not bytes.
|
|
46
|
+
format: One of ``"json"``, ``"yaml"``, or ``"toml"``. If omitted the
|
|
47
|
+
format is inferred from the file extension.
|
|
48
|
+
"""
|
|
49
|
+
try:
|
|
50
|
+
yield
|
|
51
|
+
except Exception as exc:
|
|
52
|
+
message = str(exc)
|
|
53
|
+
# This is focused on msgspec-style exceptions, which use JSONPath for
|
|
54
|
+
# some reason. If there are other formats we know can be raised,
|
|
55
|
+
# adjust this.
|
|
56
|
+
jsonpath = extract_jsonpath(message)
|
|
57
|
+
if jsonpath is None:
|
|
58
|
+
raise
|
|
59
|
+
|
|
60
|
+
try:
|
|
61
|
+
pointer = jsonpath_to_pointer(jsonpath)
|
|
62
|
+
except ValueError: # pragma: no cover
|
|
63
|
+
raise exc
|
|
64
|
+
|
|
65
|
+
path = Path(filename)
|
|
66
|
+
fmt = format or detect_format(path)
|
|
67
|
+
assert fmt is not None
|
|
68
|
+
|
|
69
|
+
source = data if data is not None else path.read_bytes()
|
|
70
|
+
source_map = build_source_map(source, fmt)
|
|
71
|
+
|
|
72
|
+
entry = closest_entry(source_map, pointer)
|
|
73
|
+
if entry is None: # pragma: no cover
|
|
74
|
+
raise exc
|
|
75
|
+
|
|
76
|
+
loc = entry.value_start
|
|
77
|
+
# Lines are 0-based in source maps; convert to 1-based for humans.
|
|
78
|
+
raise ParseError(
|
|
79
|
+
f"{path}:{loc.line + 1}:{loc.column + 1}: {message}",
|
|
80
|
+
filename=path,
|
|
81
|
+
line=loc.line + 1,
|
|
82
|
+
column=loc.column + 1,
|
|
83
|
+
) from exc
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Thin wrapper around the json-source-map package that returns our own types."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json_source_map as _ext
|
|
6
|
+
|
|
7
|
+
from ..source_map import Entry, Location, TSourceMap
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def calculate(source: str) -> TSourceMap:
|
|
11
|
+
"""Calculate the source map for a JSON document."""
|
|
12
|
+
return {
|
|
13
|
+
pointer: Entry(
|
|
14
|
+
value_start=_loc(e.value_start),
|
|
15
|
+
value_end=_loc(e.value_end),
|
|
16
|
+
key_start=_loc(e.key_start) if e.key_start is not None else None,
|
|
17
|
+
key_end=_loc(e.key_end) if e.key_end is not None else None,
|
|
18
|
+
)
|
|
19
|
+
for pointer, e in _ext.calculate(source).items()
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _loc(ext: _ext.Location) -> Location:
|
|
24
|
+
"""Translate to our internal structure."""
|
|
25
|
+
return Location(line=ext.line, column=ext.column, position=ext.position)
|
|
File without changes
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Source map types and utilities for parse_errors."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import dataclasses
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Dict, Optional
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
# These are identical to the ones in json-source-map, but I feel icky exporting
|
|
11
|
+
# some other project's types because they may change.
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclasses.dataclass
|
|
15
|
+
class Location:
|
|
16
|
+
line: int # 0-based line number
|
|
17
|
+
column: int # 0-based character offset within the line (not bytes)
|
|
18
|
+
position: int # 0-based character offset from start of document (not bytes)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclasses.dataclass
|
|
22
|
+
class Entry:
|
|
23
|
+
value_start: Location
|
|
24
|
+
value_end: Location
|
|
25
|
+
key_start: Optional[Location] = None
|
|
26
|
+
key_end: Optional[Location] = None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
TSourceMap = Dict[str, Entry]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def detect_format(path: Path) -> str | None:
|
|
33
|
+
"""Detect the format of a file based on its extension."""
|
|
34
|
+
suffix = path.suffix.lower()
|
|
35
|
+
return {
|
|
36
|
+
".json": "json",
|
|
37
|
+
".toml": "toml",
|
|
38
|
+
".yaml": "yaml",
|
|
39
|
+
".yml": "yaml",
|
|
40
|
+
}.get(suffix)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def build_source_map(source: str | bytes, fmt: str) -> TSourceMap:
|
|
44
|
+
"""Build a source map for the given source in the given format."""
|
|
45
|
+
if fmt == "toml":
|
|
46
|
+
from . import toml_source_map
|
|
47
|
+
|
|
48
|
+
return toml_source_map.calculate(source)
|
|
49
|
+
elif fmt in ("yaml", "yml"):
|
|
50
|
+
from . import yaml_source_map
|
|
51
|
+
|
|
52
|
+
return yaml_source_map.calculate(
|
|
53
|
+
source.decode("utf-8") if isinstance(source, bytes) else source
|
|
54
|
+
)
|
|
55
|
+
elif fmt == "json":
|
|
56
|
+
from . import json_source_map
|
|
57
|
+
|
|
58
|
+
return json_source_map.calculate(
|
|
59
|
+
source.decode("utf-8") if isinstance(source, bytes) else source
|
|
60
|
+
)
|
|
61
|
+
else:
|
|
62
|
+
raise ValueError(f"Unknown format: {fmt!r}")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def closest_entry(source_map: TSourceMap, pointer: str) -> Entry | None:
|
|
66
|
+
"""Return the source map entry for ``pointer``, falling back to the longest prefix."""
|
|
67
|
+
if pointer in source_map:
|
|
68
|
+
return source_map[pointer]
|
|
69
|
+
|
|
70
|
+
# Walk up the pointer path until we find a match.
|
|
71
|
+
parts = pointer.split("/") # e.g. ['', 'foo', 'bar']
|
|
72
|
+
for length in range(len(parts) - 1, 0, -1):
|
|
73
|
+
candidate = "/".join(parts[:length])
|
|
74
|
+
if candidate in source_map:
|
|
75
|
+
return source_map[candidate]
|
|
76
|
+
|
|
77
|
+
return None
|