Files
pile/crates/pile-value/src/extract/item/toml.rs
rm-dr 4737acbcf4
All checks were successful
CI / Typos (push) Successful in 19s
CI / Build and test (push) Successful in 2m36s
CI / Clippy (push) Successful in 3m33s
CI / Build and test (all features) (push) Successful in 8m52s
Add S3 encryption
2026-03-21 21:05:48 -07:00

87 lines
2.2 KiB
Rust

use pile_config::Label;
use pile_io::AsyncReader;
use std::{
collections::HashMap,
sync::{Arc, OnceLock},
};
use crate::{
extract::traits::{ExtractState, ObjectExtractor},
value::{Item, PileValue},
};
fn toml_to_pile(value: toml::Value) -> PileValue {
match value {
toml::Value::String(s) => PileValue::String(Arc::new(s.into())),
toml::Value::Integer(i) => PileValue::String(Arc::new(i.to_string().into())),
toml::Value::Float(f) => PileValue::String(Arc::new(f.to_string().into())),
toml::Value::Boolean(b) => PileValue::String(Arc::new(b.to_string().into())),
toml::Value::Datetime(d) => PileValue::String(Arc::new(d.to_string().into())),
toml::Value::Array(a) => {
PileValue::Array(Arc::new(a.into_iter().map(toml_to_pile).collect()))
}
toml::Value::Table(_) => PileValue::Null,
}
}
pub struct TomlExtractor {
item: Item,
output: OnceLock<HashMap<Label, PileValue>>,
}
impl TomlExtractor {
pub fn new(item: &Item) -> Self {
Self {
item: item.clone(),
output: OnceLock::new(),
}
}
async fn get_inner(&self) -> Result<&HashMap<Label, PileValue>, std::io::Error> {
if let Some(x) = self.output.get() {
return Ok(x);
}
let mut reader = self.item.read().await?;
let bytes = reader.read_to_end().await?;
let toml: toml::Value = match toml::from_slice(&bytes) {
Ok(x) => x,
Err(_) => return Ok(self.output.get_or_init(HashMap::new)),
};
let output: HashMap<Label, PileValue> = match toml {
toml::Value::Table(t) => t
.into_iter()
.filter_map(|(k, v)| Label::new(&k).map(|label| (label, toml_to_pile(v))))
.collect(),
_ => HashMap::new(),
};
return Ok(self.output.get_or_init(|| output));
}
}
#[async_trait::async_trait]
impl ObjectExtractor for TomlExtractor {
async fn field(
&self,
state: &ExtractState,
name: &Label,
args: Option<&str>,
) -> Result<Option<PileValue>, std::io::Error> {
if args.is_some() {
return Ok(None);
}
if !state.ignore_mime && self.item.mime().type_() != mime::TEXT {
return Ok(None);
}
Ok(self.get_inner().await?.get(name).cloned())
}
async fn fields(&self) -> Result<Vec<Label>, std::io::Error> {
Ok(self.get_inner().await?.keys().cloned().collect())
}
}