parse-toml 0.1.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_toml-0.1.0/LICENSE +21 -0
- parse_toml-0.1.0/PKG-INFO +49 -0
- parse_toml-0.1.0/README.md +34 -0
- parse_toml-0.1.0/docs/api.md +32 -0
- parse_toml-0.1.0/docs/releasing.md +27 -0
- parse_toml-0.1.0/pyproject.toml +46 -0
- parse_toml-0.1.0/pyproject.toml.orig +34 -0
- parse_toml-0.1.0/scripts/check_distribution.py +104 -0
- parse_toml-0.1.0/src/parse_toml/__init__.py +14 -0
- parse_toml-0.1.0/src/parse_toml/nodes.py +42 -0
- parse_toml-0.1.0/src/parse_toml/parser.py +237 -0
- parse_toml-0.1.0/tests/fixtures/config.toml +11 -0
- parse_toml-0.1.0/tests/test_parser.py +133 -0
parse_toml-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 wispsy
|
|
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,49 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: parse-toml
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Bounded, source-aware TOML 1.0 parsing for Python
|
|
5
|
+
Author: wispsy
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
10
|
+
Classifier: Typing :: Typed
|
|
11
|
+
Requires-Python: >=3.14
|
|
12
|
+
Project-URL: Repository, https://github.com/wispsy/parse-toml
|
|
13
|
+
Project-URL: Issues, https://github.com/wispsy/parse-toml/issues
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# parse-toml
|
|
17
|
+
|
|
18
|
+
`parse-toml` is a typed, bounded TOML 1.0 parser for Python 3.14 and newer.
|
|
19
|
+
It uses Python's standard-library `tomllib`, has no runtime dependencies, and
|
|
20
|
+
preserves the original source alongside the parsed value.
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
from parse_toml import parse
|
|
24
|
+
|
|
25
|
+
document = parse('name = "Ada"\nactive = true\n')
|
|
26
|
+
print(document.value["name"]) # Ada
|
|
27
|
+
print(document.to_toml()) # the original source
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Use `loads(source)` when only the converted Python value is needed. Invalid
|
|
31
|
+
input raises `ParseError` with a message, line, column, and error code. Resource
|
|
32
|
+
limits can be adjusted with `ParseOptions`; inputs that exceed a limit do not
|
|
33
|
+
produce a partial result.
|
|
34
|
+
|
|
35
|
+
See [the API and supported syntax](docs/api.md) for TOML value types, resource
|
|
36
|
+
limits, and error behavior.
|
|
37
|
+
|
|
38
|
+
See [the release guide](docs/releasing.md) for PyPI Trusted Publishing setup
|
|
39
|
+
and release instructions.
|
|
40
|
+
|
|
41
|
+
## Development
|
|
42
|
+
|
|
43
|
+
```sh
|
|
44
|
+
uv sync --locked
|
|
45
|
+
uv run --frozen python -m pytest
|
|
46
|
+
uv run --frozen python scripts/check_distribution.py --output-dir dist
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
The test and distribution checks also run in GitHub Actions on Python 3.14.
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# parse-toml
|
|
2
|
+
|
|
3
|
+
`parse-toml` is a typed, bounded TOML 1.0 parser for Python 3.14 and newer.
|
|
4
|
+
It uses Python's standard-library `tomllib`, has no runtime dependencies, and
|
|
5
|
+
preserves the original source alongside the parsed value.
|
|
6
|
+
|
|
7
|
+
```python
|
|
8
|
+
from parse_toml import parse
|
|
9
|
+
|
|
10
|
+
document = parse('name = "Ada"\nactive = true\n')
|
|
11
|
+
print(document.value["name"]) # Ada
|
|
12
|
+
print(document.to_toml()) # the original source
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Use `loads(source)` when only the converted Python value is needed. Invalid
|
|
16
|
+
input raises `ParseError` with a message, line, column, and error code. Resource
|
|
17
|
+
limits can be adjusted with `ParseOptions`; inputs that exceed a limit do not
|
|
18
|
+
produce a partial result.
|
|
19
|
+
|
|
20
|
+
See [the API and supported syntax](docs/api.md) for TOML value types, resource
|
|
21
|
+
limits, and error behavior.
|
|
22
|
+
|
|
23
|
+
See [the release guide](docs/releasing.md) for PyPI Trusted Publishing setup
|
|
24
|
+
and release instructions.
|
|
25
|
+
|
|
26
|
+
## Development
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
uv sync --locked
|
|
30
|
+
uv run --frozen python -m pytest
|
|
31
|
+
uv run --frozen python scripts/check_distribution.py --output-dir dist
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
The test and distribution checks also run in GitHub Actions on Python 3.14.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# Parser and source contract
|
|
2
|
+
|
|
3
|
+
`parse(source, options=ParseOptions())` parses one TOML 1.0 document and
|
|
4
|
+
returns a `Document` containing its Python value, the exact original source,
|
|
5
|
+
and a half-open code-point `SourceSpan`. `Document.to_toml()` returns that
|
|
6
|
+
original source; it does not serialize modified Python values. `loads()` is a
|
|
7
|
+
convenience that returns only the converted value.
|
|
8
|
+
|
|
9
|
+
The implementation delegates TOML syntax and value conversion to Python's
|
|
10
|
+
standard-library `tomllib`. TOML strings, booleans, integers, floats, local
|
|
11
|
+
dates, local times, local datetimes, offset datetimes, arrays, and tables map
|
|
12
|
+
to `str`, `bool`, `int`, `float`, `datetime.date`, `datetime.time`,
|
|
13
|
+
`datetime.datetime`, `list`, and string-keyed `dict` values, respectively.
|
|
14
|
+
|
|
15
|
+
## Errors and limits
|
|
16
|
+
|
|
17
|
+
Malformed input raises `ParseError`, which exposes `message`, `line`,
|
|
18
|
+
`column`, `code`, and `position`. Syntax errors retain the location reported
|
|
19
|
+
by `tomllib`; resource-limit errors use the location where the limit was
|
|
20
|
+
reached when available. No partial document is returned.
|
|
21
|
+
|
|
22
|
+
`ParseOptions` is immutable and configures limits for each call:
|
|
23
|
+
|
|
24
|
+
| Limit | Default |
|
|
25
|
+
| --- | ---: |
|
|
26
|
+
| Source characters | 1,000,000 |
|
|
27
|
+
| Parsed values and containers | 100,000 |
|
|
28
|
+
| Container nesting depth | 64 |
|
|
29
|
+
|
|
30
|
+
TOML parsing is local and data-only. This package does not read files, access
|
|
31
|
+
the network, construct application objects, or invoke callbacks. Python 3.14
|
|
32
|
+
or newer is required.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Releasing
|
|
2
|
+
|
|
3
|
+
Releases are published to PyPI from a version tag. The release workflow checks
|
|
4
|
+
the test suite and distributions, verifies that the tag matches the package
|
|
5
|
+
version, and requires the tagged commit to be reachable from `main` before
|
|
6
|
+
publishing.
|
|
7
|
+
|
|
8
|
+
## One-time PyPI setup
|
|
9
|
+
|
|
10
|
+
Before the first release, configure a PyPI Trusted Publisher for this project:
|
|
11
|
+
|
|
12
|
+
- PyPI project: `parse-toml`
|
|
13
|
+
- GitHub owner: `wispsy`
|
|
14
|
+
- GitHub repository: `parse-toml`
|
|
15
|
+
- Workflow: `release.yaml`
|
|
16
|
+
- GitHub environment: `pypi`
|
|
17
|
+
|
|
18
|
+
Create the `pypi` environment in the repository's GitHub Actions environment
|
|
19
|
+
settings if it does not already exist. The workflow uses PyPI Trusted
|
|
20
|
+
Publishing via GitHub's OIDC identity token; no PyPI API token is needed.
|
|
21
|
+
|
|
22
|
+
## Publishing a release
|
|
23
|
+
|
|
24
|
+
After the release commit is merged to `main`, create and push a tag matching
|
|
25
|
+
the version in `pyproject.toml`. For example, version `0.1.0` uses the tag
|
|
26
|
+
`v0.1.0`. A tag with a different version or a commit not reachable from
|
|
27
|
+
`main` fails release checks and is not published.
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "parse-toml"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Bounded, source-aware TOML 1.0 parsing for Python"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.14"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
dependencies = []
|
|
10
|
+
classifiers = [
|
|
11
|
+
"Development Status :: 3 - Alpha",
|
|
12
|
+
"Programming Language :: Python :: 3.14",
|
|
13
|
+
"Typing :: Typed",
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
[[project.authors]]
|
|
17
|
+
name = "wispsy"
|
|
18
|
+
|
|
19
|
+
[project.urls]
|
|
20
|
+
Repository = "https://github.com/wispsy/parse-toml"
|
|
21
|
+
Issues = "https://github.com/wispsy/parse-toml/issues"
|
|
22
|
+
|
|
23
|
+
[dependency-groups]
|
|
24
|
+
dev = ["pytest>=8"]
|
|
25
|
+
|
|
26
|
+
[build-system]
|
|
27
|
+
requires = ["uv_build>=0.13.6,<0.14.0"]
|
|
28
|
+
build-backend = "uv_build"
|
|
29
|
+
|
|
30
|
+
[tool.uv.build-backend]
|
|
31
|
+
source-include = [
|
|
32
|
+
"tests/**",
|
|
33
|
+
"docs/**",
|
|
34
|
+
"scripts/**",
|
|
35
|
+
"LICENSE",
|
|
36
|
+
"README.md",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
[tool.pytest.ini_options]
|
|
40
|
+
addopts = [
|
|
41
|
+
"-ra",
|
|
42
|
+
"--strict-config",
|
|
43
|
+
"--strict-markers",
|
|
44
|
+
]
|
|
45
|
+
testpaths = ["tests"]
|
|
46
|
+
filterwarnings = ["error"]
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "parse-toml"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Bounded, source-aware TOML 1.0 parsing for Python"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.14"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
authors = [{name = "wispsy"}]
|
|
10
|
+
dependencies = []
|
|
11
|
+
classifiers = [
|
|
12
|
+
"Development Status :: 3 - Alpha",
|
|
13
|
+
"Programming Language :: Python :: 3.14",
|
|
14
|
+
"Typing :: Typed",
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
[project.urls]
|
|
18
|
+
Repository = "https://github.com/wispsy/parse-toml"
|
|
19
|
+
Issues = "https://github.com/wispsy/parse-toml/issues"
|
|
20
|
+
|
|
21
|
+
[dependency-groups]
|
|
22
|
+
dev = ["pytest>=8"]
|
|
23
|
+
|
|
24
|
+
[build-system]
|
|
25
|
+
requires = ["uv_build>=0.13.6,<0.14.0"]
|
|
26
|
+
build-backend = "uv_build"
|
|
27
|
+
|
|
28
|
+
[tool.uv.build-backend]
|
|
29
|
+
source-include = ["tests/**", "docs/**", "scripts/**", "LICENSE", "README.md"]
|
|
30
|
+
|
|
31
|
+
[tool.pytest.ini_options]
|
|
32
|
+
addopts = ["-ra", "--strict-config", "--strict-markers"]
|
|
33
|
+
testpaths = ["tests"]
|
|
34
|
+
filterwarnings = ["error"]
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Build and smoke-test the source and wheel distributions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import os
|
|
7
|
+
import subprocess
|
|
8
|
+
import tarfile
|
|
9
|
+
import tempfile
|
|
10
|
+
import venv
|
|
11
|
+
import zipfile
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
NAME = "parse-toml"
|
|
15
|
+
VERSION = "0.1.0"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _metadata_fields(text: str) -> dict[str, str]:
|
|
19
|
+
fields: dict[str, str] = {}
|
|
20
|
+
for line in text.splitlines():
|
|
21
|
+
if line.startswith(("Name:", "Version:", "Requires-Dist:")):
|
|
22
|
+
key, value = line.split(":", 1)
|
|
23
|
+
fields[key] = value.strip()
|
|
24
|
+
return fields
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _verify_metadata(metadata: str, artifact: Path) -> None:
|
|
28
|
+
fields = _metadata_fields(metadata)
|
|
29
|
+
if fields.get("Name") != NAME or fields.get("Version") != VERSION:
|
|
30
|
+
raise SystemExit(f"{artifact.name} has unexpected package metadata: {fields}")
|
|
31
|
+
if "Requires-Dist" in fields:
|
|
32
|
+
raise SystemExit(f"{artifact.name} declares runtime dependencies")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def main() -> None:
|
|
36
|
+
argument_parser = argparse.ArgumentParser(description=__doc__)
|
|
37
|
+
argument_parser.add_argument("--tag", default="")
|
|
38
|
+
argument_parser.add_argument("--output-dir", required=True, type=Path)
|
|
39
|
+
args = argument_parser.parse_args()
|
|
40
|
+
if args.tag and args.tag != f"v{VERSION}":
|
|
41
|
+
raise SystemExit(
|
|
42
|
+
f"release tag {args.tag!r} does not match package version v{VERSION}"
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
output_dir = args.output_dir.resolve()
|
|
46
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
47
|
+
subprocess.run(["uv", "build", "--out-dir", str(output_dir)], check=True)
|
|
48
|
+
wheels = sorted(output_dir.glob("parse_toml-*.whl"))
|
|
49
|
+
sdists = sorted(output_dir.glob("parse_toml-*.tar.gz"))
|
|
50
|
+
if len(wheels) != 1 or len(sdists) != 1:
|
|
51
|
+
raise SystemExit("expected exactly one parse-toml wheel and source distribution")
|
|
52
|
+
|
|
53
|
+
wheel = wheels[0]
|
|
54
|
+
with zipfile.ZipFile(wheel) as archive:
|
|
55
|
+
members = archive.namelist()
|
|
56
|
+
package_metadata = next(
|
|
57
|
+
(member for member in members if member.endswith(".dist-info/METADATA")),
|
|
58
|
+
None,
|
|
59
|
+
)
|
|
60
|
+
if "parse_toml/__init__.py" not in members or package_metadata is None:
|
|
61
|
+
raise SystemExit(f"{wheel.name} is missing the package or wheel metadata")
|
|
62
|
+
_verify_metadata(archive.read(package_metadata).decode("utf-8"), wheel)
|
|
63
|
+
|
|
64
|
+
sdist = sdists[0]
|
|
65
|
+
with tarfile.open(sdist, "r:gz") as archive:
|
|
66
|
+
members = archive.getnames()
|
|
67
|
+
package_source = next(
|
|
68
|
+
(member for member in members if member.endswith("/src/parse_toml/__init__.py")),
|
|
69
|
+
None,
|
|
70
|
+
)
|
|
71
|
+
package_metadata = next(
|
|
72
|
+
(member for member in members if member.endswith("/PKG-INFO")),
|
|
73
|
+
None,
|
|
74
|
+
)
|
|
75
|
+
if package_source is None or package_metadata is None:
|
|
76
|
+
raise SystemExit(f"{sdist.name} is missing the package or source metadata")
|
|
77
|
+
metadata_file = archive.extractfile(package_metadata)
|
|
78
|
+
if metadata_file is None:
|
|
79
|
+
raise SystemExit(f"{sdist.name} has unreadable source metadata")
|
|
80
|
+
_verify_metadata(metadata_file.read().decode("utf-8"), sdist)
|
|
81
|
+
|
|
82
|
+
with tempfile.TemporaryDirectory(prefix="parse-toml-install-") as directory:
|
|
83
|
+
environment = Path(directory) / "venv"
|
|
84
|
+
venv.EnvBuilder(with_pip=True).create(environment)
|
|
85
|
+
python = environment / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
|
|
86
|
+
subprocess.run(
|
|
87
|
+
[str(python), "-m", "pip", "install", "--no-index", "--no-deps", str(wheel)],
|
|
88
|
+
check=True,
|
|
89
|
+
)
|
|
90
|
+
subprocess.run(
|
|
91
|
+
[
|
|
92
|
+
str(python),
|
|
93
|
+
"-c",
|
|
94
|
+
"from parse_toml import parse; "
|
|
95
|
+
"assert parse('answer = 42\\n').value == {'answer': 42}",
|
|
96
|
+
],
|
|
97
|
+
check=True,
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
print(f"Verified {sdist.name} and {wheel.name}")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
if __name__ == "__main__":
|
|
104
|
+
main()
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""A bounded, source-aware TOML 1.0 parser with no runtime dependencies."""
|
|
2
|
+
|
|
3
|
+
from .nodes import Document, SourceSpan, TomlValue
|
|
4
|
+
from .parser import ParseError, ParseOptions, loads, parse
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"Document",
|
|
8
|
+
"ParseError",
|
|
9
|
+
"ParseOptions",
|
|
10
|
+
"SourceSpan",
|
|
11
|
+
"TomlValue",
|
|
12
|
+
"loads",
|
|
13
|
+
"parse",
|
|
14
|
+
]
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Public result types for TOML parsing."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from datetime import date, datetime, time
|
|
5
|
+
from typing import TypeAlias
|
|
6
|
+
|
|
7
|
+
TomlValue: TypeAlias = (
|
|
8
|
+
str
|
|
9
|
+
| int
|
|
10
|
+
| float
|
|
11
|
+
| bool
|
|
12
|
+
| date
|
|
13
|
+
| datetime
|
|
14
|
+
| time
|
|
15
|
+
| list["TomlValue"]
|
|
16
|
+
| dict[str, "TomlValue"]
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True, slots=True)
|
|
21
|
+
class SourceSpan:
|
|
22
|
+
"""A half-open range in the original source, measured in code points."""
|
|
23
|
+
|
|
24
|
+
start: int
|
|
25
|
+
end: int
|
|
26
|
+
line: int
|
|
27
|
+
column: int
|
|
28
|
+
end_line: int
|
|
29
|
+
end_column: int
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True, slots=True)
|
|
33
|
+
class Document:
|
|
34
|
+
"""Parsed value together with the exact source that produced it."""
|
|
35
|
+
|
|
36
|
+
value: dict[str, TomlValue]
|
|
37
|
+
source: str
|
|
38
|
+
span: SourceSpan
|
|
39
|
+
|
|
40
|
+
def to_toml(self) -> str:
|
|
41
|
+
"""Return the original source without normalizing or re-serializing it."""
|
|
42
|
+
return self.source
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
"""Bounded TOML 1.0 parsing backed by Python's standard-library tomllib."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import tomllib
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import NoReturn
|
|
8
|
+
|
|
9
|
+
from .nodes import Document, SourceSpan, TomlValue
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ParseError(ValueError):
|
|
13
|
+
"""Invalid TOML or an exceeded resource limit with a source location."""
|
|
14
|
+
|
|
15
|
+
def __init__(
|
|
16
|
+
self,
|
|
17
|
+
message: str,
|
|
18
|
+
line: int,
|
|
19
|
+
column: int,
|
|
20
|
+
code: str = "invalid-toml",
|
|
21
|
+
position: int | None = None,
|
|
22
|
+
) -> None:
|
|
23
|
+
self.message = message
|
|
24
|
+
self.line = line
|
|
25
|
+
self.column = column
|
|
26
|
+
self.code = code
|
|
27
|
+
self.position = position
|
|
28
|
+
super().__init__(f"{message} at line {line}, column {column}")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True, slots=True)
|
|
32
|
+
class ParseOptions:
|
|
33
|
+
"""Resource limits applied to one parse operation."""
|
|
34
|
+
|
|
35
|
+
max_characters: int = 1_000_000
|
|
36
|
+
max_nodes: int = 100_000
|
|
37
|
+
max_depth: int = 64
|
|
38
|
+
|
|
39
|
+
def __post_init__(self) -> None:
|
|
40
|
+
if self.max_characters < 1:
|
|
41
|
+
raise ValueError("max_characters must be at least 1")
|
|
42
|
+
if self.max_nodes < 1:
|
|
43
|
+
raise ValueError("max_nodes must be at least 1")
|
|
44
|
+
if self.max_depth < 1:
|
|
45
|
+
raise ValueError("max_depth must be at least 1")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def parse(source: str, *, options: ParseOptions = ParseOptions()) -> Document:
|
|
49
|
+
"""Parse TOML 1.0 *source* and retain it exactly on the returned document."""
|
|
50
|
+
if not isinstance(source, str):
|
|
51
|
+
raise TypeError("source must be str")
|
|
52
|
+
if len(source) > options.max_characters:
|
|
53
|
+
_raise_limit(
|
|
54
|
+
source,
|
|
55
|
+
0,
|
|
56
|
+
f"source exceeds the {options.max_characters}-character limit",
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
_check_container_depth(source, options.max_depth)
|
|
60
|
+
try:
|
|
61
|
+
value = tomllib.loads(source)
|
|
62
|
+
except tomllib.TOMLDecodeError as error:
|
|
63
|
+
position = getattr(error, "pos", None)
|
|
64
|
+
line = getattr(error, "lineno", None)
|
|
65
|
+
column = getattr(error, "colno", None)
|
|
66
|
+
if position is None:
|
|
67
|
+
position = 0
|
|
68
|
+
if line is None or column is None:
|
|
69
|
+
line, column = _line_column(source, position)
|
|
70
|
+
message = str(error)
|
|
71
|
+
if message.endswith(")") and " (at " in message:
|
|
72
|
+
message = message.rsplit(" (at ", 1)[0]
|
|
73
|
+
raise ParseError(message, line, column, position=position) from error
|
|
74
|
+
except RecursionError:
|
|
75
|
+
_raise_limit(source, 0, "document exceeds the parser nesting limit")
|
|
76
|
+
|
|
77
|
+
_check_value_limits(source, value, options)
|
|
78
|
+
end_line, end_column = _end_location(source)
|
|
79
|
+
return Document(
|
|
80
|
+
value=value,
|
|
81
|
+
source=source,
|
|
82
|
+
span=SourceSpan(0, len(source), 1, 1, end_line, end_column),
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def loads(source: str, *, options: ParseOptions = ParseOptions()) -> dict[str, TomlValue]:
|
|
87
|
+
"""Parse *source* and return its Python value."""
|
|
88
|
+
return parse(source, options=options).value
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _check_value_limits(
|
|
92
|
+
source: str,
|
|
93
|
+
value: dict[str, TomlValue],
|
|
94
|
+
options: ParseOptions,
|
|
95
|
+
) -> None:
|
|
96
|
+
nodes = 0
|
|
97
|
+
pending: list[tuple[TomlValue, int]] = [(value, 0)]
|
|
98
|
+
while pending:
|
|
99
|
+
current, depth = pending.pop()
|
|
100
|
+
nodes += 1
|
|
101
|
+
if nodes > options.max_nodes:
|
|
102
|
+
_raise_limit(
|
|
103
|
+
source,
|
|
104
|
+
0,
|
|
105
|
+
f"document exceeds the {options.max_nodes}-node limit",
|
|
106
|
+
)
|
|
107
|
+
if isinstance(current, dict):
|
|
108
|
+
if depth > options.max_depth:
|
|
109
|
+
_raise_limit(
|
|
110
|
+
source,
|
|
111
|
+
0,
|
|
112
|
+
f"document exceeds the {options.max_depth}-level nesting limit",
|
|
113
|
+
)
|
|
114
|
+
pending.extend((child, depth + 1) for child in current.values())
|
|
115
|
+
elif isinstance(current, list):
|
|
116
|
+
if depth > options.max_depth:
|
|
117
|
+
_raise_limit(
|
|
118
|
+
source,
|
|
119
|
+
0,
|
|
120
|
+
f"document exceeds the {options.max_depth}-level nesting limit",
|
|
121
|
+
)
|
|
122
|
+
pending.extend((child, depth + 1) for child in current)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _check_container_depth(source: str, max_depth: int) -> None:
|
|
126
|
+
depth = 0
|
|
127
|
+
quote: str | None = None
|
|
128
|
+
at_line_start = True
|
|
129
|
+
index = 0
|
|
130
|
+
|
|
131
|
+
while index < len(source):
|
|
132
|
+
char = source[index]
|
|
133
|
+
if quote is not None:
|
|
134
|
+
if quote in {'"""', "'''"}:
|
|
135
|
+
if quote == '"""' and char == "\\":
|
|
136
|
+
index += 2
|
|
137
|
+
continue
|
|
138
|
+
if source.startswith(quote, index):
|
|
139
|
+
quote = None
|
|
140
|
+
index += 3
|
|
141
|
+
continue
|
|
142
|
+
else:
|
|
143
|
+
if quote == '"' and char == "\\":
|
|
144
|
+
index += 2
|
|
145
|
+
continue
|
|
146
|
+
if char == quote:
|
|
147
|
+
quote = None
|
|
148
|
+
at_line_start = char in "\r\n"
|
|
149
|
+
index += 1
|
|
150
|
+
continue
|
|
151
|
+
|
|
152
|
+
if char in " \t" and at_line_start:
|
|
153
|
+
index += 1
|
|
154
|
+
continue
|
|
155
|
+
if char in "\r\n":
|
|
156
|
+
at_line_start = True
|
|
157
|
+
index += 1
|
|
158
|
+
continue
|
|
159
|
+
if at_line_start and char == "[" and depth == 0:
|
|
160
|
+
header_end = _table_header_end(source, index)
|
|
161
|
+
if header_end is not None:
|
|
162
|
+
index = header_end
|
|
163
|
+
at_line_start = False
|
|
164
|
+
continue
|
|
165
|
+
at_line_start = False
|
|
166
|
+
|
|
167
|
+
if char == "#":
|
|
168
|
+
newline = min(
|
|
169
|
+
(position for position in (source.find("\n", index), source.find("\r", index)) if position >= 0),
|
|
170
|
+
default=len(source),
|
|
171
|
+
)
|
|
172
|
+
index = newline
|
|
173
|
+
continue
|
|
174
|
+
if char in "\"'":
|
|
175
|
+
delimiter = char * 3
|
|
176
|
+
if source.startswith(delimiter, index):
|
|
177
|
+
quote = delimiter
|
|
178
|
+
index += 3
|
|
179
|
+
else:
|
|
180
|
+
quote = char
|
|
181
|
+
index += 1
|
|
182
|
+
continue
|
|
183
|
+
if char in "[{":
|
|
184
|
+
depth += 1
|
|
185
|
+
if depth > max_depth:
|
|
186
|
+
_raise_limit(
|
|
187
|
+
source,
|
|
188
|
+
index,
|
|
189
|
+
f"document exceeds the {max_depth}-level nesting limit",
|
|
190
|
+
)
|
|
191
|
+
elif char in "]}" and depth:
|
|
192
|
+
depth -= 1
|
|
193
|
+
index += 1
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _table_header_end(source: str, start: int) -> int | None:
|
|
197
|
+
double = source.startswith("[[", start)
|
|
198
|
+
closing = "]]" if double else "]"
|
|
199
|
+
index = start + (2 if double else 1)
|
|
200
|
+
quote: str | None = None
|
|
201
|
+
while index < len(source) and source[index] not in "\r\n":
|
|
202
|
+
char = source[index]
|
|
203
|
+
if quote is not None:
|
|
204
|
+
if quote == '"' and char == "\\":
|
|
205
|
+
index += 2
|
|
206
|
+
continue
|
|
207
|
+
if char == quote:
|
|
208
|
+
quote = None
|
|
209
|
+
elif char in "\"'":
|
|
210
|
+
quote = char
|
|
211
|
+
elif source.startswith(closing, index):
|
|
212
|
+
end = index + len(closing)
|
|
213
|
+
line_end = min(
|
|
214
|
+
(position for position in (source.find("\n", end), source.find("\r", end)) if position >= 0),
|
|
215
|
+
default=len(source),
|
|
216
|
+
)
|
|
217
|
+
tail = source[end:line_end]
|
|
218
|
+
if tail.strip() == "" or tail.lstrip().startswith("#"):
|
|
219
|
+
return end
|
|
220
|
+
return None
|
|
221
|
+
index += 1
|
|
222
|
+
return None
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _raise_limit(source: str, position: int, message: str) -> NoReturn:
|
|
226
|
+
line, column = _line_column(source, position)
|
|
227
|
+
raise ParseError(message, line, column, "limit-exceeded", position)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _line_column(source: str, position: int) -> tuple[int, int]:
|
|
231
|
+
prefix = source[:position]
|
|
232
|
+
last_newline = max(prefix.rfind("\n"), prefix.rfind("\r"))
|
|
233
|
+
return prefix.count("\n") + prefix.count("\r") - prefix.count("\r\n") + 1, position - last_newline
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _end_location(source: str) -> tuple[int, int]:
|
|
237
|
+
return _line_column(source, len(source))
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
from datetime import date, datetime, time, timezone, timedelta
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
from parse_toml import Document, ParseError, ParseOptions, SourceSpan, TomlValue, loads, parse
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
FIXTURES = Path(__file__).parent / "fixtures"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def test_document_retains_source_and_parses_standard_types() -> None:
|
|
13
|
+
source = (FIXTURES / "config.toml").read_text()
|
|
14
|
+
|
|
15
|
+
document = parse(source)
|
|
16
|
+
|
|
17
|
+
assert isinstance(document, Document)
|
|
18
|
+
assert document.value["title"] == "TOML Example"
|
|
19
|
+
owner = document.value["owner"]
|
|
20
|
+
assert isinstance(owner, dict)
|
|
21
|
+
assert owner["name"] == "Tom Preston-Werner"
|
|
22
|
+
assert owner["dob"] == datetime(1979, 5, 27, 7, 32, tzinfo=timezone(timedelta(hours=-8)))
|
|
23
|
+
database = document.value["database"]
|
|
24
|
+
assert isinstance(database, dict)
|
|
25
|
+
assert database["enabled"] is True
|
|
26
|
+
assert database["ports"] == [8000, 8001, 8002]
|
|
27
|
+
assert document.source == source
|
|
28
|
+
assert document.to_toml() == source
|
|
29
|
+
assert document.span == SourceSpan(0, len(source), 1, 1, source.count("\n") + 1, 1)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def test_toml_10_values_and_table_forms() -> None:
|
|
33
|
+
value = loads(
|
|
34
|
+
'quoted."key" = "value"\n'
|
|
35
|
+
"numbers = [+99, 5_349_221, 0xDEAD_BEEF, 0o755, 0b1101]\n"
|
|
36
|
+
"special = [inf, -inf, nan]\n"
|
|
37
|
+
"date = 1979-05-27\n"
|
|
38
|
+
"time = 07:32:00.123\n"
|
|
39
|
+
"local_datetime = 1979-05-27T07:32:00\n"
|
|
40
|
+
'inline = { name = "Ada", active = true }\n'
|
|
41
|
+
"[[products]]\nname = 'Hammer'\n"
|
|
42
|
+
"[[products]]\nname = 'Nail'\n"
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
assert value["quoted"] == {"key": "value"}
|
|
46
|
+
assert value["numbers"] == [99, 5_349_221, 0xDEAD_BEEF, 0o755, 0b1101]
|
|
47
|
+
assert value["special"][0] == float("inf")
|
|
48
|
+
assert value["special"][1] == float("-inf")
|
|
49
|
+
assert value["special"][2] != value["special"][2]
|
|
50
|
+
assert value["date"] == date(1979, 5, 27)
|
|
51
|
+
assert value["time"] == time(7, 32, 0, 123000)
|
|
52
|
+
assert value["local_datetime"] == datetime(1979, 5, 27, 7, 32)
|
|
53
|
+
assert value["inline"] == {"name": "Ada", "active": True}
|
|
54
|
+
assert value["products"] == [{"name": "Hammer"}, {"name": "Nail"}]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_loads_returns_typed_python_values() -> None:
|
|
58
|
+
value: dict[str, TomlValue] = loads('message = "hello"\ncount = 3\n')
|
|
59
|
+
|
|
60
|
+
assert value == {"message": "hello", "count": 3}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@pytest.mark.parametrize(
|
|
64
|
+
"source",
|
|
65
|
+
[
|
|
66
|
+
"answer = 1\nanswer = 2\n",
|
|
67
|
+
"answer = [1, 2\n",
|
|
68
|
+
'answer = "unterminated\n',
|
|
69
|
+
"[table]\nkey = 1\n[table]\nother = 2\n",
|
|
70
|
+
"value = 01\n",
|
|
71
|
+
],
|
|
72
|
+
)
|
|
73
|
+
def test_invalid_toml_fails_with_source_location(source: str) -> None:
|
|
74
|
+
with pytest.raises(ParseError) as error:
|
|
75
|
+
parse(source)
|
|
76
|
+
|
|
77
|
+
assert error.value.line >= 1
|
|
78
|
+
assert error.value.column >= 1
|
|
79
|
+
assert error.value.code == "invalid-toml"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def test_errors_retain_tomllib_position() -> None:
|
|
83
|
+
with pytest.raises(ParseError) as error:
|
|
84
|
+
parse("good = 1\nbad = [\n")
|
|
85
|
+
|
|
86
|
+
assert error.value.line == 3
|
|
87
|
+
assert error.value.column == 1
|
|
88
|
+
assert error.value.position == len("good = 1\nbad = [\n")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def test_resource_limits_are_enforced() -> None:
|
|
92
|
+
with pytest.raises(ParseError, match="character limit") as source_error:
|
|
93
|
+
parse("long = true", options=ParseOptions(max_characters=4))
|
|
94
|
+
assert source_error.value.code == "limit-exceeded"
|
|
95
|
+
|
|
96
|
+
with pytest.raises(ParseError, match="node limit") as node_error:
|
|
97
|
+
parse("values = [1, 2]", options=ParseOptions(max_nodes=2))
|
|
98
|
+
assert node_error.value.code == "limit-exceeded"
|
|
99
|
+
|
|
100
|
+
with pytest.raises(ParseError, match="nesting limit") as depth_error:
|
|
101
|
+
parse("values = [[[1]]]", options=ParseOptions(max_depth=2))
|
|
102
|
+
assert depth_error.value.code == "limit-exceeded"
|
|
103
|
+
|
|
104
|
+
with pytest.raises(ParseError, match="nesting limit"):
|
|
105
|
+
parse("values = [[]]", options=ParseOptions(max_depth=1))
|
|
106
|
+
|
|
107
|
+
with pytest.raises(ParseError, match="nesting limit"):
|
|
108
|
+
parse("[first.second.third]\nvalue = 1", options=ParseOptions(max_depth=2))
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def test_table_headers_do_not_count_as_value_nesting() -> None:
|
|
112
|
+
assert loads("[table]\nvalue = 1\n", options=ParseOptions(max_depth=1)) == {
|
|
113
|
+
"table": {"value": 1}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def test_empty_document_and_invalid_input_type() -> None:
|
|
118
|
+
assert loads("") == {}
|
|
119
|
+
with pytest.raises(TypeError, match="source must be str"):
|
|
120
|
+
parse(b"key = 1") # type: ignore[arg-type]
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@pytest.mark.parametrize(
|
|
124
|
+
("field", "value"),
|
|
125
|
+
[
|
|
126
|
+
("max_characters", 0),
|
|
127
|
+
("max_nodes", 0),
|
|
128
|
+
("max_depth", 0),
|
|
129
|
+
],
|
|
130
|
+
)
|
|
131
|
+
def test_parse_options_require_positive_limits(field: str, value: int) -> None:
|
|
132
|
+
with pytest.raises(ValueError, match=field):
|
|
133
|
+
ParseOptions(**{field: value})
|