dialogical/comptime/include.rs
1//!
2//! Type definitions for the `Execute` and `Import` directives.
3//!
4//! IMPORTANT: `Execute` is NOT for importing interactions from
5//! other files! It just executes the contents of the file as-is
6//! in a separate execution environment. If you want to import
7//! interactions from another file, PLEASE use the `Import`
8//! directive instead.
9//!
10//! TODO unit test if that claim is actually true ^^^ lol
11//!
12
13use std::fs::File;
14use std::io;
15use std::path::PathBuf;
16
17use super::{Result, ScriptError};
18use crate::parser::DgParser;
19use crate::{InteractionMap, ParseResult};
20
21/// Used for `Execute` and `Import` directives.
22#[derive(Clone, Debug)]
23pub struct ScriptPath(pub PathBuf);
24
25impl ScriptPath {
26 /// Create new ScriptPath by resolving one and appending
27 /// a new path onto it
28 pub fn make_append(&self, path: PathBuf) -> Self {
29 Self(self.0.parent().unwrap().join(path))
30 }
31
32 /// Get the contents of the script at the path.
33 /// Used by the `Execute` directive.
34 pub fn read(&self) -> Result<String> {
35 File::open(&self.0)
36 .and_then(|file| io::read_to_string(file))
37 .map_err(|_| ScriptError::FileOpen(self.0.clone()))
38 }
39
40 /// Run a second parser instance on the script at the path.
41 /// Used by the `Import` directive.
42 pub fn parse_import(&self) -> ParseResult<InteractionMap> {
43 let contents = self.read()?;
44
45 let mut parser = DgParser::new(self.0.clone());
46 parser.parse_all(&contents)
47 }
48}