Просмотр исходного кода

feat(api): Add `exists` function to the fs module. (#5060)

Co-authored-by: Amr Bashir <amr.bashir2015@gmail.com>
Co-authored-by: Lucas Fernandes Nogueira <lucas@tauri.studio>
Fabian-Lars 2 лет назад
Родитель
Сommit
3c62dbc902

+ 6 - 0
.changes/feat-exists-api.md

@@ -0,0 +1,6 @@
+---
+"api": minor
+"tauri": minor
+---
+
+Add `exists` function to the fs module.

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

@@ -1204,6 +1204,9 @@ pub struct FsAllowlistConfig {
   /// Rename file from local filesystem.
   #[serde(default, alias = "rename-file")]
   pub rename_file: bool,
+  /// Check if path exists on the local filesystem.
+  #[serde(default)]
+  pub exists: bool,
 }
 
 impl Allowlist for FsAllowlistConfig {
@@ -1219,6 +1222,7 @@ impl Allowlist for FsAllowlistConfig {
       remove_dir: true,
       remove_file: true,
       rename_file: true,
+      exists: true,
     };
     let mut features = allowlist.to_features();
     features.push("fs-all");
@@ -1238,6 +1242,7 @@ impl Allowlist for FsAllowlistConfig {
       check_feature!(self, features, remove_dir, "fs-remove-dir");
       check_feature!(self, features, remove_file, "fs-remove-file");
       check_feature!(self, features, rename_file, "fs-rename-file");
+      check_feature!(self, features, exists, "fs-exists");
       features
     }
   }

+ 2 - 0
core/tauri/Cargo.toml

@@ -195,6 +195,7 @@ dialog-save = [ "dialog" ]
 fs-all = [
   "fs-copy-file",
   "fs-create-dir",
+  "fs-exists",
   "fs-read-file",
   "fs-read-dir",
   "fs-remove-dir",
@@ -204,6 +205,7 @@ fs-all = [
 ]
 fs-copy-file = [ ]
 fs-create-dir = [ ]
+fs-exists = [ ]
 fs-read-file = [ ]
 fs-read-dir = [ ]
 fs-remove-dir = [ ]

+ 1 - 0
core/tauri/build.rs

@@ -59,6 +59,7 @@ fn main() {
       "remove-dir",
       "remove-file",
       "rename-file",
+      "exists",
     ],
     api_all,
   );

Разница между файлами не показана из-за своего большого размера
+ 0 - 0
core/tauri/scripts/bundle.js


+ 29 - 0
core/tauri/src/endpoints/file_system.rs

@@ -114,6 +114,12 @@ pub(crate) enum Cmd {
     new_path: SafePathBuf,
     options: Option<FileOperationOptions>,
   },
+  /// The exists API.
+  #[cmd(fs_exists, "fs > exists")]
+  Exists {
+    path: SafePathBuf,
+    options: Option<FileOperationOptions>,
+  },
 }
 
 impl Cmd {
@@ -339,6 +345,22 @@ impl Cmd {
       .with_context(|| format!("old: {}, new: {}", old.display(), new.display()))
       .map_err(Into::into)
   }
+
+  #[module_command_handler(fs_exists)]
+  fn exists<R: Runtime>(
+    context: InvokeContext<R>,
+    path: SafePathBuf,
+    options: Option<FileOperationOptions>,
+  ) -> super::Result<bool> {
+    let resolved_path = resolve_path(
+      &context.config,
+      &context.package_info,
+      &context.window,
+      path,
+      options.and_then(|o| o.dir),
+    )?;
+    Ok(resolved_path.as_ref().exists())
+  }
 }
 
 #[allow(dead_code)]
@@ -474,4 +496,11 @@ mod tests {
     );
     crate::test_utils::assert_not_allowlist_error(res);
   }
+
+  #[tauri_macros::module_command_test(fs_exists, "fs > exists")]
+  #[quickcheck_macros::quickcheck]
+  fn exists(path: SafePathBuf, options: Option<FileOperationOptions>) {
+    let res = super::Cmd::exists(crate::test::mock_invoke_context(), path, options);
+    crate::test_utils::assert_not_allowlist_error(res);
+  }
 }

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

@@ -69,6 +69,7 @@
 //! - **fs-all**: Enables all [Filesystem APIs](https://tauri.app/en/docs/api/js/modules/fs).
 //! - **fs-copy-file**: Enables the [`copyFile` API](https://tauri.app/en/docs/api/js/modules/fs#copyfile).
 //! - **fs-create-dir**: Enables the [`createDir` API](https://tauri.app/en/docs/api/js/modules/fs#createdir).
+//! - **fs-exists**: Enables the [`exists` API](https://tauri.app/en/docs/api/js/modules/fs#exists).
 //! - **fs-read-dir**: Enables the [`readDir` API](https://tauri.app/en/docs/api/js/modules/fs#readdir).
 //! - **fs-read-file**: Enables the [`readTextFile` API](https://tauri.app/en/docs/api/js/modules/fs#readtextfile) and the [`readBinaryFile` API](https://tauri.app/en/docs/api/js/modules/fs#readbinaryfile).
 //! - **fs-remove-dir**: Enables the [`removeDir` API](https://tauri.app/en/docs/api/js/modules/fs#removedir).

Разница между файлами не показана из-за своего большого размера
+ 0 - 0
examples/api/dist/assets/index.js


+ 26 - 2
tooling/api/src/fs.ts

@@ -21,7 +21,8 @@
  *         "createDir": true,
  *         "removeDir": true,
  *         "removeFile": true,
- *         "renameFile": true
+ *         "renameFile": true,
+ *         "exists": true
  *       }
  *     }
  *   }
@@ -550,6 +551,28 @@ async function renameFile(
   })
 }
 
+/**
+ * Check if a path exists.
+ * @example
+ * ```typescript
+ * import { exists, BaseDirectory } from '@tauri-apps/api/fs';
+ * // Check if the `$APPDIR/avatar.png` file exists
+ * await exists('avatar.png', { dir: BaseDirectory.App });
+ * ```
+ *
+ * @since 1.1.0
+ */
+async function exists(path: string, options: FsOptions = {}): Promise<void> {
+  return invokeTauriCommand({
+    __tauriModule: 'Fs',
+    message: {
+      cmd: 'exists',
+      path,
+      options
+    }
+  })
+}
+
 export type {
   FsOptions,
   FsDirOptions,
@@ -571,5 +594,6 @@ export {
   removeDir,
   copyFile,
   removeFile,
-  renameFile
+  renameFile,
+  exists
 }

+ 8 - 0
tooling/cli/schema.json

@@ -45,6 +45,7 @@
             "all": false,
             "copyFile": false,
             "createDir": false,
+            "exists": false,
             "readDir": false,
             "readFile": false,
             "removeDir": false,
@@ -306,6 +307,7 @@
               "all": false,
               "copyFile": false,
               "createDir": false,
+              "exists": false,
               "readDir": false,
               "readFile": false,
               "removeDir": false,
@@ -1498,6 +1500,7 @@
             "all": false,
             "copyFile": false,
             "createDir": false,
+            "exists": false,
             "readDir": false,
             "readFile": false,
             "removeDir": false,
@@ -1735,6 +1738,11 @@
           "description": "Rename file from local filesystem.",
           "default": false,
           "type": "boolean"
+        },
+        "exists": {
+          "description": "Check if path exists on the local filesystem.",
+          "default": false,
+          "type": "boolean"
         }
       },
       "additionalProperties": false

Некоторые файлы не были показаны из-за большого количества измененных файлов