predsync_compiler/
builder.rs1use std::{
4 env, fmt, fs, io,
5 path::{Path, PathBuf},
6 string::String,
7 vec::Vec,
8};
9
10use predsync_schema::SchemaError;
11
12use crate::{
13 check::{CheckError, check_sets, yaml_files},
14 codegen::{CodegenError, generate_rust_with_options},
15 parse_schema,
16};
17
18#[derive(Debug, Default)]
20pub struct Builder {
21 sets: Vec<PathBuf>,
22 custom_predictors: std::collections::BTreeMap<String, String>,
23}
24
25#[derive(Debug)]
27pub enum BuildError {
28 Check(CheckError),
29 Parse { path: PathBuf, error: SchemaError },
30 Codegen(CodegenError),
31 Io(io::Error),
32 MissingOutDir,
33}
34
35impl Builder {
36 pub fn new() -> Self {
37 Self::default()
38 }
39
40 pub fn set(mut self, path: impl Into<PathBuf>) -> Self {
42 self.sets.push(path.into());
43 self
44 }
45
46 pub fn custom_predictor(mut self, name: impl Into<String>, path: impl Into<String>) -> Self {
48 self.custom_predictors.insert(name.into(), path.into());
49 self
50 }
51
52 pub fn check(&self) -> Result<(), BuildError> {
54 check_sets(&self.sets)?;
55 Ok(())
56 }
57
58 pub fn generate(&self, file_name: impl AsRef<Path>) -> Result<(), BuildError> {
60 let out_dir = env::var_os("OUT_DIR").ok_or(BuildError::MissingOutDir)?;
61 for set in &self.sets {
62 for file in yaml_files(set)? {
63 println!("cargo:rerun-if-changed={}", file.display());
64 }
65 }
66 self.generate_to(Path::new(&out_dir).join(file_name))
67 }
68
69 pub fn generate_to(&self, output: impl AsRef<Path>) -> Result<(), BuildError> {
71 self.check()?;
72 let mut sets = self.sets.clone();
73 sets.sort();
74
75 let mut source = String::new();
76 for set in sets {
77 for file in yaml_files(&set)? {
78 let text = fs::read_to_string(&file)?;
79 let parsed = parse_schema(&text).map_err(|error| BuildError::Parse {
80 path: file.clone(),
81 error,
82 })?;
83 for message in &parsed.set.messages {
84 for field in &message.fields {
85 if let Some(spec) = &field.predictor
86 && let predsync_schema::PredictorKind::Custom(name) = &spec.kind
87 && !self.custom_predictors.contains_key(name)
88 {
89 return Err(BuildError::Parse {
90 path: file.clone(),
91 error: predsync_schema::SchemaError::UnknownPredictorKind(
92 name.clone(),
93 ),
94 });
95 }
96 }
97 }
98 source.push_str(&generate_rust_with_options(
99 &parsed.set,
100 &self.custom_predictors,
101 )?);
102 }
103 }
104
105 let path = output.as_ref();
106 if let Some(parent) = path
107 .parent()
108 .filter(|parent| !parent.as_os_str().is_empty())
109 {
110 fs::create_dir_all(parent)?;
111 }
112 fs::write(path, source)?;
113 Ok(())
114 }
115}
116
117impl fmt::Display for BuildError {
118 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119 match self {
120 Self::Check(error) => write!(f, "schema check failed: {error}"),
121 Self::Parse { path, error } => write!(f, "{}: {error}", path.display()),
122 Self::Codegen(error) => write!(f, "code generation failed: {error}"),
123 Self::Io(error) => write!(f, "I/O error: {error}"),
124 Self::MissingOutDir => {
125 write!(f, "OUT_DIR is not set; Builder::generate is for build.rs")
126 }
127 }
128 }
129}
130
131impl std::error::Error for BuildError {}
132
133impl From<CheckError> for BuildError {
134 fn from(error: CheckError) -> Self {
135 Self::Check(error)
136 }
137}
138
139impl From<CodegenError> for BuildError {
140 fn from(error: CodegenError) -> Self {
141 Self::Codegen(error)
142 }
143}
144
145impl From<io::Error> for BuildError {
146 fn from(error: io::Error) -> Self {
147 Self::Io(error)
148 }
149}