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 c3dd68eb43 feat(bindings/python): generate WriteOptions from core
(#9388)
c3dd68eb43 is described below
commit c3dd68eb43758f8a546f8e2ee3e56c3c6bb3b033
Author: Chitral Verma <[email protected]>
AuthorDate: Sun Nov 29 23:51:08 2026 +0530
feat(bindings/python): generate WriteOptions from core (#9388)
* feat(bindings/python): generate WriteOptions from core
Signed-off-by: Chitral Verma <[email protected]>
* fixup! feat(bindings/python): generate WriteOptions from core
Signed-off-by: Chitral Verma <[email protected]>
---------
Signed-off-by: Chitral Verma <[email protected]>
---
bindings/python/python/opendal/_opendal.pyi | 23 +-
bindings/python/python/opendal/operator.pyi | 38 +-
bindings/python/python/opendal/options.py | 257 +++++-
bindings/python/src/operator.rs | 42 +-
bindings/python/src/options.rs | 89 +-
bindings/python/src/options/generated.rs | 293 +++++++
dev/src/generate/options.rs | 47 +-
dev/src/generate/python.rs | 1268 +++++++++++++++++++++++++--
8 files changed, 1853 insertions(+), 204 deletions(-)
diff --git a/bindings/python/python/opendal/_opendal.pyi
b/bindings/python/python/opendal/_opendal.pyi
index 51fc77d368..9501584f20 100644
--- a/bindings/python/python/opendal/_opendal.pyi
+++ b/bindings/python/python/opendal/_opendal.pyi
@@ -122,7 +122,28 @@ class StatOptions:
@final
class WriteOptions:
- """Options for `write` operations."""
+ """
+ Options for write operations.
+
+ Each condition checks the file currently stored at the write path, and
+ the service evaluates it atomically with the write's visible commit:
+
+ - A false condition fails the write with
+ `opendal.exceptions.ConditionNotMatch` and leaves the previously
+ visible file unchanged. In a write mode, `open()` does not access storage,
+ so depending on the service, a check against the stored file fails
+ while writing to the file or when closing it.
+ - A condition the service does not advertise through its capability fails
+ the write 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`, or as `OSError` from the `write()` or
+ `flush()` of a file from `open()`.
+
+ See the conditional operation specification
+ for the complete cross-operation contract.
+ """
def _reconstruct_async_operator(scheme: str, map: dict[str, str]) ->
AsyncOperator:
"""
diff --git a/bindings/python/python/opendal/operator.pyi
b/bindings/python/python/opendal/operator.pyi
index f14507c4d2..946acbe58b 100644
--- a/bindings/python/python/opendal/operator.pyi
+++ b/bindings/python/python/opendal/operator.pyi
@@ -379,8 +379,8 @@ class AsyncOperator:
update (`"+"`) modes, or if the mode conflicts with `append` or
`if_not_exists` in `**kwargs`, or if the checksum name is
unrecognized.
ConditionNotMatch
- If create mode (`"x"`) targets an existing file. The failure can
- surface from `write()` or `close()`.
+ If create mode (`"x"`) targets an existing file, or another write
+ condition fails. The failure can surface from `write()` or
`close()`.
Unsupported
If the service does not support the requested read or write
options,
including the selected checksum algorithm. Append writes cannot
request
@@ -395,6 +395,9 @@ class AsyncOperator:
file size. With a positive `chunk` and no `size`, `open()` stats
the
file first and raises such errors as `opendal.exceptions` classes
itself.
+ In write, append, or create mode, if writing fails other than by a
+ failed condition. The failure surfaces from the file's `write()`,
+ while `close()` raises such errors as `opendal.exceptions` classes.
Returns
-------
@@ -807,7 +810,9 @@ class AsyncOperator:
chunk : int, optional
The chunk size to use when writing the file.
concurrent : int, optional
- The number of concurrent requests to make when writing the file.
+ The number of writes to run concurrently. Without `chunk`,
`write()`
+ passes its bytes to the service writer as one write, which only a
+ service that splits it internally can write concurrently.
cache_control : str, optional
The cache control header to set on the file.
content_type : str, optional
@@ -832,9 +837,12 @@ class AsyncOperator:
------
ValueError
If the checksum name is unrecognized.
+ ConditionNotMatch
+ If `if_match`, `if_none_match`, or `if_not_exists` fails.
Unsupported
- If the service cannot verify the write with the selected algorithm,
- including when appending.
+ If the service does not support `append`, a requested condition, or
+ the selected checksum algorithm. Append writes cannot request a
+ checksum.
ChecksumMismatch
If the checksum fails verification.
@@ -1162,8 +1170,9 @@ class Operator:
update (`"+"`) modes, or if the mode conflicts with `append` or
`if_not_exists` in `**kwargs`, or if the checksum name is
unrecognized.
ConditionNotMatch
- If create mode (`"x"`) targets an existing file. The failure can
- surface from `write()`, `flush()`, or `close()`.
+ If create mode (`"x"`) targets an existing file, or another write
+ condition fails. The failure can surface from `write()`, `flush()`,
+ or `close()`.
Unsupported
If the service does not support the requested read or write
options,
including the selected checksum algorithm. Append writes cannot
request
@@ -1178,6 +1187,10 @@ class Operator:
file size. With a positive `chunk` and no `size`, `open()` stats
the
file first and raises such errors as `opendal.exceptions` classes
itself.
+ In write, append, or create mode, if writing fails other than by a
+ failed condition. The failure surfaces from the file's `write()` or
+ `flush()`, while `close()` raises such errors as
`opendal.exceptions`
+ classes.
Returns
-------
@@ -1415,7 +1428,9 @@ class Operator:
chunk : int, optional
The chunk size to use when writing the file.
concurrent : int, optional
- The number of concurrent requests to make when writing the file.
+ The number of writes to run concurrently. Without `chunk`,
`write()`
+ passes its bytes to the service writer as one write, which only a
+ service that splits it internally can write concurrently.
cache_control : str, optional
The cache control header to set on the file.
content_type : str, optional
@@ -1440,9 +1455,12 @@ class Operator:
------
ValueError
If the checksum name is unrecognized.
+ ConditionNotMatch
+ If `if_match`, `if_none_match`, or `if_not_exists` fails.
Unsupported
- If the service cannot verify the write with the selected algorithm,
- including when appending.
+ If the service does not support `append`, a requested condition, or
+ the selected checksum algorithm. Append writes cannot request a
+ checksum.
ChecksumMismatch
If the checksum fails verification.
"""
diff --git a/bindings/python/python/opendal/options.py
b/bindings/python/python/opendal/options.py
index c0489223d3..0d470d528d 100644
--- a/bindings/python/python/opendal/options.py
+++ b/bindings/python/python/opendal/options.py
@@ -203,30 +203,255 @@ class ReadKwargs(TypedDict, total=False):
class WriteKwargs(TypedDict, total=False):
- """Options for `write` operations."""
+ """Options for write operations.
+
+ Each condition checks the file currently stored at the write path, and
+ the service evaluates it atomically with the write's visible commit:
+
+ - A false condition fails the write with
+ `opendal.exceptions.ConditionNotMatch` and leaves the previously
+ visible file unchanged. In a write mode, `open()` does not access storage,
+ so depending on the service, a check against the stored file fails
+ while writing to the file or when closing it.
+ - A condition the service does not advertise through its capability fails
+ the write 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`, or as `OSError` from the `write()` or
+ `flush()` of a file from `open()`.
+
+ See the conditional operation specification
+ for the complete cross-operation contract.
+ """
append: bool
- """Whether to append to the file instead of overwriting it."""
+ """Sets append mode for this operation.
+
+ ### Capability
+
+ Check `op.capability().write_can_append` before using this option.
+
+ ### Behavior
+
+ - By default, write operations overwrite existing files
+ - When append is set to true:
+ - New data will be appended to the end of existing file
+ - If file doesn't exist, it will be created
+ - If not supported, raises `opendal.exceptions.Unsupported`
+
+ This operation allows adding data to existing files instead of overwriting
them.
+ """
chunk: int
- """The chunk size to use when writing the file."""
+ """Sets chunk size for buffered writes.
+
+ ### Capability
+
+ Check `op.capability().write_multi_min_size` and
`op.capability().write_multi_max_size` for size limits.
+
+ ### Behavior
+
+ - By default, OpenDAL buffers data until it reaches the service's
+ `op.capability().write_multi_min_size` and then writes everything
+ buffered at once. Without that minimum, `write()` passes its bytes to
+ the service writer as one write, and `open()` sets `chunk` to 256 KiB
+ - `0` has the same behavior as `None`
+ - When chunk size is set:
+ - Data will be buffered until reaching chunk size
+ - Each chunk reaches the service writer as one write; a service may
+ add requests, such as the ones that start and complete an S3
+ multipart upload
+ - Last chunk may be smaller than chunk size
+ - Important considerations:
+ - Some services require minimum chunk sizes, so OpenDAL raises a chunk
+ size below `op.capability().write_multi_min_size` to that minimum
+ and lowers one above `op.capability().write_multi_max_size` to
+ that maximum
+ - Smaller chunks increase API calls and costs
+ - Larger chunks increase memory usage, but improve performance and
reduce costs
+
+ ### Performance Impact
+
+ Setting appropriate chunk size can:
+ - Reduce number of API calls
+ - Improve overall throughput
+ - Lower operation costs
+ - Better utilize network bandwidth
+ """
concurrent: int
- """The number of concurrent requests to make when writing the file."""
+ """Sets concurrent write operations for `write()` or a file from `open()`.
+
+ ## Behavior
+
+ - By default, OpenDAL writes files sequentially
+ - When concurrent is set:
+ - Multiple write operations can execute in parallel
+ - Write operations return immediately without waiting if tasks space are
available
+ - Close operation ensures all writes complete in order
+ - Memory usage increases with concurrency level
+ - If not supported, falls back to sequential writes
+
+ `write()` without `chunk` passes its bytes to the service writer as one
+ write. A service that splits the buffer internally, such as `fs` with
+ `direct_io` on Linux, can write the parts concurrently.
+
+ This feature significantly improves performance when:
+ - Writing large files
+ - Network latency is high
+ - Storage service supports concurrent uploads like multipart uploads
+
+ ## Performance Impact
+
+ Setting appropriate concurrency can:
+ - Increase write throughput
+ - Reduce total write time
+ - Better utilize available bandwidth
+ - Trade memory for performance
+ """
cache_control: str
- """The cache control header to set on the file."""
+ """Sets Cache-Control header for this write operation.
+
+ ### Capability
+
+ Check `op.capability().write_with_cache_control` before using this feature.
+
+ ### Behavior
+
+ - If supported, sets Cache-Control as system metadata on the target file
+ - The value should follow HTTP Cache-Control header format
+ - If not supported, the value will be ignored
+
+ This operation allows controlling caching behavior for the written content.
+
+ ### Use Cases
+
+ - Setting browser cache duration
+ - Configuring CDN behavior
+ - Optimizing content delivery
+ - Managing cache invalidation
+
+ ### References
+
+ - [MDN
Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control)
+ - [RFC 7234 Section 5.2](https://tools.ietf.org/html/rfc7234#section-5.2)
+ """
content_type: str
- """The content type header to set on the file."""
+ """Sets `Content-Type` header for this write operation.
+
+ ## Capability
+
+ Check `op.capability().write_with_content_type` before using this feature.
+
+ ### Behavior
+
+ - If supported, sets Content-Type as system metadata on the target file
+ - The value should follow MIME type format (e.g. "text/plain",
"image/jpeg")
+ - If not supported, the value will be ignored
+
+ This operation allows specifying the media type of the content being
written.
+ """
content_disposition: str
- """The content disposition header to set on the file."""
+ """Sets Content-Disposition header for this write request.
+
+ ### Capability
+
+ Check `op.capability().write_with_content_disposition` before using this
feature.
+
+ ### Behavior
+
+ - If supported, sets Content-Disposition as system metadata on the target
file
+ - The value should follow HTTP Content-Disposition header format
+ - Common values include:
+ - `inline` - Content displayed within browser
+ - `attachment` - Content downloaded as file
+ - `attachment; filename="example.jpg"` - Downloaded with specified
filename
+ - If not supported, the value will be ignored
+
+ This operation allows controlling how the content should be displayed or
downloaded.
+ """
content_encoding: str
- """The content encoding header to set on the file."""
+ """Sets Content-Encoding header for this write request.
+
+ ### Capability
+
+ Check `op.capability().write_with_content_encoding` before using this
feature.
+
+ ### Behavior
+
+ - If supported, sets Content-Encoding as system metadata on the target file
+ - The value should follow HTTP Content-Encoding header format
+ - Common values include:
+ - `gzip` - Content encoded using gzip compression
+ - `deflate` - Content encoded using deflate compression
+ - `br` - Content encoded using Brotli compression
+ - `identity` - No encoding applied (default value)
+ - If not supported, the value will be ignored
+
+ This operation allows specifying the encoding applied to the content being
written.
+ """
if_match: str
- """The ETag to match when writing the file."""
+ """Write only when the file at the write 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
+ write 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().write_with_if_match`.
+ """
if_none_match: str
- """The ETag to not match when writing the file."""
+ """Write only when the file at the write path does not have this ETag.
+
+ With a concrete ETag value, the condition succeeds when the file has
+ a different ETag or does not exist; the write then replaces or
+ creates the file. A file whose ETag equals this value fails the write
+ 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().write_with_if_none_match`. Some services, such
+ as `s3`, support `if_not_exists` but not `if_none_match`; use
+ `if_not_exists` when you only need to guard against
+ an existing file.
+ """
if_not_exists: bool
- """Whether to fail if the file already exists."""
+ """Write only when no file exists at the write path.
+
+ The condition succeeds when the path is empty, so the write creates
+ the file. An existing file fails the write with
+ `opendal.exceptions.ConditionNotMatch`.
+
+ The operation raises `opendal.exceptions.Unsupported` when the
+ service does not advertise
+ `op.capability().write_with_if_not_exists`.
+ """
user_metadata: dict[str, str]
- """The user metadata to set on the file."""
+ """Sets user metadata for this write request.
+
+ ### Capability
+
+ Check `op.capability().write_with_user_metadata` before using this feature.
+
+ ### Behavior
+
+ - If supported, the user metadata will be attached to the object during
write
+ - Accepts key-value pairs where both key and value are strings
+ - Some services, such as `s3`, return keys in lowercase
+ - Services may have limitations for user metadata, for example:
+ - Key length is typically limited (e.g., 1024 bytes)
+ - Value length is typically limited (e.g., 4096 bytes)
+ - Total metadata size might be limited
+ - Some characters might be forbidden in keys
+ - If not supported, the metadata will be ignored
+
+ User metadata provides a way to attach custom metadata to objects during
write operations.
+ A later `stat()` returns this metadata as `user_metadata` when the
+ service exposes user metadata.
+ """
checksum: ChecksumAlgorithm | None
"""The algorithm the service uses to verify the full object before
committing.
`None` preserves the service default.
@@ -458,6 +683,14 @@ class OpenKwargs(ReadKwargs, WriteKwargs, total=False):
or a failed condition. Otherwise those errors occur later and raise
`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
+ `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
+ `Operator.open`, raise `opendal.exceptions.ConditionNotMatch` for a failed
+ condition and `OSError` for any other error, while `close()` raises each
+ error as its `opendal.exceptions` class.
"""
diff --git a/bindings/python/src/operator.rs b/bindings/python/src/operator.rs
index 117978a93c..281c8f8d89 100644
--- a/bindings/python/src/operator.rs
+++ b/bindings/python/src/operator.rs
@@ -585,8 +585,9 @@ impl Operator {
/// update (`"+"`) modes, or if the mode conflicts with `append` or
/// `if_not_exists` in `**kwargs`, or if the checksum name is
unrecognized.
/// ConditionNotMatch
- /// If create mode (`"x"`) targets an existing file. The failure can
- /// surface from `write()`, `flush()`, or `close()`.
+ /// If create mode (`"x"`) targets an existing file, or another write
+ /// condition fails. The failure can surface from `write()`, `flush()`,
+ /// or `close()`.
/// Unsupported
/// If the service does not support the requested read or write
options,
/// including the selected checksum algorithm. Append writes cannot
request
@@ -601,6 +602,10 @@ impl Operator {
/// file size. With a positive `chunk` and no `size`, `open()` stats
the
/// file first and raises such errors as `opendal.exceptions` classes
/// itself.
+ /// In write, append, or create mode, if writing fails other than by a
+ /// failed condition. The failure surfaces from the file's `write()` or
+ /// `flush()`, while `close()` raises such errors as
`opendal.exceptions`
+ /// classes.
///
/// Returns
/// -------
@@ -634,7 +639,7 @@ impl Operator {
Ok(File::new_reader(r))
} else {
let mut writer_opts = kwargs
- .map(|v| v.extract::<WriteOptions>())
+ .map(WriteOptions::from_open_kwargs)
.transpose()?
.unwrap_or_default();
mode.apply_write_options(&mut writer_opts)?;
@@ -790,7 +795,9 @@ impl Operator {
/// chunk : int, optional
/// The chunk size to use when writing the file.
/// concurrent : int, optional
- /// The number of concurrent requests to make when writing the file.
+ /// The number of writes to run concurrently. Without `chunk`,
`write()`
+ /// passes its bytes to the service writer as one write, which only a
+ /// service that splits it internally can write concurrently.
/// cache_control : str, optional
/// The cache control header to set on the file.
/// content_type : str, optional
@@ -815,9 +822,12 @@ impl Operator {
/// ------
/// ValueError
/// If the checksum name is unrecognized.
+ /// ConditionNotMatch
+ /// If `if_match`, `if_none_match`, or `if_not_exists` fails.
/// Unsupported
- /// If the service cannot verify the write with the selected algorithm,
- /// including when appending.
+ /// If the service does not support `append`, a requested condition, or
+ /// the selected checksum algorithm. Append writes cannot request a
+ /// checksum.
/// ChecksumMismatch
/// If the checksum fails verification.
#[allow(clippy::too_many_arguments)]
@@ -1522,8 +1532,8 @@ impl AsyncOperator {
/// update (`"+"`) modes, or if the mode conflicts with `append` or
/// `if_not_exists` in `**kwargs`, or if the checksum name is
unrecognized.
/// ConditionNotMatch
- /// If create mode (`"x"`) targets an existing file. The failure can
- /// surface from `write()` or `close()`.
+ /// If create mode (`"x"`) targets an existing file, or another write
+ /// condition fails. The failure can surface from `write()` or
`close()`.
/// Unsupported
/// If the service does not support the requested read or write
options,
/// including the selected checksum algorithm. Append writes cannot
request
@@ -1538,6 +1548,9 @@ impl AsyncOperator {
/// file size. With a positive `chunk` and no `size`, `open()` stats
the
/// file first and raises such errors as `opendal.exceptions` classes
/// itself.
+ /// In write, append, or create mode, if writing fails other than by a
+ /// failed condition. The failure surfaces from the file's `write()`,
+ /// while `close()` raises such errors as `opendal.exceptions` classes.
///
/// Returns
/// -------
@@ -1576,7 +1589,7 @@ impl AsyncOperator {
})
} else {
let mut writer_opts = kwargs
- .map(|v| v.extract::<WriteOptions>())
+ .map(WriteOptions::from_open_kwargs)
.transpose()?
.unwrap_or_default();
mode.apply_write_options(&mut writer_opts)?;
@@ -1730,7 +1743,9 @@ impl AsyncOperator {
/// chunk : int, optional
/// The chunk size to use when writing the file.
/// concurrent : int, optional
- /// The number of concurrent requests to make when writing the file.
+ /// The number of writes to run concurrently. Without `chunk`,
`write()`
+ /// passes its bytes to the service writer as one write, which only a
+ /// service that splits it internally can write concurrently.
/// cache_control : str, optional
/// The cache control header to set on the file.
/// content_type : str, optional
@@ -1755,9 +1770,12 @@ impl AsyncOperator {
/// ------
/// ValueError
/// If the checksum name is unrecognized.
+ /// ConditionNotMatch
+ /// If `if_match`, `if_none_match`, or `if_not_exists` fails.
/// Unsupported
- /// If the service cannot verify the write with the selected algorithm,
- /// including when appending.
+ /// If the service does not support `append`, a requested condition, or
+ /// the selected checksum algorithm. Append writes cannot request a
+ /// checksum.
/// ChecksumMismatch
/// If the checksum fails verification.
///
diff --git a/bindings/python/src/options.rs b/bindings/python/src/options.rs
index 573e76a2cc..423e0450af 100644
--- a/bindings/python/src/options.rs
+++ b/bindings/python/src/options.rs
@@ -17,7 +17,6 @@
use opendal::{self as ocore, BytesRange};
use pyo3::Borrowed;
-use pyo3::FromPyObject;
use pyo3::PyAny;
use pyo3::PyErr;
use pyo3::PyResult;
@@ -28,7 +27,6 @@ use pyo3::pyclass;
use pyo3::types::PyAnyMethods;
use pyo3::types::PyDict;
use pyo3::types::PyDictMethods;
-use std::collections::HashMap;
mod generated;
pub use generated::*;
@@ -159,6 +157,15 @@ impl ReadOptions {
}
}
+impl WriteOptions {
+ /// Extract writer options for `open()` in a write mode. Rejects keys that
+ /// are not write options, except read options set to `None`.
+ pub fn from_open_kwargs(dict: &pyo3::Bound<'_, PyDict>) -> PyResult<Self> {
+ reject_unknown_kwargs(dict, WRITE_OPTION_KEYS, true)?;
+ dict.extract()
+ }
+}
+
const CHECKSUM_ALGORITHMS: &[(&str, ocore::ChecksumAlgo)] = &[
("crc32c", ocore::ChecksumAlgo::Crc32c),
("crc64nvme", ocore::ChecksumAlgo::Crc64Nvme),
@@ -182,64 +189,6 @@ pub(crate) fn checksum_into_python(checksum:
ocore::Checksum) -> Option<(&'stati
Some((name, checksum.value))
}
-/// Options for `write` operations.
-#[pyclass(module = "opendal")]
-#[derive(Default)]
-pub struct WriteOptions {
- /// Whether to append to the file instead of overwriting it.
- pub append: Option<bool>,
- /// The chunk size to use when writing the file.
- pub chunk: Option<usize>,
- /// The number of concurrent requests to make when writing the file.
- pub concurrent: Option<usize>,
- /// The cache control header to set on the file.
- pub cache_control: Option<String>,
- /// The content type header to set on the file.
- pub content_type: Option<String>,
- /// The content disposition header to set on the file.
- pub content_disposition: Option<String>,
- /// The content encoding header to set on the file.
- pub content_encoding: Option<String>,
- /// The ETag to match when writing the file.
- pub if_match: Option<String>,
- /// The ETag to not match when writing the file.
- pub if_none_match: Option<String>,
- /// Whether to fail if the file already exists.
- pub if_not_exists: Option<bool>,
- /// The user metadata to set on the file.
- pub user_metadata: Option<HashMap<String, String>>,
- /// The algorithm the service uses to verify the full object before
committing.
- /// `None` preserves the service default.
- pub checksum: Option<ocore::ChecksumAlgo>,
-}
-
-impl<'a, 'py> FromPyObject<'a, 'py> for WriteOptions {
- type Error = PyErr;
-
- fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
- let dict = downcast_kwargs(obj)?;
- reject_unknown_kwargs(&dict, WRITE_OPTION_KEYS, true)?;
-
- Ok(Self {
- append: extract_optional(&dict, "append")?,
- chunk: extract_optional(&dict, "chunk")?,
- concurrent: extract_optional(&dict, "concurrent")?,
- cache_control: extract_optional(&dict, "cache_control")?,
- content_type: extract_optional(&dict, "content_type")?,
- content_disposition: extract_optional(&dict,
"content_disposition")?,
- content_encoding: extract_optional(&dict, "content_encoding")?,
- if_match: extract_optional(&dict, "if_match")?,
- if_none_match: extract_optional(&dict, "if_none_match")?,
- if_not_exists: extract_optional(&dict, "if_not_exists")?,
- user_metadata: extract_optional(&dict, "user_metadata")?,
- checksum: extract_optional::<String>(&dict, "checksum")?
- .as_deref()
- .map(parse_checksum_algorithm)
- .transpose()?,
- })
- }
-}
-
impl From<ReadOptions> for ocore::options::ReaderOptions {
fn from(opts: ReadOptions) -> Self {
Self {
@@ -262,26 +211,6 @@ impl From<ReadOptions> for ocore::options::ReaderOptions {
}
}
-impl From<WriteOptions> for ocore::options::WriteOptions {
- fn from(opts: WriteOptions) -> Self {
- Self {
- append: opts.append.unwrap_or(false),
- concurrent: opts.concurrent.unwrap_or_default(),
- chunk: opts.chunk,
- content_type: opts.content_type,
- content_disposition: opts.content_disposition,
- cache_control: opts.cache_control,
- content_encoding: opts.content_encoding,
- user_metadata: opts.user_metadata,
- if_match: opts.if_match,
- if_none_match: opts.if_none_match,
- if_not_exists: opts.if_not_exists.unwrap_or(false),
- checksum: opts.checksum.map(ocore::WriteChecksum::Algo),
- ..Default::default()
- }
- }
-}
-
/// Options for `copy` operations.
#[pyclass(module = "opendal")]
#[derive(Default, Debug)]
diff --git a/bindings/python/src/options/generated.rs
b/bindings/python/src/options/generated.rs
index 47b353ba2e..400f6ef673 100644
--- a/bindings/python/src/options/generated.rs
+++ b/bindings/python/src/options/generated.rs
@@ -490,3 +490,296 @@ impl From<ReadOptions> for ocore::options::ReadOptions {
}
}
}
+
+/// Options for write operations.
+///
+/// Each condition checks the file currently stored at the write path, and
+/// the service evaluates it atomically with the write's visible commit:
+///
+/// - A false condition fails the write with
+/// `opendal.exceptions.ConditionNotMatch` and leaves the previously
+/// visible file unchanged. In a write mode, `open()` does not access storage,
+/// so depending on the service, a check against the stored file fails
+/// while writing to the file or when closing it.
+/// - A condition the service does not advertise through its capability fails
+/// the write 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`, or as `OSError` from the `write()` or
+/// `flush()` of a file from `open()`.
+///
+/// See the conditional operation specification
+/// for the complete cross-operation contract.
+#[pyclass(module = "opendal")]
+#[derive(Default, Debug)]
+pub struct WriteOptions {
+ /// Sets append mode for this operation.
+ ///
+ /// ### Capability
+ ///
+ /// Check `op.capability().write_can_append` before using this option.
+ ///
+ /// ### Behavior
+ ///
+ /// - By default, write operations overwrite existing files
+ /// - When append is set to true:
+ /// - New data will be appended to the end of existing file
+ /// - If file doesn't exist, it will be created
+ /// - If not supported, raises `opendal.exceptions.Unsupported`
+ ///
+ /// This operation allows adding data to existing files instead of
overwriting them.
+ pub append: Option<bool>,
+ /// Sets chunk size for buffered writes.
+ ///
+ /// ### Capability
+ ///
+ /// Check `op.capability().write_multi_min_size` and
`op.capability().write_multi_max_size` for size limits.
+ ///
+ /// ### Behavior
+ ///
+ /// - By default, OpenDAL buffers data until it reaches the service's
+ /// `op.capability().write_multi_min_size` and then writes everything
+ /// buffered at once. Without that minimum, `write()` passes its bytes to
+ /// the service writer as one write, and `open()` sets `chunk` to 256 KiB
+ /// - `0` has the same behavior as `None`
+ /// - When chunk size is set:
+ /// - Data will be buffered until reaching chunk size
+ /// - Each chunk reaches the service writer as one write; a service may
+ /// add requests, such as the ones that start and complete an S3
+ /// multipart upload
+ /// - Last chunk may be smaller than chunk size
+ /// - Important considerations:
+ /// - Some services require minimum chunk sizes, so OpenDAL raises a
chunk
+ /// size below `op.capability().write_multi_min_size` to that minimum
+ /// and lowers one above `op.capability().write_multi_max_size` to
+ /// that maximum
+ /// - Smaller chunks increase API calls and costs
+ /// - Larger chunks increase memory usage, but improve performance and
reduce costs
+ ///
+ /// ### Performance Impact
+ ///
+ /// Setting appropriate chunk size can:
+ /// - Reduce number of API calls
+ /// - Improve overall throughput
+ /// - Lower operation costs
+ /// - Better utilize network bandwidth
+ pub chunk: Option<usize>,
+ /// Sets concurrent write operations for `write()` or a file from `open()`.
+ ///
+ /// ## Behavior
+ ///
+ /// - By default, OpenDAL writes files sequentially
+ /// - When concurrent is set:
+ /// - Multiple write operations can execute in parallel
+ /// - Write operations return immediately without waiting if tasks space
are available
+ /// - Close operation ensures all writes complete in order
+ /// - Memory usage increases with concurrency level
+ /// - If not supported, falls back to sequential writes
+ ///
+ /// `write()` without `chunk` passes its bytes to the service writer as one
+ /// write. A service that splits the buffer internally, such as `fs` with
+ /// `direct_io` on Linux, can write the parts concurrently.
+ ///
+ /// This feature significantly improves performance when:
+ /// - Writing large files
+ /// - Network latency is high
+ /// - Storage service supports concurrent uploads like multipart uploads
+ ///
+ /// ## Performance Impact
+ ///
+ /// Setting appropriate concurrency can:
+ /// - Increase write throughput
+ /// - Reduce total write time
+ /// - Better utilize available bandwidth
+ /// - Trade memory for performance
+ pub concurrent: Option<usize>,
+ /// Sets Cache-Control header for this write operation.
+ ///
+ /// ### Capability
+ ///
+ /// Check `op.capability().write_with_cache_control` before using this
feature.
+ ///
+ /// ### Behavior
+ ///
+ /// - If supported, sets Cache-Control as system metadata on the target
file
+ /// - The value should follow HTTP Cache-Control header format
+ /// - If not supported, the value will be ignored
+ ///
+ /// This operation allows controlling caching behavior for the written
content.
+ ///
+ /// ### Use Cases
+ ///
+ /// - Setting browser cache duration
+ /// - Configuring CDN behavior
+ /// - Optimizing content delivery
+ /// - Managing cache invalidation
+ ///
+ /// ### References
+ ///
+ /// - [MDN
Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control)
+ /// - [RFC 7234 Section
5.2](https://tools.ietf.org/html/rfc7234#section-5.2)
+ pub cache_control: Option<String>,
+ /// Sets `Content-Type` header for this write operation.
+ ///
+ /// ## Capability
+ ///
+ /// Check `op.capability().write_with_content_type` before using this
feature.
+ ///
+ /// ### Behavior
+ ///
+ /// - If supported, sets Content-Type as system metadata on the target file
+ /// - The value should follow MIME type format (e.g. "text/plain",
"image/jpeg")
+ /// - If not supported, the value will be ignored
+ ///
+ /// This operation allows specifying the media type of the content being
written.
+ pub content_type: Option<String>,
+ /// Sets Content-Disposition header for this write request.
+ ///
+ /// ### Capability
+ ///
+ /// Check `op.capability().write_with_content_disposition` before using
this feature.
+ ///
+ /// ### Behavior
+ ///
+ /// - If supported, sets Content-Disposition as system metadata on the
target file
+ /// - The value should follow HTTP Content-Disposition header format
+ /// - Common values include:
+ /// - `inline` - Content displayed within browser
+ /// - `attachment` - Content downloaded as file
+ /// - `attachment; filename="example.jpg"` - Downloaded with specified
filename
+ /// - If not supported, the value will be ignored
+ ///
+ /// This operation allows controlling how the content should be displayed
or downloaded.
+ pub content_disposition: Option<String>,
+ /// Sets Content-Encoding header for this write request.
+ ///
+ /// ### Capability
+ ///
+ /// Check `op.capability().write_with_content_encoding` before using this
feature.
+ ///
+ /// ### Behavior
+ ///
+ /// - If supported, sets Content-Encoding as system metadata on the target
file
+ /// - The value should follow HTTP Content-Encoding header format
+ /// - Common values include:
+ /// - `gzip` - Content encoded using gzip compression
+ /// - `deflate` - Content encoded using deflate compression
+ /// - `br` - Content encoded using Brotli compression
+ /// - `identity` - No encoding applied (default value)
+ /// - If not supported, the value will be ignored
+ ///
+ /// This operation allows specifying the encoding applied to the content
being written.
+ pub content_encoding: Option<String>,
+ /// Write only when the file at the write 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
+ /// write 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().write_with_if_match`.
+ pub if_match: Option<String>,
+ /// Write only when the file at the write path does not have this ETag.
+ ///
+ /// With a concrete ETag value, the condition succeeds when the file has
+ /// a different ETag or does not exist; the write then replaces or
+ /// creates the file. A file whose ETag equals this value fails the write
+ /// 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().write_with_if_none_match`. Some services, such
+ /// as `s3`, support `if_not_exists` but not `if_none_match`; use
+ /// `if_not_exists` when you only need to guard against
+ /// an existing file.
+ pub if_none_match: Option<String>,
+ /// Write only when no file exists at the write path.
+ ///
+ /// The condition succeeds when the path is empty, so the write creates
+ /// the file. An existing file fails the write with
+ /// `opendal.exceptions.ConditionNotMatch`.
+ ///
+ /// The operation raises `opendal.exceptions.Unsupported` when the
+ /// service does not advertise
+ /// `op.capability().write_with_if_not_exists`.
+ pub if_not_exists: Option<bool>,
+ /// Sets user metadata for this write request.
+ ///
+ /// ### Capability
+ ///
+ /// Check `op.capability().write_with_user_metadata` before using this
feature.
+ ///
+ /// ### Behavior
+ ///
+ /// - If supported, the user metadata will be attached to the object
during write
+ /// - Accepts key-value pairs where both key and value are strings
+ /// - Some services, such as `s3`, return keys in lowercase
+ /// - Services may have limitations for user metadata, for example:
+ /// - Key length is typically limited (e.g., 1024 bytes)
+ /// - Value length is typically limited (e.g., 4096 bytes)
+ /// - Total metadata size might be limited
+ /// - Some characters might be forbidden in keys
+ /// - If not supported, the metadata will be ignored
+ ///
+ /// User metadata provides a way to attach custom metadata to objects
during write operations.
+ /// A later `stat()` returns this metadata as `user_metadata` when the
+ /// service exposes user metadata.
+ pub user_metadata: Option<std::collections::HashMap<String, String>>,
+ /// The algorithm the service uses to verify the full object before
committing.
+ /// `None` preserves the service default.
+ pub checksum: Option<ocore::ChecksumAlgo>,
+}
+
+impl<'a, 'py> FromPyObject<'a, 'py> for WriteOptions {
+ type Error = PyErr;
+
+ fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
+ let dict = downcast_kwargs(obj)?;
+
+ Ok(Self {
+ append: extract_optional(&dict, "append")?,
+ chunk: extract_optional(&dict, "chunk")?,
+ concurrent: extract_optional(&dict, "concurrent")?,
+ cache_control: extract_optional(&dict, "cache_control")?,
+ content_type: extract_optional(&dict, "content_type")?,
+ content_disposition: extract_optional(&dict,
"content_disposition")?,
+ content_encoding: extract_optional(&dict, "content_encoding")?,
+ if_match: extract_optional(&dict, "if_match")?,
+ if_none_match: extract_optional(&dict, "if_none_match")?,
+ if_not_exists: extract_optional(&dict, "if_not_exists")?,
+ user_metadata: extract_optional(&dict, "user_metadata")?,
+ checksum: extract_optional(&dict, "checksum")?
+ .map(|name: String| super::parse_checksum_algorithm(&name))
+ .transpose()?,
+ })
+ }
+}
+
+impl From<WriteOptions> for ocore::options::WriteOptions {
+ fn from(opts: WriteOptions) -> Self {
+ Self {
+ append: opts.append.unwrap_or(false),
+ cache_control: opts.cache_control,
+ content_type: opts.content_type,
+ content_disposition: opts.content_disposition,
+ content_encoding: opts.content_encoding,
+ content_language: None,
+ user_metadata: opts.user_metadata,
+ expires: None,
+ if_match: opts.if_match,
+ if_none_match: opts.if_none_match,
+ if_version_match: None,
+ if_version_not_match: None,
+ if_not_exists: opts.if_not_exists.unwrap_or(false),
+ if_not_changed: None,
+ concurrent: opts.concurrent.unwrap_or_default(),
+ chunk: opts.chunk,
+ checksum: opts.checksum.map(ocore::WriteChecksum::Algo),
+ }
+ }
+}
diff --git a/dev/src/generate/options.rs b/dev/src/generate/options.rs
index f2311179fa..b8c699d286 100644
--- a/dev/src/generate/options.rs
+++ b/dev/src/generate/options.rs
@@ -194,27 +194,9 @@ mod tests {
let options = parse(&path).unwrap();
let names: Vec<&str> = options.iter().map(|o|
o.name.as_str()).collect();
- assert_eq!(names, ["WriteOptions", "CopyOptions", "RenameOptions"]);
-
- let write = &options[0];
- assert_eq!(write.doc, "Options for `write` operations.");
- assert_eq!(write.fields.len(), 12);
- assert_eq!(write.fields[0].name, "append");
- assert_eq!(write.fields[0].ty, OptionType::Bool);
- assert_eq!(write.fields[1].name, "chunk");
- assert_eq!(write.fields[1].ty, OptionType::Int);
- assert_eq!(write.fields[3].name, "cache_control");
- assert_eq!(write.fields[3].ty, OptionType::Str);
- assert_eq!(write.fields[11].name, "checksum");
- assert_eq!(write.fields[11].ty, OptionType::ChecksumAlgo);
- assert_eq!(write.fields[10].name, "user_metadata");
- assert_eq!(write.fields[10].ty, OptionType::Dict);
- assert_eq!(
- write.fields[10].doc,
- "The user metadata to set on the file."
- );
+ assert_eq!(names, ["CopyOptions", "RenameOptions"]);
- for option in [&options[1], &options[2]] {
+ for option in &options {
assert!(
option
.fields
@@ -226,8 +208,8 @@ mod tests {
}
// A field doc keeps its paragraphs, which `options.py` renders as
- // separate docstring paragraphs. No hand-written struct has an
- // `Option<u64>` or a timestamp any more, so a sample covers them.
+ // separate docstring paragraphs. The hand-written structs only have
+ // `Option<bool>` fields now, so a sample covers the other types.
let options = parse_struct(&syn::parse_quote! {
pub struct FakeOptions {
/// First paragraph,
@@ -239,6 +221,11 @@ mod tests {
pub offset: Option<u64>,
/// A time.
pub since: Option<jiff::Timestamp>,
+ pub chunk: Option<usize>,
+ pub name: Option<String>,
+ pub append: bool,
+ pub user_metadata: Option<HashMap<String, String>>,
+ pub checksum: Option<ocore::ChecksumAlgo>,
}
})
.unwrap();
@@ -246,8 +233,20 @@ mod tests {
options.fields[0].doc,
"First paragraph,\ncontinued.\n\nSecond paragraph."
);
- assert_eq!(options.fields[1].ty, OptionType::Int);
assert_eq!(options.fields[1].doc, "An offset.");
- assert_eq!(options.fields[2].ty, OptionType::DateTime);
+ let types: Vec<OptionType> = options.fields.iter().map(|f|
f.ty).collect();
+ assert_eq!(
+ types,
+ [
+ OptionType::Bool,
+ OptionType::Int,
+ OptionType::DateTime,
+ OptionType::Int,
+ OptionType::Str,
+ OptionType::Bool,
+ OptionType::Dict,
+ OptionType::ChecksumAlgo,
+ ]
+ );
}
}
diff --git a/dev/src/generate/python.rs b/dev/src/generate/python.rs
index 97ad87a81e..fd951dd90d 100644
--- a/dev/src/generate/python.rs
+++ b/dev/src/generate/python.rs
@@ -669,15 +669,31 @@ struct PyOptions {
/// A core field that no keyword argument sets is not exposed and keeps
/// its default.
options: &'static [(&'static str, &'static str, OptionKind, &'static str)],
+ /// Keyword arguments, after `options`, that set a core field which the
+ /// core options parser skips, so core gives them no kind or doc.
+ unmirrored: &'static [PyUnmirrored],
/// Python docs that replace the core doc of a keyword argument, as
- /// `(name, lines)`, where the core doc does not hold for Python.
+ /// `(name, lines)`, where the core doc does not hold for Python. Each
+ /// keyword argument in `unmirrored` needs one.
docs: &'static [(&'static str, &'static [&'static str])],
- /// Python wording for core text that names what Python does not expose,
- /// as `(core, Python)`. Each core text sits within one doc line, and
- /// generation fails once no doc of the class contains it.
+ /// Python wording for core text that does not hold for Python, as
+ /// `(core, Python)`. Generation fails once no doc contains the core text.
rewrites: &'static [(&'static str, &'static str)],
}
+/// A keyword argument that sets a core field which the core options parser
+/// skips (`NOT_MIRRORED` in `core_options.rs`), converted by hand.
+struct PyUnmirrored {
+ /// The name, which is also the Rust field and the core field it sets.
+ name: &'static str,
+ py_type: options::OptionType,
+ rust_type: &'static str,
+ /// Appended to the `extract_optional` call that reads the keyword.
+ extract: &'static str,
+ /// Appended to `opts.<name>` to set the core field.
+ convert: &'static str,
+}
+
/// The Python options classes generated from `core/core/src/types/options.rs`.
/// The other classes in `bindings/python/src/options.rs` are hand-written.
const GENERATED_OPTIONS: &[PyOptions] = &[
@@ -695,6 +711,7 @@ const GENERATED_OPTIONS: &[PyOptions] = &[
("versions", "versions", OptionKind::Bool, "Option<bool>"),
("deleted", "deleted", OptionKind::Bool, "Option<bool>"),
],
+ unmirrored: &[],
docs: &[],
rewrites: &[],
},
@@ -751,6 +768,7 @@ const GENERATED_OPTIONS: &[PyOptions] = &[
),
("checksum", "checksum", OptionKind::Bool, "bool"),
],
+ unmirrored: &[],
docs: &[],
rewrites: &[],
},
@@ -771,6 +789,7 @@ const GENERATED_OPTIONS: &[PyOptions] = &[
"Option<String>",
),
],
+ unmirrored: &[],
docs: &[],
rewrites: &[],
},
@@ -846,6 +865,7 @@ const GENERATED_OPTIONS: &[PyOptions] = &[
"Option<String>",
),
],
+ unmirrored: &[],
// Core documents `range` in Rust range syntax, `gap` for
// `Reader::fetch`, which Python does not expose, and `prefetch` for
// the Rust `Reader`.
@@ -916,6 +936,145 @@ const GENERATED_OPTIONS: &[PyOptions] = &[
(", unless `content_length_hint` is set.", "."),
],
},
+ PyOptions {
+ name: "WriteOptions",
+ options: &[
+ ("append", "append", OptionKind::Bool, "Option<bool>"),
+ ("chunk", "chunk", OptionKind::OptionUsize, "Option<usize>"),
+ (
+ "concurrent",
+ "concurrent",
+ OptionKind::Usize,
+ "Option<usize>",
+ ),
+ (
+ "cache_control",
+ "cache_control",
+ OptionKind::OptionString,
+ "Option<String>",
+ ),
+ (
+ "content_type",
+ "content_type",
+ OptionKind::OptionString,
+ "Option<String>",
+ ),
+ (
+ "content_disposition",
+ "content_disposition",
+ OptionKind::OptionString,
+ "Option<String>",
+ ),
+ (
+ "content_encoding",
+ "content_encoding",
+ OptionKind::OptionString,
+ "Option<String>",
+ ),
+ (
+ "if_match",
+ "if_match",
+ OptionKind::OptionString,
+ "Option<String>",
+ ),
+ (
+ "if_none_match",
+ "if_none_match",
+ OptionKind::OptionString,
+ "Option<String>",
+ ),
+ (
+ "if_not_exists",
+ "if_not_exists",
+ OptionKind::Bool,
+ "Option<bool>",
+ ),
+ (
+ "user_metadata",
+ "user_metadata",
+ OptionKind::OptionStringMap,
+ "Option<std::collections::HashMap<String, String>>",
+ ),
+ ],
+ // No binding mirrors core `WriteChecksum` yet (#9316), so Python
+ // keeps its algorithm name from main.
+ unmirrored: &[PyUnmirrored {
+ name: "checksum",
+ py_type: options::OptionType::ChecksumAlgo,
+ rust_type: "Option<ocore::ChecksumAlgo>",
+ extract: ".map(|name: String|
super::parse_checksum_algorithm(&name))\
+ .transpose()?",
+ convert: ".map(ocore::WriteChecksum::Algo)",
+ }],
+ docs: &[(
+ "checksum",
+ &[
+ "The algorithm the service uses to verify the full object
before committing.",
+ "`None` preserves the service default.",
+ ],
+ )],
+ // Python has no writer, `if_not_changed`, `if_version_match`, or
+ // `Reader::metadata`; `open()` sets a `chunk` and files raise
`OSError`.
+ rewrites: &[
+ (
+ concat!(
+ "Creating a writer does not access storage, so\n",
+ "depending on the service, a check against the stored file
fails while\n",
+ "writing or when closing the writer. Combining
`if_not_changed` with a\n",
+ "conflicting `if_match` or `if_version_match` fails before
the writer\n",
+ "exists, without accessing storage.",
+ ),
+ concat!(
+ "In a write mode, `open()` does not access storage,\n",
+ "so depending on the service, a check against the stored
file fails\n",
+ "while writing to the file or when closing it.",
+ ),
+ ),
+ (
+ "surfaces as\n`opendal.exceptions.Conflict`.",
+ concat!(
+ "surfaces as\n`opendal.exceptions.Conflict`, or as
`OSError` from the `write()` or\n",
+ "`flush()` of a file from `open()`.",
+ ),
+ ),
+ (
+ "- If not supported, will return an error",
+ "- If not supported, raises `opendal.exceptions.Unsupported`",
+ ),
+ (
+ concat!(
+ "buffered at once; a service without that minimum receives
each write\n",
+ "as it arrives",
+ ),
+ concat!(
+ "buffered at once. Without that minimum, `write()` passes
its bytes to\n",
+ "the service writer as one write, and `open()` sets
`chunk` to 256 KiB",
+ ),
+ ),
+ (
+ "Sets concurrent write operations for this writer.",
+ "Sets concurrent write operations for `write()` or a file from
`open()`.",
+ ),
+ (
+ concat!(
+ "`crate::Operator::write_with` and
`crate::Operator::write_options`\n",
+ "without `chunk` pass the whole buffer to the service
writer as one\n",
+ "write.",
+ ),
+ "`write()` without `chunk` passes its bytes to the service
writer as one\nwrite.",
+ ),
+ (
+ concat!(
+ "A later stat returns this metadata when the service
exposes user metadata.\n",
+ "`crate::Reader::metadata` may omit it, for example on
`fs`.",
+ ),
+ concat!(
+ "A later `stat()` returns this metadata as `user_metadata`
when the\n",
+ "service exposes user metadata.",
+ ),
+ ),
+ ],
+ },
];
/// The class order of `options.py`, which hand-written and generated classes
@@ -948,9 +1107,14 @@ struct PyField {
name: &'static str,
/// The core field it sets, as listed in [`PyOptions::options`].
core: &'static str,
- kind: OptionKind,
+ /// The kind of that core field, or `None` for a keyword argument in
+ /// [`PyOptions::unmirrored`].
+ kind: Option<OptionKind>,
/// The core doc comment, one entry per line.
doc: Vec<String>,
+ /// The `options.py` type.
+ #[serde(skip)]
+ py_type: options::OptionType,
rust_type: &'static str,
/// Appended to the `extract_optional` call that reads the keyword.
extract: &'static str,
@@ -988,6 +1152,9 @@ fn lowering(
"",
".map(crate::utils::timestamp_from_jiff)",
),
+ (OptionKind::OptionStringMap,
"Option<std::collections::HashMap<String, String>>") => {
+ (options::OptionType::Dict, "", "")
+ }
// A flag whose keyword argument defaults to `None`, such as
// `list(recursive=None)`.
(OptionKind::Bool, "Option<bool>") => (options::OptionType::Bool, "",
".unwrap_or(false)"),
@@ -1225,9 +1392,20 @@ fn py_class(spec: &PyOptions, parsed: &[OptionsStruct],
names: &PyNames) -> Resu
let Some(core) = parsed.iter().find(|options| options.name == class) else {
bail!("core options struct `{class}` not found");
};
- if core.has_unmirrored_fields {
+ // The generated conversion names every core field, so each field that
+ // the parser skips needs an `unmirrored` keyword argument to set it.
+ if core.has_unmirrored_fields && spec.unmirrored.is_empty() {
bail!("core {class} has fields the core options parser skips; Python
cannot set them");
}
+ if let Some(field) = spec.unmirrored.first()
+ && !core.has_unmirrored_fields
+ {
+ bail!(
+ "core {class} has no fields the core options parser skips; \
+ list Python {class}.{} with its core kind",
+ field.name
+ );
+ }
let mut seen = HashSet::new();
for field in &core.fields {
if !seen.insert(field.name.as_str()) {
@@ -1235,15 +1413,27 @@ 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.
+ let paths: Vec<(String, &str)> = spec
+ .options
+ .iter()
+ .filter(|&&(_, core, kind, _)| kind != OptionKind::BytesRange &&
!core.contains("::"))
+ .map(|&(name, core, ..)| (format!("{class}::{core}"), name))
+ .collect();
let renames: Vec<(&str, &str)> = spec
.options
.iter()
.filter(|&&(name, core, kind, _)| name != core && kind !=
OptionKind::BytesRange)
.map(|&(name, core, ..)| (core, name))
+ .chain(paths.iter().map(|(path, name)| (path.as_str(), *name)))
.collect();
+ let listed = |name: &str| {
+ spec.options.iter().any(|&(option, ..)| option == name)
+ || spec.unmirrored.iter().any(|u| u.name == name)
+ };
for &(name, _) in spec.docs {
- if !spec.options.iter().any(|&(option, ..)| option == name) {
+ if !listed(name) {
bail!("Python {class} has a doc for `{name}`, which it does not
list");
}
}
@@ -1278,7 +1468,7 @@ fn py_class(spec: &PyOptions, parsed: &[OptionsStruct],
names: &PyNames) -> Resu
field.kind
);
}
- let Some((_, extract, convert)) = lowering(kind, rust_type) else {
+ let Some((py_type, extract, convert)) = lowering(kind, rust_type) else
{
bail!(
"Python {class}.{name} is a core {kind:?} with Rust type
{rust_type}; \
teach dev/src/generate/python.rs about it"
@@ -1300,13 +1490,45 @@ fn py_class(spec: &PyOptions, parsed: &[OptionsStruct],
names: &PyNames) -> Resu
fields.push(PyField {
name,
core: core_name,
- kind,
+ kind: Some(kind),
doc,
+ py_type,
rust_type,
extract,
convert,
});
}
+ for unmirrored in spec.unmirrored {
+ let name = unmirrored.name;
+ if fields.iter().any(|field| field.name == name) {
+ bail!("Python {class} lists `{name}` twice");
+ }
+ if fields.iter().any(|field| field.core == name) {
+ bail!("Python {class} sets core `{name}` twice");
+ }
+ if core.fields.iter().any(|field| field.name == name) {
+ bail!(
+ "core {class}::{name} is no longer skipped by the core options
parser; \
+ list Python {class}.{name} with its core kind"
+ );
+ }
+ let Some(&(_, doc)) = spec.docs.iter().find(|&&(option, _)| option ==
name) else {
+ bail!(
+ "Python {class}.{name} needs a Python doc, because the core
options parser \
+ skips core `{name}`"
+ );
+ };
+ fields.push(PyField {
+ name,
+ core: name,
+ kind: None,
+ doc: doc.iter().map(|line| line.to_string()).collect(),
+ py_type: unmirrored.py_type,
+ rust_type: unmirrored.rust_type,
+ extract: unmirrored.extract,
+ convert: unmirrored.convert,
+ });
+ }
// The rewrites change docs rendered from core, not the Python docs.
let mut doc = py_doc(&core.doc, class, names, &renames)?;
@@ -1314,16 +1536,15 @@ fn py_class(spec: &PyOptions, parsed: &[OptionsStruct],
names: &PyNames) -> Resu
let from_core = fields
.iter_mut()
.filter(|f| !spec.docs.iter().any(|&(name, _)| name == f.name));
- for line in doc
- .iter_mut()
- .chain(from_core.flat_map(|f| f.doc.iter_mut()))
- {
+ for lines in std::iter::once(&mut doc).chain(from_core.map(|f| &mut
f.doc)) {
+ let mut text = lines.join("\n");
for &(from, to) in spec.rewrites {
- if line.contains(from) {
- *line = line.replace(from, to);
+ if text.contains(from) {
+ text = text.replace(from, to);
unused.retain(|&text| text != from);
}
}
+ *lines = text.split('\n').map(String::from).collect();
}
if let Some(text) = unused.first() {
bail!(
@@ -1337,7 +1558,9 @@ fn py_class(spec: &PyOptions, parsed: &[OptionsStruct],
names: &PyNames) -> Resu
let setters: Vec<&PyField> = fields.iter().filter(|f| f.core ==
field.name).collect();
let expr = match setters.as_slice() {
[] => default_expr(field.kind).to_string(),
- [f] if f.kind != OptionKind::BytesRange => format!("opts.{}{}",
f.name, f.convert),
+ [f] if f.kind != Some(OptionKind::BytesRange) => {
+ format!("opts.{}{}", f.name, f.convert)
+ }
// `make_range` in `bindings/python/src/options.rs` builds the
// range from `offset` and `size`, as `open` does.
[_, _] => "opts.make_range()".to_string(),
@@ -1351,6 +1574,12 @@ fn py_class(spec: &PyOptions, parsed: &[OptionsStruct],
names: &PyNames) -> Resu
expr,
});
}
+ for field in fields.iter().filter(|f| f.kind.is_none()) {
+ conversion.push(ConvertField {
+ name: field.name.to_string(),
+ expr: format!("opts.{}{}", field.name, field.convert),
+ });
+ }
Ok(PyClass {
name: class,
@@ -1428,9 +1657,7 @@ fn render_options_py(workspace_dir: &Path, generated:
&[PyClass]) -> Result<Stri
.iter()
.map(|field| options::OptionField {
name: field.name.to_string(),
- ty: lowering(field.kind, field.rust_type)
- .expect("generated fields have a Python type")
- .0,
+ ty: field.py_type,
doc: field.doc.join("\n"),
})
.collect(),
@@ -1490,7 +1717,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 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, [...]
);
out.push_str("\n\n__all__ = [\n");
@@ -1612,7 +1839,13 @@ mod tests {
let names: Vec<&str> = classes.iter().map(|class|
class.name).collect();
assert_eq!(
names,
- ["ListOptions", "StatOptions", "DeleteOptions", "ReadOptions"]
+ [
+ "ListOptions",
+ "StatOptions",
+ "DeleteOptions",
+ "ReadOptions",
+ "WriteOptions"
+ ]
);
classes
.into_iter()
@@ -1713,6 +1946,97 @@ mod tests {
),
];
+ /// The `WriteOptions` keyword arguments on main (a2ef00d6e), copied
+ /// from `bindings/python/src/options.rs`.
+ const WRITE_KWARGS: [&str; 12] = [
+ "append",
+ "chunk",
+ "concurrent",
+ "cache_control",
+ "content_type",
+ "content_disposition",
+ "content_encoding",
+ "if_match",
+ "if_none_match",
+ "if_not_exists",
+ "user_metadata",
+ "checksum",
+ ];
+
+ /// The Python wording of the `WriteOptions` docs for core text that
+ /// does not hold for Python, as `(core, Python)`.
+ const WRITE_REWRITES: [(&str, &str); 7] = [
+ (
+ "Creating a writer does not access storage, so\n\
+ depending on the service, a check against the stored file fails
while\n\
+ writing or when closing the writer. Combining `if_not_changed`
with a\n\
+ conflicting `if_match` or `if_version_match` fails before the
writer\n\
+ exists, without accessing storage.",
+ "In a write mode, `open()` does not access storage,\n\
+ so depending on the service, a check against the stored file
fails\n\
+ while writing to the file or when closing it.",
+ ),
+ (
+ "surfaces as\n`opendal.exceptions.Conflict`.",
+ "surfaces as\n`opendal.exceptions.Conflict`, or as `OSError` from
the `write()` or\n\
+ `flush()` of a file from `open()`.",
+ ),
+ (
+ "- If not supported, will return an error",
+ "- If not supported, raises `opendal.exceptions.Unsupported`",
+ ),
+ (
+ "buffered at once; a service without that minimum receives each
write\n\
+ as it arrives",
+ "buffered at once. Without that minimum, `write()` passes its
bytes to\n\
+ the service writer as one write, and `open()` sets `chunk` to 256
KiB",
+ ),
+ (
+ "Sets concurrent write operations for this writer.",
+ "Sets concurrent write operations for `write()` or a file from
`open()`.",
+ ),
+ (
+ "`crate::Operator::write_with` and
`crate::Operator::write_options`\n\
+ without `chunk` pass the whole buffer to the service writer as
one\n\
+ write.",
+ "`write()` without `chunk` passes its bytes to the service writer
as one\n\
+ write.",
+ ),
+ (
+ "A later stat returns this metadata when the service exposes user
metadata.\n\
+ `crate::Reader::metadata` may omit it, for example on `fs`.",
+ "A later `stat()` returns this metadata as `user_metadata` when
the\n\
+ service exposes user metadata.",
+ ),
+ ];
+
+ /// `py_doc` of a core `WriteOptions` doc, with the Python wording and
+ /// `WriteOptions::field` paths read as keyword arguments.
+ fn write_doc(core_doc: &[String], item: &str) -> Vec<String> {
+ let paths: Vec<(String, &str)> = WRITE_KWARGS
+ .iter()
+ .map(|&name| (format!("WriteOptions::{name}"), name))
+ .collect();
+ let renames: Vec<(&str, &str)> = paths
+ .iter()
+ .map(|(path, name)| (path.as_str(), *name))
+ .collect();
+ let text = py_doc(core_doc, item, &py_names(), &renames)
+ .unwrap()
+ .join("\n");
+ WRITE_REWRITES
+ .iter()
+ .fold(text, |text, (from, to)| text.replace(from, to))
+ .split('\n')
+ .map(String::from)
+ .collect()
+ }
+
+ /// The `checksum` doc on main (a2ef00d6e). Python does not mirror core
+ /// `WriteChecksum` yet (#9316).
+ const WRITE_CHECKSUM_DOC: &str = "The algorithm the service uses to verify
the full object before committing.\n\
+ `None` preserves the service default.";
+
/// 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
@@ -2080,6 +2404,108 @@ print(json.dumps(docs))
}
}
+ /// The `WriteOptions` surface on main (a2ef00d6e) and the checks and
+ /// exceptions its docs name. It pins no core wording.
+ fn assert_write_surface(class: &PyClass) {
+ let fields: Vec<String> = class
+ .fields
+ .iter()
+ .map(|f| format!("{}: {}", f.name, f.rust_type))
+ .collect();
+ assert_eq!(
+ fields,
+ [
+ "append: Option<bool>",
+ "chunk: Option<usize>",
+ "concurrent: Option<usize>",
+ "cache_control: Option<String>",
+ "content_type: Option<String>",
+ "content_disposition: Option<String>",
+ "content_encoding: Option<String>",
+ "if_match: Option<String>",
+ "if_none_match: Option<String>",
+ "if_not_exists: Option<bool>",
+ "user_metadata: Option<std::collections::HashMap<String,
String>>",
+ "checksum: Option<ocore::ChecksumAlgo>",
+ ]
+ );
+
+ // 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();
+ let condition = "ConditionNotMatch Unsupported";
+ assert_eq!(
+ references,
+ [
+ "append: write_can_append / Unsupported".to_string(),
+ "chunk: write_multi_min_size write_multi_max_size
write_multi_min_size \
+ write_multi_min_size write_multi_max_size / "
+ .to_string(),
+ "concurrent: / ".to_string(),
+ "cache_control: write_with_cache_control / ".to_string(),
+ "content_type: write_with_content_type / ".to_string(),
+ "content_disposition: write_with_content_disposition /
".to_string(),
+ "content_encoding: write_with_content_encoding / ".to_string(),
+ format!("if_match: write_with_if_match / {condition}"),
+ format!("if_none_match: write_with_if_none_match /
{condition}"),
+ format!("if_not_exists: write_with_if_not_exists /
{condition}"),
+ "user_metadata: write_with_user_metadata / ".to_string(),
+ "checksum: / ".to_string(),
+ ]
+ );
+
+ // 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::",
+ "WriteOptions::",
+ "Operator::",
+ "Reader::",
+ "returns `opendal.exceptions.",
+ "return an error",
+ "Some(",
+ "WriteChecksum",
+ "if_not_changed",
+ "if_version_match",
+ "closing the writer",
+ "this writer",
+ "as it arrives",
+ ] {
+ 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`.
@@ -2123,7 +2549,19 @@ print(json.dumps(docs))
}
let mut keyword_only = false;
let mut kwargs = Vec::new();
- for param in split {
+ for mut param in split {
+ // Drop a stub annotation, as in
+ // `checksum: "ChecksumAlgorithm | None" = None`.
+ if let [
+ TokenTree::Ident(_),
+ TokenTree::Punct(colon),
+ TokenTree::Literal(_),
+ ..,
+ ] = param.as_slice()
+ && colon.as_char() == ':'
+ {
+ param.drain(1..3);
+ }
match param.as_slice() {
[TokenTree::Punct(p)] if p.as_char() == '*' =>
keyword_only = true,
[TokenTree::Ident(name), TokenTree::Punct(eq),
default @ ..]
@@ -2656,43 +3094,268 @@ print(json.dumps(docs))
assert!(rs.contains(&format!("{expected}}}\n")), "{rs}");
}
- /// `open` in read mode accepts the `ReadOptions` keyword arguments
- /// except the response header overrides, and `reject_unknown_kwargs`
- /// treats every `ReadOptions` keyword argument as a read option. The
- /// lists in `bindings/python/src/options.rs` match main (f47ec7c1f) and
- /// the table.
+ /// The `WriteOptions` API on main (a2ef00d6e), with docstrings from core
+ /// except for `checksum`.
#[test]
- fn test_open_read_keys_match_main() {
- let path =
crate::workspace_dir().join("bindings/python/src/options.rs");
- let file =
syn::parse_file(&fs::read_to_string(path).unwrap()).unwrap();
- let list = |name: &str| -> Vec<String> {
- let item = file
- .items
- .iter()
- .find_map(|item| match item {
- syn::Item::Const(c) if c.ident == name => Some(c),
- _ => None,
- })
- .unwrap_or_else(|| panic!("{name} not found"));
- let syn::Expr::Reference(r) = &*item.expr else {
- panic!("{name} is not a slice reference");
- };
- let syn::Expr::Array(array) = &*r.expr else {
- panic!("{name} is not an array");
- };
- array
- .elems
- .iter()
- .map(|e| match e {
- syn::Expr::Lit(syn::ExprLit {
- lit: syn::Lit::Str(s),
- ..
- }) => s.value(),
- _ => panic!("{name} holds a non-string"),
- })
- .collect()
- };
- let open = [
+ fn test_write_options_match_main() {
+ let parsed = core_options();
+ let class = generated_class(&parsed, "WriteOptions");
+ assert_write_surface(&class);
+ let names: Vec<&str> = class.fields.iter().map(|f| f.name).collect();
+ assert_eq!(names, WRITE_KWARGS);
+
+ // Each docstring is the core doc comment of the field it sets, with
+ // the Python wording, and `checksum` keeps its doc from main.
+ let core = parsed.iter().find(|o| o.name == "WriteOptions").unwrap();
+ assert_eq!(class.doc, write_doc(&core.doc, "WriteOptions"));
+ for field in &class.fields {
+ if field.name == "checksum" {
+ assert_eq!(field.doc.join("\n"), WRITE_CHECKSUM_DOC);
+ continue;
+ }
+ let core = core.fields.iter().find(|f| f.name ==
field.name).unwrap();
+ assert_eq!(
+ field.doc,
+ write_doc(&core.doc, field.name),
+ "{}",
+ field.name
+ );
+ }
+ // The Python wording, as a reader sees it.
+ let text = |doc: &[String]| doc.join(" ");
+ assert!(
+ text(&class.doc).contains(
+ "In a write mode, `open()` does not access storage, so
depending on the \
+ service, a check against the stored file fails while writing
to the file \
+ or when closing it."
+ ),
+ "{:?}",
+ class.doc
+ );
+ assert!(
+ text(&class.doc).contains(
+ "surfaces as `opendal.exceptions.Conflict`, or as `OSError`
from the \
+ `write()` or `flush()` of a file from `open()`."
+ ),
+ "{:?}",
+ class.doc
+ );
+ let doc = |name: &str| class.fields.iter().find(|f| f.name ==
name).unwrap();
+ for (name, wording) in [
+ (
+ "chunk",
+ "Without that minimum, `write()` passes its bytes to the
service writer as \
+ one write, and `open()` sets `chunk` to 256 KiB",
+ ),
+ (
+ "concurrent",
+ "`write()` without `chunk` passes its bytes to the service
writer as one write.",
+ ),
+ (
+ "user_metadata",
+ "A later `stat()` returns this metadata as `user_metadata`
when the service \
+ exposes user metadata.",
+ ),
+ ] {
+ assert!(
+ text(&doc(name).doc).contains(wording),
+ "{name}: {:?}",
+ doc(name).doc
+ );
+ }
+ assert!(
+ doc("if_none_match")
+ .doc
+ .join(" ")
+ .contains("use `if_not_exists` when you only need to guard"),
+ "{:?}",
+ doc("if_none_match").doc
+ );
+ let append = doc("append");
+ assert!(
+ append
+ .doc
+ .contains(&"- If not supported, raises
`opendal.exceptions.Unsupported`".into()),
+ "{:?}",
+ append.doc
+ );
+
+ // Each keyword sets the core field main set, and every other core
+ // field keeps its default, as main's `..Default::default()` did.
+ let (set, defaulted): (Vec<_>, Vec<_>) = class
+ .conversion
+ .iter()
+ .map(|f| format!("{}: {}", f.name, f.expr))
+ .partition(|f| f.contains("opts."));
+ assert_eq!(
+ set,
+ [
+ "append: opts.append.unwrap_or(false)",
+ "cache_control: opts.cache_control",
+ "content_type: opts.content_type",
+ "content_disposition: opts.content_disposition",
+ "content_encoding: opts.content_encoding",
+ "user_metadata: opts.user_metadata",
+ "if_match: opts.if_match",
+ "if_none_match: opts.if_none_match",
+ "if_not_exists: opts.if_not_exists.unwrap_or(false)",
+ "concurrent: opts.concurrent.unwrap_or_default()",
+ "chunk: opts.chunk",
+ "checksum: opts.checksum.map(ocore::WriteChecksum::Algo)",
+ ]
+ );
+ for field in [
+ "content_language: None",
+ "expires: 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. `open` rejects unknown
+ // keys before it extracts.
+ let rs = render_options_rs(&generated_classes(&parsed,
&py_names()).unwrap()).unwrap();
+ let extract = rs
+ .split_once("impl<'a, 'py> FromPyObject<'a, 'py> for WriteOptions
{")
+ .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,
+ [
+ "append: extract_optional(&dict, \"append\")?,",
+ "chunk: extract_optional(&dict, \"chunk\")?,",
+ "concurrent: extract_optional(&dict, \"concurrent\")?,",
+ "cache_control: extract_optional(&dict, \"cache_control\")?,",
+ "content_type: extract_optional(&dict, \"content_type\")?,",
+ "content_disposition: extract_optional(&dict,
\"content_disposition\")?,",
+ "content_encoding: extract_optional(&dict,
\"content_encoding\")?,",
+ "if_match: extract_optional(&dict, \"if_match\")?,",
+ "if_none_match: extract_optional(&dict, \"if_none_match\")?,",
+ "if_not_exists: extract_optional(&dict, \"if_not_exists\")?,",
+ "user_metadata: extract_optional(&dict, \"user_metadata\")?,",
+ "checksum: extract_optional(&dict, \"checksum\")?\
+ .map(|name: String|
super::parse_checksum_algorithm(&name)).transpose()?,",
+ ]
+ );
+ assert!(!extract.contains("reject_unknown_kwargs"));
+
+ // The doc comments become `__doc__` and the `_opendal.pyi` docstrings.
+ 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 WriteOptions {{\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}");
+ }
+
+ /// `WRITE_OPTION_KEYS`, which `open` accepts in a write mode, matches main
+ /// (a2ef00d6e) and the table.
+ #[test]
+ fn test_open_write_keys_match_main() {
+ let path =
crate::workspace_dir().join("bindings/python/src/options.rs");
+ let file =
syn::parse_file(&fs::read_to_string(path).unwrap()).unwrap();
+ let item = file
+ .items
+ .iter()
+ .find_map(|item| match item {
+ syn::Item::Const(c) if c.ident == "WRITE_OPTION_KEYS" =>
Some(c),
+ _ => None,
+ })
+ .expect("WRITE_OPTION_KEYS not found");
+ let syn::Expr::Reference(r) = &*item.expr else {
+ panic!("WRITE_OPTION_KEYS is not a slice reference");
+ };
+ let syn::Expr::Array(array) = &*r.expr else {
+ panic!("WRITE_OPTION_KEYS is not an array");
+ };
+ let keys: Vec<String> = array
+ .elems
+ .iter()
+ .map(|e| match e {
+ syn::Expr::Lit(syn::ExprLit {
+ lit: syn::Lit::Str(s),
+ ..
+ }) => s.value(),
+ _ => panic!("WRITE_OPTION_KEYS holds a non-string"),
+ })
+ .collect();
+ assert_eq!(keys, WRITE_KWARGS);
+
+ let class = generated_class(&core_options(), "WriteOptions");
+ let names: Vec<&str> = class.fields.iter().map(|f| f.name).collect();
+ assert_eq!(names, keys);
+ }
+
+ /// `open` in read mode accepts the `ReadOptions` keyword arguments
+ /// except the response header overrides, and `reject_unknown_kwargs`
+ /// treats every `ReadOptions` keyword argument as a read option. The
+ /// lists in `bindings/python/src/options.rs` match main (f47ec7c1f) and
+ /// the table.
+ #[test]
+ fn test_open_read_keys_match_main() {
+ let path =
crate::workspace_dir().join("bindings/python/src/options.rs");
+ let file =
syn::parse_file(&fs::read_to_string(path).unwrap()).unwrap();
+ let list = |name: &str| -> Vec<String> {
+ let item = file
+ .items
+ .iter()
+ .find_map(|item| match item {
+ syn::Item::Const(c) if c.ident == name => Some(c),
+ _ => None,
+ })
+ .unwrap_or_else(|| panic!("{name} not found"));
+ let syn::Expr::Reference(r) = &*item.expr else {
+ panic!("{name} is not a slice reference");
+ };
+ let syn::Expr::Array(array) = &*r.expr else {
+ panic!("{name} is not an array");
+ };
+ array
+ .elems
+ .iter()
+ .map(|e| match e {
+ syn::Expr::Lit(syn::ExprLit {
+ lit: syn::Lit::Str(s),
+ ..
+ }) => s.value(),
+ _ => panic!("{name} holds a non-string"),
+ })
+ .collect()
+ };
+ let open = [
"version",
"concurrent",
"chunk",
@@ -2830,8 +3493,9 @@ print(json.dumps(docs))
/// The `options.py` TypedDicts on main (4ae8e6122 for `ListKwargs`,
/// 809b76472 for `StatKwargs`, 501c5d96f for `DeleteKwargs`, f47ec7c1f
- /// for `ReadKwargs`): the class order and the keys and types of the
- /// generated classes, with docstrings taken from core.
+ /// for `ReadKwargs`, a2ef00d6e for `WriteKwargs`): 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();
@@ -2893,6 +3557,23 @@ print(json.dumps(docs))
"content_disposition: str",
]
);
+ assert_eq!(
+ keys("WriteKwargs", "ListKwargs"),
+ [
+ "append: bool",
+ "chunk: int",
+ "concurrent: int",
+ "cache_control: str",
+ "content_type: str",
+ "content_disposition: str",
+ "content_encoding: str",
+ "if_match: str",
+ "if_none_match: str",
+ "if_not_exists: bool",
+ "user_metadata: dict[str, str]",
+ "checksum: ChecksumAlgorithm | None",
+ ]
+ );
assert_eq!(
keys("ListKwargs", "StatKwargs"),
[
@@ -2932,6 +3613,11 @@ 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 \
+ `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 \
+ `opendal.exceptions` class.",
] {
assert!(open.contains(name), "{name}");
}
@@ -3025,6 +3711,29 @@ print(json.dumps(docs))
assert!(!methods.contains_key(&("Operator".to_string(),
"presign_read".to_string())));
}
+ /// The `write` and `presign_write` keyword arguments and defaults on
+ /// main (a2ef00d6e), copied from `python/opendal/operator.pyi`.
+ #[test]
+ fn test_write_signatures_match_main() {
+ let methods = operator_kwargs();
+ let write = "append=None chunk=None concurrent=None cache_control=None
\
+ content_type=None content_disposition=None
content_encoding=None \
+ if_match=None if_none_match=None if_not_exists=None \
+ user_metadata=None checksum=None";
+ let presign = "content_type=None content_disposition=None
content_encoding=None \
+ cache_control=None if_match=None if_none_match=None \
+ if_not_exists=None user_metadata=None";
+ for (ty, method, kwargs) in [
+ ("Operator", "write", write),
+ ("AsyncOperator", "write", write),
+ ("AsyncOperator", "presign_write", presign),
+ ] {
+ let key = (ty.to_string(), method.to_string());
+ assert_eq!(methods[&key].join(" "), kwargs, "{ty}.{method}");
+ }
+ assert!(!methods.contains_key(&("Operator".to_string(),
"presign_write".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`.
@@ -3033,8 +3742,9 @@ print(json.dumps(docs))
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, and
- // `presign_read` takes no range or read tuning.
+ // 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"][..]),
@@ -3064,6 +3774,14 @@ print(json.dumps(docs))
"ReadOptions",
&["concurrent", "chunk", "gap", "offset", "prefetch",
"size"][..],
),
+ ("Operator", "write", "WriteOptions", &[][..]),
+ ("AsyncOperator", "write", "WriteOptions", &[][..]),
+ (
+ "AsyncOperator",
+ "presign_write",
+ "WriteOptions",
+ &["append", "chunk", "concurrent", "checksum"][..],
+ ),
] {
let class = generated_class(&parsed, class);
let mut expected: Vec<String> = class
@@ -3102,8 +3820,14 @@ print(json.dumps(docs))
let mut mutated = parsed.clone();
for options in mutated.iter_mut().filter(|o| {
- ["ListOptions", "StatOptions", "DeleteOptions", "ReadOptions"]
- .contains(&o.name.as_str())
+ [
+ "ListOptions",
+ "StatOptions",
+ "DeleteOptions",
+ "ReadOptions",
+ "WriteOptions",
+ ]
+ .contains(&o.name.as_str())
}) {
for (name, kind) in [
("fake_option", OptionKind::OptionString),
@@ -3133,6 +3857,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();
@@ -3145,7 +3871,7 @@ print(json.dumps(docs))
options.fields.iter().position(|f| f.name == name).unwrap()
}
type Mutation = fn(&mut OptionsStruct);
- let cases: [(&str, Mutation, &str); 30] = [
+ let cases: [(&str, Mutation, &str); 38] = [
(
"ListOptions",
|list| {
@@ -3395,6 +4121,85 @@ print(json.dumps(docs))
"core ReaderOptions::prefetch has kind OptionUsize; \
Python ReadOptions.prefetch requires Usize",
),
+ (
+ "WriteOptions",
+ |write| {
+ write.fields.remove(position(write, "if_not_exists"));
+ },
+ "core WriteOptions has no field `if_not_exists` \
+ for Python WriteOptions.if_not_exists",
+ ),
+ (
+ "WriteOptions",
+ |write| {
+ let i = position(write, "append");
+ write.fields[i].kind = OptionKind::OptionString;
+ },
+ "core WriteOptions::append has kind OptionString; \
+ Python WriteOptions.append requires Bool",
+ ),
+ (
+ "WriteOptions",
+ |write| {
+ let i = position(write, "concurrent");
+ write.fields[i].kind = OptionKind::OptionUsize;
+ },
+ "core WriteOptions::concurrent has kind OptionUsize; \
+ Python WriteOptions.concurrent requires Usize",
+ ),
+ (
+ "WriteOptions",
+ |write| {
+ let i = position(write, "user_metadata");
+ write.fields[i].kind = OptionKind::OptionMetadata;
+ },
+ "core WriteOptions::user_metadata has kind OptionMetadata; \
+ Python WriteOptions.user_metadata requires OptionStringMap",
+ ),
+ (
+ "WriteOptions",
+ |write| {
+ let i = position(write, "content_encoding");
+ write.fields[i].doc.clear();
+ },
+ "core WriteOptions::content_encoding has no doc comment",
+ ),
+ // Once core mirrors `checksum`, Python must list it with its
+ // core kind instead of converting it by hand.
+ (
+ "WriteOptions",
+ |write| write.has_unmirrored_fields = false,
+ "core WriteOptions has no fields the core options parser
skips; \
+ list Python WriteOptions.checksum with its core kind",
+ ),
+ (
+ "WriteOptions",
+ |write| {
+ let i = position(write, "append");
+ for line in &mut write.fields[i].doc {
+ *line = line.replace("will return an error", "fails");
+ }
+ },
+ "core WriteOptions docs no longer contain \
+ `- If not supported, will return an error`; \
+ update its Python rewrite in dev/src/generate/python.rs",
+ ),
+ // A rewrite that spans lines fails once core rewraps it.
+ (
+ "WriteOptions",
+ |write| {
+ for line in &mut write.doc {
+ *line = line.replace("fails before the writer", "fails
early");
+ }
+ },
+ "core WriteOptions docs no longer contain \
+ `Creating a writer does not access storage, so\n\
+ depending on the service, a check against the stored file
fails while\n\
+ writing or when closing the writer. Combining
`if_not_changed` with a\n\
+ conflicting `if_match` or `if_version_match` fails before the
writer\n\
+ exists, without accessing storage.`; \
+ update its Python rewrite in dev/src/generate/python.rs",
+ ),
];
let parsed = core_options();
@@ -3547,6 +4352,7 @@ print(json.dumps(docs))
let spec = PyOptions {
name,
options,
+ unmirrored: &[],
docs,
rewrites: &[],
};
@@ -3563,6 +4369,7 @@ print(json.dumps(docs))
let spec = PyOptions {
name: "ReadOptions",
options: &[OFFSET, SIZE],
+ unmirrored: &[],
docs: &[
("offset", &["Offset, in Python words."]),
("size", &["Size."]),
@@ -3586,6 +4393,7 @@ print(json.dumps(docs))
let spec = PyOptions {
name: "ReadOptions",
options,
+ unmirrored: &[],
docs: RANGE_DOCS,
rewrites: &[],
};
@@ -3602,6 +4410,117 @@ print(json.dumps(docs))
}
}
+ /// An `unmirrored` row needs a Python doc, a unique name, and a core
+ /// struct whose parser skips a field and does not list this one.
+ #[test]
+ fn test_options_table_rejects_bad_unmirrored_rows() {
+ const CHECKSUM: PyUnmirrored = PyUnmirrored {
+ name: "checksum",
+ py_type: options::OptionType::ChecksumAlgo,
+ rust_type: "Option<ocore::ChecksumAlgo>",
+ extract: "",
+ convert: "",
+ };
+ const APPEND: (&str, &str, OptionKind, &str) =
+ ("append", "append", OptionKind::Bool, "Option<bool>");
+ type Rows = &'static [(&'static str, &'static str, OptionKind,
&'static str)];
+ type Docs = &'static [(&'static str, &'static [&'static str])];
+ const DOC: Docs = &[("checksum", &["Checksum."])];
+ let parsed = core_options();
+ let cases: [(&str, Rows, &[PyUnmirrored], Docs, &str); 6] = [
+ (
+ "WriteOptions",
+ &[APPEND],
+ &[],
+ &[],
+ "core WriteOptions has fields the core options parser skips; \
+ Python cannot set them",
+ ),
+ (
+ "StatOptions",
+ &[],
+ &[CHECKSUM],
+ DOC,
+ "core StatOptions has no fields the core options parser skips;
\
+ list Python StatOptions.checksum with its core kind",
+ ),
+ (
+ "WriteOptions",
+ &[("checksum", "append", OptionKind::Bool, "Option<bool>")],
+ &[CHECKSUM],
+ DOC,
+ "Python WriteOptions lists `checksum` twice",
+ ),
+ (
+ "WriteOptions",
+ &[("appending", "append", OptionKind::Bool, "Option<bool>")],
+ &[PyUnmirrored {
+ name: "append",
+ ..CHECKSUM
+ }],
+ &[("append", &["Append."])],
+ "Python WriteOptions sets core `append` twice",
+ ),
+ (
+ "WriteOptions",
+ &[],
+ &[PyUnmirrored {
+ name: "concurrent",
+ ..CHECKSUM
+ }],
+ &[("concurrent", &["Concurrent."])],
+ "core WriteOptions::concurrent is no longer skipped by the
core options \
+ parser; list Python WriteOptions.concurrent with its core
kind",
+ ),
+ (
+ "WriteOptions",
+ &[APPEND],
+ &[CHECKSUM],
+ &[],
+ "Python WriteOptions.checksum needs a Python doc, because the
core options \
+ parser skips core `checksum`",
+ ),
+ ];
+ for (name, options, unmirrored, docs, error) in cases {
+ let spec = PyOptions {
+ name,
+ options,
+ unmirrored,
+ docs,
+ rewrites: &[],
+ };
+ assert_eq!(
+ py_class(&spec, &parsed, &py_names())
+ .unwrap_err()
+ .to_string(),
+ error
+ );
+ }
+
+ // The keyword argument follows the listed ones and sets its core
+ // field by hand.
+ let spec = PyOptions {
+ name: "WriteOptions",
+ options: &[APPEND],
+ unmirrored: &[PyUnmirrored {
+ convert: ".map(Algo)",
+ ..CHECKSUM
+ }],
+ docs: DOC,
+ rewrites: &[],
+ };
+ let class = py_class(&spec, &parsed, &py_names()).unwrap();
+ let names: Vec<&str> = class.fields.iter().map(|f| f.name).collect();
+ assert_eq!(names, ["append", "checksum"]);
+ assert_eq!(class.fields[1].doc, ["Checksum."]);
+ assert_eq!(class.fields[1].kind, None);
+ let checksum = class.conversion.last().unwrap();
+ assert_eq!(
+ format!("{}: {}", checksum.name, checksum.expr),
+ "checksum: opts.checksum.map(Algo)"
+ );
+ }
+
#[test]
fn test_py_doc_strips_rustdoc_links() {
let lines = [
@@ -4130,6 +5049,152 @@ print(json.dumps(docs))
}
}
+ /// Reworded core `WriteOptions` docs, in either markup and with quotes and
+ /// backslashes, pass the surface checks and read back in Python.
+ #[test]
+ fn test_write_options_survive_core_rewording() {
+ let mut parsed = core_options();
+ let base = generated_class(&parsed, "WriteOptions");
+ let write = parsed
+ .iter_mut()
+ .find(|o| o.name == "WriteOptions")
+ .unwrap();
+ write.doc = [
+ r#""Write" options, with \d."#,
+ "",
+ "- A failed condition returns `ErrorKind::ConditionNotMatch`.
Creating a writer does not access storage, so",
+ "depending on the service, a check against the stored file fails
while",
+ "writing or when closing the writer. Combining `if_not_changed`
with a",
+ "conflicting `if_match` or `if_version_match` fails before the
writer",
+ "exists, without accessing storage.",
+ "- 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 write.fields {
+ let mut doc = vec![format!(
+ r#"Reworded "{}" doc, see [the spec][crate::docs::specs::x]."#,
+ field.name
+ )];
+ if let Some(python) = base.fields.iter().find(|f| f.core ==
field.name) {
+ for (i, name) in spans(&python.doc, "op.capability().")
+ .into_iter()
+ .enumerate()
+ {
+ doc.push(match i % 2 {
+ 0 => format!("Check `Capability::{name}`."),
+ _ => format!("Check
[`Capability::{name}`](crate::Capability::{name})."),
+ });
+ }
+ // The Python wording of `append` names its exception.
+ if field.name != "append" {
+ for name in spans(&python.doc, "opendal.exceptions.") {
+ doc.push("It returns".to_string());
+ doc.push(format!("[`crate::ErrorKind::{name}`]."));
+ }
+ }
+ }
+ let core_text: &[&str] = match field.name.as_str() {
+ "chunk" => &[
+ "buffered at once; a service without that minimum receives
each write",
+ "as it arrives",
+ ],
+ "concurrent" => &[
+ "Sets concurrent write operations for this writer.",
+ "[`crate::Operator::write_with`] and
[`crate::Operator::write_options`]",
+ "without `chunk` pass the whole buffer to the service
writer as one",
+ "write.",
+ ],
+ "user_metadata" => &[
+ "A later stat returns this metadata when the service
exposes user metadata.",
+ "[`crate::Reader::metadata`] may omit it, for example on
`fs`.",
+ ],
+ _ => &[],
+ };
+ doc.extend(core_text.iter().map(|line| line.to_string()));
+ match field.name.as_str() {
+ "append" => doc.push("- If not supported, will return an
error".into()),
+ "if_none_match" => doc.push(
+ "Prefer [`WriteOptions::if_not_exists`], or
`WriteOptions::append`.".into(),
+ ),
+ _ => {}
+ }
+ field.doc = doc;
+ }
+
+ let generated = generated_classes(&parsed, &py_names()).unwrap();
+ let class = generated.iter().find(|c| c.name ==
"WriteOptions").unwrap();
+ assert_write_surface(class);
+
+ let py = render_options_py(&crate::workspace_dir(),
&generated).unwrap();
+ let docs = python_docstrings(&py);
+ assert_eq!(
+ docs["WriteKwargs"],
+ "\"Write\" options, with \\d.\n\
+ \n\
+ - A failed condition raises
`opendal.exceptions.ConditionNotMatch`. \
+ In a write mode, `open()` does not access storage,\n\
+ so depending on the service, a check against the stored file
fails\n\
+ while writing to the file or when closing it.\n\
+ - A missing capability raises `opendal.exceptions.Unsupported`,\n\
+ and a combination also raises `opendal.exceptions.Unsupported`.\n\
+ - A conflict surfaces as\n\
+ `opendal.exceptions.Conflict`, or as `OSError` from the `write()`
or\n\
+ `flush()` of a file from `open()`."
+ );
+ assert_eq!(
+ docs["WriteKwargs.append"],
+ "Reworded \"append\" doc, see the spec.\n\
+ Check `op.capability().write_can_append`.\n\
+ - If not supported, raises `opendal.exceptions.Unsupported`"
+ );
+ assert_eq!(
+ docs["WriteKwargs.if_none_match"],
+ "Reworded \"if_none_match\" doc, see the spec.\n\
+ Check `op.capability().write_with_if_none_match`.\n\
+ It raises\n\
+ `opendal.exceptions.ConditionNotMatch`.\n\
+ It raises\n\
+ `opendal.exceptions.Unsupported`.\n\
+ Prefer `if_not_exists`, or `append`."
+ );
+ assert_eq!(
+ docs["WriteKwargs.chunk"],
+ "Reworded \"chunk\" doc, see the spec.\n\
+ Check `op.capability().write_multi_min_size`.\n\
+ Check `op.capability().write_multi_max_size`.\n\
+ Check `op.capability().write_multi_min_size`.\n\
+ Check `op.capability().write_multi_min_size`.\n\
+ Check `op.capability().write_multi_max_size`.\n\
+ buffered at once. Without that minimum, `write()` passes its
bytes to\n\
+ the service writer as one write, and `open()` sets `chunk` to 256
KiB"
+ );
+ assert_eq!(
+ docs["WriteKwargs.concurrent"],
+ "Reworded \"concurrent\" doc, see the spec.\n\
+ Sets concurrent write operations for `write()` or a file from
`open()`.\n\
+ `write()` without `chunk` passes its bytes to the service writer
as one\n\
+ write."
+ );
+ assert_eq!(
+ docs["WriteKwargs.user_metadata"],
+ "Reworded \"user_metadata\" doc, see the spec.\n\
+ Check `op.capability().write_with_user_metadata`.\n\
+ A later `stat()` returns this metadata as `user_metadata` when
the\n\
+ service exposes user metadata."
+ );
+ assert_eq!(docs["WriteKwargs.checksum"], WRITE_CHECKSUM_DOC);
+ for field in &class.fields {
+ assert_eq!(
+ docs[&format!("WriteKwargs.{}", field.name)],
+ field.doc.join("\n")
+ );
+ }
+ }
+
/// 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
@@ -4214,6 +5279,59 @@ print(json.dumps(docs))
);
}
+ /// The hand-written `write` and `open` docstrings agree with the
+ /// generated `WriteOptions` and `OpenKwargs` docs.
+ #[test]
+ fn test_write_docstrings_agree_with_write_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(), "WriteOptions");
+ let conditions: Vec<String> = class
+ .fields
+ .iter()
+ .filter(|f| spans(&f.doc,
"opendal.exceptions.").contains(&"ConditionNotMatch"))
+ .map(|f| format!("`{}`", f.name))
+ .collect();
+ assert_eq!(
+ conditions,
+ ["`if_match`", "`if_none_match`", "`if_not_exists`"]
+ );
+ let raises = format!(
+ " /// ConditionNotMatch\n /// If {}, {}, or {} fails.\n",
+ conditions[0], conditions[1], conditions[2]
+ );
+ assert_eq!(
+ operator.matches(&raises).count(),
+ 2,
+ "Operator.write and AsyncOperator.write"
+ );
+ // Both `write` docstrings describe `concurrent` as its option doc
does.
+ let concurrent = class
+ .fields
+ .iter()
+ .find(|f| f.name == "concurrent")
+ .unwrap();
+ let one_write = "passes its bytes to the service writer as one";
+ assert!(concurrent.doc.join(" ").contains(one_write));
+ let param = format!(
+ " /// concurrent : int, optional\n \
+ /// The number of writes to run concurrently. Without
`chunk`, `write()`\n \
+ /// {one_write} write, which only a\n"
+ );
+ assert_eq!(
+ operator.matches(¶m).count(),
+ 2,
+ "Operator.write and AsyncOperator.write"
+ );
+ let deferred = "In write, append, or create mode, if writing fails
other than by a\n \
+ /// failed condition. The failure surfaces from
the file's `write()`";
+ assert_eq!(
+ operator.matches(deferred).count(),
+ 2,
+ "Operator.open and AsyncOperator.open"
+ );
+ }
+
/// Every capability and exception the generated docstrings name exists
/// in the Python API: `python/opendal/capability.pyi` and
/// `python/opendal/exceptions.pyi`.
@@ -4291,6 +5409,26 @@ print(json.dumps(docs))
"Unsupported",
][..],
),
+ (
+ "WriteOptions",
+ &[
+ "write_can_append",
+ "write_multi_min_size",
+ "write_multi_max_size",
+ "write_multi_min_size",
+ "write_multi_min_size",
+ "write_multi_max_size",
+ "write_with_cache_control",
+ "write_with_content_type",
+ "write_with_content_disposition",
+ "write_with_content_encoding",
+ "write_with_if_match",
+ "write_with_if_none_match",
+ "write_with_if_not_exists",
+ "write_with_user_metadata",
+ ][..],
+ &["ConditionNotMatch", "Conflict", "Unsupported"][..],
+ ),
] {
let class = generated_class(&parsed, class);
let docs: Vec<String> = class