template.rs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // Copyright 2019-2021 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. use std::{
  5. collections::BTreeMap,
  6. fs::{create_dir_all, File},
  7. io::Write,
  8. path::Path,
  9. };
  10. use handlebars::Handlebars;
  11. use include_dir::Dir;
  12. pub fn render<P: AsRef<Path>>(
  13. handlebars: &Handlebars,
  14. data: &BTreeMap<&str, serde_json::Value>,
  15. dir: &Dir,
  16. out_dir: P,
  17. ) -> crate::Result<()> {
  18. create_dir_all(out_dir.as_ref().join(dir.path()))?;
  19. for file in dir.files() {
  20. let mut file_path = file.path().to_path_buf();
  21. // cargo for some reason ignores the /templates folder packaging when it has a Cargo.toml file inside
  22. // so we rename the extension to `.crate-manifest`
  23. if let Some(extension) = file_path.extension() {
  24. if extension == "crate-manifest" {
  25. file_path.set_extension("toml");
  26. }
  27. }
  28. let mut output_file = File::create(out_dir.as_ref().join(file_path))?;
  29. if let Some(utf8) = file.contents_utf8() {
  30. handlebars
  31. .render_template_to_write(utf8, &data, &mut output_file)
  32. .expect("Failed to render template");
  33. } else {
  34. output_file.write_all(file.contents())?;
  35. }
  36. }
  37. for dir in dir.dirs() {
  38. render(handlebars, data, dir, out_dir.as_ref())?;
  39. }
  40. Ok(())
  41. }