Browse Source

Adding Clippy/Rust Fmt to the pr workflow #333 (#367)

* Added clippy configuration file, added github action to run clippy, and changed line endings for rust fmt

* fix(cippliy-check-action) install webkit2gtk

* fix(clippy_check) add env variables

* refactor(tauri) fix clippy checks

* chore(tauri) use tauri_includedir_codegen v0.5.2

* fix(tests) dir tests

Co-authored-by: Lucas Fernandes Nogueira <lucasfernandesnog@gmail.com>
Ty Tracey 5 years ago
parent
commit
b114fb8c38

+ 16 - 0
.github/workflows/test-on-pr.yml

@@ -3,6 +3,22 @@ name: test library
 on: pull_request
 
 jobs:
+  clippy_check:
+    runs-on: ubuntu-latest
+    env:
+      TAURI_DIST_DIR: tauri/test/fixture/dist
+      TAURI_DIR: ../test/fixture/src-tauri
+    steps:
+      - uses: actions/checkout@v2
+      - name: install webkit2gtk
+        run: |
+          sudo apt-get update
+          sudo apt-get install -y webkit2gtk-4.0
+      - run: rustup component add clippy
+      - uses: actions-rs/clippy-check@v1
+        with:
+          token: ${{ secrets.GITHUB_TOKEN }}
+
   build-tauri-core:
     runs-on: ${{ matrix.platform }}
 

+ 0 - 0
clippy.toml


+ 1 - 1
rustfmt.toml

@@ -1,7 +1,7 @@
 max_width = 100
 hard_tabs = false
 tab_spaces = 2
-newline_style = "Auto"
+newline_style = "Unix"
 use_small_heuristics = "Default"
 reorder_imports = true
 reorder_modules = true

+ 3 - 3
tauri-api/src/command.rs

