plugin.rs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. //! Compile-time and runtime types for Tauri plugins.
  5. #[cfg(feature = "build")]
  6. pub use build::*;
  7. #[cfg(feature = "build")]
  8. mod build {
  9. use std::{
  10. env::vars_os,
  11. fs,
  12. path::{Path, PathBuf},
  13. };
  14. const GLOBAL_API_SCRIPT_PATH_KEY: &str = "GLOBAL_API_SCRIPT_PATH";
  15. /// Known file name of the file that contains an array with the path of all API scripts defined with [`define_global_api_script_path`].
  16. pub const GLOBAL_API_SCRIPT_FILE_LIST_PATH: &str = "__global-api-script.js";
  17. /// Defines the path to the global API script using Cargo instructions.
  18. pub fn define_global_api_script_path(path: PathBuf) {
  19. println!(
  20. "cargo:{GLOBAL_API_SCRIPT_PATH_KEY}={}",
  21. path
  22. .canonicalize()
  23. .expect("failed to canonicalize global API script path")
  24. .display()
  25. )
  26. }
  27. /// Collects the path of all the global API scripts defined with [`define_global_api_script_path`]
  28. /// and saves them to the out dir with filename [`GLOBAL_API_SCRIPT_FILE_LIST_PATH`].
  29. pub fn save_global_api_scripts_paths(out_dir: &Path) {
  30. let mut scripts = Vec::new();
  31. for (key, value) in vars_os() {
  32. let key = key.to_string_lossy();
  33. if key.starts_with("DEP_") && key.ends_with(GLOBAL_API_SCRIPT_PATH_KEY) {
  34. let script_path = PathBuf::from(value);
  35. scripts.push(script_path);
  36. }
  37. }
  38. fs::write(
  39. out_dir.join(GLOBAL_API_SCRIPT_FILE_LIST_PATH),
  40. serde_json::to_string(&scripts).expect("failed to serialize global API script paths"),
  41. )
  42. .expect("failed to write global API script");
  43. }
  44. /// Read global api scripts from [`GLOBAL_API_SCRIPT_FILE_LIST_PATH`]
  45. pub fn read_global_api_scripts(out_dir: &Path) -> Option<Vec<String>> {
  46. let global_scripts_path = out_dir.join(GLOBAL_API_SCRIPT_FILE_LIST_PATH);
  47. if !global_scripts_path.exists() {
  48. return None;
  49. }
  50. let global_scripts_str = fs::read_to_string(global_scripts_path)
  51. .expect("failed to read plugin global API script paths");
  52. let global_scripts = serde_json::from_str::<Vec<PathBuf>>(&global_scripts_str)
  53. .expect("failed to parse plugin global API script paths");
  54. Some(
  55. global_scripts
  56. .into_iter()
  57. .map(|p| {
  58. fs::read_to_string(&p).unwrap_or_else(|e| {
  59. panic!(
  60. "failed to read plugin global API script {}: {e}",
  61. p.display()
  62. )
  63. })
  64. })
  65. .collect(),
  66. )
  67. }
  68. }