Browse Source

chore(lint): unused variable warnings for release builds (#4411)

Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
Cyandev 3 years ago
parent
commit
45981851e3
4 changed files with 54 additions and 32 deletions
  1. 7 0
      .changes/unused-vars.md
  2. 4 7
      core/tauri-runtime-wry/src/lib.rs
  3. 28 0
      core/tauri-utils/src/lib.rs
  4. 15 25
      core/tauri/src/manager.rs

+ 7 - 0
.changes/unused-vars.md

@@ -0,0 +1,7 @@
+---
+"tauri-utils": patch
+"tauri-runtime-wry": patch
+"tauri": patch
+---
+
+Suppress unused variable warning in release builds.

+ 4 - 7
core/tauri-runtime-wry/src/lib.rs

@@ -39,7 +39,7 @@ use wry::application::platform::windows::{WindowBuilderExtWindows, WindowExtWind
 #[cfg(feature = "system-tray")]
 use wry::application::system_tray::{SystemTray as WrySystemTray, SystemTrayBuilder};
 
-use tauri_utils::{config::WindowConfig, Theme};
+use tauri_utils::{config::WindowConfig, debug_eprintln, Theme};
 use uuid::Uuid;
 use wry::{
   application::{
@@ -2435,8 +2435,7 @@ fn handle_user_message<T: UserEvent>(
           .and_then(|w| w.inner.as_ref())
         {
           if let Err(e) = webview.evaluate_script(&script) {
-            #[cfg(debug_assertions)]
-            eprintln!("{}", e);
+            debug_eprintln!("{}", e);
           }
         }
       }
@@ -2474,8 +2473,7 @@ fn handle_user_message<T: UserEvent>(
           .insert(window_id, webview);
       }
       Err(e) => {
-        #[cfg(debug_assertions)]
-        eprintln!("{}", e);
+        debug_eprintln!("{}", e);
       }
     },
     Message::CreateWindow(window_id, handler, sender) => {
@@ -2772,8 +2770,7 @@ fn handle_event_loop<T: UserEvent>(
             .and_then(|w| w.inner.as_ref())
           {
             if let Err(e) = webview.resize() {
-              #[cfg(debug_assertions)]
-              eprintln!("{}", e);
+              debug_eprintln!("{}", e);
             }
           }
         }

+ 28 - 0
core/tauri-utils/src/lib.rs

@@ -199,3 +199,31 @@ pub enum Error {
   #[error("could not walk directory `{0}`, try changing `allow_walk` to true on the `ResourcePaths` constructor.")]
   NotAllowedToWalkDir(std::path::PathBuf),
 }
+
+/// Suppresses the unused-variable warnings of the given inputs.
+///
+/// This does not move any values. Instead, it just suppresses the warning by taking a
+/// reference to the value.
+#[macro_export]
+macro_rules! consume_unused_variable {
+  ($($arg:expr),*) => {
+    $(
+      let _ = &$arg;
+    )*
+    ()
+  };
+}
+
+/// Prints to the standard error, with a newline.
+///
+/// Equivalent to the [`eprintln!`] macro, except that it's only effective for debug builds.
+#[macro_export]
+macro_rules! debug_eprintln {
+  () => ($crate::debug_eprintln!(""));
+  ($($arg:tt)*) => {
+    #[cfg(debug_assertions)]
+    eprintln!($($arg)*);
+    #[cfg(not(debug_assertions))]
+    $crate::consume_unused_variable!($($arg)*);
+  };
+}

+ 15 - 25
core/tauri/src/manager.rs

@@ -16,6 +16,7 @@ use serialize_to_javascript::{default_template, DefaultTemplate, Template};
 use url::Url;
 
 use tauri_macros::default_runtime;
+use tauri_utils::debug_eprintln;
 #[cfg(feature = "isolation")]
 use tauri_utils::pattern::isolation::RawIsolationPayload;
 use tauri_utils::{
@@ -95,8 +96,7 @@ fn set_csp<R: Runtime>(
             acc.style.push(hash.into());
           }
           _csp_hash => {
-            #[cfg(debug_assertions)]
-            eprintln!("Unknown CspHash variant encountered: {:?}", _csp_hash)
+            debug_eprintln!("Unknown CspHash variant encountered: {:?}", _csp_hash);
           }
         }
 
@@ -514,14 +514,12 @@ impl<R: Runtime> WindowManager<R> {
           .to_string();
 
         if let Err(e) = SafePathBuf::new(path.clone().into()) {
-          #[cfg(debug_assertions)]
-          eprintln!("asset protocol path \"{}\" is not valid: {}", path, e);
+          debug_eprintln!("asset protocol path \"{}\" is not valid: {}", path, e);
           return HttpResponseBuilder::new().status(403).body(Vec::new());
         }
 
         if !asset_scope.is_allowed(&path) {
-          #[cfg(debug_assertions)]
-          eprintln!("asset protocol not configured to allow the path: {}", path);
+          debug_eprintln!("asset protocol not configured to allow the path: {}", path);
           return HttpResponseBuilder::new().status(403).body(Vec::new());
         }
 
@@ -543,8 +541,7 @@ impl<R: Runtime> WindowManager<R> {
             let mut file = match tokio::fs::File::open(path_.clone()).await {
               Ok(file) => file,
               Err(e) => {
-                #[cfg(debug_assertions)]
-                eprintln!("Failed to open asset: {}", e);
+                debug_eprintln!("Failed to open asset: {}", e);
                 return (headers, 404, buf);
               }
             };
@@ -552,8 +549,7 @@ impl<R: Runtime> WindowManager<R> {
             let file_size = match file.metadata().await {
               Ok(metadata) => metadata.len(),
               Err(e) => {
-                #[cfg(debug_assertions)]
-                eprintln!("Failed to read asset metadata: {}", e);
+                debug_eprintln!("Failed to read asset metadata: {}", e);
                 return (headers, 404, buf);
               }
             };
@@ -568,8 +564,7 @@ impl<R: Runtime> WindowManager<R> {
             ) {
               Ok(r) => r,
               Err(e) => {
-                #[cfg(debug_assertions)]
-                eprintln!("Failed to parse range {}: {:?}", range, e);
+                debug_eprintln!("Failed to parse range {}: {:?}", range, e);
                 return (headers, 400, buf);
               }
             };
@@ -599,14 +594,12 @@ impl<R: Runtime> WindowManager<R> {
               );
 
               if let Err(e) = file.seek(std::io::SeekFrom::Start(range.start)).await {
-                #[cfg(debug_assertions)]
-                eprintln!("Failed to seek file to {}: {}", range.start, e);
+                debug_eprintln!("Failed to seek file to {}: {}", range.start, e);
                 return (headers, 422, buf);
               }
 
               if let Err(e) = file.take(real_length).read_to_end(&mut buf).await {
-                #[cfg(debug_assertions)]
-                eprintln!("Failed read file: {}", e);
+                debug_eprintln!("Failed read file: {}", e);
                 return (headers, 422, buf);
               }
               // partial content
@@ -631,8 +624,7 @@ impl<R: Runtime> WindowManager<R> {
               response.mimetype(&mime_type).body(data)
             }
             Err(e) => {
-              #[cfg(debug_assertions)]
-              eprintln!("Failed to read file: {}", e);
+              debug_eprintln!("Failed to read file: {}", e);
               response.status(404).body(Vec::new())
             }
           }
@@ -756,10 +748,10 @@ impl<R: Runtime> WindowManager<R> {
         asset
       })
       .or_else(|| {
-        #[cfg(debug_assertions)]
-        eprintln!(
+        debug_eprintln!(
           "Asset `{}` not found; fallback to {}/index.html",
-          path, path
+          path,
+          path
         );
         let fallback = format!("{}/index.html", path.as_str()).into();
         let asset = assets.get(&fallback);
@@ -767,8 +759,7 @@ impl<R: Runtime> WindowManager<R> {
         asset
       })
       .or_else(|| {
-        #[cfg(debug_assertions)]
-        eprintln!("Asset `{}` not found; fallback to index.html", path);
+        debug_eprintln!("Asset `{}` not found; fallback to index.html", path);
         let fallback = AssetKey::from("index.html");
         let asset = assets.get(&fallback);
         asset_path = fallback;
@@ -806,8 +797,7 @@ impl<R: Runtime> WindowManager<R> {
         })
       }
       Err(e) => {
-        #[cfg(debug_assertions)]
-        eprintln!("{:?}", e); // TODO log::error!
+        debug_eprintln!("{:?}", e); // TODO log::error!
         Err(Box::new(e))
       }
     }