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 a3987bed6e feat(bindings/python): expose full-object checksums on stat
(#9328)
a3987bed6e is described below
commit a3987bed6e026db72a422be030688886eec18e1a
Author: Xuanwo <[email protected]>
AuthorDate: Sat Nov 28 12:24:40 2026 +0800
feat(bindings/python): expose full-object checksums on stat (#9328)
---
bindings/python/docs/api/operator.md | 14 ++++++
bindings/python/python/opendal/operator.pyi | 8 +++
bindings/python/python/opendal/options.py | 2 +
bindings/python/python/opendal/types.pyi | 5 ++
bindings/python/scripts/postprocess_stubs.py | 12 ++++-
bindings/python/src/metadata.rs | 6 +++
bindings/python/src/operator.rs | 17 ++++++-
bindings/python/src/options.rs | 35 ++++++++-----
bindings/python/tests/test_async_stat.py | 11 +++++
bindings/python/tests/test_file_http_requests.py | 40 ++++++++++++++-
bindings/python/tests/test_sync_stat.py | 10 ++++
dev/src/generate/metadata.rs | 63 +++++++++++++++++-------
dev/src/generate/options.rs | 9 ++--
dev/src/generate/python.rs | 33 ++++++++-----
dev/src/generate/python/metadata_rs.j2 | 2 +-
15 files changed, 216 insertions(+), 51 deletions(-)
diff --git a/bindings/python/docs/api/operator.md
b/bindings/python/docs/api/operator.md
index e0e6655e25..f2cc7c81f3 100644
--- a/bindings/python/docs/api/operator.md
+++ b/bindings/python/docs/api/operator.md
@@ -15,3 +15,17 @@
.. automethod:: open(path: str | os.PathLike[str], mode: str, **kwargs:
typing.Unpack[~opendal.options.OpenKwargs])
```
+
+## Get a stored checksum
+
+With a version-aware service, pass the object version ID `v` to request the
+full-object checksum for that version.
+
+```python
+stored = op.stat(key, version=v, checksum=True).checksum
+if stored is not None:
+ algorithm, digest = stored
+```
+
+The digest contains raw bytes. The property is `None` if the service does not
+provide a full-object checksum. `stat` does not read the object data to obtain
it.
diff --git a/bindings/python/python/opendal/operator.pyi
b/bindings/python/python/opendal/operator.pyi
index 0758ceffe3..331814e9ab 100644
--- a/bindings/python/python/opendal/operator.pyi
+++ b/bindings/python/python/opendal/operator.pyi
@@ -706,6 +706,7 @@ class AsyncOperator:
content_type: str | None = None,
cache_control: str | None = None,
content_disposition: str | None = None,
+ checksum: bool = False,
) -> collections.abc.Awaitable[Metadata]:
"""
Get the metadata of a file at the given path.
@@ -730,6 +731,9 @@ class AsyncOperator:
The cache control of the file.
content_disposition : str, optional
The content disposition of the file.
+ checksum : bool, optional
+ Request the service's full-object checksum when available.
+ Defaults to False. See `Metadata.checksum` for the returned value.
Returns
-------
@@ -1288,6 +1292,7 @@ class Operator:
content_type: str | None = None,
cache_control: str | None = None,
content_disposition: str | None = None,
+ checksum: bool = False,
) -> Metadata:
"""
Get the metadata of a file at the given path.
@@ -1312,6 +1317,9 @@ class Operator:
The cache control of the file.
content_disposition : str, optional
The content disposition of the file.
+ checksum : bool, optional
+ Request the service's full-object checksum when available.
+ Defaults to False. See `Metadata.checksum` for the returned value.
Returns
-------
diff --git a/bindings/python/python/opendal/options.py
b/bindings/python/python/opendal/options.py
index 4bff40c041..937a20e91f 100644
--- a/bindings/python/python/opendal/options.py
+++ b/bindings/python/python/opendal/options.py
@@ -149,6 +149,8 @@ class StatKwargs(TypedDict, total=False):
"""The cache control of the file."""
content_disposition: str
"""The content disposition of the file."""
+ checksum: bool
+ """Request the service's full-object checksum when available. Defaults to
False."""
class CopyKwargs(TypedDict, total=False):
diff --git a/bindings/python/python/opendal/types.pyi
b/bindings/python/python/opendal/types.pyi
index 4aded11fd2..2d6bf1cbe6 100644
--- a/bindings/python/python/opendal/types.pyi
+++ b/bindings/python/python/opendal/types.pyi
@@ -18,6 +18,8 @@
from datetime import datetime
from typing import Final, final
+from .options import ChecksumAlgorithm
+
__all__ = ["Entry", "EntryMode", "Metadata", "PresignedRequest"]
@final
@@ -106,6 +108,9 @@ class Metadata:
def cache_control(self, /) -> str | None:
"""Return this entry's Cache-Control value."""
@property
+ def checksum(self, /) -> tuple[ChecksumAlgorithm, bytes] | None:
+ """Return the full-object checksum as (algorithm, raw digest bytes),
or None."""
+ @property
def content_disposition(self, /) -> str | None:
"""Return this entry's Content-Disposition value."""
@property
diff --git a/bindings/python/scripts/postprocess_stubs.py
b/bindings/python/scripts/postprocess_stubs.py
index 1cd9354d40..cf5fa6fbfb 100644
--- a/bindings/python/scripts/postprocess_stubs.py
+++ b/bindings/python/scripts/postprocess_stubs.py
@@ -23,7 +23,8 @@ filesystem, so the stubs must live at ``opendal/<name>.pyi``.
This relocates
them and applies two temporary fixups (until PyO3 introspection covers them):
1. Inject the imports our forward-ref string annotations need (PyO3 writes the
- annotation but not the import).
+ annotation but not the import). Restore the `ChecksumAlgorithm` alias on
+ the generated checksum property because PyO3 infers its Rust string type.
2. Replace ``exceptions.pyi`` with a hand-written stub while the generated one
is
incomplete -- ``create_exception!`` types are not introspectable yet, so
PyO3
emits only ``__getattr__``. When that changes, the stub is kept as-is.
@@ -60,6 +61,7 @@ IMPORTS = {
"from typing_extensions import Unpack\n"
),
"file": "import collections.abc\nimport types\nimport typing\n",
+ "types": "from .options import ChecksumAlgorithm\n",
}
# Mirrors the `create_exception!` types in `src/errors.rs`; keep in sync.
@@ -112,6 +114,14 @@ def relocate() -> None:
"""Move the stubs to the public ``opendal/<name>.pyi`` paths."""
for name in SUBMODULES:
text = pin_disjoint_base_import((GEN / f"{name}.pyi").read_text())
+ if name == "types":
+ inferred = "def checksum(self, /) -> tuple[str, bytes] | None:"
+ if inferred not in text:
+ msg = "unexpected generated Metadata.checksum signature"
+ raise ValueError(msg)
+ text = text.replace(
+ inferred, inferred.replace("tuple[str,",
"tuple[ChecksumAlgorithm,"), 1
+ )
(PKG / f"{name}.pyi").write_text(IMPORTS.get(name, "") + text)
# Stub for the ``opendal/_opendal.*.so`` extension itself.
diff --git a/bindings/python/src/metadata.rs b/bindings/python/src/metadata.rs
index 10136bb8ec..8330501b6b 100644
--- a/bindings/python/src/metadata.rs
+++ b/bindings/python/src/metadata.rs
@@ -130,6 +130,12 @@ impl Metadata {
})
}
+ /// Return the full-object checksum as (algorithm, raw digest bytes), or
None.
+ #[getter]
+ pub fn checksum(&self) -> Option<(&'static str, Vec<u8>)> {
+ self.0.checksum().and_then(options::checksum_into_python)
+ }
+
/// Whether this entry is a file.
#[getter]
pub fn is_file(&self) -> bool {
diff --git a/bindings/python/src/operator.rs b/bindings/python/src/operator.rs
index e83d5b7043..ccbfba373b 100644
--- a/bindings/python/src/operator.rs
+++ b/bindings/python/src/operator.rs
@@ -854,6 +854,9 @@ impl Operator {
/// The cache control of the file.
/// content_disposition : str, optional
/// The content disposition of the file.
+ /// checksum : bool, optional
+ /// Request the service's full-object checksum when available.
+ /// Defaults to False. See `Metadata.checksum` for the returned value.
///
/// Returns
/// -------
@@ -868,7 +871,8 @@ impl Operator {
if_unmodified_since=None,
content_type=None,
cache_control=None,
- content_disposition=None))]
+ content_disposition=None,
+ checksum=false))]
pub fn stat(
&self,
py: Python<'_>,
@@ -881,6 +885,7 @@ impl Operator {
content_type: Option<String>,
cache_control: Option<String>,
content_disposition: Option<String>,
+ checksum: bool,
) -> PyResult<Metadata> {
let path = path.to_string_lossy().to_string();
let opts = StatOptions {
@@ -892,6 +897,7 @@ impl Operator {
content_type,
cache_control,
content_disposition,
+ checksum,
};
check_runtime_process()?;
let this = self.core.clone();
@@ -1773,6 +1779,9 @@ impl AsyncOperator {
/// The cache control of the file.
/// content_disposition : str, optional
/// The content disposition of the file.
+ /// checksum : bool, optional
+ /// Request the service's full-object checksum when available.
+ /// Defaults to False. See `Metadata.checksum` for the returned value.
///
/// Returns
/// -------
@@ -1787,7 +1796,8 @@ impl AsyncOperator {
if_unmodified_since=None,
content_type=None,
cache_control=None,
- content_disposition=None) -> "collections.abc.Awaitable[Metadata]")]
+ content_disposition=None,
+ checksum=false) -> "collections.abc.Awaitable[Metadata]")]
pub fn stat<'p>(
&'p self,
py: Python<'p>,
@@ -1800,6 +1810,7 @@ impl AsyncOperator {
content_type: Option<String>,
cache_control: Option<String>,
content_disposition: Option<String>,
+ checksum: bool,
) -> PyResult<Bound<'p, PyAny>> {
let this = self.core.clone();
let path = path.to_string_lossy().to_string();
@@ -1812,6 +1823,7 @@ impl AsyncOperator {
content_type,
cache_control,
content_disposition,
+ checksum,
};
future_into_py(py, async move {
@@ -2232,6 +2244,7 @@ impl AsyncOperator {
content_type,
cache_control,
content_disposition,
+ checksum: false,
};
future_into_py(py, async move {
let res = this
diff --git a/bindings/python/src/options.rs b/bindings/python/src/options.rs
index 6d28ada499..02fe333c3a 100644
--- a/bindings/python/src/options.rs
+++ b/bindings/python/src/options.rs
@@ -231,18 +231,27 @@ impl ReadOptions {
}
}
+const CHECKSUM_ALGORITHMS: &[(&str, ocore::ChecksumAlgo)] = &[
+ ("crc32c", ocore::ChecksumAlgo::Crc32c),
+ ("crc64nvme", ocore::ChecksumAlgo::Crc64Nvme),
+ ("crc64ecma", ocore::ChecksumAlgo::Crc64Ecma),
+ ("md5", ocore::ChecksumAlgo::Md5),
+ ("sha1", ocore::ChecksumAlgo::Sha1),
+ ("sha256", ocore::ChecksumAlgo::Sha256),
+];
+
pub(crate) fn parse_checksum_algorithm(name: &str) ->
PyResult<ocore::ChecksumAlgo> {
- match name {
- "crc32c" => Ok(ocore::ChecksumAlgo::Crc32c),
- "crc64nvme" => Ok(ocore::ChecksumAlgo::Crc64Nvme),
- "crc64ecma" => Ok(ocore::ChecksumAlgo::Crc64Ecma),
- "md5" => Ok(ocore::ChecksumAlgo::Md5),
- "sha1" => Ok(ocore::ChecksumAlgo::Sha1),
- "sha256" => Ok(ocore::ChecksumAlgo::Sha256),
- _ => Err(PyValueError::new_err(format!(
- "unknown checksum algorithm {name:?}"
- ))),
- }
+ CHECKSUM_ALGORITHMS
+ .iter()
+ .find_map(|&(label, algo)| (label == name).then_some(algo))
+ .ok_or_else(|| PyValueError::new_err(format!("unknown checksum
algorithm {name:?}")))
+}
+
+pub(crate) fn checksum_into_python(checksum: ocore::Checksum) ->
Option<(&'static str, Vec<u8>)> {
+ let name = CHECKSUM_ALGORITHMS
+ .iter()
+ .find_map(|&(name, algo)| (algo == checksum.algo).then_some(name))?;
+ Some((name, checksum.value))
}
/// Options for `write` operations.
@@ -435,6 +444,8 @@ pub struct StatOptions {
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 {
@@ -452,6 +463,7 @@ impl<'a, 'py> FromPyObject<'a, 'py> for StatOptions {
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(),
})
}
}
@@ -471,6 +483,7 @@ impl From<StatOptions> for ocore::options::StatOptions {
override_content_type: opts.content_type,
override_cache_control: opts.cache_control,
override_content_disposition: opts.content_disposition,
+ checksum: opts.checksum,
..Default::default()
}
}
diff --git a/bindings/python/tests/test_async_stat.py
b/bindings/python/tests/test_async_stat.py
index 60ca45ac6e..cc867d9e0b 100644
--- a/bindings/python/tests/test_async_stat.py
+++ b/bindings/python/tests/test_async_stat.py
@@ -20,6 +20,7 @@ from uuid import uuid4
import pytest
+import opendal
from opendal.exceptions import NotFound
@@ -47,6 +48,16 @@ async def test_async_stat_non_existent(service_name,
operator, async_operator):
await async_operator.stat(path)
[email protected]
+async def test_async_stat_checksum_hint_on_memory():
+ operator = opendal.AsyncOperator("memory")
+ await operator.write("object", b"content")
+
+ assert (await operator.stat("object", checksum=True)).checksum is None
+ with pytest.raises(NotFound):
+ await operator.stat("missing", checksum=True)
+
+
@pytest.mark.asyncio
@pytest.mark.need_capability("read", "write", "delete", "stat", "create_dir")
async def test_async_stat_dir(service_name, operator, async_operator):
diff --git a/bindings/python/tests/test_file_http_requests.py
b/bindings/python/tests/test_file_http_requests.py
index d853fdd766..9cae7244b3 100644
--- a/bindings/python/tests/test_file_http_requests.py
+++ b/bindings/python/tests/test_file_http_requests.py
@@ -30,7 +30,7 @@ from urllib.parse import parse_qs, urlsplit
import pytest
import opendal
-from opendal.options import ReadKwargs
+from opendal.options import ReadKwargs, StatKwargs
CONTENT = b"HelloWorld"
TRUNCATED_CONTENT = b"Hell"
@@ -132,6 +132,16 @@ def serve_requests(port_queue, requests, slow_started,
slow_release, stop):
def do_GET(self) -> None:
range_header = self.headers.get("Range")
requests.append(("GET", self.path, range_header))
+ if urlsplit(self.path).path ==
"/storage/v1/b/checksum-test/o/object":
+ # GCS reports CRC32C in the object metadata without a hint.
+ body = b'{"size":"9","generation":"42","crc32c":"4waSgw=="}'
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+ return
+
content = TRUNCATED_CONTENT if self.path == "/truncated" else
CONTENT
body = content
status = 200
@@ -253,6 +263,34 @@ async def
test_read_forwards_response_overrides(request_server, prefetch):
] == [(expected_query, "bytes=2-6")] * 2
[email protected]
[email protected]("asynchronous", [False, True], ids=["sync", "async"])
[email protected]("options", [{}, {"checksum": False}, {"checksum":
True}])
+async def test_stat_exposes_checksum_returned_by_the_service(
+ request_server, asynchronous, options
+):
+ endpoint, state = request_server
+ state._reset()
+ operator = opendal.Operator(
+ "gcs", endpoint=endpoint, bucket="checksum-test", skip_signature="true"
+ )
+ kwargs: StatKwargs = {"version": "42", **options}
+ if asynchronous:
+ metadata = await operator.to_async_operator().stat("object", **kwargs)
+ else:
+ metadata = operator.stat("object", **kwargs)
+
+ checksum = metadata.checksum
+ assert checksum == ("crc32c", b"\xe3\x06\x92\x83")
+ assert isinstance(checksum[1], bytes)
+ assert metadata.version == "42"
+ assert state._reads() == [
+ ("/storage/v1/b/checksum-test/o/object?generation=42", None)
+ ]
+ with pytest.raises(AttributeError):
+ metadata.checksum = None
+
+
@pytest.fixture
def crc32c_operator(request_server):
endpoint, state = request_server
diff --git a/bindings/python/tests/test_sync_stat.py
b/bindings/python/tests/test_sync_stat.py
index 38a191b3be..12fdae8cf0 100644
--- a/bindings/python/tests/test_sync_stat.py
+++ b/bindings/python/tests/test_sync_stat.py
@@ -20,6 +20,7 @@ from uuid import uuid4
import pytest
+import opendal
from opendal.exceptions import NotFound
@@ -45,6 +46,15 @@ def test_sync_stat_non_existent(service_name, operator,
async_operator):
operator.stat(path)
+def test_sync_stat_checksum_hint_on_memory():
+ operator = opendal.Operator("memory")
+ operator.write("object", b"content")
+
+ assert operator.stat("object", checksum=True).checksum is None
+ with pytest.raises(NotFound):
+ operator.stat("missing", checksum=True)
+
+
@pytest.mark.need_capability("read", "write", "delete", "stat", "create_dir")
def test_sync_stat_dir(service_name, operator, async_operator):
path = f"test_sync_stat_dir_{uuid4()}/"
diff --git a/dev/src/generate/metadata.rs b/dev/src/generate/metadata.rs
index 4f026ee4c1..6f9fcf2e7b 100644
--- a/dev/src/generate/metadata.rs
+++ b/dev/src/generate/metadata.rs
@@ -19,10 +19,9 @@
//!
//! `Metadata` is a compact encoding, so it has no field list to mirror; its
//! public shape is the set of `pub fn name(&self) -> T` accessors. This module
-//! reads those accessors in source order and classifies each return type into
-//! the handful of shapes the .NET FFI mirror knows how to carry, so the Rust
-//! mirror, the C# interop struct, the marshaller, and the public class are all
-//! rendered from the same list.
+//! reads those accessors in source order and classifies the return types
+//! shared by the binding generators. A binding can map additional accessors
+//! from their original return types.
use anyhow::{Context, Result, bail};
use serde::Serialize;
@@ -71,16 +70,45 @@ pub struct MetadataField {
/// Accessors derived from another field, which have no FFI representation.
const DERIVED: &[&str] = &["is_file", "is_dir"];
-/// Accessors whose types bindings do not mirror yet.
-const NOT_MIRRORED: &[&str] = &["checksum"];
+/// Accessors that require a binding-specific mapping.
+const BINDING_SPECIFIC: &[&str] = &["checksum"];
-/// Parse the `impl Metadata` accessors out of the given core source file.
+/// A core accessor before its return type is mapped for a binding.
+pub(super) struct MetadataAccessor {
+ pub name: String,
+ pub output: ReturnType,
+ pub doc: String,
+}
+
+impl MetadataAccessor {
+ pub(super) fn into_field(self) -> Result<MetadataField> {
+ let Self { name, output, doc } = self;
+ let Some(kind) = classify(&output) else {
+ bail!(
+ "metadata accessor `{name}` returns an unsupported type; \
+ teach dev/src/generate/metadata.rs about it before
regenerating"
+ );
+ };
+ Ok(MetadataField { name, kind, doc })
+ }
+}
+
+/// Parse the core metadata accessors with shared binding mappings.
pub fn parse(path: &Path) -> Result<Vec<MetadataField>> {
+ parse_accessors(path)?
+ .into_iter()
+ .filter(|accessor| !BINDING_SPECIFIC.contains(&accessor.name.as_str()))
+ .map(MetadataAccessor::into_field)
+ .collect()
+}
+
+/// Extract the public `impl Metadata` accessors from the core source file.
+pub(super) fn parse_accessors(path: &Path) -> Result<Vec<MetadataAccessor>> {
let content =
fs::read_to_string(path).with_context(|| format!("failed to read {}",
path.display()))?;
let ast = syn::parse_file(&content)?;
- let mut fields = Vec::new();
+ let mut accessors = Vec::new();
for item in ast.items {
let Item::Impl(impl_) = item else {
continue;
@@ -98,26 +126,23 @@ pub fn parse(path: &Path) -> Result<Vec<MetadataField>> {
}
let name = func.sig.ident.to_string();
- if DERIVED.contains(&name.as_str()) ||
NOT_MIRRORED.contains(&name.as_str()) {
+ if DERIVED.contains(&name.as_str()) {
continue;
}
- let Some(kind) = classify(&func.sig.output) else {
- bail!(
- "metadata accessor `{name}` returns an unsupported type; \
- teach dev/src/generate/metadata.rs about it before
regenerating"
- );
- };
- let doc = first_paragraph(&doc_lines(&func.attrs));
- fields.push(MetadataField { name, kind, doc });
+ accessors.push(MetadataAccessor {
+ name,
+ output: func.sig.output,
+ doc: first_paragraph(&doc_lines(&func.attrs)),
+ });
}
}
- if fields.is_empty() {
+ if accessors.is_empty() {
bail!("impl Metadata not found in {}", path.display());
}
- Ok(fields)
+ Ok(accessors)
}
/// Parse the names of the public `impl MetadataBuilder` methods that take
diff --git a/dev/src/generate/options.rs b/dev/src/generate/options.rs
index 3476591f47..c7b39bcdaa 100644
--- a/dev/src/generate/options.rs
+++ b/dev/src/generate/options.rs
@@ -30,7 +30,7 @@ pub enum OptionType {
Str,
/// `Option<usize>` or `Option<u64>`
Int,
- /// `Option<bool>`
+ /// `bool` or `Option<bool>`
Bool,
/// `Option<jiff::Timestamp>`
DateTime,
@@ -125,7 +125,7 @@ fn parse_field(field: &Field) -> Result<OptionField> {
Ok(OptionField { name, ty, doc })
}
-/// Parse the type of an option field, which must be `Option<T>`.
+/// 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:?}");
@@ -134,8 +134,11 @@ fn parse_type(ty: &Type) -> Result<OptionType> {
.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>, found {segment:?}");
+ 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");
diff --git a/dev/src/generate/python.rs b/dev/src/generate/python.rs
index df90f52af0..d469948276 100644
--- a/dev/src/generate/python.rs
+++ b/dev/src/generate/python.rs
@@ -247,15 +247,23 @@ struct MetadataField {
/// Expression that produces the getter value from the core metadata.
py_value: String,
/// `format!` placeholder used for this accessor in `__repr__`.
- repr_fmt: &'static str,
+ repr_fmt: Option<&'static str>,
}
/// Map one core accessor to its Python getter.
-///
-/// A new return type in core fails parsing in `metadata::parse`, and a new
-/// `MetadataKind` fails this exhaustive match, so an unsupported accessor
-/// never renders silently.
-fn metadata_field(f: metadata::MetadataField) -> MetadataField {
+fn metadata_field(accessor: metadata::MetadataAccessor) ->
Result<MetadataField> {
+ if accessor.name == "checksum" && accessor.output == syn::parse_quote!(->
Option<Checksum>) {
+ return Ok(MetadataField {
+ name: accessor.name,
+ doc: "Return the full-object checksum as (algorithm, raw digest
bytes), or None."
+ .to_string(),
+ py_type: "Option<(&'static str, Vec<u8>)>",
+ py_value:
"self.0.checksum().and_then(options::checksum_into_python)".to_string(),
+ repr_fmt: None,
+ });
+ }
+
+ let f = accessor.into_field()?;
let name = &f.name;
let mut doc = f.doc;
let (py_type, py_value, repr_fmt) = match f.kind {
@@ -290,27 +298,26 @@ fn metadata_field(f: metadata::MetadataField) ->
MetadataField {
}
};
- MetadataField {
+ Ok(MetadataField {
name: f.name,
doc,
py_type,
py_value,
- repr_fmt,
- }
+ repr_fmt: Some(repr_fmt),
+ })
}
/// Render `bindings/python/src/metadata.rs` from
-/// `core/core/src/types/metadata.rs`, so that every core metadata accessor is
-/// exposed as a getter with its core doc comment.
+/// `core/core/src/types/metadata.rs`, including the Python checksum mapping.
///
/// The derived `is_file` and `is_dir` getters are part of the template, and
/// the `.pyi` stub is derived from this pyclass by `just stub-gen`.
fn generate_metadata(workspace_dir: &Path) -> Result<()> {
let source = workspace_dir.join("core/core/src/types/metadata.rs");
- let fields: Vec<MetadataField> = metadata::parse(&source)?
+ let fields: Vec<MetadataField> = metadata::parse_accessors(&source)?
.into_iter()
.map(metadata_field)
- .collect();
+ .collect::<Result<_>>()?;
let mut env = Environment::new();
env.add_template("metadata_rs", include_str!("python/metadata_rs.j2"))?;
diff --git a/dev/src/generate/python/metadata_rs.j2
b/dev/src/generate/python/metadata_rs.j2
index c5b5e01c4d..69635e4a7c 100644
--- a/dev/src/generate/python/metadata_rs.j2
+++ b/dev/src/generate/python/metadata_rs.j2
@@ -62,7 +62,7 @@ impl Metadata {
pub fn __repr__(&self) -> String {
let parts = [
-{%- for f in fields %}
+{%- for f in fields if f.repr_fmt %}
format!("{{ f.name }}={{ f.repr_fmt }}", self.0.{{ f.name }}()),
{%- endfor %}
];