├── android
├── .gitignore
├── src
│ ├── main
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── FsPlugin.kt
│ ├── test
│ │ └── java
│ │ │ └── ExampleUnitTest.kt
│ └── androidTest
│ │ └── java
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
├── settings.gradle
└── build.gradle.kts
├── banner.png
├── tsconfig.json
├── rollup.config.js
├── permissions
├── deny-default.toml
├── create-app-specific-dirs.toml
├── read-meta.toml
├── read-dirs.toml
├── write-files.toml
├── write-all.toml
├── autogenerated
│ ├── commands
│ │ ├── open.toml
│ │ ├── read.toml
│ │ ├── seek.toml
│ │ ├── size.toml
│ │ ├── stat.toml
│ │ ├── fstat.toml
│ │ ├── lstat.toml
│ │ ├── mkdir.toml
│ │ ├── watch.toml
│ │ ├── write.toml
│ │ ├── create.toml
│ │ ├── exists.toml
│ │ ├── remove.toml
│ │ ├── rename.toml
│ │ ├── unwatch.toml
│ │ ├── read_dir.toml
│ │ ├── truncate.toml
│ │ ├── copy_file.toml
│ │ ├── ftruncate.toml
│ │ ├── read_file.toml
│ │ ├── read_text_file.toml
│ │ ├── write_text_file.toml
│ │ ├── read_text_file_lines_next.toml
│ │ ├── write_file.toml
│ │ └── read_text_file_lines.toml
│ └── base-directories
│ │ ├── exe.toml
│ │ ├── log.toml
│ │ ├── data.toml
│ │ ├── font.toml
│ │ ├── home.toml
│ │ ├── temp.toml
│ │ ├── audio.toml
│ │ ├── cache.toml
│ │ ├── video.toml
│ │ ├── applog.toml
│ │ ├── config.toml
│ │ ├── public.toml
│ │ ├── appdata.toml
│ │ ├── desktop.toml
│ │ ├── picture.toml
│ │ ├── runtime.toml
│ │ ├── appcache.toml
│ │ ├── document.toml
│ │ ├── download.toml
│ │ ├── resource.toml
│ │ ├── template.toml
│ │ ├── appconfig.toml
│ │ ├── localdata.toml
│ │ └── applocaldata.toml
├── read-files.toml
├── read-app-specific-dirs-recursive.toml
├── read-all.toml
├── scope.toml
├── deny-webview-data.toml
├── default.toml
└── app.toml
├── src
├── scope.rs
├── models.rs
├── config.rs
├── desktop.rs
├── error.rs
├── watcher.rs
├── mobile.rs
├── file_path.rs
└── lib.rs
├── package.json
├── LICENSE.spdx
├── LICENSE_MIT
├── Cargo.toml
├── README.md
├── SECURITY.md
├── api-iife.js
├── LICENSE_APACHE-2.0
├── CHANGELOG.md
└── dist-js
└── index.js
/android/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 | /.tauri
3 |
--------------------------------------------------------------------------------
/banner.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tauri-apps/tauri-plugin-fs/HEAD/banner.png
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../../tsconfig.base.json",
3 | "include": ["guest-js/*.ts"]
4 | }
5 |
--------------------------------------------------------------------------------
/android/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/rollup.config.js:
--------------------------------------------------------------------------------
1 | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2 | // SPDX-License-Identifier: Apache-2.0
3 | // SPDX-License-Identifier: MIT
4 |
5 | import { createConfig } from '../../shared/rollup.config.js'
6 |
7 | export default createConfig()
8 |
--------------------------------------------------------------------------------
/permissions/deny-default.toml:
--------------------------------------------------------------------------------
1 | "$schema" = "schemas/schema.json"
2 |
3 | [[set]]
4 | identifier = "deny-default"
5 | description = "This denies access to dangerous Tauri relevant files and folders by default."
6 | permissions = ["deny-webview-data-linux", "deny-webview-data-windows"]
7 |
--------------------------------------------------------------------------------
/permissions/create-app-specific-dirs.toml:
--------------------------------------------------------------------------------
1 | "$schema" = "schemas/schema.json"
2 |
3 | [[permission]]
4 | identifier = "create-app-specific-dirs"
5 | description = """
6 | This permissions allows to create the application specific directories.
7 | """
8 | commands.allow = ["mkdir", "scope-app-index"]
9 |
--------------------------------------------------------------------------------
/permissions/read-meta.toml:
--------------------------------------------------------------------------------
1 | "$schema" = "schemas/schema.json"
2 |
3 | [[permission]]
4 | identifier = "read-meta"
5 | description = "This enables all index or metadata related commands without any pre-configured accessible paths."
6 | commands.allow = ["read_dir", "stat", "lstat", "fstat", "exists", "size"]
7 |
--------------------------------------------------------------------------------
/permissions/read-dirs.toml:
--------------------------------------------------------------------------------
1 | "$schema" = "schemas/schema.json"
2 |
3 | [[permission]]
4 | identifier = "read-dirs"
5 | description = "This enables directory read and file metadata related commands without any pre-configured accessible paths."
6 | commands.allow = ["read_dir", "stat", "lstat", "fstat", "exists"]
7 |
--------------------------------------------------------------------------------
/permissions/write-files.toml:
--------------------------------------------------------------------------------
1 | "$schema" = "schemas/schema.json"
2 |
3 | [[permission]]
4 | identifier = "write-files"
5 | description = "This enables all file write related commands without any pre-configured accessible paths."
6 | commands.allow = [
7 | "create",
8 | "copy_file",
9 | "remove",
10 | "rename",
11 | "truncate",
12 | "ftruncate",
13 | "write",
14 | "write_file",
15 | "write_text_file",
16 | ]
17 |
--------------------------------------------------------------------------------
/permissions/write-all.toml:
--------------------------------------------------------------------------------
1 | "$schema" = "schemas/schema.json"
2 |
3 | [[permission]]
4 | identifier = "write-all"
5 | description = "This enables all write related commands without any pre-configured accessible paths."
6 | commands.allow = [
7 | "mkdir",
8 | "create",
9 | "copy_file",
10 | "remove",
11 | "rename",
12 | "truncate",
13 | "ftruncate",
14 | "write",
15 | "write_file",
16 | "write_text_file",
17 | ]
18 |
--------------------------------------------------------------------------------
/permissions/autogenerated/commands/open.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | [[permission]]
6 | identifier = "allow-open"
7 | description = "Enables the open command without any pre-configured scope."
8 | commands.allow = ["open"]
9 |
10 | [[permission]]
11 | identifier = "deny-open"
12 | description = "Denies the open command without any pre-configured scope."
13 | commands.deny = ["open"]
14 |
--------------------------------------------------------------------------------
/permissions/autogenerated/commands/read.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | [[permission]]
6 | identifier = "allow-read"
7 | description = "Enables the read command without any pre-configured scope."
8 | commands.allow = ["read"]
9 |
10 | [[permission]]
11 | identifier = "deny-read"
12 | description = "Denies the read command without any pre-configured scope."
13 | commands.deny = ["read"]
14 |
--------------------------------------------------------------------------------
/permissions/autogenerated/commands/seek.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | [[permission]]
6 | identifier = "allow-seek"
7 | description = "Enables the seek command without any pre-configured scope."
8 | commands.allow = ["seek"]
9 |
10 | [[permission]]
11 | identifier = "deny-seek"
12 | description = "Denies the seek command without any pre-configured scope."
13 | commands.deny = ["seek"]
14 |
--------------------------------------------------------------------------------
/permissions/autogenerated/commands/size.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | [[permission]]
6 | identifier = "allow-size"
7 | description = "Enables the size command without any pre-configured scope."
8 | commands.allow = ["size"]
9 |
10 | [[permission]]
11 | identifier = "deny-size"
12 | description = "Denies the size command without any pre-configured scope."
13 | commands.deny = ["size"]
14 |
--------------------------------------------------------------------------------
/permissions/autogenerated/commands/stat.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | [[permission]]
6 | identifier = "allow-stat"
7 | description = "Enables the stat command without any pre-configured scope."
8 | commands.allow = ["stat"]
9 |
10 | [[permission]]
11 | identifier = "deny-stat"
12 | description = "Denies the stat command without any pre-configured scope."
13 | commands.deny = ["stat"]
14 |
--------------------------------------------------------------------------------
/permissions/autogenerated/commands/fstat.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | [[permission]]
6 | identifier = "allow-fstat"
7 | description = "Enables the fstat command without any pre-configured scope."
8 | commands.allow = ["fstat"]
9 |
10 | [[permission]]
11 | identifier = "deny-fstat"
12 | description = "Denies the fstat command without any pre-configured scope."
13 | commands.deny = ["fstat"]
14 |
--------------------------------------------------------------------------------
/permissions/autogenerated/commands/lstat.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | [[permission]]
6 | identifier = "allow-lstat"
7 | description = "Enables the lstat command without any pre-configured scope."
8 | commands.allow = ["lstat"]
9 |
10 | [[permission]]
11 | identifier = "deny-lstat"
12 | description = "Denies the lstat command without any pre-configured scope."
13 | commands.deny = ["lstat"]
14 |
--------------------------------------------------------------------------------
/permissions/autogenerated/commands/mkdir.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | [[permission]]
6 | identifier = "allow-mkdir"
7 | description = "Enables the mkdir command without any pre-configured scope."
8 | commands.allow = ["mkdir"]
9 |
10 | [[permission]]
11 | identifier = "deny-mkdir"
12 | description = "Denies the mkdir command without any pre-configured scope."
13 | commands.deny = ["mkdir"]
14 |
--------------------------------------------------------------------------------
/permissions/autogenerated/commands/watch.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | [[permission]]
6 | identifier = "allow-watch"
7 | description = "Enables the watch command without any pre-configured scope."
8 | commands.allow = ["watch"]
9 |
10 | [[permission]]
11 | identifier = "deny-watch"
12 | description = "Denies the watch command without any pre-configured scope."
13 | commands.deny = ["watch"]
14 |
--------------------------------------------------------------------------------
/permissions/autogenerated/commands/write.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | [[permission]]
6 | identifier = "allow-write"
7 | description = "Enables the write command without any pre-configured scope."
8 | commands.allow = ["write"]
9 |
10 | [[permission]]
11 | identifier = "deny-write"
12 | description = "Denies the write command without any pre-configured scope."
13 | commands.deny = ["write"]
14 |
--------------------------------------------------------------------------------
/permissions/read-files.toml:
--------------------------------------------------------------------------------
1 | "$schema" = "schemas/schema.json"
2 |
3 | [[permission]]
4 | identifier = "read-files"
5 | description = "This enables file read related commands without any pre-configured accessible paths."
6 | commands.allow = [
7 | "read_file",
8 | "read",
9 | "open",
10 | "read_text_file",
11 | "read_text_file_lines",
12 | "read_text_file_lines_next",
13 | "seek",
14 | "stat",
15 | "lstat",
16 | "fstat",
17 | "exists",
18 |
19 | ]
20 |
--------------------------------------------------------------------------------
/permissions/autogenerated/commands/create.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | [[permission]]
6 | identifier = "allow-create"
7 | description = "Enables the create command without any pre-configured scope."
8 | commands.allow = ["create"]
9 |
10 | [[permission]]
11 | identifier = "deny-create"
12 | description = "Denies the create command without any pre-configured scope."
13 | commands.deny = ["create"]
14 |
--------------------------------------------------------------------------------
/permissions/autogenerated/commands/exists.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | [[permission]]
6 | identifier = "allow-exists"
7 | description = "Enables the exists command without any pre-configured scope."
8 | commands.allow = ["exists"]
9 |
10 | [[permission]]
11 | identifier = "deny-exists"
12 | description = "Denies the exists command without any pre-configured scope."
13 | commands.deny = ["exists"]
14 |
--------------------------------------------------------------------------------
/permissions/autogenerated/commands/remove.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | [[permission]]
6 | identifier = "allow-remove"
7 | description = "Enables the remove command without any pre-configured scope."
8 | commands.allow = ["remove"]
9 |
10 | [[permission]]
11 | identifier = "deny-remove"
12 | description = "Denies the remove command without any pre-configured scope."
13 | commands.deny = ["remove"]
14 |
--------------------------------------------------------------------------------
/permissions/autogenerated/commands/rename.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | [[permission]]
6 | identifier = "allow-rename"
7 | description = "Enables the rename command without any pre-configured scope."
8 | commands.allow = ["rename"]
9 |
10 | [[permission]]
11 | identifier = "deny-rename"
12 | description = "Denies the rename command without any pre-configured scope."
13 | commands.deny = ["rename"]
14 |
--------------------------------------------------------------------------------
/src/scope.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2 | // SPDX-License-Identifier: Apache-2.0
3 | // SPDX-License-Identifier: MIT
4 |
5 | use std::path::PathBuf;
6 |
7 | use serde::Deserialize;
8 |
9 | #[derive(Debug)]
10 | pub struct Entry {
11 | pub path: Option,
12 | }
13 |
14 | #[derive(Deserialize)]
15 | #[serde(untagged)]
16 | pub(crate) enum EntryRaw {
17 | Value(PathBuf),
18 | Object { path: PathBuf },
19 | }
20 |
--------------------------------------------------------------------------------
/permissions/autogenerated/commands/unwatch.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | [[permission]]
6 | identifier = "allow-unwatch"
7 | description = "Enables the unwatch command without any pre-configured scope."
8 | commands.allow = ["unwatch"]
9 |
10 | [[permission]]
11 | identifier = "deny-unwatch"
12 | description = "Denies the unwatch command without any pre-configured scope."
13 | commands.deny = ["unwatch"]
14 |
--------------------------------------------------------------------------------
/permissions/autogenerated/commands/read_dir.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | [[permission]]
6 | identifier = "allow-read-dir"
7 | description = "Enables the read_dir command without any pre-configured scope."
8 | commands.allow = ["read_dir"]
9 |
10 | [[permission]]
11 | identifier = "deny-read-dir"
12 | description = "Denies the read_dir command without any pre-configured scope."
13 | commands.deny = ["read_dir"]
14 |
--------------------------------------------------------------------------------
/permissions/autogenerated/commands/truncate.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | [[permission]]
6 | identifier = "allow-truncate"
7 | description = "Enables the truncate command without any pre-configured scope."
8 | commands.allow = ["truncate"]
9 |
10 | [[permission]]
11 | identifier = "deny-truncate"
12 | description = "Denies the truncate command without any pre-configured scope."
13 | commands.deny = ["truncate"]
14 |
--------------------------------------------------------------------------------
/permissions/autogenerated/commands/copy_file.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | [[permission]]
6 | identifier = "allow-copy-file"
7 | description = "Enables the copy_file command without any pre-configured scope."
8 | commands.allow = ["copy_file"]
9 |
10 | [[permission]]
11 | identifier = "deny-copy-file"
12 | description = "Denies the copy_file command without any pre-configured scope."
13 | commands.deny = ["copy_file"]
14 |
--------------------------------------------------------------------------------
/permissions/autogenerated/commands/ftruncate.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | [[permission]]
6 | identifier = "allow-ftruncate"
7 | description = "Enables the ftruncate command without any pre-configured scope."
8 | commands.allow = ["ftruncate"]
9 |
10 | [[permission]]
11 | identifier = "deny-ftruncate"
12 | description = "Denies the ftruncate command without any pre-configured scope."
13 | commands.deny = ["ftruncate"]
14 |
--------------------------------------------------------------------------------
/permissions/autogenerated/commands/read_file.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | [[permission]]
6 | identifier = "allow-read-file"
7 | description = "Enables the read_file command without any pre-configured scope."
8 | commands.allow = ["read_file"]
9 |
10 | [[permission]]
11 | identifier = "deny-read-file"
12 | description = "Denies the read_file command without any pre-configured scope."
13 | commands.deny = ["read_file"]
14 |
--------------------------------------------------------------------------------
/permissions/read-app-specific-dirs-recursive.toml:
--------------------------------------------------------------------------------
1 | "$schema" = "schemas/schema.json"
2 |
3 | [[permission]]
4 | identifier = "read-app-specific-dirs-recursive"
5 | description = """
6 | This permission allows recursive read functionality on the application
7 | specific base directories.
8 | """
9 | commands.allow = [
10 | "read_dir",
11 | "read_file",
12 | "read_text_file",
13 | "read_text_file_lines",
14 | "read_text_file_lines_next",
15 | "exists",
16 | "scope-app-recursive",
17 | ]
18 |
--------------------------------------------------------------------------------
/permissions/read-all.toml:
--------------------------------------------------------------------------------
1 | "$schema" = "schemas/schema.json"
2 |
3 | [[permission]]
4 | identifier = "read-all"
5 | description = "This enables all read related commands without any pre-configured accessible paths."
6 | commands.allow = [
7 | "read_dir",
8 | "read_file",
9 | "read",
10 | "open",
11 | "read_text_file",
12 | "read_text_file_lines",
13 | "read_text_file_lines_next",
14 | "seek",
15 | "stat",
16 | "lstat",
17 | "fstat",
18 | "exists",
19 | "watch",
20 | "unwatch",
21 | ]
22 |
--------------------------------------------------------------------------------
/permissions/autogenerated/commands/read_text_file.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | [[permission]]
6 | identifier = "allow-read-text-file"
7 | description = "Enables the read_text_file command without any pre-configured scope."
8 | commands.allow = ["read_text_file"]
9 |
10 | [[permission]]
11 | identifier = "deny-read-text-file"
12 | description = "Denies the read_text_file command without any pre-configured scope."
13 | commands.deny = ["read_text_file"]
14 |
--------------------------------------------------------------------------------
/permissions/autogenerated/commands/write_text_file.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | [[permission]]
6 | identifier = "allow-write-text-file"
7 | description = "Enables the write_text_file command without any pre-configured scope."
8 | commands.allow = ["write_text_file"]
9 |
10 | [[permission]]
11 | identifier = "deny-write-text-file"
12 | description = "Denies the write_text_file command without any pre-configured scope."
13 | commands.deny = ["write_text_file"]
14 |
--------------------------------------------------------------------------------
/permissions/scope.toml:
--------------------------------------------------------------------------------
1 | "$schema" = "schemas/schema.json"
2 |
3 | [[permission]]
4 | identifier = "scope"
5 | description = """
6 | An empty permission you can use to modify the global scope.
7 |
8 | ## Example
9 |
10 | ```json
11 | {
12 | "identifier": "read-documents",
13 | "windows": ["main"],
14 | "permissions": [
15 | "fs:allow-read",
16 | {
17 | "identifier": "fs:scope",
18 | "allow": [
19 | "$APPDATA/documents/**/*"
20 | ],
21 | "deny": [
22 | "$APPDATA/documents/secret.txt"
23 | ]
24 | }
25 | ]
26 | }
27 | ```
28 | """
29 |
--------------------------------------------------------------------------------
/src/models.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2 | // SPDX-License-Identifier: Apache-2.0
3 | // SPDX-License-Identifier: MIT
4 |
5 | use serde::{Deserialize, Serialize};
6 |
7 | #[derive(Debug, Clone, Default, Deserialize, Serialize)]
8 | #[serde(rename_all = "camelCase")]
9 | pub struct GetFileDescriptorPayload {
10 | pub uri: String,
11 | pub mode: String,
12 | }
13 |
14 | #[derive(Debug, Clone, Default, Deserialize, Serialize)]
15 | #[serde(rename_all = "camelCase")]
16 | pub struct GetFileDescriptorResponse {
17 | pub fd: Option,
18 | }
19 |
--------------------------------------------------------------------------------
/permissions/autogenerated/commands/read_text_file_lines_next.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | [[permission]]
6 | identifier = "allow-read-text-file-lines-next"
7 | description = "Enables the read_text_file_lines_next command without any pre-configured scope."
8 | commands.allow = ["read_text_file_lines_next"]
9 |
10 | [[permission]]
11 | identifier = "deny-read-text-file-lines-next"
12 | description = "Denies the read_text_file_lines_next command without any pre-configured scope."
13 | commands.deny = ["read_text_file_lines_next"]
14 |
--------------------------------------------------------------------------------
/android/src/test/java/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2 | // SPDX-License-Identifier: Apache-2.0
3 | // SPDX-License-Identifier: MIT
4 |
5 | package com.plugin.fs
6 |
7 | import org.junit.Test
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Example local unit test, which will execute on the development machine (host).
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | class ExampleUnitTest {
17 | @Test
18 | fun addition_isCorrect() {
19 | assertEquals(4, 2 + 2)
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/permissions/autogenerated/commands/write_file.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | [[permission]]
6 | identifier = "allow-write-file"
7 | description = "Enables the write_file command without any pre-configured scope."
8 |
9 | [permission.commands]
10 | allow = [
11 | "write_file",
12 | "open",
13 | "write",
14 | ]
15 | deny = []
16 |
17 | [[permission]]
18 | identifier = "deny-write-file"
19 | description = "Denies the write_file command without any pre-configured scope."
20 |
21 | [permission.commands]
22 | allow = []
23 | deny = ["write_file"]
24 |
--------------------------------------------------------------------------------
/permissions/autogenerated/commands/read_text_file_lines.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | [[permission]]
6 | identifier = "allow-read-text-file-lines"
7 | description = "Enables the read_text_file_lines command without any pre-configured scope."
8 |
9 | [permission.commands]
10 | allow = [
11 | "read_text_file_lines",
12 | "read_text_file_lines_next",
13 | ]
14 | deny = []
15 |
16 | [[permission]]
17 | identifier = "deny-read-text-file-lines"
18 | description = "Denies the read_text_file_lines command without any pre-configured scope."
19 |
20 | [permission.commands]
21 | allow = []
22 | deny = ["read_text_file_lines"]
23 |
--------------------------------------------------------------------------------
/permissions/deny-webview-data.toml:
--------------------------------------------------------------------------------
1 | "$schema" = "schemas/schema.json"
2 |
3 | [[permission]]
4 | identifier = "deny-webview-data-linux"
5 | description = """This denies read access to the
6 | `$APPLOCALDATA` folder on linux as the webview data and configuration values are stored here.
7 | Allowing access can lead to sensitive information disclosure and should be well considered."""
8 |
9 | [[scope.deny]]
10 | path = "$APPLOCALDATA/**"
11 |
12 | [[permission]]
13 | identifier = "deny-webview-data-windows"
14 | description = """This denies read access to the
15 | `$APPLOCALDATA/EBWebView` folder on windows as the webview data and configuration values are stored here.
16 | Allowing access can lead to sensitive information disclosure and should be well considered."""
17 |
18 | [[scope.deny]]
19 | path = "$APPLOCALDATA/EBWebView/**"
20 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@tauri-apps/plugin-fs",
3 | "version": "2.4.4",
4 | "description": "Access the file system.",
5 | "license": "MIT OR Apache-2.0",
6 | "authors": [
7 | "Tauri Programme within The Commons Conservancy"
8 | ],
9 | "repository": "https://github.com/tauri-apps/plugins-workspace",
10 | "type": "module",
11 | "types": "./dist-js/index.d.ts",
12 | "main": "./dist-js/index.cjs",
13 | "module": "./dist-js/index.js",
14 | "exports": {
15 | "types": "./dist-js/index.d.ts",
16 | "import": "./dist-js/index.js",
17 | "require": "./dist-js/index.cjs"
18 | },
19 | "scripts": {
20 | "build": "rollup -c"
21 | },
22 | "files": [
23 | "dist-js",
24 | "README.md",
25 | "LICENSE"
26 | ],
27 | "dependencies": {
28 | "@tauri-apps/api": "^2.8.0"
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/android/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/android/settings.gradle:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | mavenCentral()
4 | gradlePluginPortal()
5 | google()
6 | }
7 | resolutionStrategy {
8 | eachPlugin {
9 | switch (requested.id.id) {
10 | case "com.android.library":
11 | useVersion("8.0.2")
12 | break
13 | case "org.jetbrains.kotlin.android":
14 | useVersion("1.8.20")
15 | break
16 | }
17 | }
18 | }
19 | }
20 |
21 | dependencyResolutionManagement {
22 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
23 | repositories {
24 | mavenCentral()
25 | google()
26 |
27 | }
28 | }
29 |
30 | include ':tauri-android'
31 | project(':tauri-android').projectDir = new File('./.tauri/tauri-api')
32 |
--------------------------------------------------------------------------------
/src/config.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2 | // SPDX-License-Identifier: Apache-2.0
3 | // SPDX-License-Identifier: MIT
4 |
5 | use serde::Deserialize;
6 |
7 | #[derive(Deserialize)]
8 | #[serde(rename_all = "camelCase", deny_unknown_fields)]
9 | pub struct Config {
10 | /// Whether or not paths that contain components that start with a `.`
11 | /// will require that `.` appears literally in the pattern; `*`, `?`, `**`,
12 | /// or `[...]` will not match. This is useful because such files are
13 | /// conventionally considered hidden on Unix systems and it might be
14 | /// desirable to skip them when listing files.
15 | ///
16 | /// Defaults to `true` on Unix systems and `false` on Windows
17 | // dotfiles are not supposed to be exposed by default on unix
18 | pub require_literal_leading_dot: Option,
19 | }
20 |
--------------------------------------------------------------------------------
/android/src/androidTest/java/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2 | // SPDX-License-Identifier: Apache-2.0
3 | // SPDX-License-Identifier: MIT
4 |
5 | package com.plugin.fs
6 |
7 | import androidx.test.platform.app.InstrumentationRegistry
8 | import androidx.test.ext.junit.runners.AndroidJUnit4
9 |
10 | import org.junit.Test
11 | import org.junit.runner.RunWith
12 |
13 | import org.junit.Assert.*
14 |
15 | /**
16 | * Instrumented test, which will execute on an Android device.
17 | *
18 | * See [testing documentation](http://d.android.com/tools/testing).
19 | */
20 | @RunWith(AndroidJUnit4::class)
21 | class ExampleInstrumentedTest {
22 | @Test
23 | fun useAppContext() {
24 | // Context of the app under test.
25 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
26 | assertEquals("com.plugin.fs", appContext.packageName)
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/LICENSE.spdx:
--------------------------------------------------------------------------------
1 | SPDXVersion: SPDX-2.1
2 | DataLicense: CC0-1.0
3 | PackageName: tauri
4 | DataFormat: SPDXRef-1
5 | PackageSupplier: Organization: The Tauri Programme in the Commons Conservancy
6 | PackageHomePage: https://tauri.app
7 | PackageLicenseDeclared: Apache-2.0
8 | PackageLicenseDeclared: MIT
9 | PackageCopyrightText: 2019-2022, The Tauri Programme in the Commons Conservancy
10 | PackageSummary: Tauri is a rust project that enables developers to make secure
11 | and small desktop applications using a web frontend.
12 |
13 | PackageComment: The package includes the following libraries; see
14 | Relationship information.
15 |
16 | Created: 2019-05-20T09:00:00Z
17 | PackageDownloadLocation: git://github.com/tauri-apps/tauri
18 | PackageDownloadLocation: git+https://github.com/tauri-apps/tauri.git
19 | PackageDownloadLocation: git+ssh://github.com/tauri-apps/tauri.git
20 | Creator: Person: Daniel Thompson-Yvetot
--------------------------------------------------------------------------------
/LICENSE_MIT:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2017 - Present Tauri Apps Contributors
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/permissions/default.toml:
--------------------------------------------------------------------------------
1 | "$schema" = "schemas/schema.json"
2 |
3 | [default]
4 | description = """
5 | This set of permissions describes the what kind of
6 | file system access the `fs` plugin has enabled or denied by default.
7 |
8 | #### Granted Permissions
9 |
10 | This default permission set enables read access to the
11 | application specific directories (AppConfig, AppData, AppLocalData, AppCache,
12 | AppLog) and all files and sub directories created in it.
13 | The location of these directories depends on the operating system,
14 | where the application is run.
15 |
16 | In general these directories need to be manually created
17 | by the application at runtime, before accessing files or folders
18 | in it is possible.
19 |
20 | Therefore, it is also allowed to create all of these folders via
21 | the `mkdir` command.
22 |
23 | #### Denied Permissions
24 |
25 | This default permission set prevents access to critical components
26 | of the Tauri application by default.
27 | On Windows the webview data folder access is denied.
28 | """
29 | permissions = [
30 | "create-app-specific-dirs",
31 | "read-app-specific-dirs-recursive",
32 | "deny-default",
33 | ]
34 |
--------------------------------------------------------------------------------
/src/desktop.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2 | // SPDX-License-Identifier: Apache-2.0
3 | // SPDX-License-Identifier: MIT
4 |
5 | use std::path::PathBuf;
6 |
7 | use tauri::{AppHandle, Runtime};
8 |
9 | use crate::{FilePath, OpenOptions};
10 |
11 | pub struct Fs(pub(crate) AppHandle);
12 |
13 | fn path_or_err>(p: P) -> std::io::Result {
14 | match p.into() {
15 | FilePath::Path(p) => Ok(p),
16 | FilePath::Url(u) if u.scheme() == "file" => u
17 | .to_file_path()
18 | .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidInput, "invalid file URL")),
19 | FilePath::Url(_) => Err(std::io::Error::new(
20 | std::io::ErrorKind::InvalidInput,
21 | "cannot use a URL to load files on desktop and iOS",
22 | )),
23 | }
24 | }
25 |
26 | impl Fs {
27 | pub fn open>(
28 | &self,
29 | path: P,
30 | opts: OpenOptions,
31 | ) -> std::io::Result {
32 | let path = path_or_err(path)?;
33 | std::fs::OpenOptions::from(opts).open(path)
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/android/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | id("com.android.library")
3 | id("org.jetbrains.kotlin.android")
4 | }
5 |
6 | android {
7 | namespace = "com.plugin.fs"
8 | compileSdk = 36
9 |
10 | defaultConfig {
11 | minSdk = 21
12 |
13 | testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
14 | consumerProguardFiles("consumer-rules.pro")
15 | }
16 |
17 | buildTypes {
18 | release {
19 | isMinifyEnabled = false
20 | proguardFiles(
21 | getDefaultProguardFile("proguard-android-optimize.txt"),
22 | "proguard-rules.pro"
23 | )
24 | }
25 | }
26 | compileOptions {
27 | sourceCompatibility = JavaVersion.VERSION_1_8
28 | targetCompatibility = JavaVersion.VERSION_1_8
29 | }
30 | kotlinOptions {
31 | jvmTarget = "1.8"
32 | }
33 | }
34 |
35 | dependencies {
36 |
37 | implementation("androidx.core:core-ktx:1.9.0")
38 | implementation("androidx.appcompat:appcompat:1.6.0")
39 | implementation("com.google.android.material:material:1.7.0")
40 | testImplementation("junit:junit:4.13.2")
41 | androidTestImplementation("androidx.test.ext:junit:1.1.5")
42 | androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
43 | implementation(project(":tauri-android"))
44 | }
45 |
--------------------------------------------------------------------------------
/src/error.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2 | // SPDX-License-Identifier: Apache-2.0
3 | // SPDX-License-Identifier: MIT
4 |
5 | use std::path::PathBuf;
6 |
7 | use serde::{Serialize, Serializer};
8 |
9 | #[derive(Debug, thiserror::Error)]
10 | #[non_exhaustive]
11 | pub enum Error {
12 | #[error(transparent)]
13 | Json(#[from] serde_json::Error),
14 | #[error(transparent)]
15 | Tauri(#[from] tauri::Error),
16 | #[error(transparent)]
17 | Io(#[from] std::io::Error),
18 | #[error("forbidden path: {0}")]
19 | PathForbidden(PathBuf),
20 | /// Invalid glob pattern.
21 | #[error("invalid glob pattern: {0}")]
22 | GlobPattern(#[from] glob::PatternError),
23 | /// Watcher error.
24 | #[cfg(feature = "watch")]
25 | #[error(transparent)]
26 | Watch(#[from] notify::Error),
27 | #[cfg(target_os = "android")]
28 | #[error(transparent)]
29 | PluginInvoke(#[from] tauri::plugin::mobile::PluginInvokeError),
30 | #[error("URL is not a valid path")]
31 | InvalidPathUrl,
32 | #[error("Unsafe PathBuf: {0}")]
33 | UnsafePathBuf(&'static str),
34 | }
35 |
36 | impl Serialize for Error {
37 | fn serialize(&self, serializer: S) -> std::result::Result
38 | where
39 | S: Serializer,
40 | {
41 | serializer.serialize_str(self.to_string().as_ref())
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "tauri-plugin-fs"
3 | version = "2.4.4"
4 | description = "Access the file system."
5 | authors = { workspace = true }
6 | license = { workspace = true }
7 | edition = { workspace = true }
8 | rust-version = { workspace = true }
9 | repository = { workspace = true }
10 | links = "tauri-plugin-fs"
11 |
12 | [package.metadata.platforms.support]
13 | windows = { level = "full", notes = "Apps installed via MSI or NSIS in `perMachine` and `both` mode require admin permissions for write access in `$RESOURCES` folder" }
14 | linux = { level = "full", notes = "No write access to `$RESOURCES` folder" }
15 | macos = { level = "full", notes = "No write access to `$RESOURCES` folder" }
16 | android = { level = "partial", notes = "Access is restricted to Application folder by default" }
17 | ios = { level = "partial", notes = "Access is restricted to Application folder by default" }
18 |
19 | [build-dependencies]
20 | tauri-plugin = { workspace = true, features = ["build"] }
21 | schemars = { workspace = true }
22 | serde = { workspace = true }
23 | toml = "0.9"
24 | tauri-utils = { workspace = true, features = ["build"] }
25 |
26 | [dependencies]
27 | serde = { workspace = true }
28 | serde_json = { workspace = true }
29 | serde_repr = "0.1"
30 | tauri = { workspace = true }
31 | thiserror = { workspace = true }
32 | url = { workspace = true }
33 | anyhow = "1"
34 | glob = { workspace = true }
35 | # TODO: Remove `serialization-compat-6` in v3
36 | notify = { version = "8", optional = true, features = [
37 | "serde",
38 | "serialization-compat-6",
39 | ] }
40 | notify-debouncer-full = { version = "0.6", optional = true }
41 | dunce = { workspace = true }
42 | percent-encoding = "2"
43 |
44 | [features]
45 | watch = ["notify", "notify-debouncer-full"]
46 |
--------------------------------------------------------------------------------
/permissions/autogenerated/base-directories/exe.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | # Scopes Section
6 | # This section contains scopes, which define file level access
7 |
8 | [[permission]]
9 | identifier = "scope-exe-recursive"
10 | description = "This scope permits recursive access to the complete `$EXE` folder, including sub directories and files."
11 |
12 | [[permission.scope.allow]]
13 | path = "$EXE"
14 | [[permission.scope.allow]]
15 | path = "$EXE/**"
16 |
17 | [[permission]]
18 | identifier = "scope-exe"
19 | description = "This scope permits access to all files and list content of top level directories in the `$EXE` folder."
20 |
21 | [[permission.scope.allow]]
22 | path = "$EXE"
23 | [[permission.scope.allow]]
24 | path = "$EXE/*"
25 |
26 | [[permission]]
27 | identifier = "scope-exe-index"
28 | description = "This scope permits to list all files and folders in the `$EXE`folder."
29 |
30 | [[permission.scope.allow]]
31 | path = "$EXE"
32 |
33 | # Sets Section
34 | # This section combines the scope elements with enablement of commands
35 |
36 | [[set]]
37 | identifier = "allow-exe-read-recursive"
38 | description = "This allows full recursive read access to the complete `$EXE` folder, files and subdirectories."
39 | permissions = [
40 | "read-all",
41 | "scope-exe-recursive"
42 | ]
43 |
44 | [[set]]
45 | identifier = "allow-exe-write-recursive"
46 | description = "This allows full recursive write access to the complete `$EXE` folder, files and subdirectories."
47 | permissions = [
48 | "write-all",
49 | "scope-exe-recursive"
50 | ]
51 |
52 | [[set]]
53 | identifier = "allow-exe-read"
54 | description = "This allows non-recursive read access to the `$EXE` folder."
55 | permissions = [
56 | "read-all",
57 | "scope-exe"
58 | ]
59 |
60 | [[set]]
61 | identifier = "allow-exe-write"
62 | description = "This allows non-recursive write access to the `$EXE` folder."
63 | permissions = [
64 | "write-all",
65 | "scope-exe"
66 | ]
67 |
68 | [[set]]
69 | identifier = "allow-exe-meta-recursive"
70 | description = "This allows full recursive read access to metadata of the `$EXE` folder, including file listing and statistics."
71 | permissions = [
72 | "read-meta",
73 | "scope-exe-recursive"
74 | ]
75 |
76 | [[set]]
77 | identifier = "allow-exe-meta"
78 | description = "This allows non-recursive read access to metadata of the `$EXE` folder, including file listing and statistics."
79 | permissions = [
80 | "read-meta",
81 | "scope-exe-index"
82 | ]
--------------------------------------------------------------------------------
/permissions/autogenerated/base-directories/log.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | # Scopes Section
6 | # This section contains scopes, which define file level access
7 |
8 | [[permission]]
9 | identifier = "scope-log-recursive"
10 | description = "This scope permits recursive access to the complete `$LOG` folder, including sub directories and files."
11 |
12 | [[permission.scope.allow]]
13 | path = "$LOG"
14 | [[permission.scope.allow]]
15 | path = "$LOG/**"
16 |
17 | [[permission]]
18 | identifier = "scope-log"
19 | description = "This scope permits access to all files and list content of top level directories in the `$LOG` folder."
20 |
21 | [[permission.scope.allow]]
22 | path = "$LOG"
23 | [[permission.scope.allow]]
24 | path = "$LOG/*"
25 |
26 | [[permission]]
27 | identifier = "scope-log-index"
28 | description = "This scope permits to list all files and folders in the `$LOG`folder."
29 |
30 | [[permission.scope.allow]]
31 | path = "$LOG"
32 |
33 | # Sets Section
34 | # This section combines the scope elements with enablement of commands
35 |
36 | [[set]]
37 | identifier = "allow-log-read-recursive"
38 | description = "This allows full recursive read access to the complete `$LOG` folder, files and subdirectories."
39 | permissions = [
40 | "read-all",
41 | "scope-log-recursive"
42 | ]
43 |
44 | [[set]]
45 | identifier = "allow-log-write-recursive"
46 | description = "This allows full recursive write access to the complete `$LOG` folder, files and subdirectories."
47 | permissions = [
48 | "write-all",
49 | "scope-log-recursive"
50 | ]
51 |
52 | [[set]]
53 | identifier = "allow-log-read"
54 | description = "This allows non-recursive read access to the `$LOG` folder."
55 | permissions = [
56 | "read-all",
57 | "scope-log"
58 | ]
59 |
60 | [[set]]
61 | identifier = "allow-log-write"
62 | description = "This allows non-recursive write access to the `$LOG` folder."
63 | permissions = [
64 | "write-all",
65 | "scope-log"
66 | ]
67 |
68 | [[set]]
69 | identifier = "allow-log-meta-recursive"
70 | description = "This allows full recursive read access to metadata of the `$LOG` folder, including file listing and statistics."
71 | permissions = [
72 | "read-meta",
73 | "scope-log-recursive"
74 | ]
75 |
76 | [[set]]
77 | identifier = "allow-log-meta"
78 | description = "This allows non-recursive read access to metadata of the `$LOG` folder, including file listing and statistics."
79 | permissions = [
80 | "read-meta",
81 | "scope-log-index"
82 | ]
--------------------------------------------------------------------------------
/permissions/autogenerated/base-directories/data.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | # Scopes Section
6 | # This section contains scopes, which define file level access
7 |
8 | [[permission]]
9 | identifier = "scope-data-recursive"
10 | description = "This scope permits recursive access to the complete `$DATA` folder, including sub directories and files."
11 |
12 | [[permission.scope.allow]]
13 | path = "$DATA"
14 | [[permission.scope.allow]]
15 | path = "$DATA/**"
16 |
17 | [[permission]]
18 | identifier = "scope-data"
19 | description = "This scope permits access to all files and list content of top level directories in the `$DATA` folder."
20 |
21 | [[permission.scope.allow]]
22 | path = "$DATA"
23 | [[permission.scope.allow]]
24 | path = "$DATA/*"
25 |
26 | [[permission]]
27 | identifier = "scope-data-index"
28 | description = "This scope permits to list all files and folders in the `$DATA`folder."
29 |
30 | [[permission.scope.allow]]
31 | path = "$DATA"
32 |
33 | # Sets Section
34 | # This section combines the scope elements with enablement of commands
35 |
36 | [[set]]
37 | identifier = "allow-data-read-recursive"
38 | description = "This allows full recursive read access to the complete `$DATA` folder, files and subdirectories."
39 | permissions = [
40 | "read-all",
41 | "scope-data-recursive"
42 | ]
43 |
44 | [[set]]
45 | identifier = "allow-data-write-recursive"
46 | description = "This allows full recursive write access to the complete `$DATA` folder, files and subdirectories."
47 | permissions = [
48 | "write-all",
49 | "scope-data-recursive"
50 | ]
51 |
52 | [[set]]
53 | identifier = "allow-data-read"
54 | description = "This allows non-recursive read access to the `$DATA` folder."
55 | permissions = [
56 | "read-all",
57 | "scope-data"
58 | ]
59 |
60 | [[set]]
61 | identifier = "allow-data-write"
62 | description = "This allows non-recursive write access to the `$DATA` folder."
63 | permissions = [
64 | "write-all",
65 | "scope-data"
66 | ]
67 |
68 | [[set]]
69 | identifier = "allow-data-meta-recursive"
70 | description = "This allows full recursive read access to metadata of the `$DATA` folder, including file listing and statistics."
71 | permissions = [
72 | "read-meta",
73 | "scope-data-recursive"
74 | ]
75 |
76 | [[set]]
77 | identifier = "allow-data-meta"
78 | description = "This allows non-recursive read access to metadata of the `$DATA` folder, including file listing and statistics."
79 | permissions = [
80 | "read-meta",
81 | "scope-data-index"
82 | ]
--------------------------------------------------------------------------------
/permissions/autogenerated/base-directories/font.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | # Scopes Section
6 | # This section contains scopes, which define file level access
7 |
8 | [[permission]]
9 | identifier = "scope-font-recursive"
10 | description = "This scope permits recursive access to the complete `$FONT` folder, including sub directories and files."
11 |
12 | [[permission.scope.allow]]
13 | path = "$FONT"
14 | [[permission.scope.allow]]
15 | path = "$FONT/**"
16 |
17 | [[permission]]
18 | identifier = "scope-font"
19 | description = "This scope permits access to all files and list content of top level directories in the `$FONT` folder."
20 |
21 | [[permission.scope.allow]]
22 | path = "$FONT"
23 | [[permission.scope.allow]]
24 | path = "$FONT/*"
25 |
26 | [[permission]]
27 | identifier = "scope-font-index"
28 | description = "This scope permits to list all files and folders in the `$FONT`folder."
29 |
30 | [[permission.scope.allow]]
31 | path = "$FONT"
32 |
33 | # Sets Section
34 | # This section combines the scope elements with enablement of commands
35 |
36 | [[set]]
37 | identifier = "allow-font-read-recursive"
38 | description = "This allows full recursive read access to the complete `$FONT` folder, files and subdirectories."
39 | permissions = [
40 | "read-all",
41 | "scope-font-recursive"
42 | ]
43 |
44 | [[set]]
45 | identifier = "allow-font-write-recursive"
46 | description = "This allows full recursive write access to the complete `$FONT` folder, files and subdirectories."
47 | permissions = [
48 | "write-all",
49 | "scope-font-recursive"
50 | ]
51 |
52 | [[set]]
53 | identifier = "allow-font-read"
54 | description = "This allows non-recursive read access to the `$FONT` folder."
55 | permissions = [
56 | "read-all",
57 | "scope-font"
58 | ]
59 |
60 | [[set]]
61 | identifier = "allow-font-write"
62 | description = "This allows non-recursive write access to the `$FONT` folder."
63 | permissions = [
64 | "write-all",
65 | "scope-font"
66 | ]
67 |
68 | [[set]]
69 | identifier = "allow-font-meta-recursive"
70 | description = "This allows full recursive read access to metadata of the `$FONT` folder, including file listing and statistics."
71 | permissions = [
72 | "read-meta",
73 | "scope-font-recursive"
74 | ]
75 |
76 | [[set]]
77 | identifier = "allow-font-meta"
78 | description = "This allows non-recursive read access to metadata of the `$FONT` folder, including file listing and statistics."
79 | permissions = [
80 | "read-meta",
81 | "scope-font-index"
82 | ]
--------------------------------------------------------------------------------
/permissions/autogenerated/base-directories/home.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | # Scopes Section
6 | # This section contains scopes, which define file level access
7 |
8 | [[permission]]
9 | identifier = "scope-home-recursive"
10 | description = "This scope permits recursive access to the complete `$HOME` folder, including sub directories and files."
11 |
12 | [[permission.scope.allow]]
13 | path = "$HOME"
14 | [[permission.scope.allow]]
15 | path = "$HOME/**"
16 |
17 | [[permission]]
18 | identifier = "scope-home"
19 | description = "This scope permits access to all files and list content of top level directories in the `$HOME` folder."
20 |
21 | [[permission.scope.allow]]
22 | path = "$HOME"
23 | [[permission.scope.allow]]
24 | path = "$HOME/*"
25 |
26 | [[permission]]
27 | identifier = "scope-home-index"
28 | description = "This scope permits to list all files and folders in the `$HOME`folder."
29 |
30 | [[permission.scope.allow]]
31 | path = "$HOME"
32 |
33 | # Sets Section
34 | # This section combines the scope elements with enablement of commands
35 |
36 | [[set]]
37 | identifier = "allow-home-read-recursive"
38 | description = "This allows full recursive read access to the complete `$HOME` folder, files and subdirectories."
39 | permissions = [
40 | "read-all",
41 | "scope-home-recursive"
42 | ]
43 |
44 | [[set]]
45 | identifier = "allow-home-write-recursive"
46 | description = "This allows full recursive write access to the complete `$HOME` folder, files and subdirectories."
47 | permissions = [
48 | "write-all",
49 | "scope-home-recursive"
50 | ]
51 |
52 | [[set]]
53 | identifier = "allow-home-read"
54 | description = "This allows non-recursive read access to the `$HOME` folder."
55 | permissions = [
56 | "read-all",
57 | "scope-home"
58 | ]
59 |
60 | [[set]]
61 | identifier = "allow-home-write"
62 | description = "This allows non-recursive write access to the `$HOME` folder."
63 | permissions = [
64 | "write-all",
65 | "scope-home"
66 | ]
67 |
68 | [[set]]
69 | identifier = "allow-home-meta-recursive"
70 | description = "This allows full recursive read access to metadata of the `$HOME` folder, including file listing and statistics."
71 | permissions = [
72 | "read-meta",
73 | "scope-home-recursive"
74 | ]
75 |
76 | [[set]]
77 | identifier = "allow-home-meta"
78 | description = "This allows non-recursive read access to metadata of the `$HOME` folder, including file listing and statistics."
79 | permissions = [
80 | "read-meta",
81 | "scope-home-index"
82 | ]
--------------------------------------------------------------------------------
/permissions/autogenerated/base-directories/temp.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | # Scopes Section
6 | # This section contains scopes, which define file level access
7 |
8 | [[permission]]
9 | identifier = "scope-temp-recursive"
10 | description = "This scope permits recursive access to the complete `$TEMP` folder, including sub directories and files."
11 |
12 | [[permission.scope.allow]]
13 | path = "$TEMP"
14 | [[permission.scope.allow]]
15 | path = "$TEMP/**"
16 |
17 | [[permission]]
18 | identifier = "scope-temp"
19 | description = "This scope permits access to all files and list content of top level directories in the `$TEMP` folder."
20 |
21 | [[permission.scope.allow]]
22 | path = "$TEMP"
23 | [[permission.scope.allow]]
24 | path = "$TEMP/*"
25 |
26 | [[permission]]
27 | identifier = "scope-temp-index"
28 | description = "This scope permits to list all files and folders in the `$TEMP`folder."
29 |
30 | [[permission.scope.allow]]
31 | path = "$TEMP"
32 |
33 | # Sets Section
34 | # This section combines the scope elements with enablement of commands
35 |
36 | [[set]]
37 | identifier = "allow-temp-read-recursive"
38 | description = "This allows full recursive read access to the complete `$TEMP` folder, files and subdirectories."
39 | permissions = [
40 | "read-all",
41 | "scope-temp-recursive"
42 | ]
43 |
44 | [[set]]
45 | identifier = "allow-temp-write-recursive"
46 | description = "This allows full recursive write access to the complete `$TEMP` folder, files and subdirectories."
47 | permissions = [
48 | "write-all",
49 | "scope-temp-recursive"
50 | ]
51 |
52 | [[set]]
53 | identifier = "allow-temp-read"
54 | description = "This allows non-recursive read access to the `$TEMP` folder."
55 | permissions = [
56 | "read-all",
57 | "scope-temp"
58 | ]
59 |
60 | [[set]]
61 | identifier = "allow-temp-write"
62 | description = "This allows non-recursive write access to the `$TEMP` folder."
63 | permissions = [
64 | "write-all",
65 | "scope-temp"
66 | ]
67 |
68 | [[set]]
69 | identifier = "allow-temp-meta-recursive"
70 | description = "This allows full recursive read access to metadata of the `$TEMP` folder, including file listing and statistics."
71 | permissions = [
72 | "read-meta",
73 | "scope-temp-recursive"
74 | ]
75 |
76 | [[set]]
77 | identifier = "allow-temp-meta"
78 | description = "This allows non-recursive read access to metadata of the `$TEMP` folder, including file listing and statistics."
79 | permissions = [
80 | "read-meta",
81 | "scope-temp-index"
82 | ]
--------------------------------------------------------------------------------
/permissions/autogenerated/base-directories/audio.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | # Scopes Section
6 | # This section contains scopes, which define file level access
7 |
8 | [[permission]]
9 | identifier = "scope-audio-recursive"
10 | description = "This scope permits recursive access to the complete `$AUDIO` folder, including sub directories and files."
11 |
12 | [[permission.scope.allow]]
13 | path = "$AUDIO"
14 | [[permission.scope.allow]]
15 | path = "$AUDIO/**"
16 |
17 | [[permission]]
18 | identifier = "scope-audio"
19 | description = "This scope permits access to all files and list content of top level directories in the `$AUDIO` folder."
20 |
21 | [[permission.scope.allow]]
22 | path = "$AUDIO"
23 | [[permission.scope.allow]]
24 | path = "$AUDIO/*"
25 |
26 | [[permission]]
27 | identifier = "scope-audio-index"
28 | description = "This scope permits to list all files and folders in the `$AUDIO`folder."
29 |
30 | [[permission.scope.allow]]
31 | path = "$AUDIO"
32 |
33 | # Sets Section
34 | # This section combines the scope elements with enablement of commands
35 |
36 | [[set]]
37 | identifier = "allow-audio-read-recursive"
38 | description = "This allows full recursive read access to the complete `$AUDIO` folder, files and subdirectories."
39 | permissions = [
40 | "read-all",
41 | "scope-audio-recursive"
42 | ]
43 |
44 | [[set]]
45 | identifier = "allow-audio-write-recursive"
46 | description = "This allows full recursive write access to the complete `$AUDIO` folder, files and subdirectories."
47 | permissions = [
48 | "write-all",
49 | "scope-audio-recursive"
50 | ]
51 |
52 | [[set]]
53 | identifier = "allow-audio-read"
54 | description = "This allows non-recursive read access to the `$AUDIO` folder."
55 | permissions = [
56 | "read-all",
57 | "scope-audio"
58 | ]
59 |
60 | [[set]]
61 | identifier = "allow-audio-write"
62 | description = "This allows non-recursive write access to the `$AUDIO` folder."
63 | permissions = [
64 | "write-all",
65 | "scope-audio"
66 | ]
67 |
68 | [[set]]
69 | identifier = "allow-audio-meta-recursive"
70 | description = "This allows full recursive read access to metadata of the `$AUDIO` folder, including file listing and statistics."
71 | permissions = [
72 | "read-meta",
73 | "scope-audio-recursive"
74 | ]
75 |
76 | [[set]]
77 | identifier = "allow-audio-meta"
78 | description = "This allows non-recursive read access to metadata of the `$AUDIO` folder, including file listing and statistics."
79 | permissions = [
80 | "read-meta",
81 | "scope-audio-index"
82 | ]
--------------------------------------------------------------------------------
/permissions/autogenerated/base-directories/cache.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | # Scopes Section
6 | # This section contains scopes, which define file level access
7 |
8 | [[permission]]
9 | identifier = "scope-cache-recursive"
10 | description = "This scope permits recursive access to the complete `$CACHE` folder, including sub directories and files."
11 |
12 | [[permission.scope.allow]]
13 | path = "$CACHE"
14 | [[permission.scope.allow]]
15 | path = "$CACHE/**"
16 |
17 | [[permission]]
18 | identifier = "scope-cache"
19 | description = "This scope permits access to all files and list content of top level directories in the `$CACHE` folder."
20 |
21 | [[permission.scope.allow]]
22 | path = "$CACHE"
23 | [[permission.scope.allow]]
24 | path = "$CACHE/*"
25 |
26 | [[permission]]
27 | identifier = "scope-cache-index"
28 | description = "This scope permits to list all files and folders in the `$CACHE`folder."
29 |
30 | [[permission.scope.allow]]
31 | path = "$CACHE"
32 |
33 | # Sets Section
34 | # This section combines the scope elements with enablement of commands
35 |
36 | [[set]]
37 | identifier = "allow-cache-read-recursive"
38 | description = "This allows full recursive read access to the complete `$CACHE` folder, files and subdirectories."
39 | permissions = [
40 | "read-all",
41 | "scope-cache-recursive"
42 | ]
43 |
44 | [[set]]
45 | identifier = "allow-cache-write-recursive"
46 | description = "This allows full recursive write access to the complete `$CACHE` folder, files and subdirectories."
47 | permissions = [
48 | "write-all",
49 | "scope-cache-recursive"
50 | ]
51 |
52 | [[set]]
53 | identifier = "allow-cache-read"
54 | description = "This allows non-recursive read access to the `$CACHE` folder."
55 | permissions = [
56 | "read-all",
57 | "scope-cache"
58 | ]
59 |
60 | [[set]]
61 | identifier = "allow-cache-write"
62 | description = "This allows non-recursive write access to the `$CACHE` folder."
63 | permissions = [
64 | "write-all",
65 | "scope-cache"
66 | ]
67 |
68 | [[set]]
69 | identifier = "allow-cache-meta-recursive"
70 | description = "This allows full recursive read access to metadata of the `$CACHE` folder, including file listing and statistics."
71 | permissions = [
72 | "read-meta",
73 | "scope-cache-recursive"
74 | ]
75 |
76 | [[set]]
77 | identifier = "allow-cache-meta"
78 | description = "This allows non-recursive read access to metadata of the `$CACHE` folder, including file listing and statistics."
79 | permissions = [
80 | "read-meta",
81 | "scope-cache-index"
82 | ]
--------------------------------------------------------------------------------
/permissions/autogenerated/base-directories/video.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | # Scopes Section
6 | # This section contains scopes, which define file level access
7 |
8 | [[permission]]
9 | identifier = "scope-video-recursive"
10 | description = "This scope permits recursive access to the complete `$VIDEO` folder, including sub directories and files."
11 |
12 | [[permission.scope.allow]]
13 | path = "$VIDEO"
14 | [[permission.scope.allow]]
15 | path = "$VIDEO/**"
16 |
17 | [[permission]]
18 | identifier = "scope-video"
19 | description = "This scope permits access to all files and list content of top level directories in the `$VIDEO` folder."
20 |
21 | [[permission.scope.allow]]
22 | path = "$VIDEO"
23 | [[permission.scope.allow]]
24 | path = "$VIDEO/*"
25 |
26 | [[permission]]
27 | identifier = "scope-video-index"
28 | description = "This scope permits to list all files and folders in the `$VIDEO`folder."
29 |
30 | [[permission.scope.allow]]
31 | path = "$VIDEO"
32 |
33 | # Sets Section
34 | # This section combines the scope elements with enablement of commands
35 |
36 | [[set]]
37 | identifier = "allow-video-read-recursive"
38 | description = "This allows full recursive read access to the complete `$VIDEO` folder, files and subdirectories."
39 | permissions = [
40 | "read-all",
41 | "scope-video-recursive"
42 | ]
43 |
44 | [[set]]
45 | identifier = "allow-video-write-recursive"
46 | description = "This allows full recursive write access to the complete `$VIDEO` folder, files and subdirectories."
47 | permissions = [
48 | "write-all",
49 | "scope-video-recursive"
50 | ]
51 |
52 | [[set]]
53 | identifier = "allow-video-read"
54 | description = "This allows non-recursive read access to the `$VIDEO` folder."
55 | permissions = [
56 | "read-all",
57 | "scope-video"
58 | ]
59 |
60 | [[set]]
61 | identifier = "allow-video-write"
62 | description = "This allows non-recursive write access to the `$VIDEO` folder."
63 | permissions = [
64 | "write-all",
65 | "scope-video"
66 | ]
67 |
68 | [[set]]
69 | identifier = "allow-video-meta-recursive"
70 | description = "This allows full recursive read access to metadata of the `$VIDEO` folder, including file listing and statistics."
71 | permissions = [
72 | "read-meta",
73 | "scope-video-recursive"
74 | ]
75 |
76 | [[set]]
77 | identifier = "allow-video-meta"
78 | description = "This allows non-recursive read access to metadata of the `$VIDEO` folder, including file listing and statistics."
79 | permissions = [
80 | "read-meta",
81 | "scope-video-index"
82 | ]
--------------------------------------------------------------------------------
/permissions/autogenerated/base-directories/applog.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | # Scopes Section
6 | # This section contains scopes, which define file level access
7 |
8 | [[permission]]
9 | identifier = "scope-applog-recursive"
10 | description = "This scope permits recursive access to the complete `$APPLOG` folder, including sub directories and files."
11 |
12 | [[permission.scope.allow]]
13 | path = "$APPLOG"
14 | [[permission.scope.allow]]
15 | path = "$APPLOG/**"
16 |
17 | [[permission]]
18 | identifier = "scope-applog"
19 | description = "This scope permits access to all files and list content of top level directories in the `$APPLOG` folder."
20 |
21 | [[permission.scope.allow]]
22 | path = "$APPLOG"
23 | [[permission.scope.allow]]
24 | path = "$APPLOG/*"
25 |
26 | [[permission]]
27 | identifier = "scope-applog-index"
28 | description = "This scope permits to list all files and folders in the `$APPLOG`folder."
29 |
30 | [[permission.scope.allow]]
31 | path = "$APPLOG"
32 |
33 | # Sets Section
34 | # This section combines the scope elements with enablement of commands
35 |
36 | [[set]]
37 | identifier = "allow-applog-read-recursive"
38 | description = "This allows full recursive read access to the complete `$APPLOG` folder, files and subdirectories."
39 | permissions = [
40 | "read-all",
41 | "scope-applog-recursive"
42 | ]
43 |
44 | [[set]]
45 | identifier = "allow-applog-write-recursive"
46 | description = "This allows full recursive write access to the complete `$APPLOG` folder, files and subdirectories."
47 | permissions = [
48 | "write-all",
49 | "scope-applog-recursive"
50 | ]
51 |
52 | [[set]]
53 | identifier = "allow-applog-read"
54 | description = "This allows non-recursive read access to the `$APPLOG` folder."
55 | permissions = [
56 | "read-all",
57 | "scope-applog"
58 | ]
59 |
60 | [[set]]
61 | identifier = "allow-applog-write"
62 | description = "This allows non-recursive write access to the `$APPLOG` folder."
63 | permissions = [
64 | "write-all",
65 | "scope-applog"
66 | ]
67 |
68 | [[set]]
69 | identifier = "allow-applog-meta-recursive"
70 | description = "This allows full recursive read access to metadata of the `$APPLOG` folder, including file listing and statistics."
71 | permissions = [
72 | "read-meta",
73 | "scope-applog-recursive"
74 | ]
75 |
76 | [[set]]
77 | identifier = "allow-applog-meta"
78 | description = "This allows non-recursive read access to metadata of the `$APPLOG` folder, including file listing and statistics."
79 | permissions = [
80 | "read-meta",
81 | "scope-applog-index"
82 | ]
--------------------------------------------------------------------------------
/permissions/autogenerated/base-directories/config.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | # Scopes Section
6 | # This section contains scopes, which define file level access
7 |
8 | [[permission]]
9 | identifier = "scope-config-recursive"
10 | description = "This scope permits recursive access to the complete `$CONFIG` folder, including sub directories and files."
11 |
12 | [[permission.scope.allow]]
13 | path = "$CONFIG"
14 | [[permission.scope.allow]]
15 | path = "$CONFIG/**"
16 |
17 | [[permission]]
18 | identifier = "scope-config"
19 | description = "This scope permits access to all files and list content of top level directories in the `$CONFIG` folder."
20 |
21 | [[permission.scope.allow]]
22 | path = "$CONFIG"
23 | [[permission.scope.allow]]
24 | path = "$CONFIG/*"
25 |
26 | [[permission]]
27 | identifier = "scope-config-index"
28 | description = "This scope permits to list all files and folders in the `$CONFIG`folder."
29 |
30 | [[permission.scope.allow]]
31 | path = "$CONFIG"
32 |
33 | # Sets Section
34 | # This section combines the scope elements with enablement of commands
35 |
36 | [[set]]
37 | identifier = "allow-config-read-recursive"
38 | description = "This allows full recursive read access to the complete `$CONFIG` folder, files and subdirectories."
39 | permissions = [
40 | "read-all",
41 | "scope-config-recursive"
42 | ]
43 |
44 | [[set]]
45 | identifier = "allow-config-write-recursive"
46 | description = "This allows full recursive write access to the complete `$CONFIG` folder, files and subdirectories."
47 | permissions = [
48 | "write-all",
49 | "scope-config-recursive"
50 | ]
51 |
52 | [[set]]
53 | identifier = "allow-config-read"
54 | description = "This allows non-recursive read access to the `$CONFIG` folder."
55 | permissions = [
56 | "read-all",
57 | "scope-config"
58 | ]
59 |
60 | [[set]]
61 | identifier = "allow-config-write"
62 | description = "This allows non-recursive write access to the `$CONFIG` folder."
63 | permissions = [
64 | "write-all",
65 | "scope-config"
66 | ]
67 |
68 | [[set]]
69 | identifier = "allow-config-meta-recursive"
70 | description = "This allows full recursive read access to metadata of the `$CONFIG` folder, including file listing and statistics."
71 | permissions = [
72 | "read-meta",
73 | "scope-config-recursive"
74 | ]
75 |
76 | [[set]]
77 | identifier = "allow-config-meta"
78 | description = "This allows non-recursive read access to metadata of the `$CONFIG` folder, including file listing and statistics."
79 | permissions = [
80 | "read-meta",
81 | "scope-config-index"
82 | ]
--------------------------------------------------------------------------------
/permissions/autogenerated/base-directories/public.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | # Scopes Section
6 | # This section contains scopes, which define file level access
7 |
8 | [[permission]]
9 | identifier = "scope-public-recursive"
10 | description = "This scope permits recursive access to the complete `$PUBLIC` folder, including sub directories and files."
11 |
12 | [[permission.scope.allow]]
13 | path = "$PUBLIC"
14 | [[permission.scope.allow]]
15 | path = "$PUBLIC/**"
16 |
17 | [[permission]]
18 | identifier = "scope-public"
19 | description = "This scope permits access to all files and list content of top level directories in the `$PUBLIC` folder."
20 |
21 | [[permission.scope.allow]]
22 | path = "$PUBLIC"
23 | [[permission.scope.allow]]
24 | path = "$PUBLIC/*"
25 |
26 | [[permission]]
27 | identifier = "scope-public-index"
28 | description = "This scope permits to list all files and folders in the `$PUBLIC`folder."
29 |
30 | [[permission.scope.allow]]
31 | path = "$PUBLIC"
32 |
33 | # Sets Section
34 | # This section combines the scope elements with enablement of commands
35 |
36 | [[set]]
37 | identifier = "allow-public-read-recursive"
38 | description = "This allows full recursive read access to the complete `$PUBLIC` folder, files and subdirectories."
39 | permissions = [
40 | "read-all",
41 | "scope-public-recursive"
42 | ]
43 |
44 | [[set]]
45 | identifier = "allow-public-write-recursive"
46 | description = "This allows full recursive write access to the complete `$PUBLIC` folder, files and subdirectories."
47 | permissions = [
48 | "write-all",
49 | "scope-public-recursive"
50 | ]
51 |
52 | [[set]]
53 | identifier = "allow-public-read"
54 | description = "This allows non-recursive read access to the `$PUBLIC` folder."
55 | permissions = [
56 | "read-all",
57 | "scope-public"
58 | ]
59 |
60 | [[set]]
61 | identifier = "allow-public-write"
62 | description = "This allows non-recursive write access to the `$PUBLIC` folder."
63 | permissions = [
64 | "write-all",
65 | "scope-public"
66 | ]
67 |
68 | [[set]]
69 | identifier = "allow-public-meta-recursive"
70 | description = "This allows full recursive read access to metadata of the `$PUBLIC` folder, including file listing and statistics."
71 | permissions = [
72 | "read-meta",
73 | "scope-public-recursive"
74 | ]
75 |
76 | [[set]]
77 | identifier = "allow-public-meta"
78 | description = "This allows non-recursive read access to metadata of the `$PUBLIC` folder, including file listing and statistics."
79 | permissions = [
80 | "read-meta",
81 | "scope-public-index"
82 | ]
--------------------------------------------------------------------------------
/permissions/autogenerated/base-directories/appdata.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | # Scopes Section
6 | # This section contains scopes, which define file level access
7 |
8 | [[permission]]
9 | identifier = "scope-appdata-recursive"
10 | description = "This scope permits recursive access to the complete `$APPDATA` folder, including sub directories and files."
11 |
12 | [[permission.scope.allow]]
13 | path = "$APPDATA"
14 | [[permission.scope.allow]]
15 | path = "$APPDATA/**"
16 |
17 | [[permission]]
18 | identifier = "scope-appdata"
19 | description = "This scope permits access to all files and list content of top level directories in the `$APPDATA` folder."
20 |
21 | [[permission.scope.allow]]
22 | path = "$APPDATA"
23 | [[permission.scope.allow]]
24 | path = "$APPDATA/*"
25 |
26 | [[permission]]
27 | identifier = "scope-appdata-index"
28 | description = "This scope permits to list all files and folders in the `$APPDATA`folder."
29 |
30 | [[permission.scope.allow]]
31 | path = "$APPDATA"
32 |
33 | # Sets Section
34 | # This section combines the scope elements with enablement of commands
35 |
36 | [[set]]
37 | identifier = "allow-appdata-read-recursive"
38 | description = "This allows full recursive read access to the complete `$APPDATA` folder, files and subdirectories."
39 | permissions = [
40 | "read-all",
41 | "scope-appdata-recursive"
42 | ]
43 |
44 | [[set]]
45 | identifier = "allow-appdata-write-recursive"
46 | description = "This allows full recursive write access to the complete `$APPDATA` folder, files and subdirectories."
47 | permissions = [
48 | "write-all",
49 | "scope-appdata-recursive"
50 | ]
51 |
52 | [[set]]
53 | identifier = "allow-appdata-read"
54 | description = "This allows non-recursive read access to the `$APPDATA` folder."
55 | permissions = [
56 | "read-all",
57 | "scope-appdata"
58 | ]
59 |
60 | [[set]]
61 | identifier = "allow-appdata-write"
62 | description = "This allows non-recursive write access to the `$APPDATA` folder."
63 | permissions = [
64 | "write-all",
65 | "scope-appdata"
66 | ]
67 |
68 | [[set]]
69 | identifier = "allow-appdata-meta-recursive"
70 | description = "This allows full recursive read access to metadata of the `$APPDATA` folder, including file listing and statistics."
71 | permissions = [
72 | "read-meta",
73 | "scope-appdata-recursive"
74 | ]
75 |
76 | [[set]]
77 | identifier = "allow-appdata-meta"
78 | description = "This allows non-recursive read access to metadata of the `$APPDATA` folder, including file listing and statistics."
79 | permissions = [
80 | "read-meta",
81 | "scope-appdata-index"
82 | ]
--------------------------------------------------------------------------------
/permissions/autogenerated/base-directories/desktop.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | # Scopes Section
6 | # This section contains scopes, which define file level access
7 |
8 | [[permission]]
9 | identifier = "scope-desktop-recursive"
10 | description = "This scope permits recursive access to the complete `$DESKTOP` folder, including sub directories and files."
11 |
12 | [[permission.scope.allow]]
13 | path = "$DESKTOP"
14 | [[permission.scope.allow]]
15 | path = "$DESKTOP/**"
16 |
17 | [[permission]]
18 | identifier = "scope-desktop"
19 | description = "This scope permits access to all files and list content of top level directories in the `$DESKTOP` folder."
20 |
21 | [[permission.scope.allow]]
22 | path = "$DESKTOP"
23 | [[permission.scope.allow]]
24 | path = "$DESKTOP/*"
25 |
26 | [[permission]]
27 | identifier = "scope-desktop-index"
28 | description = "This scope permits to list all files and folders in the `$DESKTOP`folder."
29 |
30 | [[permission.scope.allow]]
31 | path = "$DESKTOP"
32 |
33 | # Sets Section
34 | # This section combines the scope elements with enablement of commands
35 |
36 | [[set]]
37 | identifier = "allow-desktop-read-recursive"
38 | description = "This allows full recursive read access to the complete `$DESKTOP` folder, files and subdirectories."
39 | permissions = [
40 | "read-all",
41 | "scope-desktop-recursive"
42 | ]
43 |
44 | [[set]]
45 | identifier = "allow-desktop-write-recursive"
46 | description = "This allows full recursive write access to the complete `$DESKTOP` folder, files and subdirectories."
47 | permissions = [
48 | "write-all",
49 | "scope-desktop-recursive"
50 | ]
51 |
52 | [[set]]
53 | identifier = "allow-desktop-read"
54 | description = "This allows non-recursive read access to the `$DESKTOP` folder."
55 | permissions = [
56 | "read-all",
57 | "scope-desktop"
58 | ]
59 |
60 | [[set]]
61 | identifier = "allow-desktop-write"
62 | description = "This allows non-recursive write access to the `$DESKTOP` folder."
63 | permissions = [
64 | "write-all",
65 | "scope-desktop"
66 | ]
67 |
68 | [[set]]
69 | identifier = "allow-desktop-meta-recursive"
70 | description = "This allows full recursive read access to metadata of the `$DESKTOP` folder, including file listing and statistics."
71 | permissions = [
72 | "read-meta",
73 | "scope-desktop-recursive"
74 | ]
75 |
76 | [[set]]
77 | identifier = "allow-desktop-meta"
78 | description = "This allows non-recursive read access to metadata of the `$DESKTOP` folder, including file listing and statistics."
79 | permissions = [
80 | "read-meta",
81 | "scope-desktop-index"
82 | ]
--------------------------------------------------------------------------------
/permissions/autogenerated/base-directories/picture.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | # Scopes Section
6 | # This section contains scopes, which define file level access
7 |
8 | [[permission]]
9 | identifier = "scope-picture-recursive"
10 | description = "This scope permits recursive access to the complete `$PICTURE` folder, including sub directories and files."
11 |
12 | [[permission.scope.allow]]
13 | path = "$PICTURE"
14 | [[permission.scope.allow]]
15 | path = "$PICTURE/**"
16 |
17 | [[permission]]
18 | identifier = "scope-picture"
19 | description = "This scope permits access to all files and list content of top level directories in the `$PICTURE` folder."
20 |
21 | [[permission.scope.allow]]
22 | path = "$PICTURE"
23 | [[permission.scope.allow]]
24 | path = "$PICTURE/*"
25 |
26 | [[permission]]
27 | identifier = "scope-picture-index"
28 | description = "This scope permits to list all files and folders in the `$PICTURE`folder."
29 |
30 | [[permission.scope.allow]]
31 | path = "$PICTURE"
32 |
33 | # Sets Section
34 | # This section combines the scope elements with enablement of commands
35 |
36 | [[set]]
37 | identifier = "allow-picture-read-recursive"
38 | description = "This allows full recursive read access to the complete `$PICTURE` folder, files and subdirectories."
39 | permissions = [
40 | "read-all",
41 | "scope-picture-recursive"
42 | ]
43 |
44 | [[set]]
45 | identifier = "allow-picture-write-recursive"
46 | description = "This allows full recursive write access to the complete `$PICTURE` folder, files and subdirectories."
47 | permissions = [
48 | "write-all",
49 | "scope-picture-recursive"
50 | ]
51 |
52 | [[set]]
53 | identifier = "allow-picture-read"
54 | description = "This allows non-recursive read access to the `$PICTURE` folder."
55 | permissions = [
56 | "read-all",
57 | "scope-picture"
58 | ]
59 |
60 | [[set]]
61 | identifier = "allow-picture-write"
62 | description = "This allows non-recursive write access to the `$PICTURE` folder."
63 | permissions = [
64 | "write-all",
65 | "scope-picture"
66 | ]
67 |
68 | [[set]]
69 | identifier = "allow-picture-meta-recursive"
70 | description = "This allows full recursive read access to metadata of the `$PICTURE` folder, including file listing and statistics."
71 | permissions = [
72 | "read-meta",
73 | "scope-picture-recursive"
74 | ]
75 |
76 | [[set]]
77 | identifier = "allow-picture-meta"
78 | description = "This allows non-recursive read access to metadata of the `$PICTURE` folder, including file listing and statistics."
79 | permissions = [
80 | "read-meta",
81 | "scope-picture-index"
82 | ]
--------------------------------------------------------------------------------
/permissions/autogenerated/base-directories/runtime.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | # Scopes Section
6 | # This section contains scopes, which define file level access
7 |
8 | [[permission]]
9 | identifier = "scope-runtime-recursive"
10 | description = "This scope permits recursive access to the complete `$RUNTIME` folder, including sub directories and files."
11 |
12 | [[permission.scope.allow]]
13 | path = "$RUNTIME"
14 | [[permission.scope.allow]]
15 | path = "$RUNTIME/**"
16 |
17 | [[permission]]
18 | identifier = "scope-runtime"
19 | description = "This scope permits access to all files and list content of top level directories in the `$RUNTIME` folder."
20 |
21 | [[permission.scope.allow]]
22 | path = "$RUNTIME"
23 | [[permission.scope.allow]]
24 | path = "$RUNTIME/*"
25 |
26 | [[permission]]
27 | identifier = "scope-runtime-index"
28 | description = "This scope permits to list all files and folders in the `$RUNTIME`folder."
29 |
30 | [[permission.scope.allow]]
31 | path = "$RUNTIME"
32 |
33 | # Sets Section
34 | # This section combines the scope elements with enablement of commands
35 |
36 | [[set]]
37 | identifier = "allow-runtime-read-recursive"
38 | description = "This allows full recursive read access to the complete `$RUNTIME` folder, files and subdirectories."
39 | permissions = [
40 | "read-all",
41 | "scope-runtime-recursive"
42 | ]
43 |
44 | [[set]]
45 | identifier = "allow-runtime-write-recursive"
46 | description = "This allows full recursive write access to the complete `$RUNTIME` folder, files and subdirectories."
47 | permissions = [
48 | "write-all",
49 | "scope-runtime-recursive"
50 | ]
51 |
52 | [[set]]
53 | identifier = "allow-runtime-read"
54 | description = "This allows non-recursive read access to the `$RUNTIME` folder."
55 | permissions = [
56 | "read-all",
57 | "scope-runtime"
58 | ]
59 |
60 | [[set]]
61 | identifier = "allow-runtime-write"
62 | description = "This allows non-recursive write access to the `$RUNTIME` folder."
63 | permissions = [
64 | "write-all",
65 | "scope-runtime"
66 | ]
67 |
68 | [[set]]
69 | identifier = "allow-runtime-meta-recursive"
70 | description = "This allows full recursive read access to metadata of the `$RUNTIME` folder, including file listing and statistics."
71 | permissions = [
72 | "read-meta",
73 | "scope-runtime-recursive"
74 | ]
75 |
76 | [[set]]
77 | identifier = "allow-runtime-meta"
78 | description = "This allows non-recursive read access to metadata of the `$RUNTIME` folder, including file listing and statistics."
79 | permissions = [
80 | "read-meta",
81 | "scope-runtime-index"
82 | ]
--------------------------------------------------------------------------------
/permissions/autogenerated/base-directories/appcache.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | # Scopes Section
6 | # This section contains scopes, which define file level access
7 |
8 | [[permission]]
9 | identifier = "scope-appcache-recursive"
10 | description = "This scope permits recursive access to the complete `$APPCACHE` folder, including sub directories and files."
11 |
12 | [[permission.scope.allow]]
13 | path = "$APPCACHE"
14 | [[permission.scope.allow]]
15 | path = "$APPCACHE/**"
16 |
17 | [[permission]]
18 | identifier = "scope-appcache"
19 | description = "This scope permits access to all files and list content of top level directories in the `$APPCACHE` folder."
20 |
21 | [[permission.scope.allow]]
22 | path = "$APPCACHE"
23 | [[permission.scope.allow]]
24 | path = "$APPCACHE/*"
25 |
26 | [[permission]]
27 | identifier = "scope-appcache-index"
28 | description = "This scope permits to list all files and folders in the `$APPCACHE`folder."
29 |
30 | [[permission.scope.allow]]
31 | path = "$APPCACHE"
32 |
33 | # Sets Section
34 | # This section combines the scope elements with enablement of commands
35 |
36 | [[set]]
37 | identifier = "allow-appcache-read-recursive"
38 | description = "This allows full recursive read access to the complete `$APPCACHE` folder, files and subdirectories."
39 | permissions = [
40 | "read-all",
41 | "scope-appcache-recursive"
42 | ]
43 |
44 | [[set]]
45 | identifier = "allow-appcache-write-recursive"
46 | description = "This allows full recursive write access to the complete `$APPCACHE` folder, files and subdirectories."
47 | permissions = [
48 | "write-all",
49 | "scope-appcache-recursive"
50 | ]
51 |
52 | [[set]]
53 | identifier = "allow-appcache-read"
54 | description = "This allows non-recursive read access to the `$APPCACHE` folder."
55 | permissions = [
56 | "read-all",
57 | "scope-appcache"
58 | ]
59 |
60 | [[set]]
61 | identifier = "allow-appcache-write"
62 | description = "This allows non-recursive write access to the `$APPCACHE` folder."
63 | permissions = [
64 | "write-all",
65 | "scope-appcache"
66 | ]
67 |
68 | [[set]]
69 | identifier = "allow-appcache-meta-recursive"
70 | description = "This allows full recursive read access to metadata of the `$APPCACHE` folder, including file listing and statistics."
71 | permissions = [
72 | "read-meta",
73 | "scope-appcache-recursive"
74 | ]
75 |
76 | [[set]]
77 | identifier = "allow-appcache-meta"
78 | description = "This allows non-recursive read access to metadata of the `$APPCACHE` folder, including file listing and statistics."
79 | permissions = [
80 | "read-meta",
81 | "scope-appcache-index"
82 | ]
--------------------------------------------------------------------------------
/permissions/autogenerated/base-directories/document.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | # Scopes Section
6 | # This section contains scopes, which define file level access
7 |
8 | [[permission]]
9 | identifier = "scope-document-recursive"
10 | description = "This scope permits recursive access to the complete `$DOCUMENT` folder, including sub directories and files."
11 |
12 | [[permission.scope.allow]]
13 | path = "$DOCUMENT"
14 | [[permission.scope.allow]]
15 | path = "$DOCUMENT/**"
16 |
17 | [[permission]]
18 | identifier = "scope-document"
19 | description = "This scope permits access to all files and list content of top level directories in the `$DOCUMENT` folder."
20 |
21 | [[permission.scope.allow]]
22 | path = "$DOCUMENT"
23 | [[permission.scope.allow]]
24 | path = "$DOCUMENT/*"
25 |
26 | [[permission]]
27 | identifier = "scope-document-index"
28 | description = "This scope permits to list all files and folders in the `$DOCUMENT`folder."
29 |
30 | [[permission.scope.allow]]
31 | path = "$DOCUMENT"
32 |
33 | # Sets Section
34 | # This section combines the scope elements with enablement of commands
35 |
36 | [[set]]
37 | identifier = "allow-document-read-recursive"
38 | description = "This allows full recursive read access to the complete `$DOCUMENT` folder, files and subdirectories."
39 | permissions = [
40 | "read-all",
41 | "scope-document-recursive"
42 | ]
43 |
44 | [[set]]
45 | identifier = "allow-document-write-recursive"
46 | description = "This allows full recursive write access to the complete `$DOCUMENT` folder, files and subdirectories."
47 | permissions = [
48 | "write-all",
49 | "scope-document-recursive"
50 | ]
51 |
52 | [[set]]
53 | identifier = "allow-document-read"
54 | description = "This allows non-recursive read access to the `$DOCUMENT` folder."
55 | permissions = [
56 | "read-all",
57 | "scope-document"
58 | ]
59 |
60 | [[set]]
61 | identifier = "allow-document-write"
62 | description = "This allows non-recursive write access to the `$DOCUMENT` folder."
63 | permissions = [
64 | "write-all",
65 | "scope-document"
66 | ]
67 |
68 | [[set]]
69 | identifier = "allow-document-meta-recursive"
70 | description = "This allows full recursive read access to metadata of the `$DOCUMENT` folder, including file listing and statistics."
71 | permissions = [
72 | "read-meta",
73 | "scope-document-recursive"
74 | ]
75 |
76 | [[set]]
77 | identifier = "allow-document-meta"
78 | description = "This allows non-recursive read access to metadata of the `$DOCUMENT` folder, including file listing and statistics."
79 | permissions = [
80 | "read-meta",
81 | "scope-document-index"
82 | ]
--------------------------------------------------------------------------------
/permissions/autogenerated/base-directories/download.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | # Scopes Section
6 | # This section contains scopes, which define file level access
7 |
8 | [[permission]]
9 | identifier = "scope-download-recursive"
10 | description = "This scope permits recursive access to the complete `$DOWNLOAD` folder, including sub directories and files."
11 |
12 | [[permission.scope.allow]]
13 | path = "$DOWNLOAD"
14 | [[permission.scope.allow]]
15 | path = "$DOWNLOAD/**"
16 |
17 | [[permission]]
18 | identifier = "scope-download"
19 | description = "This scope permits access to all files and list content of top level directories in the `$DOWNLOAD` folder."
20 |
21 | [[permission.scope.allow]]
22 | path = "$DOWNLOAD"
23 | [[permission.scope.allow]]
24 | path = "$DOWNLOAD/*"
25 |
26 | [[permission]]
27 | identifier = "scope-download-index"
28 | description = "This scope permits to list all files and folders in the `$DOWNLOAD`folder."
29 |
30 | [[permission.scope.allow]]
31 | path = "$DOWNLOAD"
32 |
33 | # Sets Section
34 | # This section combines the scope elements with enablement of commands
35 |
36 | [[set]]
37 | identifier = "allow-download-read-recursive"
38 | description = "This allows full recursive read access to the complete `$DOWNLOAD` folder, files and subdirectories."
39 | permissions = [
40 | "read-all",
41 | "scope-download-recursive"
42 | ]
43 |
44 | [[set]]
45 | identifier = "allow-download-write-recursive"
46 | description = "This allows full recursive write access to the complete `$DOWNLOAD` folder, files and subdirectories."
47 | permissions = [
48 | "write-all",
49 | "scope-download-recursive"
50 | ]
51 |
52 | [[set]]
53 | identifier = "allow-download-read"
54 | description = "This allows non-recursive read access to the `$DOWNLOAD` folder."
55 | permissions = [
56 | "read-all",
57 | "scope-download"
58 | ]
59 |
60 | [[set]]
61 | identifier = "allow-download-write"
62 | description = "This allows non-recursive write access to the `$DOWNLOAD` folder."
63 | permissions = [
64 | "write-all",
65 | "scope-download"
66 | ]
67 |
68 | [[set]]
69 | identifier = "allow-download-meta-recursive"
70 | description = "This allows full recursive read access to metadata of the `$DOWNLOAD` folder, including file listing and statistics."
71 | permissions = [
72 | "read-meta",
73 | "scope-download-recursive"
74 | ]
75 |
76 | [[set]]
77 | identifier = "allow-download-meta"
78 | description = "This allows non-recursive read access to metadata of the `$DOWNLOAD` folder, including file listing and statistics."
79 | permissions = [
80 | "read-meta",
81 | "scope-download-index"
82 | ]
--------------------------------------------------------------------------------
/permissions/autogenerated/base-directories/resource.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | # Scopes Section
6 | # This section contains scopes, which define file level access
7 |
8 | [[permission]]
9 | identifier = "scope-resource-recursive"
10 | description = "This scope permits recursive access to the complete `$RESOURCE` folder, including sub directories and files."
11 |
12 | [[permission.scope.allow]]
13 | path = "$RESOURCE"
14 | [[permission.scope.allow]]
15 | path = "$RESOURCE/**"
16 |
17 | [[permission]]
18 | identifier = "scope-resource"
19 | description = "This scope permits access to all files and list content of top level directories in the `$RESOURCE` folder."
20 |
21 | [[permission.scope.allow]]
22 | path = "$RESOURCE"
23 | [[permission.scope.allow]]
24 | path = "$RESOURCE/*"
25 |
26 | [[permission]]
27 | identifier = "scope-resource-index"
28 | description = "This scope permits to list all files and folders in the `$RESOURCE`folder."
29 |
30 | [[permission.scope.allow]]
31 | path = "$RESOURCE"
32 |
33 | # Sets Section
34 | # This section combines the scope elements with enablement of commands
35 |
36 | [[set]]
37 | identifier = "allow-resource-read-recursive"
38 | description = "This allows full recursive read access to the complete `$RESOURCE` folder, files and subdirectories."
39 | permissions = [
40 | "read-all",
41 | "scope-resource-recursive"
42 | ]
43 |
44 | [[set]]
45 | identifier = "allow-resource-write-recursive"
46 | description = "This allows full recursive write access to the complete `$RESOURCE` folder, files and subdirectories."
47 | permissions = [
48 | "write-all",
49 | "scope-resource-recursive"
50 | ]
51 |
52 | [[set]]
53 | identifier = "allow-resource-read"
54 | description = "This allows non-recursive read access to the `$RESOURCE` folder."
55 | permissions = [
56 | "read-all",
57 | "scope-resource"
58 | ]
59 |
60 | [[set]]
61 | identifier = "allow-resource-write"
62 | description = "This allows non-recursive write access to the `$RESOURCE` folder."
63 | permissions = [
64 | "write-all",
65 | "scope-resource"
66 | ]
67 |
68 | [[set]]
69 | identifier = "allow-resource-meta-recursive"
70 | description = "This allows full recursive read access to metadata of the `$RESOURCE` folder, including file listing and statistics."
71 | permissions = [
72 | "read-meta",
73 | "scope-resource-recursive"
74 | ]
75 |
76 | [[set]]
77 | identifier = "allow-resource-meta"
78 | description = "This allows non-recursive read access to metadata of the `$RESOURCE` folder, including file listing and statistics."
79 | permissions = [
80 | "read-meta",
81 | "scope-resource-index"
82 | ]
--------------------------------------------------------------------------------
/permissions/autogenerated/base-directories/template.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | # Scopes Section
6 | # This section contains scopes, which define file level access
7 |
8 | [[permission]]
9 | identifier = "scope-template-recursive"
10 | description = "This scope permits recursive access to the complete `$TEMPLATE` folder, including sub directories and files."
11 |
12 | [[permission.scope.allow]]
13 | path = "$TEMPLATE"
14 | [[permission.scope.allow]]
15 | path = "$TEMPLATE/**"
16 |
17 | [[permission]]
18 | identifier = "scope-template"
19 | description = "This scope permits access to all files and list content of top level directories in the `$TEMPLATE` folder."
20 |
21 | [[permission.scope.allow]]
22 | path = "$TEMPLATE"
23 | [[permission.scope.allow]]
24 | path = "$TEMPLATE/*"
25 |
26 | [[permission]]
27 | identifier = "scope-template-index"
28 | description = "This scope permits to list all files and folders in the `$TEMPLATE`folder."
29 |
30 | [[permission.scope.allow]]
31 | path = "$TEMPLATE"
32 |
33 | # Sets Section
34 | # This section combines the scope elements with enablement of commands
35 |
36 | [[set]]
37 | identifier = "allow-template-read-recursive"
38 | description = "This allows full recursive read access to the complete `$TEMPLATE` folder, files and subdirectories."
39 | permissions = [
40 | "read-all",
41 | "scope-template-recursive"
42 | ]
43 |
44 | [[set]]
45 | identifier = "allow-template-write-recursive"
46 | description = "This allows full recursive write access to the complete `$TEMPLATE` folder, files and subdirectories."
47 | permissions = [
48 | "write-all",
49 | "scope-template-recursive"
50 | ]
51 |
52 | [[set]]
53 | identifier = "allow-template-read"
54 | description = "This allows non-recursive read access to the `$TEMPLATE` folder."
55 | permissions = [
56 | "read-all",
57 | "scope-template"
58 | ]
59 |
60 | [[set]]
61 | identifier = "allow-template-write"
62 | description = "This allows non-recursive write access to the `$TEMPLATE` folder."
63 | permissions = [
64 | "write-all",
65 | "scope-template"
66 | ]
67 |
68 | [[set]]
69 | identifier = "allow-template-meta-recursive"
70 | description = "This allows full recursive read access to metadata of the `$TEMPLATE` folder, including file listing and statistics."
71 | permissions = [
72 | "read-meta",
73 | "scope-template-recursive"
74 | ]
75 |
76 | [[set]]
77 | identifier = "allow-template-meta"
78 | description = "This allows non-recursive read access to metadata of the `$TEMPLATE` folder, including file listing and statistics."
79 | permissions = [
80 | "read-meta",
81 | "scope-template-index"
82 | ]
--------------------------------------------------------------------------------
/permissions/autogenerated/base-directories/appconfig.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | # Scopes Section
6 | # This section contains scopes, which define file level access
7 |
8 | [[permission]]
9 | identifier = "scope-appconfig-recursive"
10 | description = "This scope permits recursive access to the complete `$APPCONFIG` folder, including sub directories and files."
11 |
12 | [[permission.scope.allow]]
13 | path = "$APPCONFIG"
14 | [[permission.scope.allow]]
15 | path = "$APPCONFIG/**"
16 |
17 | [[permission]]
18 | identifier = "scope-appconfig"
19 | description = "This scope permits access to all files and list content of top level directories in the `$APPCONFIG` folder."
20 |
21 | [[permission.scope.allow]]
22 | path = "$APPCONFIG"
23 | [[permission.scope.allow]]
24 | path = "$APPCONFIG/*"
25 |
26 | [[permission]]
27 | identifier = "scope-appconfig-index"
28 | description = "This scope permits to list all files and folders in the `$APPCONFIG`folder."
29 |
30 | [[permission.scope.allow]]
31 | path = "$APPCONFIG"
32 |
33 | # Sets Section
34 | # This section combines the scope elements with enablement of commands
35 |
36 | [[set]]
37 | identifier = "allow-appconfig-read-recursive"
38 | description = "This allows full recursive read access to the complete `$APPCONFIG` folder, files and subdirectories."
39 | permissions = [
40 | "read-all",
41 | "scope-appconfig-recursive"
42 | ]
43 |
44 | [[set]]
45 | identifier = "allow-appconfig-write-recursive"
46 | description = "This allows full recursive write access to the complete `$APPCONFIG` folder, files and subdirectories."
47 | permissions = [
48 | "write-all",
49 | "scope-appconfig-recursive"
50 | ]
51 |
52 | [[set]]
53 | identifier = "allow-appconfig-read"
54 | description = "This allows non-recursive read access to the `$APPCONFIG` folder."
55 | permissions = [
56 | "read-all",
57 | "scope-appconfig"
58 | ]
59 |
60 | [[set]]
61 | identifier = "allow-appconfig-write"
62 | description = "This allows non-recursive write access to the `$APPCONFIG` folder."
63 | permissions = [
64 | "write-all",
65 | "scope-appconfig"
66 | ]
67 |
68 | [[set]]
69 | identifier = "allow-appconfig-meta-recursive"
70 | description = "This allows full recursive read access to metadata of the `$APPCONFIG` folder, including file listing and statistics."
71 | permissions = [
72 | "read-meta",
73 | "scope-appconfig-recursive"
74 | ]
75 |
76 | [[set]]
77 | identifier = "allow-appconfig-meta"
78 | description = "This allows non-recursive read access to metadata of the `$APPCONFIG` folder, including file listing and statistics."
79 | permissions = [
80 | "read-meta",
81 | "scope-appconfig-index"
82 | ]
--------------------------------------------------------------------------------
/permissions/autogenerated/base-directories/localdata.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | # Scopes Section
6 | # This section contains scopes, which define file level access
7 |
8 | [[permission]]
9 | identifier = "scope-localdata-recursive"
10 | description = "This scope permits recursive access to the complete `$LOCALDATA` folder, including sub directories and files."
11 |
12 | [[permission.scope.allow]]
13 | path = "$LOCALDATA"
14 | [[permission.scope.allow]]
15 | path = "$LOCALDATA/**"
16 |
17 | [[permission]]
18 | identifier = "scope-localdata"
19 | description = "This scope permits access to all files and list content of top level directories in the `$LOCALDATA` folder."
20 |
21 | [[permission.scope.allow]]
22 | path = "$LOCALDATA"
23 | [[permission.scope.allow]]
24 | path = "$LOCALDATA/*"
25 |
26 | [[permission]]
27 | identifier = "scope-localdata-index"
28 | description = "This scope permits to list all files and folders in the `$LOCALDATA`folder."
29 |
30 | [[permission.scope.allow]]
31 | path = "$LOCALDATA"
32 |
33 | # Sets Section
34 | # This section combines the scope elements with enablement of commands
35 |
36 | [[set]]
37 | identifier = "allow-localdata-read-recursive"
38 | description = "This allows full recursive read access to the complete `$LOCALDATA` folder, files and subdirectories."
39 | permissions = [
40 | "read-all",
41 | "scope-localdata-recursive"
42 | ]
43 |
44 | [[set]]
45 | identifier = "allow-localdata-write-recursive"
46 | description = "This allows full recursive write access to the complete `$LOCALDATA` folder, files and subdirectories."
47 | permissions = [
48 | "write-all",
49 | "scope-localdata-recursive"
50 | ]
51 |
52 | [[set]]
53 | identifier = "allow-localdata-read"
54 | description = "This allows non-recursive read access to the `$LOCALDATA` folder."
55 | permissions = [
56 | "read-all",
57 | "scope-localdata"
58 | ]
59 |
60 | [[set]]
61 | identifier = "allow-localdata-write"
62 | description = "This allows non-recursive write access to the `$LOCALDATA` folder."
63 | permissions = [
64 | "write-all",
65 | "scope-localdata"
66 | ]
67 |
68 | [[set]]
69 | identifier = "allow-localdata-meta-recursive"
70 | description = "This allows full recursive read access to metadata of the `$LOCALDATA` folder, including file listing and statistics."
71 | permissions = [
72 | "read-meta",
73 | "scope-localdata-recursive"
74 | ]
75 |
76 | [[set]]
77 | identifier = "allow-localdata-meta"
78 | description = "This allows non-recursive read access to metadata of the `$LOCALDATA` folder, including file listing and statistics."
79 | permissions = [
80 | "read-meta",
81 | "scope-localdata-index"
82 | ]
--------------------------------------------------------------------------------
/permissions/autogenerated/base-directories/applocaldata.toml:
--------------------------------------------------------------------------------
1 | # Automatically generated - DO NOT EDIT!
2 |
3 | "$schema" = "../../schemas/schema.json"
4 |
5 | # Scopes Section
6 | # This section contains scopes, which define file level access
7 |
8 | [[permission]]
9 | identifier = "scope-applocaldata-recursive"
10 | description = "This scope permits recursive access to the complete `$APPLOCALDATA` folder, including sub directories and files."
11 |
12 | [[permission.scope.allow]]
13 | path = "$APPLOCALDATA"
14 | [[permission.scope.allow]]
15 | path = "$APPLOCALDATA/**"
16 |
17 | [[permission]]
18 | identifier = "scope-applocaldata"
19 | description = "This scope permits access to all files and list content of top level directories in the `$APPLOCALDATA` folder."
20 |
21 | [[permission.scope.allow]]
22 | path = "$APPLOCALDATA"
23 | [[permission.scope.allow]]
24 | path = "$APPLOCALDATA/*"
25 |
26 | [[permission]]
27 | identifier = "scope-applocaldata-index"
28 | description = "This scope permits to list all files and folders in the `$APPLOCALDATA`folder."
29 |
30 | [[permission.scope.allow]]
31 | path = "$APPLOCALDATA"
32 |
33 | # Sets Section
34 | # This section combines the scope elements with enablement of commands
35 |
36 | [[set]]
37 | identifier = "allow-applocaldata-read-recursive"
38 | description = "This allows full recursive read access to the complete `$APPLOCALDATA` folder, files and subdirectories."
39 | permissions = [
40 | "read-all",
41 | "scope-applocaldata-recursive"
42 | ]
43 |
44 | [[set]]
45 | identifier = "allow-applocaldata-write-recursive"
46 | description = "This allows full recursive write access to the complete `$APPLOCALDATA` folder, files and subdirectories."
47 | permissions = [
48 | "write-all",
49 | "scope-applocaldata-recursive"
50 | ]
51 |
52 | [[set]]
53 | identifier = "allow-applocaldata-read"
54 | description = "This allows non-recursive read access to the `$APPLOCALDATA` folder."
55 | permissions = [
56 | "read-all",
57 | "scope-applocaldata"
58 | ]
59 |
60 | [[set]]
61 | identifier = "allow-applocaldata-write"
62 | description = "This allows non-recursive write access to the `$APPLOCALDATA` folder."
63 | permissions = [
64 | "write-all",
65 | "scope-applocaldata"
66 | ]
67 |
68 | [[set]]
69 | identifier = "allow-applocaldata-meta-recursive"
70 | description = "This allows full recursive read access to metadata of the `$APPLOCALDATA` folder, including file listing and statistics."
71 | permissions = [
72 | "read-meta",
73 | "scope-applocaldata-recursive"
74 | ]
75 |
76 | [[set]]
77 | identifier = "allow-applocaldata-meta"
78 | description = "This allows non-recursive read access to metadata of the `$APPLOCALDATA` folder, including file listing and statistics."
79 | permissions = [
80 | "read-meta",
81 | "scope-applocaldata-index"
82 | ]
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | Access the file system.
4 |
5 | | Platform | Supported |
6 | | -------- | --------- |
7 | | Linux | ✓ |
8 | | Windows | ✓ |
9 | | macOS | ✓ |
10 | | Android | ✓ |
11 | | iOS | ✓ |
12 |
13 | ## Install
14 |
15 | _This plugin requires a Rust version of at least **1.77.2**_
16 |
17 | There are three general methods of installation that we can recommend.
18 |
19 | 1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked)
20 | 2. Pull sources directly from Github using git tags / revision hashes (most secure)
21 | 3. Git submodule install this repo in your tauri project and then use file protocol to ingest the source (most secure, but inconvenient to use)
22 |
23 | Install the Core plugin by adding the following to your `Cargo.toml` file:
24 |
25 | `src-tauri/Cargo.toml`
26 |
27 | ```toml
28 | [dependencies]
29 | tauri-plugin-fs = "2.0.0"
30 | # alternatively with Git:
31 | tauri-plugin-fs = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
32 | ```
33 |
34 | You can install the JavaScript Guest bindings using your preferred JavaScript package manager:
35 |
36 | ```sh
37 | pnpm add @tauri-apps/plugin-fs
38 | # or
39 | npm add @tauri-apps/plugin-fs
40 | # or
41 | yarn add @tauri-apps/plugin-fs
42 | ```
43 |
44 | ## Usage
45 |
46 | First you need to register the core plugin with Tauri:
47 |
48 | `src-tauri/src/lib.rs`
49 |
50 | ```rust
51 | fn main() {
52 | tauri::Builder::default()
53 | .plugin(tauri_plugin_fs::init())
54 | .run(tauri::generate_context!())
55 | .expect("error while running tauri application");
56 | }
57 | ```
58 |
59 | Afterwards all the plugin's APIs are available through the JavaScript guest bindings:
60 |
61 | ```javascript
62 | import { stat } from '@tauri-apps/plugin-fs'
63 |
64 | await stat('/path/to/file')
65 | ```
66 |
67 | ## Contributing
68 |
69 | PRs accepted. Please make sure to read the Contributing Guide before making a pull request.
70 |
71 | ## Partners
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 | |
81 |
82 |
83 |
84 |
85 | For the complete list of sponsors please visit our [website](https://tauri.app#sponsors) and [Open Collective](https://opencollective.com/tauri).
86 |
87 | ## License
88 |
89 | Code: (c) 2015 - Present - The Tauri Programme within The Commons Conservancy.
90 |
91 | MIT or MIT/Apache 2.0 where applicable.
92 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 | # Security Policy
2 |
3 | **Do not report security vulnerabilities through public GitHub issues.**
4 |
5 | **Please use the [Private Vulnerability Disclosure](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability) feature of GitHub.**
6 |
7 | Include as much of the following information:
8 |
9 | - Type of issue (e.g. improper input parsing, privilege escalation, etc.)
10 | - The location of the affected source code (tag/branch/commit or direct URL)
11 | - Any special configuration required to reproduce the issue
12 | - The distribution affected or used to help us with reproduction of the issue
13 | - Step-by-step instructions to reproduce the issue
14 | - Ideally a reproduction repository
15 | - Impact of the issue, including how an attacker might exploit the issue
16 |
17 | We prefer to receive reports in English.
18 |
19 | ## Contact
20 |
21 | Please disclose a vulnerability or security relevant issue here: [https://github.com/tauri-apps/plugins-workspace/security/advisories/new](https://github.com/tauri-apps/plugins-workspace/security/advisories/new).
22 |
23 | Alternatively, you can also contact us by email via [security@tauri.app](mailto:security@tauri.app).
24 |
25 | ## Threat Model
26 |
27 | This plugin possibly allows access to the full filesystem available to the application process.
28 | Depending on the operating system the access is already confined (android/ios) to only certain locations.
29 | In other operating systems like Linux/MacOS/Windows it depends on the installation and packaging method but in most cases full
30 | access is granted.
31 |
32 | To prevent exposure of sensitive locations and data this plugin can be scoped to only allow certain base directories
33 | or only access to specific files or subdirectories.
34 | This scoping effectively affects only calls made from the webviews/frontend code and calls made from rust can always circumvent
35 | the restrictions imposed by the scope.
36 |
37 | The scope is defined at compile time in the used permissions but the user or application developer can grant or revoke access to specific files or folders at runtime by modifying the scope state through the runtime authority, if configured during plugin initialization.
38 |
39 | ### Security Assumptions
40 |
41 | - The filesystem access is limited by user permissions
42 | - The operating system filesystem access confinment works as documented
43 | - The scoping mechanism of the Tauri `fs` commands work as intended and has no bypasses
44 | - The user or application developer can grant or revoke access to specific files at runtime by modifying the scope
45 |
46 | #### Out Of Scope
47 |
48 | - Exploits in underlying filesystems
49 | - Exploits in the underlying rust `std::fs` library
50 |
--------------------------------------------------------------------------------
/src/watcher.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2 | // SPDX-License-Identifier: Apache-2.0
3 | // SPDX-License-Identifier: MIT
4 |
5 | use notify::{Config, RecommendedWatcher, RecursiveMode, Watcher};
6 | use notify_debouncer_full::{new_debouncer, DebouncedEvent, Debouncer, RecommendedCache};
7 | use serde::Deserialize;
8 | use tauri::{
9 | ipc::{Channel, CommandScope, GlobalScope},
10 | path::BaseDirectory,
11 | Manager, Resource, ResourceId, Runtime, Webview,
12 | };
13 |
14 | use std::time::Duration;
15 |
16 | use crate::{
17 | commands::{resolve_path, CommandResult},
18 | scope::Entry,
19 | SafeFilePath,
20 | };
21 |
22 | #[allow(unused)]
23 | enum WatcherKind {
24 | Debouncer(Debouncer),
25 | Watcher(RecommendedWatcher),
26 | }
27 |
28 | impl Resource for WatcherKind {}
29 |
30 | #[derive(Clone, Deserialize)]
31 | #[serde(rename_all = "camelCase")]
32 | pub struct WatchOptions {
33 | base_dir: Option,
34 | #[serde(default)]
35 | recursive: bool,
36 | delay_ms: Option,
37 | }
38 |
39 | #[tauri::command]
40 | pub fn watch(
41 | webview: Webview,
42 | paths: Vec,
43 | options: WatchOptions,
44 | on_event: Channel,
45 | global_scope: GlobalScope,
46 | command_scope: CommandScope,
47 | ) -> CommandResult {
48 | let resolved_paths = paths
49 | .into_iter()
50 | .map(|path| {
51 | resolve_path(
52 | "watch",
53 | &webview,
54 | &global_scope,
55 | &command_scope,
56 | path,
57 | options.base_dir,
58 | )
59 | })
60 | .collect::>>()?;
61 |
62 | let recursive_mode = if options.recursive {
63 | RecursiveMode::Recursive
64 | } else {
65 | RecursiveMode::NonRecursive
66 | };
67 |
68 | let watcher_kind = if let Some(delay) = options.delay_ms {
69 | let mut debouncer = new_debouncer(
70 | Duration::from_millis(delay),
71 | None,
72 | move |events: Result, Vec>| {
73 | if let Ok(events) = events {
74 | for event in events {
75 | // TODO: Should errors be emitted too?
76 | let _ = on_event.send(event.event);
77 | }
78 | }
79 | },
80 | )?;
81 | for path in &resolved_paths {
82 | debouncer.watch(path, recursive_mode)?;
83 | }
84 | WatcherKind::Debouncer(debouncer)
85 | } else {
86 | let mut watcher = RecommendedWatcher::new(
87 | move |event| {
88 | if let Ok(event) = event {
89 | // TODO: Should errors be emitted too?
90 | let _ = on_event.send(event);
91 | }
92 | },
93 | Config::default(),
94 | )?;
95 | for path in &resolved_paths {
96 | watcher.watch(path, recursive_mode)?;
97 | }
98 | WatcherKind::Watcher(watcher)
99 | };
100 |
101 | let rid = webview.resources_table().add(watcher_kind);
102 |
103 | Ok(rid)
104 | }
105 |
--------------------------------------------------------------------------------
/android/src/main/java/FsPlugin.kt:
--------------------------------------------------------------------------------
1 | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2 | // SPDX-License-Identifier: Apache-2.0
3 | // SPDX-License-Identifier: MIT
4 |
5 | package com.plugin.fs
6 |
7 | import android.annotation.SuppressLint
8 | import android.app.Activity
9 | import android.content.res.AssetManager.ACCESS_BUFFER
10 | import android.net.Uri
11 | import android.os.ParcelFileDescriptor
12 | import app.tauri.annotation.Command
13 | import app.tauri.annotation.InvokeArg
14 | import app.tauri.annotation.TauriPlugin
15 | import app.tauri.plugin.Invoke
16 | import app.tauri.plugin.JSObject
17 | import app.tauri.plugin.Plugin
18 | import java.io.File
19 | import java.io.FileOutputStream
20 | import java.io.IOException
21 | import java.io.InputStream
22 | import java.io.OutputStream
23 |
24 | @InvokeArg
25 | class WriteTextFileArgs {
26 | val uri: String = ""
27 | val content: String = ""
28 | }
29 |
30 | @InvokeArg
31 | class GetFileDescriptorArgs {
32 | lateinit var uri: String
33 | lateinit var mode: String
34 | }
35 |
36 | @TauriPlugin
37 | class FsPlugin(private val activity: Activity): Plugin(activity) {
38 | @SuppressLint("Recycle")
39 | @Command
40 | fun getFileDescriptor(invoke: Invoke) {
41 | val args = invoke.parseArgs(GetFileDescriptorArgs::class.java)
42 |
43 | val res = JSObject()
44 |
45 | if (args.uri.startsWith(app.tauri.TAURI_ASSETS_DIRECTORY_URI)) {
46 | val path = args.uri.substring(app.tauri.TAURI_ASSETS_DIRECTORY_URI.length)
47 | try {
48 | val fd = activity.assets.openFd(path).parcelFileDescriptor?.detachFd()
49 | res.put("fd", fd)
50 | } catch (e: IOException) {
51 | // if the asset is compressed, we cannot open a file descriptor directly
52 | // so we copy it to the cache and get a fd from there
53 | // this is a lot faster than serializing the file and sending it as invoke response
54 | // because on the Rust side we can leverage the custom protocol IPC and read the file directly
55 | val cacheFile = File(activity.cacheDir, "_assets/$path")
56 | cacheFile.parentFile?.mkdirs()
57 | copyAsset(path, cacheFile)
58 |
59 | val fd = ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(args.mode)).detachFd()
60 | res.put("fd", fd)
61 | }
62 | } else {
63 | val fd = activity.contentResolver.openAssetFileDescriptor(
64 | Uri.parse(args.uri),
65 | args.mode
66 | )?.parcelFileDescriptor?.detachFd()
67 | res.put("fd", fd)
68 | }
69 |
70 | invoke.resolve(res)
71 | }
72 |
73 | @Throws(IOException::class)
74 | private fun copy(input: InputStream, output: OutputStream) {
75 | val buf = ByteArray(1024)
76 | var len: Int
77 | while ((input.read(buf).also { len = it }) > 0) {
78 | output.write(buf, 0, len)
79 | }
80 | }
81 |
82 | @Throws(IOException::class)
83 | private fun copyAsset(assetPath: String, cacheFile: File) {
84 | val input = activity.assets.open(assetPath, ACCESS_BUFFER)
85 | input.use { i ->
86 | val output = FileOutputStream(cacheFile, false)
87 | output.use { o ->
88 | copy(i, o)
89 | }
90 | }
91 | }
92 | }
93 |
94 |
--------------------------------------------------------------------------------
/src/mobile.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2 | // SPDX-License-Identifier: Apache-2.0
3 | // SPDX-License-Identifier: MIT
4 |
5 | use serde::de::DeserializeOwned;
6 | use tauri::{
7 | plugin::{PluginApi, PluginHandle},
8 | AppHandle, Runtime,
9 | };
10 |
11 | use crate::{models::*, FilePath, OpenOptions};
12 |
13 | #[cfg(target_os = "android")]
14 | const PLUGIN_IDENTIFIER: &str = "com.plugin.fs";
15 |
16 | #[cfg(target_os = "ios")]
17 | tauri::ios_plugin_binding!(init_plugin_fs);
18 |
19 | // initializes the Kotlin or Swift plugin classes
20 | pub fn init(
21 | _app: &AppHandle,
22 | api: PluginApi,
23 | ) -> crate::Result> {
24 | #[cfg(target_os = "android")]
25 | let handle = api
26 | .register_android_plugin(PLUGIN_IDENTIFIER, "FsPlugin")
27 | .unwrap();
28 | #[cfg(target_os = "ios")]
29 | let handle = api.register_ios_plugin(init_plugin_android - intent - send)?;
30 | Ok(Fs(handle))
31 | }
32 |
33 | /// Access to the android-intent-send APIs.
34 | pub struct Fs(PluginHandle);
35 |
36 | impl Fs {
37 | pub fn open>(
38 | &self,
39 | path: P,
40 | opts: OpenOptions,
41 | ) -> std::io::Result {
42 | match path.into() {
43 | FilePath::Url(u) => self
44 | .resolve_content_uri(u.to_string(), opts.android_mode())
45 | .map_err(|e| {
46 | std::io::Error::new(
47 | std::io::ErrorKind::Other,
48 | format!("failed to open file: {e}"),
49 | )
50 | }),
51 | FilePath::Path(p) => {
52 | // tauri::utils::platform::resources_dir() returns a PathBuf with the Android asset URI prefix
53 | // we must resolve that file with the Android API
54 | if p.strip_prefix(tauri::utils::platform::ANDROID_ASSET_PROTOCOL_URI_PREFIX)
55 | .is_ok()
56 | {
57 | self.resolve_content_uri(p.to_string_lossy(), opts.android_mode())
58 | .map_err(|e| {
59 | std::io::Error::new(
60 | std::io::ErrorKind::Other,
61 | format!("failed to open file: {e}"),
62 | )
63 | })
64 | } else {
65 | std::fs::OpenOptions::from(opts).open(p)
66 | }
67 | }
68 | }
69 | }
70 |
71 | #[cfg(target_os = "android")]
72 | fn resolve_content_uri(
73 | &self,
74 | uri: impl Into,
75 | mode: impl Into,
76 | ) -> crate::Result {
77 | #[cfg(target_os = "android")]
78 | {
79 | let result = self.0.run_mobile_plugin::(
80 | "getFileDescriptor",
81 | GetFileDescriptorPayload {
82 | uri: uri.into(),
83 | mode: mode.into(),
84 | },
85 | )?;
86 | if let Some(fd) = result.fd {
87 | Ok(unsafe {
88 | use std::os::fd::FromRawFd;
89 | std::fs::File::from_raw_fd(fd)
90 | })
91 | } else {
92 | unimplemented!()
93 | }
94 | }
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/permissions/app.toml:
--------------------------------------------------------------------------------
1 | "$schema" = "schemas/schema.json"
2 |
3 | # Scopes Section
4 | # This section contains scopes, which define file level access
5 |
6 | [[permission]]
7 | identifier = "scope-app-recursive"
8 | description = "This scope permits recursive access to the complete application folders, including sub directories and files."
9 |
10 | [[permission.scope.allow]]
11 | path = "$APPCONFIG"
12 | [[permission.scope.allow]]
13 | path = "$APPCONFIG/**"
14 |
15 | [[permission.scope.allow]]
16 | path = "$APPDATA"
17 | [[permission.scope.allow]]
18 | path = "$APPDATA/**"
19 |
20 | [[permission.scope.allow]]
21 | path = "$APPLOCALDATA"
22 | [[permission.scope.allow]]
23 | path = "$APPLOCALDATA/**"
24 |
25 | [[permission.scope.allow]]
26 | path = "$APPCACHE"
27 | [[permission.scope.allow]]
28 | path = "$APPCACHE/**"
29 |
30 | [[permission.scope.allow]]
31 | path = "$APPLOG"
32 | [[permission.scope.allow]]
33 | path = "$APPLOG/**"
34 |
35 | [[permission]]
36 | identifier = "scope-app"
37 | description = "This scope permits access to all files and list content of top level directories in the application folders."
38 |
39 | [[permission.scope.allow]]
40 | path = "$APPCONFIG"
41 | [[permission.scope.allow]]
42 | path = "$APPCONFIG/*"
43 |
44 | [[permission.scope.allow]]
45 | path = "$APPDATA"
46 | [[permission.scope.allow]]
47 | path = "$APPDATA/*"
48 |
49 | [[permission.scope.allow]]
50 | path = "$APPLOCALDATA"
51 | [[permission.scope.allow]]
52 | path = "$APPLOCALDATA/*"
53 |
54 | [[permission.scope.allow]]
55 | path = "$APPCACHE"
56 | [[permission.scope.allow]]
57 | path = "$APPCACHE/*"
58 |
59 | [[permission.scope.allow]]
60 | path = "$APPLOG"
61 | [[permission.scope.allow]]
62 | path = "$APPLOG/*"
63 |
64 | [[permission]]
65 | identifier = "scope-app-index"
66 | description = "This scope permits to list all files and folders in the application directories."
67 |
68 | [[permission.scope.allow]]
69 | path = "$APPCONFIG"
70 |
71 | [[permission.scope.allow]]
72 | path = "$APPDATA"
73 |
74 | [[permission.scope.allow]]
75 | path = "$APPLOCALDATA"
76 |
77 | [[permission.scope.allow]]
78 | path = "$APPCACHE"
79 |
80 | [[permission.scope.allow]]
81 | path = "$APPLOG"
82 |
83 | # Sets Section
84 | # This section combines the scope elements with enablement of commands
85 |
86 | [[set]]
87 | identifier = "allow-app-read-recursive"
88 | description = "This allows full recursive read access to the complete application folders, files and subdirectories."
89 | permissions = ["read-all", "scope-app-recursive"]
90 |
91 | [[set]]
92 | identifier = "allow-app-write-recursive"
93 | description = "This allows full recursive write access to the complete application folders, files and subdirectories."
94 | permissions = ["write-all", "scope-app-recursive"]
95 |
96 | [[set]]
97 | identifier = "allow-app-read"
98 | description = "This allows non-recursive read access to the application folders."
99 | permissions = ["read-all", "scope-app"]
100 |
101 | [[set]]
102 | identifier = "allow-app-write"
103 | description = "This allows non-recursive write access to the application folders."
104 | permissions = ["write-all", "scope-app"]
105 |
106 | [[set]]
107 | identifier = "allow-app-meta-recursive"
108 | description = "This allows full recursive read access to metadata of the application folders, including file listing and statistics."
109 | permissions = ["read-meta", "scope-app-recursive"]
110 |
111 | [[set]]
112 | identifier = "allow-app-meta"
113 | description = "This allows non-recursive read access to metadata of the application folders, including file listing and statistics."
114 | permissions = ["read-meta", "scope-app-index"]
115 |
--------------------------------------------------------------------------------
/api-iife.js:
--------------------------------------------------------------------------------
1 | if("__TAURI__"in window){var __TAURI_PLUGIN_FS__=function(t){"use strict";function e(t,e,n,i){if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)}function n(t,e,n,i,o){if("function"==typeof e||!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n}var i,o,r,a,s;"function"==typeof SuppressedError&&SuppressedError;const c="__TAURI_TO_IPC_KEY__";class f{constructor(t){i.set(this,void 0),o.set(this,0),r.set(this,[]),a.set(this,void 0),n(this,i,t||(()=>{})),this.id=function(t,e=!1){return window.__TAURI_INTERNALS__.transformCallback(t,e)}((t=>{const s=t.index;if("end"in t)return void(s==e(this,o,"f")?this.cleanupCallback():n(this,a,s));const c=t.message;if(s==e(this,o,"f")){for(e(this,i,"f").call(this,c),n(this,o,e(this,o,"f")+1);e(this,o,"f")in e(this,r,"f");){const t=e(this,r,"f")[e(this,o,"f")];e(this,i,"f").call(this,t),delete e(this,r,"f")[e(this,o,"f")],n(this,o,e(this,o,"f")+1)}e(this,o,"f")===e(this,a,"f")&&this.cleanupCallback()}else e(this,r,"f")[s]=c}))}cleanupCallback(){window.__TAURI_INTERNALS__.unregisterCallback(this.id)}set onmessage(t){n(this,i,t)}get onmessage(){return e(this,i,"f")}[(i=new WeakMap,o=new WeakMap,r=new WeakMap,a=new WeakMap,c)](){return`__CHANNEL__:${this.id}`}toJSON(){return this[c]()}}async function l(t,e={},n){return window.__TAURI_INTERNALS__.invoke(t,e,n)}class u{get rid(){return e(this,s,"f")}constructor(t){s.set(this,void 0),n(this,s,t)}async close(){return l("plugin:resources|close",{rid:this.rid})}}var p,w;function d(t){return{isFile:t.isFile,isDirectory:t.isDirectory,isSymlink:t.isSymlink,size:t.size,mtime:null!==t.mtime?new Date(t.mtime):null,atime:null!==t.atime?new Date(t.atime):null,birthtime:null!==t.birthtime?new Date(t.birthtime):null,readonly:t.readonly,fileAttributes:t.fileAttributes,dev:t.dev,ino:t.ino,mode:t.mode,nlink:t.nlink,uid:t.uid,gid:t.gid,rdev:t.rdev,blksize:t.blksize,blocks:t.blocks}}s=new WeakMap,t.BaseDirectory=void 0,(p=t.BaseDirectory||(t.BaseDirectory={}))[p.Audio=1]="Audio",p[p.Cache=2]="Cache",p[p.Config=3]="Config",p[p.Data=4]="Data",p[p.LocalData=5]="LocalData",p[p.Document=6]="Document",p[p.Download=7]="Download",p[p.Picture=8]="Picture",p[p.Public=9]="Public",p[p.Video=10]="Video",p[p.Resource=11]="Resource",p[p.Temp=12]="Temp",p[p.AppConfig=13]="AppConfig",p[p.AppData=14]="AppData",p[p.AppLocalData=15]="AppLocalData",p[p.AppCache=16]="AppCache",p[p.AppLog=17]="AppLog",p[p.Desktop=18]="Desktop",p[p.Executable=19]="Executable",p[p.Font=20]="Font",p[p.Home=21]="Home",p[p.Runtime=22]="Runtime",p[p.Template=23]="Template",t.SeekMode=void 0,(w=t.SeekMode||(t.SeekMode={}))[w.Start=0]="Start",w[w.Current=1]="Current",w[w.End=2]="End";class h extends u{async read(t){if(0===t.byteLength)return 0;const e=await l("plugin:fs|read",{rid:this.rid,len:t.byteLength}),n=function(t){const e=new Uint8ClampedArray(t),n=e.byteLength;let i=0;for(let t=0;tt instanceof URL?t.toString():t)),options:n,onEvent:o}),a=new L(r);return()=>{a.close()}}return t.FileHandle=h,t.copyFile=async function(t,e,n){if(t instanceof URL&&"file:"!==t.protocol||e instanceof URL&&"file:"!==e.protocol)throw new TypeError("Must be a file URL.");await l("plugin:fs|copy_file",{fromPath:t instanceof URL?t.toString():t,toPath:e instanceof URL?e.toString():e,options:n})},t.create=async function(t,e){if(t instanceof URL&&"file:"!==t.protocol)throw new TypeError("Must be a file URL.");const n=await l("plugin:fs|create",{path:t instanceof URL?t.toString():t,options:e});return new h(n)},t.exists=async function(t,e){if(t instanceof URL&&"file:"!==t.protocol)throw new TypeError("Must be a file URL.");return await l("plugin:fs|exists",{path:t instanceof URL?t.toString():t,options:e})},t.lstat=async function(t,e){return d(await l("plugin:fs|lstat",{path:t instanceof URL?t.toString():t,options:e}))},t.mkdir=async function(t,e){if(t instanceof URL&&"file:"!==t.protocol)throw new TypeError("Must be a file URL.");await l("plugin:fs|mkdir",{path:t instanceof URL?t.toString():t,options:e})},t.open=y,t.readDir=async function(t,e){if(t instanceof URL&&"file:"!==t.protocol)throw new TypeError("Must be a file URL.");return await l("plugin:fs|read_dir",{path:t instanceof URL?t.toString():t,options:e})},t.readFile=async function(t,e){if(t instanceof URL&&"file:"!==t.protocol)throw new TypeError("Must be a file URL.");const n=await l("plugin:fs|read_file",{path:t instanceof URL?t.toString():t,options:e});return n instanceof ArrayBuffer?new Uint8Array(n):Uint8Array.from(n)},t.readTextFile=async function(t,e){if(t instanceof URL&&"file:"!==t.protocol)throw new TypeError("Must be a file URL.");const n=await l("plugin:fs|read_text_file",{path:t instanceof URL?t.toString():t,options:e}),i=n instanceof ArrayBuffer?n:Uint8Array.from(n);return(new TextDecoder).decode(i)},t.readTextFileLines=async function(t,e){if(t instanceof URL&&"file:"!==t.protocol)throw new TypeError("Must be a file URL.");const n=t instanceof URL?t.toString():t;return await Promise.resolve({path:n,rid:null,async next(){null===this.rid&&(this.rid=await l("plugin:fs|read_text_file_lines",{path:n,options:e}));const t=await l("plugin:fs|read_text_file_lines_next",{rid:this.rid}),i=t instanceof ArrayBuffer?new Uint8Array(t):Uint8Array.from(t),o=1===i[i.byteLength-1];if(o)return this.rid=null,{value:null,done:o};return{value:(new TextDecoder).decode(i.slice(0,i.byteLength-1)),done:o}},[Symbol.asyncIterator](){return this}})},t.remove=async function(t,e){if(t instanceof URL&&"file:"!==t.protocol)throw new TypeError("Must be a file URL.");await l("plugin:fs|remove",{path:t instanceof URL?t.toString():t,options:e})},t.rename=async function(t,e,n){if(t instanceof URL&&"file:"!==t.protocol||e instanceof URL&&"file:"!==e.protocol)throw new TypeError("Must be a file URL.");await l("plugin:fs|rename",{oldPath:t instanceof URL?t.toString():t,newPath:e instanceof URL?e.toString():e,options:n})},t.size=async function(t){if(t instanceof URL&&"file:"!==t.protocol)throw new TypeError("Must be a file URL.");return await l("plugin:fs|size",{path:t instanceof URL?t.toString():t})},t.stat=async function(t,e){return d(await l("plugin:fs|stat",{path:t instanceof URL?t.toString():t,options:e}))},t.truncate=async function(t,e,n){if(t instanceof URL&&"file:"!==t.protocol)throw new TypeError("Must be a file URL.");await l("plugin:fs|truncate",{path:t instanceof URL?t.toString():t,len:e,options:n})},t.watch=async function(t,e,n){return await R(t,e,{delayMs:2e3,...n})},t.watchImmediate=async function(t,e,n){return await R(t,e,{...n,delayMs:void 0})},t.writeFile=async function(t,e,n){if(t instanceof URL&&"file:"!==t.protocol)throw new TypeError("Must be a file URL.");if(e instanceof ReadableStream){const i=await y(t,{read:!1,create:!0,write:!0,...n}),o=e.getReader();try{for(;;){const{done:t,value:e}=await o.read();if(t)break;await i.write(e)}}finally{o.releaseLock(),await i.close()}}else await l("plugin:fs|write_file",e,{headers:{path:encodeURIComponent(t instanceof URL?t.toString():t),options:JSON.stringify(n)}})},t.writeTextFile=async function(t,e,n){if(t instanceof URL&&"file:"!==t.protocol)throw new TypeError("Must be a file URL.");const i=new TextEncoder;await l("plugin:fs|write_text_file",i.encode(e),{headers:{path:encodeURIComponent(t instanceof URL?t.toString():t),options:JSON.stringify(n)}})},t}({});Object.defineProperty(window.__TAURI__,"fs",{value:__TAURI_PLUGIN_FS__})}
2 |
--------------------------------------------------------------------------------
/src/file_path.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2 | // SPDX-License-Identifier: Apache-2.0
3 | // SPDX-License-Identifier: MIT
4 |
5 | use std::{
6 | convert::Infallible,
7 | path::{Path, PathBuf},
8 | str::FromStr,
9 | };
10 |
11 | use serde::Serialize;
12 | use tauri::path::SafePathBuf;
13 |
14 | use crate::{Error, Result};
15 |
16 | /// Represents either a filesystem path or a URI pointing to a file
17 | /// such as `file://` URIs or Android `content://` URIs.
18 | #[derive(Debug, Serialize, Clone)]
19 | #[serde(untagged)]
20 | pub enum FilePath {
21 | /// `file://` URIs or Android `content://` URIs.
22 | Url(url::Url),
23 | /// Regular [`PathBuf`]
24 | Path(PathBuf),
25 | }
26 |
27 | /// Represents either a safe filesystem path or a URI pointing to a file
28 | /// such as `file://` URIs or Android `content://` URIs.
29 | #[derive(Debug, Clone, Serialize)]
30 | pub enum SafeFilePath {
31 | /// `file://` URIs or Android `content://` URIs.
32 | Url(url::Url),
33 | /// Safe [`PathBuf`], see [`SafePathBuf``].
34 | Path(SafePathBuf),
35 | }
36 |
37 | impl FilePath {
38 | /// Get a reference to the contained [`Path`] if the variant is [`FilePath::Path`].
39 | ///
40 | /// Use [`FilePath::into_path`] to try to convert the [`FilePath::Url`] variant as well.
41 | #[inline]
42 | pub fn as_path(&self) -> Option<&Path> {
43 | match self {
44 | Self::Url(_) => None,
45 | Self::Path(p) => Some(p),
46 | }
47 | }
48 |
49 | /// Try to convert into [`PathBuf`] if possible.
50 | ///
51 | /// This calls [`Url::to_file_path`](url::Url::to_file_path) if the variant is [`FilePath::Url`],
52 | /// otherwise returns the contained [PathBuf] as is.
53 | #[inline]
54 | pub fn into_path(self) -> Result {
55 | match self {
56 | Self::Url(url) => url.to_file_path().map_err(|_| Error::InvalidPathUrl),
57 | Self::Path(p) => Ok(p),
58 | }
59 | }
60 |
61 | /// Takes the contained [`PathBuf`] if the variant is [`FilePath::Path`],
62 | /// and when possible, converts Windows UNC paths to regular paths.
63 | #[inline]
64 | pub fn simplified(self) -> Self {
65 | match self {
66 | Self::Url(url) => Self::Url(url),
67 | Self::Path(p) => Self::Path(dunce::simplified(&p).to_path_buf()),
68 | }
69 | }
70 | }
71 |
72 | impl SafeFilePath {
73 | /// Get a reference to the contained [`Path`] if the variant is [`SafeFilePath::Path`].
74 | ///
75 | /// Use [`SafeFilePath::into_path`] to try to convert the [`SafeFilePath::Url`] variant as well.
76 | #[inline]
77 | pub fn as_path(&self) -> Option<&Path> {
78 | match self {
79 | Self::Url(_) => None,
80 | Self::Path(p) => Some(p.as_ref()),
81 | }
82 | }
83 |
84 | /// Try to convert into [`PathBuf`] if possible.
85 | ///
86 | /// This calls [`Url::to_file_path`](url::Url::to_file_path) if the variant is [`SafeFilePath::Url`],
87 | /// otherwise returns the contained [PathBuf] as is.
88 | #[inline]
89 | pub fn into_path(self) -> Result {
90 | match self {
91 | Self::Url(url) => url.to_file_path().map_err(|_| Error::InvalidPathUrl),
92 | Self::Path(p) => Ok(p.as_ref().to_owned()),
93 | }
94 | }
95 |
96 | /// Takes the contained [`PathBuf`] if the variant is [`SafeFilePath::Path`],
97 | /// and when possible, converts Windows UNC paths to regular paths.
98 | #[inline]
99 | pub fn simplified(self) -> Self {
100 | match self {
101 | Self::Url(url) => Self::Url(url),
102 | Self::Path(p) => {
103 | // Safe to unwrap since it was a safe file path already
104 | Self::Path(SafePathBuf::new(dunce::simplified(p.as_ref()).to_path_buf()).unwrap())
105 | }
106 | }
107 | }
108 | }
109 |
110 | impl std::fmt::Display for FilePath {
111 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112 | match self {
113 | Self::Url(u) => u.fmt(f),
114 | Self::Path(p) => p.display().fmt(f),
115 | }
116 | }
117 | }
118 |
119 | impl std::fmt::Display for SafeFilePath {
120 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121 | match self {
122 | Self::Url(u) => u.fmt(f),
123 | Self::Path(p) => p.display().fmt(f),
124 | }
125 | }
126 | }
127 |
128 | impl<'de> serde::Deserialize<'de> for FilePath {
129 | fn deserialize(deserializer: D) -> std::result::Result
130 | where
131 | D: serde::Deserializer<'de>,
132 | {
133 | struct FilePathVisitor;
134 |
135 | impl serde::de::Visitor<'_> for FilePathVisitor {
136 | type Value = FilePath;
137 |
138 | fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
139 | formatter.write_str("a string representing an file URL or a path")
140 | }
141 |
142 | fn visit_str(self, s: &str) -> std::result::Result
143 | where
144 | E: serde::de::Error,
145 | {
146 | FilePath::from_str(s).map_err(|e| {
147 | serde::de::Error::invalid_value(
148 | serde::de::Unexpected::Str(s),
149 | &e.to_string().as_str(),
150 | )
151 | })
152 | }
153 | }
154 |
155 | deserializer.deserialize_str(FilePathVisitor)
156 | }
157 | }
158 |
159 | impl<'de> serde::Deserialize<'de> for SafeFilePath {
160 | fn deserialize(deserializer: D) -> std::result::Result
161 | where
162 | D: serde::Deserializer<'de>,
163 | {
164 | struct SafeFilePathVisitor;
165 |
166 | impl serde::de::Visitor<'_> for SafeFilePathVisitor {
167 | type Value = SafeFilePath;
168 |
169 | fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
170 | formatter.write_str("a string representing an file URL or a path")
171 | }
172 |
173 | fn visit_str(self, s: &str) -> std::result::Result
174 | where
175 | E: serde::de::Error,
176 | {
177 | SafeFilePath::from_str(s).map_err(|e| {
178 | serde::de::Error::invalid_value(
179 | serde::de::Unexpected::Str(s),
180 | &e.to_string().as_str(),
181 | )
182 | })
183 | }
184 | }
185 |
186 | deserializer.deserialize_str(SafeFilePathVisitor)
187 | }
188 | }
189 |
190 | impl FromStr for FilePath {
191 | type Err = Infallible;
192 | fn from_str(s: &str) -> std::result::Result {
193 | if let Ok(url) = url::Url::from_str(s) {
194 | if url.scheme().len() != 1 {
195 | return Ok(Self::Url(url));
196 | }
197 | }
198 | Ok(Self::Path(PathBuf::from(s)))
199 | }
200 | }
201 |
202 | impl FromStr for SafeFilePath {
203 | type Err = Error;
204 | fn from_str(s: &str) -> Result {
205 | if let Ok(url) = url::Url::from_str(s) {
206 | if url.scheme().len() != 1 {
207 | return Ok(Self::Url(url));
208 | }
209 | }
210 |
211 | SafePathBuf::new(s.into())
212 | .map(SafeFilePath::Path)
213 | .map_err(Error::UnsafePathBuf)
214 | }
215 | }
216 |
217 | impl From for FilePath {
218 | fn from(value: PathBuf) -> Self {
219 | Self::Path(value)
220 | }
221 | }
222 |
223 | impl TryFrom for SafeFilePath {
224 | type Error = Error;
225 | fn try_from(value: PathBuf) -> Result {
226 | SafePathBuf::new(value)
227 | .map(SafeFilePath::Path)
228 | .map_err(Error::UnsafePathBuf)
229 | }
230 | }
231 |
232 | impl From<&Path> for FilePath {
233 | fn from(value: &Path) -> Self {
234 | Self::Path(value.to_owned())
235 | }
236 | }
237 |
238 | impl TryFrom<&Path> for SafeFilePath {
239 | type Error = Error;
240 | fn try_from(value: &Path) -> Result {
241 | SafePathBuf::new(value.to_path_buf())
242 | .map(SafeFilePath::Path)
243 | .map_err(Error::UnsafePathBuf)
244 | }
245 | }
246 |
247 | impl From<&PathBuf> for FilePath {
248 | fn from(value: &PathBuf) -> Self {
249 | Self::Path(value.to_owned())
250 | }
251 | }
252 |
253 | impl TryFrom<&PathBuf> for SafeFilePath {
254 | type Error = Error;
255 | fn try_from(value: &PathBuf) -> Result {
256 | SafePathBuf::new(value.to_owned())
257 | .map(SafeFilePath::Path)
258 | .map_err(Error::UnsafePathBuf)
259 | }
260 | }
261 |
262 | impl From for FilePath {
263 | fn from(value: url::Url) -> Self {
264 | Self::Url(value)
265 | }
266 | }
267 |
268 | impl From for SafeFilePath {
269 | fn from(value: url::Url) -> Self {
270 | Self::Url(value)
271 | }
272 | }
273 |
274 | impl TryFrom for PathBuf {
275 | type Error = Error;
276 | fn try_from(value: FilePath) -> Result {
277 | value.into_path()
278 | }
279 | }
280 |
281 | impl TryFrom for PathBuf {
282 | type Error = Error;
283 | fn try_from(value: SafeFilePath) -> Result {
284 | value.into_path()
285 | }
286 | }
287 |
288 | impl From for FilePath {
289 | fn from(value: SafeFilePath) -> Self {
290 | match value {
291 | SafeFilePath::Url(url) => FilePath::Url(url),
292 | SafeFilePath::Path(p) => FilePath::Path(p.as_ref().to_owned()),
293 | }
294 | }
295 | }
296 |
297 | impl TryFrom for SafeFilePath {
298 | type Error = Error;
299 |
300 | fn try_from(value: FilePath) -> Result {
301 | match value {
302 | FilePath::Url(url) => Ok(SafeFilePath::Url(url)),
303 | FilePath::Path(p) => SafePathBuf::new(p)
304 | .map(SafeFilePath::Path)
305 | .map_err(Error::UnsafePathBuf),
306 | }
307 | }
308 | }
309 |
--------------------------------------------------------------------------------
/LICENSE_APACHE-2.0:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
--------------------------------------------------------------------------------
/src/lib.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2 | // SPDX-License-Identifier: Apache-2.0
3 | // SPDX-License-Identifier: MIT
4 |
5 | //! Access the file system.
6 |
7 | #![doc(
8 | html_logo_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png",
9 | html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png"
10 | )]
11 |
12 | use std::io::Read;
13 |
14 | use serde::Deserialize;
15 | use tauri::{
16 | ipc::ScopeObject,
17 | plugin::{Builder as PluginBuilder, TauriPlugin},
18 | utils::{acl::Value, config::FsScope},
19 | AppHandle, DragDropEvent, Manager, RunEvent, Runtime, WindowEvent,
20 | };
21 |
22 | mod commands;
23 | mod config;
24 | #[cfg(not(target_os = "android"))]
25 | mod desktop;
26 | mod error;
27 | mod file_path;
28 | #[cfg(target_os = "android")]
29 | mod mobile;
30 | #[cfg(target_os = "android")]
31 | mod models;
32 | mod scope;
33 | #[cfg(feature = "watch")]
34 | mod watcher;
35 |
36 | #[cfg(not(target_os = "android"))]
37 | pub use desktop::Fs;
38 | #[cfg(target_os = "android")]
39 | pub use mobile::Fs;
40 |
41 | pub use error::Error;
42 |
43 | pub use file_path::FilePath;
44 | pub use file_path::SafeFilePath;
45 |
46 | type Result = std::result::Result;
47 |
48 | #[derive(Debug, Default, Clone, Deserialize)]
49 | #[serde(rename_all = "camelCase")]
50 | pub struct OpenOptions {
51 | #[serde(default = "default_true")]
52 | read: bool,
53 | #[serde(default)]
54 | write: bool,
55 | #[serde(default)]
56 | append: bool,
57 | #[serde(default)]
58 | truncate: bool,
59 | #[serde(default)]
60 | create: bool,
61 | #[serde(default)]
62 | create_new: bool,
63 | #[serde(default)]
64 | #[allow(unused)]
65 | mode: Option,
66 | #[serde(default)]
67 | #[allow(unused)]
68 | custom_flags: Option,
69 | }
70 |
71 | fn default_true() -> bool {
72 | true
73 | }
74 |
75 | impl From for std::fs::OpenOptions {
76 | fn from(open_options: OpenOptions) -> Self {
77 | let mut opts = std::fs::OpenOptions::new();
78 |
79 | #[cfg(unix)]
80 | {
81 | use std::os::unix::fs::OpenOptionsExt;
82 | if let Some(mode) = open_options.mode {
83 | opts.mode(mode);
84 | }
85 | if let Some(flags) = open_options.custom_flags {
86 | opts.custom_flags(flags);
87 | }
88 | }
89 |
90 | opts.read(open_options.read)
91 | .write(open_options.write)
92 | .create(open_options.create)
93 | .append(open_options.append)
94 | .truncate(open_options.truncate)
95 | .create_new(open_options.create_new);
96 |
97 | opts
98 | }
99 | }
100 |
101 | impl OpenOptions {
102 | /// Creates a blank new set of options ready for configuration.
103 | ///
104 | /// All options are initially set to `false`.
105 | ///
106 | /// # Examples
107 | ///
108 | /// ```no_run
109 | /// use tauri_plugin_fs::OpenOptions;
110 | ///
111 | /// let mut options = OpenOptions::new();
112 | /// let file = options.read(true).open("foo.txt");
113 | /// ```
114 | #[must_use]
115 | pub fn new() -> Self {
116 | Self::default()
117 | }
118 |
119 | /// Sets the option for read access.
120 | ///
121 | /// This option, when true, will indicate that the file should be
122 | /// `read`-able if opened.
123 | ///
124 | /// # Examples
125 | ///
126 | /// ```no_run
127 | /// use tauri_plugin_fs::OpenOptions;
128 | ///
129 | /// let file = OpenOptions::new().read(true).open("foo.txt");
130 | /// ```
131 | pub fn read(&mut self, read: bool) -> &mut Self {
132 | self.read = read;
133 | self
134 | }
135 |
136 | /// Sets the option for write access.
137 | ///
138 | /// This option, when true, will indicate that the file should be
139 | /// `write`-able if opened.
140 | ///
141 | /// If the file already exists, any write calls on it will overwrite its
142 | /// contents, without truncating it.
143 | ///
144 | /// # Examples
145 | ///
146 | /// ```no_run
147 | /// use tauri_plugin_fs::OpenOptions;
148 | ///
149 | /// let file = OpenOptions::new().write(true).open("foo.txt");
150 | /// ```
151 | pub fn write(&mut self, write: bool) -> &mut Self {
152 | self.write = write;
153 | self
154 | }
155 |
156 | /// Sets the option for the append mode.
157 | ///
158 | /// This option, when true, means that writes will append to a file instead
159 | /// of overwriting previous contents.
160 | /// Note that setting `.write(true).append(true)` has the same effect as
161 | /// setting only `.append(true)`.
162 | ///
163 | /// Append mode guarantees that writes will be positioned at the current end of file,
164 | /// even when there are other processes or threads appending to the same file. This is
165 | /// unlike [seek]\([SeekFrom]::[End]\(0)) followed by `write()`, which
166 | /// has a race between seeking and writing during which another writer can write, with
167 | /// our `write()` overwriting their data.
168 | ///
169 | /// Keep in mind that this does not necessarily guarantee that data appended by
170 | /// different processes or threads does not interleave. The amount of data accepted a
171 | /// single `write()` call depends on the operating system and file system. A
172 | /// successful `write()` is allowed to write only part of the given data, so even if
173 | /// you're careful to provide the whole message in a single call to `write()`, there
174 | /// is no guarantee that it will be written out in full. If you rely on the filesystem
175 | /// accepting the message in a single write, make sure that all data that belongs
176 | /// together is written in one operation. This can be done by concatenating strings
177 | /// before passing them to [`write()`].
178 | ///
179 | /// If a file is opened with both read and append access, beware that after
180 | /// opening, and after every write, the position for reading may be set at the
181 | /// end of the file. So, before writing, save the current position (using
182 | /// [Seek]::[stream_position]), and restore it before the next read.
183 | ///
184 | /// ## Note
185 | ///
186 | /// This function doesn't create the file if it doesn't exist. Use the
187 | /// [`OpenOptions::create`] method to do so.
188 | ///
189 | /// [`write()`]: Write::write "io::Write::write"
190 | /// [`flush()`]: Write::flush "io::Write::flush"
191 | /// [stream_position]: Seek::stream_position "io::Seek::stream_position"
192 | /// [seek]: Seek::seek "io::Seek::seek"
193 | /// [Current]: SeekFrom::Current "io::SeekFrom::Current"
194 | /// [End]: SeekFrom::End "io::SeekFrom::End"
195 | ///
196 | /// # Examples
197 | ///
198 | /// ```no_run
199 | /// use tauri_plugin_fs::OpenOptions;
200 | ///
201 | /// let file = OpenOptions::new().append(true).open("foo.txt");
202 | /// ```
203 | pub fn append(&mut self, append: bool) -> &mut Self {
204 | self.append = append;
205 | self
206 | }
207 |
208 | /// Sets the option for truncating a previous file.
209 | ///
210 | /// If a file is successfully opened with this option set it will truncate
211 | /// the file to 0 length if it already exists.
212 | ///
213 | /// The file must be opened with write access for truncate to work.
214 | ///
215 | /// # Examples
216 | ///
217 | /// ```no_run
218 | /// use tauri_plugin_fs::OpenOptions;
219 | ///
220 | /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
221 | /// ```
222 | pub fn truncate(&mut self, truncate: bool) -> &mut Self {
223 | self.truncate = truncate;
224 | self
225 | }
226 |
227 | /// Sets the option to create a new file, or open it if it already exists.
228 | ///
229 | /// In order for the file to be created, [`OpenOptions::write`] or
230 | /// [`OpenOptions::append`] access must be used.
231 | ///
232 | ///
233 | /// # Examples
234 | ///
235 | /// ```no_run
236 | /// use tauri_plugin_fs::OpenOptions;
237 | ///
238 | /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
239 | /// ```
240 | pub fn create(&mut self, create: bool) -> &mut Self {
241 | self.create = create;
242 | self
243 | }
244 |
245 | /// Sets the option to create a new file, failing if it already exists.
246 | ///
247 | /// No file is allowed to exist at the target location, also no (dangling) symlink. In this
248 | /// way, if the call succeeds, the file returned is guaranteed to be new.
249 | /// If a file exists at the target location, creating a new file will fail with [`AlreadyExists`]
250 | /// or another error based on the situation. See [`OpenOptions::open`] for a
251 | /// non-exhaustive list of likely errors.
252 | ///
253 | /// This option is useful because it is atomic. Otherwise between checking
254 | /// whether a file exists and creating a new one, the file may have been
255 | /// created by another process (a TOCTOU race condition / attack).
256 | ///
257 | /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
258 | /// ignored.
259 | ///
260 | /// The file must be opened with write or append access in order to create
261 | /// a new file.
262 | ///
263 | /// [`.create()`]: OpenOptions::create
264 | /// [`.truncate()`]: OpenOptions::truncate
265 | /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
266 | ///
267 | /// # Examples
268 | ///
269 | /// ```no_run
270 | /// use tauri_plugin_fs::OpenOptions;
271 | ///
272 | /// let file = OpenOptions::new().write(true)
273 | /// .create_new(true)
274 | /// .open("foo.txt");
275 | /// ```
276 | pub fn create_new(&mut self, create_new: bool) -> &mut Self {
277 | self.create_new = create_new;
278 | self
279 | }
280 | }
281 |
282 | #[cfg(unix)]
283 | impl std::os::unix::fs::OpenOptionsExt for OpenOptions {
284 | fn custom_flags(&mut self, flags: i32) -> &mut Self {
285 | self.custom_flags.replace(flags);
286 | self
287 | }
288 |
289 | fn mode(&mut self, mode: u32) -> &mut Self {
290 | self.mode.replace(mode);
291 | self
292 | }
293 | }
294 |
295 | impl OpenOptions {
296 | #[cfg(target_os = "android")]
297 | fn android_mode(&self) -> String {
298 | let mut mode = String::new();
299 |
300 | if self.read {
301 | mode.push('r');
302 | }
303 | if self.write {
304 | mode.push('w');
305 | }
306 | if self.truncate {
307 | mode.push('t');
308 | }
309 | if self.append {
310 | mode.push('a');
311 | }
312 |
313 | mode
314 | }
315 | }
316 |
317 | impl Fs {
318 | pub fn read_to_string>(&self, path: P) -> std::io::Result {
319 | let mut s = String::new();
320 | self.open(
321 | path,
322 | OpenOptions {
323 | read: true,
324 | ..Default::default()
325 | },
326 | )?
327 | .read_to_string(&mut s)?;
328 | Ok(s)
329 | }
330 |
331 | pub fn read>(&self, path: P) -> std::io::Result> {
332 | let mut buf = Vec::new();
333 | self.open(
334 | path,
335 | OpenOptions {
336 | read: true,
337 | ..Default::default()
338 | },
339 | )?
340 | .read_to_end(&mut buf)?;
341 | Ok(buf)
342 | }
343 | }
344 |
345 | // implement ScopeObject here instead of in the scope module because it is also used on the build script
346 | // and we don't want to add tauri as a build dependency
347 | impl ScopeObject for scope::Entry {
348 | type Error = Error;
349 | fn deserialize(
350 | app: &AppHandle,
351 | raw: Value,
352 | ) -> std::result::Result {
353 | let path = serde_json::from_value(raw.into()).map(|raw| match raw {
354 | scope::EntryRaw::Value(path) => path,
355 | scope::EntryRaw::Object { path } => path,
356 | })?;
357 |
358 | match app.path().parse(path) {
359 | Ok(path) => Ok(Self { path: Some(path) }),
360 | #[cfg(not(target_os = "android"))]
361 | Err(tauri::Error::UnknownPath) => Ok(Self { path: None }),
362 | Err(err) => Err(err.into()),
363 | }
364 | }
365 | }
366 |
367 | pub(crate) struct Scope {
368 | pub(crate) scope: tauri::fs::Scope,
369 | pub(crate) require_literal_leading_dot: Option,
370 | }
371 |
372 | pub trait FsExt {
373 | fn fs_scope(&self) -> tauri::fs::Scope;
374 | fn try_fs_scope(&self) -> Option;
375 |
376 | /// Cross platform file system APIs that also support manipulating Android files.
377 | fn fs(&self) -> &Fs;
378 | }
379 |
380 | impl> FsExt for T {
381 | fn fs_scope(&self) -> tauri::fs::Scope {
382 | self.state::().scope.clone()
383 | }
384 |
385 | fn try_fs_scope(&self) -> Option {
386 | self.try_state::().map(|s| s.scope.clone())
387 | }
388 |
389 | fn fs(&self) -> &Fs {
390 | self.state::>().inner()
391 | }
392 | }
393 |
394 | pub fn init() -> TauriPlugin> {
395 | PluginBuilder::>::new("fs")
396 | .invoke_handler(tauri::generate_handler![
397 | commands::create,
398 | commands::open,
399 | commands::copy_file,
400 | commands::mkdir,
401 | commands::read_dir,
402 | commands::read,
403 | commands::read_file,
404 | commands::read_text_file,
405 | commands::read_text_file_lines,
406 | commands::read_text_file_lines_next,
407 | commands::remove,
408 | commands::rename,
409 | commands::seek,
410 | commands::stat,
411 | commands::lstat,
412 | commands::fstat,
413 | commands::truncate,
414 | commands::ftruncate,
415 | commands::write,
416 | commands::write_file,
417 | commands::write_text_file,
418 | commands::exists,
419 | commands::size,
420 | #[cfg(feature = "watch")]
421 | watcher::watch,
422 | ])
423 | .setup(|app, api| {
424 | let scope = Scope {
425 | require_literal_leading_dot: api
426 | .config()
427 | .as_ref()
428 | .and_then(|c| c.require_literal_leading_dot),
429 | scope: tauri::fs::Scope::new(app, &FsScope::default())?,
430 | };
431 |
432 | #[cfg(target_os = "android")]
433 | {
434 | let fs = mobile::init(app, api)?;
435 | app.manage(fs);
436 | }
437 | #[cfg(not(target_os = "android"))]
438 | app.manage(Fs(app.clone()));
439 |
440 | app.manage(scope);
441 | Ok(())
442 | })
443 | .on_event(|app, event| {
444 | if let RunEvent::WindowEvent {
445 | label: _,
446 | event: WindowEvent::DragDrop(DragDropEvent::Drop { paths, position: _ }),
447 | ..
448 | } = event
449 | {
450 | let scope = app.fs_scope();
451 | for path in paths {
452 | if path.is_file() {
453 | let _ = scope.allow_file(path);
454 | } else {
455 | let _ = scope.allow_directory(path, true);
456 | }
457 | }
458 | }
459 | })
460 | .build()
461 | }
462 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | ## \[2.4.4]
4 |
5 | - [`93426f85`](https://github.com/tauri-apps/plugins-workspace/commit/93426f85120f49beb9f40222bff45185a32d54a9) Fixed an issue that caused docs.rs builds to fail. No user facing changes.
6 |
7 | ## \[2.4.3]
8 |
9 | - [`6c9b61fb`](https://github.com/tauri-apps/plugins-workspace/commit/6c9b61fb658145d13893626112fc489f7458aa17) ([#3039](https://github.com/tauri-apps/plugins-workspace/pull/3039) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) On Android, updated compileSdk to 36.
10 | - [`6b5b1053`](https://github.com/tauri-apps/plugins-workspace/commit/6b5b1053ba8aeb789dd5cb5fb05b7e98f3b8de0b) ([#1939](https://github.com/tauri-apps/plugins-workspace/pull/1939) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Enhance error messages.
11 |
12 | ## \[2.4.2]
13 |
14 | - [`4eb36b0f`](https://github.com/tauri-apps/plugins-workspace/commit/4eb36b0ff57acb0bb1b911c583efa3bf2f56aa32) ([#2907](https://github.com/tauri-apps/plugins-workspace/pull/2907) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Fixed calling `writeFile` with `data: ReadableStream` throws `Invalid argument`
15 | - [`515182a1`](https://github.com/tauri-apps/plugins-workspace/commit/515182a179d4439079b2b7f6927555ba5ab0b035) ([#2915](https://github.com/tauri-apps/plugins-workspace/pull/2915) by [@samhinshaw](https://github.com/tauri-apps/plugins-workspace/../../samhinshaw)) `readFile` now returns a more specific type `Promise>` instead of the default `Promise`
16 |
17 | ## \[2.4.1]
18 |
19 | - [`44a1f659`](https://github.com/tauri-apps/plugins-workspace/commit/44a1f659125a341191420e650608b0b6ff316a0e) ([#2846](https://github.com/tauri-apps/plugins-workspace/pull/2846) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Fix `writeFile` doesn't create a new file by default when the data is a `ReadableStream`
20 |
21 | ## \[2.4.0]
22 |
23 | - [`f209b2f2`](https://github.com/tauri-apps/plugins-workspace/commit/f209b2f23cb29133c97ad5961fb46ef794dbe063) ([#2804](https://github.com/tauri-apps/plugins-workspace/pull/2804) by [@renovate](https://github.com/tauri-apps/plugins-workspace/../../renovate)) Updated tauri to 2.6
24 |
25 | ## \[2.3.0]
26 |
27 | - [`dac4d537`](https://github.com/tauri-apps/plugins-workspace/commit/dac4d53724bb3430a00a3f0119857cba32a031e8) ([#2613](https://github.com/tauri-apps/plugins-workspace/pull/2613) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Reduce the overhead of `watch` and `unwatch`
28 |
29 | ## \[2.2.1]
30 |
31 | ### bug
32 |
33 | - [`831c35ff`](https://github.com/tauri-apps/plugins-workspace/commit/831c35ff3940e841fe4418bb4cb104038b03304b) ([#2550](https://github.com/tauri-apps/plugins-workspace/pull/2550)) Fix `writeFile` ReadableStream handling due to missing async iterator support on macOS platform
34 |
35 | ## \[2.2.0]
36 |
37 | - [`3a79266b`](https://github.com/tauri-apps/plugins-workspace/commit/3a79266b8cf96a55b1ae6339d725567d45a44b1d) ([#2173](https://github.com/tauri-apps/plugins-workspace/pull/2173) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) Bumped all plugins to `v2.2.0`. From now, the versions for the Rust and JavaScript packages of each plugin will be in sync with each other.
38 |
39 | ## \[2.0.4]
40 |
41 | - [`77b85507`](https://github.com/tauri-apps/plugins-workspace/commit/77b855074aad612f2b28e6a3b5881fac767a05ae) ([#2171](https://github.com/tauri-apps/plugins-workspace/pull/2171) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) Fixed docs.rs build.
42 |
43 | ## \[2.0.3]
44 |
45 | - [`ed981027`](https://github.com/tauri-apps/plugins-workspace/commit/ed981027dd4fba7d0e2f836eb5db34d344388d73) ([#1962](https://github.com/tauri-apps/plugins-workspace/pull/1962) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Improve performance of `readTextFile` and `readTextFileLines` APIs
46 | - [`3e78173d`](https://github.com/tauri-apps/plugins-workspace/commit/3e78173df9ce90aa3b19e1f36d1f8712c5020fb6) ([#2018](https://github.com/tauri-apps/plugins-workspace/pull/2018) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Fix `readDir` function failing to read directories that contain broken symlinks.
47 | - [`5092ea5e`](https://github.com/tauri-apps/plugins-workspace/commit/5092ea5e89817c0550d09b0a4ad17bf1253b23df) ([#1964](https://github.com/tauri-apps/plugins-workspace/pull/1964) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Add support for using `ReadableStream` with `writeFile` API.
48 |
49 | ## \[2.0.2]
50 |
51 | - [`77149dc4`](https://github.com/tauri-apps/plugins-workspace/commit/77149dc4320d26b413e4a6bbe82c654367c51b32) ([#1965](https://github.com/tauri-apps/plugins-workspace/pull/1965) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Fix `writeTextFile` converting UTF-8 characters (for example `äöü`) in the given path into replacement character (`�`)
52 |
53 | ## \[2.0.3]
54 |
55 | - [`14cee64c`](https://github.com/tauri-apps/plugins-workspace/commit/14cee64c82a72655ae6a4ac0892736a2959dbda5) ([#1958](https://github.com/tauri-apps/plugins-workspace/pull/1958) by [@bWanShiTong](https://github.com/tauri-apps/plugins-workspace/../../bWanShiTong)) Fix compilation on targets with pointer width of `16` or `32`
56 |
57 | ## \[2.0.1]
58 |
59 | - [`ae802456`](https://github.com/tauri-apps/plugins-workspace/commit/ae8024565f074f313084777c8b10d1b5e3bbe220) ([#1950](https://github.com/tauri-apps/plugins-workspace/pull/1950) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Improve performance of the `FileHandle.read` and `writeTextFile` APIs.
60 |
61 | ## \[2.0.1]
62 |
63 | - [`a1a82208`](https://github.com/tauri-apps/plugins-workspace/commit/a1a82208ed4ab87f83310be0dc95428aec9ab241) ([#1873](https://github.com/tauri-apps/plugins-workspace/pull/1873) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Downgrade MSRV to 1.77.2 to support Windows 7.
64 |
65 | ## \[2.0.0]
66 |
67 | - [`e2c4dfb6`](https://github.com/tauri-apps/plugins-workspace/commit/e2c4dfb6af43e5dd8d9ceba232c315f5febd55c1) Update to tauri v2 stable release.
68 |
69 | ## \[2.0.0-rc.6]
70 |
71 | - [`fc9b189e`](https://github.com/tauri-apps/plugins-workspace/commit/fc9b189e83a29bd750714ec6336133c6eabdfa20) ([#1837](https://github.com/tauri-apps/plugins-workspace/pull/1837) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) Fix failing to deserialize capability file when using an OS specific path in the scope that is not available on the current OS.
72 |
73 | ## \[2.0.0-rc.5]
74 |
75 | - [`cc03ccf5`](https://github.com/tauri-apps/plugins-workspace/commit/cc03ccf5e0e4be8bbf50bbdebe957c84be7f779b) ([#1774](https://github.com/tauri-apps/plugins-workspace/pull/1774)) Fix `scope-app`, `scope-app-recursive` and `scope-index` not properly enabling the application paths.
76 |
77 | ## \[2.0.0-rc.4]
78 |
79 | - [`9291e4d2`](https://github.com/tauri-apps/plugins-workspace/commit/9291e4d2caa31c883c71e55f2193bd8754d72f03) ([#1640](https://github.com/tauri-apps/plugins-workspace/pull/1640) by [@SRutile](https://github.com/tauri-apps/plugins-workspace/../../SRutile)) Support any UTF-8 character in the writeFile API.
80 |
81 | ## \[2.0.0-rc.3]
82 |
83 | - [`a2fe5551`](https://github.com/tauri-apps/plugins-workspace/commit/a2fe55512f908dd11c814ce021d164f01677572a) ([#1727](https://github.com/tauri-apps/plugins-workspace/pull/1727) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Add utility methods on `FilePath` and `SafeFilePath` enums which are:
84 |
85 | - `path`
86 | - `simplified`
87 | - `into_path`
88 | - [`a2fe5551`](https://github.com/tauri-apps/plugins-workspace/commit/a2fe55512f908dd11c814ce021d164f01677572a) ([#1727](https://github.com/tauri-apps/plugins-workspace/pull/1727) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Implement `Serialize`, `Deserialize`, `From`, `TryFrom` and `FromStr` traits for `FilePath` and `SafeFilePath` enums.
89 | - [`a2fe5551`](https://github.com/tauri-apps/plugins-workspace/commit/a2fe55512f908dd11c814ce021d164f01677572a) ([#1727](https://github.com/tauri-apps/plugins-workspace/pull/1727) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Mark `Error` enum as `#[non_exhuastive]`.
90 | - [`a2fe5551`](https://github.com/tauri-apps/plugins-workspace/commit/a2fe55512f908dd11c814ce021d164f01677572a) ([#1727](https://github.com/tauri-apps/plugins-workspace/pull/1727) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Add `SafeFilePath` enum.
91 |
92 | ## \[2.0.0-rc.2]
93 |
94 | - [`f7280c88`](https://github.com/tauri-apps/plugins-workspace/commit/f7280c88309cdf1f2330574fec31e26e01e9cdbd) ([#1710](https://github.com/tauri-apps/plugins-workspace/pull/1710) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Fix can't use Windows paths like `C:/Users/UserName/file.txt`
95 |
96 | ### bug
97 |
98 | - [`51819c60`](https://github.com/tauri-apps/plugins-workspace/commit/51819c601f863cbfbd11809a1c4cf9df5a20b1e0) ([#1708](https://github.com/tauri-apps/plugins-workspace/pull/1708) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Fixes `writeFile` command implementation on Android.
99 |
100 | ## \[2.0.0-rc.2]
101 |
102 | - [`e2e97db5`](https://github.com/tauri-apps/plugins-workspace/commit/e2e97db51983267f5be84d4f6f0278d58834d1f5) ([#1701](https://github.com/tauri-apps/plugins-workspace/pull/1701) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Update to tauri 2.0.0-rc.8
103 |
104 | ## \[2.0.0-rc.1]
105 |
106 | - [`5f689902`](https://github.com/tauri-apps/plugins-workspace/commit/5f68990297f2cefac4220649a469adb7fa94fe1b) ([#1645](https://github.com/tauri-apps/plugins-workspace/pull/1645) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Update documentation.
107 |
108 | ## \[2.0.0-rc.0]
109 |
110 | - [`9887d1`](https://github.com/tauri-apps/plugins-workspace/commit/9887d14bd0e971c4c0f5c1188fc4005d3fc2e29e) Update to tauri RC.
111 |
112 | ## \[2.0.0-beta.8]
113 |
114 | - [`99d6ac0f`](https://github.com/tauri-apps/plugins-workspace/commit/99d6ac0f9506a6a4a1aa59c728157190a7441af6) ([#1606](https://github.com/tauri-apps/plugins-workspace/pull/1606) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) The JS packages now specify the *minimum* `@tauri-apps/api` version instead of a single exact version.
115 | - [`6de87966`](https://github.com/tauri-apps/plugins-workspace/commit/6de87966ecc00ad9d91c25be452f1f46bd2b7e1f) ([#1597](https://github.com/tauri-apps/plugins-workspace/pull/1597) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Update to tauri beta.25.
116 |
117 | ## \[2.0.0-beta.7]
118 |
119 | - [`22a17980`](https://github.com/tauri-apps/plugins-workspace/commit/22a17980ff4f6f8c40adb1b8f4ffc6dae2fe7e30) ([#1537](https://github.com/tauri-apps/plugins-workspace/pull/1537) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Update to tauri beta.24.
120 |
121 | ## \[2.0.0-beta.6]
122 |
123 | - [`76daee7a`](https://github.com/tauri-apps/plugins-workspace/commit/76daee7aafece34de3092c86e531cf9eb1138989) ([#1512](https://github.com/tauri-apps/plugins-workspace/pull/1512) by [@renovate](https://github.com/tauri-apps/plugins-workspace/../../renovate)) Update to tauri beta.23.
124 |
125 | ## \[2.0.0-beta.5]
126 |
127 | - [`9013854f`](https://github.com/tauri-apps/plugins-workspace/commit/9013854f42a49a230b9dbb9d02774765528a923f)([#1382](https://github.com/tauri-apps/plugins-workspace/pull/1382)) Update to tauri beta.22.
128 |
129 | ## \[2.0.0-beta.4]
130 |
131 | - [`430bd6f4`](https://github.com/tauri-apps/plugins-workspace/commit/430bd6f4f379bee5d232ae6b098ae131db7f178a)([#1363](https://github.com/tauri-apps/plugins-workspace/pull/1363)) Update to tauri beta.20.
132 |
133 | ## \[2.0.0-beta.3]
134 |
135 | - [`bd1ed590`](https://github.com/tauri-apps/plugins-workspace/commit/bd1ed5903ffcce5500310dac1e59e8c67674ef1e)([#1237](https://github.com/tauri-apps/plugins-workspace/pull/1237)) Update to tauri beta.17.
136 |
137 | ## \[2.0.0-beta.6]
138 |
139 | - [`b115fd22`](https://github.com/tauri-apps/plugins-workspace/commit/b115fd22e0da073f5d758c13474ec2106cf78163)([#1221](https://github.com/tauri-apps/plugins-workspace/pull/1221)) Fixes an issue that caused the app to freeze when the `dialog`, `fs`, and `persisted-scope` plugins were used together.
140 |
141 | ## \[2.0.0-beta.5]
142 |
143 | - [`bb51a41`](https://github.com/tauri-apps/plugins-workspace/commit/bb51a41d67ebf989e8aedf10c4b1a7f9514d1bdf)([#1168](https://github.com/tauri-apps/plugins-workspace/pull/1168)) **Breaking Change:** All apis that return paths to the frontend will now remove the `\\?\` UNC prefix on Windows.
144 | - [`e3d41f4`](https://github.com/tauri-apps/plugins-workspace/commit/e3d41f4011bd3ea3ce281bb38bbe31d3709f8e0f)([#1191](https://github.com/tauri-apps/plugins-workspace/pull/1191)) Internally use the webview scoped resources table instead of the app one, so other webviews can't access other webviews resources.
145 | - [`e3d41f4`](https://github.com/tauri-apps/plugins-workspace/commit/e3d41f4011bd3ea3ce281bb38bbe31d3709f8e0f)([#1191](https://github.com/tauri-apps/plugins-workspace/pull/1191)) Update for tauri 2.0.0-beta.15.
146 |
147 | ## \[2.0.0-beta.4]
148 |
149 | - [`9c2fb93`](https://github.com/tauri-apps/plugins-workspace/commit/9c2fb9306ecd3936a2aef56b3c012899036db098) Enhance the scope type to also allow a plain string representing the path to allow or deny.
150 | - [`772f2bc`](https://github.com/tauri-apps/plugins-workspace/commit/772f2bc3495a4f83f1c3e538cbac6d29cbd7d5ef)([#1136](https://github.com/tauri-apps/plugins-workspace/pull/1136)) Update for tauri 2.0.0-beta.14.
151 |
152 | ## \[2.0.0-beta.3]
153 |
154 | - [`cb96aa0`](https://github.com/tauri-apps/plugins-workspace/commit/cb96aa06277f7b864952827ec9fb1e74c8a1f761)([#1082](https://github.com/tauri-apps/plugins-workspace/pull/1082)) Fixes `watch` and `watchImmediate` which previously ignored the `baseDir` parameter.
155 | - [`a04ea2f`](https://github.com/tauri-apps/plugins-workspace/commit/a04ea2f38294d5a3987578283badc8eec87a7752)([#1071](https://github.com/tauri-apps/plugins-workspace/pull/1071)) The global API script is now only added to the binary when the `withGlobalTauri` config is true.
156 |
157 | ## \[2.0.0-beta.2]
158 |
159 | - [`7358102`](https://github.com/tauri-apps/plugins-workspace/commit/735810237e21504a027a65a7b3c25fd7e594288a)([#1029](https://github.com/tauri-apps/plugins-workspace/pull/1029)) Fix infinite loop on cargo build operations
160 | - [`99bea25`](https://github.com/tauri-apps/plugins-workspace/commit/99bea2559c2c0648c2519c50a18cd124dacef57b)([#1005](https://github.com/tauri-apps/plugins-workspace/pull/1005)) Update to tauri beta.8.
161 |
162 | ## \[2.0.0-beta.1]
163 |
164 | - [`569defb`](https://github.com/tauri-apps/plugins-workspace/commit/569defbe9492e38938554bb7bdc1be9151456d21) Update to tauri beta.4.
165 |
166 | ## \[2.0.0-beta.0]
167 |
168 | - [`d198c01`](https://github.com/tauri-apps/plugins-workspace/commit/d198c014863ee260cb0de88a14b7fc4356ef7474)([#862](https://github.com/tauri-apps/plugins-workspace/pull/862)) Update to tauri beta.
169 | - [`ea8eadc`](https://github.com/tauri-apps/plugins-workspace/commit/ea8eadce85b2e3e8eb7eb1a779fc3aa6c1201fa3)([#865](https://github.com/tauri-apps/plugins-workspace/pull/865)) Fix incorrect `create` option default value for `writeFile` and `writeTextFile` which didn't match documentation.
170 | - [`61edbbe`](https://github.com/tauri-apps/plugins-workspace/commit/61edbbec0acda4213ed8684f75a973e8be123a52)([#885](https://github.com/tauri-apps/plugins-workspace/pull/885)) Replace `notify-debouncer-mini` with `notify-debouncer-full`. [(plugins-workspace#885)](https://github.com/tauri-apps/plugins-workspace/pull/885)
171 |
172 | ## \[2.0.0-alpha.6]
173 |
174 | - [`85f8419`](https://github.com/tauri-apps/plugins-workspace/commit/85f841968200316958d707db0c39bb115f762471)([#848](https://github.com/tauri-apps/plugins-workspace/pull/848)) Fix `DebouncedEvent` type to correctly represent the actual type.
175 | - [`c601230`](https://github.com/tauri-apps/plugins-workspace/commit/c60123093ddf725af7228494182fed697ff8b021)([#847](https://github.com/tauri-apps/plugins-workspace/pull/847)) Add `createNew` option for `writeFile` and `writeTextFile` to create the file if doesn't exist and fail if it does.
176 | - [`c601230`](https://github.com/tauri-apps/plugins-workspace/commit/c60123093ddf725af7228494182fed697ff8b021)([#847](https://github.com/tauri-apps/plugins-workspace/pull/847)) Truncate files when using `writeFile` and `writeTextFile` with `append: false`.
177 | - [`2e2fc8d`](https://github.com/tauri-apps/plugins-workspace/commit/2e2fc8de69dd8d282b66ec81561d57d8af802dc5)([#857](https://github.com/tauri-apps/plugins-workspace/pull/857)) Fix `invalid args id for command unwatch` error when trying to unwatch a previously watched file or directory.
178 | - [`c601230`](https://github.com/tauri-apps/plugins-workspace/commit/c60123093ddf725af7228494182fed697ff8b021)([#847](https://github.com/tauri-apps/plugins-workspace/pull/847)) Fix panic when using `writeFile` or `writeTextFile` without passing an option object.
179 |
180 | ## \[2.0.0-alpha.5]
181 |
182 | - [`387c2f9`](https://github.com/tauri-apps/plugins-workspace/commit/387c2f9e0ce4c75c07ffa3fd76391a25b58f5daf)([#802](https://github.com/tauri-apps/plugins-workspace/pull/802)) Update to @tauri-apps/api v2.0.0-alpha.13.
183 | - [`69a1fa0`](https://github.com/tauri-apps/plugins-workspace/commit/69a1fa099c3143b6e426492f1c9d9cfbe56d2209)([#751](https://github.com/tauri-apps/plugins-workspace/pull/751)) The `fs` plugin received a major overhaul to add new APIs and changed existing APIs to be closer to Node.js and Deno APIs.
184 |
185 | ## \[2.0.0-alpha.4]
186 |
187 | - [`387c2f9`](https://github.com/tauri-apps/plugins-workspace/commit/387c2f9e0ce4c75c07ffa3fd76391a25b58f5daf)([#802](https://github.com/tauri-apps/plugins-workspace/pull/802)) Update to @tauri-apps/api v2.0.0-alpha.12.
188 | - [`88d260d`](https://github.com/tauri-apps/plugins-workspace/commit/88d260d90130f9df4b9ce00c1ad1bf1e4b30b1c0)([#744](https://github.com/tauri-apps/plugins-workspace/pull/744)) Add second argument to `exists` function to specify base directory.
189 |
190 | ## \[2.0.0-alpha.3]
191 |
192 | - [`e438e0a`](https://github.com/tauri-apps/plugins-workspace/commit/e438e0a62d4b430a5159f05f13ecd397dd891a0d)([#676](https://github.com/tauri-apps/plugins-workspace/pull/676)) Update to @tauri-apps/api v2.0.0-alpha.11.
193 |
194 | ## \[2.0.0-alpha.2]
195 |
196 | - [`5c13736`](https://github.com/tauri-apps/plugins-workspace/commit/5c137365c60790e8d4037d449e8237aa3fffdab0)([#673](https://github.com/tauri-apps/plugins-workspace/pull/673)) Update to @tauri-apps/api v2.0.0-alpha.9.
197 |
198 | ## \[2.0.0-alpha.2]
199 |
200 | - [`4e2cef9`](https://github.com/tauri-apps/plugins-workspace/commit/4e2cef9b702bbbb9cf4ee17de50791cb21f1b2a4)([#593](https://github.com/tauri-apps/plugins-workspace/pull/593)) Update to alpha.12.
201 |
202 | ## \[2.0.0-alpha.1]
203 |
204 | - [`0bba693`](https://github.com/tauri-apps/plugins-workspace/commit/0bba6932c09da5267a9dbf75ba52252e39458420)([#454](https://github.com/tauri-apps/plugins-workspace/pull/454)) Fix `writeBinaryFile` crashing with `command 'write_binary_file' not found`
205 | - [`d74fc0a`](https://github.com/tauri-apps/plugins-workspace/commit/d74fc0a097996e90a37be8f57d50b7d1f6ca616f)([#555](https://github.com/tauri-apps/plugins-workspace/pull/555)) Update to alpha.11.
206 |
207 | ## \[2.0.0-alpha.0]
208 |
209 | - [`717ae67`](https://github.com/tauri-apps/plugins-workspace/commit/717ae670978feb4492fac1f295998b93f2b9347f)([#371](https://github.com/tauri-apps/plugins-workspace/pull/371)) First v2 alpha release!
210 |
--------------------------------------------------------------------------------
/dist-js/index.js:
--------------------------------------------------------------------------------
1 | export { BaseDirectory } from '@tauri-apps/api/path';
2 | import { Resource, invoke, Channel } from '@tauri-apps/api/core';
3 |
4 | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
5 | // SPDX-License-Identifier: Apache-2.0
6 | // SPDX-License-Identifier: MIT
7 | /**
8 | * Access the file system.
9 | *
10 | * ## Security
11 | *
12 | * This module prevents path traversal, not allowing parent directory accessors to be used
13 | * (i.e. "/usr/path/to/../file" or "../path/to/file" paths are not allowed).
14 | * Paths accessed with this API must be either relative to one of the {@link BaseDirectory | base directories}
15 | * or created with the {@link https://v2.tauri.app/reference/javascript/api/namespacepath/ | path API}.
16 | *
17 | * The API has a scope configuration that forces you to restrict the paths that can be accessed using glob patterns.
18 | *
19 | * The scope configuration is an array of glob patterns describing file/directory paths that are allowed.
20 | * For instance, this scope configuration allows **all** enabled `fs` APIs to (only) access files in the
21 | * *databases* directory of the {@link https://v2.tauri.app/reference/javascript/api/namespacepath/#appdatadir | `$APPDATA` directory}:
22 | * ```json
23 | * {
24 | * "permissions": [
25 | * {
26 | * "identifier": "fs:scope",
27 | * "allow": [{ "path": "$APPDATA/databases/*" }]
28 | * }
29 | * ]
30 | * }
31 | * ```
32 | *
33 | * Scopes can also be applied to specific `fs` APIs by using the API's identifier instead of `fs:scope`:
34 | * ```json
35 | * {
36 | * "permissions": [
37 | * {
38 | * "identifier": "fs:allow-exists",
39 | * "allow": [{ "path": "$APPDATA/databases/*" }]
40 | * }
41 | * ]
42 | * }
43 | * ```
44 | *
45 | * Notice the use of the `$APPDATA` variable. The value is injected at runtime, resolving to the {@link https://v2.tauri.app/reference/javascript/api/namespacepath/#appdatadir | app data directory}.
46 | *
47 | * The available variables are:
48 | * {@linkcode https://v2.tauri.app/reference/javascript/api/namespacepath/#appconfigdir | $APPCONFIG},
49 | * {@linkcode https://v2.tauri.app/reference/javascript/api/namespacepath/#appdatadir | $APPDATA},
50 | * {@linkcode https://v2.tauri.app/reference/javascript/api/namespacepath/#applocaldatadir | $APPLOCALDATA},
51 | * {@linkcode https://v2.tauri.app/reference/javascript/api/namespacepath/#appcachedir | $APPCACHE},
52 | * {@linkcode https://v2.tauri.app/reference/javascript/api/namespacepath/#applogdir | $APPLOG},
53 | * {@linkcode https://v2.tauri.app/reference/javascript/api/namespacepath/#audiodir | $AUDIO},
54 | * {@linkcode https://v2.tauri.app/reference/javascript/api/namespacepath/#cachedir | $CACHE},
55 | * {@linkcode https://v2.tauri.app/reference/javascript/api/namespacepath/#configdir | $CONFIG},
56 | * {@linkcode https://v2.tauri.app/reference/javascript/api/namespacepath/#datadir | $DATA},
57 | * {@linkcode https://v2.tauri.app/reference/javascript/api/namespacepath/#localdatadir | $LOCALDATA},
58 | * {@linkcode https://v2.tauri.app/reference/javascript/api/namespacepath/#desktopdir | $DESKTOP},
59 | * {@linkcode https://v2.tauri.app/reference/javascript/api/namespacepath/#documentdir | $DOCUMENT},
60 | * {@linkcode https://v2.tauri.app/reference/javascript/api/namespacepath/#downloaddir | $DOWNLOAD},
61 | * {@linkcode https://v2.tauri.app/reference/javascript/api/namespacepath/#executabledir | $EXE},
62 | * {@linkcode https://v2.tauri.app/reference/javascript/api/namespacepath/#fontdir | $FONT},
63 | * {@linkcode https://v2.tauri.app/reference/javascript/api/namespacepath/#homedir | $HOME},
64 | * {@linkcode https://v2.tauri.app/reference/javascript/api/namespacepath/#picturedir | $PICTURE},
65 | * {@linkcode https://v2.tauri.app/reference/javascript/api/namespacepath/#publicdir | $PUBLIC},
66 | * {@linkcode https://v2.tauri.app/reference/javascript/api/namespacepath/#runtimedir | $RUNTIME},
67 | * {@linkcode https://v2.tauri.app/reference/javascript/api/namespacepath/#templatedir | $TEMPLATE},
68 | * {@linkcode https://v2.tauri.app/reference/javascript/api/namespacepath/#videodir | $VIDEO},
69 | * {@linkcode https://v2.tauri.app/reference/javascript/api/namespacepath/#resourcedir | $RESOURCE},
70 | * {@linkcode https://v2.tauri.app/reference/javascript/api/namespacepath/#tempdir | $TEMP}.
71 | *
72 | * Trying to execute any API with a URL not configured on the scope results in a promise rejection due to denied access.
73 | *
74 | * @module
75 | */
76 | var SeekMode;
77 | (function (SeekMode) {
78 | SeekMode[SeekMode["Start"] = 0] = "Start";
79 | SeekMode[SeekMode["Current"] = 1] = "Current";
80 | SeekMode[SeekMode["End"] = 2] = "End";
81 | })(SeekMode || (SeekMode = {}));
82 | function parseFileInfo(r) {
83 | return {
84 | isFile: r.isFile,
85 | isDirectory: r.isDirectory,
86 | isSymlink: r.isSymlink,
87 | size: r.size,
88 | mtime: r.mtime !== null ? new Date(r.mtime) : null,
89 | atime: r.atime !== null ? new Date(r.atime) : null,
90 | birthtime: r.birthtime !== null ? new Date(r.birthtime) : null,
91 | readonly: r.readonly,
92 | fileAttributes: r.fileAttributes,
93 | dev: r.dev,
94 | ino: r.ino,
95 | mode: r.mode,
96 | nlink: r.nlink,
97 | uid: r.uid,
98 | gid: r.gid,
99 | rdev: r.rdev,
100 | blksize: r.blksize,
101 | blocks: r.blocks
102 | };
103 | }
104 | // https://gist.github.com/zapthedingbat/38ebfbedd98396624e5b5f2ff462611d
105 | /** Converts a big-endian eight byte array to number */
106 | function fromBytes(buffer) {
107 | const bytes = new Uint8ClampedArray(buffer);
108 | const size = bytes.byteLength;
109 | let x = 0;
110 | for (let i = 0; i < size; i++) {
111 | // eslint-disable-next-line security/detect-object-injection
112 | const byte = bytes[i];
113 | x *= 0x100;
114 | x += byte;
115 | }
116 | return x;
117 | }
118 | /**
119 | * The Tauri abstraction for reading and writing files.
120 | *
121 | * @since 2.0.0
122 | */
123 | class FileHandle extends Resource {
124 | /**
125 | * Reads up to `p.byteLength` bytes into `p`. It resolves to the number of
126 | * bytes read (`0` < `n` <= `p.byteLength`) and rejects if any error
127 | * encountered. Even if `read()` resolves to `n` < `p.byteLength`, it may
128 | * use all of `p` as scratch space during the call. If some data is
129 | * available but not `p.byteLength` bytes, `read()` conventionally resolves
130 | * to what is available instead of waiting for more.
131 | *
132 | * When `read()` encounters end-of-file condition, it resolves to EOF
133 | * (`null`).
134 | *
135 | * When `read()` encounters an error, it rejects with an error.
136 | *
137 | * Callers should always process the `n` > `0` bytes returned before
138 | * considering the EOF (`null`). Doing so correctly handles I/O errors that
139 | * happen after reading some bytes and also both of the allowed EOF
140 | * behaviors.
141 | *
142 | * @example
143 | * ```typescript
144 | * import { open, BaseDirectory } from "@tauri-apps/plugin-fs"
145 | * // if "$APPCONFIG/foo/bar.txt" contains the text "hello world":
146 | * const file = await open("foo/bar.txt", { baseDir: BaseDirectory.AppConfig });
147 | * const buf = new Uint8Array(100);
148 | * const numberOfBytesRead = await file.read(buf); // 11 bytes
149 | * const text = new TextDecoder().decode(buf); // "hello world"
150 | * await file.close();
151 | * ```
152 | *
153 | * @since 2.0.0
154 | */
155 | async read(buffer) {
156 | if (buffer.byteLength === 0) {
157 | return 0;
158 | }
159 | const data = await invoke('plugin:fs|read', {
160 | rid: this.rid,
161 | len: buffer.byteLength
162 | });
163 | // Rust side will never return an empty array for this command and
164 | // ensure there is at least 8 elements there.
165 | //
166 | // This is an optimization to include the number of read bytes (as bigendian bytes)
167 | // at the end of returned array to avoid serialization overhead of separate values.
168 | const nread = fromBytes(data.slice(-8));
169 | const bytes = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
170 | buffer.set(bytes.slice(0, bytes.length - 8));
171 | return nread === 0 ? null : nread;
172 | }
173 | /**
174 | * Seek sets the offset for the next `read()` or `write()` to offset,
175 | * interpreted according to `whence`: `Start` means relative to the
176 | * start of the file, `Current` means relative to the current offset,
177 | * and `End` means relative to the end. Seek resolves to the new offset
178 | * relative to the start of the file.
179 | *
180 | * Seeking to an offset before the start of the file is an error. Seeking to
181 | * any positive offset is legal, but the behavior of subsequent I/O
182 | * operations on the underlying object is implementation-dependent.
183 | * It returns the number of cursor position.
184 | *
185 | * @example
186 | * ```typescript
187 | * import { open, SeekMode, BaseDirectory } from '@tauri-apps/plugin-fs';
188 | *
189 | * // Given hello.txt pointing to file with "Hello world", which is 11 bytes long:
190 | * const file = await open('hello.txt', { read: true, write: true, truncate: true, create: true, baseDir: BaseDirectory.AppLocalData });
191 | * await file.write(new TextEncoder().encode("Hello world"));
192 | *
193 | * // Seek 6 bytes from the start of the file
194 | * console.log(await file.seek(6, SeekMode.Start)); // "6"
195 | * // Seek 2 more bytes from the current position
196 | * console.log(await file.seek(2, SeekMode.Current)); // "8"
197 | * // Seek backwards 2 bytes from the end of the file
198 | * console.log(await file.seek(-2, SeekMode.End)); // "9" (e.g. 11-2)
199 | *
200 | * await file.close();
201 | * ```
202 | *
203 | * @since 2.0.0
204 | */
205 | async seek(offset, whence) {
206 | return await invoke('plugin:fs|seek', {
207 | rid: this.rid,
208 | offset,
209 | whence
210 | });
211 | }
212 | /**
213 | * Returns a {@linkcode FileInfo } for this file.
214 | *
215 | * @example
216 | * ```typescript
217 | * import { open, BaseDirectory } from '@tauri-apps/plugin-fs';
218 | * const file = await open("file.txt", { read: true, baseDir: BaseDirectory.AppLocalData });
219 | * const fileInfo = await file.stat();
220 | * console.log(fileInfo.isFile); // true
221 | * await file.close();
222 | * ```
223 | *
224 | * @since 2.0.0
225 | */
226 | async stat() {
227 | const res = await invoke('plugin:fs|fstat', {
228 | rid: this.rid
229 | });
230 | return parseFileInfo(res);
231 | }
232 | /**
233 | * Truncates or extends this file, to reach the specified `len`.
234 | * If `len` is not specified then the entire file contents are truncated.
235 | *
236 | * @example
237 | * ```typescript
238 | * import { open, BaseDirectory } from '@tauri-apps/plugin-fs';
239 | *
240 | * // truncate the entire file
241 | * const file = await open("my_file.txt", { read: true, write: true, create: true, baseDir: BaseDirectory.AppLocalData });
242 | * await file.truncate();
243 | *
244 | * // truncate part of the file
245 | * const file = await open("my_file.txt", { read: true, write: true, create: true, baseDir: BaseDirectory.AppLocalData });
246 | * await file.write(new TextEncoder().encode("Hello World"));
247 | * await file.truncate(7);
248 | * const data = new Uint8Array(32);
249 | * await file.read(data);
250 | * console.log(new TextDecoder().decode(data)); // Hello W
251 | * await file.close();
252 | * ```
253 | *
254 | * @since 2.0.0
255 | */
256 | async truncate(len) {
257 | await invoke('plugin:fs|ftruncate', {
258 | rid: this.rid,
259 | len
260 | });
261 | }
262 | /**
263 | * Writes `data.byteLength` bytes from `data` to the underlying data stream. It
264 | * resolves to the number of bytes written from `data` (`0` <= `n` <=
265 | * `data.byteLength`) or reject with the error encountered that caused the
266 | * write to stop early. `write()` must reject with a non-null error if
267 | * would resolve to `n` < `data.byteLength`. `write()` must not modify the
268 | * slice data, even temporarily.
269 | *
270 | * @example
271 | * ```typescript
272 | * import { open, write, BaseDirectory } from '@tauri-apps/plugin-fs';
273 | * const encoder = new TextEncoder();
274 | * const data = encoder.encode("Hello world");
275 | * const file = await open("bar.txt", { write: true, baseDir: BaseDirectory.AppLocalData });
276 | * const bytesWritten = await file.write(data); // 11
277 | * await file.close();
278 | * ```
279 | *
280 | * @since 2.0.0
281 | */
282 | async write(data) {
283 | return await invoke('plugin:fs|write', {
284 | rid: this.rid,
285 | data
286 | });
287 | }
288 | }
289 | /**
290 | * Creates a file if none exists or truncates an existing file and resolves to
291 | * an instance of {@linkcode FileHandle }.
292 | *
293 | * @example
294 | * ```typescript
295 | * import { create, BaseDirectory } from "@tauri-apps/plugin-fs"
296 | * const file = await create("foo/bar.txt", { baseDir: BaseDirectory.AppConfig });
297 | * await file.write(new TextEncoder().encode("Hello world"));
298 | * await file.close();
299 | * ```
300 | *
301 | * @since 2.0.0
302 | */
303 | async function create(path, options) {
304 | if (path instanceof URL && path.protocol !== 'file:') {
305 | throw new TypeError('Must be a file URL.');
306 | }
307 | const rid = await invoke('plugin:fs|create', {
308 | path: path instanceof URL ? path.toString() : path,
309 | options
310 | });
311 | return new FileHandle(rid);
312 | }
313 | /**
314 | * Open a file and resolve to an instance of {@linkcode FileHandle}. The
315 | * file does not need to previously exist if using the `create` or `createNew`
316 | * open options. It is the callers responsibility to close the file when finished
317 | * with it.
318 | *
319 | * @example
320 | * ```typescript
321 | * import { open, BaseDirectory } from "@tauri-apps/plugin-fs"
322 | * const file = await open("foo/bar.txt", { read: true, write: true, baseDir: BaseDirectory.AppLocalData });
323 | * // Do work with file
324 | * await file.close();
325 | * ```
326 | *
327 | * @since 2.0.0
328 | */
329 | async function open(path, options) {
330 | if (path instanceof URL && path.protocol !== 'file:') {
331 | throw new TypeError('Must be a file URL.');
332 | }
333 | const rid = await invoke('plugin:fs|open', {
334 | path: path instanceof URL ? path.toString() : path,
335 | options
336 | });
337 | return new FileHandle(rid);
338 | }
339 | /**
340 | * Copies the contents and permissions of one file to another specified path, by default creating a new file if needed, else overwriting.
341 | * @example
342 | * ```typescript
343 | * import { copyFile, BaseDirectory } from '@tauri-apps/plugin-fs';
344 | * await copyFile('app.conf', 'app.conf.bk', { fromPathBaseDir: BaseDirectory.AppConfig, toPathBaseDir: BaseDirectory.AppConfig });
345 | * ```
346 | *
347 | * @since 2.0.0
348 | */
349 | async function copyFile(fromPath, toPath, options) {
350 | if ((fromPath instanceof URL && fromPath.protocol !== 'file:')
351 | || (toPath instanceof URL && toPath.protocol !== 'file:')) {
352 | throw new TypeError('Must be a file URL.');
353 | }
354 | await invoke('plugin:fs|copy_file', {
355 | fromPath: fromPath instanceof URL ? fromPath.toString() : fromPath,
356 | toPath: toPath instanceof URL ? toPath.toString() : toPath,
357 | options
358 | });
359 | }
360 | /**
361 | * Creates a new directory with the specified path.
362 | * @example
363 | * ```typescript
364 | * import { mkdir, BaseDirectory } from '@tauri-apps/plugin-fs';
365 | * await mkdir('users', { baseDir: BaseDirectory.AppLocalData });
366 | * ```
367 | *
368 | * @since 2.0.0
369 | */
370 | async function mkdir(path, options) {
371 | if (path instanceof URL && path.protocol !== 'file:') {
372 | throw new TypeError('Must be a file URL.');
373 | }
374 | await invoke('plugin:fs|mkdir', {
375 | path: path instanceof URL ? path.toString() : path,
376 | options
377 | });
378 | }
379 | /**
380 | * Reads the directory given by path and returns an array of `DirEntry`.
381 | * @example
382 | * ```typescript
383 | * import { readDir, BaseDirectory } from '@tauri-apps/plugin-fs';
384 | * import { join } from '@tauri-apps/api/path';
385 | * const dir = "users"
386 | * const entries = await readDir('users', { baseDir: BaseDirectory.AppLocalData });
387 | * processEntriesRecursively(dir, entries);
388 | * async function processEntriesRecursively(parent, entries) {
389 | * for (const entry of entries) {
390 | * console.log(`Entry: ${entry.name}`);
391 | * if (entry.isDirectory) {
392 | * const dir = await join(parent, entry.name);
393 | * processEntriesRecursively(dir, await readDir(dir, { baseDir: BaseDirectory.AppLocalData }))
394 | * }
395 | * }
396 | * }
397 | * ```
398 | *
399 | * @since 2.0.0
400 | */
401 | async function readDir(path, options) {
402 | if (path instanceof URL && path.protocol !== 'file:') {
403 | throw new TypeError('Must be a file URL.');
404 | }
405 | return await invoke('plugin:fs|read_dir', {
406 | path: path instanceof URL ? path.toString() : path,
407 | options
408 | });
409 | }
410 | /**
411 | * Reads and resolves to the entire contents of a file as an array of bytes.
412 | * TextDecoder can be used to transform the bytes to string if required.
413 | * @example
414 | * ```typescript
415 | * import { readFile, BaseDirectory } from '@tauri-apps/plugin-fs';
416 | * const contents = await readFile('avatar.png', { baseDir: BaseDirectory.Resource });
417 | * ```
418 | *
419 | * @since 2.0.0
420 | */
421 | async function readFile(path, options) {
422 | if (path instanceof URL && path.protocol !== 'file:') {
423 | throw new TypeError('Must be a file URL.');
424 | }
425 | const arr = await invoke('plugin:fs|read_file', {
426 | path: path instanceof URL ? path.toString() : path,
427 | options
428 | });
429 | return arr instanceof ArrayBuffer ? new Uint8Array(arr) : Uint8Array.from(arr);
430 | }
431 | /**
432 | * Reads and returns the entire contents of a file as UTF-8 string.
433 | * @example
434 | * ```typescript
435 | * import { readTextFile, BaseDirectory } from '@tauri-apps/plugin-fs';
436 | * const contents = await readTextFile('app.conf', { baseDir: BaseDirectory.AppConfig });
437 | * ```
438 | *
439 | * @since 2.0.0
440 | */
441 | async function readTextFile(path, options) {
442 | if (path instanceof URL && path.protocol !== 'file:') {
443 | throw new TypeError('Must be a file URL.');
444 | }
445 | const arr = await invoke('plugin:fs|read_text_file', {
446 | path: path instanceof URL ? path.toString() : path,
447 | options
448 | });
449 | const bytes = arr instanceof ArrayBuffer ? arr : Uint8Array.from(arr);
450 | return new TextDecoder().decode(bytes);
451 | }
452 | /**
453 | * Returns an async {@linkcode AsyncIterableIterator} over the lines of a file as UTF-8 string.
454 | * @example
455 | * ```typescript
456 | * import { readTextFileLines, BaseDirectory } from '@tauri-apps/plugin-fs';
457 | * const lines = await readTextFileLines('app.conf', { baseDir: BaseDirectory.AppConfig });
458 | * for await (const line of lines) {
459 | * console.log(line);
460 | * }
461 | * ```
462 | * You could also call {@linkcode AsyncIterableIterator.next} to advance the
463 | * iterator so you can lazily read the next line whenever you want.
464 | *
465 | * @since 2.0.0
466 | */
467 | async function readTextFileLines(path, options) {
468 | if (path instanceof URL && path.protocol !== 'file:') {
469 | throw new TypeError('Must be a file URL.');
470 | }
471 | const pathStr = path instanceof URL ? path.toString() : path;
472 | return await Promise.resolve({
473 | path: pathStr,
474 | rid: null,
475 | async next() {
476 | if (this.rid === null) {
477 | this.rid = await invoke('plugin:fs|read_text_file_lines', {
478 | path: pathStr,
479 | options
480 | });
481 | }
482 | const arr = await invoke('plugin:fs|read_text_file_lines_next', { rid: this.rid });
483 | const bytes = arr instanceof ArrayBuffer ? new Uint8Array(arr) : Uint8Array.from(arr);
484 | // Rust side will never return an empty array for this command and
485 | // ensure there is at least one elements there.
486 | //
487 | // This is an optimization to include whether we finished iteration or not (1 or 0)
488 | // at the end of returned array to avoid serialization overhead of separate values.
489 | const done = bytes[bytes.byteLength - 1] === 1;
490 | if (done) {
491 | // a full iteration is over, reset rid for next iteration
492 | this.rid = null;
493 | return { value: null, done };
494 | }
495 | const line = new TextDecoder().decode(bytes.slice(0, bytes.byteLength - 1));
496 | return {
497 | value: line,
498 | done
499 | };
500 | },
501 | [Symbol.asyncIterator]() {
502 | return this;
503 | }
504 | });
505 | }
506 | /**
507 | * Removes the named file or directory.
508 | * If the directory is not empty and the `recursive` option isn't set to true, the promise will be rejected.
509 | * @example
510 | * ```typescript
511 | * import { remove, BaseDirectory } from '@tauri-apps/plugin-fs';
512 | * await remove('users/file.txt', { baseDir: BaseDirectory.AppLocalData });
513 | * await remove('users', { baseDir: BaseDirectory.AppLocalData });
514 | * ```
515 | *
516 | * @since 2.0.0
517 | */
518 | async function remove(path, options) {
519 | if (path instanceof URL && path.protocol !== 'file:') {
520 | throw new TypeError('Must be a file URL.');
521 | }
522 | await invoke('plugin:fs|remove', {
523 | path: path instanceof URL ? path.toString() : path,
524 | options
525 | });
526 | }
527 | /**
528 | * Renames (moves) oldpath to newpath. Paths may be files or directories.
529 | * If newpath already exists and is not a directory, rename() replaces it.
530 | * OS-specific restrictions may apply when oldpath and newpath are in different directories.
531 | *
532 | * On Unix, this operation does not follow symlinks at either path.
533 | *
534 | * @example
535 | * ```typescript
536 | * import { rename, BaseDirectory } from '@tauri-apps/plugin-fs';
537 | * await rename('avatar.png', 'deleted.png', { oldPathBaseDir: BaseDirectory.App, newPathBaseDir: BaseDirectory.AppLocalData });
538 | * ```
539 | *
540 | * @since 2.0.0
541 | */
542 | async function rename(oldPath, newPath, options) {
543 | if ((oldPath instanceof URL && oldPath.protocol !== 'file:')
544 | || (newPath instanceof URL && newPath.protocol !== 'file:')) {
545 | throw new TypeError('Must be a file URL.');
546 | }
547 | await invoke('plugin:fs|rename', {
548 | oldPath: oldPath instanceof URL ? oldPath.toString() : oldPath,
549 | newPath: newPath instanceof URL ? newPath.toString() : newPath,
550 | options
551 | });
552 | }
553 | /**
554 | * Resolves to a {@linkcode FileInfo} for the specified `path`. Will always
555 | * follow symlinks but will reject if the symlink points to a path outside of the scope.
556 | *
557 | * @example
558 | * ```typescript
559 | * import { stat, BaseDirectory } from '@tauri-apps/plugin-fs';
560 | * const fileInfo = await stat("hello.txt", { baseDir: BaseDirectory.AppLocalData });
561 | * console.log(fileInfo.isFile); // true
562 | * ```
563 | *
564 | * @since 2.0.0
565 | */
566 | async function stat(path, options) {
567 | const res = await invoke('plugin:fs|stat', {
568 | path: path instanceof URL ? path.toString() : path,
569 | options
570 | });
571 | return parseFileInfo(res);
572 | }
573 | /**
574 | * Resolves to a {@linkcode FileInfo} for the specified `path`. If `path` is a
575 | * symlink, information for the symlink will be returned instead of what it
576 | * points to.
577 | *
578 | * @example
579 | * ```typescript
580 | * import { lstat, BaseDirectory } from '@tauri-apps/plugin-fs';
581 | * const fileInfo = await lstat("hello.txt", { baseDir: BaseDirectory.AppLocalData });
582 | * console.log(fileInfo.isFile); // true
583 | * ```
584 | *
585 | * @since 2.0.0
586 | */
587 | async function lstat(path, options) {
588 | const res = await invoke('plugin:fs|lstat', {
589 | path: path instanceof URL ? path.toString() : path,
590 | options
591 | });
592 | return parseFileInfo(res);
593 | }
594 | /**
595 | * Truncates or extends the specified file, to reach the specified `len`.
596 | * If `len` is `0` or not specified, then the entire file contents are truncated.
597 | *
598 | * @example
599 | * ```typescript
600 | * import { truncate, readTextFile, writeTextFile, BaseDirectory } from '@tauri-apps/plugin-fs';
601 | * // truncate the entire file
602 | * await truncate("my_file.txt", 0, { baseDir: BaseDirectory.AppLocalData });
603 | *
604 | * // truncate part of the file
605 | * const filePath = "file.txt";
606 | * await writeTextFile(filePath, "Hello World", { baseDir: BaseDirectory.AppLocalData });
607 | * await truncate(filePath, 7, { baseDir: BaseDirectory.AppLocalData });
608 | * const data = await readTextFile(filePath, { baseDir: BaseDirectory.AppLocalData });
609 | * console.log(data); // "Hello W"
610 | * ```
611 | *
612 | * @since 2.0.0
613 | */
614 | async function truncate(path, len, options) {
615 | if (path instanceof URL && path.protocol !== 'file:') {
616 | throw new TypeError('Must be a file URL.');
617 | }
618 | await invoke('plugin:fs|truncate', {
619 | path: path instanceof URL ? path.toString() : path,
620 | len,
621 | options
622 | });
623 | }
624 | /**
625 | * Write `data` to the given `path`, by default creating a new file if needed, else overwriting.
626 | * @example
627 | * ```typescript
628 | * import { writeFile, BaseDirectory } from '@tauri-apps/plugin-fs';
629 | *
630 | * let encoder = new TextEncoder();
631 | * let data = encoder.encode("Hello World");
632 | * await writeFile('file.txt', data, { baseDir: BaseDirectory.AppLocalData });
633 | * ```
634 | *
635 | * @since 2.0.0
636 | */
637 | async function writeFile(path, data, options) {
638 | if (path instanceof URL && path.protocol !== 'file:') {
639 | throw new TypeError('Must be a file URL.');
640 | }
641 | if (data instanceof ReadableStream) {
642 | const file = await open(path, {
643 | read: false,
644 | create: true,
645 | write: true,
646 | ...options
647 | });
648 | const reader = data.getReader();
649 | try {
650 | while (true) {
651 | const { done, value } = await reader.read();
652 | if (done)
653 | break;
654 | await file.write(value);
655 | }
656 | }
657 | finally {
658 | reader.releaseLock();
659 | await file.close();
660 | }
661 | }
662 | else {
663 | await invoke('plugin:fs|write_file', data, {
664 | headers: {
665 | path: encodeURIComponent(path instanceof URL ? path.toString() : path),
666 | options: JSON.stringify(options)
667 | }
668 | });
669 | }
670 | }
671 | /**
672 | * Writes UTF-8 string `data` to the given `path`, by default creating a new file if needed, else overwriting.
673 | @example
674 | * ```typescript
675 | * import { writeTextFile, BaseDirectory } from '@tauri-apps/plugin-fs';
676 | *
677 | * await writeTextFile('file.txt', "Hello world", { baseDir: BaseDirectory.AppLocalData });
678 | * ```
679 | *
680 | * @since 2.0.0
681 | */
682 | async function writeTextFile(path, data, options) {
683 | if (path instanceof URL && path.protocol !== 'file:') {
684 | throw new TypeError('Must be a file URL.');
685 | }
686 | const encoder = new TextEncoder();
687 | await invoke('plugin:fs|write_text_file', encoder.encode(data), {
688 | headers: {
689 | path: encodeURIComponent(path instanceof URL ? path.toString() : path),
690 | options: JSON.stringify(options)
691 | }
692 | });
693 | }
694 | /**
695 | * Check if a path exists.
696 | * @example
697 | * ```typescript
698 | * import { exists, BaseDirectory } from '@tauri-apps/plugin-fs';
699 | * // Check if the `$APPDATA/avatar.png` file exists
700 | * await exists('avatar.png', { baseDir: BaseDirectory.AppData });
701 | * ```
702 | *
703 | * @since 2.0.0
704 | */
705 | async function exists(path, options) {
706 | if (path instanceof URL && path.protocol !== 'file:') {
707 | throw new TypeError('Must be a file URL.');
708 | }
709 | return await invoke('plugin:fs|exists', {
710 | path: path instanceof URL ? path.toString() : path,
711 | options
712 | });
713 | }
714 | class Watcher extends Resource {
715 | }
716 | async function watchInternal(paths, cb, options) {
717 | const watchPaths = Array.isArray(paths) ? paths : [paths];
718 | for (const path of watchPaths) {
719 | if (path instanceof URL && path.protocol !== 'file:') {
720 | throw new TypeError('Must be a file URL.');
721 | }
722 | }
723 | const onEvent = new Channel();
724 | onEvent.onmessage = cb;
725 | const rid = await invoke('plugin:fs|watch', {
726 | paths: watchPaths.map((p) => (p instanceof URL ? p.toString() : p)),
727 | options,
728 | onEvent
729 | });
730 | const watcher = new Watcher(rid);
731 | return () => {
732 | void watcher.close();
733 | };
734 | }
735 | // TODO: Return `Watcher` instead in v3
736 | /**
737 | * Watch changes (after a delay) on files or directories.
738 | *
739 | * @since 2.0.0
740 | */
741 | async function watch(paths, cb, options) {
742 | return await watchInternal(paths, cb, {
743 | delayMs: 2000,
744 | ...options
745 | });
746 | }
747 | // TODO: Return `Watcher` instead in v3
748 | /**
749 | * Watch changes on files or directories.
750 | *
751 | * @since 2.0.0
752 | */
753 | async function watchImmediate(paths, cb, options) {
754 | return await watchInternal(paths, cb, {
755 | ...options,
756 | delayMs: undefined
757 | });
758 | }
759 | /**
760 | * Get the size of a file or directory. For files, the `stat` functions can be used as well.
761 | *
762 | * If `path` is a directory, this function will recursively iterate over every file and every directory inside of `path` and therefore will be very time consuming if used on larger directories.
763 | *
764 | * @example
765 | * ```typescript
766 | * import { size, BaseDirectory } from '@tauri-apps/plugin-fs';
767 | * // Get the size of the `$APPDATA/tauri` directory.
768 | * const dirSize = await size('tauri', { baseDir: BaseDirectory.AppData });
769 | * console.log(dirSize); // 1024
770 | * ```
771 | *
772 | * @since 2.1.0
773 | */
774 | async function size(path) {
775 | if (path instanceof URL && path.protocol !== 'file:') {
776 | throw new TypeError('Must be a file URL.');
777 | }
778 | return await invoke('plugin:fs|size', {
779 | path: path instanceof URL ? path.toString() : path
780 | });
781 | }
782 |
783 | export { FileHandle, SeekMode, copyFile, create, exists, lstat, mkdir, open, readDir, readFile, readTextFile, readTextFileLines, remove, rename, size, stat, truncate, watch, watchImmediate, writeFile, writeTextFile };
784 |
--------------------------------------------------------------------------------