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 408b614049 feat(bindings/python): expose the ListOptions glob option
(#9415)
408b614049 is described below
commit 408b614049a68abfbd9082bf333bbcef5794b1c8
Author: Chitral Verma <[email protected]>
AuthorDate: Mon Nov 30 09:15:41 2026 +0530
feat(bindings/python): expose the ListOptions glob option (#9415)
* feat(bindings/python): expose the ListOptions glob option
Add a glob keyword argument to Operator.list and AsyncOperator.list,
generated from core ListOptions::glob. The deprecated scan does not take
it.
The ListKwargs docstring comes from core. Python renders Self::recursive
as recursive, and replaces the dropped SimulateLayer sentence with
"otherwise
OpenDAL evaluates patterns client-side". A Self:: code span that names a
field Python does not expose now fails generation.
Signed-off-by: Chitral Verma <[email protected]>
* fix(bindings/python): drop the glob recursion requirement from Python docs
Python cannot turn off recursive list simulation, so a multi-directory
glob with start_after, versions, or deleted never needs
op.capability().list_with_recursive, even when a CapabilityOverrideLayer
reports it as false. Drop that sentence from ListKwargs.glob.
Render ListKwargs on the Sphinx types page, which the list glob
parameter doc points to. Check Self:: code spans after Python drops a
sentence, so a span in a dropped sentence does not fail generation.
Signed-off-by: Chitral Verma <[email protected]>
* fix(bindings/python): limit the glob doc rewrite to the recursion sentence
The ListOptions rewrite matched the first word of the next sentence, so
rewording core's error sentence alone failed generation. Match only the
list_with_recursive sentence, and check that the ConfigInvalid sentence
comes from core.
Signed-off-by: Chitral Verma <[email protected]>
---------
Signed-off-by: Chitral Verma <[email protected]>
---
bindings/python/docs/api/types.md | 3 +
bindings/python/python/opendal/operator.pyi | 8 +
bindings/python/python/opendal/options.py | 18 ++
bindings/python/src/operator.rs | 38 +++-
bindings/python/src/options/generated.rs | 20 ++-
bindings/python/tests/test_async_list.py | 17 ++
bindings/python/tests/test_sync_list.py | 17 ++
dev/src/generate/python.rs | 261 +++++++++++++++++++++-------
8 files changed, 317 insertions(+), 65 deletions(-)
diff --git a/bindings/python/docs/api/types.md
b/bindings/python/docs/api/types.md
index 69bc3bb615..a125877aab 100644
--- a/bindings/python/docs/api/types.md
+++ b/bindings/python/docs/api/types.md
@@ -26,4 +26,7 @@ This page documents all types in OpenDAL.
.. autodata:: opendal.options.ChecksumAlgorithm
.. autoclass:: opendal.options.OpenKwargs
+
+.. autoclass:: opendal.options.ListKwargs
+ :members:
```
diff --git a/bindings/python/python/opendal/operator.pyi
b/bindings/python/python/opendal/operator.pyi
index 946acbe58b..144d1afee7 100644
--- a/bindings/python/python/opendal/operator.pyi
+++ b/bindings/python/python/opendal/operator.pyi
@@ -316,6 +316,7 @@ class AsyncOperator:
recursive: bool | None = None,
versions: bool | None = None,
deleted: bool | None = None,
+ glob: str | None = None,
) -> collections.abc.Awaitable[collections.abc.AsyncIterable[Entry]]:
"""
List entries in the given directory.
@@ -337,6 +338,9 @@ class AsyncOperator:
Whether to list versions.
deleted : bool, optional
Whether to list deleted entries.
+ glob : str, optional
+ Filter entries with a case-sensitive Unix shell style glob pattern.
+ `opendal.options.ListKwargs` describes the pattern syntax.
Returns
-------
@@ -1107,6 +1111,7 @@ class Operator:
recursive: bool | None = None,
versions: bool | None = None,
deleted: bool | None = None,
+ glob: str | None = None,
) -> collections.abc.Iterable[Entry]:
"""
List entries in the given directory.
@@ -1128,6 +1133,9 @@ class Operator:
Whether to list versions.
deleted : bool, optional
Whether to list deleted entries.
+ glob : str, optional
+ Filter entries with a case-sensitive Unix shell style glob pattern.
+ `opendal.options.ListKwargs` describes the pattern syntax.
Returns
-------
diff --git a/bindings/python/python/opendal/options.py
b/bindings/python/python/opendal/options.py
index 482e71cfa1..9526112735 100644
--- a/bindings/python/python/opendal/options.py
+++ b/bindings/python/python/opendal/options.py
@@ -495,6 +495,24 @@ class ListKwargs(TypedDict, total=False):
Requires `op.capability().list_with_deleted`.
"""
+ glob: str
+ """Filter entries with a case-sensitive Unix shell style glob pattern.
+
+ The pattern is relative to the listed directory, or to the parent
+ directory when the list path is a prefix without a trailing slash.
+ Entries must also satisfy the list prefix. The pattern determines which
+ depths can match, independently of `recursive`.
+
+ - `*` matches zero or more characters within one path component.
+ - `?` matches one Unicode scalar value within one path component.
+ - `**` matches zero or more path components and must occupy a whole
component.
+ - `{a,b}` matches either alternative within a component.
+ - `[ab]`, `[a-z]`, and `[!a-z]` match character sets, ranges, and negated
sets.
+ - A backslash escapes the next character within a component.
+ - A trailing slash restricts matches to directories.
+
+ Requires `op.capability().list_with_glob`. Services with native glob
support handle patterns directly; otherwise OpenDAL evaluates patterns
client-side. Empty or malformed patterns fail with
`opendal.exceptions.ConfigInvalid`.
+ """
class StatKwargs(TypedDict, total=False):
diff --git a/bindings/python/src/operator.rs b/bindings/python/src/operator.rs
index 281c8f8d89..62b7ddcf41 100644
--- a/bindings/python/src/operator.rs
+++ b/bindings/python/src/operator.rs
@@ -1169,6 +1169,9 @@ impl Operator {
/// Whether to list versions.
/// deleted : bool, optional
/// Whether to list deleted entries.
+ /// glob : str, optional
+ /// Filter entries with a case-sensitive Unix shell style glob pattern.
+ /// `opendal.options.ListKwargs` describes the pattern syntax.
///
/// Returns
/// -------
@@ -1180,7 +1183,8 @@ impl Operator {
start_after=None,
recursive=None,
versions=None,
- deleted=None) -> "collections.abc.Iterable[Entry]")]
+ deleted=None,
+ glob=None) -> "collections.abc.Iterable[Entry]")]
pub fn list(
&self,
py: Python<'_>,
@@ -1190,6 +1194,7 @@ impl Operator {
recursive: Option<bool>,
versions: Option<bool>,
deleted: Option<bool>,
+ glob: Option<String>,
) -> PyResult<BlockingLister> {
let path = path.to_string_lossy().to_string();
@@ -1199,6 +1204,7 @@ impl Operator {
recursive,
versions,
deleted,
+ glob,
};
check_runtime_process()?;
@@ -1249,7 +1255,16 @@ impl Operator {
versions: Option<bool>,
deleted: Option<bool>,
) -> PyResult<BlockingLister> {
- self.list(py, path, limit, start_after, Some(true), versions, deleted)
+ self.list(
+ py,
+ path,
+ limit,
+ start_after,
+ Some(true),
+ versions,
+ deleted,
+ None,
+ )
}
/// Get all capabilities of this operator.
@@ -2185,6 +2200,9 @@ impl AsyncOperator {
/// Whether to list versions.
/// deleted : bool, optional
/// Whether to list deleted entries.
+ /// glob : str, optional
+ /// Filter entries with a case-sensitive Unix shell style glob pattern.
+ /// `opendal.options.ListKwargs` describes the pattern syntax.
///
/// Returns
/// -------
@@ -2196,7 +2214,8 @@ impl AsyncOperator {
start_after=None,
recursive=None,
versions=None,
- deleted=None) ->
"collections.abc.Awaitable[collections.abc.AsyncIterable[Entry]]")]
+ deleted=None,
+ glob=None) ->
"collections.abc.Awaitable[collections.abc.AsyncIterable[Entry]]")]
pub fn list<'p>(
&'p self,
py: Python<'p>,
@@ -2206,6 +2225,7 @@ impl AsyncOperator {
recursive: Option<bool>,
versions: Option<bool>,
deleted: Option<bool>,
+ glob: Option<String>,
) -> PyResult<Bound<'p, PyAny>> {
let this = self.core.clone();
let path = path.to_string_lossy().to_string();
@@ -2215,6 +2235,7 @@ impl AsyncOperator {
recursive,
versions,
deleted,
+ glob,
};
future_into_py(py, async move {
@@ -2268,7 +2289,16 @@ impl AsyncOperator {
versions: Option<bool>,
deleted: Option<bool>,
) -> PyResult<Bound<'p, PyAny>> {
- self.list(py, path, limit, start_after, Some(true), versions, deleted)
+ self.list(
+ py,
+ path,
+ limit,
+ start_after,
+ Some(true),
+ versions,
+ deleted,
+ None,
+ )
}
/// Create a presigned request for a stat operation.
diff --git a/bindings/python/src/options/generated.rs
b/bindings/python/src/options/generated.rs
index 5b68fc3dd9..929a74913a 100644
--- a/bindings/python/src/options/generated.rs
+++ b/bindings/python/src/options/generated.rs
@@ -57,6 +57,23 @@ pub struct ListOptions {
///
/// Requires `op.capability().list_with_deleted`.
pub deleted: Option<bool>,
+ /// Filter entries with a case-sensitive Unix shell style glob pattern.
+ ///
+ /// The pattern is relative to the listed directory, or to the parent
+ /// directory when the list path is a prefix without a trailing slash.
+ /// Entries must also satisfy the list prefix. The pattern determines which
+ /// depths can match, independently of `recursive`.
+ ///
+ /// - `*` matches zero or more characters within one path component.
+ /// - `?` matches one Unicode scalar value within one path component.
+ /// - `**` matches zero or more path components and must occupy a whole
component.
+ /// - `{a,b}` matches either alternative within a component.
+ /// - `[ab]`, `[a-z]`, and `[!a-z]` match character sets, ranges, and
negated sets.
+ /// - A backslash escapes the next character within a component.
+ /// - A trailing slash restricts matches to directories.
+ ///
+ /// Requires `op.capability().list_with_glob`. Services with native glob
support handle patterns directly; otherwise OpenDAL evaluates patterns
client-side. Empty or malformed patterns fail with
`opendal.exceptions.ConfigInvalid`.
+ pub glob: Option<String>,
}
impl<'a, 'py> FromPyObject<'a, 'py> for ListOptions {
@@ -71,6 +88,7 @@ impl<'a, 'py> FromPyObject<'a, 'py> for ListOptions {
recursive: extract_optional(&dict, "recursive")?,
versions: extract_optional(&dict, "versions")?,
deleted: extract_optional(&dict, "deleted")?,
+ glob: extract_optional(&dict, "glob")?,
})
}
}
@@ -83,7 +101,7 @@ impl From<ListOptions> for ocore::options::ListOptions {
recursive: opts.recursive.unwrap_or(false),
versions: opts.versions.unwrap_or(false),
deleted: opts.deleted.unwrap_or(false),
- glob: None,
+ glob: opts.glob,
}
}
}
diff --git a/bindings/python/tests/test_async_list.py
b/bindings/python/tests/test_async_list.py
index 52c3afe24a..1f0f6ea8cb 100644
--- a/bindings/python/tests/test_async_list.py
+++ b/bindings/python/tests/test_async_list.py
@@ -163,3 +163,20 @@ async def test_async_list_with_start_after(service_name,
operator, async_operato
)
# 6. Cleanup
await async_operator.remove_all(test_dir)
+
+
[email protected]
[email protected]_capability("write", "list", "list_with_glob")
+async def test_async_list_with_glob(service_name, operator, async_operator):
+ test_dir = f"test_async_list_glob_dir_{uuid4()}/"
+ for path in ["a.txt", "b.log", "sub/c.txt"]:
+ await async_operator.write(f"{test_dir}{path}", b"test_content")
+
+ lister = await async_operator.list(test_dir, glob="**/*.txt")
+ entries = sorted([entry.path async for entry in lister])
+ assert entries == [f"{test_dir}a.txt", f"{test_dir}sub/c.txt"]
+
+ with pytest.raises(opendal.exceptions.ConfigInvalid):
+ await async_operator.list(test_dir, glob="")
+
+ await async_operator.remove_all(test_dir)
diff --git a/bindings/python/tests/test_sync_list.py
b/bindings/python/tests/test_sync_list.py
index 5ac2c4c727..31dc287200 100644
--- a/bindings/python/tests/test_sync_list.py
+++ b/bindings/python/tests/test_sync_list.py
@@ -19,6 +19,8 @@ from uuid import uuid4
import pytest
+import opendal
+
@pytest.mark.need_capability("read", "write", "copy", "list",
"list_with_start_after")
def test_sync_list_with_start_after(service_name, operator, async_operator):
@@ -54,3 +56,18 @@ def test_sync_list_with_start_after(service_name, operator,
async_operator):
)
# 6. Cleanup
operator.remove_all(test_dir)
+
+
[email protected]_capability("write", "list", "list_with_glob")
+def test_sync_list_with_glob(service_name, operator, async_operator):
+ test_dir = f"test_sync_list_glob_dir_{uuid4()}/"
+ for path in ["a.txt", "b.log", "sub/c.txt"]:
+ operator.write(f"{test_dir}{path}", b"test_content")
+
+ entries = sorted(entry.path for entry in operator.list(test_dir,
glob="**/*.txt"))
+ assert entries == [f"{test_dir}a.txt", f"{test_dir}sub/c.txt"]
+
+ with pytest.raises(opendal.exceptions.ConfigInvalid):
+ operator.list(test_dir, glob="")
+
+ operator.remove_all(test_dir)
diff --git a/dev/src/generate/python.rs b/dev/src/generate/python.rs
index bda0d234d7..9dec7e7100 100644
--- a/dev/src/generate/python.rs
+++ b/dev/src/generate/python.rs
@@ -708,10 +708,20 @@ const GENERATED_OPTIONS: &[PyOptions] = &[
("recursive", "recursive", OptionKind::Bool, "Option<bool>"),
("versions", "versions", OptionKind::Bool, "Option<bool>"),
("deleted", "deleted", OptionKind::Bool, "Option<bool>"),
+ ("glob", "glob", OptionKind::OptionString, "Option<String>"),
],
unmirrored: &[],
docs: &[],
- rewrites: &[],
+ // Python cannot turn off recursive list simulation, so the
+ // `list_with_recursive` requirement never applies to it. Its place
+ // keeps what the dropped `SimulateLayer` sentence says.
+ rewrites: &[(
+ "Combining a multi-directory pattern with `start_after`,
`versions`, \
+ or `deleted` during client-side simulation also requires \
+ `op.capability().list_with_recursive`.",
+ "Services with native glob support handle patterns directly; \
+ otherwise OpenDAL evaluates patterns client-side.",
+ )],
},
PyOptions {
name: "StatOptions",
@@ -1253,7 +1263,8 @@ impl PyNames {
/// - 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.
+/// as written. A `Self::` code span that keeps no Python name fails
+/// generation, because that name means nothing to Python callers.
/// - 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
@@ -1313,6 +1324,10 @@ fn py_doc(
if out.is_empty() {
bail!("core {item} has no doc comment that applies to Python");
}
+ if let Some(reference) = out.iter().find_map(|line|
line.split("`Self::").nth(1)) {
+ let name = reference.split('`').next().unwrap_or_default();
+ bail!("core {item} docs name `Self::{name}`, which has no Python
name");
+ }
Ok(out)
}
@@ -1384,7 +1399,9 @@ fn raises(text: &str) -> String {
/// 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`.
+/// arguments keep their core names, like `start_after`. A path to a field
+/// that Python exposes, like `Self::recursive`, becomes its keyword
+/// argument too.
/// - A Rust `Some(value)`, like `Some(0)`, becomes the Python value `0`;
/// `None` is already the Python value of an omitted option.
fn py_code_span(code: &str, names: &PyNames, renames: &[(&str, &str)]) ->
Option<String> {
@@ -1435,13 +1452,19 @@ fn py_class(spec: &PyOptions, parsed: &[OptionsStruct],
names: &PyNames) -> Resu
}
}
- // Core field names and `Class::field` paths read as the keyword argument.
- // `offset` and `size` both set a range, so neither renames it.
+ // Core field names and `Class::field` or `Self::field` paths read as the
+ // keyword argument. `offset` and `size` both set a range, so neither
+ // renames it.
let paths: Vec<(String, &str)> = spec
.options
.iter()
.filter(|&&(_, core, kind, _)| kind != OptionKind::BytesRange &&
!core.contains("::"))
- .map(|&(name, core, ..)| (format!("{class}::{core}"), name))
+ .flat_map(|&(name, core, ..)| {
+ [
+ (format!("{class}::{core}"), name),
+ (format!("Self::{core}"), name),
+ ]
+ })
.collect();
let renames: Vec<(&str, &str)> = spec
.options
@@ -2042,6 +2065,32 @@ mod tests {
const WRITE_CHECKSUM_DOC: &str = "The algorithm the service uses to verify
the full object before committing.\n\
`None` preserves the service default.";
+ /// The Python wording of the `ListOptions` docs for core text that does
+ /// not hold for Python, as `(core, Python)`. Python drops the core
+ /// sentence that names `SimulateLayer`, and the `list_with_recursive`
+ /// requirement, which Python callers cannot fail.
+ const LIST_REWRITES: [(&str, &str); 1] = [(
+ "Combining a multi-directory pattern with `start_after`, `versions`,
or \
+ `deleted` during client-side simulation also requires \
+ `op.capability().list_with_recursive`.",
+ "Services with native glob support handle patterns directly; otherwise
\
+ OpenDAL evaluates patterns client-side.",
+ )];
+
+ /// `py_doc` of a core `ListOptions` doc, with the Python wording.
+ fn list_doc(core_doc: &[String], item: &str) -> Vec<String> {
+ let renames = [("Self::recursive", "recursive")];
+ let text = py_doc(core_doc, item, &py_names(), &renames)
+ .unwrap()
+ .join("\n");
+ LIST_REWRITES
+ .iter()
+ .fold(text, |text, (from, to)| text.replace(from, to))
+ .split('\n')
+ .map(String::from)
+ .collect()
+ }
+
/// The Python wording of the `CopyOptions` docs for core text that does
/// not hold for Python, as `(core, Python)`.
const COPY_REWRITES: [(&str, &str); 1] = [(
@@ -2132,10 +2181,10 @@ print(json.dumps(docs))
}
/// 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.
+ /// `bindings/python/src/options.rs`, plus `glob`, and the Python checks
+ /// and exceptions its docs name, copied from the capabilities and 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_list_surface(class: &PyClass) {
let fields: Vec<String> = class
.fields
@@ -2150,6 +2199,7 @@ print(json.dumps(docs))
"recursive: Option<bool>",
"versions: Option<bool>",
"deleted: Option<bool>",
+ "glob: Option<String>",
]
);
@@ -2159,25 +2209,27 @@ print(json.dumps(docs))
"{:?}",
class.doc
);
- let checks: Vec<String> = class
+ let references: Vec<String> = class
.fields
.iter()
.map(|f| {
format!(
- "{}: {}",
+ "{}: {} / {}",
f.name,
- spans(&f.doc, "op.capability().").join(" ")
+ spans(&f.doc, "op.capability().").join(" "),
+ spans(&f.doc, "opendal.exceptions.").join(" ")
)
})
.collect();
assert_eq!(
- checks,
+ references,
[
- "limit: ",
- "start_after: list_with_start_after",
- "recursive: list_with_recursive",
- "versions: list_with_versions",
- "deleted: list_with_deleted",
+ "limit: / ",
+ "start_after: list_with_start_after / ",
+ "recursive: list_with_recursive / ",
+ "versions: list_with_versions / ",
+ "deleted: list_with_deleted / ",
+ "glob: list_with_glob / ConfigInvalid",
]
);
@@ -2187,7 +2239,14 @@ print(json.dumps(docs))
.iter()
.chain(class.fields.iter().flat_map(|f| &f.doc))
{
- for rust in ["crate::", "Capability::", "ErrorKind::",
"auto-simulate"] {
+ for rust in [
+ "crate::",
+ "Capability::",
+ "ErrorKind::",
+ "Self::",
+ "SimulateLayer",
+ "auto-simulate",
+ ] {
assert!(!line.contains(rust), "{line}");
}
}
@@ -2740,36 +2799,54 @@ print(json.dumps(docs))
}
/// The `ListOptions` API on main (4ae8e6122), copied from
- /// `bindings/python/src/options.rs`, with docstrings taken from core.
+ /// `bindings/python/src/options.rs`, plus `glob`, with docstrings taken
+ /// from core.
#[test]
fn test_list_options_match_main() {
let parsed = core_options();
let class = generated_class(&parsed, "ListOptions");
assert_list_surface(&class);
- // Each docstring is its own core doc comment.
+ // Each docstring is its own core doc comment, with the Python
+ // wording.
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()
- );
+ assert_eq!(class.doc, list_doc(&core.doc, "ListOptions"));
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()
- );
+ assert_eq!(field.doc, list_doc(&core.doc, field.name), "{}",
field.name);
}
+ let glob = class.fields.iter().find(|f| f.name == "glob").unwrap();
+ let glob = glob.doc.join(" ");
+ for text in [
+ "The pattern determines which depths can match, independently of
`recursive`.",
+ "Services with native glob support handle patterns directly;
otherwise \
+ OpenDAL evaluates patterns client-side.",
+ ] {
+ assert!(glob.contains(text), "{glob}");
+ }
+ // The error sentence is core's, with the Python exception.
+ let core_glob = core.fields.iter().find(|f| f.name == "glob").unwrap();
+ let error = core_glob
+ .doc
+ .iter()
+ .find(|line| line.contains("ConfigInvalid"))
+ .unwrap();
+ let error = py_doc(std::slice::from_ref(error), "glob", &py_names(),
&[])
+ .unwrap()
+ .join(" ");
+ assert!(
+ error.contains("`opendal.exceptions.ConfigInvalid`"),
+ "{error}"
+ );
+ assert!(glob.contains(&error), "{glob}");
- // 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
+ // An explicit `limit`, including `0`, passes through, an omitted
+ // flag is `false`, and an omitted `glob` is `None`.
+ let set: Vec<String> = class
.conversion
.iter()
.map(|f| format!("{}: {}", f.name, f.expr))
- .partition(|f| f.contains("opts."));
+ .collect();
assert_eq!(
set,
[
@@ -2778,16 +2855,9 @@ print(json.dumps(docs))
"recursive: opts.recursive.unwrap_or(false)",
"versions: opts.versions.unwrap_or(false)",
"deleted: opts.deleted.unwrap_or(false)",
+ "glob: opts.glob",
]
);
- 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();
@@ -2811,6 +2881,7 @@ print(json.dumps(docs))
"recursive: extract_optional(&dict, \"recursive\")?,",
"versions: extract_optional(&dict, \"versions\")?,",
"deleted: extract_optional(&dict, \"deleted\")?,",
+ "glob: extract_optional(&dict, \"glob\")?,",
]
);
assert!(!extract.contains("reject_unknown_kwargs"));
@@ -2836,6 +2907,7 @@ print(json.dumps(docs))
"pub recursive: Option<bool>,",
"pub versions: Option<bool>,",
"pub deleted: Option<bool>,",
+ "pub glob: Option<String>,",
]
);
assert!(body.starts_with(" /// "), "{body}");
@@ -3920,6 +3992,7 @@ print(json.dumps(docs))
"recursive: bool",
"versions: bool",
"deleted: bool",
+ "glob: str",
]
);
assert_eq!(
@@ -3985,11 +4058,13 @@ print(json.dumps(docs))
}
/// The `list` and `scan` keyword arguments and defaults on main
- /// (4ae8e6122), copied from `python/opendal/operator.pyi`.
+ /// (4ae8e6122), copied from `python/opendal/operator.pyi`, plus `glob`
+ /// on `list`.
#[test]
fn test_list_signatures_match_main() {
let methods = operator_kwargs();
- let list = "limit=None start_after=None recursive=None versions=None
deleted=None";
+ let list =
+ "limit=None start_after=None recursive=None versions=None
deleted=None glob=None";
let scan = "limit=None start_after=None versions=None deleted=None";
for (ty, method, kwargs) in [
("Operator", "list", list),
@@ -4118,15 +4193,26 @@ print(json.dumps(docs))
fn test_signatures_match_options_table() {
let parsed = core_options();
let methods = operator_kwargs();
- // `scan` is `list` with `recursive=True`, `presign_stat` cannot
- // request a checksum, `presign_delete` takes only a version,
+ // `scan` is the deprecated `list` with `recursive=True` and no
+ // `glob`, `presign_stat` cannot request a checksum,
+ // `presign_delete` takes only a version,
// `presign_read` takes no range or read tuning, and `presign_write`
// takes no write mode, tuning, or checksum.
for (ty, method, class, omitted) in [
("Operator", "list", "ListOptions", &[][..]),
- ("Operator", "scan", "ListOptions", &["recursive"][..]),
+ (
+ "Operator",
+ "scan",
+ "ListOptions",
+ &["recursive", "glob"][..],
+ ),
("AsyncOperator", "list", "ListOptions", &[][..]),
- ("AsyncOperator", "scan", "ListOptions", &["recursive"][..]),
+ (
+ "AsyncOperator",
+ "scan",
+ "ListOptions",
+ &["recursive", "glob"][..],
+ ),
("Operator", "stat", "StatOptions", &[][..]),
("AsyncOperator", "stat", "StatOptions", &[][..]),
(
@@ -4254,7 +4340,7 @@ print(json.dumps(docs))
options.fields.iter().position(|f| f.name == name).unwrap()
}
type Mutation = fn(&mut OptionsStruct);
- let cases: [(&str, Mutation, &str); 48] = [
+ let cases: [(&str, Mutation, &str); 49] = [
(
"ListOptions",
|list| {
@@ -4282,6 +4368,15 @@ print(json.dumps(docs))
"core ListOptions::start_after has kind Bool; \
Python ListOptions.start_after requires OptionString",
),
+ (
+ "ListOptions",
+ |list| {
+ let i = position(list, "glob");
+ list.fields[i].kind = OptionKind::Bool;
+ },
+ "core ListOptions::glob has kind Bool; \
+ Python ListOptions.glob requires OptionString",
+ ),
(
"ListOptions",
|list| {
@@ -4998,15 +5093,19 @@ print(json.dumps(docs))
"and [`Self::checksum`][crate::StatOptions::checksum];
[rfc](https://example.com), [x] and `v[0]` stay.",
]
.map(String::from);
+ let renames = [
+ ("Self::recursive", "recursive"),
+ ("Self::checksum", "checksum"),
+ ];
assert_eq!(
- py_doc(&lines, "Test", &py_names(), &[]).unwrap(),
+ py_doc(&lines, "Test", &py_names(), &renames).unwrap(),
[
- "Use `crate::Operator::list_with` and `Self::recursive`.",
+ "Use `crate::Operator::list_with` and `recursive`.",
"",
"A [plain](https://opendal.apache.org) link and `code` stay.",
"",
"See the checksum specification, the guide,",
- "and `Self::checksum`; [rfc](https://example.com), [x] and
`v[0]` stay.",
+ "and `checksum`; [rfc](https://example.com), [x] and `v[0]`
stay.",
]
);
}
@@ -5036,20 +5135,38 @@ print(json.dumps(docs))
]
);
- // A core field that a keyword argument of another name sets reads
- // as that keyword argument.
+ // A core field that a keyword argument of another name sets, or a
+ // `Self::` path to it, reads as that keyword argument.
let lines = [
"Conflicts with
[`override_content_type`](Self::override_content_type) and
`override_cache_control`,",
- "not `override_content_disposition`,
`Self::override_content_type`, or override_content_type.",
+ "not `override_content_disposition`,
[`Self::override_cache_control`], or override_content_type.",
]
.map(String::from);
+ let renames = [
+ STAT_RENAMES[0],
+ STAT_RENAMES[1],
+ ("Self::override_cache_control", "cache_control"),
+ ];
assert_eq!(
- py_doc(&lines, "Test", &py_names(), &STAT_RENAMES[..2]).unwrap(),
+ py_doc(&lines, "Test", &py_names(), &renames).unwrap(),
[
"Conflicts with `content_type` and `cache_control`,",
- "not `override_content_disposition`,
`Self::override_content_type`, or override_content_type.",
+ "not `override_content_disposition`, `cache_control`, or
override_content_type.",
]
);
+
+ // A `Self::` path without a Python name fails, unless Python drops
+ // its sentence.
+ let lines = ["Independent of [`Self::recursive`].".to_string()];
+ assert_eq!(
+ py_doc(&lines, "Test", &py_names(), &[])
+ .unwrap_err()
+ .to_string(),
+ "core Test docs name `Self::recursive`, which has no Python name"
+ );
+ let lines =
+ ["Kept. Built by [`crate::layers::SimulateLayer`] from
[`Self::new`].".to_string()];
+ assert_eq!(py_doc(&lines, "Test", &py_names(), &[]).unwrap(),
["Kept."]);
}
/// Core returns an error kind, while Python raises the exception.
@@ -5178,6 +5295,19 @@ print(json.dumps(docs))
r#"Needs
[`Capability::list_with_deleted`](crate::Capability::list_with_deleted) and \
"x""#
.to_string(),
];
+ // The Python rewrite replaces the dropped `SimulateLayer` sentence
+ // and the `list_with_recursive` requirement.
+ *field(list, "glob") = [
+ "Reworded glob doc, independent of [`Self::recursive`].",
+ "",
+ "Needs
[`Capability::list_with_glob`](crate::Capability::list_with_glob). Uses",
+ "[`crate::layers::SimulateLayer`] otherwise. Combining a
multi-directory pattern",
+ "with `start_after`, `versions`, or `deleted` during client-side
simulation also",
+ "requires `Capability::list_with_recursive`. Malformed or empty
patterns fail with",
+ "[`crate::ErrorKind::ConfigInvalid`].",
+ ]
+ .map(String::from)
+ .to_vec();
let generated = generated_classes(&parsed, &py_names()).unwrap();
let class = &generated[0];
@@ -5189,6 +5319,16 @@ print(json.dumps(docs))
r#"Reworded "start_after" doc. Needs
`op.capability().list_with_start_after`. Keys match \d+."#
]
);
+ assert_eq!(
+ class.fields[5].doc,
+ [
+ "Reworded glob doc, independent of `recursive`.",
+ "",
+ "Needs `op.capability().list_with_glob`. Services with native
glob support \
+ handle patterns directly; otherwise OpenDAL evaluates
patterns client-side. \
+ Malformed or empty patterns fail with
`opendal.exceptions.ConfigInvalid`.",
+ ]
+ );
let py = render_options_py(&generated).unwrap();
// `bindings/python/tests/test_stub_docstrings.py` checks that
@@ -6037,8 +6177,9 @@ print(json.dumps(docs))
"list_with_recursive",
"list_with_versions",
"list_with_deleted",
+ "list_with_glob",
][..],
- &["Unsupported"][..],
+ &["ConfigInvalid", "Unsupported"][..],
),
(
"StatOptions",