chitralverma commented on code in PR #9332:
URL: https://github.com/apache/opendal/pull/9332#discussion_r4725845021
##########
bindings/python/python/opendal/options.py:
##########
@@ -116,18 +116,41 @@ 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 `crate::ErrorKind::Unsupported` when an option
Review Comment:
(AI-generated reply) Changed in 2bcb5b7a9. The generator now adjusts core's
docs for Python. The rule is stated on `py_doc` in `dev/src/generate/python.rs`:
- An `ErrorKind::X` span becomes the exception that
`bindings/python/src/errors.rs` raises for that kind. The class doc now reads
"The operation fails with `opendal.exceptions.Unsupported` when an option
requires a capability that the operator lacks."
- A `Capability::x` span becomes `op.capability().x`. `recursive` now reads
"Requires `op.capability().list_with_recursive`.", and `start_after`,
`versions`, and `deleted` follow the same pattern.
- A sentence that names a Rust layer (a `crate::layers::` span) is dropped,
which removes the `SimulateLayer` / `auto-simulate` note.
On a local build, `opendal.Operator("memory").list("/", versions=True)` and
`deleted=True` raise `opendal.exceptions.Unsupported`, and `op.capability()`
has the four `list_with_*` attributes. A test checks every named capability
against `capability.pyi` and every named exception against `exceptions.pyi`.
##########
dev/src/generate/python.rs:
##########
@@ -626,6 +629,276 @@ 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 docstring of a generated class or field: the core doc comment, one
+/// entry per line.
+///
+/// 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 then use its Python name (see
+/// [`py_code_span`]); other code spans stay as written.
+fn py_doc(
+ core_doc: &[String],
+ item: &str,
+ capabilities: &[CapabilityField],
+) -> Result<Vec<String>> {
+ if core_doc.iter().all(|line| line.is_empty()) {
+ bail!("core {item} has no doc comment");
+ }
+ let mut lines = Vec::with_capacity(core_doc.len());
+ for line in core_doc {
+ let mut unlinked = String::with_capacity(line.len());
+ let mut rest = line.as_str();
+ 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, capabilities).unwrap_or_else(||
code.to_string()));
+ out.push('`');
+ rest = &rest[start + len + 2..];
+ }
+ out.push_str(rest);
+ if out.contains('"') || out.contains('\\') {
+ bail!(
+ "core {item} doc line `{out}` has a character docstrings must
escape; \
Review Comment:
(AI-generated reply) Fixed in 2bcb5b7a9.
- The quote and backslash bail is gone. `options.py` renders any core text
as a docstring that Python reads back unchanged. Text with a backslash becomes
a raw docstring when a raw string can hold it, because ruff's D301 rejects
backslash escapes and the fix that `just stub-gen` applies changes their value.
Other text escapes only backslashes, every third `"` in a row, and quotes right
before inline closing quotes.
- The tests no longer pin core paragraphs. They check field names, Rust and
Python types, the `op.capability().x` each field names, and the exception the
class names. Python's `ast` parses the rendered `options.py`, and each
docstring must read back equal to its doc. A new test feeds core docs with
quotes, backslashes, `"""`, trailing quotes, and new wording.
- Your two edits: with core `limit` set to `Maximum results "per request" to
control memory and throttling.` or `Maximum results per backend request to
control memory and throttling.`, `generate -l python` succeeds and all 11
Python generator tests pass. These scratch edits still fail tests: dropping
`deleted` from the table (5 tests), a wrong capability name (5), core naming
the wrong capability for `recursive` (3), and turning off the escaping, the raw
form, the trailing-quote escape, or the `"""` escape (1 each).
- One limit outside this generator: pyo3-introspection writes the pyclass
docstring into `_opendal.pyi`, and the same ruff D301 fix doubles a backslash
there. Quotes are unaffected.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]