@@ -27,9 +27,9 @@ pub fn format_command(path: String, command: String) -> String {
 
 pub fn relative_command(command: String) -> crate::Result<String> {
   match std::env::current_exe()?.parent() {
-    Some(exe_dir) => return Ok(format_command(exe_dir.display().to_string(), command)),
+    Some(exe_dir) => Ok(format_command(exe_dir.display().to_string(), command)),
     None => {
-      return Err(crate::ErrorKind::Command("Could not evaluate executable dir".to_string()).into())
+      Err(crate::ErrorKind::Command("Could not evaluate executable dir".to_string()).into())
     }
   }
 }
@@ -54,7 +54,7 @@ pub fn spawn_relative_command(
 }
 
 pub fn binary_command(binary_name: String) -> crate::Result<String> {
-  return Ok(format!("{}-{}", binary_name, platform::target_triple()?));
+  Ok(format!("{}-{}", binary_name, platform::target_triple()?))
 }
 
 // tests for the commands functions.

+ 21 - 28
tauri-api/src/dir.rs

@@ -16,39 +16,33 @@ pub struct DiskEntry {
 }
 
 fn is_dir(file_name: String) -> crate::Result<bool> {
-  match metadata(file_name.to_string()) {
-    Ok(md) => return Result::Ok(md.is_dir()),
-    Err(err) => return Result::Err(err.to_string().into()),
-  };
+  match metadata(file_name) {
+    Ok(md) => Result::Ok(md.is_dir()),
+    Err(err) => Result::Err(err.to_string().into()),
+  }
 }
 
 pub fn walk_dir(path_copy: String) -> crate::Result<Vec<DiskEntry>> {
   println!("Trying to walk: {}", path_copy.as_str());
   let mut files_and_dirs: Vec<DiskEntry> = vec![];
   for result in Walk::new(path_copy) {
-    match result {
-      Ok(entry) => {
-        let display_value = entry.path().display();
-        let _dir_name = display_value.to_string();
-
-        match is_dir(display_value.to_string()) {
-          Ok(flag) => {
-            files_and_dirs.push(DiskEntry {
-              path: display_value.to_string(),
-              is_dir: flag,
-              name: display_value.to_string(),
-            });
-          }
-          Err(_) => {}
-        }
+    if let Ok(entry) = result {
+      let display_value = entry.path().display();
+      let _dir_name = display_value.to_string();
+
+      if let Ok(flag) = is_dir(display_value.to_string()) {
+        files_and_dirs.push(DiskEntry {
+          path: display_value.to_string(),
+          is_dir: flag,
+          name: display_value.to_string(),
+        });
       }
-      Err(_) => {}
     }
   }
-  return Result::Ok(files_and_dirs);
+  Result::Ok(files_and_dirs)
 }
 
-pub fn list_dir_contents(dir_path: &String) -> crate::Result<Vec<DiskEntry>> {
+pub fn list_dir_contents(dir_path: String) -> crate::Result<Vec<DiskEntry>> {
   fs::read_dir(dir_path)
     .map_err(|err| crate::Error::with_chain(err, "read string failed"))
     .and_then(|paths| {
@@ -83,11 +77,10 @@ mod test {
   #[quickcheck]
   fn qc_is_dir(f: String) -> bool {
     // is the string runs through is_dir and comes out as an OK result then it must be a DIR.
-    match is_dir(f.clone()) {
-      // check to see that the path exists.
-      Ok(_) => std::path::PathBuf::from(f).exists(),
-      // if is Err then string isn't a path nor a dir and function passes.
-      Err(_) => true,
+    if let Ok(_) = is_dir(f.clone()) {
+      std::path::PathBuf::from(f).exists()
+    } else {
+      true
     }
   }
 
@@ -154,7 +147,7 @@ mod test {
     let dir = String::from("test/");
 
     // call list_dir_contents on the dir string
-    let res = list_dir_contents(&dir);
+    let res = list_dir_contents(dir);
 
     // assert that the result is Ok()
     assert_ok!(&res);

+ 2 - 2
tauri-api/src/dir/utils.rs

@@ -1,4 +1,4 @@
 pub fn get_dir_name_from_path(path: String) -> String {
-  let path_collect: Vec<&str> = path.split("/").collect();
-  return path_collect[path_collect.len() - 1].to_string();
+  let path_collect: Vec<&str> = path.split('/').collect();
+  path_collect[path_collect.len() - 1].to_string()
 }

+ 3 - 3
tauri-api/src/rpc.rs

@@ -1,6 +1,6 @@
 pub fn format_callback(function_name: String, arg: String) -> String {
   let formatted_string = &format!("window[\"{}\"]({})", function_name, arg);
-  return formatted_string.to_string();
+  formatted_string.to_string()
 }
 
 pub fn format_callback_result(
@@ -9,8 +9,8 @@ pub fn format_callback_result(
   error_callback: String,
 ) -> String {
   match result {
-    Ok(res) => return format_callback(callback, res),
-    Err(err) => return format_callback(error_callback, format!("\"{}\"", err)),
+    Ok(res) => format_callback(callback, res),
+    Err(err) => format_callback(error_callback, format!("\"{}\"", err)),
   }
 }
 

+ 5 - 6
tauri-api/src/version.rs

@@ -1,15 +1,14 @@
 use semver::Version;
+use std::cmp::Ordering;
 
 /// Compare two semver versions
 pub fn compare(first: &str, second: &str) -> crate::Result<i32> {
   let v1 = Version::parse(first)?;
   let v2 = Version::parse(second)?;
-  if v1 > v2 {
-    Ok(-1)
-  } else if v1 == v2 {
-    Ok(0)
-  } else {
-    Ok(1)
+  match v1.cmp(&v2) {
+    Ordering::Greater => Ok(-1),
+    Ordering::Less => Ok(1),
+    Ordering::Equal => Ok(0)
   }
 }
 

+ 3 - 3
tauri-updater/src/http.rs

@@ -5,19 +5,19 @@ use std::io::{BufWriter, Write};
 
 pub(crate) mod link_value;
 
-pub fn get(url: &String) -> crate::Result<attohttpc::Response> {
+pub fn get(url: String) -> crate::Result<attohttpc::Response> {
   let response = attohttpc::get(url).send()?;
 
   Ok(response)
 }
 
-pub fn post_as_json<T: Serialize>(url: &String, payload: &T) -> crate::Result<attohttpc::Response> {
+pub fn post_as_json<T: Serialize>(url: String, payload: &T) -> crate::Result<attohttpc::Response> {
   let response = attohttpc::post(url).json(payload)?.send()?;
 
   Ok(response)
 }
 
-pub fn download<T: Write>(url: &String, dest: T, _display_progress: bool) -> crate::Result<()> {
+pub fn download<T: Write>(url: String, dest: T, _display_progress: bool) -> crate::Result<()> {
   set_ssl_vars!();
 
   let resp = get(url)?;

+ 1 - 1
tauri-updater/src/updater.rs

@@ -244,7 +244,7 @@ impl Update {
 
     self.println("Downloading...");
     http::download(
-      &self.release.download_url,
+      self.release.download_url.clone(),
       &mut tmp_archive,
       self.show_download_progress,
     )?;

+ 2 - 2
tauri-updater/src/updater/github.rs

@@ -10,7 +10,7 @@ pub fn get_latest_release(repo_owner: &str, repo_name: &str) -> crate::Result<Re
     "https://api.github.com/repos/{}/{}/releases/latest",
     repo_owner, repo_name
   );
-  let resp = http::get(&api_url)?;
+  let resp = http::get(api_url.clone())?;
   if !resp.status().is_success() {
     bail!(
       crate::ErrorKind::Network,
@@ -29,7 +29,7 @@ pub fn get_release_version(repo_owner: &str, repo_name: &str, ver: &str) -> crat
     "https://api.github.com/repos/{}/{}/releases/tags/{}",
     repo_owner, repo_name, ver
   );
-  let resp = http::get(&api_url)?;
+  let resp = http::get(api_url.clone())?;
   if !resp.status().is_success() {
     bail!(
       crate::ErrorKind::Network,

+ 1 - 1
tauri-updater/src/updater/github/release.rs

@@ -178,7 +178,7 @@ impl ReleaseList {
       )
     }
 
-    let releases = reader.json::<serde_json::Value>()?.clone();
+    let releases = reader.json::<serde_json::Value>()?;
     let releases = releases
       .as_array()
       .ok_or_else(|| format_err!(crate::ErrorKind::Network, "No releases found"))?;

+ 1 - 1
tauri/Cargo.toml

@@ -27,7 +27,7 @@ error-chain = "0.12.1"
 tauri-api = { version = "0.3",  path = "../tauri-api" }
 
 [build-dependencies]
-tauri_includedir_codegen = "0.5.1"
+tauri_includedir_codegen = "0.5.2"
 
 [dev-dependencies]
 proptest = "0.9.5"

+ 1 - 1
tauri/build.rs

@@ -7,7 +7,7 @@ pub fn main() {
   match std::env::var("TAURI_DIST_DIR") {
     Ok(dist_path) => {
       let inlined_assets = match std::env::var("TAURI_INLINED_ASSETS") {
-        Ok(assets) => assets.split("|").map(|s| s.to_string()).collect(),
+        Ok(assets) => assets.split('|').map(|s| s.to_string()).collect(),
         Err(_) => Vec::new(),
       };
       // include assets

+ 11 - 15
tauri/src/app.rs

@@ -2,11 +2,12 @@ use web_view::WebView;
 
 mod runner;
 
-//type FnMut(&mut InvokeHandler<WebView<'_, ()>>, &str) = FnMut(&mut FnMut(&mut InvokeHandler<WebView<'_, ()>>, &str)<WebView<'_, ()>>, &str);
+type InvokeHandler = Box<dyn FnMut(&mut WebView<'_, ()>, &str)>;
+type Setup = Box<dyn FnMut(&mut WebView<'_, ()>, String)>;
 
 pub struct App {
-  invoke_handler: Option<Box<dyn FnMut(&mut WebView<'_, ()>, &str)>>,
-  setup: Option<Box<dyn FnMut(&mut WebView<'_, ()>, String)>>,
+  invoke_handler: Option<InvokeHandler>,
+  setup: Option<Setup>,
   splashscreen_html: Option<String>,
 }
 
@@ -16,20 +17,14 @@ impl App {
   }
 
   pub(crate) fn run_invoke_handler(&mut self, webview: &mut WebView<'_, ()>, arg: &str) {
-    match self.invoke_handler {
-      Some(ref mut invoke_handler) => {
-        invoke_handler(webview, arg);
-      }
-      None => {}
+    if let Some(ref mut invoke_handler) = self.invoke_handler {
+      invoke_handler(webview, arg);
     }
   }
 
   pub(crate) fn run_setup(&mut self, webview: &mut WebView<'_, ()>, source: String) {
-    match self.setup {
-      Some(ref mut setup) => {
-        setup(webview, source);
-      }
-      None => {}
+    if let Some(ref mut setup) = self.setup {
+      setup(webview, source);
     }
   }
 
@@ -38,9 +33,10 @@ impl App {
   }
 }
 
+#[derive(Default)]
 pub struct AppBuilder {
-  invoke_handler: Option<Box<dyn FnMut(&mut WebView<'_, ()>, &str)>>,
-  setup: Option<Box<dyn FnMut(&mut WebView<'_, ()>, String)>>,
+  invoke_handler: Option<InvokeHandler>,
+  setup: Option<Setup>,
   splashscreen_html: Option<String>
 }
 

+ 1 - 1
tauri/src/app/runner.rs

@@ -9,7 +9,7 @@ use crate::config::{get, Config};
 use crate::tcp::{get_available_port, port_is_available};
 
 // JavaScript string literal
-const JS_STRING: &'static str = r#"
+const JS_STRING: &str = r#"
 if (window.onTauriInit !== void 0) {
   window.onTauriInit()
   window.onTauriInit = void 0

+ 2 - 2
tauri/src/config.rs

@@ -32,12 +32,12 @@ fn default_title() -> String {
 }
 
 fn default_window() -> WindowConfig {
-  return WindowConfig {
+  WindowConfig {
     width: default_width(),
     height: default_height(),
     resizable: default_resizable(),
     title: default_title(),
-  };
+  }
 }
 
 #[derive(PartialEq, Deserialize, Clone, Debug)]

+ 1 - 1
tauri/src/endpoints.rs

@@ -204,7 +204,7 @@ fn load_asset<T: 'static>(
     webview,
     move || {
       let mut path = PathBuf::from(
-        if asset.starts_with("/") {
+        if asset.starts_with('/') {
           asset.replacen("/", "", 1)
         } else {
           asset.clone()

+ 2 - 4
tauri/src/file_system.rs

@@ -15,7 +15,7 @@ pub fn list<T: 'static>(
   crate::execute_promise(
     webview,
     move || {
-      dir::walk_dir(path.to_string())
+      dir::walk_dir(path)
         .map_err(|e| crate::ErrorKind::Command(e.to_string()).into())
         .and_then(|f| serde_json::to_string(&f).map_err(|err| err.into()))
     },
@@ -33,7 +33,7 @@ pub fn list_dirs<T: 'static>(
   crate::execute_promise(
     webview,
     move || {
-      dir::list_dir_contents(&path)
+      dir::list_dir_contents(path)
         .map_err(|e| crate::ErrorKind::Command(e.to_string()).into())
         .and_then(|f| serde_json::to_string(&f).map_err(|err| err.into()))
     },
@@ -79,7 +79,6 @@ pub fn read_text_file<T: 'static>(
         .and_then(|f| {
           serde_json::to_string(&f)
             .map_err(|err| err.into())
-            .map(|s| s.to_string())
         })
     },
     callback,
@@ -101,7 +100,6 @@ pub fn read_binary_file<T: 'static>(
         .and_then(|f| {
           serde_json::to_string(&f)
             .map_err(|err| err.into())
-            .map(|s| s.to_string())
         })
     },
     callback,

+ 2 - 2
tauri/src/salt.rs

@@ -22,7 +22,7 @@ pub fn generate() -> String {
       value: salt.to_string(),
       one_time: true,
     });
-  return salt.to_string();
+  salt.to_string()
 }
 
 pub fn generate_static() -> String {
@@ -34,7 +34,7 @@ pub fn generate_static() -> String {
       value: salt.to_string(),
       one_time: false,
     });
-  return salt.to_string();
+  salt.to_string()
 }
 
 pub fn is_valid(salt: String) -> bool {