tauri_utils/
plugin.rs

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