openfunctions_rs/core/loader.rs
1//! Loader utilities for tools and agents
2//!
3//! This module provides a simple and convenient loader for deserializing
4//! data from common file formats like YAML and JSON.
5
6use anyhow::Result;
7
8/// A loader for deserializing data from files.
9///
10/// `Loader` provides a set of methods to easily load and parse files
11/// into specified data structures.
12pub struct Loader;
13
14impl Loader {
15 /// Creates a new `Loader` instance.
16 pub fn new() -> Self {
17 Self
18 }
19
20 /// Loads and deserializes a YAML file into a specified type.
21 ///
22 /// # Arguments
23 ///
24 /// * `path` - A path to the YAML file.
25 ///
26 /// # Type Parameters
27 ///
28 /// * `T` - The type to deserialize the YAML content into. It must implement
29 /// `serde::de::DeserializeOwned`.
30 pub async fn load_yaml<T>(&self, path: &std::path::Path) -> Result<T>
31 where
32 T: serde::de::DeserializeOwned,
33 {
34 let content = tokio::fs::read_to_string(path).await?;
35 Ok(serde_yaml::from_str(&content)?)
36 }
37
38 /// Loads and deserializes a JSON file into a specified type.
39 ///
40 /// # Arguments
41 ///
42 /// * `path` - A path to the JSON file.
43 ///
44 /// # Type Parameters
45 ///
46 /// * `T` - The type to deserialize the JSON content into. It must implement
47 /// `serde::de::DeserializeOwned`.
48 pub async fn load_json<T>(&self, path: &std::path::Path) -> Result<T>
49 where
50 T: serde::de::DeserializeOwned,
51 {
52 let content = tokio::fs::read_to_string(path).await?;
53 Ok(serde_json::from_str(&content)?)
54 }
55}
56
57impl Default for Loader {
58 /// Creates a new `Loader` instance with default settings.
59 fn default() -> Self {
60 Self::new()
61 }
62}