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 4f064d75ff feat(bindings/python): generate CopyOptions from core
(#9398)
4f064d75ff is described below
commit 4f064d75ff8fa61439d089f13ed80a11ccf106a9
Author: Chitral Verma <[email protected]>
AuthorDate: Mon Nov 30 01:04:49 2026 +0530
feat(bindings/python): generate CopyOptions from core (#9398)
* feat(bindings/python): generate CopyOptions from core
Generate the Python CopyOptions pyclass and CopyKwargs from core's
CopyOptions. The if_not_exists keyword argument keeps its name, type,
and default, and every other core field keeps its core default.
The docstrings come from core. Python reads core's "which error the copy
returns is unspecified" as "which exception the copy raises is
unspecified".
The OpenKwargs docstring now says that open() ignores an option of the
other mode when its value is None and raises TypeError for any other
value, and that in write modes open() sets chunk to 256 KiB when the
service has no write_multi_min_size.
Signed-off-by: Chitral Verma <[email protected]>
* fix(bindings/python): state the None rule for open() response overrides
In read mode, open() ignores content_type, cache_control, and
content_disposition when their value is None and raises TypeError for
any other value, as for every other writer option. The OpenKwargs
docstring said that they always raise TypeError.
The test of the 256 KiB open() chunk now requires its whole condition
in both open() methods, not only the 256 KiB value.
Signed-off-by: Chitral Verma <[email protected]>
---------
Signed-off-by: Chitral Verma <[email protected]>
---
bindings/python/python/opendal/options.py | 49 +++-
bindings/python/src/options.rs | 17 --
bindings/python/src/options/generated.rs | 65 ++++++
dev/src/generate/options.rs | 6 +-
dev/src/generate/python.rs | 371 +++++++++++++++++++++++++++++-
5 files changed, 476 insertions(+), 32 deletions(-)
diff --git a/bindings/python/python/opendal/options.py
b/bindings/python/python/opendal/options.py
index 0d470d528d..3f5645a06d 100644
--- a/bindings/python/python/opendal/options.py
+++ b/bindings/python/python/opendal/options.py
@@ -593,10 +593,37 @@ class StatKwargs(TypedDict, total=False):
class CopyKwargs(TypedDict, total=False):
- """Options for `copy` operations."""
+ """Options for copy operations.
+
+ Each condition checks the destination file, never the source, and every
+ condition must hold for the copy to proceed:
+
+ - A false condition fails the copy with
+ `opendal.exceptions.ConditionNotMatch`.
+ - A condition the service does not advertise through its capability fails
+ the copy with `opendal.exceptions.Unsupported`; OpenDAL never silently
+ drops a condition.
+ - A missing source fails the copy with `opendal.exceptions.NotFound`;
+ when a condition error applies at the same time, which exception the copy
+ raises is unspecified.
+ - A service-side conflict unrelated to these conditions surfaces as
+ `opendal.exceptions.Conflict`.
+
+ See the conditional operation specification
+ for the complete cross-operation contract.
+ """
if_not_exists: bool
- """Whether to fail if a file already exists at the target path."""
+ """Copy only when no file exists at the destination path.
+
+ The condition succeeds when the destination path is empty, so the
+ copy creates the destination file. An existing destination file fails
+ the copy with `opendal.exceptions.ConditionNotMatch`.
+
+ The operation raises `opendal.exceptions.Unsupported` when the
+ service does not advertise
+ `op.capability().copy_with_if_not_exists`.
+ """
class RenameKwargs(TypedDict, total=False):
@@ -668,13 +695,17 @@ class OpenKwargs(ReadKwargs, WriteKwargs, total=False):
"""Keyword arguments for `Operator.open` and `AsyncOperator.open`.
Accepted keys depend on `mode`: read modes (`"r"`, `"rb"`, `"br"`) accept
- reader options only, while write, append, and create modes (`"w"`, `"wb"`,
- `"ab"`, `"xb"`, etc.) accept writer options only.
+ reader options, while write, append, and create modes (`"w"`, `"wb"`,
+ `"ab"`, `"xb"`, etc.) accept writer options. `Operator.open()` and
+ `AsyncOperator.open()` ignore an option of the other mode when its value
+ is `None`, and raise `TypeError` for any other value, such as `offset=0`
+ in write mode.
The `content_type`, `cache_control`, and `content_disposition` options
- apply only when writing, appending, or creating and raise `TypeError` in
- read mode. Use the operator's `read()` method to supply response header
- overrides.
+ apply only when writing, appending, or creating. In read mode, `open()`
+ ignores each of them when its value is `None` and raises `TypeError` for
+ any other value. Use the operator's `read()` method to supply response
+ header overrides.
In read mode, `open()` raises `opendal.exceptions.Unsupported` for an
option that the service does not support. With a positive `chunk` and
@@ -684,7 +715,9 @@ class OpenKwargs(ReadKwargs, WriteKwargs, total=False):
`OSError` from the file's read methods, or from `seek()` when seeking
from the end needs the file's size.
- In write, append, and create modes, `open()` raises
+ In write, append, and create modes, `open()` sets `chunk` to 256 KiB when
+ `chunk` is unset or `0` and the service has no
+ `op.capability().write_multi_min_size`. `open()` raises
`opendal.exceptions.Unsupported` for appending, a condition, or a
`checksum` that the service does not support. Errors while writing
surface from the file: its `write()`, and the `flush()` of a file from
diff --git a/bindings/python/src/options.rs b/bindings/python/src/options.rs
index 423e0450af..b177c91940 100644
--- a/bindings/python/src/options.rs
+++ b/bindings/python/src/options.rs
@@ -211,23 +211,6 @@ impl From<ReadOptions> for ocore::options::ReaderOptions {
}
}
-/// Options for `copy` operations.
-#[pyclass(module = "opendal")]
-#[derive(Default, Debug)]
-pub struct CopyOptions {
- /// Whether to fail if a file already exists at the target path.
- pub if_not_exists: Option<bool>,
-}
-
-impl From<CopyOptions> for ocore::options::CopyOptions {
- fn from(opts: CopyOptions) -> Self {
- Self {
- if_not_exists: opts.if_not_exists.unwrap_or(false),
- ..Default::default()
- }
- }
-}
-
/// Options for `rename` operations.
#[pyclass(module = "opendal")]
#[derive(Default, Debug)]
diff --git a/bindings/python/src/options/generated.rs
b/bindings/python/src/options/generated.rs
index 400f6ef673..fbc0f344b8 100644
--- a/bindings/python/src/options/generated.rs
+++ b/bindings/python/src/options/generated.rs
@@ -783,3 +783,68 @@ impl From<WriteOptions> for ocore::options::WriteOptions {
}
}
}
+
+/// Options for copy operations.
+///
+/// Each condition checks the destination file, never the source, and every
+/// condition must hold for the copy to proceed:
+///
+/// - A false condition fails the copy with
+/// `opendal.exceptions.ConditionNotMatch`.
+/// - A condition the service does not advertise through its capability fails
+/// the copy with `opendal.exceptions.Unsupported`; OpenDAL never silently
+/// drops a condition.
+/// - A missing source fails the copy with `opendal.exceptions.NotFound`;
+/// when a condition error applies at the same time, which exception the copy
+/// raises is unspecified.
+/// - A service-side conflict unrelated to these conditions surfaces as
+/// `opendal.exceptions.Conflict`.
+///
+/// See the conditional operation specification
+/// for the complete cross-operation contract.
+#[pyclass(module = "opendal")]
+#[derive(Default, Debug)]
+pub struct CopyOptions {
+ /// Copy only when no file exists at the destination path.
+ ///
+ /// The condition succeeds when the destination path is empty, so the
+ /// copy creates the destination file. An existing destination file fails
+ /// the copy with `opendal.exceptions.ConditionNotMatch`.
+ ///
+ /// The operation raises `opendal.exceptions.Unsupported` when the
+ /// service does not advertise
+ /// `op.capability().copy_with_if_not_exists`.
+ pub if_not_exists: Option<bool>,
+}
+
+impl<'a, 'py> FromPyObject<'a, 'py> for CopyOptions {
+ type Error = PyErr;
+
+ fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
+ let dict = downcast_kwargs(obj)?;
+
+ Ok(Self {
+ if_not_exists: extract_optional(&dict, "if_not_exists")?,
+ })
+ }
+}
+
+impl From<CopyOptions> for ocore::options::CopyOptions {
+ fn from(opts: CopyOptions) -> Self {
+ Self {
+ if_not_exists: opts.if_not_exists.unwrap_or(false),
+ if_match: None,
+ if_none_match: None,
+ if_version_match: None,
+ if_version_not_match: None,
+ if_not_changed: None,
+ source_version: None,
+ user_metadata: None,
+ content_type: None,
+ content_language: None,
+ source_content_length_hint: None,
+ concurrent: 0,
+ chunk: None,
+ }
+ }
+}
diff --git a/dev/src/generate/options.rs b/dev/src/generate/options.rs
index b8c699d286..2383199715 100644
--- a/dev/src/generate/options.rs
+++ b/dev/src/generate/options.rs
@@ -194,7 +194,7 @@ mod tests {
let options = parse(&path).unwrap();
let names: Vec<&str> = options.iter().map(|o|
o.name.as_str()).collect();
- assert_eq!(names, ["CopyOptions", "RenameOptions"]);
+ assert_eq!(names, ["RenameOptions"]);
for option in &options {
assert!(
@@ -208,8 +208,8 @@ mod tests {
}
// A field doc keeps its paragraphs, which `options.py` renders as
- // separate docstring paragraphs. The hand-written structs only have
- // `Option<bool>` fields now, so a sample covers the other types.
+ // separate docstring paragraphs. The hand-written struct only has an
+ // `Option<bool>` field now, so a sample covers the other types.
let options = parse_struct(&syn::parse_quote! {
pub struct FakeOptions {
/// First paragraph,
diff --git a/dev/src/generate/python.rs b/dev/src/generate/python.rs
index fd951dd90d..e748c2d833 100644
--- a/dev/src/generate/python.rs
+++ b/dev/src/generate/python.rs
@@ -1075,6 +1075,21 @@ const GENERATED_OPTIONS: &[PyOptions] = &[
),
],
},
+ PyOptions {
+ name: "CopyOptions",
+ options: &[(
+ "if_not_exists",
+ "if_not_exists",
+ OptionKind::Bool,
+ "Option<bool>",
+ )],
+ unmirrored: &[],
+ docs: &[],
+ rewrites: &[(
+ "which error the copy\nreturns is unspecified",
+ "which exception the copy\nraises is unspecified",
+ )],
+ },
];
/// The class order of `options.py`, which hand-written and generated classes
@@ -1717,7 +1732,7 @@ fn render_options_py(workspace_dir: &Path, generated:
&[PyClass]) -> Result<Stri
// TypedDict inherits both.
exports.push("OpenKwargs".to_string());
out.push_str(
- "\n\nclass OpenKwargs(ReadKwargs, WriteKwargs, total=False):\n
\"\"\"Keyword arguments for `Operator.open` and `AsyncOperator.open`.\n\n
Accepted keys depend on `mode`: read modes (`\"r\"`, `\"rb\"`, `\"br\"`)
accept\n reader options only, while write, append, and create modes
(`\"w\"`, `\"wb\"`,\n `\"ab\"`, `\"xb\"`, etc.) accept writer options
only.\n\n The `content_type`, `cache_control`, and `content_disposition`
options\n apply only when writing, appending, [...]
+ "\n\nclass OpenKwargs(ReadKwargs, WriteKwargs, total=False):\n
\"\"\"Keyword arguments for `Operator.open` and `AsyncOperator.open`.\n\n
Accepted keys depend on `mode`: read modes (`\"r\"`, `\"rb\"`, `\"br\"`)
accept\n reader options, while write, append, and create modes (`\"w\"`,
`\"wb\"`,\n `\"ab\"`, `\"xb\"`, etc.) accept writer options.
`Operator.open()` and\n `AsyncOperator.open()` ignore an option of the other
mode when its value\n is `None`, and raise `T [...]
);
out.push_str("\n\n__all__ = [\n");
@@ -1844,7 +1859,8 @@ mod tests {
"StatOptions",
"DeleteOptions",
"ReadOptions",
- "WriteOptions"
+ "WriteOptions",
+ "CopyOptions"
]
);
classes
@@ -2037,6 +2053,24 @@ 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 `CopyOptions` docs for core text that does
+ /// not hold for Python, as `(core, Python)`.
+ const COPY_REWRITES: [(&str, &str); 1] = [(
+ "which error the copy\nreturns is unspecified",
+ "which exception the copy\nraises is unspecified",
+ )];
+
+ /// `py_doc` of a core `CopyOptions` doc, with the Python wording.
+ fn copy_doc(core_doc: &[String], item: &str) -> Vec<String> {
+ let text = py_doc(core_doc, item, &py_names(),
&[]).unwrap().join("\n");
+ COPY_REWRITES
+ .iter()
+ .fold(text, |text, (from, to)| text.replace(from, to))
+ .split('\n')
+ .map(String::from)
+ .collect()
+ }
+
/// 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
@@ -2506,6 +2540,63 @@ print(json.dumps(docs))
}
}
+ /// The `CopyOptions` surface on main (c3dd68eb4), copied from
+ /// `bindings/python/src/options.rs`, and the Python checks and exceptions
+ /// its docs name: the capability is the one `OpCopy::check` in
+ /// `core/core/src/raw/ops.rs` enforces for `if_not_exists`, and the
+ /// exceptions are the error kinds in `core/core/src/types/options.rs`.
+ /// It pins no core wording.
+ fn assert_copy_surface(class: &PyClass) {
+ let fields: Vec<String> = class
+ .fields
+ .iter()
+ .map(|f| format!("{}: {}", f.name, f.rust_type))
+ .collect();
+ assert_eq!(fields, ["if_not_exists: Option<bool>"]);
+
+ assert_eq!(
+ spans(&class.doc, "opendal.exceptions."),
+ ["ConditionNotMatch", "Unsupported", "NotFound", "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,
+ ["if_not_exists: copy_with_if_not_exists / 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.",
+ "copy returns",
+ ] {
+ 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`.
@@ -3281,6 +3372,100 @@ print(json.dumps(docs))
assert!(rs.contains(&format!("{expected}}}\n")), "{rs}");
}
+ /// The `CopyOptions` API on main (c3dd68eb4), copied from
+ /// `bindings/python/src/options.rs`, with docstrings taken from core.
+ #[test]
+ fn test_copy_options_match_main() {
+ let parsed = core_options();
+ let class = generated_class(&parsed, "CopyOptions");
+ assert_copy_surface(&class);
+
+ // Each docstring is the core doc comment of the field it sets, with
+ // the Python wording.
+ let core = parsed.iter().find(|o| o.name == "CopyOptions").unwrap();
+ assert_eq!(class.doc, copy_doc(&core.doc, "CopyOptions"));
+ for field in &class.fields {
+ let core = core.fields.iter().find(|f| f.name ==
field.name).unwrap();
+ assert_eq!(field.doc, copy_doc(&core.doc, field.name), "{}",
field.name);
+ }
+ assert!(
+ class.doc.join(" ").contains(
+ "A missing source fails the copy with
`opendal.exceptions.NotFound`; when a \
+ condition error applies at the same time, which exception the
copy raises \
+ is unspecified."
+ ),
+ "{:?}",
+ class.doc
+ );
+
+ // `if_not_exists` sets the core field main set, an omitted
+ // `if_not_exists` is `false`, and every other core field 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, ["if_not_exists:
opts.if_not_exists.unwrap_or(false)"]);
+ for field in [
+ "if_match: None",
+ "if_none_match: None",
+ "if_not_changed: None",
+ "source_version: None",
+ "user_metadata: None",
+ "concurrent: 0",
+ ] {
+ 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 only `if_not_exists` from a dict and ignores
+ // any other key.
+ let rs = render_options_rs(&generated_classes(&parsed,
&py_names()).unwrap()).unwrap();
+ let extract = rs
+ .split_once("impl<'a, 'py> FromPyObject<'a, 'py> for CopyOptions
{")
+ .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,
+ ["if_not_exists: extract_optional(&dict, \"if_not_exists\")?,"]
+ );
+ assert!(!extract.contains("reject_unknown_kwargs"));
+
+ // The pyclass holds the field after its doc comment, which becomes
+ // `__doc__`.
+ 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 field = &class.fields[0];
+ let expected = format!(
+ "{}\n#[pyclass(module = \"opendal\")]\n#[derive(Default,
Debug)]\npub struct CopyOptions {{\n{}\n pub if_not_exists:
Option<bool>,\n}}\n",
+ comment(&class.doc, ""),
+ comment(&field.doc, " "),
+ );
+ assert!(rs.contains(&expected), "{rs}");
+ }
+
/// `WRITE_OPTION_KEYS`, which `open` accepts in a write mode, matches main
/// (a2ef00d6e) and the table.
#[test]
@@ -3598,6 +3783,7 @@ print(json.dumps(docs))
"checksum: bool",
]
);
+ assert_eq!(keys("CopyKwargs", "RenameKwargs"), ["if_not_exists:
bool"]);
assert_eq!(
keys("DeleteKwargs", "OpenKwargs"),
["version: str", "recursive: bool", "if_match: str"]
@@ -3613,7 +3799,15 @@ print(json.dumps(docs))
"`OSError`",
"With a positive `chunk` and no `size`, `open()` first stats the
file",
"or from `seek()` when seeking from the end needs the file's size",
- "In write, append, and create modes, `open()` raises \
+ "`Operator.open()` and `AsyncOperator.open()` ignore an option of
the other \
+ mode when its value is `None`, and raise `TypeError` for any
other value, \
+ such as `offset=0` in write mode.",
+ "options apply only when writing, appending, or creating. In read
mode, \
+ `open()` ignores each of them when its value is `None` and raises
\
+ `TypeError` for any other value.",
+ "In write, append, and create modes, `open()` sets `chunk` to 256
KiB when \
+ `chunk` is unset or `0` and the service has no \
+ `op.capability().write_multi_min_size`. `open()` raises \
`opendal.exceptions.Unsupported` for appending, a condition, or a
`checksum`",
"raise `opendal.exceptions.ConditionNotMatch` for a failed
condition and \
`OSError` for any other error, while `close()` raises each error
as its \
@@ -3734,6 +3928,19 @@ print(json.dumps(docs))
assert!(!methods.contains_key(&("Operator".to_string(),
"presign_write".to_string())));
}
+ /// The `copy` keyword arguments and defaults on main (c3dd68eb4), copied
+ /// from `python/opendal/operator.pyi`.
+ #[test]
+ fn test_copy_signatures_match_main() {
+ let methods = operator_kwargs();
+ for ty in ["Operator", "AsyncOperator"] {
+ let key = (ty.to_string(), "copy".to_string());
+ assert_eq!(methods[&key].join(" "), "if_not_exists=None",
"{ty}.copy");
+ let presign = (ty.to_string(), "presign_copy".to_string());
+ assert!(!methods.contains_key(&presign), "{ty}.presign_copy");
+ }
+ }
+
/// 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`.
@@ -3782,6 +3989,8 @@ print(json.dumps(docs))
"WriteOptions",
&["append", "chunk", "concurrent", "checksum"][..],
),
+ ("Operator", "copy", "CopyOptions", &[][..]),
+ ("AsyncOperator", "copy", "CopyOptions", &[][..]),
] {
let class = generated_class(&parsed, class);
let mut expected: Vec<String> = class
@@ -3826,6 +4035,7 @@ print(json.dumps(docs))
"DeleteOptions",
"ReadOptions",
"WriteOptions",
+ "CopyOptions",
]
.contains(&o.name.as_str())
}) {
@@ -3859,6 +4069,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();
@@ -3871,7 +4083,7 @@ print(json.dumps(docs))
options.fields.iter().position(|f| f.name == name).unwrap()
}
type Mutation = fn(&mut OptionsStruct);
- let cases: [(&str, Mutation, &str); 38] = [
+ let cases: [(&str, Mutation, &str); 43] = [
(
"ListOptions",
|list| {
@@ -4200,6 +4412,47 @@ print(json.dumps(docs))
exists, without accessing storage.`; \
update its Python rewrite in dev/src/generate/python.rs",
),
+ (
+ "CopyOptions",
+ |copy| {
+ copy.fields.remove(position(copy, "if_not_exists"));
+ },
+ "core CopyOptions has no field `if_not_exists` \
+ for Python CopyOptions.if_not_exists",
+ ),
+ (
+ "CopyOptions",
+ |copy| {
+ let i = position(copy, "if_not_exists");
+ copy.fields[i].kind = OptionKind::OptionString;
+ },
+ "core CopyOptions::if_not_exists has kind OptionString; \
+ Python CopyOptions.if_not_exists requires Bool",
+ ),
+ (
+ "CopyOptions",
+ |copy| {
+ let i = position(copy, "if_not_exists");
+ copy.fields[i].doc.clear();
+ },
+ "core CopyOptions::if_not_exists has no doc comment",
+ ),
+ (
+ "CopyOptions",
+ |copy| copy.has_unmirrored_fields = true,
+ "core CopyOptions has fields the core options parser skips;
Python cannot set them",
+ ),
+ (
+ "CopyOptions",
+ |copy| {
+ for line in &mut copy.doc {
+ *line = line.replace("which error the copy", "which
error it");
+ }
+ },
+ "core CopyOptions docs no longer contain \
+ `which error the copy\nreturns is unspecified`; \
+ update its Python rewrite in dev/src/generate/python.rs",
+ ),
];
let parsed = core_options();
@@ -5195,6 +5448,74 @@ print(json.dumps(docs))
}
}
+ /// Reworded core `CopyOptions` docs, in either markup and with quotes and
+ /// backslashes, pass the surface checks and read back in Python.
+ #[test]
+ fn test_copy_options_survive_core_rewording() {
+ let mut parsed = core_options();
+ let base = generated_class(&parsed, "CopyOptions");
+ let copy = parsed.iter_mut().find(|o| o.name ==
"CopyOptions").unwrap();
+ copy.doc = [
+ r#""Copy" options, with \d."#,
+ "",
+ "- A failed condition returns `ErrorKind::ConditionNotMatch`.",
+ "- A missing capability returns
[`ErrorKind::Unsupported`](crate::ErrorKind::Unsupported).",
+ "- A missing source returns `NotFound`; which error the copy",
+ "returns is unspecified.",
+ "- A conflict surfaces as [`crate::ErrorKind::Conflict`].",
+ ]
+ .map(String::from)
+ .to_vec();
+ for field in &mut copy.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}`](crate::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 ==
"CopyOptions").unwrap();
+ assert_copy_surface(class);
+
+ let py = render_options_py(&crate::workspace_dir(),
&generated).unwrap();
+ let docs = python_docstrings(&py);
+ assert_eq!(
+ docs["CopyKwargs"],
+ "\"Copy\" options, with \\d.\n\
+ \n\
+ - A failed condition raises
`opendal.exceptions.ConditionNotMatch`.\n\
+ - A missing capability raises `opendal.exceptions.Unsupported`.\n\
+ - A missing source raises `opendal.exceptions.NotFound`; which
exception the copy\n\
+ raises is unspecified.\n\
+ - A conflict surfaces as `opendal.exceptions.Conflict`."
+ );
+ assert_eq!(
+ docs["CopyKwargs.if_not_exists"],
+ "Reworded \"if_not_exists\" doc, see the spec.\n\
+ Check `op.capability().copy_with_if_not_exists`.\n\
+ It raises `opendal.exceptions.ConditionNotMatch`.\n\
+ It raises `opendal.exceptions.Unsupported`."
+ );
+ }
+
/// The hand-written `read` docstrings in `bindings/python/src/operator.rs`
/// agree with the generated `ReadOptions` docs: both name the overrides
/// that a positive `prefetch` rejects with `ValueError`, which
@@ -5330,6 +5651,43 @@ print(json.dumps(docs))
2,
"Operator.open and AsyncOperator.open"
);
+ // `open()` sets the 256 KiB `chunk` that `OpenKwargs` and the `chunk`
+ // doc name, under the condition `OpenKwargs` states.
+ let code = operator.split_whitespace().collect::<Vec<_>>().join(" ");
+ let default_chunk = "if matches!(writer_opts.chunk, None | Some(0)) \
+ &&
this.info().capability().write_multi_min_size.is_none() \
+ { writer_opts.chunk = Some(256 * 1024); }";
+ assert_eq!(
+ code.matches(default_chunk).count(),
+ 2,
+ "Operator.open and AsyncOperator.open"
+ );
+ }
+
+ /// The hand-written `copy` docstrings name the capability and exceptions
+ /// of the generated `CopyOptions.if_not_exists` doc.
+ #[test]
+ fn test_copy_docstrings_agree_with_copy_options() {
+ let path =
crate::workspace_dir().join("bindings/python/src/operator.rs");
+ let operator = fs::read_to_string(path).unwrap();
+ let class = generated_class(&core_options(), "CopyOptions");
+ let doc = &class.fields[0].doc;
+ let capability = spans(doc, "op.capability().");
+ let exceptions = spans(doc, "opendal.exceptions.");
+ assert_eq!(capability, ["copy_with_if_not_exists"]);
+ assert_eq!(exceptions, ["ConditionNotMatch", "Unsupported"]);
+ let param = format!(
+ " /// if_not_exists : bool, optional\n \
+ /// If True, require `{}` and raise `{}`\n \
+ /// if the service lacks it. Raise `{}` if the target\n \
+ /// already exists. Defaults to False, which allows
overwriting.\n",
+ capability[0], exceptions[1], exceptions[0]
+ );
+ assert_eq!(
+ operator.matches(¶m).count(),
+ 2,
+ "Operator.copy and AsyncOperator.copy"
+ );
}
/// Every capability and exception the generated docstrings name exists
@@ -5429,6 +5787,11 @@ print(json.dumps(docs))
][..],
&["ConditionNotMatch", "Conflict", "Unsupported"][..],
),
+ (
+ "CopyOptions",
+ &["copy_with_if_not_exists"][..],
+ &["ConditionNotMatch", "Conflict", "NotFound",
"Unsupported"][..],
+ ),
] {
let class = generated_class(&parsed, class);
let docs: Vec<String> = class