From cf994a6bb064a50d3e5aef67e9a25903ee17a1e2 Mon Sep 17 00:00:00 2001 From: chip Date: Mon, 29 Jul 2024 22:51:56 +0900 Subject: [PATCH] add failable try_build for plugin builder (#10405) * add failable try_build for plugin builder * add changefile * implement `Hash`, `PartialEq` for `BuilderError` * mark config and acl items as unstable give some doc tips if they need to be used from Rust * Revert "mark config and acl items as unstable" [skip ci] This reverts commit e23728edb6d8d08187d3743bf9e6dc3214698ea5. --- .changes/plugin-builder-failable.md | 5 +++++ core/tauri/src/plugin.rs | 33 +++++++++++++++++++++++++---- 2 files changed, 34 insertions(+), 4 deletions(-) create mode 100644 .changes/plugin-builder-failable.md diff --git a/.changes/plugin-builder-failable.md b/.changes/plugin-builder-failable.md new file mode 100644 index 000000000..f3c675374 --- /dev/null +++ b/.changes/plugin-builder-failable.md @@ -0,0 +1,5 @@ +--- +"tauri": "patch:enhance" +--- + +Add `tauri::plugin::Builder::try_build` to allow plugins to check if their `TauriPlugin` initialization is valid. diff --git a/core/tauri/src/plugin.rs b/core/tauri/src/plugin.rs index 68875cb33..3bef88e73 100644 --- a/core/tauri/src/plugin.rs +++ b/core/tauri/src/plugin.rs @@ -15,6 +15,7 @@ use crate::{ use serde::de::DeserializeOwned; use serde_json::Value as JsonValue; use tauri_macros::default_runtime; +use thiserror::Error; use url::Url; use std::{ @@ -151,6 +152,17 @@ impl PluginApi { } } +/// Errors that can happen during [`Builder`]. +#[derive(Debug, Clone, Hash, PartialEq, Error)] +#[non_exhaustive] +pub enum BuilderError { + /// Plugin attempted to use a reserved name. + #[error("plugin uses reserved name: {0}")] + ReservedName(String), +} + +const RESERVED_PLUGIN_NAMES: &[&str] = &["core", "tauri"]; + /// Builds a [`TauriPlugin`]. /// /// This Builder offers a more concise way to construct Tauri plugins than implementing the Plugin trait directly. @@ -616,9 +628,13 @@ impl Builder { self } - /// Builds the [TauriPlugin]. - pub fn build(self) -> TauriPlugin { - TauriPlugin { + /// Builds the [`TauriPlugin`]. + pub fn try_build(self) -> Result, BuilderError> { + if let Some(&reserved) = RESERVED_PLUGIN_NAMES.iter().find(|&r| r == &self.name) { + return Err(BuilderError::ReservedName(reserved.into())); + } + + Ok(TauriPlugin { name: self.name, app: None, invoke_handler: self.invoke_handler, @@ -631,7 +647,16 @@ impl Builder { on_event: self.on_event, on_drop: self.on_drop, uri_scheme_protocols: self.uri_scheme_protocols, - } + }) + } + + /// Builds the [`TauriPlugin`]. + /// + /// # Panics + /// + /// If the builder returns an error during [`Self::try_build`], then this method will panic. + pub fn build(self) -> TauriPlugin { + self.try_build().expect("valid plugin") } }