Skip to content

Commit

Permalink
add failable try_build for plugin builder (#10405)
Browse files Browse the repository at this point in the history
* 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 e23728e.
  • Loading branch information
chippers authored Jul 29, 2024
1 parent 289ae55 commit cf994a6
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changes/plugin-builder-failable.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"tauri": "patch:enhance"
---

Add `tauri::plugin::Builder::try_build` to allow plugins to check if their `TauriPlugin` initialization is valid.
33 changes: 29 additions & 4 deletions core/tauri/src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand Down Expand Up @@ -151,6 +152,17 @@ impl<R: Runtime, C: DeserializeOwned> PluginApi<R, C> {
}
}

/// 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.
Expand Down Expand Up @@ -616,9 +628,13 @@ impl<R: Runtime, C: DeserializeOwned> Builder<R, C> {
self
}

/// Builds the [TauriPlugin].
pub fn build(self) -> TauriPlugin<R, C> {
TauriPlugin {
/// Builds the [`TauriPlugin`].
pub fn try_build(self) -> Result<TauriPlugin<R, C>, 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,
Expand All @@ -631,7 +647,16 @@ impl<R: Runtime, C: DeserializeOwned> Builder<R, C> {
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<R, C> {
self.try_build().expect("valid plugin")
}
}

Expand Down

0 comments on commit cf994a6

Please sign in to comment.