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 f47ec7c1f3 feat(bindings/python): generate DeleteOptions from core 
(#9370)
f47ec7c1f3 is described below

commit f47ec7c1f31cc975756540ebd4f894bf67733b77
Author: Chitral Verma <[email protected]>
AuthorDate: Sun Nov 29 16:52:07 2026 +0530

    feat(bindings/python): generate DeleteOptions from core (#9370)
    
    * feat(bindings/python): generate DeleteOptions from core
    
    Generate the Python DeleteOptions pyclass and DeleteKwargs from core's
    DeleteOptions through the ListOptions and StatOptions generator. The
    version, recursive, and if_match keyword arguments keep their names,
    types, and defaults, and the other core fields keep their defaults.
    
    Docstrings come from core. A code span that names an error kind without
    `ErrorKind::`, such as core's "also returns `Unsupported`", now reads as
    the opendal.exceptions class too, so it renders as "also raises
    `opendal.exceptions.Unsupported`".
    
    Signed-off-by: Chitral Verma <[email protected]>
    
    * chore: regenerate DeleteOptions docs from core
    
    Signed-off-by: Chitral Verma <[email protected]>
    
    * fix(bindings/python): qualify delete docs on missing paths and recursion
    
    Operator.delete and AsyncOperator.delete now say that deleting a missing
    path succeeds only when the supplied options are valid and supported and
    all supplied conditions hold, and the async docstring lists its keyword
    arguments under Parameters instead of Returns.
    
    Core's DeleteOptions::recursive doc now names
    Capability::delete_with_recursive, which OpDelete::check enforces, so the
    generated docs of every binding that renders it warn that recursive=True
    raises Unsupported without it, as main's Python doc did.
    
    Both delete methods now convert through the generated DeleteOptions
    class, so the generated conversion is the one the delete path uses.
    
    Signed-off-by: Chitral Verma <[email protected]>
    
    ---------
    
    Signed-off-by: Chitral Verma <[email protected]>
---
 bindings/dotnet/OpenDAL/Options/DeleteOptions.cs   |   1 +
 .../java/org/apache/opendal/DeleteOptions.java     |   2 +
 bindings/nodejs/generated.d.ts                     |   4 +
 bindings/nodejs/src/options/delete.rs              |   4 +
 bindings/python/python/opendal/_opendal.pyi        |  22 +-
 bindings/python/python/opendal/operator.pyi        |  16 +-
 bindings/python/python/opendal/options.py          |  54 ++-
 bindings/python/src/operator.rs                    |  32 +-
 bindings/python/src/options.rs                     |  39 --
 bindings/python/src/options/generated.rs           |  83 ++++
 core/core/src/types/options.rs                     |   4 +
 dev/src/generate/options.rs                        |  27 +-
 dev/src/generate/python.rs                         | 424 ++++++++++++++++++++-
 13 files changed, 614 insertions(+), 98 deletions(-)

diff --git a/bindings/dotnet/OpenDAL/Options/DeleteOptions.cs 
b/bindings/dotnet/OpenDAL/Options/DeleteOptions.cs
index 4b9d406299..6a503dfe53 100644
--- a/bindings/dotnet/OpenDAL/Options/DeleteOptions.cs
+++ b/bindings/dotnet/OpenDAL/Options/DeleteOptions.cs
@@ -38,6 +38,7 @@ public sealed class DeleteOptions : 
IOptions<OpenDALDeleteOptions>
     /// <summary>
     /// Whether to delete the target recursively.
     /// </summary>
+    /// <seealso cref="Capability.DeleteWithRecursive"/>
     public bool Recursive { get; init; }
 
     /// <summary>
diff --git a/bindings/java/src/main/java/org/apache/opendal/DeleteOptions.java 
b/bindings/java/src/main/java/org/apache/opendal/DeleteOptions.java
index 202af8d7de..7832758749 100644
--- a/bindings/java/src/main/java/org/apache/opendal/DeleteOptions.java
+++ b/bindings/java/src/main/java/org/apache/opendal/DeleteOptions.java
@@ -46,6 +46,8 @@ public class DeleteOptions {
      * Whether to delete the target recursively.
      *
      * <p>The default, {@code false}, deletes a single object. With {@code 
true}, a trailing slash (for example, {@code "a/"}) scopes deletion to a 
directory and its descendants across services. Prefix matching for paths 
without a trailing slash is service-specific. On prefix-based services such as 
{@code memory}, {@code "a"} also matches entries under {@code "ab/"}.
+     *
+     * @see Capability#deleteWithRecursive
      */
     public final boolean recursive;
 
diff --git a/bindings/nodejs/generated.d.ts b/bindings/nodejs/generated.d.ts
index 7943c4baca..6fe680e8e2 100644
--- a/bindings/nodejs/generated.d.ts
+++ b/bindings/nodejs/generated.d.ts
@@ -1243,6 +1243,10 @@ export interface DeleteOptions {
    * descendants across services. Prefix matching for paths without a
    * trailing slash is service-specific. On prefix-based services such as
    * `memory`, `"a"` also matches entries under `"ab/"`.
+   *
+   * With `true`, the operation returns an error whose message includes 
`Unsupported`
+   * when the service does not advertise
+   * `Capability.deleteWithRecursive`.
    */
   recursive?: boolean
   /**
diff --git a/bindings/nodejs/src/options/delete.rs 
b/bindings/nodejs/src/options/delete.rs
index dbf743ca55..2de9c3b89b 100644
--- a/bindings/nodejs/src/options/delete.rs
+++ b/bindings/nodejs/src/options/delete.rs
@@ -55,6 +55,10 @@ pub struct DeleteOptions {
     /// descendants across services. Prefix matching for paths without a
     /// trailing slash is service-specific. On prefix-based services such as
     /// `memory`, `"a"` also matches entries under `"ab/"`.
+    ///
+    /// With `true`, the operation returns an error whose message includes 
`Unsupported`
+    /// when the service does not advertise
+    /// `Capability.deleteWithRecursive`.
     pub recursive: Option<bool>,
 
     /// Delete only when the file at the delete path has this exact ETag.
diff --git a/bindings/python/python/opendal/_opendal.pyi 
b/bindings/python/python/opendal/_opendal.pyi
index 87b394176a..3c5da5563a 100644
--- a/bindings/python/python/opendal/_opendal.pyi
+++ b/bindings/python/python/opendal/_opendal.pyi
@@ -46,7 +46,27 @@ __version__: Final[str]
 
 @final
 class DeleteOptions:
-    """Options for `delete` operations."""
+    """
+    Options for delete operations.
+
+    Each condition checks the file currently stored at the delete path, and
+    every condition must hold for the delete to proceed:
+
+    - A false condition fails the delete with
+    `opendal.exceptions.ConditionNotMatch`.
+    - A condition the service does not advertise through its capability fails
+    the delete with `opendal.exceptions.Unsupported`; OpenDAL never
+    silently drops a condition. A service that cannot preserve a
+    combination of conditions also raises `opendal.exceptions.Unsupported`.
+    - A service-side conflict unrelated to these conditions surfaces as
+    `opendal.exceptions.Conflict`.
+
+    With valid, supported options, deleting a missing file remains a
+    successful no-op once every condition holds.
+
+    See the conditional operation specification
+    for the complete cross-operation contract.
+    """
 
 @final
 class ListOptions:
diff --git a/bindings/python/python/opendal/operator.pyi 
b/bindings/python/python/opendal/operator.pyi
index 983de22e62..dff060e52f 100644
--- a/bindings/python/python/opendal/operator.pyi
+++ b/bindings/python/python/opendal/operator.pyi
@@ -148,17 +148,13 @@ class AsyncOperator:
 
         Notes
         -----
-        This operation will not return an error if the path does not exist.
+        Deleting a path that does not exist succeeds only when the supplied
+        options are valid and supported and all supplied conditions hold.
 
         Parameters
         ----------
         path : str
             The path to the file.
-
-        Returns
-        -------
-        coroutine
-            An awaitable that completes when the file is deleted.
         version : str, optional
             The version of the file to delete. Only supported on version-aware 
backends.
         recursive : bool, optional
@@ -166,6 +162,11 @@ class AsyncOperator:
             Only supported on backends that support recursive delete.
         if_match : str, optional
             If set, only delete when the existing object's ETag matches.
+
+        Returns
+        -------
+        coroutine
+            An awaitable that completes when the file is deleted.
         """
     def delete_many(
         self, /, paths: collections.abc.Iterable[str | PathLike[str]]
@@ -929,7 +930,8 @@ class Operator:
 
         Notes
         -----
-        This operation will not return an error if the path does not exist.
+        Deleting a path that does not exist succeeds only when the supplied
+        options are valid and supported and all supplied conditions hold.
 
         Parameters
         ----------
diff --git a/bindings/python/python/opendal/options.py 
b/bindings/python/python/opendal/options.py
index 1699a6b714..6454e3acb4 100644
--- a/bindings/python/python/opendal/options.py
+++ b/bindings/python/python/opendal/options.py
@@ -264,17 +264,61 @@ class RenameKwargs(TypedDict, total=False):
 
 
 class DeleteKwargs(TypedDict, total=False):
-    """Options for `delete` operations."""
+    """Options for delete operations.
+
+    Each condition checks the file currently stored at the delete path, and
+    every condition must hold for the delete to proceed:
+
+    - A false condition fails the delete with
+    `opendal.exceptions.ConditionNotMatch`.
+    - A condition the service does not advertise through its capability fails
+    the delete with `opendal.exceptions.Unsupported`; OpenDAL never
+    silently drops a condition. A service that cannot preserve a
+    combination of conditions also raises `opendal.exceptions.Unsupported`.
+    - A service-side conflict unrelated to these conditions surfaces as
+    `opendal.exceptions.Conflict`.
+
+    With valid, supported options, deleting a missing file remains a
+    successful no-op once every condition holds.
+
+    See the conditional operation specification
+    for the complete cross-operation contract.
+    """
 
     version: str
-    """The version of the file to delete. Only supported on version-aware 
backends."""
+    """Delete the given version of the file instead of the current one.
+
+    This selects which stored version the delete removes; it is not a
+    condition on the file.
+
+    Check `op.capability().delete_with_version` before using this
+    option.
+    """
     recursive: bool
-    """If True, delete the path recursively.
+    """Whether to delete the target recursively.
 
-    Only supported on backends that support recursive delete.
+    The default, `false`, deletes a single object. With `true`, a trailing
+    slash (for example, `"a/"`) scopes deletion to a directory and its
+    descendants across services. Prefix matching for paths without a
+    trailing slash is service-specific. On prefix-based services such as
+    `memory`, `"a"` also matches entries under `"ab/"`.
+
+    With `true`, the operation raises `opendal.exceptions.Unsupported`
+    when the service does not advertise
+    `op.capability().delete_with_recursive`.
     """
     if_match: str
-    """The ETag that the object must match before deletion."""
+    """Delete only when the file at the delete path has this exact ETag.
+
+    The condition succeeds when the file exists and its ETag equals this
+    value. A file with a different ETag, or a missing file, fails the
+    delete with `opendal.exceptions.ConditionNotMatch`. Only concrete
+    ETag values are portable; a wildcard such as `"*"` has no portable
+    meaning here.
+
+    The operation raises `opendal.exceptions.Unsupported` when the
+    service does not advertise `op.capability().delete_with_if_match`.
+    """
 
 
 class OpenKwargs(ReadKwargs, WriteKwargs, total=False):
diff --git a/bindings/python/src/operator.rs b/bindings/python/src/operator.rs
index 7136520a46..cfb8a62ab7 100644
--- a/bindings/python/src/operator.rs
+++ b/bindings/python/src/operator.rs
@@ -1043,7 +1043,8 @@ impl Operator {
     ///
     /// Notes
     /// -----
-    /// This operation will not return an error if the path does not exist.
+    /// Deleting a path that does not exist succeeds only when the supplied
+    /// options are valid and supported and all supplied conditions hold.
     ///
     /// Parameters
     /// ----------
@@ -1069,13 +1070,12 @@ impl Operator {
         check_runtime_process()?;
         let this = self.core.clone();
         if version.is_some() || recursive.is_some() || if_match.is_some() {
-            let opts = ocore::options::DeleteOptions {
+            let opts = DeleteOptions {
                 version,
-                recursive: recursive.unwrap_or(false),
+                recursive,
                 if_match,
-                ..Default::default()
             };
-            py.detach(move || this.delete_options(&path, opts))
+            py.detach(move || this.delete_options(&path, opts.into()))
                 .map_err(format_pyerr)
         } else {
             py.detach(move || this.delete(&path)).map_err(format_pyerr)
@@ -2019,17 +2019,13 @@ impl AsyncOperator {
     ///
     /// Notes
     /// -----
-    /// This operation will not return an error if the path does not exist.
+    /// Deleting a path that does not exist succeeds only when the supplied
+    /// options are valid and supported and all supplied conditions hold.
     ///
     /// Parameters
     /// ----------
     /// path : str
     ///     The path to the file.
-    ///
-    /// Returns
-    /// -------
-    /// coroutine
-    ///     An awaitable that completes when the file is deleted.
     /// version : str, optional
     ///     The version of the file to delete. Only supported on version-aware 
backends.
     /// recursive : bool, optional
@@ -2037,6 +2033,11 @@ impl AsyncOperator {
     ///     Only supported on backends that support recursive delete.
     /// if_match : str, optional
     ///     If set, only delete when the existing object's ETag matches.
+    ///
+    /// Returns
+    /// -------
+    /// coroutine
+    ///     An awaitable that completes when the file is deleted.
     #[pyo3(signature = (path, *, version=None, recursive=None, if_match=None) 
-> "collections.abc.Awaitable[None]")]
     pub fn delete<'p>(
         &'p self,
@@ -2050,13 +2051,14 @@ impl AsyncOperator {
         let path = path.to_string_lossy().to_string();
         future_into_py(py, async move {
             if version.is_some() || recursive.is_some() || if_match.is_some() {
-                let opts = ocore::options::DeleteOptions {
+                let opts = DeleteOptions {
                     version,
-                    recursive: recursive.unwrap_or(false),
+                    recursive,
                     if_match,
-                    ..Default::default()
                 };
-                this.delete_options(&path, opts).await.map_err(format_pyerr)
+                this.delete_options(&path, opts.into())
+                    .await
+                    .map_err(format_pyerr)
             } else {
                 this.delete(&path).await.map_err(format_pyerr)
             }
diff --git a/bindings/python/src/options.rs b/bindings/python/src/options.rs
index f344acf019..d966f46a90 100644
--- a/bindings/python/src/options.rs
+++ b/bindings/python/src/options.rs
@@ -415,45 +415,6 @@ impl From<RenameOptions> for ocore::options::RenameOptions 
{
     }
 }
 
-/// Options for `delete` operations.
-#[pyclass(module = "opendal")]
-#[derive(Default, Debug)]
-pub struct DeleteOptions {
-    /// The version of the file to delete. Only supported on version-aware 
backends.
-    pub version: Option<String>,
-    /// If True, delete the path recursively.
-    ///
-    /// Only supported on backends that support recursive delete.
-    pub recursive: Option<bool>,
-    /// The ETag that the object must match before deletion.
-    pub if_match: Option<String>,
-}
-
-impl<'a, 'py> FromPyObject<'a, 'py> for DeleteOptions {
-    type Error = PyErr;
-
-    fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
-        let dict = downcast_kwargs(obj)?;
-
-        Ok(Self {
-            version: extract_optional(&dict, "version")?,
-            recursive: extract_optional(&dict, "recursive")?,
-            if_match: extract_optional(&dict, "if_match")?,
-        })
-    }
-}
-
-impl From<DeleteOptions> for ocore::options::DeleteOptions {
-    fn from(opts: DeleteOptions) -> Self {
-        Self {
-            version: opts.version,
-            recursive: opts.recursive.unwrap_or(false),
-            if_match: opts.if_match,
-            ..Default::default()
-        }
-    }
-}
-
 #[cfg(test)]
 mod tests {
     use super::*;
diff --git a/bindings/python/src/options/generated.rs 
b/bindings/python/src/options/generated.rs
index 1a0003f8e7..315c9844c3 100644
--- a/bindings/python/src/options/generated.rs
+++ b/bindings/python/src/options/generated.rs
@@ -217,3 +217,86 @@ impl From<StatOptions> for ocore::options::StatOptions {
         }
     }
 }
+
+/// Options for delete operations.
+///
+/// Each condition checks the file currently stored at the delete path, and
+/// every condition must hold for the delete to proceed:
+///
+/// - A false condition fails the delete with
+/// `opendal.exceptions.ConditionNotMatch`.
+/// - A condition the service does not advertise through its capability fails
+/// the delete with `opendal.exceptions.Unsupported`; OpenDAL never
+/// silently drops a condition. A service that cannot preserve a
+/// combination of conditions also raises `opendal.exceptions.Unsupported`.
+/// - A service-side conflict unrelated to these conditions surfaces as
+/// `opendal.exceptions.Conflict`.
+///
+/// With valid, supported options, deleting a missing file remains a
+/// successful no-op once every condition holds.
+///
+/// See the conditional operation specification
+/// for the complete cross-operation contract.
+#[pyclass(module = "opendal")]
+#[derive(Default, Debug)]
+pub struct DeleteOptions {
+    /// Delete the given version of the file instead of the current one.
+    ///
+    /// This selects which stored version the delete removes; it is not a
+    /// condition on the file.
+    ///
+    /// Check `op.capability().delete_with_version` before using this
+    /// option.
+    pub version: Option<String>,
+    /// Whether to delete the target recursively.
+    ///
+    /// The default, `false`, deletes a single object. With `true`, a trailing
+    /// slash (for example, `"a/"`) scopes deletion to a directory and its
+    /// descendants across services. Prefix matching for paths without a
+    /// trailing slash is service-specific. On prefix-based services such as
+    /// `memory`, `"a"` also matches entries under `"ab/"`.
+    ///
+    /// With `true`, the operation raises `opendal.exceptions.Unsupported`
+    /// when the service does not advertise
+    /// `op.capability().delete_with_recursive`.
+    pub recursive: Option<bool>,
+    /// Delete only when the file at the delete path has this exact ETag.
+    ///
+    /// The condition succeeds when the file exists and its ETag equals this
+    /// value. A file with a different ETag, or a missing file, fails the
+    /// delete with `opendal.exceptions.ConditionNotMatch`. Only concrete
+    /// ETag values are portable; a wildcard such as `"*"` has no portable
+    /// meaning here.
+    ///
+    /// The operation raises `opendal.exceptions.Unsupported` when the
+    /// service does not advertise `op.capability().delete_with_if_match`.
+    pub if_match: Option<String>,
+}
+
+impl<'a, 'py> FromPyObject<'a, 'py> for DeleteOptions {
+    type Error = PyErr;
+
+    fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
+        let dict = downcast_kwargs(obj)?;
+
+        Ok(Self {
+            version: extract_optional(&dict, "version")?,
+            recursive: extract_optional(&dict, "recursive")?,
+            if_match: extract_optional(&dict, "if_match")?,
+        })
+    }
+}
+
+impl From<DeleteOptions> for ocore::options::DeleteOptions {
+    fn from(opts: DeleteOptions) -> Self {
+        Self {
+            version: opts.version,
+            recursive: opts.recursive.unwrap_or(false),
+            if_match: opts.if_match,
+            if_none_match: None,
+            if_version_match: None,
+            if_version_not_match: None,
+            if_not_changed: None,
+        }
+    }
+}
diff --git a/core/core/src/types/options.rs b/core/core/src/types/options.rs
index b6d194bb8f..19b06cba85 100644
--- a/core/core/src/types/options.rs
+++ b/core/core/src/types/options.rs
@@ -59,6 +59,10 @@ pub struct DeleteOptions {
     /// descendants across services. Prefix matching for paths without a
     /// trailing slash is service-specific. On prefix-based services such as
     /// `memory`, `"a"` also matches entries under `"ab/"`.
+    ///
+    /// With `true`, the operation returns [`crate::ErrorKind::Unsupported`]
+    /// when the service does not advertise
+    /// [`crate::Capability::delete_with_recursive`].
     pub recursive: bool,
     /// Delete only when the file at the delete path has this exact ETag.
     ///
diff --git a/dev/src/generate/options.rs b/dev/src/generate/options.rs
index 93649699e3..0aed517867 100644
--- a/dev/src/generate/options.rs
+++ b/dev/src/generate/options.rs
@@ -200,8 +200,7 @@ mod tests {
                 "ReadOptions",
                 "WriteOptions",
                 "CopyOptions",
-                "RenameOptions",
-                "DeleteOptions"
+                "RenameOptions"
             ]
         );
 
@@ -238,17 +237,21 @@ mod tests {
             );
         }
 
-        let delete = &options[4];
-        assert_eq!(delete.fields.len(), 3);
-        assert_eq!(
-            delete.fields[1].doc,
-            "If True, delete the path recursively.\n\nOnly supported on 
backends that support recursive delete."
-        );
-        assert_eq!(delete.fields[2].name, "if_match");
-        assert_eq!(delete.fields[2].ty, OptionType::Str);
+        // A field doc keeps its paragraphs, which `options.py` renders as
+        // separate docstring paragraphs.
+        let options = parse_struct(&syn::parse_quote! {
+            pub struct FakeOptions {
+                /// First paragraph,
+                /// continued.
+                ///
+                /// Second paragraph.
+                pub flag: Option<bool>,
+            }
+        })
+        .unwrap();
         assert_eq!(
-            delete.fields[2].doc,
-            "The ETag that the object must match before deletion."
+            options.fields[0].doc,
+            "First paragraph,\ncontinued.\n\nSecond paragraph."
         );
     }
 }
diff --git a/dev/src/generate/python.rs b/dev/src/generate/python.rs
index 025aeadc0a..12820fd958 100644
--- a/dev/src/generate/python.rs
+++ b/dev/src/generate/python.rs
@@ -740,6 +740,24 @@ const GENERATED_OPTIONS: &[PyOptions] = &[
             ("checksum", "checksum", OptionKind::Bool, "bool"),
         ],
     },
+    PyOptions {
+        name: "DeleteOptions",
+        options: &[
+            (
+                "version",
+                "version",
+                OptionKind::OptionString,
+                "Option<String>",
+            ),
+            ("recursive", "recursive", OptionKind::Bool, "Option<bool>"),
+            (
+                "if_match",
+                "if_match",
+                OptionKind::OptionString,
+                "Option<String>",
+            ),
+        ],
+    },
 ];
 
 /// The class order of `options.py`, which hand-written and generated classes
@@ -877,9 +895,10 @@ impl PyNames {
 ///   A link with plain text to a Rust path, such as
 ///   ``[checksum specification][crate::docs::specs::checksum]``, keeps only
 ///   its text. Links to URLs stay.
-/// - Code spans that name a core capability, error kind, or renamed field
-///   use the Python check, exception, or keyword argument instead (see
-///   [`py_code_span`]); other code spans stay as written.
+/// - Code spans that name a core capability, error kind (with or without
+///   `ErrorKind::`), or renamed field use the Python check, exception, or
+///   keyword argument instead (see [`py_code_span`]); other code spans stay
+///   as written.
 /// - Core returns an error kind where Python raises the exception, so a
 ///   `returns` right before an exception reads `raises`.
 /// - A sentence that names a Rust layer (a `crate::layers::` code span) is
@@ -998,6 +1017,8 @@ fn raises(text: &str) -> String {
 ///   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.
+///   So does a bare `Unsupported`, which core writes when an earlier
+///   sentence already named the kind.
 /// - A core field listed in `renames`, like `override_content_type`, becomes
 ///   the keyword argument that sets it, like `content_type`. Other keyword
 ///   arguments keep their core names, like `start_after`.
@@ -1013,7 +1034,7 @@ fn py_code_span(code: &str, names: &PyNames, renames: 
&[(&str, &str)]) -> Option
             .any(|f| f.name == name)
             .then(|| format!("op.capability().{name}"));
     }
-    let kind = path.strip_prefix("ErrorKind::")?;
+    let kind = path.strip_prefix("ErrorKind::").unwrap_or(code);
     let class = names.exceptions.get(kind)?;
     Some(format!("opendal.exceptions.{class}"))
 }
@@ -1353,7 +1374,7 @@ mod tests {
     fn generated_class(parsed: &[OptionsStruct], name: &str) -> PyClass {
         let classes = generated_classes(parsed, &py_names()).unwrap();
         let names: Vec<&str> = classes.iter().map(|class| 
class.name).collect();
-        assert_eq!(names, ["ListOptions", "StatOptions"]);
+        assert_eq!(names, ["ListOptions", "StatOptions", "DeleteOptions"]);
         classes
             .into_iter()
             .find(|class| class.name == name)
@@ -1559,6 +1580,80 @@ print(json.dumps(docs))
         }
     }
 
+    /// The `DeleteOptions` surface on main (501c5d96f), copied from
+    /// `bindings/python/src/options.rs`, and the Python checks and exceptions
+    /// its docs name: each field's capability is the one `OpDelete::check`
+    /// in `core/core/src/raw/ops.rs` enforces for it, and the exceptions are
+    /// the error kinds of each field in `core/core/src/types/options.rs`.
+    /// The doc wording itself is core's, so a core reword passes.
+    fn assert_delete_surface(class: &PyClass) {
+        let fields: Vec<String> = class
+            .fields
+            .iter()
+            .map(|f| format!("{}: {}", f.name, f.rust_type))
+            .collect();
+        assert_eq!(
+            fields,
+            [
+                "version: Option<String>",
+                "recursive: Option<bool>",
+                "if_match: Option<String>",
+            ]
+        );
+
+        // Core names `Unsupported` twice, the second time without
+        // `ErrorKind::`.
+        assert_eq!(
+            spans(&class.doc, "opendal.exceptions."),
+            [
+                "ConditionNotMatch",
+                "Unsupported",
+                "Unsupported",
+                "Conflict"
+            ],
+            "{:?}",
+            class.doc
+        );
+        let references: Vec<String> = class
+            .fields
+            .iter()
+            .map(|f| {
+                format!(
+                    "{}: {} / {}",
+                    f.name,
+                    spans(&f.doc, "op.capability().").join(" "),
+                    spans(&f.doc, "opendal.exceptions.").join(" ")
+                )
+            })
+            .collect();
+        assert_eq!(
+            references,
+            [
+                "version: delete_with_version / ",
+                "recursive: delete_with_recursive / Unsupported",
+                "if_match: delete_with_if_match / ConditionNotMatch 
Unsupported",
+            ]
+        );
+
+        // No Rust-only names reach Python callers, no error kind keeps its
+        // core name, and Python raises the exceptions that core returns.
+        let exceptions = py_names().exceptions;
+        for doc in 
std::iter::once(&class.doc).chain(class.fields.iter().map(|f| &f.doc)) {
+            let text = doc.join(" ");
+            for rust in [
+                "crate::",
+                "Capability::",
+                "ErrorKind::",
+                "returns `opendal.exceptions.",
+            ] {
+                assert!(!text.contains(rust), "{rust} in {text}");
+            }
+            for kind in exceptions.keys() {
+                assert!(!text.contains(&format!("`{kind}`")), "{kind} in 
{text}");
+            }
+        }
+    }
+
     /// The keyword-only parameters of every `#[pyo3(signature)]` method in
     /// `bindings/python/src/operator.rs`, keyed by type and method, each as
     /// `name=default`.
@@ -1848,9 +1943,139 @@ print(json.dumps(docs))
         assert!(body.starts_with("    /// "), "{body}");
     }
 
+    /// The `DeleteOptions` API on main (501c5d96f), copied from
+    /// `bindings/python/src/options.rs`, with docstrings taken from core.
+    #[test]
+    fn test_delete_options_match_main() {
+        let parsed = core_options();
+        let class = generated_class(&parsed, "DeleteOptions");
+        assert_delete_surface(&class);
+
+        // Each docstring is the core doc comment of the field it sets.
+        let core = parsed.iter().find(|o| o.name == "DeleteOptions").unwrap();
+        let names = py_names();
+        assert_eq!(
+            class.doc,
+            py_doc(&core.doc, "DeleteOptions", &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()
+            );
+        }
+
+        // Each keyword sets the core field main's `From` impl set it to, an
+        // omitted `recursive` is `false`, and every other core field, such
+        // as `if_none_match`, 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,
+            [
+                "version: opts.version",
+                "recursive: opts.recursive.unwrap_or(false)",
+                "if_match: opts.if_match",
+            ]
+        );
+        for field in [
+            "if_none_match: None",
+            "if_version_match: None",
+            "if_version_not_match: None",
+            "if_not_changed: None",
+        ] {
+            assert!(defaulted.contains(&field.to_string()), "{defaulted:?}");
+        }
+        for field in &defaulted {
+            let value = field.split_once(": ").unwrap().1;
+            assert!(
+                ["None", "false", "0", "Default::default()"].contains(&value),
+                "{field}"
+            );
+        }
+
+        // `FromPyObject` reads each key as main did, and any other key is
+        // ignored.
+        let rs = render_options_rs(&generated_classes(&parsed, 
&names).unwrap()).unwrap();
+        let extract = rs
+            .split_once("impl<'a, 'py> FromPyObject<'a, 'py> for DeleteOptions 
{")
+            .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,
+            [
+                "version: extract_optional(&dict, \"version\")?,",
+                "recursive: extract_optional(&dict, \"recursive\")?,",
+                "if_match: extract_optional(&dict, \"if_match\")?,",
+            ]
+        );
+        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 DeleteOptions {\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 version: Option<String>,",
+                "pub recursive: Option<bool>,",
+                "pub if_match: Option<String>,",
+            ]
+        );
+
+        // The doc comments, which become `__doc__` and the `_opendal.pyi`
+        // docstrings, hold every line of the docs.
+        let comment = |doc: &[String], indent: &str| -> String {
+            doc.iter()
+                .map(|line| match line.as_str() {
+                    "" => format!("{indent}///"),
+                    line => format!("{indent}/// {line}"),
+                })
+                .collect::<Vec<_>>()
+                .join("\n")
+        };
+        let mut expected = format!(
+            "{}\n#[pyclass(module = \"opendal\")]\n#[derive(Default, 
Debug)]\npub struct DeleteOptions {{\n",
+            comment(&class.doc, "")
+        );
+        for f in &class.fields {
+            expected += &format!(
+                "{}\n    pub {}: {},\n",
+                comment(&f.doc, "    "),
+                f.name,
+                f.rust_type
+            );
+        }
+        assert!(rs.contains(&format!("{expected}}}\n")), "{rs}");
+    }
+
     /// The `options.py` TypedDicts on main (4ae8e6122 for `ListKwargs`,
-    /// 809b76472 for `StatKwargs`): the class order and the keys and types
-    /// of the generated classes, with docstrings taken from core.
+    /// 809b76472 for `StatKwargs`, 501c5d96f for `DeleteKwargs`): the class
+    /// order and the keys and types of the generated classes, with
+    /// docstrings taken from core.
     #[test]
     fn test_options_py_matches_main() {
         let generated = generated_classes(&core_options(), 
&py_names()).unwrap();
@@ -1917,6 +2142,10 @@ print(json.dumps(docs))
                 "checksum: bool",
             ]
         );
+        assert_eq!(
+            keys("DeleteKwargs", "OpenKwargs"),
+            ["version: str", "recursive: bool", "if_match: str"]
+        );
 
         // The docstrings parse back, as Python reads them, to the docs.
         let docs = python_docstrings(&py);
@@ -1970,6 +2199,23 @@ print(json.dumps(docs))
         assert!(!methods.contains_key(&("Operator".to_string(), 
"presign_stat".to_string())));
     }
 
+    /// The `delete` and `presign_delete` keyword arguments and defaults on
+    /// main (501c5d96f), copied from `python/opendal/operator.pyi`.
+    #[test]
+    fn test_delete_signatures_match_main() {
+        let methods = operator_kwargs();
+        let delete = "version=None recursive=None if_match=None";
+        for (ty, method, kwargs) in [
+            ("Operator", "delete", delete),
+            ("AsyncOperator", "delete", delete),
+            ("AsyncOperator", "presign_delete", "version=None"),
+        ] {
+            let key = (ty.to_string(), method.to_string());
+            assert_eq!(methods[&key].join(" "), kwargs, "{ty}.{method}");
+        }
+        assert!(!methods.contains_key(&("Operator".to_string(), 
"presign_delete".to_string())));
+    }
+
     /// Each method takes the keyword arguments of its options class, and a
     /// keyword whose Rust field is `bool` defaults to `false` while the
     /// others default to `None`.
@@ -1977,27 +2223,35 @@ print(json.dumps(docs))
     fn test_signatures_match_options_table() {
         let parsed = core_options();
         let methods = operator_kwargs();
-        // `scan` is `list` with `recursive=True`, and `presign_stat` cannot
-        // request a checksum.
+        // `scan` is `list` with `recursive=True`, `presign_stat` cannot
+        // request a checksum, and `presign_delete` takes only a version.
         for (ty, method, class, omitted) in [
-            ("Operator", "list", "ListOptions", None),
-            ("Operator", "scan", "ListOptions", Some("recursive")),
-            ("AsyncOperator", "list", "ListOptions", None),
-            ("AsyncOperator", "scan", "ListOptions", Some("recursive")),
-            ("Operator", "stat", "StatOptions", None),
-            ("AsyncOperator", "stat", "StatOptions", None),
+            ("Operator", "list", "ListOptions", &[][..]),
+            ("Operator", "scan", "ListOptions", &["recursive"][..]),
+            ("AsyncOperator", "list", "ListOptions", &[][..]),
+            ("AsyncOperator", "scan", "ListOptions", &["recursive"][..]),
+            ("Operator", "stat", "StatOptions", &[][..]),
+            ("AsyncOperator", "stat", "StatOptions", &[][..]),
             (
                 "AsyncOperator",
                 "presign_stat",
                 "StatOptions",
-                Some("checksum"),
+                &["checksum"][..],
+            ),
+            ("Operator", "delete", "DeleteOptions", &[][..]),
+            ("AsyncOperator", "delete", "DeleteOptions", &[][..]),
+            (
+                "AsyncOperator",
+                "presign_delete",
+                "DeleteOptions",
+                &["recursive", "if_match"][..],
             ),
         ] {
             let class = generated_class(&parsed, class);
             let mut expected: Vec<String> = class
                 .fields
                 .iter()
-                .filter(|f| Some(f.name) != omitted)
+                .filter(|f| !omitted.contains(&f.name))
                 .map(|f| {
                     let default = if f.rust_type == "bool" {
                         "false"
@@ -2031,7 +2285,7 @@ print(json.dumps(docs))
         let mut mutated = parsed.clone();
         for options in mutated
             .iter_mut()
-            .filter(|o| ["ListOptions", 
"StatOptions"].contains(&o.name.as_str()))
+            .filter(|o| ["ListOptions", "StatOptions", 
"DeleteOptions"].contains(&o.name.as_str()))
         {
             for (name, kind) in [
                 ("fake_option", OptionKind::OptionString),
@@ -2057,6 +2311,8 @@ print(json.dumps(docs))
                 "            fake_flag: false,",
                 "            fake_option: None,",
                 "            fake_flag: false,",
+                "            fake_option: None,",
+                "            fake_flag: false,",
             ]
         );
         let kept: Vec<&str> = rs.lines().filter(|l| 
!l.contains("fake_")).collect();
@@ -2069,7 +2325,7 @@ print(json.dumps(docs))
             options.fields.iter().position(|f| f.name == name).unwrap()
         }
         type Mutation = fn(&mut OptionsStruct);
-        let cases: [(&str, Mutation, &str); 13] = [
+        let cases: [(&str, Mutation, &str); 18] = [
             (
                 "ListOptions",
                 |list| {
@@ -2175,6 +2431,44 @@ print(json.dumps(docs))
                 |stat| stat.has_unmirrored_fields = true,
                 "core StatOptions has fields the core options parser skips; 
Python cannot set them",
             ),
+            (
+                "DeleteOptions",
+                |delete| {
+                    delete.fields.remove(position(delete, "recursive"));
+                },
+                "core DeleteOptions has no field `recursive` for Python 
DeleteOptions.recursive",
+            ),
+            (
+                "DeleteOptions",
+                |delete| {
+                    let i = position(delete, "recursive");
+                    delete.fields[i].kind = OptionKind::Usize;
+                },
+                "core DeleteOptions::recursive has kind Usize; \
+                 Python DeleteOptions.recursive requires Bool",
+            ),
+            (
+                "DeleteOptions",
+                |delete| {
+                    let i = position(delete, "if_match");
+                    delete.fields[i].kind = OptionKind::OptionMetadata;
+                },
+                "core DeleteOptions::if_match has kind OptionMetadata; \
+                 Python DeleteOptions.if_match requires OptionString",
+            ),
+            (
+                "DeleteOptions",
+                |delete| {
+                    let i = position(delete, "version");
+                    delete.fields[i].doc.clear();
+                },
+                "core DeleteOptions::version has no doc comment",
+            ),
+            (
+                "DeleteOptions",
+                |delete| delete.has_unmirrored_fields = true,
+                "core DeleteOptions has fields the core options parser skips; 
Python cannot set them",
+            ),
         ];
 
         let parsed = core_options();
@@ -2287,7 +2581,9 @@ print(json.dumps(docs))
             "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`.",
+            "Bare `Unsupported` and [`NotFound`] name kinds too.",
             "Unknown `Capability::no_such_flag`, `ErrorKind::NoSuchKind`, and 
prose Capability::list stay.",
+            "So do `NoSuchKind`, `crate::NotFound`, `ErrorKind`, `notfound`, 
and prose Unsupported.",
         ]
         .map(String::from);
         assert_eq!(
@@ -2297,7 +2593,9 @@ print(json.dumps(docs))
                 "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`.",
+                "Bare `opendal.exceptions.Unsupported` and 
`opendal.exceptions.NotFound` name kinds too.",
                 "Unknown `Capability::no_such_flag`, `ErrorKind::NoSuchKind`, 
and prose Capability::list stay.",
+                "So do `NoSuchKind`, `crate::NotFound`, `ErrorKind`, 
`notfound`, and prose Unsupported.",
             ]
         );
 
@@ -2327,6 +2625,7 @@ print(json.dumps(docs))
             "Returns `ErrorKind::Unsupported` and may return  
`ErrorKind::NotFound`.",
             "It returns `Capability::stat_with_version`, fails with 
`ErrorKind::Unsupported`,",
             "returns `NoSuchKind`, and noreturns `ErrorKind::NotFound`.",
+            "A combination also returns `Unsupported`.",
         ]
         .map(String::from);
         assert_eq!(
@@ -2338,6 +2637,7 @@ print(json.dumps(docs))
                 "Raises `opendal.exceptions.Unsupported` and may raise  
`opendal.exceptions.NotFound`.",
                 "It returns `op.capability().stat_with_version`, fails with 
`opendal.exceptions.Unsupported`,",
                 "returns `NoSuchKind`, and noreturns 
`opendal.exceptions.NotFound`.",
+                "A combination also raises `opendal.exceptions.Unsupported`.",
             ]
         );
     }
@@ -2551,6 +2851,83 @@ print(json.dumps(docs))
         }
     }
 
+    /// Core may reword the `DeleteOptions` docs and name an error kind with
+    /// or without `ErrorKind::`: the surface checks, which pin no core
+    /// wording, still pass, and Python reads back each docstring.
+    #[test]
+    fn test_delete_options_survive_core_rewording() {
+        let mut parsed = core_options();
+        let base = generated_class(&parsed, "DeleteOptions");
+        let delete = parsed
+            .iter_mut()
+            .find(|o| o.name == "DeleteOptions")
+            .unwrap();
+        delete.doc = [
+            r#""Delete" options, with \d."#,
+            "",
+            "- A failed condition returns `ErrorKind::ConditionNotMatch`.",
+            "- A missing capability returns 
[`ErrorKind::Unsupported`](crate::ErrorKind::Unsupported),",
+            "and a combination also returns `Unsupported`.",
+            "- A conflict surfaces as [`crate::ErrorKind::Conflict`].",
+        ]
+        .map(String::from)
+        .to_vec();
+        for field in &mut delete.fields {
+            let Some(python) = base.fields.iter().find(|f| f.core == 
field.name) else {
+                continue;
+            };
+            let mut doc = vec![format!(
+                r#"Reworded "{}" doc, see [the spec][crate::docs::specs::x]."#,
+                field.name
+            )];
+            for name in spans(&python.doc, "op.capability().") {
+                doc.push(format!("Check `Capability::{name}`."));
+            }
+            for (i, name) in spans(&python.doc, "opendal.exceptions.")
+                .into_iter()
+                .enumerate()
+            {
+                doc.push(match i % 2 {
+                    0 => format!("It returns `{name}`."),
+                    _ => format!("It returns [`crate::ErrorKind::{name}`]."),
+                });
+            }
+            field.doc = doc;
+        }
+
+        let generated = generated_classes(&parsed, &py_names()).unwrap();
+        let class = generated
+            .iter()
+            .find(|c| c.name == "DeleteOptions")
+            .unwrap();
+        assert_delete_surface(class);
+
+        let py = render_options_py(&crate::workspace_dir(), 
&generated).unwrap();
+        let docs = python_docstrings(&py);
+        assert_eq!(
+            docs["DeleteKwargs"],
+            "\"Delete\" options, with \\d.\n\
+             \n\
+             - A failed condition raises 
`opendal.exceptions.ConditionNotMatch`.\n\
+             - A missing capability raises `opendal.exceptions.Unsupported`,\n\
+             and a combination also raises `opendal.exceptions.Unsupported`.\n\
+             - A conflict surfaces as `opendal.exceptions.Conflict`."
+        );
+        assert_eq!(
+            docs["DeleteKwargs.if_match"],
+            "Reworded \"if_match\" doc, see the spec.\n\
+             Check `op.capability().delete_with_if_match`.\n\
+             It raises `opendal.exceptions.ConditionNotMatch`.\n\
+             It raises `opendal.exceptions.Unsupported`."
+        );
+        for field in &class.fields {
+            assert_eq!(
+                docs[&format!("DeleteKwargs.{}", field.name)],
+                field.doc.join("\n")
+            );
+        }
+    }
+
     /// Every capability and exception the generated docstrings name exists
     /// in the Python API: `python/opendal/capability.pyi` and
     /// `python/opendal/exceptions.pyi`.
@@ -2602,6 +2979,15 @@ print(json.dumps(docs))
                 ][..],
                 &["ConditionNotMatch", "NotFound", "Unsupported"][..],
             ),
+            (
+                "DeleteOptions",
+                &[
+                    "delete_with_version",
+                    "delete_with_recursive",
+                    "delete_with_if_match",
+                ][..],
+                &["ConditionNotMatch", "Conflict", "Unsupported"][..],
+            ),
         ] {
             let class = generated_class(&parsed, class);
             let docs: Vec<String> = class

Reply via email to