frontend.rs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. use crate::{
  5. helpers::{app_paths::walk_builder, npm::PackageManager},
  6. Result,
  7. };
  8. use std::{
  9. fs::{read_to_string, write},
  10. path::Path,
  11. process::Command,
  12. };
  13. const CORE_API_MODULES: &[&str] = &["dpi", "event", "path", "primitives", "window", "mocks"];
  14. const JS_EXTENSIONS: &[&str] = &["js", "jsx", "ts", "tsx", "mjs"];
  15. pub fn migrate(app_dir: &Path, tauri_dir: &Path) -> Result<()> {
  16. let mut new_npm_packages = Vec::new();
  17. let mut new_cargo_packages = Vec::new();
  18. let pm = PackageManager::from_project(app_dir)
  19. .into_iter()
  20. .next()
  21. .unwrap_or(PackageManager::Npm);
  22. let tauri_api_import_regex = regex::Regex::new(r"@tauri-apps/api/(\w+)").unwrap();
  23. for entry in walk_builder(app_dir).build().flatten() {
  24. if entry.file_type().map(|t| t.is_file()).unwrap_or_default() {
  25. let path = entry.path();
  26. let ext = path.extension().unwrap_or_default();
  27. if JS_EXTENSIONS.iter().any(|e| e == &ext) {
  28. let js_contents = read_to_string(path)?;
  29. let new_contents =
  30. tauri_api_import_regex.replace_all(&js_contents, |cap: &regex::Captures<'_>| {
  31. let module = cap.get(1).unwrap().as_str();
  32. let original = cap.get(0).unwrap().as_str();
  33. if module == "tauri" {
  34. let new = "@tauri-apps/api/primitives".to_string();
  35. log::info!("Replacing `{original}` with `{new}` on {}", path.display());
  36. new
  37. } else if CORE_API_MODULES.contains(&module) {
  38. original.to_string()
  39. } else {
  40. let plugin = format!("@tauri-apps/plugin-{module}");
  41. log::info!(
  42. "Replacing `{original}` with `{plugin}` on {}",
  43. path.display()
  44. );
  45. new_npm_packages.push(plugin.clone());
  46. new_cargo_packages.push(format!(
  47. "tauri-plugin-{}",
  48. if module == "clipboard" {
  49. "clipboard-manager"
  50. } else {
  51. module
  52. }
  53. ));
  54. plugin
  55. }
  56. });
  57. if new_contents != js_contents {
  58. write(path, new_contents.as_bytes())?;
  59. }
  60. }
  61. }
  62. }
  63. if !new_npm_packages.is_empty() {
  64. log::info!(
  65. "Installing NPM packages for plugins: {}",
  66. new_npm_packages.join(", ")
  67. );
  68. pm.install(&new_npm_packages)?;
  69. }
  70. if !new_cargo_packages.is_empty() {
  71. log::info!(
  72. "Installing Cargo dependencies for plugins: {}",
  73. new_cargo_packages.join(", ")
  74. );
  75. Command::new("cargo")
  76. .arg("add")
  77. .args(new_cargo_packages)
  78. .current_dir(tauri_dir)
  79. .status()?;
  80. }
  81. Ok(())
  82. }