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 7283211520 feat(bindings/python): generate RenameOptions from core
(#9400)
7283211520 is described below
commit 72832115209f13b768f733d1b8bf07a9eed6516d
Author: Chitral Verma <[email protected]>
AuthorDate: Mon Nov 30 01:51:23 2026 +0530
feat(bindings/python): generate RenameOptions from core (#9400)
Generate the Python RenameOptions pyclass and RenameKwargs from core's
RenameOptions. The if_not_exists keyword argument keeps its name, type,
and default, and the conversion to core is unchanged.
The docstrings come from core. Python reads core's "which error the
rename returns is unspecified" as "which exception the rename raises is
unspecified".
RenameOptions was the last hand-written options class, so options.py is
now rendered from the generated classes only. Remove
dev/src/generate/options.rs, which parsed the hand-written classes, and
move its doc_lines helper to dev/src/generate/rustdoc.rs.
Signed-off-by: Chitral Verma <[email protected]>
---
bindings/python/python/opendal/options.py | 22 +-
bindings/python/src/options.rs | 17 -
bindings/python/src/options/generated.rs | 44 +++
dev/src/generate/capability.rs | 2 +-
dev/src/generate/metadata.rs | 2 +-
dev/src/generate/mod.rs | 1 -
dev/src/generate/options.rs | 252 ---------------
dev/src/generate/python.rs | 501 ++++++++++++++++++++++++------
dev/src/generate/rustdoc.rs | 21 ++
9 files changed, 495 insertions(+), 367 deletions(-)
diff --git a/bindings/python/python/opendal/options.py
b/bindings/python/python/opendal/options.py
index 3f5645a06d..4cf057c9df 100644
--- a/bindings/python/python/opendal/options.py
+++ b/bindings/python/python/opendal/options.py
@@ -627,10 +627,28 @@ class CopyKwargs(TypedDict, total=False):
class RenameKwargs(TypedDict, total=False):
- """Options for `rename` operations."""
+ """Options for rename operations.
+
+ The condition checks the destination file, never the source. A missing
+ source fails the rename with `opendal.exceptions.NotFound`; when a
+ condition error applies at the same time, which exception the rename raises
+ is unspecified.
+
+ See the conditional operation specification
+ for the complete cross-operation contract.
+ """
if_not_exists: bool
- """Whether to fail if a file already exists at the target path."""
+ """Rename only when no file exists at the destination path.
+
+ The condition succeeds when the destination path is empty. An
+ existing destination file fails the rename with
+ `opendal.exceptions.ConditionNotMatch`.
+
+ The operation raises `opendal.exceptions.Unsupported` when the
+ service does not advertise
+ `op.capability().rename_with_if_not_exists`.
+ """
class DeleteKwargs(TypedDict, total=False):
diff --git a/bindings/python/src/options.rs b/bindings/python/src/options.rs
index b177c91940..3d12ef5ce3 100644
--- a/bindings/python/src/options.rs
+++ b/bindings/python/src/options.rs
@@ -23,7 +23,6 @@ use pyo3::PyResult;
use pyo3::conversion::FromPyObjectOwned;
use pyo3::exceptions::PyTypeError;
use pyo3::exceptions::PyValueError;
-use pyo3::pyclass;
use pyo3::types::PyAnyMethods;
use pyo3::types::PyDict;
use pyo3::types::PyDictMethods;
@@ -211,22 +210,6 @@ impl From<ReadOptions> for ocore::options::ReaderOptions {
}
}
-/// Options for `rename` operations.
-#[pyclass(module = "opendal")]
-#[derive(Default, Debug)]
-pub struct RenameOptions {
- /// Whether to fail if a file already exists at the target path.
- pub if_not_exists: Option<bool>,
-}
-
-impl From<RenameOptions> for ocore::options::RenameOptions {
- fn from(opts: RenameOptions) -> Self {
- Self {
- if_not_exists: opts.if_not_exists.unwrap_or(false),
- }
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/bindings/python/src/options/generated.rs
b/bindings/python/src/options/generated.rs
index fbc0f344b8..4549d8556d 100644
--- a/bindings/python/src/options/generated.rs
+++ b/bindings/python/src/options/generated.rs
@@ -848,3 +848,47 @@ impl From<CopyOptions> for ocore::options::CopyOptions {
}
}
}
+
+/// Options for rename operations.
+///
+/// The condition checks the destination file, never the source. A missing
+/// source fails the rename with `opendal.exceptions.NotFound`; when a
+/// condition error applies at the same time, which exception the rename raises
+/// is unspecified.
+///
+/// See the conditional operation specification
+/// for the complete cross-operation contract.
+#[pyclass(module = "opendal")]
+#[derive(Default, Debug)]
+pub struct RenameOptions {
+ /// Rename only when no file exists at the destination path.
+ ///
+ /// The condition succeeds when the destination path is empty. An
+ /// existing destination file fails the rename with
+ /// `opendal.exceptions.ConditionNotMatch`.
+ ///
+ /// The operation raises `opendal.exceptions.Unsupported` when the
+ /// service does not advertise
+ /// `op.capability().rename_with_if_not_exists`.
+ pub if_not_exists: Option<bool>,
+}
+
+impl<'a, 'py> FromPyObject<'a, 'py> for RenameOptions {
+ type Error = PyErr;
+
+ fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
+ let dict = downcast_kwargs(obj)?;
+
+ Ok(Self {
+ if_not_exists: extract_optional(&dict, "if_not_exists")?,
+ })
+ }
+}
+
+impl From<RenameOptions> for ocore::options::RenameOptions {
+ fn from(opts: RenameOptions) -> Self {
+ Self {
+ if_not_exists: opts.if_not_exists.unwrap_or(false),
+ }
+ }
+}
diff --git a/dev/src/generate/capability.rs b/dev/src/generate/capability.rs
index fec29420ad..e0be2cd092 100644
--- a/dev/src/generate/capability.rs
+++ b/dev/src/generate/capability.rs
@@ -27,7 +27,7 @@ use std::fs;
use std::path::Path;
use syn::{GenericArgument, Item, ItemStruct, PathArguments, Type, TypePath};
-use super::options::doc_lines;
+use super::rustdoc::doc_lines;
/// A single field of the core `Capability` struct.
///
diff --git a/dev/src/generate/metadata.rs b/dev/src/generate/metadata.rs
index 6f9fcf2e7b..62e1ec4b1f 100644
--- a/dev/src/generate/metadata.rs
+++ b/dev/src/generate/metadata.rs
@@ -29,7 +29,7 @@ use std::fs;
use std::path::Path;
use syn::{FnArg, GenericArgument, ImplItem, Item, PathArguments, ReturnType,
Type};
-use super::options::doc_lines;
+use super::rustdoc::doc_lines;
/// The FFI shape of one accessor's return type.
///
diff --git a/dev/src/generate/mod.rs b/dev/src/generate/mod.rs
index ebc9d0f9a6..53cac58757 100644
--- a/dev/src/generate/mod.rs
+++ b/dev/src/generate/mod.rs
@@ -27,7 +27,6 @@ mod java;
mod metadata;
mod nodejs;
mod ocaml;
-mod options;
mod parser;
mod python;
mod ruby;
diff --git a/dev/src/generate/options.rs b/dev/src/generate/options.rs
deleted file mode 100644
index 2383199715..0000000000
--- a/dev/src/generate/options.rs
+++ /dev/null
@@ -1,252 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements. See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership. The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License. You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations
-// under the License.
-
-use anyhow::{Context, Result, anyhow, bail};
-use std::fs;
-use std::path::Path;
-use syn::{
- Expr, ExprLit, Field, GenericArgument, Item, ItemStruct, Lit, Meta,
PathArguments, Type,
- TypePath,
-};
-
-/// The Python type an operator option field maps to.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum OptionType {
- /// `Option<String>`
- Str,
- /// `Option<usize>` or `Option<u64>`
- Int,
- /// `bool` or `Option<bool>`
- Bool,
- /// `Option<jiff::Timestamp>`
- DateTime,
- /// `Option<HashMap<String, String>>`
- Dict,
- /// `Option<ocore::ChecksumAlgo>`
- ChecksumAlgo,
-}
-
-/// One keyword option of an operator method.
-#[derive(Debug, Clone)]
-pub struct OptionField {
- /// The option name, e.g. `if_match`.
- pub name: String,
- /// The value type of this option.
- pub ty: OptionType,
- /// The doc comment of the field, trimmed.
- pub doc: String,
-}
-
-/// One option type, parsed from a `#[pyclass]` struct in
-/// `bindings/python/src/options.rs`, e.g. `ReadOptions`.
-#[derive(Debug, Clone)]
-pub struct Options {
- /// The struct name, e.g. `ReadOptions`.
- pub name: String,
- /// The doc comment of the struct, trimmed.
- pub doc: String,
- /// The fields of the struct.
- pub fields: Vec<OptionField>,
-}
-
-/// Parse all `#[pyclass]` option structs from
`bindings/python/src/options.rs`.
-///
-/// A struct is treated as an option type when it is annotated with
-/// `#[pyclass]` and its name ends with `Options`.
-pub fn parse(path: &Path) -> Result<Vec<Options>> {
- let content =
- fs::read_to_string(path).with_context(|| format!("failed to read {}",
path.display()))?;
- let ast = syn::parse_file(&content)?;
-
- let mut options = Vec::new();
- for item in ast.items {
- if let Item::Struct(struct_) = item
- && is_option_struct(&struct_)
- {
- options.push(parse_struct(&struct_)?);
- }
- }
- Ok(options)
-}
-
-/// Whether a struct maps to a generated `*OptionsKwargs` TypedDict.
-fn is_option_struct(struct_: &ItemStruct) -> bool {
- struct_.ident.to_string().ends_with("Options")
- && struct_
- .attrs
- .iter()
- .any(|attr| attr.path().is_ident("pyclass"))
-}
-
-fn parse_struct(struct_: &ItemStruct) -> Result<Options> {
- let name = struct_.ident.to_string();
- let doc = doc_lines(&struct_.attrs).join("\n").trim().to_string();
-
- let fields = match &struct_.fields {
- syn::Fields::Named(named) => &named.named,
- _ => bail!("option struct {name} must have named fields"),
- };
-
- let mut parsed = Vec::with_capacity(fields.len());
- for field in fields {
- parsed.push(parse_field(field)?);
- }
-
- Ok(Options {
- name,
- doc,
- fields: parsed,
- })
-}
-
-fn parse_field(field: &Field) -> Result<OptionField> {
- let name = field
- .ident
- .as_ref()
- .ok_or_else(|| anyhow!("option field is unnamed: {field:?}"))?
- .to_string();
- let ty = parse_type(&field.ty)?;
- let doc = doc_lines(&field.attrs).join("\n").trim().to_string();
-
- Ok(OptionField { name, ty, doc })
-}
-
-/// Parse an optional field or a boolean flag that defaults to false.
-fn parse_type(ty: &Type) -> Result<OptionType> {
- let Type::Path(TypePath { path, .. }) = ty else {
- bail!("unsupported option field type: {ty:?}");
- };
- let segment = path
- .segments
- .last()
- .ok_or_else(|| anyhow!("option type path is empty: {ty:?}"))?;
- if segment.ident == "bool" {
- return Ok(OptionType::Bool);
- }
- if segment.ident != "Option" {
- bail!("option field must be Option<T> or bool, found {segment:?}");
- }
- let PathArguments::AngleBracketed(args) = &segment.arguments else {
- bail!("Option must have angle bracketed arguments");
- };
- let Some(GenericArgument::Type(Type::Path(inner))) = args.args.first()
else {
- bail!("Option must contain a type argument");
- };
- let inner_segment = inner
- .path
- .segments
- .last()
- .ok_or_else(|| anyhow!("option inner type path is empty: {inner:?}"))?;
-
- Ok(match inner_segment.ident.to_string().as_str() {
- "String" => OptionType::Str,
- "usize" | "u64" => OptionType::Int,
- "bool" => OptionType::Bool,
- // jiff::Timestamp
- "Timestamp" => OptionType::DateTime,
- // HashMap<String, String>
- "HashMap" => OptionType::Dict,
- "ChecksumAlgo" => OptionType::ChecksumAlgo,
- other => bail!("unsupported option type: {other}"),
- })
-}
-
-/// Collect the doc comment of a struct or field as trimmed lines.
-pub(super) fn doc_lines(attrs: &[syn::Attribute]) -> Vec<String> {
- attrs
- .iter()
- .filter(|attr| attr.path().is_ident("doc"))
- .filter_map(|attr| {
- if let Meta::NameValue(meta) = &attr.meta
- && let Expr::Lit(ExprLit {
- lit: Lit::Str(s), ..
- }) = &meta.value
- {
- return Some(s.value().trim().to_string());
- }
-
- None
- })
- .collect()
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn test_parse_options() {
- let path =
crate::workspace_dir().join("bindings/python/src/options.rs");
- let options = parse(&path).unwrap();
-
- let names: Vec<&str> = options.iter().map(|o|
o.name.as_str()).collect();
- assert_eq!(names, ["RenameOptions"]);
-
- for option in &options {
- assert!(
- option
- .fields
- .iter()
- .any(|field| field.name == "if_not_exists" && field.ty ==
OptionType::Bool),
- "{} must have a boolean if_not_exists field",
- option.name
- );
- }
-
- // A field doc keeps its paragraphs, which `options.py` renders as
- // separate docstring paragraphs. The hand-written struct only has an
- // `Option<bool>` field now, so a sample covers the other types.
- let options = parse_struct(&syn::parse_quote! {
- pub struct FakeOptions {
- /// First paragraph,
- /// continued.
- ///
- /// Second paragraph.
- pub flag: Option<bool>,
- /// An offset.
- 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();
- assert_eq!(
- options.fields[0].doc,
- "First paragraph,\ncontinued.\n\nSecond paragraph."
- );
- assert_eq!(options.fields[1].doc, "An offset.");
- 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 e748c2d833..bda0d234d7 100644
--- a/dev/src/generate/python.rs
+++ b/dev/src/generate/python.rs
@@ -18,7 +18,6 @@
use crate::generate::capability::{self, CapabilityField};
use crate::generate::core_options::{self, OptionKind, OptionsStruct};
use crate::generate::metadata::{self, MetadataKind};
-use crate::generate::options;
use crate::generate::parser::{Config, ConfigType, Services, service_feature,
sorted_services};
use crate::generate::rustdoc::rewrite_code_spans;
use anyhow::{Context, Result, bail};
@@ -686,7 +685,7 @@ struct PyOptions {
struct PyUnmirrored {
/// The name, which is also the Rust field and the core field it sets.
name: &'static str,
- py_type: options::OptionType,
+ py_type: OptionType,
rust_type: &'static str,
/// Appended to the `extract_optional` call that reads the keyword.
extract: &'static str,
@@ -694,8 +693,7 @@ struct PyUnmirrored {
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.
+/// The Python options classes, generated from
`core/core/src/types/options.rs`.
const GENERATED_OPTIONS: &[PyOptions] = &[
PyOptions {
name: "ListOptions",
@@ -1000,7 +998,7 @@ const GENERATED_OPTIONS: &[PyOptions] = &[
// keeps its algorithm name from main.
unmirrored: &[PyUnmirrored {
name: "checksum",
- py_type: options::OptionType::ChecksumAlgo,
+ py_type: OptionType::ChecksumAlgo,
rust_type: "Option<ocore::ChecksumAlgo>",
extract: ".map(|name: String|
super::parse_checksum_algorithm(&name))\
.transpose()?",
@@ -1090,10 +1088,24 @@ const GENERATED_OPTIONS: &[PyOptions] = &[
"which exception the copy\nraises is unspecified",
)],
},
+ PyOptions {
+ name: "RenameOptions",
+ options: &[(
+ "if_not_exists",
+ "if_not_exists",
+ OptionKind::Bool,
+ "Option<bool>",
+ )],
+ unmirrored: &[],
+ docs: &[],
+ rewrites: &[(
+ "which error the rename returns\nis unspecified",
+ "which exception the rename raises\nis unspecified",
+ )],
+ },
];
-/// The class order of `options.py`, which hand-written and generated classes
-/// share.
+/// The class order of `options.py`.
const OPTIONS_PY_ORDER: &[&str] = &[
"ReadOptions",
"WriteOptions",
@@ -1129,7 +1141,7 @@ struct PyField {
doc: Vec<String>,
/// The `options.py` type.
#[serde(skip)]
- py_type: options::OptionType,
+ py_type: OptionType,
rust_type: &'static str,
/// Appended to the `extract_optional` call that reads the keyword.
extract: &'static str,
@@ -1147,35 +1159,30 @@ struct ConvertField {
/// 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)> {
+fn lowering(kind: OptionKind, rust_type: &str) -> Option<(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::OptionString, "Option<String>") => (OptionType::Str, "",
""),
+ (OptionKind::OptionUsize, "Option<usize>") => (OptionType::Int, "",
""),
// A count whose keyword argument defaults to `None`, such as
// `read(concurrent=None)`. An omitted count is `0`.
- (OptionKind::Usize, "Option<usize>") => {
- (options::OptionType::Int, "", ".unwrap_or_default()")
- }
+ (OptionKind::Usize, "Option<usize>") => (OptionType::Int, "",
".unwrap_or_default()"),
// `offset` or `size`. The conversion builds the range from both with
// `ReadOptions::make_range` in `bindings/python/src/options.rs`.
- (OptionKind::BytesRange, "Option<u64>") => (options::OptionType::Int,
"", ""),
+ (OptionKind::BytesRange, "Option<u64>") => (OptionType::Int, "", ""),
(OptionKind::OptionTimestamp, "Option<jiff::Timestamp>") => (
- options::OptionType::DateTime,
+ OptionType::DateTime,
"",
".map(crate::utils::timestamp_from_jiff)",
),
(OptionKind::OptionStringMap,
"Option<std::collections::HashMap<String, String>>") => {
- (options::OptionType::Dict, "", "")
+ (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)"),
+ (OptionKind::Bool, "Option<bool>") => (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()", ""),
+ (OptionKind::Bool, "bool") => (OptionType::Bool,
".unwrap_or_default()", ""),
_ => return None,
})
}
@@ -1632,63 +1639,50 @@ fn generate_options_rs(workspace_dir: &Path) ->
Result<Vec<PyClass>> {
Ok(classes)
}
-/// Python type of an operator option field, parsed from
-/// `bindings/python/src/options.rs`.
-fn make_option_type(ty: options::OptionType) -> &'static str {
+/// The `options.py` type of a keyword argument.
+#[derive(Debug, Clone, Copy)]
+enum OptionType {
+ Str,
+ Int,
+ Bool,
+ DateTime,
+ Dict,
+ ChecksumAlgo,
+}
+
+fn make_option_type(ty: OptionType) -> &'static str {
match ty {
- options::OptionType::Str => "str",
- options::OptionType::Int => "int",
- options::OptionType::Bool => "bool",
- options::OptionType::DateTime => "datetime",
- options::OptionType::Dict => "dict[str, str]",
- options::OptionType::ChecksumAlgo => "ChecksumAlgorithm | None",
+ OptionType::Str => "str",
+ OptionType::Int => "int",
+ OptionType::Bool => "bool",
+ OptionType::DateTime => "datetime",
+ OptionType::Dict => "dict[str, str]",
+ OptionType::ChecksumAlgo => "ChecksumAlgorithm | None",
}
}
/// Generate `bindings/python/python/opendal/options.py`, the typed keyword
-/// arguments accepted by the operator methods.
-///
-/// The option fields come from the hand-written `#[pyclass]` structs in
-/// `bindings/python/src/options.rs` and from the generated classes, so the
-/// generated file stays in sync with the Rust option types.
+/// arguments accepted by the operator methods, from the generated classes.
fn generate_options_py(workspace_dir: &Path, generated: &[PyClass]) ->
Result<()> {
let output =
workspace_dir.join("bindings/python/python/opendal/options.py");
- fs::write(output, render_options_py(workspace_dir, generated)?)?;
+ fs::write(output, render_options_py(generated)?)?;
Ok(())
}
-fn render_options_py(workspace_dir: &Path, generated: &[PyClass]) ->
Result<String> {
- let source = workspace_dir.join("bindings/python/src/options.rs");
- let mut options = options::parse(&source)?;
- if options.is_empty() {
- anyhow::bail!("no option structs parsed from {}", source.display());
- }
- for class in generated {
- options.push(options::Options {
- name: class.name.to_string(),
- doc: class.doc.join("\n"),
- fields: class
- .fields
- .iter()
- .map(|field| options::OptionField {
- name: field.name.to_string(),
- ty: field.py_type,
- doc: field.doc.join("\n"),
- })
- .collect(),
- });
- }
- let mut ordered = Vec::with_capacity(options.len());
+fn render_options_py(generated: &[PyClass]) -> Result<String> {
+ let mut classes = Vec::with_capacity(generated.len());
for name in OPTIONS_PY_ORDER {
- let Some(at) = options.iter().position(|opts| opts.name == *name) else
{
- bail!("options class {name} is neither hand-written nor
generated");
+ let Some(class) = generated.iter().find(|class| class.name == *name)
else {
+ bail!("options class {name} is not generated");
};
- ordered.push(options.remove(at));
+ classes.push(class);
}
- if let Some(extra) = options.first() {
+ if let Some(extra) = generated
+ .iter()
+ .find(|class| !OPTIONS_PY_ORDER.contains(&class.name))
+ {
bail!("add {} to OPTIONS_PY_ORDER", extra.name);
}
- let options = ordered;
let mut out = String::new();
out.push_str(PYTHON_LICENSE_HEADER);
@@ -1702,29 +1696,23 @@ fn render_options_py(workspace_dir: &Path, generated:
&[PyClass]) -> Result<Stri
);
let mut exports = vec!["ChecksumAlgorithm".to_string()];
- for opts in &options {
+ for class in classes {
// `ReadOptions` maps to the `ReadKwargs` TypedDict.
let kwargs = format!(
"{}Kwargs",
- opts.name.strip_suffix("Options").unwrap_or(&opts.name)
+ class.name.strip_suffix("Options").unwrap_or(class.name)
);
exports.push(kwargs.clone());
- let doc = if opts.doc.is_empty() {
- "Keyword arguments for the corresponding `Operator` /
`AsyncOperator` method."
- .to_string()
- } else {
- opts.doc.clone()
- };
out.push_str(&format!("\n\nclass {kwargs}(TypedDict,
total=False):\n"));
- push_docstring(&mut out, &doc);
+ push_docstring(&mut out, &class.doc.join("\n"));
out.push('\n');
- for field in &opts.fields {
+ for field in &class.fields {
out.push_str(&format!(
" {}: {}\n",
field.name,
- make_option_type(field.ty)
+ make_option_type(field.py_type)
));
- push_docstring(&mut out, &field.doc);
+ push_docstring(&mut out, &field.doc.join("\n"));
}
}
@@ -1860,7 +1848,8 @@ mod tests {
"DeleteOptions",
"ReadOptions",
"WriteOptions",
- "CopyOptions"
+ "CopyOptions",
+ "RenameOptions"
]
);
classes
@@ -2071,6 +2060,24 @@ mod tests {
.collect()
}
+ /// The Python wording of the `RenameOptions` docs for core text that
+ /// does not hold for Python, as `(core, Python)`.
+ const RENAME_REWRITES: [(&str, &str); 1] = [(
+ "which error the rename returns\nis unspecified",
+ "which exception the rename raises\nis unspecified",
+ )];
+
+ /// `py_doc` of a core `RenameOptions` doc, with the Python wording.
+ fn rename_doc(core_doc: &[String], item: &str) -> Vec<String> {
+ let text = py_doc(core_doc, item, &py_names(),
&[]).unwrap().join("\n");
+ RENAME_REWRITES
+ .iter()
+ .fold(text, |text, (from, to)| text.replace(from, to))
+ .split('\n')
+ .map(String::from)
+ .collect()
+ }
+
/// The docstrings of every class and class field in `source`, keyed by
/// `Class` and `Class.field`, as Python's `ast` parses them and
/// `inspect.cleandoc` dedents them. Panics when `source` is not valid
@@ -2597,6 +2604,63 @@ print(json.dumps(docs))
}
}
+ /// The `RenameOptions` surface on main (4f064d75f), copied from
+ /// `bindings/python/src/options.rs`, and the Python checks and exceptions
+ /// its docs name: the capability is the one `OpRename::from_options` in
+ /// `core/core/src/raw/ops.rs` enforces for `if_not_exists`, and the
+ /// exceptions are the error kinds in `core/core/src/types/options.rs`.
+ /// It pins no core wording.
+ fn assert_rename_surface(class: &PyClass) {
+ let fields: Vec<String> = class
+ .fields
+ .iter()
+ .map(|f| format!("{}: {}", f.name, f.rust_type))
+ .collect();
+ assert_eq!(fields, ["if_not_exists: Option<bool>"]);
+
+ assert_eq!(
+ spans(&class.doc, "opendal.exceptions."),
+ ["NotFound"],
+ "{:?}",
+ class.doc
+ );
+ let references: Vec<String> = class
+ .fields
+ .iter()
+ .map(|f| {
+ format!(
+ "{}: {} / {}",
+ f.name,
+ spans(&f.doc, "op.capability().").join(" "),
+ spans(&f.doc, "opendal.exceptions.").join(" ")
+ )
+ })
+ .collect();
+ assert_eq!(
+ references,
+ ["if_not_exists: rename_with_if_not_exists / ConditionNotMatch
Unsupported"]
+ );
+
+ // No Rust-only names reach Python callers, no error kind keeps its
+ // core name, and Python raises the exceptions that core returns.
+ let exceptions = py_names().exceptions;
+ for doc in
std::iter::once(&class.doc).chain(class.fields.iter().map(|f| &f.doc)) {
+ let text = doc.join(" ");
+ for rust in [
+ "crate::",
+ "Capability::",
+ "ErrorKind::",
+ "returns `opendal.exceptions.",
+ "rename returns",
+ ] {
+ assert!(!text.contains(rust), "{rust} in {text}");
+ }
+ for kind in exceptions.keys() {
+ assert!(!text.contains(&format!("`{kind}`")), "{kind} in
{text}");
+ }
+ }
+ }
+
/// The keyword-only parameters of every `#[pyo3(signature)]` method in
/// `bindings/python/src/operator.rs`, keyed by type and method, each as
/// `name=default`.
@@ -3466,6 +3530,94 @@ print(json.dumps(docs))
assert!(rs.contains(&expected), "{rs}");
}
+ /// The `RenameOptions` API on main (4f064d75f), copied from
+ /// `bindings/python/src/options.rs`, with docstrings taken from core.
+ #[test]
+ fn test_rename_options_match_main() {
+ let parsed = core_options();
+ let class = generated_class(&parsed, "RenameOptions");
+ assert_rename_surface(&class);
+
+ // Each docstring is the core doc comment of the field it sets, with
+ // the Python wording.
+ let core = parsed.iter().find(|o| o.name == "RenameOptions").unwrap();
+ assert_eq!(class.doc, rename_doc(&core.doc, "RenameOptions"));
+ for field in &class.fields {
+ let core = core.fields.iter().find(|f| f.name ==
field.name).unwrap();
+ assert_eq!(
+ field.doc,
+ rename_doc(&core.doc, field.name),
+ "{}",
+ field.name
+ );
+ }
+ assert!(
+ class.doc.join(" ").contains(
+ "A missing source fails the rename with
`opendal.exceptions.NotFound`; when \
+ a condition error applies at the same time, which exception
the rename \
+ raises is unspecified."
+ ),
+ "{:?}",
+ class.doc
+ );
+
+ // `if_not_exists` sets the core field main set, and an omitted
+ // `if_not_exists` is `false`. A core field that Python does not set
+ // keeps its default.
+ let (set, defaulted): (Vec<_>, Vec<_>) = class
+ .conversion
+ .iter()
+ .map(|f| format!("{}: {}", f.name, f.expr))
+ .partition(|f| f.contains("opts."));
+ assert_eq!(set, ["if_not_exists:
opts.if_not_exists.unwrap_or(false)"]);
+ for field in &defaulted {
+ let value = field.split_once(": ").unwrap().1;
+ assert!(
+ ["None", "false", "0", "Default::default()"].contains(&value),
+ "{field}"
+ );
+ }
+
+ // `FromPyObject` reads only `if_not_exists` from a dict and ignores
+ // any other key.
+ let rs = render_options_rs(&generated_classes(&parsed,
&py_names()).unwrap()).unwrap();
+ let extract = rs
+ .split_once("impl<'a, 'py> FromPyObject<'a, 'py> for RenameOptions
{")
+ .unwrap()
+ .1
+ .split("\n}\n")
+ .next()
+ .unwrap();
+ let reads: Vec<&str> = extract
+ .lines()
+ .map(str::trim)
+ .filter(|line| line.contains("extract_optional"))
+ .collect();
+ assert_eq!(
+ reads,
+ ["if_not_exists: extract_optional(&dict, \"if_not_exists\")?,"]
+ );
+ assert!(!extract.contains("reject_unknown_kwargs"));
+
+ // The pyclass holds the field after its doc comment.
+ let comment = |doc: &[String], indent: &str| -> String {
+ doc.iter()
+ .map(|line| match line.as_str() {
+ "" => format!("{indent}///"),
+ line => format!("{indent}/// {line}"),
+ })
+ .collect::<Vec<_>>()
+ .join("\n")
+ };
+ let field = &class.fields[0];
+ let expected = format!(
+ "{}\n#[pyclass(module = \"opendal\")]\n#[derive(Default,
Debug)]\npub struct RenameOptions {{\n{}\n pub if_not_exists:
Option<bool>,\n}}\n",
+ comment(&class.doc, ""),
+ comment(&field.doc, " "),
+ );
+ assert!(rs.contains(&expected), "{rs}");
+ }
+
/// `WRITE_OPTION_KEYS`, which `open` accepts in a write mode, matches main
/// (a2ef00d6e) and the table.
#[test]
@@ -3678,13 +3830,14 @@ print(json.dumps(docs))
/// The `options.py` TypedDicts on main (4ae8e6122 for `ListKwargs`,
/// 809b76472 for `StatKwargs`, 501c5d96f for `DeleteKwargs`, f47ec7c1f
- /// for `ReadKwargs`, a2ef00d6e for `WriteKwargs`): the class order and
+ /// for `ReadKwargs`, a2ef00d6e for `WriteKwargs`, 4f064d75f for
+ /// `CopyKwargs` and `RenameKwargs`): 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();
- let py = render_options_py(&crate::workspace_dir(),
&generated).unwrap();
+ let py = render_options_py(&generated).unwrap();
let classes: Vec<&str> = py
.lines()
.filter_map(|line| line.strip_prefix("class "))
@@ -3784,6 +3937,10 @@ print(json.dumps(docs))
]
);
assert_eq!(keys("CopyKwargs", "RenameKwargs"), ["if_not_exists:
bool"]);
+ assert_eq!(
+ keys("RenameKwargs", "DeleteKwargs"),
+ ["if_not_exists: bool"]
+ );
assert_eq!(
keys("DeleteKwargs", "OpenKwargs"),
["version: str", "recursive: bool", "if_match: str"]
@@ -3941,6 +4098,19 @@ print(json.dumps(docs))
}
}
+ /// The `rename` keyword arguments and defaults on main (4f064d75f), copied
+ /// from `python/opendal/operator.pyi`.
+ #[test]
+ fn test_rename_signatures_match_main() {
+ let methods = operator_kwargs();
+ for ty in ["Operator", "AsyncOperator"] {
+ let key = (ty.to_string(), "rename".to_string());
+ assert_eq!(methods[&key].join(" "), "if_not_exists=None",
"{ty}.rename");
+ let presign = (ty.to_string(), "presign_rename".to_string());
+ assert!(!methods.contains_key(&presign), "{ty}.presign_rename");
+ }
+ }
+
/// 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`.
@@ -3991,6 +4161,8 @@ print(json.dumps(docs))
),
("Operator", "copy", "CopyOptions", &[][..]),
("AsyncOperator", "copy", "CopyOptions", &[][..]),
+ ("Operator", "rename", "RenameOptions", &[][..]),
+ ("AsyncOperator", "rename", "RenameOptions", &[][..]),
] {
let class = generated_class(&parsed, class);
let mut expected: Vec<String> = class
@@ -4021,11 +4193,7 @@ print(json.dumps(docs))
fn test_new_core_field_is_not_exposed() {
let parsed = core_options();
let base_rs = render_options_rs(&generated_classes(&parsed,
&py_names()).unwrap()).unwrap();
- let base_py = render_options_py(
- &crate::workspace_dir(),
- &generated_classes(&parsed, &py_names()).unwrap(),
- )
- .unwrap();
+ let base_py = render_options_py(&generated_classes(&parsed,
&py_names()).unwrap()).unwrap();
let mut mutated = parsed.clone();
for options in mutated.iter_mut().filter(|o| {
@@ -4036,6 +4204,7 @@ print(json.dumps(docs))
"ReadOptions",
"WriteOptions",
"CopyOptions",
+ "RenameOptions",
]
.contains(&o.name.as_str())
}) {
@@ -4052,7 +4221,7 @@ print(json.dumps(docs))
}
let classes = generated_classes(&mutated, &py_names()).unwrap();
let rs = render_options_rs(&classes).unwrap();
- let py = render_options_py(&crate::workspace_dir(), &classes).unwrap();
+ let py = render_options_py(&classes).unwrap();
assert_eq!(py, base_py);
let added: Vec<&str> = rs.lines().filter(|l|
l.contains("fake_")).collect();
@@ -4071,6 +4240,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();
@@ -4083,7 +4254,7 @@ print(json.dumps(docs))
options.fields.iter().position(|f| f.name == name).unwrap()
}
type Mutation = fn(&mut OptionsStruct);
- let cases: [(&str, Mutation, &str); 43] = [
+ let cases: [(&str, Mutation, &str); 48] = [
(
"ListOptions",
|list| {
@@ -4453,6 +4624,48 @@ print(json.dumps(docs))
`which error the copy\nreturns is unspecified`; \
update its Python rewrite in dev/src/generate/python.rs",
),
+ (
+ "RenameOptions",
+ |rename| {
+ rename.fields.remove(position(rename, "if_not_exists"));
+ },
+ "core RenameOptions has no field `if_not_exists` \
+ for Python RenameOptions.if_not_exists",
+ ),
+ (
+ "RenameOptions",
+ |rename| {
+ let i = position(rename, "if_not_exists");
+ rename.fields[i].kind = OptionKind::OptionString;
+ },
+ "core RenameOptions::if_not_exists has kind OptionString; \
+ Python RenameOptions.if_not_exists requires Bool",
+ ),
+ (
+ "RenameOptions",
+ |rename| {
+ let i = position(rename, "if_not_exists");
+ rename.fields[i].doc.clear();
+ },
+ "core RenameOptions::if_not_exists has no doc comment",
+ ),
+ (
+ "RenameOptions",
+ |rename| rename.has_unmirrored_fields = true,
+ "core RenameOptions has fields the core options parser skips; \
+ Python cannot set them",
+ ),
+ (
+ "RenameOptions",
+ |rename| {
+ for line in &mut rename.doc {
+ *line = line.replace("which error the rename", "which
error it");
+ }
+ },
+ "core RenameOptions docs no longer contain \
+ `which error the rename returns\nis unspecified`; \
+ update its Python rewrite in dev/src/generate/python.rs",
+ ),
];
let parsed = core_options();
@@ -4669,7 +4882,7 @@ print(json.dumps(docs))
fn test_options_table_rejects_bad_unmirrored_rows() {
const CHECKSUM: PyUnmirrored = PyUnmirrored {
name: "checksum",
- py_type: options::OptionType::ChecksumAlgo,
+ py_type: OptionType::ChecksumAlgo,
rust_type: "Option<ocore::ChecksumAlgo>",
extract: "",
convert: "",
@@ -4977,7 +5190,7 @@ print(json.dumps(docs))
]
);
- let py = render_options_py(&crate::workspace_dir(),
&generated).unwrap();
+ let py = render_options_py(&generated).unwrap();
// `bindings/python/tests/test_stub_docstrings.py` checks that
// `just fmt` keeps the first of these lines.
for line in [
@@ -5072,7 +5285,7 @@ print(json.dumps(docs))
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 py = render_options_py(&generated).unwrap();
let docs = python_docstrings(&py);
assert_eq!(
docs["StatKwargs"],
@@ -5154,7 +5367,7 @@ print(json.dumps(docs))
.unwrap();
assert_delete_surface(class);
- let py = render_options_py(&crate::workspace_dir(),
&generated).unwrap();
+ let py = render_options_py(&generated).unwrap();
let docs = python_docstrings(&py);
assert_eq!(
docs["DeleteKwargs"],
@@ -5252,7 +5465,7 @@ print(json.dumps(docs))
let class = generated.iter().find(|c| c.name ==
"ReadOptions").unwrap();
assert_read_surface(class);
- let py = render_options_py(&crate::workspace_dir(),
&generated).unwrap();
+ let py = render_options_py(&generated).unwrap();
let docs = python_docstrings(&py);
assert_eq!(
docs["ReadKwargs"],
@@ -5382,7 +5595,7 @@ print(json.dumps(docs))
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 py = render_options_py(&generated).unwrap();
let docs = python_docstrings(&py);
assert_eq!(
docs["WriteKwargs"],
@@ -5495,7 +5708,7 @@ print(json.dumps(docs))
let class = generated.iter().find(|c| c.name ==
"CopyOptions").unwrap();
assert_copy_surface(class);
- let py = render_options_py(&crate::workspace_dir(),
&generated).unwrap();
+ let py = render_options_py(&generated).unwrap();
let docs = python_docstrings(&py);
assert_eq!(
docs["CopyKwargs"],
@@ -5516,6 +5729,76 @@ print(json.dumps(docs))
);
}
+ /// Reworded core `RenameOptions` docs, in either markup and with quotes
+ /// and backslashes, pass the surface checks and read back in Python.
+ #[test]
+ fn test_rename_options_survive_core_rewording() {
+ let mut parsed = core_options();
+ let base = generated_class(&parsed, "RenameOptions");
+ let rename = parsed
+ .iter_mut()
+ .find(|o| o.name == "RenameOptions")
+ .unwrap();
+ rename.doc = [
+ r#""Rename" options, with \d."#,
+ "",
+ "- A missing source returns
[`ErrorKind::NotFound`](crate::ErrorKind::NotFound);",
+ "which error the rename returns",
+ "is unspecified.",
+ ]
+ .map(String::from)
+ .to_vec();
+ for field in &mut rename.fields {
+ let Some(python) = base.fields.iter().find(|f| f.core ==
field.name) else {
+ continue;
+ };
+ let mut doc = vec![format!(
+ r#"Reworded "{}" doc, see [the spec][crate::docs::specs::x]."#,
+ field.name
+ )];
+ for name in spans(&python.doc, "op.capability().") {
+ doc.push(format!(
+ "Check [`Capability::{name}`](crate::Capability::{name})."
+ ));
+ }
+ for (i, name) in spans(&python.doc, "opendal.exceptions.")
+ .into_iter()
+ .enumerate()
+ {
+ doc.push(match i % 2 {
+ 0 => format!("It returns `{name}`."),
+ _ => format!("It returns [`crate::ErrorKind::{name}`]."),
+ });
+ }
+ field.doc = doc;
+ }
+
+ let generated = generated_classes(&parsed, &py_names()).unwrap();
+ let class = generated
+ .iter()
+ .find(|c| c.name == "RenameOptions")
+ .unwrap();
+ assert_rename_surface(class);
+
+ let py = render_options_py(&generated).unwrap();
+ let docs = python_docstrings(&py);
+ assert_eq!(
+ docs["RenameKwargs"],
+ "\"Rename\" options, with \\d.\n\
+ \n\
+ - A missing source raises `opendal.exceptions.NotFound`;\n\
+ which exception the rename raises\n\
+ is unspecified."
+ );
+ assert_eq!(
+ docs["RenameKwargs.if_not_exists"],
+ "Reworded \"if_not_exists\" doc, see the spec.\n\
+ Check `op.capability().rename_with_if_not_exists`.\n\
+ It raises `opendal.exceptions.ConditionNotMatch`.\n\
+ It raises `opendal.exceptions.Unsupported`."
+ );
+ }
+
/// The hand-written `read` docstrings in `bindings/python/src/operator.rs`
/// agree with the generated `ReadOptions` docs: both name the overrides
/// that a positive `prefetch` rejects with `ValueError`, which
@@ -5690,6 +5973,33 @@ print(json.dumps(docs))
);
}
+ /// The hand-written `rename` docstrings name the capability and
+ /// exceptions of the generated `RenameOptions.if_not_exists` doc.
+ #[test]
+ fn test_rename_docstrings_agree_with_rename_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(), "RenameOptions");
+ let doc = &class.fields[0].doc;
+ let capability = spans(doc, "op.capability().");
+ let exceptions = spans(doc, "opendal.exceptions.");
+ assert_eq!(capability, ["rename_with_if_not_exists"]);
+ assert_eq!(exceptions, ["ConditionNotMatch", "Unsupported"]);
+ let param = format!(
+ " /// if_not_exists : bool, optional\n \
+ /// If True, require `{}` and raise `{}`\n \
+ /// if the service lacks it. Raise `{}` if the target\n \
+ /// already exists, leaving both files unchanged. Defaults to
False,\n \
+ /// which allows overwriting.\n",
+ capability[0], exceptions[1], exceptions[0]
+ );
+ assert_eq!(
+ operator.matches(¶m).count(),
+ 2,
+ "Operator.rename and AsyncOperator.rename"
+ );
+ }
+
/// Every capability and exception the generated docstrings name exists
/// in the Python API: `python/opendal/capability.pyi` and
/// `python/opendal/exceptions.pyi`.
@@ -5792,6 +6102,11 @@ print(json.dumps(docs))
&["copy_with_if_not_exists"][..],
&["ConditionNotMatch", "Conflict", "NotFound",
"Unsupported"][..],
),
+ (
+ "RenameOptions",
+ &["rename_with_if_not_exists"][..],
+ &["ConditionNotMatch", "NotFound", "Unsupported"][..],
+ ),
] {
let class = generated_class(&parsed, class);
let docs: Vec<String> = class
diff --git a/dev/src/generate/rustdoc.rs b/dev/src/generate/rustdoc.rs
index 5ca8b2b40f..87dc1d1941 100644
--- a/dev/src/generate/rustdoc.rs
+++ b/dev/src/generate/rustdoc.rs
@@ -15,6 +15,27 @@
// specific language governing permissions and limitations
// under the License.
+use syn::{Expr, ExprLit, Lit, Meta};
+
+/// Collect the doc comment of a struct or field as trimmed lines.
+pub(super) fn doc_lines(attrs: &[syn::Attribute]) -> Vec<String> {
+ attrs
+ .iter()
+ .filter(|attr| attr.path().is_ident("doc"))
+ .filter_map(|attr| {
+ if let Meta::NameValue(meta) = &attr.meta
+ && let Expr::Lit(ExprLit {
+ lit: Lit::Str(s), ..
+ }) = &meta.value
+ {
+ return Some(s.value().trim().to_string());
+ }
+
+ None
+ })
+ .collect()
+}
+
/// Rewrite the contents of code spans on one doc line.
///
/// Normalize ``[`name`]`` and ``[`name`](target)`` to plain code spans and