Ver Fonte

feat: add `#[non_exhaustive]` attribute (#1725)

Lucas Fernandes Nogueira há 4 anos atrás
pai
commit
e087f0f937

+ 8 - 0
.changes/non-exhaustive.md

@@ -0,0 +1,8 @@
+---
+"tauri": patch
+"tauri-bundler": patch
+"tauri-codegen": patch
+"tauri-utils": patch
+---
+
+Added the `#[non_exhaustive] attribute where appropriate.

+ 5 - 0
.changes/remove-api-modules.md

@@ -0,0 +1,5 @@
+---
+"tauri": patch
+---
+
+Removed the `tcp` module from `tauri::api`.

+ 5 - 0
.changes/setup-error-send.md

@@ -0,0 +1,5 @@
+---
+"tauri": patch
+---
+
+The `setup` Error type must be `Send`.

+ 1 - 0
core/tauri-codegen/src/embedded_assets.rs

@@ -25,6 +25,7 @@ type Asset = (AssetKey, (PathBuf, PathBuf));
 
 /// All possible errors while reading and compressing an [`EmbeddedAssets`] directory
 #[derive(Debug, Error)]
+#[non_exhaustive]
 pub enum EmbeddedAssetsError {
   #[error("failed to read asset at {path} because {error}")]
   AssetRead {

+ 1 - 0
core/tauri-codegen/src/lib.rs

@@ -17,6 +17,7 @@ pub mod embedded_assets;
 
 /// Represents all the errors that can happen while reading the config.
 #[derive(Debug, Error)]
+#[non_exhaustive]
 pub enum ConfigError {
   #[error("unable to access current working directory: {0}")]
   CurrentDir(std::io::Error),

+ 0 - 1
core/tauri-utils/Cargo.toml

@@ -11,7 +11,6 @@ edition = "2018"
 [dependencies]
 serde = { version = "1.0", features = [ "derive" ] }
 serde_json = "1.0"
-sysinfo = "0.17"
 thiserror = "1.0.24"
 phf = { version = "0.8", features = [ "macros" ] }
 zstd = "0.8"

+ 1 - 0
core/tauri-utils/src/config.rs

@@ -11,6 +11,7 @@ use url::Url;
 /// The window webview URL options.
 #[derive(PartialEq, Debug, Clone, Deserialize)]
 #[serde(untagged)]
+#[non_exhaustive]
 pub enum WindowUrl {
   /// An external URL.
   External(Url),

+ 1 - 2
core/tauri-utils/src/lib.rs

@@ -13,14 +13,13 @@ pub mod config;
 pub mod html;
 /// Platform helpers
 pub mod platform;
-/// Process helpers
-pub mod process;
 
 /// Result type alias using the crate's error type.
 pub type Result<T> = std::result::Result<T, Error>;
 
 /// The error types.
 #[derive(Debug, thiserror::Error)]
+#[non_exhaustive]
 pub enum Error {
   /// Target triple architecture error
   #[error("Unable to determine target-architecture")]

+ 0 - 18
core/tauri-utils/src/process.rs

@@ -1,18 +0,0 @@
-// Copyright 2019-2021 Tauri Programme within The Commons Conservancy
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-License-Identifier: MIT
-
-use crate::Error;
-
-pub use sysinfo::{Process, ProcessExt, Signal, System, SystemExt};
-
-/// Gets the parent process
-pub fn get_parent_process(system: &mut sysinfo::System) -> Result<&Process, Error> {
-  let pid = sysinfo::get_current_pid().unwrap();
-  system.refresh_process(pid);
-  let current_process = system.get_process(pid).ok_or(Error::ParentProcess)?;
-  let parent_pid = current_process.parent().ok_or(Error::ParentPid)?;
-  let parent_process = system.get_process(parent_pid).ok_or(Error::ParentProcess)?;
-
-  Ok(parent_process)
-}

+ 3 - 0
core/tauri/src/api/cli.rs

@@ -16,6 +16,7 @@ mod macros;
 
 /// The resolution of a arg match.
 #[derive(Default, Debug, Serialize)]
+#[non_exhaustive]
 pub struct ArgData {
   /// The value of the arg.
   /// - Value::Bool if it's a flag,
@@ -30,6 +31,7 @@ pub struct ArgData {
 
 /// The matched subcommand.
 #[derive(Default, Debug, Serialize)]
+#[non_exhaustive]
 pub struct SubcommandMatches {
   /// The subcommand name.
   pub name: String,
@@ -39,6 +41,7 @@ pub struct SubcommandMatches {
 
 /// The arg matches of a command.
 #[derive(Default, Debug, Serialize)]
+#[non_exhaustive]
 pub struct Matches {
   /// Data structure mapping each found arg with its resolution.
   pub args: HashMap<String, ArgData>,

+ 1 - 0
core/tauri/src/api/dir.rs

@@ -14,6 +14,7 @@ use tempfile::{self, tempdir};
 /// A DiskEntry is either a file or a directory.
 /// The `children` Vec is always `Some` if the entry is a directory.
 #[derive(Debug, Serialize)]
+#[non_exhaustive]
 pub struct DiskEntry {
   /// The path to this entry.
   pub path: PathBuf,

+ 1 - 0
core/tauri/src/api/error.rs

@@ -4,6 +4,7 @@
 
 /// The error types.
 #[derive(thiserror::Error, Debug)]
+#[non_exhaustive]
 pub enum Error {
   /// Command error.
   #[error("Command Error: {0}")]

+ 2 - 0
core/tauri/src/api/file/extract.rs

@@ -8,6 +8,7 @@ use std::{fs, io, path};
 
 /// The supported archive formats.
 #[derive(Debug, Clone, Copy, PartialEq)]
+#[non_exhaustive]
 pub enum ArchiveFormat {
   /// Tar archive.
   Tar(Option<Compression>),
@@ -19,6 +20,7 @@ pub enum ArchiveFormat {
 
 /// The supported compression types.
 #[derive(Debug, Clone, Copy, PartialEq)]
+#[non_exhaustive]
 pub enum Compression {
   /// Gz compression (e.g. `.tar.gz` archives)
   Gz,

+ 3 - 0
core/tauri/src/api/http.rs

@@ -114,6 +114,7 @@ impl Client {
 
 #[derive(Serialize_repr, Deserialize_repr, Clone, Debug)]
 #[repr(u16)]
+#[non_exhaustive]
 /// The request's response type
 pub enum ResponseType {
   /// Read the response as JSON
@@ -127,6 +128,7 @@ pub enum ResponseType {
 /// FormBody data types.
 #[derive(Deserialize)]
 #[serde(untagged)]
+#[non_exhaustive]
 pub enum FormPart {
   /// A file path value.
   File(PathBuf),
@@ -150,6 +152,7 @@ impl FormBody {
 /// A body for the request.
 #[derive(Deserialize)]
 #[serde(tag = "type", content = "payload")]
+#[non_exhaustive]
 pub enum Body {
   /// A multipart formdata body.
   Form(FormBody),

+ 0 - 2
core/tauri/src/api/mod.rs

@@ -22,8 +22,6 @@ pub mod process;
 pub mod rpc;
 /// The shell api.
 pub mod shell;
-/// TCP ports access API.
-pub mod tcp;
 /// The semver API.
 pub mod version;
 

+ 1 - 0
core/tauri/src/api/path.rs

@@ -18,6 +18,7 @@ use serde_repr::{Deserialize_repr, Serialize_repr};
 /// For more information, check the [dirs_next documentation](https://docs.rs/dirs_next/).
 #[derive(Serialize_repr, Deserialize_repr, Clone, Debug)]
 #[repr(u16)]
+#[non_exhaustive]
 pub enum BaseDirectory {
   /// The Audio directory.
   Audio = 1,

+ 1 - 0
core/tauri/src/api/process.rs

@@ -37,6 +37,7 @@ pub struct TerminatedPayload {
 /// A event sent to the command callback.
 #[derive(Debug, Clone, Serialize)]
 #[serde(tag = "event", content = "payload")]
+#[non_exhaustive]
 pub enum CommandEvent {
   /// Stderr line.
   Stderr(String),

+ 0 - 26
core/tauri/src/api/tcp.rs

@@ -1,26 +0,0 @@
-// Copyright 2019-2021 Tauri Programme within The Commons Conservancy
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-License-Identifier: MIT
-
-use std::net::TcpListener;
-
-use rand::distributions::{Distribution, Uniform};
-
-/// Gets the first available port between 8000 and 9000.
-pub fn get_available_port() -> Option<u16> {
-  let mut rng = rand::thread_rng();
-  let die = Uniform::from(8000..9000);
-
-  for _i in 0..100 {
-    let port = die.sample(&mut rng);
-    if port_is_available(port) {
-      return Some(port);
-    }
-  }
-  None
-}
-
-/// Checks if the given port is available to use.
-pub fn port_is_available(port: u16) -> bool {
-  TcpListener::bind(("127.0.0.1", port)).is_ok()
-}

+ 4 - 3
core/tauri/src/error.rs

@@ -6,10 +6,11 @@ use std::path::PathBuf;
 
 /// Runtime errors that can happen inside a Tauri application.
 #[derive(Debug, thiserror::Error)]
+#[non_exhaustive]
 pub enum Error {
   /// Failed to create webview.
   #[error("failed to create webview: {0}")]
-  CreateWebview(String),
+  CreateWebview(Box<dyn std::error::Error + Send>),
   /// Failed to create window.
   #[error("failed to create window")]
   CreateWindow,
@@ -39,7 +40,7 @@ pub enum Error {
   Base64Decode(#[from] base64::DecodeError),
   /// Failed to load window icon.
   #[error("invalid icon: {0}")]
-  InvalidIcon(String),
+  InvalidIcon(Box<dyn std::error::Error + Send>),
   /// Client with specified ID not found.
   #[error("http client dropped or not initialized")]
   HttpClientNotInitialized,
@@ -54,7 +55,7 @@ pub enum Error {
   InvalidArgs(&'static str, serde_json::Error),
   /// Encountered an error in the setup hook,
   #[error("error encountered during setup hook: {0}")]
-  Setup(String),
+  Setup(Box<dyn std::error::Error + Send>),
   /// Tauri updater error.
   #[cfg(feature = "updater")]
   #[error("Updater: {0}")]

+ 2 - 1
core/tauri/src/hooks.rs

@@ -12,7 +12,8 @@ use serde_json::Value as JsonValue;
 use std::{future::Future, sync::Arc};
 
 /// A closure that is run when the Tauri application is setting up.
-pub type SetupHook<P> = Box<dyn Fn(&mut App<P>) -> Result<(), Box<dyn std::error::Error>> + Send>;
+pub type SetupHook<P> =
+  Box<dyn Fn(&mut App<P>) -> Result<(), Box<dyn std::error::Error + Send>> + Send>;
 
 /// A closure that is run everytime Tauri receives a message it doesn't explicitly handle.
 pub type InvokeHandler<P> = dyn Fn(Invoke<P>) + Send + Sync + 'static;

+ 1 - 0
core/tauri/src/lib.rs

@@ -106,6 +106,7 @@ macro_rules! tauri_build_context {
 
 /// A icon definition.
 #[derive(Debug, Clone)]
+#[non_exhaustive]
 pub enum Icon {
   /// Icon from file path.
   File(PathBuf),

+ 4 - 2
core/tauri/src/runtime/app.rs

@@ -163,7 +163,9 @@ where
   /// Defines the setup hook.
   pub fn setup<F>(mut self, setup: F) -> Self
   where
-    F: Fn(&mut App<Args<E, L, A, R>>) -> Result<(), Box<dyn std::error::Error>> + Send + 'static,
+    F: Fn(&mut App<Args<E, L, A, R>>) -> Result<(), Box<dyn std::error::Error + Send>>
+      + Send
+      + 'static,
   {
     self.setup = Box::new(setup);
     self
@@ -340,7 +342,7 @@ where
     #[cfg(feature = "updater")]
     app.run_updater(main_window);
 
-    (self.setup)(&mut app).map_err(|e| crate::Error::Setup(e.to_string()))?;
+    (self.setup)(&mut app).map_err(|e| crate::Error::Setup(e))?;
 
     app.runtime.run();
     Ok(())

+ 5 - 7
core/tauri/src/runtime/flavors/wry.rs

@@ -70,11 +70,9 @@ impl TryFrom<Icon> for WryIcon {
   type Error = crate::Error;
   fn try_from(icon: Icon) -> Result<Self, Self::Error> {
     let image = match icon {
-      Icon::File(path) => {
-        image::open(path).map_err(|e| crate::Error::InvalidIcon(e.to_string()))?
-      }
+      Icon::File(path) => image::open(path).map_err(|e| crate::Error::InvalidIcon(Box::new(e)))?,
       Icon::Raw(raw) => {
-        image::load_from_memory(&raw).map_err(|e| crate::Error::InvalidIcon(e.to_string()))?
+        image::load_from_memory(&raw).map_err(|e| crate::Error::InvalidIcon(Box::new(e)))?
       }
     };
     let (width, height) = image.dimensions();
@@ -83,7 +81,7 @@ impl TryFrom<Icon> for WryIcon {
       rgba.extend_from_slice(&pixel.to_rgba().0);
     }
     let icon = WindowIcon::from_rgba(rgba, width, height)
-      .map_err(|e| crate::Error::InvalidIcon(e.to_string()))?;
+      .map_err(|e| crate::Error::InvalidIcon(Box::new(e)))?;
     Ok(Self(icon))
   }
 }
@@ -813,7 +811,7 @@ fn create_webview<M: Params<Runtime = Wry>>(
 
   let window = window_attributes.build(event_loop).unwrap();
   let mut webview_builder = WebViewBuilder::new(window)
-    .map_err(|e| crate::Error::CreateWebview(e.to_string()))?
+    .map_err(|e| crate::Error::CreateWebview(Box::new(e)))?
     .with_url(&url)
     .unwrap(); // safe to unwrap because we validate the URL beforehand
   if let Some(handler) = rpc_handler {
@@ -842,7 +840,7 @@ fn create_webview<M: Params<Runtime = Wry>>(
 
   webview_builder
     .build()
-    .map_err(|e| crate::Error::CreateWebview(e.to_string()))
+    .map_err(|e| crate::Error::CreateWebview(Box::new(e)))
 }
 
 /// Create a wry rpc handler from a tauri rpc handler.

+ 1 - 0
core/tauri/src/runtime/manager.rs

@@ -468,6 +468,7 @@ impl<P: Params> WindowManager<P> {
         )
       }
       WindowUrl::External(url) => (url.as_str().starts_with("tauri://"), url.to_string()),
+      _ => unimplemented!(),
     };
 
     if is_local {

+ 2 - 0
core/tauri/src/runtime/webview.rs

@@ -137,6 +137,7 @@ pub trait WindowBuilder: WindowBuilderBase {
 }
 
 /// Rpc request.
+#[non_exhaustive]
 pub struct RpcRequest {
   /// RPC command.
   pub command: String,
@@ -152,6 +153,7 @@ pub struct CustomProtocol {
 
 /// The file drop event payload.
 #[derive(Debug, Clone)]
+#[non_exhaustive]
 pub enum FileDropEvent {
   /// The file(s) have been dragged onto the window, but have not been dropped yet.
   Hovered(Vec<PathBuf>),

+ 1 - 0
core/tauri/src/settings.rs

@@ -18,6 +18,7 @@ use std::{
 
 /// Tauri Settings.
 #[derive(Default, Deserialize, Serialize)]
+#[non_exhaustive]
 pub struct Settings {
   /// Whether the user allows notifications or not.
   #[cfg(notification_all)]

+ 1 - 0
core/tauri/src/updater/error.rs

@@ -6,6 +6,7 @@ use thiserror::Error;
 
 /// All errors that can occur while running the updater.
 #[derive(Debug, Error)]
+#[non_exhaustive]
 pub enum Error {
   /// IO Errors.
   #[error("`{0}`")]

+ 1 - 0
tooling/bundler/src/bundle/category.rs

@@ -15,6 +15,7 @@ const MACOS_APP_CATEGORY_PREFIX: &str = "public.app-category.";
 /// Corresponds to `LSApplicationCategoryType` on macOS and the GNOME desktop categories on Debian.
 #[allow(missing_docs)]
 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
+#[non_exhaustive]
 pub enum AppCategory {
   Business,
   DeveloperTool,

+ 1 - 0
tooling/bundler/src/bundle/settings.rs

@@ -12,6 +12,7 @@ use std::{
 
 /// The type of the package we're bundling.
 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
+#[non_exhaustive]
 pub enum PackageType {
   /// The macOS application bundle (.app).
   MacOsBundle,

+ 1 - 0
tooling/bundler/src/error.rs

@@ -7,6 +7,7 @@ use thiserror::Error as DeriveError;
 
 /// Errors returned by the bundler.
 #[derive(Debug, DeriveError)]
+#[non_exhaustive]
 pub enum Error {
   /// Bundler error.
   #[error("{0}")]