Brian Silverman | cc09f18 | 2022-03-09 15:40:20 -0800 | [diff] [blame^] | 1 | //! A template engine backed by [Tera] for rendering Files. |
| 2 | |
| 3 | use std::collections::HashMap; |
| 4 | |
| 5 | use anyhow::{Context as AnyhowContext, Result}; |
| 6 | use serde_json::{from_value, to_value, Value}; |
| 7 | use tera::{self, Tera}; |
| 8 | |
| 9 | use crate::config::{CrateId, RenderConfig}; |
| 10 | use crate::context::Context; |
| 11 | use crate::rendering::{ |
| 12 | render_crate_bazel_label, render_crate_bazel_repository, render_crate_build_file, |
| 13 | render_module_label, render_platform_constraint_label, |
| 14 | }; |
| 15 | use crate::utils::sanitize_module_name; |
| 16 | use crate::utils::sanitize_repository_name; |
| 17 | use crate::utils::starlark::{SelectStringDict, SelectStringList}; |
| 18 | |
| 19 | pub struct TemplateEngine { |
| 20 | engine: Tera, |
| 21 | context: tera::Context, |
| 22 | } |
| 23 | |
| 24 | impl TemplateEngine { |
| 25 | pub fn new(render_config: &RenderConfig) -> Self { |
| 26 | let mut tera = Tera::default(); |
| 27 | tera.add_raw_templates(vec![ |
| 28 | ( |
| 29 | "partials/crate/aliases.j2", |
| 30 | include_str!(concat!( |
| 31 | env!("CARGO_MANIFEST_DIR"), |
| 32 | "/src/rendering/templates/partials/crate/aliases.j2" |
| 33 | )), |
| 34 | ), |
| 35 | ( |
| 36 | "partials/crate/binary.j2", |
| 37 | include_str!(concat!( |
| 38 | env!("CARGO_MANIFEST_DIR"), |
| 39 | "/src/rendering/templates/partials/crate/binary.j2" |
| 40 | )), |
| 41 | ), |
| 42 | ( |
| 43 | "partials/crate/build_script.j2", |
| 44 | include_str!(concat!( |
| 45 | env!("CARGO_MANIFEST_DIR"), |
| 46 | "/src/rendering/templates/partials/crate/build_script.j2" |
| 47 | )), |
| 48 | ), |
| 49 | ( |
| 50 | "partials/crate/common_attrs.j2", |
| 51 | include_str!(concat!( |
| 52 | env!("CARGO_MANIFEST_DIR"), |
| 53 | "/src/rendering/templates/partials/crate/common_attrs.j2" |
| 54 | )), |
| 55 | ), |
| 56 | ( |
| 57 | "partials/crate/deps.j2", |
| 58 | include_str!(concat!( |
| 59 | env!("CARGO_MANIFEST_DIR"), |
| 60 | "/src/rendering/templates/partials/crate/deps.j2" |
| 61 | )), |
| 62 | ), |
| 63 | ( |
| 64 | "partials/crate/library.j2", |
| 65 | include_str!(concat!( |
| 66 | env!("CARGO_MANIFEST_DIR"), |
| 67 | "/src/rendering/templates/partials/crate/library.j2" |
| 68 | )), |
| 69 | ), |
| 70 | ( |
| 71 | "partials/crate/proc_macro.j2", |
| 72 | include_str!(concat!( |
| 73 | env!("CARGO_MANIFEST_DIR"), |
| 74 | "/src/rendering/templates/partials/crate/proc_macro.j2" |
| 75 | )), |
| 76 | ), |
| 77 | ( |
| 78 | "partials/module/aliases_map.j2", |
| 79 | include_str!(concat!( |
| 80 | env!("CARGO_MANIFEST_DIR"), |
| 81 | "/src/rendering/templates/partials/module/aliases_map.j2" |
| 82 | )), |
| 83 | ), |
| 84 | ( |
| 85 | "partials/module/deps_map.j2", |
| 86 | include_str!(concat!( |
| 87 | env!("CARGO_MANIFEST_DIR"), |
| 88 | "/src/rendering/templates/partials/module/deps_map.j2" |
| 89 | )), |
| 90 | ), |
| 91 | ( |
| 92 | "partials/module/repo_git.j2", |
| 93 | include_str!(concat!( |
| 94 | env!("CARGO_MANIFEST_DIR"), |
| 95 | "/src/rendering/templates/partials/module/repo_git.j2" |
| 96 | )), |
| 97 | ), |
| 98 | ( |
| 99 | "partials/module/repo_http.j2", |
| 100 | include_str!(concat!( |
| 101 | env!("CARGO_MANIFEST_DIR"), |
| 102 | "/src/rendering/templates/partials/module/repo_http.j2" |
| 103 | )), |
| 104 | ), |
| 105 | ( |
| 106 | "partials/starlark/glob.j2", |
| 107 | include_str!(concat!( |
| 108 | env!("CARGO_MANIFEST_DIR"), |
| 109 | "/src/rendering/templates/partials/starlark/glob.j2" |
| 110 | )), |
| 111 | ), |
| 112 | ( |
| 113 | "partials/starlark/selectable_dict.j2", |
| 114 | include_str!(concat!( |
| 115 | env!("CARGO_MANIFEST_DIR"), |
| 116 | "/src/rendering/templates/partials/starlark/selectable_dict.j2" |
| 117 | )), |
| 118 | ), |
| 119 | ( |
| 120 | "partials/starlark/selectable_list.j2", |
| 121 | include_str!(concat!( |
| 122 | env!("CARGO_MANIFEST_DIR"), |
| 123 | "/src/rendering/templates/partials/starlark/selectable_list.j2" |
| 124 | )), |
| 125 | ), |
| 126 | ( |
| 127 | "partials/header.j2", |
| 128 | include_str!(concat!( |
| 129 | env!("CARGO_MANIFEST_DIR"), |
| 130 | "/src/rendering/templates/partials/header.j2" |
| 131 | )), |
| 132 | ), |
| 133 | ( |
| 134 | "crate_build_file.j2", |
| 135 | include_str!(concat!( |
| 136 | env!("CARGO_MANIFEST_DIR"), |
| 137 | "/src/rendering/templates/crate_build_file.j2" |
| 138 | )), |
| 139 | ), |
| 140 | ( |
| 141 | "module_build_file.j2", |
| 142 | include_str!(concat!( |
| 143 | env!("CARGO_MANIFEST_DIR"), |
| 144 | "/src/rendering/templates/module_build_file.j2" |
| 145 | )), |
| 146 | ), |
| 147 | ( |
| 148 | "module_bzl.j2", |
| 149 | include_str!(concat!( |
| 150 | env!("CARGO_MANIFEST_DIR"), |
| 151 | "/src/rendering/templates/module_bzl.j2" |
| 152 | )), |
| 153 | ), |
| 154 | ( |
| 155 | "vendor_module.j2", |
| 156 | include_str!(concat!( |
| 157 | env!("CARGO_MANIFEST_DIR"), |
| 158 | "/src/rendering/templates/vendor_module.j2" |
| 159 | )), |
| 160 | ), |
| 161 | ]) |
| 162 | .unwrap(); |
| 163 | |
| 164 | tera.register_function( |
| 165 | "crate_build_file", |
| 166 | crate_build_file_fn_generator(render_config.build_file_template.clone()), |
| 167 | ); |
| 168 | tera.register_function( |
| 169 | "crate_label", |
| 170 | crate_label_fn_generator( |
| 171 | render_config.crate_label_template.clone(), |
| 172 | render_config.repository_name.clone(), |
| 173 | ), |
| 174 | ); |
| 175 | tera.register_function( |
| 176 | "crate_repository", |
| 177 | crate_repository_fn_generator( |
| 178 | render_config.crate_repository_template.clone(), |
| 179 | render_config.repository_name.clone(), |
| 180 | ), |
| 181 | ); |
| 182 | tera.register_function( |
| 183 | "platform_label", |
| 184 | platform_label_fn_generator(render_config.platforms_template.clone()), |
| 185 | ); |
| 186 | tera.register_function("sanitize_module_name", sanitize_module_name_fn); |
| 187 | tera.register_function( |
| 188 | "crates_module_label", |
| 189 | module_label_fn_generator(render_config.crates_module_template.clone()), |
| 190 | ); |
| 191 | |
| 192 | let mut context = tera::Context::new(); |
| 193 | context.insert("default_select_list", &SelectStringList::default()); |
| 194 | context.insert("default_select_dict", &SelectStringDict::default()); |
| 195 | context.insert("repository_name", &render_config.repository_name); |
| 196 | context.insert("vendor_mode", &render_config.vendor_mode); |
| 197 | context.insert("Null", &tera::Value::Null); |
| 198 | context.insert( |
| 199 | "default_package_name", |
| 200 | &match render_config.default_package_name.as_ref() { |
| 201 | Some(pkg_name) => format!("\"{}\"", pkg_name), |
| 202 | None => "None".to_owned(), |
| 203 | }, |
| 204 | ); |
| 205 | |
| 206 | Self { |
| 207 | engine: tera, |
| 208 | context, |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | fn new_tera_ctx(&self) -> tera::Context { |
| 213 | self.context.clone() |
| 214 | } |
| 215 | |
| 216 | pub fn render_crate_build_files<'a>( |
| 217 | &self, |
| 218 | ctx: &'a Context, |
| 219 | ) -> Result<HashMap<&'a CrateId, String>> { |
| 220 | // Create the render context with the global planned context to be |
| 221 | // reused when rendering crates. |
| 222 | let mut context = self.new_tera_ctx(); |
| 223 | context.insert("context", ctx); |
| 224 | |
| 225 | ctx.crates |
| 226 | .iter() |
| 227 | .map(|(id, _)| { |
| 228 | let aliases = ctx.crate_aliases(id, false, false); |
| 229 | let build_aliases = ctx.crate_aliases(id, true, false); |
| 230 | |
| 231 | context.insert("crate_id", &id); |
| 232 | context.insert("common_aliases", &aliases); |
| 233 | context.insert("build_aliases", &build_aliases); |
| 234 | |
| 235 | let content = self |
| 236 | .engine |
| 237 | .render("crate_build_file.j2", &context) |
| 238 | .context("Failed to render BUILD file")?; |
| 239 | |
| 240 | Ok((id, content)) |
| 241 | }) |
| 242 | .collect() |
| 243 | } |
| 244 | |
| 245 | pub fn render_module_build_file(&self, data: &Context) -> Result<String> { |
| 246 | let mut context = self.new_tera_ctx(); |
| 247 | context.insert("context", data); |
| 248 | |
| 249 | let workspace_member_deps = data.flat_workspace_member_deps(); |
| 250 | context.insert("workspace_member_dependencies", &workspace_member_deps); |
| 251 | |
| 252 | let binary_crates_map = data.flat_binary_deps(); |
| 253 | context.insert("binary_crates_map", &binary_crates_map); |
| 254 | |
| 255 | self.engine |
| 256 | .render("module_build_file.j2", &context) |
| 257 | .context("Failed to render crates module") |
| 258 | } |
| 259 | |
| 260 | pub fn render_module_bzl(&self, data: &Context) -> Result<String> { |
| 261 | let mut context = self.new_tera_ctx(); |
| 262 | context.insert("context", data); |
| 263 | |
| 264 | self.engine |
| 265 | .render("module_bzl.j2", &context) |
| 266 | .context("Failed to render crates module") |
| 267 | } |
| 268 | |
| 269 | pub fn render_vendor_module_file(&self, data: &Context) -> Result<String> { |
| 270 | let mut context = self.new_tera_ctx(); |
| 271 | context.insert("context", data); |
| 272 | |
| 273 | self.engine |
| 274 | .render("vendor_module.j2", &context) |
| 275 | .context("Failed to render vendor module") |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | /// A convienience wrapper for parsing parameters to tera functions |
| 280 | macro_rules! parse_tera_param { |
| 281 | ($param:literal, $param_type:ty, $args:ident) => { |
| 282 | match $args.get($param) { |
| 283 | Some(val) => match from_value::<$param_type>(val.clone()) { |
| 284 | Ok(v) => v, |
| 285 | Err(_) => { |
| 286 | return Err(tera::Error::msg(format!( |
| 287 | "The `{}` paramater could not be parsed as a String.", |
| 288 | $param |
| 289 | ))) |
| 290 | } |
| 291 | }, |
| 292 | None => { |
| 293 | return Err(tera::Error::msg(format!( |
| 294 | "No `{}` parameter was passed.", |
| 295 | $param |
| 296 | ))) |
| 297 | } |
| 298 | } |
| 299 | }; |
| 300 | } |
| 301 | |
| 302 | /// Convert a crate name into a module name by applying transforms to invalid characters. |
| 303 | fn sanitize_module_name_fn(args: &HashMap<String, Value>) -> tera::Result<Value> { |
| 304 | let crate_name = parse_tera_param!("crate_name", String, args); |
| 305 | |
| 306 | match to_value(sanitize_module_name(&crate_name)) { |
| 307 | Ok(v) => Ok(v), |
| 308 | Err(_) => Err(tera::Error::msg("Failed to generate resulting module name")), |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | /// Convert a crate name into a module name by applying transforms to invalid characters. |
| 313 | fn platform_label_fn_generator(template: String) -> impl tera::Function { |
| 314 | Box::new( |
| 315 | move |args: &HashMap<String, Value>| -> tera::Result<Value> { |
| 316 | let triple = parse_tera_param!("triple", String, args); |
| 317 | match to_value(render_platform_constraint_label(&template, &triple)) { |
| 318 | Ok(v) => Ok(v), |
| 319 | Err(_) => Err(tera::Error::msg("Failed to generate resulting module name")), |
| 320 | } |
| 321 | }, |
| 322 | ) |
| 323 | } |
| 324 | |
| 325 | /// Convert a crate name into a module name by applying transforms to invalid characters. |
| 326 | fn crate_build_file_fn_generator(template: String) -> impl tera::Function { |
| 327 | Box::new( |
| 328 | move |args: &HashMap<String, Value>| -> tera::Result<Value> { |
| 329 | let name = parse_tera_param!("name", String, args); |
| 330 | let version = parse_tera_param!("version", String, args); |
| 331 | |
| 332 | match to_value(render_crate_build_file(&template, &name, &version)) { |
| 333 | Ok(v) => Ok(v), |
| 334 | Err(_) => Err(tera::Error::msg("Failed to generate crate's BUILD file")), |
| 335 | } |
| 336 | }, |
| 337 | ) |
| 338 | } |
| 339 | |
| 340 | /// Convert a file name to a Bazel label |
| 341 | fn module_label_fn_generator(template: String) -> impl tera::Function { |
| 342 | Box::new( |
| 343 | move |args: &HashMap<String, Value>| -> tera::Result<Value> { |
| 344 | let file = parse_tera_param!("file", String, args); |
| 345 | |
| 346 | let label = match render_module_label(&template, &file) { |
| 347 | Ok(v) => v, |
| 348 | Err(e) => return Err(tera::Error::msg(e)), |
| 349 | }; |
| 350 | |
| 351 | match to_value(label.to_string()) { |
| 352 | Ok(v) => Ok(v), |
| 353 | Err(_) => Err(tera::Error::msg("Failed to generate crate's BUILD file")), |
| 354 | } |
| 355 | }, |
| 356 | ) |
| 357 | } |
| 358 | |
| 359 | /// Convert a crate name into a module name by applying transforms to invalid characters. |
| 360 | fn crate_label_fn_generator(template: String, repository_name: String) -> impl tera::Function { |
| 361 | Box::new( |
| 362 | move |args: &HashMap<String, Value>| -> tera::Result<Value> { |
| 363 | let name = parse_tera_param!("name", String, args); |
| 364 | let version = parse_tera_param!("version", String, args); |
| 365 | let target = parse_tera_param!("target", String, args); |
| 366 | |
| 367 | match to_value(sanitize_repository_name(&render_crate_bazel_label( |
| 368 | &template, |
| 369 | &repository_name, |
| 370 | &name, |
| 371 | &version, |
| 372 | &target, |
| 373 | ))) { |
| 374 | Ok(v) => Ok(v), |
| 375 | Err(_) => Err(tera::Error::msg("Failed to generate crate's label")), |
| 376 | } |
| 377 | }, |
| 378 | ) |
| 379 | } |
| 380 | |
| 381 | /// Convert a crate name into a module name by applying transforms to invalid characters. |
| 382 | fn crate_repository_fn_generator(template: String, repository_name: String) -> impl tera::Function { |
| 383 | Box::new( |
| 384 | move |args: &HashMap<String, Value>| -> tera::Result<Value> { |
| 385 | let name = parse_tera_param!("name", String, args); |
| 386 | let version = parse_tera_param!("version", String, args); |
| 387 | |
| 388 | match to_value(sanitize_repository_name(&render_crate_bazel_repository( |
| 389 | &template, |
| 390 | &repository_name, |
| 391 | &name, |
| 392 | &version, |
| 393 | ))) { |
| 394 | Ok(v) => Ok(v), |
| 395 | Err(_) => Err(tera::Error::msg("Failed to generate crate repository name")), |
| 396 | } |
| 397 | }, |
| 398 | ) |
| 399 | } |