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 501c5d96f6 feat(bindings/python): generate StatOptions from core
(#9351)
501c5d96f6 is described below
commit 501c5d96f6a420d8e17396926c91d277f4070d31
Author: Chitral Verma <[email protected]>
AuthorDate: Sun Nov 29 15:05:35 2026 +0530
feat(bindings/python): generate StatOptions from core (#9351)
* feat(bindings/python): generate StatOptions from core
Generate the Python StatOptions pyclass and StatKwargs from core's
StatOptions through the ListOptions generator. The table now records the
core field each keyword sets, so content_type, cache_control, and
content_disposition keep their names, and the Rust field type, so
checksum stays a bool. Docstrings come from core, with Rust path links
reduced to their text and "returns" before an exception read as
"raises".
Signed-off-by: Chitral Verma <[email protected]>
* chore: regenerate StatOptions docs from core
Signed-off-by: Chitral Verma <[email protected]>
---------
Signed-off-by: Chitral Verma <[email protected]>
---
bindings/python/python/opendal/_opendal.pyi | 16 +-
bindings/python/python/opendal/options.py | 94 ++-
bindings/python/src/options.rs | 65 --
bindings/python/src/options/generated.rs | 130 ++++
dev/src/generate/options.rs | 5 +-
dev/src/generate/python.rs | 1040 ++++++++++++++++++++++-----
dev/src/generate/python/options_rs.j2 | 2 +-
7 files changed, 1097 insertions(+), 255 deletions(-)
diff --git a/bindings/python/python/opendal/_opendal.pyi
b/bindings/python/python/opendal/_opendal.pyi
index bfae3927b3..87b394176a 100644
--- a/bindings/python/python/opendal/_opendal.pyi
+++ b/bindings/python/python/opendal/_opendal.pyi
@@ -68,7 +68,21 @@ class ReadOptions:
@final
class StatOptions:
- """Options for `stat` operations."""
+ """
+ Options for stat operations.
+
+ Each condition checks the file being observed, and every condition must
+ hold for the stat to return metadata. With valid, supported options, stat
+ raises `opendal.exceptions.NotFound` for a missing file. An existing
+ file that fails a condition raises
+ `opendal.exceptions.ConditionNotMatch`, and a condition the service does
+ not advertise through its capability raises
+ `opendal.exceptions.Unsupported`; OpenDAL never silently drops a
+ condition.
+
+ See the conditional operation specification
+ for the complete cross-operation contract.
+ """
@final
class WriteOptions:
diff --git a/bindings/python/python/opendal/options.py
b/bindings/python/python/opendal/options.py
index ef8a473505..1699a6b714 100644
--- a/bindings/python/python/opendal/options.py
+++ b/bindings/python/python/opendal/options.py
@@ -153,26 +153,100 @@ class ListKwargs(TypedDict, total=False):
class StatKwargs(TypedDict, total=False):
- """Options for `stat` operations."""
+ """Options for stat operations.
+
+ Each condition checks the file being observed, and every condition must
+ hold for the stat to return metadata. With valid, supported options, stat
+ raises `opendal.exceptions.NotFound` for a missing file. An existing
+ file that fails a condition raises
+ `opendal.exceptions.ConditionNotMatch`, and a condition the service does
+ not advertise through its capability raises
+ `opendal.exceptions.Unsupported`; OpenDAL never silently drops a
+ condition.
+
+ See the conditional operation specification
+ for the complete cross-operation contract.
+ """
version: str
- """The version of the file."""
+ """Stat the given version of the file instead of the current one.
+
+ This selects which stored version the stat describes; it is not a
+ condition on the file. A version that does not exist raises
+ `opendal.exceptions.NotFound`.
+
+ Check `op.capability().stat_with_version` before using this
+ option.
+ """
if_match: str
- """The ETag of the file."""
+ """Stat only when the file has this exact ETag.
+
+ The condition succeeds when the file exists and its ETag equals this
+ value. A file with a different ETag raises
+ `opendal.exceptions.ConditionNotMatch`; a missing file raises
+ `opendal.exceptions.NotFound`. 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().stat_with_if_match`.
+ """
if_none_match: str
- """The ETag of the file."""
+ """Stat only when the file does not have this ETag.
+
+ With a concrete ETag value, the condition succeeds when the file
+ exists with a different ETag. A file whose ETag equals this value
+ raises `opendal.exceptions.ConditionNotMatch`; a missing file
+ raises `opendal.exceptions.NotFound`. 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().stat_with_if_none_match`.
+ """
if_modified_since: datetime
- """The last modified time of the file."""
+ """Stat only when the file was modified after this timestamp.
+
+ The condition succeeds when the file exists and was modified after
+ this time. A file not modified since this time raises
+ `opendal.exceptions.ConditionNotMatch`; a missing file raises
+ `opendal.exceptions.NotFound`.
+
+ The operation raises `opendal.exceptions.Unsupported` when the
+ service does not advertise
+ `op.capability().stat_with_if_modified_since`.
+ """
if_unmodified_since: datetime
- """The last modified time of the file."""
+ """Stat only when the file was not modified after this timestamp.
+
+ The condition succeeds when the file exists and was not modified
+ after this time. A file modified after this time raises
+ `opendal.exceptions.ConditionNotMatch`; a missing file raises
+ `opendal.exceptions.NotFound`.
+
+ The operation raises `opendal.exceptions.Unsupported` when the
+ service does not advertise
+ `op.capability().stat_with_if_unmodified_since`.
+ """
content_type: str
- """The content type of the file."""
+ """Request a `content-type` response header override from services that
+ support it, including for presigned stat requests.
+ """
cache_control: str
- """The cache control of the file."""
+ """Request a `cache-control` response header override from services that
+ support it, including for presigned stat requests.
+ """
content_disposition: str
- """The content disposition of the file."""
+ """Request a `content-disposition` response header override from services
+ that support it, including for presigned stat requests.
+ """
checksum: bool
- """Request the service's full-object checksum when available. Defaults to
False."""
+ """Request full-file checksum metadata when the service can provide it.
+
+ This hint defaults to `false`. Services can ignore it or return checksum
+ metadata by default. OpenDAL does not read object data to obtain it.
+
+ See the checksum specification.
+ """
class CopyKwargs(TypedDict, total=False):
diff --git a/bindings/python/src/options.rs b/bindings/python/src/options.rs
index f3c7027d93..f344acf019 100644
--- a/bindings/python/src/options.rs
+++ b/bindings/python/src/options.rs
@@ -382,71 +382,6 @@ impl From<WriteOptions> for ocore::options::WriteOptions {
}
}
-/// Options for `stat` operations.
-#[pyclass(module = "opendal")]
-#[derive(Default, Debug)]
-pub struct StatOptions {
- /// The version of the file.
- pub version: Option<String>,
- /// The ETag of the file.
- pub if_match: Option<String>,
- /// The ETag of the file.
- pub if_none_match: Option<String>,
- /// The last modified time of the file.
- pub if_modified_since: Option<jiff::Timestamp>,
- /// The last modified time of the file.
- pub if_unmodified_since: Option<jiff::Timestamp>,
- /// The content type of the file.
- pub content_type: Option<String>,
- /// The cache control of the file.
- pub cache_control: Option<String>,
- /// The content disposition of the file.
- pub content_disposition: Option<String>,
- /// Request the service's full-object checksum when available. Defaults to
False.
- pub checksum: bool,
-}
-
-impl<'a, 'py> FromPyObject<'a, 'py> for StatOptions {
- type Error = PyErr;
-
- fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
- let dict = downcast_kwargs(obj)?;
-
- Ok(Self {
- version: extract_optional(&dict, "version")?,
- if_match: extract_optional(&dict, "if_match")?,
- if_none_match: extract_optional(&dict, "if_none_match")?,
- if_modified_since: extract_optional(&dict, "if_modified_since")?,
- if_unmodified_since: extract_optional(&dict,
"if_unmodified_since")?,
- content_type: extract_optional(&dict, "content_type")?,
- cache_control: extract_optional(&dict, "cache_control")?,
- content_disposition: extract_optional(&dict,
"content_disposition")?,
- checksum: extract_optional(&dict, "checksum")?.unwrap_or_default(),
- })
- }
-}
-
-impl From<StatOptions> for ocore::options::StatOptions {
- fn from(opts: StatOptions) -> Self {
- Self {
- version: opts.version,
- if_match: opts.if_match,
- if_none_match: opts.if_none_match,
- if_modified_since: opts
- .if_modified_since
- .map(crate::utils::timestamp_from_jiff),
- if_unmodified_since: opts
- .if_unmodified_since
- .map(crate::utils::timestamp_from_jiff),
- override_content_type: opts.content_type,
- override_cache_control: opts.cache_control,
- override_content_disposition: opts.content_disposition,
- checksum: opts.checksum,
- ..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 94f5f4f7d4..1a0003f8e7 100644
--- a/bindings/python/src/options/generated.rs
+++ b/bindings/python/src/options/generated.rs
@@ -87,3 +87,133 @@ impl From<ListOptions> for ocore::options::ListOptions {
}
}
}
+
+/// Options for stat operations.
+///
+/// Each condition checks the file being observed, and every condition must
+/// hold for the stat to return metadata. With valid, supported options, stat
+/// raises `opendal.exceptions.NotFound` for a missing file. An existing
+/// file that fails a condition raises
+/// `opendal.exceptions.ConditionNotMatch`, and a condition the service does
+/// not advertise through its capability raises
+/// `opendal.exceptions.Unsupported`; OpenDAL never silently drops a
+/// condition.
+///
+/// See the conditional operation specification
+/// for the complete cross-operation contract.
+#[pyclass(module = "opendal")]
+#[derive(Default, Debug)]
+pub struct StatOptions {
+ /// Stat the given version of the file instead of the current one.
+ ///
+ /// This selects which stored version the stat describes; it is not a
+ /// condition on the file. A version that does not exist raises
+ /// `opendal.exceptions.NotFound`.
+ ///
+ /// Check `op.capability().stat_with_version` before using this
+ /// option.
+ pub version: Option<String>,
+ /// Stat only when the file has this exact ETag.
+ ///
+ /// The condition succeeds when the file exists and its ETag equals this
+ /// value. A file with a different ETag raises
+ /// `opendal.exceptions.ConditionNotMatch`; a missing file raises
+ /// `opendal.exceptions.NotFound`. 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().stat_with_if_match`.
+ pub if_match: Option<String>,
+ /// Stat only when the file does not have this ETag.
+ ///
+ /// With a concrete ETag value, the condition succeeds when the file
+ /// exists with a different ETag. A file whose ETag equals this value
+ /// raises `opendal.exceptions.ConditionNotMatch`; a missing file
+ /// raises `opendal.exceptions.NotFound`. 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().stat_with_if_none_match`.
+ pub if_none_match: Option<String>,
+ /// Stat only when the file was modified after this timestamp.
+ ///
+ /// The condition succeeds when the file exists and was modified after
+ /// this time. A file not modified since this time raises
+ /// `opendal.exceptions.ConditionNotMatch`; a missing file raises
+ /// `opendal.exceptions.NotFound`.
+ ///
+ /// The operation raises `opendal.exceptions.Unsupported` when the
+ /// service does not advertise
+ /// `op.capability().stat_with_if_modified_since`.
+ pub if_modified_since: Option<jiff::Timestamp>,
+ /// Stat only when the file was not modified after this timestamp.
+ ///
+ /// The condition succeeds when the file exists and was not modified
+ /// after this time. A file modified after this time raises
+ /// `opendal.exceptions.ConditionNotMatch`; a missing file raises
+ /// `opendal.exceptions.NotFound`.
+ ///
+ /// The operation raises `opendal.exceptions.Unsupported` when the
+ /// service does not advertise
+ /// `op.capability().stat_with_if_unmodified_since`.
+ pub if_unmodified_since: Option<jiff::Timestamp>,
+ /// Request a `content-type` response header override from services that
+ /// support it, including for presigned stat requests.
+ pub content_type: Option<String>,
+ /// Request a `cache-control` response header override from services that
+ /// support it, including for presigned stat requests.
+ pub cache_control: Option<String>,
+ /// Request a `content-disposition` response header override from services
+ /// that support it, including for presigned stat requests.
+ pub content_disposition: Option<String>,
+ /// Request full-file checksum metadata when the service can provide it.
+ ///
+ /// This hint defaults to `false`. Services can ignore it or return
checksum
+ /// metadata by default. OpenDAL does not read object data to obtain it.
+ ///
+ /// See the checksum specification.
+ pub checksum: bool,
+}
+
+impl<'a, 'py> FromPyObject<'a, 'py> for StatOptions {
+ type Error = PyErr;
+
+ fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
+ let dict = downcast_kwargs(obj)?;
+
+ Ok(Self {
+ version: extract_optional(&dict, "version")?,
+ if_match: extract_optional(&dict, "if_match")?,
+ if_none_match: extract_optional(&dict, "if_none_match")?,
+ if_modified_since: extract_optional(&dict, "if_modified_since")?,
+ if_unmodified_since: extract_optional(&dict,
"if_unmodified_since")?,
+ content_type: extract_optional(&dict, "content_type")?,
+ cache_control: extract_optional(&dict, "cache_control")?,
+ content_disposition: extract_optional(&dict,
"content_disposition")?,
+ checksum: extract_optional(&dict, "checksum")?.unwrap_or_default(),
+ })
+ }
+}
+
+impl From<StatOptions> for ocore::options::StatOptions {
+ fn from(opts: StatOptions) -> Self {
+ Self {
+ version: opts.version,
+ if_match: opts.if_match,
+ if_none_match: opts.if_none_match,
+ if_version_match: None,
+ if_version_not_match: None,
+ if_modified_since: opts
+ .if_modified_since
+ .map(crate::utils::timestamp_from_jiff),
+ if_unmodified_since: opts
+ .if_unmodified_since
+ .map(crate::utils::timestamp_from_jiff),
+ override_content_type: opts.content_type,
+ override_cache_control: opts.cache_control,
+ override_content_disposition: opts.content_disposition,
+ checksum: opts.checksum,
+ }
+ }
+}
diff --git a/dev/src/generate/options.rs b/dev/src/generate/options.rs
index e178ba080f..93649699e3 100644
--- a/dev/src/generate/options.rs
+++ b/dev/src/generate/options.rs
@@ -199,7 +199,6 @@ mod tests {
[
"ReadOptions",
"WriteOptions",
- "StatOptions",
"CopyOptions",
"RenameOptions",
"DeleteOptions"
@@ -228,7 +227,7 @@ mod tests {
"The user metadata to set on the file."
);
- for option in [&options[3], &options[4]] {
+ for option in [&options[2], &options[3]] {
assert!(
option
.fields
@@ -239,7 +238,7 @@ mod tests {
);
}
- let delete = &options[5];
+ let delete = &options[4];
assert_eq!(delete.fields.len(), 3);
assert_eq!(
delete.fields[1].doc,
diff --git a/dev/src/generate/python.rs b/dev/src/generate/python.rs
index 1639ab669d..025aeadc0a 100644
--- a/dev/src/generate/python.rs
+++ b/dev/src/generate/python.rs
@@ -655,25 +655,92 @@ const PYTHON_LICENSE_HEADER: &str = "\
struct PyOptions {
/// The class name, e.g. `ListOptions`.
name: &'static str,
- /// The keyword arguments in their Python order: the name, which is also
- /// the core field and the Rust field it sets, and the kind that core
- /// field must have. A core field that no keyword argument sets is not
- /// exposed and keeps its default.
- options: &'static [(&'static str, OptionKind)],
+ /// The keyword arguments in their Python order, each as:
+ ///
+ /// - the name, which is also the Rust field it sets;
+ /// - the core field it sets;
+ /// - the kind that core field must have;
+ /// - the Rust field type, which the methods in `operator.rs` build the
+ /// class with (see [`lowering`]).
+ ///
+ /// A core field that no keyword argument sets is not exposed and keeps
+ /// its default.
+ options: &'static [(&'static str, &'static str, OptionKind, &'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] = &[PyOptions {
- name: "ListOptions",
- options: &[
- ("limit", OptionKind::OptionUsize),
- ("start_after", OptionKind::OptionString),
- ("recursive", OptionKind::Bool),
- ("versions", OptionKind::Bool),
- ("deleted", OptionKind::Bool),
- ],
-}];
+const GENERATED_OPTIONS: &[PyOptions] = &[
+ PyOptions {
+ name: "ListOptions",
+ options: &[
+ ("limit", "limit", OptionKind::OptionUsize, "Option<usize>"),
+ (
+ "start_after",
+ "start_after",
+ OptionKind::OptionString,
+ "Option<String>",
+ ),
+ ("recursive", "recursive", OptionKind::Bool, "Option<bool>"),
+ ("versions", "versions", OptionKind::Bool, "Option<bool>"),
+ ("deleted", "deleted", OptionKind::Bool, "Option<bool>"),
+ ],
+ },
+ PyOptions {
+ name: "StatOptions",
+ options: &[
+ (
+ "version",
+ "version",
+ OptionKind::OptionString,
+ "Option<String>",
+ ),
+ (
+ "if_match",
+ "if_match",
+ OptionKind::OptionString,
+ "Option<String>",
+ ),
+ (
+ "if_none_match",
+ "if_none_match",
+ OptionKind::OptionString,
+ "Option<String>",
+ ),
+ (
+ "if_modified_since",
+ "if_modified_since",
+ OptionKind::OptionTimestamp,
+ "Option<jiff::Timestamp>",
+ ),
+ (
+ "if_unmodified_since",
+ "if_unmodified_since",
+ OptionKind::OptionTimestamp,
+ "Option<jiff::Timestamp>",
+ ),
+ (
+ "content_type",
+ "override_content_type",
+ OptionKind::OptionString,
+ "Option<String>",
+ ),
+ (
+ "cache_control",
+ "override_cache_control",
+ OptionKind::OptionString,
+ "Option<String>",
+ ),
+ (
+ "content_disposition",
+ "override_content_disposition",
+ OptionKind::OptionString,
+ "Option<String>",
+ ),
+ ("checksum", "checksum", OptionKind::Bool, "bool"),
+ ],
+ },
+];
/// The class order of `options.py`, which hand-written and generated classes
/// share.
@@ -701,11 +768,18 @@ struct PyClass {
#[derive(Debug, Serialize)]
struct PyField {
+ /// The keyword argument and the Rust field.
name: &'static str,
+ /// The core field it sets.
+ core: &'static str,
kind: OptionKind,
/// The core doc comment, one entry per line.
doc: Vec<String>,
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,
}
#[derive(Debug, Serialize)]
@@ -714,13 +788,28 @@ struct ConvertField {
expr: String,
}
-/// The Rust field type of a keyword argument and its `options.py` type, for
-/// the core kinds that generated classes expose so far.
-fn option_types(kind: OptionKind) -> Option<(&'static str,
options::OptionType)> {
- Some(match kind {
- OptionKind::OptionString => ("Option<String>",
options::OptionType::Str),
- OptionKind::OptionUsize => ("Option<usize>", options::OptionType::Int),
- OptionKind::Bool => ("Option<bool>", options::OptionType::Bool),
+/// How a keyword argument moves from Python to core, for each core kind and
+/// Rust field type that generated classes use: the `options.py` type, the
+/// suffix of the `extract_optional` call, and the suffix of `opts.<name>` in
+/// the conversion to core.
+fn lowering(
+ kind: OptionKind,
+ rust_type: &str,
+) -> Option<(options::OptionType, &'static str, &'static str)> {
+ Some(match (kind, rust_type) {
+ (OptionKind::OptionString, "Option<String>") =>
(options::OptionType::Str, "", ""),
+ (OptionKind::OptionUsize, "Option<usize>") =>
(options::OptionType::Int, "", ""),
+ (OptionKind::OptionTimestamp, "Option<jiff::Timestamp>") => (
+ options::OptionType::DateTime,
+ "",
+ ".map(crate::utils::timestamp_from_jiff)",
+ ),
+ // A flag whose keyword argument defaults to `None`, such as
+ // `list(recursive=None)`.
+ (OptionKind::Bool, "Option<bool>") => (options::OptionType::Bool, "",
".unwrap_or(false)"),
+ // A flag whose keyword argument defaults to `False`, such as
+ // `stat(checksum=False)`.
+ (OptionKind::Bool, "bool") => (options::OptionType::Bool,
".unwrap_or_default()", ""),
_ => return None,
})
}
@@ -785,32 +874,44 @@ impl PyNames {
/// - Rustdoc links become plain code spans, because Python documentation
/// cannot resolve Rust paths:
``[`Capability::list_with_limit`](crate::Capability::list_with_limit)``
/// and ``[`crate::layers::SimulateLayer`]`` keep only their code span.
-/// - Code spans that name a core capability or error kind use the Python
-/// check or exception instead (see [`py_code_span`]); other code spans stay
-/// as written.
+/// A link with plain text to a Rust path, such as
+/// ``[checksum specification][crate::docs::specs::checksum]``, keeps only
+/// its text. Links to URLs stay.
+/// - Code spans that name a core capability, error kind, or renamed field
+/// use the Python check, exception, or keyword argument instead (see
+/// [`py_code_span`]); other code spans stay as written.
+/// - Core returns an error kind where Python raises the exception, so a
+/// `returns` right before an exception reads `raises`.
/// - A sentence that names a Rust layer (a `crate::layers::` code span) is
/// dropped, because Python callers cannot install Rust layers or choose
/// Cargo features. The capability that the same doc names, such as
/// `op.capability().list_with_recursive`, is the check Python callers have.
/// The rest of that paragraph is joined into one line.
///
+/// `renames` pairs each core field of the class with the keyword argument
+/// that sets it, where the two names differ.
+///
/// The text is not escaped here; the renderers escape it for their output.
-fn py_doc(core_doc: &[String], item: &str, names: &PyNames) ->
Result<Vec<String>> {
+fn py_doc(
+ core_doc: &[String],
+ item: &str,
+ names: &PyNames,
+ renames: &[(&str, &str)],
+) -> Result<Vec<String>> {
if core_doc.iter().all(|line| line.is_empty()) {
bail!("core {item} has no doc comment");
}
let lines: Vec<String> = core_doc
.iter()
- .map(|line| rewrite_code_spans(line, |code| py_code_span(code, names)))
+ .map(|line| rewrite_code_spans(line, |code| py_code_span(code, names,
renames)))
.collect();
let mut out = Vec::with_capacity(lines.len());
for paragraph in lines.split(|line| line.is_empty()) {
- let paragraph: Vec<String> = if paragraph
- .iter()
- .any(|line| line.contains("`crate::layers::"))
- {
- let text = paragraph.join(" ");
+ // A `returns` may end the line before the exception.
+ let text = raises(¶graph.join("\n"));
+ let paragraph: Vec<String> = if text.contains("`crate::layers::") {
+ let text = text.replace('\n', " ");
let kept: Vec<&str> = sentences(&text)
.into_iter()
.filter(|sentence| !sentence.contains("`crate::layers::"))
@@ -821,7 +922,7 @@ fn py_doc(core_doc: &[String], item: &str, names: &PyNames)
-> Result<Vec<String
vec![kept.join(" ")]
}
} else {
- paragraph.to_vec()
+ text.lines().map(String::from).collect()
};
if paragraph.is_empty() {
continue;
@@ -853,8 +954,43 @@ fn sentences(text: &str) -> Vec<&str> {
sentences
}
-/// The Python form of a code span that names a core capability or error
-/// kind, or `None` to keep the code span as written.
+/// Write `raises` for a `returns` (and `raise` for a `return`) that comes
+/// right before an `opendal.exceptions` code span, across spaces or a line
+/// break: core returns an error, while Python raises the exception.
+fn raises(text: &str) -> String {
+ let mut out = String::with_capacity(text.len());
+ let mut rest = text;
+ while let Some(at) = rest.find("`opendal.exceptions.") {
+ let head = &rest[..at];
+ let word_end = head.trim_end().len();
+ let word = head[..word_end]
+ .rsplit(|c: char| !c.is_ascii_alphabetic())
+ .next()
+ .unwrap_or_default();
+ let verb = match word {
+ "returns" => Some("raises"),
+ "Returns" => Some("Raises"),
+ "return" => Some("raise"),
+ "Return" => Some("Raise"),
+ _ => None,
+ };
+ match verb {
+ Some(verb) if word_end < at => {
+ out.push_str(&head[..word_end - word.len()]);
+ out.push_str(verb);
+ out.push_str(&head[word_end..]);
+ }
+ _ => out.push_str(head),
+ }
+ out.push('`');
+ rest = &rest[at + 1..];
+ }
+ out.push_str(rest);
+ out
+}
+
+/// The Python form of a code span that names a core capability, error kind,
+/// or renamed field, or `None` to keep the code span as written.
///
/// - `Capability::list_with_start_after` becomes
/// `op.capability().list_with_start_after`: the `Capability` that
@@ -862,10 +998,13 @@ fn sentences(text: &str) -> Vec<&str> {
/// every core capability, so callers can check it before setting an option.
/// - `ErrorKind::Unsupported` becomes `opendal.exceptions.Unsupported`, the
/// exception that `bindings/python/src/errors.rs` raises for that kind.
-///
-/// Keyword arguments keep their core names, so a code span that names an
-/// options field, like `start_after`, needs no rewrite.
-fn py_code_span(code: &str, names: &PyNames) -> Option<String> {
+/// - A core field listed in `renames`, like `override_content_type`, becomes
+/// the keyword argument that sets it, like `content_type`. Other keyword
+/// arguments keep their core names, like `start_after`.
+fn py_code_span(code: &str, names: &PyNames, renames: &[(&str, &str)]) ->
Option<String> {
+ if let Some(&(_, python)) = renames.iter().find(|&&(core, _)| core ==
code) {
+ return Some(python.to_string());
+ }
let path = code.strip_prefix("crate::").unwrap_or(code);
if let Some(name) = path.strip_prefix("Capability::") {
return names
@@ -896,31 +1035,48 @@ fn py_class(spec: &PyOptions, parsed: &[OptionsStruct],
names: &PyNames) -> Resu
}
}
+ let renames: Vec<(&str, &str)> = spec
+ .options
+ .iter()
+ .filter(|&&(name, core, ..)| name != core)
+ .map(|&(name, core, ..)| (core, name))
+ .collect();
let mut fields = Vec::with_capacity(spec.options.len());
- for &(name, kind) in spec.options {
+ for &(name, core_name, kind, rust_type) in spec.options {
if fields.iter().any(|field: &PyField| field.name == name) {
bail!("Python {class} lists `{name}` twice");
}
- let Some(field) = core.fields.iter().find(|field| field.name == name)
else {
- bail!("core {class} has no field `{name}` for Python
{class}.{name}");
+ if fields.iter().any(|field: &PyField| field.core == core_name) {
+ bail!("Python {class} sets core `{core_name}` twice");
+ }
+ let Some(field) = core.fields.iter().find(|field| field.name ==
core_name) else {
+ bail!("core {class} has no field `{core_name}` for Python
{class}.{name}");
};
if field.kind != kind {
bail!(
- "core {class}::{name} has kind {:?}; Python {class}.{name}
requires {kind:?}",
+ "core {class}::{core_name} has kind {:?}; Python
{class}.{name} requires {kind:?}",
field.kind
);
}
- let Some((rust_type, _)) = option_types(kind) else {
+ let Some((_, extract, convert)) = lowering(kind, rust_type) else {
bail!(
- "Python {class}.{name} is a core {kind:?}; \
+ "Python {class}.{name} is a core {kind:?} with Rust type
{rust_type}; \
teach dev/src/generate/python.rs about it"
);
};
fields.push(PyField {
name,
+ core: core_name,
kind,
- doc: py_doc(&field.doc, &format!("{class}::{name}"), names)?,
+ doc: py_doc(
+ &field.doc,
+ &format!("{class}::{core_name}"),
+ names,
+ &renames,
+ )?,
rust_type,
+ extract,
+ convert,
});
}
@@ -928,14 +1084,12 @@ fn py_class(spec: &PyOptions, parsed: &[OptionsStruct],
names: &PyNames) -> Resu
.fields
.iter()
.map(|field| {
- let name = &field.name;
- let expr = match fields.iter().find(|f| f.name == name) {
+ let expr = match fields.iter().find(|f| f.core == field.name) {
None => default_expr(field.kind).to_string(),
- Some(f) if f.kind == OptionKind::Bool =>
format!("opts.{name}.unwrap_or(false)"),
- Some(_) => format!("opts.{name}"),
+ Some(f) => format!("opts.{}{}", f.name, f.convert),
};
ConvertField {
- name: name.clone(),
+ name: field.name.clone(),
expr,
}
})
@@ -943,7 +1097,7 @@ fn py_class(spec: &PyOptions, parsed: &[OptionsStruct],
names: &PyNames) -> Resu
Ok(PyClass {
name: class,
- doc: py_doc(&core.doc, class, names)?,
+ doc: py_doc(&core.doc, class, names, &renames)?,
fields,
conversion,
})
@@ -1017,9 +1171,9 @@ fn render_options_py(workspace_dir: &Path, generated:
&[PyClass]) -> Result<Stri
.iter()
.map(|field| options::OptionField {
name: field.name.to_string(),
- ty: option_types(field.kind)
+ ty: lowering(field.kind, field.rust_type)
.expect("generated fields have a Python type")
- .1,
+ .0,
doc: field.doc.join("\n"),
})
.collect(),
@@ -1196,12 +1350,24 @@ mod tests {
PyNames::parse(&crate::workspace_dir()).expect("Python names must
parse")
}
- fn list_class(parsed: &[OptionsStruct]) -> PyClass {
- let mut classes = generated_classes(parsed, &py_names()).unwrap();
- assert_eq!(classes.len(), 1);
- classes.remove(0)
+ fn generated_class(parsed: &[OptionsStruct], name: &str) -> PyClass {
+ let classes = generated_classes(parsed, &py_names()).unwrap();
+ let names: Vec<&str> = classes.iter().map(|class|
class.name).collect();
+ assert_eq!(names, ["ListOptions", "StatOptions"]);
+ classes
+ .into_iter()
+ .find(|class| class.name == name)
+ .unwrap()
}
+ /// The `StatOptions` keyword arguments whose core fields have other
+ /// names, as `(core, Python)`.
+ const STAT_RENAMES: [(&str, &str); 3] = [
+ ("override_content_type", "content_type"),
+ ("override_cache_control", "cache_control"),
+ ("override_content_disposition", "content_disposition"),
+ ];
+
/// 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
@@ -1317,8 +1483,85 @@ print(json.dumps(docs))
}
}
+ /// The `StatOptions` surface on main (809b76472), copied from
+ /// `bindings/python/src/options.rs`, and the Python checks and exceptions
+ /// its docs name, copied from the capability and error kinds of each
+ /// field in `core/core/src/types/options.rs`. The doc wording itself is
+ /// core's, so a core reword passes.
+ fn assert_stat_surface(class: &PyClass) {
+ let fields: Vec<String> = class
+ .fields
+ .iter()
+ .map(|f| format!("{}: {}", f.name, f.rust_type))
+ .collect();
+ assert_eq!(
+ fields,
+ [
+ "version: Option<String>",
+ "if_match: Option<String>",
+ "if_none_match: Option<String>",
+ "if_modified_since: Option<jiff::Timestamp>",
+ "if_unmodified_since: Option<jiff::Timestamp>",
+ "content_type: Option<String>",
+ "cache_control: Option<String>",
+ "content_disposition: Option<String>",
+ "checksum: bool",
+ ]
+ );
+
+ assert_eq!(
+ spans(&class.doc, "opendal.exceptions."),
+ ["NotFound", "ConditionNotMatch", "Unsupported"],
+ "{:?}",
+ 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 NotFound Unsupported";
+ assert_eq!(
+ references,
+ [
+ "version: stat_with_version / NotFound".to_string(),
+ format!("if_match: stat_with_if_match / {condition}"),
+ format!("if_none_match: stat_with_if_none_match /
{condition}"),
+ format!("if_modified_since: stat_with_if_modified_since /
{condition}"),
+ format!("if_unmodified_since: stat_with_if_unmodified_since /
{condition}"),
+ "content_type: / ".to_string(),
+ "cache_control: / ".to_string(),
+ "content_disposition: / ".to_string(),
+ "checksum: / ".to_string(),
+ ]
+ );
+
+ // No Rust-only names reach Python callers, and Python raises the
+ // exceptions that core returns.
+ for doc in
std::iter::once(&class.doc).chain(class.fields.iter().map(|f| &f.doc)) {
+ let text = doc.join(" ");
+ for rust in [
+ "crate::",
+ "Capability::",
+ "ErrorKind::",
+ "returns `opendal.exceptions.",
+ "`override_",
+ ] {
+ assert!(!text.contains(rust), "{rust} in {text}");
+ }
+ }
+ }
+
/// The keyword-only parameters of every `#[pyo3(signature)]` method in
- /// `bindings/python/src/operator.rs`, keyed by type and method.
+ /// `bindings/python/src/operator.rs`, keyed by type and method, each as
+ /// `name=default`.
fn operator_kwargs() -> BTreeMap<(String, String), Vec<String>> {
let path =
crate::workspace_dir().join("bindings/python/src/operator.rs");
let file =
syn::parse_file(&fs::read_to_string(path).unwrap()).unwrap();
@@ -1349,7 +1592,7 @@ print(json.dumps(docs))
continue;
}
// Split `(path, *, limit=None, ...)` at its top-level
- // commas and keep the names after the bare `*`.
+ // commas and keep the parameters after the bare `*`.
let mut split: Vec<Vec<TokenTree>> = vec![Vec::new()];
for token in params.stream() {
match token {
@@ -1362,7 +1605,14 @@ print(json.dumps(docs))
for param in split {
match param.as_slice() {
[TokenTree::Punct(p)] if p.as_char() == '*' =>
keyword_only = true,
- [TokenTree::Ident(name), ..] if keyword_only => {
+ [TokenTree::Ident(name), TokenTree::Punct(eq),
default @ ..]
+ if keyword_only && eq.as_char() == '=' =>
+ {
+ let default: proc_macro2::TokenStream =
+ default.iter().cloned().collect();
+ kwargs.push(format!("{name}={default}"))
+ }
+ [TokenTree::Ident(name)] if keyword_only => {
kwargs.push(name.to_string())
}
_ => {}
@@ -1380,16 +1630,22 @@ print(json.dumps(docs))
#[test]
fn test_list_options_match_main() {
let parsed = core_options();
- let class = list_class(&parsed);
+ let class = generated_class(&parsed, "ListOptions");
assert_list_surface(&class);
// Each docstring is its own core doc comment.
let core = parsed.iter().find(|o| o.name == "ListOptions").unwrap();
let names = py_names();
- assert_eq!(class.doc, py_doc(&core.doc, "ListOptions",
&names).unwrap());
+ assert_eq!(
+ class.doc,
+ py_doc(&core.doc, "ListOptions", &names, &[]).unwrap()
+ );
for field in &class.fields {
let core = core.fields.iter().find(|f| f.name ==
field.name).unwrap();
- assert_eq!(field.doc, py_doc(&core.doc, field.name,
&names).unwrap());
+ assert_eq!(
+ field.doc,
+ py_doc(&core.doc, field.name, &names, &[]).unwrap()
+ );
}
// An explicit `limit`, including `0`, passes through, and an omitted
@@ -1471,8 +1727,130 @@ print(json.dumps(docs))
assert!(body.starts_with(" /// "), "{body}");
}
- /// The `options.py` TypedDicts on main (4ae8e6122): the class order and
- /// the `ListKwargs` keys and types, with docstrings taken from core.
+ /// The `StatOptions` API on main (809b76472), copied from
+ /// `bindings/python/src/options.rs`, with docstrings taken from core.
+ #[test]
+ fn test_stat_options_match_main() {
+ let parsed = core_options();
+ let class = generated_class(&parsed, "StatOptions");
+ assert_stat_surface(&class);
+
+ // Each docstring is the core doc comment of the field it sets.
+ let core = parsed.iter().find(|o| o.name == "StatOptions").unwrap();
+ let names = py_names();
+ assert_eq!(
+ class.doc,
+ py_doc(&core.doc, "StatOptions", &names, &STAT_RENAMES).unwrap()
+ );
+ for field in &class.fields {
+ let name = STAT_RENAMES
+ .iter()
+ .find(|&&(_, python)| python == field.name)
+ .map_or(field.name, |&(core, _)| core);
+ let core = core.fields.iter().find(|f| f.name == name).unwrap();
+ assert_eq!(
+ field.doc,
+ py_doc(&core.doc, name, &names, &STAT_RENAMES).unwrap()
+ );
+ }
+
+ // Each keyword sets the core field main's `From` impl set it to, and
+ // every other core field, such as `if_version_match`, keeps the
+ // default that main's `..Default::default()` gave it.
+ let (set, defaulted): (Vec<_>, Vec<_>) = class
+ .conversion
+ .iter()
+ .map(|f| format!("{}: {}", f.name, f.expr))
+ .partition(|f| f.contains("opts."));
+ assert_eq!(
+ set,
+ [
+ "version: opts.version",
+ "if_match: opts.if_match",
+ "if_none_match: opts.if_none_match",
+ "if_modified_since:
opts.if_modified_since.map(crate::utils::timestamp_from_jiff)",
+ "if_unmodified_since:
opts.if_unmodified_since.map(crate::utils::timestamp_from_jiff)",
+ "override_content_type: opts.content_type",
+ "override_cache_control: opts.cache_control",
+ "override_content_disposition: opts.content_disposition",
+ "checksum: opts.checksum",
+ ]
+ );
+ for field in ["if_version_match: None", "if_version_not_match: 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, an omitted `checksum`
+ // is `false`, and any other key is ignored.
+ let rs = render_options_rs(&generated_classes(&parsed,
&names).unwrap()).unwrap();
+ let extract = rs
+ .split_once("impl<'a, 'py> FromPyObject<'a, 'py> for StatOptions
{")
+ .unwrap()
+ .1
+ .split("\n}\n")
+ .next()
+ .unwrap();
+ let reads: Vec<&str> = extract
+ .lines()
+ .map(str::trim)
+ .filter(|line| line.contains("extract_optional"))
+ .collect();
+ assert_eq!(
+ reads,
+ [
+ "version: extract_optional(&dict, \"version\")?,",
+ "if_match: extract_optional(&dict, \"if_match\")?,",
+ "if_none_match: extract_optional(&dict, \"if_none_match\")?,",
+ "if_modified_since: extract_optional(&dict,
\"if_modified_since\")?,",
+ "if_unmodified_since: extract_optional(&dict,
\"if_unmodified_since\")?,",
+ "content_type: extract_optional(&dict, \"content_type\")?,",
+ "cache_control: extract_optional(&dict, \"cache_control\")?,",
+ "content_disposition: extract_optional(&dict,
\"content_disposition\")?,",
+ "checksum: extract_optional(&dict,
\"checksum\")?.unwrap_or_default(),",
+ ]
+ );
+ assert!(!extract.contains("reject_unknown_kwargs"));
+
+ // The pyclass and its fields, in order, each after its docs.
+ let body = rs
+ .split_once("#[pyclass(module = \"opendal\")]\n#[derive(Default,
Debug)]\npub struct StatOptions {\n")
+ .unwrap()
+ .1
+ .split_once("\n}\n")
+ .unwrap()
+ .0;
+ let members: Vec<&str> = body
+ .lines()
+ .map(str::trim)
+ .filter(|line| !line.starts_with("///"))
+ .collect();
+ assert_eq!(
+ members,
+ [
+ "pub version: Option<String>,",
+ "pub if_match: Option<String>,",
+ "pub if_none_match: Option<String>,",
+ "pub if_modified_since: Option<jiff::Timestamp>,",
+ "pub if_unmodified_since: Option<jiff::Timestamp>,",
+ "pub content_type: Option<String>,",
+ "pub cache_control: Option<String>,",
+ "pub content_disposition: Option<String>,",
+ "pub checksum: bool,",
+ ]
+ );
+ assert!(body.starts_with(" /// "), "{body}");
+ }
+
+ /// The `options.py` TypedDicts on main (4ae8e6122 for `ListKwargs`,
+ /// 809b76472 for `StatKwargs`): the class order and the keys and types
+ /// of the generated classes, with docstrings taken from core.
#[test]
fn test_options_py_matches_main() {
let generated = generated_classes(&core_options(),
&py_names()).unwrap();
@@ -1496,25 +1874,27 @@ print(json.dumps(docs))
]
);
- let list = py
- .split_once("\n\nclass ListKwargs(TypedDict, total=False):\n")
- .unwrap()
- .1
- .split_once("\n\n\nclass StatKwargs(")
- .unwrap()
- .0;
- // A key is an `identifier: type` line; docstring lines are not.
- let keys: Vec<&str> = list
- .lines()
- .filter_map(|line| line.strip_prefix(" "))
- .filter(|line| {
- line.split_once(": ").is_some_and(|(key, _)| {
- !key.is_empty() && key.chars().all(|c|
c.is_ascii_lowercase() || c == '_')
+ // The `identifier: type` lines of a class body; docstring lines are
+ // not keys.
+ let keys = |class: &str, next: &str| -> Vec<String> {
+ py.split_once(&format!("\n\nclass {class}(TypedDict,
total=False):\n"))
+ .unwrap()
+ .1
+ .split_once(&format!("\n\n\nclass {next}("))
+ .unwrap()
+ .0
+ .lines()
+ .filter_map(|line| line.strip_prefix(" "))
+ .filter(|line| {
+ line.split_once(": ").is_some_and(|(key, _)| {
+ !key.is_empty() && key.chars().all(|c|
c.is_ascii_lowercase() || c == '_')
+ })
})
- })
- .collect();
+ .map(String::from)
+ .collect()
+ };
assert_eq!(
- keys,
+ keys("ListKwargs", "StatKwargs"),
[
"limit: int",
"start_after: str",
@@ -1523,73 +1903,117 @@ print(json.dumps(docs))
"deleted: bool",
]
);
+ assert_eq!(
+ keys("StatKwargs", "CopyKwargs"),
+ [
+ "version: str",
+ "if_match: str",
+ "if_none_match: str",
+ "if_modified_since: datetime",
+ "if_unmodified_since: datetime",
+ "content_type: str",
+ "cache_control: str",
+ "content_disposition: str",
+ "checksum: bool",
+ ]
+ );
// The docstrings parse back, as Python reads them, to the docs.
let docs = python_docstrings(&py);
- let class = &generated[0];
- assert_eq!(docs["ListKwargs"], class.doc.join("\n"));
- for field in &class.fields {
- assert_eq!(
- docs[&format!("ListKwargs.{}", field.name)],
- field.doc.join("\n")
- );
+ for class in &generated {
+ let kwargs = class.name.replace("Options", "Kwargs");
+ assert_eq!(docs[&kwargs], class.doc.join("\n"));
+ for field in &class.fields {
+ assert_eq!(
+ docs[&format!("{kwargs}.{}", field.name)],
+ field.doc.join("\n")
+ );
+ }
}
}
- /// The `list` and `scan` keyword arguments on main (4ae8e6122), copied
- /// from `python/opendal/operator.pyi`.
+ /// The `list` and `scan` keyword arguments and defaults on main
+ /// (4ae8e6122), copied from `python/opendal/operator.pyi`.
#[test]
fn test_list_signatures_match_main() {
let methods = operator_kwargs();
+ let list = "limit=None start_after=None recursive=None versions=None
deleted=None";
+ let scan = "limit=None start_after=None versions=None deleted=None";
for (ty, method, kwargs) in [
- (
- "Operator",
- "list",
- "limit start_after recursive versions deleted",
- ),
- ("Operator", "scan", "limit start_after versions deleted"),
- (
- "AsyncOperator",
- "list",
- "limit start_after recursive versions deleted",
- ),
- (
- "AsyncOperator",
- "scan",
- "limit start_after versions deleted",
- ),
+ ("Operator", "list", list),
+ ("Operator", "scan", scan),
+ ("AsyncOperator", "list", list),
+ ("AsyncOperator", "scan", scan),
] {
let key = (ty.to_string(), method.to_string());
assert_eq!(methods[&key].join(" "), kwargs, "{ty}.{method}");
}
}
+ /// The `stat` and `presign_stat` keyword arguments and defaults on main
+ /// (809b76472), copied from `python/opendal/operator.pyi`.
#[test]
- fn test_list_signatures_match_options_table() {
- let class = list_class(&core_options());
+ fn test_stat_signatures_match_main() {
let methods = operator_kwargs();
- // `scan` is `list` with `recursive=True`.
- for (ty, method, omitted) in [
- ("Operator", "list", None),
- ("Operator", "scan", Some("recursive")),
- ("AsyncOperator", "list", None),
- ("AsyncOperator", "scan", Some("recursive")),
+ let conditions = "version=None if_match=None if_none_match=None \
+ if_modified_since=None if_unmodified_since=None \
+ content_type=None cache_control=None
content_disposition=None";
+ let stat = format!("{conditions} checksum=false");
+ for (ty, method, kwargs) in [
+ ("Operator", "stat", stat.as_str()),
+ ("AsyncOperator", "stat", stat.as_str()),
+ ("AsyncOperator", "presign_stat", conditions),
] {
- let mut expected: Vec<&str> = class
+ let key = (ty.to_string(), method.to_string());
+ assert_eq!(methods[&key].join(" "), kwargs, "{ty}.{method}");
+ }
+ assert!(!methods.contains_key(&("Operator".to_string(),
"presign_stat".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`.
+ #[test]
+ fn test_signatures_match_options_table() {
+ let parsed = core_options();
+ let methods = operator_kwargs();
+ // `scan` is `list` with `recursive=True`, and `presign_stat` cannot
+ // request a checksum.
+ for (ty, method, class, omitted) in [
+ ("Operator", "list", "ListOptions", None),
+ ("Operator", "scan", "ListOptions", Some("recursive")),
+ ("AsyncOperator", "list", "ListOptions", None),
+ ("AsyncOperator", "scan", "ListOptions", Some("recursive")),
+ ("Operator", "stat", "StatOptions", None),
+ ("AsyncOperator", "stat", "StatOptions", None),
+ (
+ "AsyncOperator",
+ "presign_stat",
+ "StatOptions",
+ Some("checksum"),
+ ),
+ ] {
+ let class = generated_class(&parsed, class);
+ let mut expected: Vec<String> = class
.fields
.iter()
- .map(|f| f.name)
- .filter(|name| Some(*name) != omitted)
- .collect();
- let mut actual: Vec<&str> = methods[&(ty.to_string(),
method.to_string())]
- .iter()
- .map(String::as_str)
+ .filter(|f| Some(f.name) != omitted)
+ .map(|f| {
+ let default = if f.rust_type == "bool" {
+ "false"
+ } else {
+ "None"
+ };
+ format!("{}={default}", f.name)
+ })
.collect();
+ let mut actual = methods[&(ty.to_string(),
method.to_string())].clone();
expected.sort();
actual.sort();
assert_eq!(
actual, expected,
- "{ty}.{method} must take the ListOptions keyword arguments"
+ "{ty}.{method} must take the {} keyword arguments",
+ class.name
);
}
}
@@ -1605,19 +2029,20 @@ print(json.dumps(docs))
.unwrap();
let mut mutated = parsed.clone();
- let list = mutated
+ for options in mutated
.iter_mut()
- .find(|o| o.name == "ListOptions")
- .unwrap();
- for (name, kind) in [
- ("fake_option", OptionKind::OptionString),
- ("fake_flag", OptionKind::Bool),
- ] {
- list.fields.push(OptionField {
- name: name.to_string(),
- kind,
- doc: Vec::new(),
- });
+ .filter(|o| ["ListOptions",
"StatOptions"].contains(&o.name.as_str()))
+ {
+ for (name, kind) in [
+ ("fake_option", OptionKind::OptionString),
+ ("fake_flag", OptionKind::Bool),
+ ] {
+ options.fields.push(OptionField {
+ name: name.to_string(),
+ kind,
+ doc: Vec::new(),
+ });
+ }
}
let classes = generated_classes(&mutated, &py_names()).unwrap();
let rs = render_options_rs(&classes).unwrap();
@@ -1629,7 +2054,9 @@ print(json.dumps(docs))
added,
[
" fake_option: None,",
- " fake_flag: false,"
+ " fake_flag: false,",
+ " fake_option: None,",
+ " fake_flag: false,",
]
);
let kept: Vec<&str> = rs.lines().filter(|l|
!l.contains("fake_")).collect();
@@ -1637,19 +2064,21 @@ print(json.dumps(docs))
}
#[test]
- fn test_list_options_reject_core_drift() {
+ fn test_options_reject_core_drift() {
fn position(options: &OptionsStruct, name: &str) -> usize {
options.fields.iter().position(|f| f.name == name).unwrap()
}
type Mutation = fn(&mut OptionsStruct);
- let cases: [(Mutation, &str); 7] = [
+ let cases: [(&str, Mutation, &str); 13] = [
(
+ "ListOptions",
|list| {
list.fields.remove(position(list, "limit"));
},
"core ListOptions has no field `limit` for Python
ListOptions.limit",
),
(
+ "ListOptions",
|list| {
let i = position(list, "limit");
list.fields[i].kind = OptionKind::OptionU64;
@@ -1660,6 +2089,7 @@ print(json.dumps(docs))
// A change to another kind that Python supports must fail too,
// instead of silently turning `start_after` into a bool.
(
+ "ListOptions",
|list| {
let i = position(list, "start_after");
list.fields[i].kind = OptionKind::Bool;
@@ -1668,6 +2098,7 @@ print(json.dumps(docs))
Python ListOptions.start_after requires OptionString",
),
(
+ "ListOptions",
|list| {
let glob = list.fields[position(list, "glob")].clone();
list.fields.push(glob);
@@ -1675,6 +2106,7 @@ print(json.dumps(docs))
"core ListOptions contains duplicate field `glob`",
),
(
+ "ListOptions",
|list| {
let i = position(list, "limit");
list.fields[i].doc.clear();
@@ -1682,6 +2114,7 @@ print(json.dumps(docs))
"core ListOptions::limit has no doc comment",
),
(
+ "ListOptions",
|list| {
let i = position(list, "limit");
list.fields[i].doc =
@@ -1690,20 +2123,64 @@ print(json.dumps(docs))
"core ListOptions::limit has no doc comment that applies to
Python",
),
(
+ "ListOptions",
|list| list.has_unmirrored_fields = true,
"core ListOptions has fields the core options parser skips;
Python cannot set them",
),
+ (
+ "StatOptions",
+ |stat| {
+ stat.fields.remove(position(stat,
"override_content_type"));
+ },
+ "core StatOptions has no field `override_content_type` \
+ for Python StatOptions.content_type",
+ ),
+ (
+ "StatOptions",
+ |stat| {
+ let i = position(stat, "if_modified_since");
+ stat.fields[i].kind = OptionKind::OptionString;
+ },
+ "core StatOptions::if_modified_since has kind OptionString; \
+ Python StatOptions.if_modified_since requires
OptionTimestamp",
+ ),
+ (
+ "StatOptions",
+ |stat| {
+ let i = position(stat, "override_cache_control");
+ stat.fields[i].kind = OptionKind::OptionTimestamp;
+ },
+ "core StatOptions::override_cache_control has kind
OptionTimestamp; \
+ Python StatOptions.cache_control requires OptionString",
+ ),
+ (
+ "StatOptions",
+ |stat| {
+ let i = position(stat, "checksum");
+ stat.fields[i].kind = OptionKind::OptionString;
+ },
+ "core StatOptions::checksum has kind OptionString; \
+ Python StatOptions.checksum requires Bool",
+ ),
+ (
+ "StatOptions",
+ |stat| {
+ let i = position(stat, "override_content_disposition");
+ stat.fields[i].doc.clear();
+ },
+ "core StatOptions::override_content_disposition has no doc
comment",
+ ),
+ (
+ "StatOptions",
+ |stat| stat.has_unmirrored_fields = true,
+ "core StatOptions has fields the core options parser skips;
Python cannot set them",
+ ),
];
let parsed = core_options();
- for (mutate, error) in cases {
+ for (class, mutate, error) in cases {
let mut mutated = parsed.clone();
- mutate(
- mutated
- .iter_mut()
- .find(|o| o.name == "ListOptions")
- .unwrap(),
- );
+ mutate(mutated.iter_mut().find(|o| o.name == class).unwrap());
assert_eq!(
generated_classes(&mutated, &py_names())
.unwrap_err()
@@ -1713,20 +2190,92 @@ print(json.dumps(docs))
}
}
+ /// A table row must name each keyword and core field once, and use a
+ /// pair of core kind and Rust type that the generator can convert.
+ #[test]
+ fn test_options_table_rejects_bad_rows() {
+ let parsed = core_options();
+ type Rows = &'static [(&'static str, &'static str, OptionKind,
&'static str)];
+ let cases: [(Rows, &str); 4] = [
+ (
+ &[("version", "version", OptionKind::OptionString, "String")],
+ "Python StatOptions.version is a core OptionString with Rust
type String; \
+ teach dev/src/generate/python.rs about it",
+ ),
+ (
+ &[("checksum", "checksum", OptionKind::Bool,
"Option<String>")],
+ "Python StatOptions.checksum is a core Bool with Rust type
Option<String>; \
+ teach dev/src/generate/python.rs about it",
+ ),
+ (
+ &[
+ (
+ "content_type",
+ "override_content_type",
+ OptionKind::OptionString,
+ "Option<String>",
+ ),
+ (
+ "mime",
+ "override_content_type",
+ OptionKind::OptionString,
+ "Option<String>",
+ ),
+ ],
+ "Python StatOptions sets core `override_content_type` twice",
+ ),
+ (
+ &[
+ (
+ "version",
+ "version",
+ OptionKind::OptionString,
+ "Option<String>",
+ ),
+ (
+ "version",
+ "if_match",
+ OptionKind::OptionString,
+ "Option<String>",
+ ),
+ ],
+ "Python StatOptions lists `version` twice",
+ ),
+ ];
+ for (options, error) in cases {
+ let spec = PyOptions {
+ name: "StatOptions",
+ options,
+ };
+ assert_eq!(
+ py_class(&spec, &parsed, &py_names())
+ .unwrap_err()
+ .to_string(),
+ error
+ );
+ }
+ }
+
#[test]
fn test_py_doc_strips_rustdoc_links() {
let lines = [
"Use [`crate::Operator::list_with`](crate::Operator::list_with)
and [`Self::recursive`].",
"",
"A [plain](https://opendal.apache.org) link and `code` stay.",
+ "",
+ "See the [checksum specification][crate::docs::specs::checksum],
[the guide](crate::docs::x),",
+ "and [`Self::checksum`][crate::StatOptions::checksum];
[rfc](https://example.com), [x] and `v[0]` stay.",
]
.map(String::from);
assert_eq!(
- py_doc(&lines, "Test", &py_names()).unwrap(),
+ py_doc(&lines, "Test", &py_names(), &[]).unwrap(),
[
"Use `crate::Operator::list_with` and `Self::recursive`.",
"",
"A [plain](https://opendal.apache.org) link and `code` stay.",
+ "",
+ "See the checksum specification, the guide,",
+ "and `Self::checksum`; [rfc](https://example.com), [x] and
`v[0]` stay.",
]
);
}
@@ -1742,7 +2291,7 @@ print(json.dumps(docs))
]
.map(String::from);
assert_eq!(
- py_doc(&lines, "Test", &py_names()).unwrap(),
+ py_doc(&lines, "Test", &py_names(), &[]).unwrap(),
[
"- Pagination: `limit`, `start_after`.",
"Requires `op.capability().list_with_limit`.",
@@ -1751,6 +2300,46 @@ print(json.dumps(docs))
"Unknown `Capability::no_such_flag`, `ErrorKind::NoSuchKind`,
and prose Capability::list stay.",
]
);
+
+ // A core field that a keyword argument of another name sets reads
+ // as that keyword argument.
+ let lines = [
+ "Conflicts with
[`override_content_type`](Self::override_content_type) and
`override_cache_control`,",
+ "not `override_content_disposition`,
`Self::override_content_type`, or override_content_type.",
+ ]
+ .map(String::from);
+ assert_eq!(
+ py_doc(&lines, "Test", &py_names(), &STAT_RENAMES[..2]).unwrap(),
+ [
+ "Conflicts with `content_type` and `cache_control`,",
+ "not `override_content_disposition`,
`Self::override_content_type`, or override_content_type.",
+ ]
+ );
+ }
+
+ /// Core returns an error kind, while Python raises the exception.
+ #[test]
+ fn test_py_doc_raises_exceptions() {
+ let lines = [
+ "A missing file returns [`crate::ErrorKind::NotFound`]; a stale
one returns",
+ "[`crate::ErrorKind::ConditionNotMatch`].",
+ "",
+ "Returns `ErrorKind::Unsupported` and may return
`ErrorKind::NotFound`.",
+ "It returns `Capability::stat_with_version`, fails with
`ErrorKind::Unsupported`,",
+ "returns `NoSuchKind`, and noreturns `ErrorKind::NotFound`.",
+ ]
+ .map(String::from);
+ assert_eq!(
+ py_doc(&lines, "Test", &py_names(), &[]).unwrap(),
+ [
+ "A missing file raises `opendal.exceptions.NotFound`; a stale
one raises",
+ "`opendal.exceptions.ConditionNotMatch`.",
+ "",
+ "Raises `opendal.exceptions.Unsupported` and may raise
`opendal.exceptions.NotFound`.",
+ "It returns `op.capability().stat_with_version`, fails with
`opendal.exceptions.Unsupported`,",
+ "returns `NoSuchKind`, and noreturns
`opendal.exceptions.NotFound`.",
+ ]
+ );
}
/// Python callers cannot install Rust layers, so a sentence that names
@@ -1771,7 +2360,7 @@ print(json.dumps(docs))
]
.map(String::from);
assert_eq!(
- py_doc(&lines, "Test", &py_names()).unwrap(),
+ py_doc(&lines, "Test", &py_names(), &[]).unwrap(),
[
"Whether to list recursively; default `false`.",
"",
@@ -1790,7 +2379,7 @@ print(json.dumps(docs))
fn test_list_options_survive_any_core_doc() {
let mut parsed = core_options();
// The capability each field names, whatever markup core uses for it.
- let capabilities: BTreeMap<&str, String> = list_class(&parsed)
+ let capabilities: BTreeMap<&str, String> = generated_class(&parsed,
"ListOptions")
.fields
.iter()
.map(|f| (f.name, spans(&f.doc, "op.capability().").join(" ")))
@@ -1827,6 +2416,7 @@ print(json.dumps(docs))
let generated = generated_classes(&parsed, &py_names()).unwrap();
let class = &generated[0];
+ assert_eq!(class.name, "ListOptions");
assert_list_surface(class);
assert_eq!(
class.fields[1].doc,
@@ -1880,11 +2470,92 @@ print(json.dumps(docs))
}
}
+ /// Core may reword the `StatOptions` docs and use either markup for
+ /// capabilities and error kinds: the surface checks, which pin no core
+ /// wording, still pass, and Python reads back each docstring.
+ #[test]
+ fn test_stat_options_survive_core_rewording() {
+ let mut parsed = core_options();
+ let base = generated_class(&parsed, "StatOptions");
+ let stat = parsed.iter_mut().find(|o| o.name ==
"StatOptions").unwrap();
+ stat.doc = [
+ r#""Stat" options, with \d."#,
+ "",
+ "A missing file returns",
+ "`ErrorKind::NotFound`, a failed condition returns
[`crate::ErrorKind::ConditionNotMatch`],",
+ "and a missing capability returns
[`ErrorKind::Unsupported`](crate::ErrorKind::Unsupported).",
+ ]
+ .map(String::from)
+ .to_vec();
+ for field in &mut stat.fields {
+ let Some(python) = base.fields.iter().find(|f| f.core ==
field.name) else {
+ continue;
+ };
+ let mut doc = vec![format!(
+ r#"Reworded "{}" doc, see [the spec][crate::docs::specs::x]."#,
+ field.name
+ )];
+ for (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})."),
+ });
+ }
+ for name in spans(&python.doc, "opendal.exceptions.") {
+ doc.push("It returns".to_string());
+ doc.push(format!("[`crate::ErrorKind::{name}`]."));
+ }
+ if field.name == "override_content_type" {
+ doc.push(
+ "Pairs with
[`override_cache_control`](Self::override_cache_control).".into(),
+ );
+ }
+ field.doc = doc;
+ }
+
+ let generated = generated_classes(&parsed, &py_names()).unwrap();
+ let class = generated.iter().find(|c| c.name ==
"StatOptions").unwrap();
+ assert_stat_surface(class);
+
+ let py = render_options_py(&crate::workspace_dir(),
&generated).unwrap();
+ let docs = python_docstrings(&py);
+ assert_eq!(
+ docs["StatKwargs"],
+ "\"Stat\" options, with \\d.\n\
+ \n\
+ A missing file raises\n\
+ `opendal.exceptions.NotFound`, a failed condition raises \
+ `opendal.exceptions.ConditionNotMatch`,\n\
+ and a missing capability raises `opendal.exceptions.Unsupported`."
+ );
+ assert_eq!(
+ docs["StatKwargs.content_type"],
+ "Reworded \"override_content_type\" doc, see the spec.\n\
+ Pairs with `cache_control`."
+ );
+ assert_eq!(
+ docs["StatKwargs.version"],
+ "Reworded \"version\" doc, see the spec.\n\
+ Check `op.capability().stat_with_version`.\n\
+ It raises\n\
+ `opendal.exceptions.NotFound`."
+ );
+ for field in &class.fields {
+ assert_eq!(
+ docs[&format!("StatKwargs.{}", field.name)],
+ field.doc.join("\n")
+ );
+ }
+ }
+
/// Every capability and exception the generated docstrings name exists
/// in the Python API: `python/opendal/capability.pyi` and
/// `python/opendal/exceptions.pyi`.
#[test]
- fn test_list_options_docs_name_python_api() {
+ fn test_options_docs_name_python_api() {
let stub = |name: &str| {
fs::read_to_string(
crate::workspace_dir()
@@ -1908,31 +2579,50 @@ print(json.dumps(docs))
.collect();
assert!(classes.contains("NotFound"));
- let class = list_class(&core_options());
- let docs: Vec<String> = class
- .doc
- .iter()
- .chain(class.fields.iter().flat_map(|f| &f.doc))
- .cloned()
- .collect();
- let checks = spans(&docs, "op.capability().");
- for name in &checks {
- assert!(attributes.contains(name), "{name} is not in
capability.pyi");
- }
- assert_eq!(
- checks,
- [
- "list_with_start_after",
- "list_with_recursive",
- "list_with_versions",
- "list_with_deleted",
- ]
- );
- let raised = spans(&docs, "opendal.exceptions.");
- for name in &raised {
- assert!(classes.contains(name), "{name} is not in exceptions.pyi");
+ let parsed = core_options();
+ for (class, expected_checks, expected_raised) in [
+ (
+ "ListOptions",
+ &[
+ "list_with_start_after",
+ "list_with_recursive",
+ "list_with_versions",
+ "list_with_deleted",
+ ][..],
+ &["Unsupported"][..],
+ ),
+ (
+ "StatOptions",
+ &[
+ "stat_with_version",
+ "stat_with_if_match",
+ "stat_with_if_none_match",
+ "stat_with_if_modified_since",
+ "stat_with_if_unmodified_since",
+ ][..],
+ &["ConditionNotMatch", "NotFound", "Unsupported"][..],
+ ),
+ ] {
+ let class = generated_class(&parsed, class);
+ let docs: Vec<String> = class
+ .doc
+ .iter()
+ .chain(class.fields.iter().flat_map(|f| &f.doc))
+ .cloned()
+ .collect();
+ let checks = spans(&docs, "op.capability().");
+ for name in &checks {
+ assert!(attributes.contains(name), "{name} is not in
capability.pyi");
+ }
+ assert_eq!(checks, expected_checks, "{}", class.name);
+ let mut raised = spans(&docs, "opendal.exceptions.");
+ for name in &raised {
+ assert!(classes.contains(name), "{name} is not in
exceptions.pyi");
+ }
+ raised.sort();
+ raised.dedup();
+ assert_eq!(raised, expected_raised, "{}", class.name);
}
- assert_eq!(raised, ["Unsupported"]);
// Every exception that the generator may name exists.
for class in py_names().exceptions.values() {
diff --git a/dev/src/generate/python/options_rs.j2
b/dev/src/generate/python/options_rs.j2
index afa44e5539..69a3714c12 100644
--- a/dev/src/generate/python/options_rs.j2
+++ b/dev/src/generate/python/options_rs.j2
@@ -48,7 +48,7 @@ impl<'a, 'py> FromPyObject<'a, 'py> for {{ class.name }} {
Ok(Self {
{%- for f in class.fields %}
- {{ f.name }}: extract_optional(&dict, "{{ f.name }}")?,
+ {{ f.name }}: extract_optional(&dict, "{{ f.name }}")?{{ f.extract
}},
{%- endfor %}
})
}