Skip to main content

ModuleSource

Enum ModuleSource 

Source
pub enum ModuleSource {
    File(String),
    Text {
        uri: String,
        text: String,
    },
    Uri(String),
}
Expand description

Represents the source of a Pkl module to evaluate.

Variants§

§

File(String)

A file path to a .pkl file.

§

Text

Inline Pkl source text with an optional name URI.

Fields

§text: String
§

Uri(String)

A URI pointing to a module.

Implementations§

Source§

impl ModuleSource

Source

pub fn file(path: impl AsRef<Path>) -> Self

Create a ModuleSource from a file path.

Source

pub fn text(text: impl Into<String>) -> Self

Create a ModuleSource from inline text.

Examples found in repository?
examples/basic.rs (lines 16-21)
10fn main() -> Result<(), Box<dyn std::error::Error>> {
11    let mut manager = EvaluatorManager::new()?;
12    let opts = EvaluatorOptions::preconfigured();
13    let evaluator = manager.new_evaluator(opts)?;
14
15    // Evaluate inline Pkl text
16    let source = ModuleSource::text(
17        r#"
18        host = "localhost"
19        port = 8080
20        "#,
21    );
22
23    let server: Server = manager.evaluate_module_typed(&evaluator, source)?;
24    println!("Server: {server:?}");
25
26    // Evaluate a Pkl file (if it exists)
27    // let source = ModuleSource::file("config.pkl");
28    // let value = manager.evaluate_module(&evaluator, source)?;
29    // println!("Value: {value:?}");
30
31    manager.close_evaluator(&evaluator)?;
32    Ok(())
33}
More examples
Hide additional examples
examples/multiple_modules.rs (lines 29-35)
22fn main() -> Result<(), Box<dyn std::error::Error>> {
23    let mut manager = EvaluatorManager::new()?;
24    let evaluator = manager.new_evaluator(EvaluatorOptions::preconfigured())?;
25
26    // First module: database config
27    let db: DbConfig = manager.evaluate_module_typed(
28        &evaluator,
29        ModuleSource::text(
30            r#"
31            host = "db.internal"
32            port = 5432
33            name = "myapp_production"
34            "#,
35        ),
36    )?;
37    println!("Database: {db:?}");
38
39    // Second module: cache config
40    let cache: CacheConfig = manager.evaluate_module_typed(
41        &evaluator,
42        ModuleSource::text(
43            r#"
44            host = "redis.internal"
45            port = 6379
46            ttl = 3600
47            "#,
48        ),
49    )?;
50    println!("Cache: {cache:?}");
51
52    manager.close_evaluator(&evaluator)?;
53    Ok(())
54}
examples/typed_eval.rs (lines 25-40)
21fn main() -> Result<(), Box<dyn std::error::Error>> {
22    let mut manager = EvaluatorManager::new()?;
23    let evaluator = manager.new_evaluator(EvaluatorOptions::preconfigured())?;
24
25    let source = ModuleSource::text(
26        r#"
27        name = "my-service"
28        version = "2.1.0"
29        server {
30            host = "0.0.0.0"
31            port = 8443
32            maxConnections = 100
33        }
34        features = new Listing {
35            "auth"
36            "logging"
37            "metrics"
38        }
39        "#,
40    );
41
42    let config: AppConfig = manager.evaluate_module_typed(&evaluator, source)?;
43    println!("App: {} v{}", config.name, config.version);
44    println!("Server: {}:{}", config.server.host, config.server.port);
45    println!("Max connections: {}", config.server.max_connections);
46    println!("Features: {:?}", config.features);
47
48    manager.close_evaluator(&evaluator)?;
49    Ok(())
50}
examples/expressions.rs (lines 8-15)
4fn main() -> Result<(), Box<dyn std::error::Error>> {
5    let mut manager = EvaluatorManager::new()?;
6    let evaluator = manager.new_evaluator(EvaluatorOptions::preconfigured())?;
7
8    let source = ModuleSource::text(
9        r#"
10        name = "my-app"
11        port = 8080
12        url = "http://localhost:\(port)"
13        hosts = new Listing { "web-1"; "web-2"; "web-3" }
14        "#,
15    );
16
17    // Evaluate the whole module
18    let full = manager.evaluate_module(&evaluator, source.clone())?;
19    println!("Full module:\n{full:#?}\n");
20
21    // Evaluate a single expression
22    let name = manager.evaluate_expression(&evaluator, source.clone(), Some("name"))?;
23    println!("name = {name:?}");
24
25    let url = manager.evaluate_expression(&evaluator, source.clone(), Some("url"))?;
26    println!("url = {url:?}");
27
28    let hosts = manager.evaluate_expression(&evaluator, source, Some("hosts"))?;
29    println!("hosts = {hosts:?}");
30
31    manager.close_evaluator(&evaluator)?;
32    Ok(())
33}
examples/raw_values.rs (lines 11-18)
7fn main() -> Result<(), Box<dyn std::error::Error>> {
8    let mut manager = EvaluatorManager::new()?;
9    let evaluator = manager.new_evaluator(EvaluatorOptions::preconfigured())?;
10
11    let source = ModuleSource::text(
12        r#"
13        name = "example"
14        port = 8080
15        debug = true
16        tags = new Listing { "web"; "api" }
17        "#,
18    );
19
20    let value = manager.evaluate_module(&evaluator, source)?;
21
22    // Access properties via the convenience method
23    if let Some(props) = value.as_properties() {
24        for (key, val) in &props {
25            match val {
26                PklValue::String(s) => println!("{key} = \"{s}\""),
27                PklValue::Int(n) => println!("{key} = {n}"),
28                PklValue::Bool(b) => println!("{key} = {b}"),
29                PklValue::List(items) => {
30                    let strs: Vec<_> = items.iter().filter_map(|v| v.as_str()).collect();
31                    println!("{key} = {strs:?}");
32                }
33                other => println!("{key} = {other:?}"),
34            }
35        }
36    }
37
38    // Direct value accessors
39    let name = value
40        .as_properties()
41        .and_then(|p| p.get("name").copied())
42        .and_then(|v| v.as_str());
43    println!("\nDirect access — name: {name:?}");
44
45    manager.close_evaluator(&evaluator)?;
46    Ok(())
47}
Source

pub fn text_with_uri(uri: impl Into<String>, text: impl Into<String>) -> Self

Create a ModuleSource from inline text with a custom name.

Source

pub fn uri(uri: impl Into<String>) -> Self

Create a ModuleSource from a URI.

Source

pub fn module_uri(&self) -> String

Get the module URI for the request.

Source

pub fn module_text(&self) -> Option<&str>

Get the module text, if this is an inline source.

Trait Implementations§

Source§

impl Clone for ModuleSource

Source§

fn clone(&self) -> ModuleSource

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ModuleSource

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.