blanket_rs/resource/
virtual_file.rs1use std::cell::RefCell;
2use std::path::{Path, PathBuf};
3use std::rc::Rc;
4
5use crate::builder::{Build, Builder, Dependency};
6
7pub struct VirtualFile {
8 path: PathBuf,
9 content: Option<String>,
10}
11
12impl VirtualFile {
13 pub fn new<P: AsRef<Path>>(path: P) -> Self {
14 Self {
15 path: path.as_ref().to_path_buf(),
16 content: None,
17 }
18 }
19 pub fn content(&self) -> Option<&str> {
20 self.content.as_deref()
21 }
22}
23
24impl std::fmt::Debug for VirtualFile {
25 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26 write!(
27 f,
28 "{} {{ path: {:?} }}",
29 std::any::type_name::<Self>()
30 .split("::")
31 .last()
32 .unwrap_or("UnknownType"),
33 self.path
34 )
35 }
36}
37
38impl PartialEq for VirtualFile {
39 fn eq(&self, other: &Self) -> bool {
40 self.path == other.path
41 }
42}
43
44impl Build for VirtualFile {
45 fn as_any(&self) -> &dyn std::any::Any {
46 self
47 }
48 fn equals(&self, other: Rc<RefCell<dyn Build>>) -> bool {
49 let other = other.borrow();
50 let any = other.as_any();
51 match any.downcast_ref::<Self>() {
52 Some(other) => self == other,
53 None => false,
54 }
55 }
56 fn register(
57 self,
58 builder: &mut Builder,
59 ) -> Result<(Option<PathBuf>, Dependency, Vec<Dependency>), Box<dyn std::error::Error>> {
60 let dependency = builder.make_dependency(self)?;
61 Ok((None, dependency, vec![]))
62 }
63 fn generate(&mut self) -> Result<(), Box<dyn std::error::Error>> {
64 let VirtualFile { path, .. } = self;
65 self.content = Some(std::fs::read_to_string(path)?);
66 Ok(())
67 }
68}
69
70pub fn extract_content(dependency: &Dependency) -> Result<String, Box<dyn std::error::Error>> {
71 let resource = dependency.resource();
72 let resource = resource.borrow();
73 let any = resource.as_any();
74 let resource = match any.downcast_ref::<VirtualFile>() {
75 Some(resource) => resource,
76 None => return Err("resource is not a virtual file".into()),
77 };
78 let content = match resource.content() {
79 Some(content) => content.to_string(),
80 None => return Err("resource has no content".into()),
81 };
82 Ok(content)
83}