This is an automated email from the ASF dual-hosted git repository.
Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git
The following commit(s) were added to refs/heads/main by this push:
new 5f23a69ac7 feat(bindings/python): generate ListOptions from core
(#9332)
5f23a69ac7 is described below
commit 5f23a69ac71c583efbacf7751a73513a37fb18ee
Author: Chitral Verma <[email protected]>
AuthorDate: Sat Nov 28 21:05:27 2026 +0530
feat(bindings/python): generate ListOptions from core (#9332)
* feat(bindings/python): generate ListOptions from core
Render the ListOptions pyclass, its FromPyObject impl, and its conversion
to core into bindings/python/src/options/generated.rs from
core/core/src/types/options.rs, using the shared core options parser and
a table in dev/src/generate/python.rs. The other option classes stay
hand-written, and options.py and the stubs are unchanged.
Signed-off-by: Chitral Verma <[email protected]>
* feat(bindings/python): take ListOptions docstrings from core
Render the ListOptions class and field docstrings from core's full doc
comments instead of keeping Python copies in the table, as the Node.js
ListOptions generator does. Rustdoc links become plain code spans,
because Python documentation cannot resolve Rust paths. A missing core
doc comment, or a doc line with a character a docstring must escape,
fails generation.
Only docstring text changes in generated.rs, options.py and
_opendal.pyi. The frozen-surface tests keep main's names, types, order
and conversion, and pin the docstrings to core's text.
Signed-off-by: Chitral Verma <[email protected]>
* fix(bindings/python): name ListOptions capabilities as Python attributes
Render code spans that name a core capability in the generated ListOptions
docstrings as the Python attribute, e.g. `Capability.list_with_start_after`.
Keyword arguments keep their core names, so field spans stay unchanged.
Also cover a kind change of start_after to another supported kind.
Signed-off-by: Chitral Verma <[email protected]>
* fix(bindings/python): write ListOptions docs for Python callers
- Name `opendal.exceptions.Unsupported` and the `op.capability()` check
for each option, and drop core sentences that name a Rust layer.
- Render any core doc text, including quotes and backslashes, as a
docstring that Python reads back unchanged.
- Check field names, types, and the named checks and exceptions instead
of pinning core's wording; parse `options.py` with Python's `ast`.
- Describe `limit` on `list` and `scan` as a per-request hint.
Signed-off-by: Chitral Verma <[email protected]>
* fix(bindings/python): keep ListOptions docstrings through just fmt
Ruff's D301 fix, which `just fmt` applies, adds an `r` prefix to a
docstring that holds a backslash escape, which changes the text Python
reads. `ruff format` also separates a leading `"` from the opening
quotes, which D210 then rejects.
The options.py generator now writes a backslash as \u005c and a quote
that would join the surrounding quotes as \u0022, which D301 accepts.
postprocess_stubs.py rewrites the escapes that pyo3-introspection writes
into the stubs the same way. ruff.toml exempts options.py from E501,
like the other generated files that copy core docs.
The doc rewrite test now takes each field's capability from the
generated docs, so either rustdoc markup in core passes.
Signed-off-by: Chitral Verma <[email protected]>
---------
Signed-off-by: Chitral Verma <[email protected]>
---
bindings/python/python/opendal/_opendal.pyi | 12 +-
bindings/python/python/opendal/operator.pyi | 20 +-
bindings/python/python/opendal/options.py | 34 +-
bindings/python/ruff.toml | 1 +
bindings/python/scripts/postprocess_stubs.py | 70 +-
bindings/python/src/operator.rs | 20 +-
bindings/python/src/options.rs | 48 +-
bindings/python/src/options/generated.rs | 89 ++
bindings/python/tests/test_stub_docstrings.py | 111 +++
dev/src/generate/options.rs | 5 +-
dev/src/generate/python.rs | 1241 ++++++++++++++++++++++++-
dev/src/generate/python/options_rs.j2 | 66 ++
12 files changed, 1632 insertions(+), 85 deletions(-)
diff --git a/bindings/python/python/opendal/_opendal.pyi
b/bindings/python/python/opendal/_opendal.pyi
index 9996ed5397..bfae3927b3 100644
--- a/bindings/python/python/opendal/_opendal.pyi
+++ b/bindings/python/python/opendal/_opendal.pyi
@@ -50,7 +50,17 @@ class DeleteOptions:
@final
class ListOptions:
- """Options for `list` operations."""
+ """
+ Options for list operations.
+
+ # Groups
+ - Traversal: `recursive`.
+ - Pagination: `limit`, `start_after`.
+ - Versioning: `versions`, `deleted`.
+
+ The operation fails with `opendal.exceptions.Unsupported` when an option
+ requires a capability that the operator lacks.
+ """
@final
class ReadOptions:
diff --git a/bindings/python/python/opendal/operator.pyi
b/bindings/python/python/opendal/operator.pyi
index 331814e9ab..798dd7d8b3 100644
--- a/bindings/python/python/opendal/operator.pyi
+++ b/bindings/python/python/opendal/operator.pyi
@@ -322,7 +322,10 @@ class AsyncOperator:
path : str
The path to the directory.
limit : int, optional
- The maximum number of entries to return.
+ The maximum number of entries the service returns per request, as
+ a hint. It does not cap the total: iteration continues across
+ pages until every entry is returned. Some services, such as fs
+ and memory, ignore it.
start_after : str, optional
The entry to start after.
recursive : bool, optional
@@ -680,7 +683,10 @@ class AsyncOperator:
path : str
The path to the directory.
limit : int, optional
- The maximum number of entries to return.
+ The maximum number of entries the service returns per request, as
+ a hint. It does not cap the total: iteration continues across
+ pages until every entry is returned. Some services, such as fs
+ and memory, ignore it.
start_after : str, optional
The entry to start after.
versions : bool, optional
@@ -1083,7 +1089,10 @@ class Operator:
path : str
The path to the directory.
limit : int, optional
- The maximum number of entries to return.
+ The maximum number of entries the service returns per request, as
+ a hint. It does not cap the total: iteration continues across
+ pages until every entry is returned. Some services, such as fs
+ and memory, ignore it.
start_after : str, optional
The entry to start after.
recursive : bool, optional
@@ -1266,7 +1275,10 @@ class Operator:
path : str
The path to the directory.
limit : int, optional
- The maximum number of entries to return.
+ The maximum number of entries the service returns per request, as
+ a hint. It does not cap the total: iteration continues across
+ pages until every entry is returned. Some services, such as fs
+ and memory, ignore it.
start_after : str, optional
The entry to start after.
versions : bool, optional
diff --git a/bindings/python/python/opendal/options.py
b/bindings/python/python/opendal/options.py
index 937a20e91f..ef8a473505 100644
--- a/bindings/python/python/opendal/options.py
+++ b/bindings/python/python/opendal/options.py
@@ -116,18 +116,40 @@ class WriteKwargs(TypedDict, total=False):
class ListKwargs(TypedDict, total=False):
- """Options for `list` operations."""
+ """Options for list operations.
+
+ # Groups
+ - Traversal: `recursive`.
+ - Pagination: `limit`, `start_after`.
+ - Versioning: `versions`, `deleted`.
+
+ The operation fails with `opendal.exceptions.Unsupported` when an option
+ requires a capability that the operator lacks.
+ """
limit: int
- """The maximum number of entries to return."""
+ """Maximum results per request (backend hint) to control memory and
throttling."""
start_after: str
- """The entry to start after."""
+ """Start listing after this key, excluding the key itself.
+
+ Setting this requires `op.capability().list_with_start_after`.
+ """
recursive: bool
- """Whether to list recursively."""
+ """Whether to list recursively under the prefix; default `false`.
+
+ Setting this option to `true` requires the operator's effective
+ `op.capability().list_with_recursive` capability.
+ """
versions: bool
- """Whether to list versions."""
+ """Include object versions; default `false`.
+
+ Requires `op.capability().list_with_versions`.
+ """
deleted: bool
- """Whether to list deleted entries."""
+ """Include delete markers; default `false`.
+
+ Requires `op.capability().list_with_deleted`.
+ """
class StatKwargs(TypedDict, total=False):
diff --git a/bindings/python/ruff.toml b/bindings/python/ruff.toml
index 5a8799f444..601607a8ba 100644
--- a/bindings/python/ruff.toml
+++ b/bindings/python/ruff.toml
@@ -86,4 +86,5 @@ known-first-party = ["opendal"]
# Generated files; docstrings are copied verbatim from Rust and can be long.
"python/opendal/capability.pyi" = ["E501"]
"python/opendal/config.py" = ["E501"]
+"python/opendal/options.py" = ["E501"]
"tests/*" = ["D101", "D100", "D103", "ANN201", "ANN001"]
diff --git a/bindings/python/scripts/postprocess_stubs.py
b/bindings/python/scripts/postprocess_stubs.py
index cf5fa6fbfb..98b37d0c84 100644
--- a/bindings/python/scripts/postprocess_stubs.py
+++ b/bindings/python/scripts/postprocess_stubs.py
@@ -20,7 +20,7 @@
``maturin`` writes them under ``opendal/_opendal/``, but the public API and the
classes' ``module=`` use ``opendal.<name>``; type checkers resolve from the
filesystem, so the stubs must live at ``opendal/<name>.pyi``. This relocates
-them and applies two temporary fixups (until PyO3 introspection covers them):
+them and applies three temporary fixups (until PyO3 introspection covers them):
1. Inject the imports our forward-ref string annotations need (PyO3 writes the
annotation but not the import). Restore the `ChecksumAlgorithm` alias on
@@ -28,10 +28,13 @@ them and applies two temporary fixups (until PyO3
introspection covers them):
2. Replace ``exceptions.pyi`` with a hand-written stub while the generated one
is
incomplete -- ``create_exception!`` types are not introspectable yet, so
PyO3
emits only ``__getattr__``. When that changes, the stub is kept as-is.
+3. Rewrite docstring escapes so that ``just fmt`` keeps the docstring text (see
+ ``escape_docstrings``).
"""
from __future__ import annotations
+import ast
from pathlib import Path
PKG = Path(__file__).resolve().parent.parent / "python" / "opendal"
@@ -110,10 +113,71 @@ def pin_disjoint_base_import(text: str) -> str:
return "".join(lines)
+def escape_docstring(doc: str) -> str:
+ r"""Return the source between the quotes of a docstring that reads as
``doc``.
+
+ A backslash becomes ``\u005c``, and an ASCII control character other than a
+ newline becomes its ``\u00XX`` escape. A ``"`` becomes ``\u0022`` when it
+ would join the quotes around it: a leading ``"``, every third ``"`` in a
+ row, and the quotes right before the closing quotes. Ruff's D301 accepts
+ these escapes. ``dev/src/generate/python.rs`` escapes backslashes and
+ quotes in the docstrings of ``options.py`` the same way.
+ """
+ body = doc.rstrip('"')
+ out = []
+ run = 0
+ for at, c in enumerate(body):
+ if c == "\\":
+ out.append(r"\u005c")
+ elif c == '"' and (at == 0 or run == 2):
+ out.append(r"\u0022")
+ elif c != "\n" and c.isascii() and not c.isprintable():
+ out.append(rf"\u{ord(c):04x}")
+ else:
+ out.append(c)
+ run = run + 1 if c == '"' and at > 0 and run < 2 else 0
+ out.append(r"\u0022" * (len(doc) - len(body)))
+ return "".join(out)
+
+
+def escape_docstrings(text: str) -> str:
+ r"""Rewrite each docstring in ``text`` whose source holds a backslash.
+
+ PyO3 writes a backslash in a docstring as ``\\``, a control character as an
+ escape such as ``\t``, and every third ``"`` in a row as ``\"``. Ruff's
D301
+ fix, which ``just fmt`` applies, adds an ``r`` prefix to such a docstring,
+ so Python reads different text. The rewritten docstring holds the same
+ text with escapes that D301 accepts (see ``escape_docstring``).
+ """
+ data = text.encode()
+ starts = [0]
+ for line in data.splitlines(keepends=True):
+ starts.append(starts[-1] + len(line))
+ edits = []
+ for node in ast.walk(ast.parse(text)):
+ if not (
+ isinstance(node, ast.Expr)
+ and isinstance(node.value, ast.Constant)
+ and isinstance(node.value.value, str)
+ ):
+ continue
+ start = starts[node.lineno - 1] + node.col_offset
+ end = starts[node.end_lineno - 1] + node.end_col_offset
+ source = data[start:end]
+ if b"\\" in source and source.startswith(b'"""'):
+ quoted = '"""' + escape_docstring(node.value.value) + '"""'
+ edits.append((start, end, quoted.encode()))
+ for start, end, quoted in sorted(edits, reverse=True):
+ data = data[:start] + quoted + data[end:]
+ return data.decode()
+
+
def relocate() -> None:
"""Move the stubs to the public ``opendal/<name>.pyi`` paths."""
for name in SUBMODULES:
- text = pin_disjoint_base_import((GEN / f"{name}.pyi").read_text())
+ text = escape_docstrings(
+ pin_disjoint_base_import((GEN / f"{name}.pyi").read_text())
+ )
if name == "types":
inferred = "def checksum(self, /) -> tuple[str, bytes] | None:"
if inferred not in text:
@@ -126,7 +190,7 @@ def relocate() -> None:
# Stub for the ``opendal/_opendal.*.so`` extension itself.
(PKG / "_opendal.pyi").write_text(
- pin_disjoint_base_import((GEN / "__init__.pyi").read_text())
+ escape_docstrings(pin_disjoint_base_import((GEN /
"__init__.pyi").read_text()))
)
for child in GEN.iterdir():
diff --git a/bindings/python/src/operator.rs b/bindings/python/src/operator.rs
index ccbfba373b..45555c399e 100644
--- a/bindings/python/src/operator.rs
+++ b/bindings/python/src/operator.rs
@@ -1103,7 +1103,10 @@ impl Operator {
/// path : str
/// The path to the directory.
/// limit : int, optional
- /// The maximum number of entries to return.
+ /// The maximum number of entries the service returns per request, as
+ /// a hint. It does not cap the total: iteration continues across
+ /// pages until every entry is returned. Some services, such as fs
+ /// and memory, ignore it.
/// start_after : str, optional
/// The entry to start after.
/// recursive : bool, optional
@@ -1163,7 +1166,10 @@ impl Operator {
/// path : str
/// The path to the directory.
/// limit : int, optional
- /// The maximum number of entries to return.
+ /// The maximum number of entries the service returns per request, as
+ /// a hint. It does not cap the total: iteration continues across
+ /// pages until every entry is returned. Some services, such as fs
+ /// and memory, ignore it.
/// start_after : str, optional
/// The entry to start after.
/// versions : bool, optional
@@ -2088,7 +2094,10 @@ impl AsyncOperator {
/// path : str
/// The path to the directory.
/// limit : int, optional
- /// The maximum number of entries to return.
+ /// The maximum number of entries the service returns per request, as
+ /// a hint. It does not cap the total: iteration continues across
+ /// pages until every entry is returned. Some services, such as fs
+ /// and memory, ignore it.
/// start_after : str, optional
/// The entry to start after.
/// recursive : bool, optional
@@ -2151,7 +2160,10 @@ impl AsyncOperator {
/// path : str
/// The path to the directory.
/// limit : int, optional
- /// The maximum number of entries to return.
+ /// The maximum number of entries the service returns per request, as
+ /// a hint. It does not cap the total: iteration continues across
+ /// pages until every entry is returned. Some services, such as fs
+ /// and memory, ignore it.
/// start_after : str, optional
/// The entry to start after.
/// versions : bool, optional
diff --git a/bindings/python/src/options.rs b/bindings/python/src/options.rs
index 02fe333c3a..f3c7027d93 100644
--- a/bindings/python/src/options.rs
+++ b/bindings/python/src/options.rs
@@ -30,6 +30,9 @@ use pyo3::types::PyDict;
use pyo3::types::PyDictMethods;
use std::collections::HashMap;
+mod generated;
+pub use generated::*;
+
/// Options for `read` operations.
#[pyclass(module = "opendal")]
#[derive(Default)]
@@ -379,51 +382,6 @@ impl From<WriteOptions> for ocore::options::WriteOptions {
}
}
-/// Options for `list` operations.
-#[pyclass(module = "opendal")]
-#[derive(Default, Debug)]
-pub struct ListOptions {
- /// The maximum number of entries to return.
- pub limit: Option<usize>,
- /// The entry to start after.
- pub start_after: Option<String>,
- /// Whether to list recursively.
- pub recursive: Option<bool>,
- /// Whether to list versions.
- pub versions: Option<bool>,
- /// Whether to list deleted entries.
- pub deleted: Option<bool>,
-}
-
-impl<'a, 'py> FromPyObject<'a, 'py> for ListOptions {
- type Error = PyErr;
-
- fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
- let dict = downcast_kwargs(obj)?;
-
- Ok(Self {
- limit: extract_optional(&dict, "limit")?,
- start_after: extract_optional(&dict, "start_after")?,
- recursive: extract_optional(&dict, "recursive")?,
- versions: extract_optional(&dict, "versions")?,
- deleted: extract_optional(&dict, "deleted")?,
- })
- }
-}
-
-impl From<ListOptions> for ocore::options::ListOptions {
- fn from(opts: ListOptions) -> Self {
- Self {
- limit: opts.limit,
- start_after: opts.start_after,
- recursive: opts.recursive.unwrap_or(false),
- versions: opts.versions.unwrap_or(false),
- deleted: opts.deleted.unwrap_or(false),
- ..Default::default()
- }
- }
-}
-
/// Options for `stat` operations.
#[pyclass(module = "opendal")]
#[derive(Default, Debug)]
diff --git a/bindings/python/src/options/generated.rs
b/bindings/python/src/options/generated.rs
new file mode 100644
index 0000000000..94f5f4f7d4
--- /dev/null
+++ b/bindings/python/src/options/generated.rs
@@ -0,0 +1,89 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// DO NOT EDIT IT MANUALLY. This file is generated by
opendal/dev/src/generate/python.rs.
+
+use super::downcast_kwargs;
+use super::extract_optional;
+use opendal as ocore;
+use pyo3::Borrowed;
+use pyo3::FromPyObject;
+use pyo3::PyAny;
+use pyo3::PyErr;
+use pyo3::pyclass;
+
+/// Options for list operations.
+///
+/// # Groups
+/// - Traversal: `recursive`.
+/// - Pagination: `limit`, `start_after`.
+/// - Versioning: `versions`, `deleted`.
+///
+/// The operation fails with `opendal.exceptions.Unsupported` when an option
+/// requires a capability that the operator lacks.
+#[pyclass(module = "opendal")]
+#[derive(Default, Debug)]
+pub struct ListOptions {
+ /// Maximum results per request (backend hint) to control memory and
throttling.
+ pub limit: Option<usize>,
+ /// Start listing after this key, excluding the key itself.
+ ///
+ /// Setting this requires `op.capability().list_with_start_after`.
+ pub start_after: Option<String>,
+ /// Whether to list recursively under the prefix; default `false`.
+ ///
+ /// Setting this option to `true` requires the operator's effective
+ /// `op.capability().list_with_recursive` capability.
+ pub recursive: Option<bool>,
+ /// Include object versions; default `false`.
+ ///
+ /// Requires `op.capability().list_with_versions`.
+ pub versions: Option<bool>,
+ /// Include delete markers; default `false`.
+ ///
+ /// Requires `op.capability().list_with_deleted`.
+ pub deleted: Option<bool>,
+}
+
+impl<'a, 'py> FromPyObject<'a, 'py> for ListOptions {
+ type Error = PyErr;
+
+ fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
+ let dict = downcast_kwargs(obj)?;
+
+ Ok(Self {
+ limit: extract_optional(&dict, "limit")?,
+ start_after: extract_optional(&dict, "start_after")?,
+ recursive: extract_optional(&dict, "recursive")?,
+ versions: extract_optional(&dict, "versions")?,
+ deleted: extract_optional(&dict, "deleted")?,
+ })
+ }
+}
+
+impl From<ListOptions> for ocore::options::ListOptions {
+ fn from(opts: ListOptions) -> Self {
+ Self {
+ limit: opts.limit,
+ start_after: opts.start_after,
+ recursive: opts.recursive.unwrap_or(false),
+ versions: opts.versions.unwrap_or(false),
+ deleted: opts.deleted.unwrap_or(false),
+ glob: None,
+ }
+ }
+}
diff --git a/bindings/python/tests/test_stub_docstrings.py
b/bindings/python/tests/test_stub_docstrings.py
new file mode 100644
index 0000000000..273a09498d
--- /dev/null
+++ b/bindings/python/tests/test_stub_docstrings.py
@@ -0,0 +1,111 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Docstrings with quotes and backslashes keep their text through `just
fmt`."""
+
+import ast
+import importlib.util
+import inspect
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+BINDING = Path(__file__).resolve().parents[1]
+
+_spec = importlib.util.spec_from_file_location(
+ "postprocess_stubs", BINDING / "scripts" / "postprocess_stubs.py"
+)
+postprocess_stubs = importlib.util.module_from_spec(_spec)
+_spec.loader.exec_module(postprocess_stubs)
+
+# A core `ListOptions` doc with quotes and backslashes.
+DOC = '"Options" for list operations, with \\d, \\\\ and """ inside.\n\nMore
text.'
+
+
+def just_fmt(tmp_path: Path, name: str, source: str) -> str:
+ """Run the ruff steps of `just fmt` on `source` at the binding path
`name`."""
+ shutil.copy(BINDING / "ruff.toml", tmp_path / "ruff.toml")
+ (tmp_path / name).parent.mkdir(parents=True)
+ (tmp_path / name).write_text(source)
+ ruff = [sys.executable, "-m", "ruff"]
+ subprocess.run([*ruff, "format", "--quiet", name], cwd=tmp_path,
check=True)
+ subprocess.run(
+ [*ruff, "check", "--unsafe-fixes", "--fix", "--silent", name],
+ cwd=tmp_path,
+ check=True,
+ )
+ return (tmp_path / name).read_text()
+
+
+def docstring(source: str) -> str:
+ """Return the cleaned docstring of the only class in `source`."""
+ (cls,) = (n for n in ast.parse(source).body if isinstance(n, ast.ClassDef))
+ return inspect.cleandoc(ast.get_docstring(cls, clean=False))
+
+
+def test_stub_docstring_survives_fmt(tmp_path):
+ # `_opendal.pyi` as pyo3-introspection 0.30.1 writes the pyclass doc.
+ stub = (
+ '"""Stub."""\n\n'
+ "from typing import final\n\n"
+ "@final\n"
+ "class ListOptions:\n"
+ ' """\n'
+ ' "Options" for list operations, with \\\\d, \\\\\\\\ and ""\\"
inside.\n'
+ "\n"
+ " More text.\n"
+ ' """\n'
+ )
+ assert docstring(stub) == DOC
+ escaped = postprocess_stubs.escape_docstrings(stub)
+ assert docstring(escaped) == DOC
+ assert docstring(just_fmt(tmp_path, "python/opendal/_opendal.pyi",
escaped)) == DOC
+
+
+def test_options_docstring_survives_fmt(tmp_path):
+ # The first line is `dev/src/generate/python.rs` output, which
+ # `test_list_options_survive_any_core_doc` checks.
+ options = (
+ '"""Options."""\n\n'
+ "from typing import TypedDict\n\n\n"
+ "class ListKwargs(TypedDict, total=False):\n"
+ ' """\\u0022Options" for list operations, with \\u005cd,
\\u005c\\u005c'
+ ' and ""\\u0022 inside.\n'
+ "\n"
+ " More text.\n"
+ ' """\n'
+ )
+ assert docstring(options) == DOC
+ formatted = just_fmt(tmp_path, "python/opendal/options.py", options)
+ assert formatted == options
+ assert docstring(formatted) == DOC
+
+
+def test_escape_docstring_reads_back():
+ for doc in [
+ DOC,
+ '"',
+ '""""',
+ 'ends with ""',
+ "tab\tand\x7f",
+ "plain text",
+ ]:
+ source = '"""' + postprocess_stubs.escape_docstring(doc) + '"""'
+ assert ast.literal_eval(source) == doc
+ assert "\\" not in source.replace("\\u", "")
+ assert not source.startswith('""""')
diff --git a/dev/src/generate/options.rs b/dev/src/generate/options.rs
index c7b39bcdaa..e178ba080f 100644
--- a/dev/src/generate/options.rs
+++ b/dev/src/generate/options.rs
@@ -199,7 +199,6 @@ mod tests {
[
"ReadOptions",
"WriteOptions",
- "ListOptions",
"StatOptions",
"CopyOptions",
"RenameOptions",
@@ -229,7 +228,7 @@ mod tests {
"The user metadata to set on the file."
);
- for option in [&options[4], &options[5]] {
+ for option in [&options[3], &options[4]] {
assert!(
option
.fields
@@ -240,7 +239,7 @@ mod tests {
);
}
- let delete = &options[6];
+ let delete = &options[5];
assert_eq!(delete.fields.len(), 3);
assert_eq!(
delete.fields[1].doc,
diff --git a/dev/src/generate/python.rs b/dev/src/generate/python.rs
index d469948276..aba55caaa4 100644
--- a/dev/src/generate/python.rs
+++ b/dev/src/generate/python.rs
@@ -15,7 +15,8 @@
// specific language governing permissions and limitations
// under the License.
-use crate::generate::capability;
+use crate::generate::capability::{self, CapabilityField};
+use crate::generate::core_options::{self, OptionKind, OptionsStruct};
use crate::generate::metadata::{self, MetadataKind};
use crate::generate::options;
use crate::generate::parser::{Config, ConfigType, Services, service_feature,
sorted_services};
@@ -23,7 +24,7 @@ use anyhow::{Context, Result, bail};
use minijinja::value::Serde;
use minijinja::{Environment, context};
use serde::{Deserialize, Serialize};
-use std::collections::HashSet;
+use std::collections::{BTreeMap, HashSet};
use std::fs;
use std::path::Path;
use std::path::PathBuf;
@@ -202,8 +203,10 @@ pub fn generate(workspace_dir: PathBuf, services:
Services) -> Result<()> {
}
fs::write(output, rendered)?;
- // Generate the typed operator options TypedDicts (Python).
- generate_options_py(&workspace_dir)?;
+ // Generate the operator options that come from core (Rust), then the
+ // typed operator options TypedDicts (Python).
+ let generated = generate_options_rs(&workspace_dir)?;
+ generate_options_py(&workspace_dir, &generated)?;
// Generate the `Capability` pyclass (Rust) from core.
generate_capability(&workspace_dir)?;
@@ -626,6 +629,369 @@ const PYTHON_LICENSE_HEADER: &str = "\
# under the License.
";
+/// A Python options class generated from the core options struct of the
+/// same name. The class and field docstrings come from the core doc comments.
+struct PyOptions {
+ /// The class name, e.g. `ListOptions`.
+ name: &'static str,
+ /// The keyword arguments in their Python order: the name, which is also
+ /// the core field and the Rust field it sets, and the kind that core
+ /// field must have. A core field that no keyword argument sets is not
+ /// exposed and keeps its default.
+ options: &'static [(&'static str, OptionKind)],
+}
+
+/// The Python options classes generated from `core/core/src/types/options.rs`.
+/// The other classes in `bindings/python/src/options.rs` are hand-written.
+const GENERATED_OPTIONS: &[PyOptions] = &[PyOptions {
+ name: "ListOptions",
+ options: &[
+ ("limit", OptionKind::OptionUsize),
+ ("start_after", OptionKind::OptionString),
+ ("recursive", OptionKind::Bool),
+ ("versions", OptionKind::Bool),
+ ("deleted", OptionKind::Bool),
+ ],
+}];
+
+/// The class order of `options.py`, which hand-written and generated classes
+/// share.
+const OPTIONS_PY_ORDER: &[&str] = &[
+ "ReadOptions",
+ "WriteOptions",
+ "ListOptions",
+ "StatOptions",
+ "CopyOptions",
+ "RenameOptions",
+ "DeleteOptions",
+];
+
+/// Render model of one generated Python options class.
+#[derive(Debug, Serialize)]
+struct PyClass {
+ name: &'static str,
+ /// The core doc comment, one entry per line.
+ doc: Vec<String>,
+ fields: Vec<PyField>,
+ /// Every field of the core struct in core order, with the expression
+ /// that sets it.
+ conversion: Vec<ConvertField>,
+}
+
+#[derive(Debug, Serialize)]
+struct PyField {
+ name: &'static str,
+ kind: OptionKind,
+ /// The core doc comment, one entry per line.
+ doc: Vec<String>,
+ rust_type: &'static str,
+}
+
+#[derive(Debug, Serialize)]
+struct ConvertField {
+ name: String,
+ expr: String,
+}
+
+/// The Rust field type of a keyword argument and its `options.py` type, for
+/// the core kinds that generated classes expose so far.
+fn option_types(kind: OptionKind) -> Option<(&'static str,
options::OptionType)> {
+ Some(match kind {
+ OptionKind::OptionString => ("Option<String>",
options::OptionType::Str),
+ OptionKind::OptionUsize => ("Option<usize>", options::OptionType::Int),
+ OptionKind::Bool => ("Option<bool>", options::OptionType::Bool),
+ _ => return None,
+ })
+}
+
+/// The value of a core field that Python does not expose. Every core options
+/// struct derives `Default`, so this equals the field's default.
+fn default_expr(kind: OptionKind) -> &'static str {
+ match kind {
+ OptionKind::Bool => "false",
+ OptionKind::Usize => "0",
+ OptionKind::BytesRange => "Default::default()",
+ _ => "None",
+ }
+}
+
+/// The Python names of the core items that generated docstrings reference.
+struct PyNames {
+ /// The core capabilities; the Python `Capability` has an attribute of
+ /// the same name for each.
+ capabilities: Vec<CapabilityField>,
+ /// Each core `ErrorKind` variant and the `opendal.exceptions` class that
+ /// `bindings/python/src/errors.rs` raises for it.
+ exceptions: BTreeMap<String, String>,
+}
+
+impl PyNames {
+ fn parse(workspace_dir: &Path) -> Result<Self> {
+ let capabilities =
+
capability::parse(&workspace_dir.join("core/core/src/types/capability.rs"))?;
+ let errors = workspace_dir.join("bindings/python/src/errors.rs");
+ // `format_pyerr_impl` maps each kind with a line such as
+ // `ocore::ErrorKind::Unsupported => Unsupported::new_err(e),`.
+ let exceptions: BTreeMap<String, String> = fs::read_to_string(&errors)?
+ .lines()
+ .filter_map(|line| {
+ let (kind, class) = line
+ .trim()
+ .strip_prefix("ocore::ErrorKind::")?
+ .split_once(" => ")?;
+ Some((
+ kind.to_string(),
+ class.strip_suffix("::new_err(e),")?.to_string(),
+ ))
+ })
+ .collect();
+ if !exceptions.contains_key("Unsupported") {
+ bail!(
+ "no ErrorKind to exception mapping parsed from {}",
+ errors.display()
+ );
+ }
+ Ok(Self {
+ capabilities,
+ exceptions,
+ })
+ }
+}
+
+/// The docstring of a generated class or field: the core doc comment, one
+/// entry per line, adjusted for Python callers.
+///
+/// - Rustdoc links become plain code spans, because Python documentation
+/// cannot resolve Rust paths:
``[`Capability::list_with_limit`](crate::Capability::list_with_limit)``
+/// and ``[`crate::layers::SimulateLayer`]`` keep only their code span.
+/// - Code spans that name a core capability or error kind use the Python
+/// check or exception instead (see [`py_code_span`]); other code spans stay
+/// as written.
+/// - A sentence that names a Rust layer (a `crate::layers::` code span) is
+/// dropped, because Python callers cannot install Rust layers or choose
+/// Cargo features. The capability that the same doc names, such as
+/// `op.capability().list_with_recursive`, is the check Python callers have.
+/// The rest of that paragraph is joined into one line.
+///
+/// The text is not escaped here; the renderers escape it for their output.
+fn py_doc(core_doc: &[String], item: &str, names: &PyNames) ->
Result<Vec<String>> {
+ if core_doc.iter().all(|line| line.is_empty()) {
+ bail!("core {item} has no doc comment");
+ }
+ let lines: Vec<String> = core_doc
+ .iter()
+ .map(|line| py_doc_line(line, names))
+ .collect();
+
+ let mut out = Vec::with_capacity(lines.len());
+ for paragraph in lines.split(|line| line.is_empty()) {
+ let paragraph: Vec<String> = if paragraph
+ .iter()
+ .any(|line| line.contains("`crate::layers::"))
+ {
+ let text = paragraph.join(" ");
+ let kept: Vec<&str> = sentences(&text)
+ .into_iter()
+ .filter(|sentence| !sentence.contains("`crate::layers::"))
+ .collect();
+ if kept.is_empty() {
+ Vec::new()
+ } else {
+ vec![kept.join(" ")]
+ }
+ } else {
+ paragraph.to_vec()
+ };
+ if paragraph.is_empty() {
+ continue;
+ }
+ if !out.is_empty() {
+ out.push(String::new());
+ }
+ out.extend(paragraph);
+ }
+ if out.is_empty() {
+ bail!("core {item} has no doc comment that applies to Python");
+ }
+ Ok(out)
+}
+
+/// Split prose into sentences at a `. ` that an uppercase letter or a code
+/// span follows, so `e.g. a` and `(see below).` stay inside their sentence.
+fn sentences(text: &str) -> Vec<&str> {
+ let mut sentences = Vec::new();
+ let mut start = 0;
+ for (at, _) in text.match_indices(". ") {
+ let next = text[at + 2..].chars().next();
+ if next.is_some_and(|c| c.is_ascii_uppercase() || c == '`') {
+ sentences.push(&text[start..=at]);
+ start = at + 2;
+ }
+ }
+ sentences.push(&text[start..]);
+ sentences
+}
+
+/// One doc line with rustdoc links unlinked and code spans renamed for
+/// Python (see [`py_doc`]).
+fn py_doc_line(line: &str, names: &PyNames) -> String {
+ let mut unlinked = String::with_capacity(line.len());
+ let mut rest = line;
+ while let Some(start) = rest.find("[`") {
+ let Some(len) = rest[start + 1..].find("`]") else {
+ break;
+ };
+ unlinked.push_str(&rest[..start]);
+ unlinked.push_str(&rest[start + 1..start + len + 2]);
+ rest = &rest[start + len + 3..];
+ if let Some(target) = rest.strip_prefix('(')
+ && let Some(end) = target.find(')')
+ {
+ rest = &target[end + 1..];
+ }
+ }
+ unlinked.push_str(rest);
+
+ let mut out = String::with_capacity(unlinked.len());
+ let mut rest = unlinked.as_str();
+ while let Some(start) = rest.find('`') {
+ let Some(len) = rest[start + 1..].find('`') else {
+ break;
+ };
+ let code = &rest[start + 1..start + 1 + len];
+ out.push_str(&rest[..=start]);
+ out.push_str(&py_code_span(code, names).unwrap_or_else(||
code.to_string()));
+ out.push('`');
+ rest = &rest[start + len + 2..];
+ }
+ out.push_str(rest);
+ out
+}
+
+/// The Python form of a code span that names a core capability or error
+/// kind, or `None` to keep the code span as written.
+///
+/// - `Capability::list_with_start_after` becomes
+/// `op.capability().list_with_start_after`: the `Capability` that
+/// `Operator.capability()` returns has an attribute of the same name for
+/// every core capability, so callers can check it before setting an option.
+/// - `ErrorKind::Unsupported` becomes `opendal.exceptions.Unsupported`, the
+/// exception that `bindings/python/src/errors.rs` raises for that kind.
+///
+/// Keyword arguments keep their core names, so a code span that names an
+/// options field, like `start_after`, needs no rewrite.
+fn py_code_span(code: &str, names: &PyNames) -> Option<String> {
+ let path = code.strip_prefix("crate::").unwrap_or(code);
+ if let Some(name) = path.strip_prefix("Capability::") {
+ return names
+ .capabilities
+ .iter()
+ .any(|f| f.name == name)
+ .then(|| format!("op.capability().{name}"));
+ }
+ let kind = path.strip_prefix("ErrorKind::")?;
+ let class = names.exceptions.get(kind)?;
+ Some(format!("opendal.exceptions.{class}"))
+}
+
+/// Build the render model of one generated class, checking the table against
+/// the parsed core struct.
+fn py_class(spec: &PyOptions, parsed: &[OptionsStruct], names: &PyNames) ->
Result<PyClass> {
+ let class = spec.name;
+ let Some(core) = parsed.iter().find(|options| options.name == class) else {
+ bail!("core options struct `{class}` not found");
+ };
+ if core.has_unmirrored_fields {
+ bail!("core {class} has fields the core options parser skips; Python
cannot set them");
+ }
+ let mut seen = HashSet::new();
+ for field in &core.fields {
+ if !seen.insert(field.name.as_str()) {
+ bail!("core {class} contains duplicate field `{}`", field.name);
+ }
+ }
+
+ let mut fields = Vec::with_capacity(spec.options.len());
+ for &(name, kind) in spec.options {
+ if fields.iter().any(|field: &PyField| field.name == name) {
+ bail!("Python {class} lists `{name}` twice");
+ }
+ let Some(field) = core.fields.iter().find(|field| field.name == name)
else {
+ bail!("core {class} has no field `{name}` for Python
{class}.{name}");
+ };
+ if field.kind != kind {
+ bail!(
+ "core {class}::{name} has kind {:?}; Python {class}.{name}
requires {kind:?}",
+ field.kind
+ );
+ }
+ let Some((rust_type, _)) = option_types(kind) else {
+ bail!(
+ "Python {class}.{name} is a core {kind:?}; \
+ teach dev/src/generate/python.rs about it"
+ );
+ };
+ fields.push(PyField {
+ name,
+ kind,
+ doc: py_doc(&field.doc, &format!("{class}::{name}"), names)?,
+ rust_type,
+ });
+ }
+
+ let conversion = core
+ .fields
+ .iter()
+ .map(|field| {
+ let name = &field.name;
+ let expr = match fields.iter().find(|f| f.name == name) {
+ None => default_expr(field.kind).to_string(),
+ Some(f) if f.kind == OptionKind::Bool =>
format!("opts.{name}.unwrap_or(false)"),
+ Some(_) => format!("opts.{name}"),
+ };
+ ConvertField {
+ name: name.clone(),
+ expr,
+ }
+ })
+ .collect();
+
+ Ok(PyClass {
+ name: class,
+ doc: py_doc(&core.doc, class, names)?,
+ fields,
+ conversion,
+ })
+}
+
+fn generated_classes(parsed: &[OptionsStruct], names: &PyNames) ->
Result<Vec<PyClass>> {
+ GENERATED_OPTIONS
+ .iter()
+ .map(|spec| py_class(spec, parsed, names))
+ .collect()
+}
+
+fn render_options_rs(classes: &[PyClass]) -> Result<String> {
+ let mut env = Environment::new();
+ env.add_template("options_rs", include_str!("python/options_rs.j2"))?;
+ let rendered = env
+ .get_template("options_rs")?
+ .render(context! { classes => Serde(classes) })?;
+ Ok(format!("{rendered}\n"))
+}
+
+/// Render `bindings/python/src/options/generated.rs`, the option classes
+/// generated from `core/core/src/types/options.rs`.
+fn generate_options_rs(workspace_dir: &Path) -> Result<Vec<PyClass>> {
+ let source = workspace_dir.join("core/core/src/types/options.rs");
+ let names = PyNames::parse(workspace_dir)?;
+ let classes = generated_classes(&core_options::parse(&source)?, &names)?;
+ let output =
workspace_dir.join("bindings/python/src/options/generated.rs");
+ fs::create_dir_all(output.parent().expect("output has a parent"))?;
+ fs::write(output, render_options_rs(&classes)?)?;
+ Ok(classes)
+}
+
/// Python type of an operator option field, parsed from
/// `bindings/python/src/options.rs`.
fn make_option_type(ty: options::OptionType) -> &'static str {
@@ -642,15 +1008,49 @@ fn make_option_type(ty: options::OptionType) -> &'static
str {
/// Generate `bindings/python/python/opendal/options.py`, the typed keyword
/// arguments accepted by the operator methods.
///
-/// The option fields are parsed from the `#[pyclass]` structs in
-/// `bindings/python/src/options.rs`, so the generated file stays in sync with
-/// the Rust option types.
-fn generate_options_py(workspace_dir: &Path) -> Result<()> {
+/// The option fields come from the hand-written `#[pyclass]` structs in
+/// `bindings/python/src/options.rs` and from the generated classes, so the
+/// generated file stays in sync with the Rust option types.
+fn generate_options_py(workspace_dir: &Path, generated: &[PyClass]) ->
Result<()> {
+ let output =
workspace_dir.join("bindings/python/python/opendal/options.py");
+ fs::write(output, render_options_py(workspace_dir, generated)?)?;
+ Ok(())
+}
+
+fn render_options_py(workspace_dir: &Path, generated: &[PyClass]) ->
Result<String> {
let source = workspace_dir.join("bindings/python/src/options.rs");
- let options = options::parse(&source)?;
+ let mut options = options::parse(&source)?;
if options.is_empty() {
anyhow::bail!("no option structs parsed from {}", source.display());
}
+ for class in generated {
+ options.push(options::Options {
+ name: class.name.to_string(),
+ doc: class.doc.join("\n"),
+ fields: class
+ .fields
+ .iter()
+ .map(|field| options::OptionField {
+ name: field.name.to_string(),
+ ty: option_types(field.kind)
+ .expect("generated fields have a Python type")
+ .1,
+ doc: field.doc.join("\n"),
+ })
+ .collect(),
+ });
+ }
+ let mut ordered = Vec::with_capacity(options.len());
+ for name in OPTIONS_PY_ORDER {
+ let Some(at) = options.iter().position(|opts| opts.name == *name) else
{
+ bail!("options class {name} is neither hand-written nor
generated");
+ };
+ ordered.push(options.remove(at));
+ }
+ if let Some(extra) = options.first() {
+ bail!("add {} to OPTIONS_PY_ORDER", extra.name);
+ }
+ let options = ordered;
let mut out = String::new();
out.push_str(PYTHON_LICENSE_HEADER);
@@ -677,16 +1077,16 @@ fn generate_options_py(workspace_dir: &Path) ->
Result<()> {
} else {
opts.doc.clone()
};
- out.push_str(&format!(
- "\n\nclass {kwargs}(TypedDict, total=False):\n
\"\"\"{doc}\"\"\"\n\n"
- ));
+ out.push_str(&format!("\n\nclass {kwargs}(TypedDict,
total=False):\n"));
+ push_docstring(&mut out, &doc);
+ out.push('\n');
for field in &opts.fields {
out.push_str(&format!(
" {}: {}\n",
field.name,
make_option_type(field.ty)
));
- push_field_doc(&mut out, &field.doc);
+ push_docstring(&mut out, &field.doc);
}
}
@@ -702,10 +1102,7 @@ fn generate_options_py(workspace_dir: &Path) ->
Result<()> {
out.push_str(&format!(" \"{name}\",\n"));
}
out.push_str("]\n");
-
- let output =
workspace_dir.join("bindings/python/python/opendal/options.py");
- fs::write(output, out)?;
- Ok(())
+ Ok(out)
}
/// Module docstring for the generated `options.py`.
@@ -734,8 +1131,11 @@ method's keyword arguments.
\"\"\"
";
-/// Render a field docstring as a `"""..."""` block, one line per source line.
-fn push_field_doc(out: &mut String, doc: &str) {
+/// Render a class or field docstring as a `"""..."""` block in a class body,
+/// one line per source line. Python reads the block back as `doc`, whatever
+/// quotes or backslashes it holds, and `just fmt` leaves it unchanged.
+fn push_docstring(out: &mut String, doc: &str) {
+ let doc = docstring_source(doc, !doc.contains('\n'));
let lines: Vec<&str> = doc.lines().collect();
if lines.is_empty() {
return;
@@ -755,3 +1155,806 @@ fn push_field_doc(out: &mut String, doc: &str) {
out.push_str("\n \"\"\"\n");
}
}
+
+/// The text between the `"""` quotes of a docstring that Python reads back as
+/// `doc`. `closes_inline` says the closing quotes follow the text on the same
+/// line.
+///
+/// A backslash becomes `\u005c`. A `"` becomes `\u0022` when it would join
+/// the quotes around it: a leading `"`, every third `"` in a row, and the
+/// quotes right before inline closing quotes. `just fmt` keeps these escapes:
+/// ruff's D301 accepts `\u` escapes, but its fix for any other escape adds an
+/// `r` prefix that changes the value, and `ruff format` puts a space after
+/// opening quotes that a `"` follows, which D210 then rejects.
+/// `scripts/postprocess_stubs.py` applies the same escapes to the stubs.
+fn docstring_source(doc: &str, closes_inline: bool) -> String {
+ const BACKSLASH: &str = r"\u005c";
+ const QUOTE: &str = r"\u0022";
+ let trailing = if closes_inline {
+ doc.len() - doc.trim_end_matches('"').len()
+ } else {
+ 0
+ };
+ let (body, quotes) = doc.split_at(doc.len() - trailing);
+ let mut out = String::with_capacity(doc.len());
+ let mut run = 0;
+ for (at, c) in body.char_indices() {
+ match c {
+ '\\' => out.push_str(BACKSLASH),
+ '"' if at == 0 || run == 2 => out.push_str(QUOTE),
+ c => out.push(c),
+ }
+ run = match c {
+ '"' if at > 0 && run < 2 => run + 1,
+ _ => 0,
+ };
+ }
+ for _ in quotes.chars() {
+ out.push_str(QUOTE);
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::generate::core_options::OptionField;
+ use proc_macro2::TokenTree;
+ use std::collections::BTreeMap;
+
+ fn core_options() -> Vec<OptionsStruct> {
+ let path =
crate::workspace_dir().join("core/core/src/types/options.rs");
+ core_options::parse(&path).expect("core options must parse")
+ }
+
+ fn py_names() -> PyNames {
+ PyNames::parse(&crate::workspace_dir()).expect("Python names must
parse")
+ }
+
+ fn list_class(parsed: &[OptionsStruct]) -> PyClass {
+ let mut classes = generated_classes(parsed, &py_names()).unwrap();
+ assert_eq!(classes.len(), 1);
+ classes.remove(0)
+ }
+
+ /// The docstrings of every class and class field in `source`, keyed by
+ /// `Class` and `Class.field`, as Python's `ast` parses them and
+ /// `inspect.cleandoc` dedents them. Panics when `source` is not valid
+ /// Python.
+ fn python_docstrings(source: &str) -> BTreeMap<String, String> {
+ use std::io::Write;
+ use std::process::Stdio;
+
+ const SCRIPT: &str = r#"
+import ast, inspect, json, sys
+docs = {}
+for cls in ast.parse(sys.stdin.read()).body:
+ if not isinstance(cls, ast.ClassDef):
+ continue
+ field = None
+ for i, node in enumerate(cls.body):
+ if isinstance(node, ast.AnnAssign):
+ field = node.target.id
+ elif isinstance(node, ast.Expr) and isinstance(node.value,
ast.Constant):
+ key = cls.name if i == 0 else f"{cls.name}.{field}"
+ docs[key] = inspect.cleandoc(node.value.value)
+print(json.dumps(docs))
+"#;
+ let mut child = Command::new("python3")
+ .args(["-c", SCRIPT])
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .expect("python3 must be installed to check generated Python");
+ child
+ .stdin
+ .take()
+ .unwrap()
+ .write_all(source.as_bytes())
+ .unwrap();
+ let output = child.wait_with_output().unwrap();
+ assert!(
+ output.status.success(),
+ "generated Python does not parse:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ serde_json::from_slice(&output.stdout).unwrap()
+ }
+
+ /// The code spans in `doc` that start with `prefix`, without it.
+ fn spans<'a>(doc: &'a [String], prefix: &str) -> Vec<&'a str> {
+ doc.iter()
+ .flat_map(|line| line.split('`').skip(1).step_by(2))
+ .filter_map(|span| span.strip_prefix(prefix))
+ .collect()
+ }
+
+ /// The `ListOptions` surface on main (4ae8e6122), copied from
+ /// `bindings/python/src/options.rs`, and the Python checks its docs
+ /// name, copied from the capability each field requires in
+ /// `core/core/src/types/options.rs`. The doc wording itself is core's,
+ /// so a core reword passes.
+ fn assert_list_surface(class: &PyClass) {
+ let fields: Vec<String> = class
+ .fields
+ .iter()
+ .map(|f| format!("{}: {}", f.name, f.rust_type))
+ .collect();
+ assert_eq!(
+ fields,
+ [
+ "limit: Option<usize>",
+ "start_after: Option<String>",
+ "recursive: Option<bool>",
+ "versions: Option<bool>",
+ "deleted: Option<bool>",
+ ]
+ );
+
+ assert_eq!(
+ spans(&class.doc, "opendal.exceptions."),
+ ["Unsupported"],
+ "{:?}",
+ class.doc
+ );
+ let checks: Vec<String> = class
+ .fields
+ .iter()
+ .map(|f| {
+ format!(
+ "{}: {}",
+ f.name,
+ spans(&f.doc, "op.capability().").join(" ")
+ )
+ })
+ .collect();
+ assert_eq!(
+ checks,
+ [
+ "limit: ",
+ "start_after: list_with_start_after",
+ "recursive: list_with_recursive",
+ "versions: list_with_versions",
+ "deleted: list_with_deleted",
+ ]
+ );
+
+ // No Rust-only names reach Python callers.
+ for line in class
+ .doc
+ .iter()
+ .chain(class.fields.iter().flat_map(|f| &f.doc))
+ {
+ for rust in ["crate::", "Capability::", "ErrorKind::",
"auto-simulate"] {
+ assert!(!line.contains(rust), "{line}");
+ }
+ }
+ }
+
+ /// The keyword-only parameters of every `#[pyo3(signature)]` method in
+ /// `bindings/python/src/operator.rs`, keyed by type and method.
+ fn operator_kwargs() -> BTreeMap<(String, String), Vec<String>> {
+ let path =
crate::workspace_dir().join("bindings/python/src/operator.rs");
+ let file =
syn::parse_file(&fs::read_to_string(path).unwrap()).unwrap();
+ let mut methods = BTreeMap::new();
+ for item in file.items {
+ let syn::Item::Impl(impl_) = item else {
+ continue;
+ };
+ let syn::Type::Path(ty) = &*impl_.self_ty else {
+ continue;
+ };
+ let ty = ty.path.segments.last().unwrap().ident.to_string();
+ for item in impl_.items {
+ let syn::ImplItem::Fn(method) = item else {
+ continue;
+ };
+ for attr in &method.attrs {
+ let syn::Meta::List(list) = &attr.meta else {
+ continue;
+ };
+ let tokens: Vec<TokenTree> =
list.tokens.clone().into_iter().collect();
+ let (Some(TokenTree::Ident(key)),
Some(TokenTree::Group(params))) =
+ (tokens.first(), tokens.get(2))
+ else {
+ continue;
+ };
+ if !attr.path().is_ident("pyo3") || key != "signature" {
+ continue;
+ }
+ // Split `(path, *, limit=None, ...)` at its top-level
+ // commas and keep the names after the bare `*`.
+ let mut split: Vec<Vec<TokenTree>> = vec![Vec::new()];
+ for token in params.stream() {
+ match token {
+ TokenTree::Punct(p) if p.as_char() == ',' =>
split.push(Vec::new()),
+ token => split.last_mut().unwrap().push(token),
+ }
+ }
+ let mut keyword_only = false;
+ let mut kwargs = Vec::new();
+ for param in split {
+ match param.as_slice() {
+ [TokenTree::Punct(p)] if p.as_char() == '*' =>
keyword_only = true,
+ [TokenTree::Ident(name), ..] if keyword_only => {
+ kwargs.push(name.to_string())
+ }
+ _ => {}
+ }
+ }
+ methods.insert((ty.clone(), method.sig.ident.to_string()),
kwargs);
+ }
+ }
+ }
+ methods
+ }
+
+ /// The `ListOptions` API on main (4ae8e6122), copied from
+ /// `bindings/python/src/options.rs`, with docstrings taken from core.
+ #[test]
+ fn test_list_options_match_main() {
+ let parsed = core_options();
+ let class = list_class(&parsed);
+ assert_list_surface(&class);
+
+ // Each docstring is its own core doc comment.
+ let core = parsed.iter().find(|o| o.name == "ListOptions").unwrap();
+ let names = py_names();
+ assert_eq!(class.doc, py_doc(&core.doc, "ListOptions",
&names).unwrap());
+ for field in &class.fields {
+ let core = core.fields.iter().find(|f| f.name ==
field.name).unwrap();
+ assert_eq!(field.doc, py_doc(&core.doc, field.name,
&names).unwrap());
+ }
+
+ // An explicit `limit`, including `0`, passes through, and an omitted
+ // flag is `false`. Every other core field, such as `glob`, keeps the
+ // default that main's `..Default::default()` gave it.
+ let (set, defaulted): (Vec<_>, Vec<_>) = class
+ .conversion
+ .iter()
+ .map(|f| format!("{}: {}", f.name, f.expr))
+ .partition(|f| f.contains("opts."));
+ assert_eq!(
+ set,
+ [
+ "limit: opts.limit",
+ "start_after: opts.start_after",
+ "recursive: opts.recursive.unwrap_or(false)",
+ "versions: opts.versions.unwrap_or(false)",
+ "deleted: opts.deleted.unwrap_or(false)",
+ ]
+ );
+ assert!(defaulted.contains(&"glob: None".to_string()));
+ for field in &defaulted {
+ let value = field.split_once(": ").unwrap().1;
+ assert!(
+ ["None", "false", "0", "Default::default()"].contains(&value),
+ "{field}"
+ );
+ }
+
+ // `FromPyObject` reads each key and ignores any other key.
+ let rs = render_options_rs(&[class]).unwrap();
+ let extract = rs
+ .split_once("impl<'a, 'py> FromPyObject<'a, 'py> for ListOptions
{")
+ .unwrap()
+ .1
+ .split("\n}\n")
+ .next()
+ .unwrap();
+ let reads: Vec<&str> = extract
+ .lines()
+ .map(str::trim)
+ .filter(|line| line.contains("extract_optional"))
+ .collect();
+ assert_eq!(
+ reads,
+ [
+ "limit: extract_optional(&dict, \"limit\")?,",
+ "start_after: extract_optional(&dict, \"start_after\")?,",
+ "recursive: extract_optional(&dict, \"recursive\")?,",
+ "versions: extract_optional(&dict, \"versions\")?,",
+ "deleted: extract_optional(&dict, \"deleted\")?,",
+ ]
+ );
+ assert!(!extract.contains("reject_unknown_kwargs"));
+
+ // The pyclass and its fields, in order, each after its docs.
+ let body = rs
+ .split_once("#[pyclass(module = \"opendal\")]\n#[derive(Default,
Debug)]\npub struct ListOptions {\n")
+ .unwrap()
+ .1
+ .split_once("\n}\n")
+ .unwrap()
+ .0;
+ let members: Vec<&str> = body
+ .lines()
+ .map(str::trim)
+ .filter(|line| !line.starts_with("///"))
+ .collect();
+ assert_eq!(
+ members,
+ [
+ "pub limit: Option<usize>,",
+ "pub start_after: Option<String>,",
+ "pub recursive: Option<bool>,",
+ "pub versions: Option<bool>,",
+ "pub deleted: Option<bool>,",
+ ]
+ );
+ assert!(body.starts_with(" /// "), "{body}");
+ }
+
+ /// The `options.py` TypedDicts on main (4ae8e6122): the class order and
+ /// the `ListKwargs` keys and types, with docstrings taken from core.
+ #[test]
+ fn test_options_py_matches_main() {
+ let generated = generated_classes(&core_options(),
&py_names()).unwrap();
+ let py = render_options_py(&crate::workspace_dir(),
&generated).unwrap();
+ let classes: Vec<&str> = py
+ .lines()
+ .filter_map(|line| line.strip_prefix("class "))
+ .map(|class| class.split('(').next().unwrap())
+ .collect();
+ assert_eq!(
+ classes,
+ [
+ "ReadKwargs",
+ "WriteKwargs",
+ "ListKwargs",
+ "StatKwargs",
+ "CopyKwargs",
+ "RenameKwargs",
+ "DeleteKwargs",
+ "OpenKwargs",
+ ]
+ );
+
+ let list = py
+ .split_once("\n\nclass ListKwargs(TypedDict, total=False):\n")
+ .unwrap()
+ .1
+ .split_once("\n\n\nclass StatKwargs(")
+ .unwrap()
+ .0;
+ // A key is an `identifier: type` line; docstring lines are not.
+ let keys: Vec<&str> = list
+ .lines()
+ .filter_map(|line| line.strip_prefix(" "))
+ .filter(|line| {
+ line.split_once(": ").is_some_and(|(key, _)| {
+ !key.is_empty() && key.chars().all(|c|
c.is_ascii_lowercase() || c == '_')
+ })
+ })
+ .collect();
+ assert_eq!(
+ keys,
+ [
+ "limit: int",
+ "start_after: str",
+ "recursive: bool",
+ "versions: bool",
+ "deleted: bool",
+ ]
+ );
+
+ // The docstrings parse back, as Python reads them, to the docs.
+ let docs = python_docstrings(&py);
+ let class = &generated[0];
+ assert_eq!(docs["ListKwargs"], class.doc.join("\n"));
+ for field in &class.fields {
+ assert_eq!(
+ docs[&format!("ListKwargs.{}", field.name)],
+ field.doc.join("\n")
+ );
+ }
+ }
+
+ /// The `list` and `scan` keyword arguments on main (4ae8e6122), copied
+ /// from `python/opendal/operator.pyi`.
+ #[test]
+ fn test_list_signatures_match_main() {
+ let methods = operator_kwargs();
+ for (ty, method, kwargs) in [
+ (
+ "Operator",
+ "list",
+ "limit start_after recursive versions deleted",
+ ),
+ ("Operator", "scan", "limit start_after versions deleted"),
+ (
+ "AsyncOperator",
+ "list",
+ "limit start_after recursive versions deleted",
+ ),
+ (
+ "AsyncOperator",
+ "scan",
+ "limit start_after versions deleted",
+ ),
+ ] {
+ let key = (ty.to_string(), method.to_string());
+ assert_eq!(methods[&key].join(" "), kwargs, "{ty}.{method}");
+ }
+ }
+
+ #[test]
+ fn test_list_signatures_match_options_table() {
+ let class = list_class(&core_options());
+ let methods = operator_kwargs();
+ // `scan` is `list` with `recursive=True`.
+ for (ty, method, omitted) in [
+ ("Operator", "list", None),
+ ("Operator", "scan", Some("recursive")),
+ ("AsyncOperator", "list", None),
+ ("AsyncOperator", "scan", Some("recursive")),
+ ] {
+ let mut expected: Vec<&str> = class
+ .fields
+ .iter()
+ .map(|f| f.name)
+ .filter(|name| Some(*name) != omitted)
+ .collect();
+ let mut actual: Vec<&str> = methods[&(ty.to_string(),
method.to_string())]
+ .iter()
+ .map(String::as_str)
+ .collect();
+ expected.sort();
+ actual.sort();
+ assert_eq!(
+ actual, expected,
+ "{ty}.{method} must take the ListOptions keyword arguments"
+ );
+ }
+ }
+
+ #[test]
+ fn test_new_core_field_is_not_exposed() {
+ let parsed = core_options();
+ let base_rs = render_options_rs(&generated_classes(&parsed,
&py_names()).unwrap()).unwrap();
+ let base_py = render_options_py(
+ &crate::workspace_dir(),
+ &generated_classes(&parsed, &py_names()).unwrap(),
+ )
+ .unwrap();
+
+ let mut mutated = parsed.clone();
+ let list = mutated
+ .iter_mut()
+ .find(|o| o.name == "ListOptions")
+ .unwrap();
+ for (name, kind) in [
+ ("fake_option", OptionKind::OptionString),
+ ("fake_flag", OptionKind::Bool),
+ ] {
+ list.fields.push(OptionField {
+ name: name.to_string(),
+ kind,
+ doc: Vec::new(),
+ });
+ }
+ let classes = generated_classes(&mutated, &py_names()).unwrap();
+ let rs = render_options_rs(&classes).unwrap();
+ let py = render_options_py(&crate::workspace_dir(), &classes).unwrap();
+
+ assert_eq!(py, base_py);
+ let added: Vec<&str> = rs.lines().filter(|l|
l.contains("fake_")).collect();
+ assert_eq!(
+ added,
+ [
+ " fake_option: None,",
+ " fake_flag: false,"
+ ]
+ );
+ let kept: Vec<&str> = rs.lines().filter(|l|
!l.contains("fake_")).collect();
+ assert_eq!(kept, base_rs.lines().collect::<Vec<_>>());
+ }
+
+ #[test]
+ fn test_list_options_reject_core_drift() {
+ fn position(options: &OptionsStruct, name: &str) -> usize {
+ options.fields.iter().position(|f| f.name == name).unwrap()
+ }
+ type Mutation = fn(&mut OptionsStruct);
+ let cases: [(Mutation, &str); 7] = [
+ (
+ |list| {
+ list.fields.remove(position(list, "limit"));
+ },
+ "core ListOptions has no field `limit` for Python
ListOptions.limit",
+ ),
+ (
+ |list| {
+ let i = position(list, "limit");
+ list.fields[i].kind = OptionKind::OptionU64;
+ },
+ "core ListOptions::limit has kind OptionU64; \
+ Python ListOptions.limit requires OptionUsize",
+ ),
+ // A change to another kind that Python supports must fail too,
+ // instead of silently turning `start_after` into a bool.
+ (
+ |list| {
+ let i = position(list, "start_after");
+ list.fields[i].kind = OptionKind::Bool;
+ },
+ "core ListOptions::start_after has kind Bool; \
+ Python ListOptions.start_after requires OptionString",
+ ),
+ (
+ |list| {
+ let glob = list.fields[position(list, "glob")].clone();
+ list.fields.push(glob);
+ },
+ "core ListOptions contains duplicate field `glob`",
+ ),
+ (
+ |list| {
+ let i = position(list, "limit");
+ list.fields[i].doc.clear();
+ },
+ "core ListOptions::limit has no doc comment",
+ ),
+ (
+ |list| {
+ let i = position(list, "limit");
+ list.fields[i].doc =
+ vec!["Install [`crate::layers::SimulateLayer`] to
page.".to_string()];
+ },
+ "core ListOptions::limit has no doc comment that applies to
Python",
+ ),
+ (
+ |list| list.has_unmirrored_fields = true,
+ "core ListOptions has fields the core options parser skips;
Python cannot set them",
+ ),
+ ];
+
+ let parsed = core_options();
+ for (mutate, error) in cases {
+ let mut mutated = parsed.clone();
+ mutate(
+ mutated
+ .iter_mut()
+ .find(|o| o.name == "ListOptions")
+ .unwrap(),
+ );
+ assert_eq!(
+ generated_classes(&mutated, &py_names())
+ .unwrap_err()
+ .to_string(),
+ error
+ );
+ }
+ }
+
+ #[test]
+ fn test_py_doc_strips_rustdoc_links() {
+ let lines = [
+ "Use [`crate::Operator::list_with`](crate::Operator::list_with)
and [`Self::recursive`].",
+ "",
+ "A [plain](https://opendal.apache.org) link and `code` stay.",
+ ]
+ .map(String::from);
+ assert_eq!(
+ py_doc(&lines, "Test", &py_names()).unwrap(),
+ [
+ "Use `crate::Operator::list_with` and `Self::recursive`.",
+ "",
+ "A [plain](https://opendal.apache.org) link and `code` stay.",
+ ]
+ );
+ }
+
+ #[test]
+ fn test_py_doc_uses_python_names() {
+ let lines = [
+ "- Pagination: `limit`, `start_after`.",
+ "Requires
[`Capability::list_with_limit`](crate::Capability::list_with_limit).",
+ "Requires [`crate::Capability::list_with_versions`] and
`Capability::list_with_deleted`.",
+ "Fails with [`crate::ErrorKind::Unsupported`] or
`ErrorKind::ConditionNotMatch`.",
+ "Unknown `Capability::no_such_flag`, `ErrorKind::NoSuchKind`, and
prose Capability::list stay.",
+ ]
+ .map(String::from);
+ assert_eq!(
+ py_doc(&lines, "Test", &py_names()).unwrap(),
+ [
+ "- Pagination: `limit`, `start_after`.",
+ "Requires `op.capability().list_with_limit`.",
+ "Requires `op.capability().list_with_versions` and
`op.capability().list_with_deleted`.",
+ "Fails with `opendal.exceptions.Unsupported` or
`opendal.exceptions.ConditionNotMatch`.",
+ "Unknown `Capability::no_such_flag`, `ErrorKind::NoSuchKind`,
and prose Capability::list stay.",
+ ]
+ );
+ }
+
+ /// Python callers cannot install Rust layers, so a sentence that names
+ /// one is dropped; the rest of its paragraph stays.
+ #[test]
+ fn test_py_doc_drops_rust_layer_sentences() {
+ let lines = [
+ "Whether to list recursively; default `false`.",
+ "",
+ "Requires
[`Capability::list_with_recursive`](crate::Capability::list_with_recursive).",
+ "Services without native recursive listing rely on
[`crate::layers::SimulateLayer`]",
+ "(installed automatically by the default `auto-simulate` feature).
Use it e.g. for scans.",
+ "",
+ "Or install [`crate::layers::SimulateLayer`] yourself.",
+ "",
+ "- A list item.",
+ "- Another item.",
+ ]
+ .map(String::from);
+ assert_eq!(
+ py_doc(&lines, "Test", &py_names()).unwrap(),
+ [
+ "Whether to list recursively; default `false`.",
+ "",
+ "Requires `op.capability().list_with_recursive`. Use it e.g.
for scans.",
+ "",
+ "- A list item.",
+ "- Another item.",
+ ]
+ );
+ }
+
+ /// Core docs may hold any text: quotes, backslashes, and rewording reach
+ /// valid Python with their value intact, and the surface checks, which
+ /// pin no core wording, still pass.
+ #[test]
+ fn test_list_options_survive_any_core_doc() {
+ let mut parsed = core_options();
+ // The capability each field names, whatever markup core uses for it.
+ let capabilities: BTreeMap<&str, String> = list_class(&parsed)
+ .fields
+ .iter()
+ .map(|f| (f.name, spans(&f.doc, "op.capability().").join(" ")))
+ .collect();
+ let list = parsed.iter_mut().find(|o| o.name ==
"ListOptions").unwrap();
+ list.doc = [
+ r#""Options" for list operations, with \d, \\ and """ inside."#,
+ "",
+ "Fails with [`crate::ErrorKind::Unsupported`] when an option",
+ r#"needs a missing capability, a "quoted" ending""#,
+ ]
+ .map(String::from)
+ .to_vec();
+ for field in &mut list.fields {
+ let capability = match capabilities.get(field.name.as_str()) {
+ Some(name) if !name.is_empty() => {
+ format!(" Needs
[`Capability::{name}`](crate::Capability::{name}).")
+ }
+ _ => String::new(),
+ };
+ field.doc = vec![format!(r#"Reworded "{}" doc.{capability}"#,
field.name)];
+ }
+ fn field<'a>(list: &'a mut OptionsStruct, name: &str) -> &'a mut
Vec<String> {
+ &mut list.fields.iter_mut().find(|f| f.name == name).unwrap().doc
+ }
+ *field(list, "limit") = vec![r#"Maximum results "per
request""#.to_string()];
+ field(list, "start_after")[0].push_str(r" Keys match \d+.");
+ *field(list, "deleted") = vec and \
"x""#
+ .to_string(),
+ ];
+
+ let generated = generated_classes(&parsed, &py_names()).unwrap();
+ let class = &generated[0];
+ assert_list_surface(class);
+ assert_eq!(
+ class.fields[1].doc,
+ [
+ r#"Reworded "start_after" doc. Needs
`op.capability().list_with_start_after`. Keys match \d+."#
+ ]
+ );
+
+ let py = render_options_py(&crate::workspace_dir(),
&generated).unwrap();
+ // `bindings/python/tests/test_stub_docstrings.py` checks that
+ // `just fmt` keeps the first of these lines.
+ for line in [
+ r#" """\u0022Options" for list operations, with \u005cd,
\u005c\u005c and ""\u0022 inside."#,
+ r#" needs a missing capability, a "quoted" ending""#,
+ r#" """Maximum results "per request\u0022""""#,
+ r#" """Reworded "start_after" doc. Needs
`op.capability().list_with_start_after`. Keys match \u005cd+.""""#,
+ ] {
+ assert!(py.lines().any(|l| l == line), "{line}\n{py}");
+ }
+ // Ruff's D301 fix rewrites any other escape, and `ruff format`
+ // separates a `"` from the opening quotes.
+ for (at, _) in py.match_indices('\\') {
+ assert!(py[at + 1..].starts_with('u'), "{}", &py[at..]);
+ }
+ assert!(!py.contains("\"\"\"\""), "{py}");
+
+ let docs = python_docstrings(&py);
+ assert_eq!(
+ docs["ListKwargs"],
+ "\"Options\" for list operations, with \\d, \\\\ and \"\"\"
inside.\n\
+ \n\
+ Fails with `opendal.exceptions.Unsupported` when an option\n\
+ needs a missing capability, a \"quoted\" ending\""
+ );
+ assert_eq!(docs["ListKwargs.limit"], r#"Maximum results "per
request""#);
+ for field in &class.fields {
+ assert_eq!(
+ docs[&format!("ListKwargs.{}", field.name)],
+ field.doc.join("\n")
+ );
+ }
+
+ // The pyclass doc, which pyo3-introspection writes into
+ // `_opendal.pyi`, is core's text unescaped.
+ let rs = render_options_rs(&generated).unwrap();
+ for line in [
+ r#"/// "Options" for list operations, with \d, \\ and """
inside."#,
+ " /// Maximum results \"per request\"\n pub limit:
Option<usize>,",
+ ] {
+ assert!(rs.contains(line), "{line}\n{rs}");
+ }
+ }
+
+ /// Every capability and exception the generated docstrings name exists
+ /// in the Python API: `python/opendal/capability.pyi` and
+ /// `python/opendal/exceptions.pyi`.
+ #[test]
+ fn test_list_options_docs_name_python_api() {
+ let stub = |name: &str| {
+ fs::read_to_string(
+ crate::workspace_dir()
+ .join("bindings/python/python/opendal")
+ .join(name),
+ )
+ .unwrap()
+ };
+ let capability = stub("capability.pyi");
+ let attributes: HashSet<&str> = capability
+ .lines()
+ .filter_map(|line| line.strip_prefix(" def
")?.split_once("(self, /)"))
+ .map(|(name, _)| name)
+ .collect();
+ assert!(attributes.contains("list_with_start_after"));
+ let exceptions = stub("exceptions.pyi");
+ let classes: HashSet<&str> = exceptions
+ .lines()
+ .filter_map(|line| line.strip_prefix("class ")?.split_once('('))
+ .map(|(name, _)| name)
+ .collect();
+ assert!(classes.contains("NotFound"));
+
+ let class = list_class(&core_options());
+ let docs: Vec<String> = class
+ .doc
+ .iter()
+ .chain(class.fields.iter().flat_map(|f| &f.doc))
+ .cloned()
+ .collect();
+ let checks = spans(&docs, "op.capability().");
+ for name in &checks {
+ assert!(attributes.contains(name), "{name} is not in
capability.pyi");
+ }
+ assert_eq!(
+ checks,
+ [
+ "list_with_start_after",
+ "list_with_recursive",
+ "list_with_versions",
+ "list_with_deleted",
+ ]
+ );
+ let raised = spans(&docs, "opendal.exceptions.");
+ for name in &raised {
+ assert!(classes.contains(name), "{name} is not in exceptions.pyi");
+ }
+ assert_eq!(raised, ["Unsupported"]);
+
+ // Every exception that the generator may name exists.
+ for class in py_names().exceptions.values() {
+ assert!(
+ classes.contains(class.as_str()),
+ "{class} is not in exceptions.pyi"
+ );
+ }
+ }
+}
diff --git a/dev/src/generate/python/options_rs.j2
b/dev/src/generate/python/options_rs.j2
new file mode 100644
index 0000000000..afa44e5539
--- /dev/null
+++ b/dev/src/generate/python/options_rs.j2
@@ -0,0 +1,66 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// DO NOT EDIT IT MANUALLY. This file is generated by
opendal/dev/src/generate/python.rs.
+
+use super::downcast_kwargs;
+use super::extract_optional;
+use opendal as ocore;
+use pyo3::Borrowed;
+use pyo3::FromPyObject;
+use pyo3::PyAny;
+use pyo3::PyErr;
+use pyo3::pyclass;
+{%- for class in classes %}
+{% for line in class.doc %}
+///{{ " " ~ line if line }}
+{%- endfor %}
+#[pyclass(module = "opendal")]
+#[derive(Default, Debug)]
+pub struct {{ class.name }} {
+{%- for f in class.fields %}
+{%- for line in f.doc %}
+ ///{{ " " ~ line if line }}
+{%- endfor %}
+ pub {{ f.name }}: {{ f.rust_type }},
+{%- endfor %}
+}
+
+impl<'a, 'py> FromPyObject<'a, 'py> for {{ class.name }} {
+ type Error = PyErr;
+
+ fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
+ let dict = downcast_kwargs(obj)?;
+
+ Ok(Self {
+{%- for f in class.fields %}
+ {{ f.name }}: extract_optional(&dict, "{{ f.name }}")?,
+{%- endfor %}
+ })
+ }
+}
+
+impl From<{{ class.name }}> for ocore::options::{{ class.name }} {
+ fn from(opts: {{ class.name }}) -> Self {
+ Self {
+{%- for f in class.conversion %}
+ {{ f.name }}: {{ f.expr }},
+{%- endfor %}
+ }
+ }
+}
+{%- endfor %}