snapshot of https://github.com/tauri-apps/plugins-workspace.git (v2, 2026-09-23; blobs > 131072B omitted)
Some checks failed
integration tests / run-integration-tests (windows-latest) (push) Has been cancelled
Test Rust / test (push) Has been cancelled
test plugins e2e (mobile) / ios (push) Has been cancelled
test plugins e2e / test (map[name:Windows os:windows-latest]) (push) Has been cancelled
test plugins e2e / test (map[name:macOS os:macos-latest]) (push) Has been cancelled
integration tests / run-integration-tests (macos-latest) (push) Has been cancelled
version or publish / version-or-publish (push) Failing after 0s
integration tests / run-integration-tests (ubuntu-22.04) (push) Failing after 0s
Lint JavaScript / eslint (push) Failing after 0s
Sync / sync-to-mirrors (push) Failing after 0s
test plugins e2e (mobile) / android (push) Failing after 0s
test plugins e2e / test (map[name:Linux os:ubuntu-latest]) (push) Failing after 0s
Test Rust / changes (push) Failing after 0s
Lint Rust / changes (push) Failing after 0s
Lint Rust / clippy (push) Has been skipped
Audit Rust / audit-rust (push) Failing after 1s
Audit JavaScript / audit-js (push) Failing after 1s
Some checks failed
integration tests / run-integration-tests (windows-latest) (push) Has been cancelled
Test Rust / test (push) Has been cancelled
test plugins e2e (mobile) / ios (push) Has been cancelled
test plugins e2e / test (map[name:Windows os:windows-latest]) (push) Has been cancelled
test plugins e2e / test (map[name:macOS os:macos-latest]) (push) Has been cancelled
integration tests / run-integration-tests (macos-latest) (push) Has been cancelled
version or publish / version-or-publish (push) Failing after 0s
integration tests / run-integration-tests (ubuntu-22.04) (push) Failing after 0s
Lint JavaScript / eslint (push) Failing after 0s
Sync / sync-to-mirrors (push) Failing after 0s
test plugins e2e (mobile) / android (push) Failing after 0s
test plugins e2e / test (map[name:Linux os:ubuntu-latest]) (push) Failing after 0s
Test Rust / changes (push) Failing after 0s
Lint Rust / changes (push) Failing after 0s
Lint Rust / clippy (push) Has been skipped
Audit Rust / audit-rust (push) Failing after 1s
Audit JavaScript / audit-js (push) Failing after 1s
This commit is contained in:
159
plugins/shell/CHANGELOG.md
Normal file
159
plugins/shell/CHANGELOG.md
Normal file
@@ -0,0 +1,159 @@
|
||||
# Changelog
|
||||
|
||||
## [2.3.6]
|
||||
|
||||
- [`db9c5998`](https://github.com/tauri-apps/plugins-workspace/commit/db9c5998feff9384f9cbbefcbe0d45937c00a1fc) ([#3531](https://github.com/tauri-apps/plugins-workspace/pull/3531) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Fix missing `consumer-rules.pro` on Gradle v9.
|
||||
|
||||
## \[2.3.5]
|
||||
|
||||
### bug
|
||||
|
||||
- [`d4613ff0`](https://github.com/tauri-apps/plugins-workspace/commit/d4613ff0029ea65f5c6895c3a6f8f5668dd1b55e) ([#3234](https://github.com/tauri-apps/plugins-workspace/pull/3234)) Make sidecars work in tests. Executable resolution is aware of the "deps" directory.
|
||||
|
||||
## \[2.3.4]
|
||||
|
||||
- [`31415eff`](https://github.com/tauri-apps/plugins-workspace/commit/31415effdf5a9ced19934a681cb044a732174088) ([#3183](https://github.com/tauri-apps/plugins-workspace/pull/3183) by [@Tunglies](https://github.com/tauri-apps/plugins-workspace/../../Tunglies)) Docs on example to Encoding usage in `Command::spawn`. No user facing changes.
|
||||
|
||||
## \[2.3.3]
|
||||
|
||||
- [`93426f85`](https://github.com/tauri-apps/plugins-workspace/commit/93426f85120f49beb9f40222bff45185a32d54a9) Fixed an issue that caused docs.rs builds to fail. No user facing changes.
|
||||
|
||||
## \[2.3.2]
|
||||
|
||||
- [`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.
|
||||
|
||||
## \[2.3.1]
|
||||
|
||||
- [`d865ed47`](https://github.com/tauri-apps/plugins-workspace/commit/d865ed47685c3923e894f7d10ee4c037507037e6) ([#2950](https://github.com/tauri-apps/plugins-workspace/pull/2950) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Fix sidecar with dots in the filename not working on Windows.
|
||||
|
||||
## \[2.3.0]
|
||||
|
||||
- [`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
|
||||
|
||||
## \[2.2.2]
|
||||
|
||||
- [`f634e524`](https://github.com/tauri-apps/plugins-workspace/commit/f634e5248ebe428f8305a59f74c13fc15147fb8e) This is an "empty" release to update the plugins' source files on crates.io and docs.rs. This should fix docs.rs build failures for projects using tauri plugins as dependencies.
|
||||
|
||||
## \[2.2.1]
|
||||
|
||||
### bug
|
||||
|
||||
- [`9cf0390a`](https://github.com/tauri-apps/plugins-workspace/commit/9cf0390a52497e273db1a1b613a0e26827aa327c) Apply the default open validation regex `^((mailto:\w+)|(tel:\w+)|(https?://\w+)).+` when the open configuration is not set, preventing unchecked input from being used in this scenario (previously the plugin would skip validation when it should disable all calls). This keeps backwards compatibility while still fixing this vulnerability.
|
||||
The scope is no longer validated for Rust calls via `ShellExt::shell()` so if you need to block JavaScript from calling the API you can simply set `tauri.conf.json > plugins > shell > open` to `false`.
|
||||
|
||||
## \[2.2.0]
|
||||
|
||||
- [`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.
|
||||
|
||||
## \[2.0.1]
|
||||
|
||||
- [`51ddf6a7`](https://github.com/tauri-apps/plugins-workspace/commit/51ddf6a71544acfb261ffc9393dab1342da0a219) ([#1881](https://github.com/tauri-apps/plugins-workspace/pull/1881) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) On Windows, Fix `open` JS API hanging and freezing the app.
|
||||
|
||||
## \[2.0.1]
|
||||
|
||||
- [`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.
|
||||
|
||||
## \[2.0.0]
|
||||
|
||||
- [`e2c4dfb6`](https://github.com/tauri-apps/plugins-workspace/commit/e2c4dfb6af43e5dd8d9ceba232c315f5febd55c1) Update to tauri v2 stable release.
|
||||
|
||||
## \[2.0.0-rc.4]
|
||||
|
||||
- [`44273b98`](https://github.com/tauri-apps/plugins-workspace/commit/44273b988957a254eff715d6be7547d2ace882e1) ([#1839](https://github.com/tauri-apps/plugins-workspace/pull/1839) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Fix the plugin schema requiring to set `sidecar` property when it is in fact optional.
|
||||
|
||||
## \[2.0.0-rc.1]
|
||||
|
||||
- [`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
|
||||
|
||||
## \[2.0.0-rc.2]
|
||||
|
||||
- [`b9147758`](https://github.com/tauri-apps/plugins-workspace/commit/b914775898c2bee7ceb20bd17ee595005cd17a64) ([#1679](https://github.com/tauri-apps/plugins-workspace/pull/1679) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Explicitly set a minimum macOS version for the Swift package.
|
||||
|
||||
## \[2.0.0-rc.1]
|
||||
|
||||
### changes
|
||||
|
||||
- [`6b079cfd`](https://github.com/tauri-apps/plugins-workspace/commit/6b079cfdd107c94abc2c7300f6af00bac3ff4040) ([#1649](https://github.com/tauri-apps/plugins-workspace/pull/1649) by [@ahqsoftwares](https://github.com/tauri-apps/plugins-workspace/../../ahqsoftwares)) Remove targetSdk from build.kts files as it is deprecated and will be removed from DSL v9.0
|
||||
|
||||
## \[2.0.0-rc.0]
|
||||
|
||||
- [`9887d1`](https://github.com/tauri-apps/plugins-workspace/commit/9887d14bd0e971c4c0f5c1188fc4005d3fc2e29e) Update to tauri RC.
|
||||
- [`34df132f`](https://github.com/tauri-apps/plugins-workspace/commit/34df132fb14212ba7330adc9ccd64267751950c8) ([#1603](https://github.com/tauri-apps/plugins-workspace/pull/1603)) Change the `open` scope validator regex to match on the entire string.
|
||||
- [`34df132f`](https://github.com/tauri-apps/plugins-workspace/commit/34df132fb14212ba7330adc9ccd64267751950c8) ([#1603](https://github.com/tauri-apps/plugins-workspace/pull/1603)) Change the `execute` scope argument validator regex to match on the entire string by default.
|
||||
If this behavior is not desired check the `raw` boolean configuration option that is available along the `validator` string.
|
||||
|
||||
## \[2.0.0-beta.9]
|
||||
|
||||
- [`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.
|
||||
- [`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.
|
||||
|
||||
## \[2.0.0-beta.8]
|
||||
|
||||
- [`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.
|
||||
|
||||
## \[2.0.0-beta.7]
|
||||
|
||||
- [`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.
|
||||
|
||||
## \[2.0.0-beta.6]
|
||||
|
||||
- [`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.
|
||||
|
||||
## \[2.0.0-beta.5]
|
||||
|
||||
- [`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.
|
||||
|
||||
## \[2.0.0-beta.4]
|
||||
|
||||
- [`eb1679b9`](https://github.com/tauri-apps/plugins-workspace/commit/eb1679b99780e5d2b867f5649a1ccc2f3f70ab56)([#1299](https://github.com/tauri-apps/plugins-workspace/pull/1299)) Fix `Command.execute` API including extra new lines.
|
||||
- [`eb1679b9`](https://github.com/tauri-apps/plugins-workspace/commit/eb1679b99780e5d2b867f5649a1ccc2f3f70ab56)([#1299](https://github.com/tauri-apps/plugins-workspace/pull/1299)) Improve the speed of the JS `Command.execute` API
|
||||
|
||||
## \[2.0.0-beta.3]
|
||||
|
||||
- [`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.
|
||||
|
||||
## \[2.0.0-beta.3]
|
||||
|
||||
- [`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.
|
||||
- [`040004a`](https://github.com/tauri-apps/plugins-workspace/commit/040004a6b9fbb89161d1b5764d79428dfe693776)([#1069](https://github.com/tauri-apps/plugins-workspace/pull/1069)) Change shell's schema property name `command` to `cmd`.
|
||||
|
||||
## \[2.0.0-beta.2]
|
||||
|
||||
- [`9586eab`](https://github.com/tauri-apps/plugins-workspace/commit/9586eabd5a96673e4d976757777f470ae358d68a)([#1021](https://github.com/tauri-apps/plugins-workspace/pull/1021)) On Windows, fix `open` can't open file if the file is being used by a program.
|
||||
- [`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.
|
||||
|
||||
## \[2.0.0-beta.1]
|
||||
|
||||
- [`569defb`](https://github.com/tauri-apps/plugins-workspace/commit/569defbe9492e38938554bb7bdc1be9151456d21) Update to tauri beta.4.
|
||||
|
||||
## \[2.0.0-beta.0]
|
||||
|
||||
- [`d198c01`](https://github.com/tauri-apps/plugins-workspace/commit/d198c014863ee260cb0de88a14b7fc4356ef7474)([#862](https://github.com/tauri-apps/plugins-workspace/pull/862)) Update to tauri beta.
|
||||
|
||||
## \[2.0.0-alpha.5]
|
||||
|
||||
- [`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.
|
||||
|
||||
## \[2.0.0-alpha.4]
|
||||
|
||||
- [`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.
|
||||
|
||||
## \[2.0.0-alpha.3]
|
||||
|
||||
- [`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.
|
||||
|
||||
## \[2.0.0-alpha.2]
|
||||
|
||||
- [`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.
|
||||
|
||||
## \[2.0.0-alpha.2]
|
||||
|
||||
- [`4e2cef9`](https://github.com/tauri-apps/plugins-workspace/commit/4e2cef9b702bbbb9cf4ee17de50791cb21f1b2a4)([#593](https://github.com/tauri-apps/plugins-workspace/pull/593)) Update to alpha.12.
|
||||
|
||||
## \[2.0.0-alpha.1]
|
||||
|
||||
- [`d74fc0a`](https://github.com/tauri-apps/plugins-workspace/commit/d74fc0a097996e90a37be8f57d50b7d1f6ca616f)([#555](https://github.com/tauri-apps/plugins-workspace/pull/555)) Update to alpha.11.
|
||||
|
||||
## \[2.0.0-alpha.0]
|
||||
|
||||
- [`717ae67`](https://github.com/tauri-apps/plugins-workspace/commit/717ae670978feb4492fac1f295998b93f2b9347f)([#371](https://github.com/tauri-apps/plugins-workspace/pull/371)) First v2 alpha release!
|
||||
49
plugins/shell/Cargo.toml
Normal file
49
plugins/shell/Cargo.toml
Normal file
@@ -0,0 +1,49 @@
|
||||
[package]
|
||||
name = "tauri-plugin-shell"
|
||||
version = "2.3.6"
|
||||
description = "Access the system shell. Allows you to spawn child processes and manage files and URLs using their default application."
|
||||
edition = { workspace = true }
|
||||
authors = { workspace = true }
|
||||
license = { workspace = true }
|
||||
rust-version = { workspace = true }
|
||||
repository = { workspace = true }
|
||||
links = "tauri-plugin-shell"
|
||||
exclude = [
|
||||
"/banner.png",
|
||||
"/guest-js",
|
||||
"/package.json",
|
||||
"/rollup.config.js",
|
||||
"/test",
|
||||
"/tsconfig.json",
|
||||
]
|
||||
|
||||
[package.metadata.platforms.support]
|
||||
windows = { level = "full", notes = "" }
|
||||
linux = { level = "full", notes = "" }
|
||||
macos = { level = "full", notes = "" }
|
||||
android = { level = "partial", notes = "Only allows to open URLs via `open`" }
|
||||
ios = { level = "partial", notes = "Only allows to open URLs via `open`" }
|
||||
|
||||
[build-dependencies]
|
||||
tauri-plugin = { workspace = true, features = ["build"] }
|
||||
schemars = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tauri = { workspace = true, features = ["wry"] }
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
tauri = { workspace = true }
|
||||
tokio = { version = "1", features = ["time"] }
|
||||
log = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
shared_child = "1"
|
||||
regex = "1"
|
||||
open = { version = "5", features = ["shellexecute-on-windows"] }
|
||||
encoding_rs = "0.8"
|
||||
os_pipe = "1"
|
||||
|
||||
[target.'cfg(target_os = "ios")'.dependencies]
|
||||
tauri = { workspace = true, features = ["wry"] }
|
||||
20
plugins/shell/LICENSE.spdx
Normal file
20
plugins/shell/LICENSE.spdx
Normal file
@@ -0,0 +1,20 @@
|
||||
SPDXVersion: SPDX-2.1
|
||||
DataLicense: CC0-1.0
|
||||
PackageName: tauri
|
||||
DataFormat: SPDXRef-1
|
||||
PackageSupplier: Organization: The Tauri Programme in the Commons Conservancy
|
||||
PackageHomePage: https://tauri.app
|
||||
PackageLicenseDeclared: Apache-2.0
|
||||
PackageLicenseDeclared: MIT
|
||||
PackageCopyrightText: 2019-2022, The Tauri Programme in the Commons Conservancy
|
||||
PackageSummary: <text>Tauri is a rust project that enables developers to make secure
|
||||
and small desktop applications using a web frontend.
|
||||
</text>
|
||||
PackageComment: <text>The package includes the following libraries; see
|
||||
Relationship information.
|
||||
</text>
|
||||
Created: 2019-05-20T09:00:00Z
|
||||
PackageDownloadLocation: git://github.com/tauri-apps/tauri
|
||||
PackageDownloadLocation: git+https://github.com/tauri-apps/tauri.git
|
||||
PackageDownloadLocation: git+ssh://github.com/tauri-apps/tauri.git
|
||||
Creator: Person: Daniel Thompson-Yvetot
|
||||
177
plugins/shell/LICENSE_APACHE-2.0
Normal file
177
plugins/shell/LICENSE_APACHE-2.0
Normal file
@@ -0,0 +1,177 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
21
plugins/shell/LICENSE_MIT
Normal file
21
plugins/shell/LICENSE_MIT
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2017 - Present Tauri Apps Contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
90
plugins/shell/README.md
Normal file
90
plugins/shell/README.md
Normal file
@@ -0,0 +1,90 @@
|
||||

|
||||
|
||||
Access the system shell. Allows you to spawn child processes and manage files and URLs using their default application.
|
||||
|
||||
| Platform | Supported |
|
||||
| -------- | --------- |
|
||||
| Linux | ✓ |
|
||||
| Windows | ✓ |
|
||||
| macOS | ✓ |
|
||||
| Android | ✓ |
|
||||
| iOS | ✓ |
|
||||
|
||||
## Install
|
||||
|
||||
_This plugin requires a Rust version of at least **1.77.2**_
|
||||
|
||||
There are three general methods of installation that we can recommend.
|
||||
|
||||
1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked)
|
||||
2. Pull sources directly from Github using git tags / revision hashes (most secure)
|
||||
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)
|
||||
|
||||
Install the Core plugin by adding the following to your `Cargo.toml` file:
|
||||
|
||||
`src-tauri/Cargo.toml`
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
tauri-plugin-shell = "2.0.0"
|
||||
# alternatively with Git:
|
||||
tauri-plugin-shell = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
|
||||
```
|
||||
|
||||
You can install the JavaScript Guest bindings using your preferred JavaScript package manager:
|
||||
|
||||
```sh
|
||||
pnpm add @tauri-apps/plugin-shell
|
||||
# or
|
||||
npm add @tauri-apps/plugin-shell
|
||||
# or
|
||||
yarn add @tauri-apps/plugin-shell
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
First you need to register the core plugin with Tauri:
|
||||
|
||||
`src-tauri/src/lib.rs`
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_shell::init())
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
}
|
||||
```
|
||||
|
||||
Afterwards all the plugin's APIs are available through the JavaScript guest bindings:
|
||||
|
||||
```javascript
|
||||
import { Command } from '@tauri-apps/plugin-shell'
|
||||
Command.create('git', ['commit', '-m', 'the commit message'])
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
PRs accepted. Please make sure to read the Contributing Guide before making a pull request.
|
||||
|
||||
## Partners
|
||||
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://crabnebula.dev" target="_blank">
|
||||
<img src="https://github.com/tauri-apps/plugins-workspace/raw/v2/.github/sponsors/crabnebula.svg" alt="CrabNebula" width="283">
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
For the complete list of sponsors please visit our [website](https://tauri.app#sponsors) and [Open Collective](https://opencollective.com/tauri).
|
||||
|
||||
## License
|
||||
|
||||
Code: (c) 2015 - Present - The Tauri Programme within The Commons Conservancy.
|
||||
|
||||
MIT or MIT/Apache 2.0 where applicable.
|
||||
23
plugins/shell/SECURITY.md
Normal file
23
plugins/shell/SECURITY.md
Normal file
@@ -0,0 +1,23 @@
|
||||
# Security Policy
|
||||
|
||||
**Do not report security vulnerabilities through public GitHub issues.**
|
||||
|
||||
**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.**
|
||||
|
||||
Include as much of the following information:
|
||||
|
||||
- Type of issue (e.g. improper input parsing, privilege escalation, etc.)
|
||||
- The location of the affected source code (tag/branch/commit or direct URL)
|
||||
- Any special configuration required to reproduce the issue
|
||||
- The distribution affected or used to help us with reproduction of the issue
|
||||
- Step-by-step instructions to reproduce the issue
|
||||
- Ideally a reproduction repository
|
||||
- Impact of the issue, including how an attacker might exploit the issue
|
||||
|
||||
We prefer to receive reports in English.
|
||||
|
||||
## Contact
|
||||
|
||||
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).
|
||||
|
||||
Alternatively, you can also contact us by email via [security@tauri.app](mailto:security@tauri.app).
|
||||
2
plugins/shell/android/.gitignore
vendored
Normal file
2
plugins/shell/android/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
/build
|
||||
/.tauri
|
||||
30
plugins/shell/android/build.gradle.kts
Normal file
30
plugins/shell/android/build.gradle.kts
Normal file
@@ -0,0 +1,30 @@
|
||||
plugins {
|
||||
id("com.android.library")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "app.tauri.shell"
|
||||
compileSdk = 36
|
||||
|
||||
defaultConfig {
|
||||
minSdk = 24
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
consumerProguardFiles("consumer-rules.pro")
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||
targetCompatibility = JavaVersion.VERSION_1_8
|
||||
}
|
||||
kotlinOptions {
|
||||
jvmTarget = "1.8"
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("androidx.core:core-ktx:1.9.0")
|
||||
implementation("com.fasterxml.jackson.core:jackson-databind:2.15.3")
|
||||
implementation(project(":tauri-android"))
|
||||
}
|
||||
21
plugins/shell/android/consumer-rules.pro
Normal file
21
plugins/shell/android/consumer-rules.pro
Normal file
@@ -0,0 +1,21 @@
|
||||
# Add project specific ProGuard rules here.
|
||||
# You can control the set of applied configuration files using the
|
||||
# proguardFiles setting in build.gradle.
|
||||
#
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
||||
|
||||
# Uncomment this to preserve the line number information for
|
||||
# debugging stack traces.
|
||||
#-keepattributes SourceFile,LineNumberTable
|
||||
|
||||
# If you keep the line number information, uncomment this to
|
||||
# hide the original source file name.
|
||||
#-renamesourcefileattribute SourceFile
|
||||
2
plugins/shell/android/settings.gradle
Normal file
2
plugins/shell/android/settings.gradle
Normal file
@@ -0,0 +1,2 @@
|
||||
include ':tauri-android'
|
||||
project(':tauri-android').projectDir = new File('./.tauri/tauri-api')
|
||||
3
plugins/shell/android/src/main/AndroidManifest.xml
Normal file
3
plugins/shell/android/src/main/AndroidManifest.xml
Normal file
@@ -0,0 +1,3 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
</manifest>
|
||||
30
plugins/shell/android/src/main/java/ShellPlugin.kt
Normal file
30
plugins/shell/android/src/main/java/ShellPlugin.kt
Normal file
@@ -0,0 +1,30 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.shell
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import app.tauri.annotation.Command
|
||||
import app.tauri.annotation.TauriPlugin
|
||||
import app.tauri.plugin.Invoke
|
||||
import app.tauri.plugin.Plugin
|
||||
import java.io.File
|
||||
|
||||
@TauriPlugin
|
||||
class ShellPlugin(private val activity: Activity) : Plugin(activity) {
|
||||
@Command
|
||||
fun open(invoke: Invoke) {
|
||||
try {
|
||||
val url = invoke.parseArgs(String::class.java)
|
||||
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
|
||||
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
activity.applicationContext?.startActivity(intent)
|
||||
invoke.resolve()
|
||||
} catch (ex: Exception) {
|
||||
invoke.reject(ex.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
1
plugins/shell/api-iife.js
Normal file
1
plugins/shell/api-iife.js
Normal file
@@ -0,0 +1 @@
|
||||
if("__TAURI__"in window){var __TAURI_PLUGIN_SHELL__=function(e,t){"use strict";class s{constructor(){this.eventListeners=Object.create(null)}addListener(e,t){return this.on(e,t)}removeListener(e,t){return this.off(e,t)}on(e,t){return e in this.eventListeners?this.eventListeners[e].push(t):this.eventListeners[e]=[t],this}once(e,t){const s=n=>{this.removeListener(e,s),t(n)};return this.addListener(e,s)}off(e,t){return e in this.eventListeners&&(this.eventListeners[e]=this.eventListeners[e].filter(e=>e!==t)),this}removeAllListeners(e){return e?delete this.eventListeners[e]:this.eventListeners=Object.create(null),this}emit(e,t){if(e in this.eventListeners){const s=this.eventListeners[e];for(const e of s)e(t);return!0}return!1}listenerCount(e){return e in this.eventListeners?this.eventListeners[e].length:0}prependListener(e,t){return e in this.eventListeners?this.eventListeners[e].unshift(t):this.eventListeners[e]=[t],this}prependOnceListener(e,t){const s=n=>{this.removeListener(e,s),t(n)};return this.prependListener(e,s)}}class n{constructor(e){this.pid=e}async write(e){await t.invoke("plugin:shell|stdin_write",{pid:this.pid,buffer:e})}async kill(){await t.invoke("plugin:shell|kill",{cmd:"killChild",pid:this.pid})}}class i extends s{constructor(e,t=[],n){super(),this.stdout=new s,this.stderr=new s,this.program=e,this.args="string"==typeof t?[t]:t,this.options=n??{}}static create(e,t=[],s){return new i(e,t,s)}static sidecar(e,t=[],s){const n=new i(e,t,s);return n.options.sidecar=!0,n}async spawn(){const e=this.program,s=this.args,i=this.options;"object"==typeof s&&Object.freeze(s);const r=new t.Channel;return r.onmessage=e=>{switch(e.event){case"Error":this.emit("error",e.payload);break;case"Terminated":this.emit("close",e.payload);break;case"Stdout":this.stdout.emit("data",e.payload);break;case"Stderr":this.stderr.emit("data",e.payload)}},await t.invoke("plugin:shell|spawn",{program:e,args:s,options:i,onEvent:r}).then(e=>new n(e))}async execute(){const e=this.program,s=this.args,n=this.options;return"object"==typeof s&&Object.freeze(s),await t.invoke("plugin:shell|execute",{program:e,args:s,options:n})}}return e.Child=n,e.Command=i,e.EventEmitter=s,e.open=async function(e,s){await t.invoke("plugin:shell|open",{path:e,with:s})},e}({},window.__TAURI__.core);Object.defineProperty(window.__TAURI__,"shell",{value:__TAURI_PLUGIN_SHELL__})}
|
||||
BIN
plugins/shell/banner.png
Normal file
BIN
plugins/shell/banner.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 51 KiB |
189
plugins/shell/build.rs
Normal file
189
plugins/shell/build.rs
Normal file
@@ -0,0 +1,189 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use schemars::JsonSchema;
|
||||
|
||||
#[path = "src/scope_entry.rs"]
|
||||
mod scope_entry;
|
||||
|
||||
/// A command argument allowed to be executed by the webview API.
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Hash, schemars::JsonSchema)]
|
||||
#[serde(untagged, deny_unknown_fields)]
|
||||
#[non_exhaustive]
|
||||
pub enum ShellScopeEntryAllowedArg {
|
||||
/// A non-configurable argument that is passed to the command in the order it was specified.
|
||||
Fixed(String),
|
||||
|
||||
/// A variable that is set while calling the command from the webview API.
|
||||
///
|
||||
Var {
|
||||
/// [regex] validator to require passed values to conform to an expected input.
|
||||
///
|
||||
/// This will require the argument value passed to this variable to match the `validator` regex
|
||||
/// before it will be executed.
|
||||
///
|
||||
/// The regex string is by default surrounded by `^...$` to match the full string.
|
||||
/// For example the `https?://\w+` regex would be registered as `^https?://\w+$`.
|
||||
///
|
||||
/// [regex]: <https://docs.rs/regex/latest/regex/#syntax>
|
||||
validator: String,
|
||||
|
||||
/// Marks the validator as a raw regex, meaning the plugin should not make any modification at runtime.
|
||||
///
|
||||
/// This means the regex will not match on the entire string by default, which might
|
||||
/// be exploited if your regex allow unexpected input to be considered valid.
|
||||
/// When using this option, make sure your regex is correct.
|
||||
#[serde(default)]
|
||||
raw: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// A set of command arguments allowed to be executed by the webview API.
|
||||
///
|
||||
/// A value of `true` will allow any arguments to be passed to the command. `false` will disable all
|
||||
/// arguments. A list of [`ShellScopeEntryAllowedArg`] will set those arguments as the only valid arguments to
|
||||
/// be passed to the attached command configuration.
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Hash, JsonSchema)]
|
||||
#[serde(untagged, deny_unknown_fields)]
|
||||
#[non_exhaustive]
|
||||
pub enum ShellScopeEntryAllowedArgs {
|
||||
/// Use a simple boolean to allow all or disable all arguments to this command configuration.
|
||||
Flag(bool),
|
||||
|
||||
/// A specific set of [`ShellScopeEntryAllowedArg`] that are valid to call for the command configuration.
|
||||
List(Vec<ShellScopeEntryAllowedArg>),
|
||||
}
|
||||
|
||||
impl Default for ShellScopeEntryAllowedArgs {
|
||||
fn default() -> Self {
|
||||
Self::Flag(false)
|
||||
}
|
||||
}
|
||||
|
||||
/// Shell scope entry.
|
||||
#[derive(JsonSchema)]
|
||||
#[serde(untagged, deny_unknown_fields)]
|
||||
#[allow(unused)]
|
||||
pub(crate) enum ShellScopeEntry {
|
||||
Command {
|
||||
/// The name for this allowed shell command configuration.
|
||||
///
|
||||
/// This name will be used inside of the webview API to call this command along with
|
||||
/// any specified arguments.
|
||||
name: String,
|
||||
/// The command name.
|
||||
/// It can start with a variable that resolves to a system base directory.
|
||||
/// The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`,
|
||||
/// `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`,
|
||||
/// `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`,
|
||||
/// `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.
|
||||
// use default just so the schema doesn't flag it as required
|
||||
#[serde(rename = "cmd")]
|
||||
command: PathBuf,
|
||||
/// The allowed arguments for the command execution.
|
||||
#[serde(default)]
|
||||
args: ShellScopeEntryAllowedArgs,
|
||||
},
|
||||
Sidecar {
|
||||
/// The name for this allowed shell command configuration.
|
||||
///
|
||||
/// This name will be used inside of the webview API to call this command along with
|
||||
/// any specified arguments.
|
||||
name: String,
|
||||
/// The allowed arguments for the command execution.
|
||||
#[serde(default)]
|
||||
args: ShellScopeEntryAllowedArgs,
|
||||
/// If this command is a sidecar command.
|
||||
sidecar: bool,
|
||||
},
|
||||
}
|
||||
|
||||
// Ensure `ShellScopeEntry` and `scope_entry::EntryRaw`
|
||||
// and `ShellScopeEntryAllowedArg` and `ShellAllowedArg`
|
||||
// and `ShellScopeEntryAllowedArgs` and `ShellAllowedArgs`
|
||||
// are kept in sync
|
||||
#[allow(clippy::unnecessary_operation)]
|
||||
fn _f() {
|
||||
match (ShellScopeEntry::Sidecar {
|
||||
name: String::new(),
|
||||
args: ShellScopeEntryAllowedArgs::Flag(false),
|
||||
sidecar: true,
|
||||
}) {
|
||||
ShellScopeEntry::Command {
|
||||
name,
|
||||
command,
|
||||
args,
|
||||
} => scope_entry::EntryRaw {
|
||||
name,
|
||||
command: Some(command),
|
||||
args: match args {
|
||||
ShellScopeEntryAllowedArgs::Flag(flag) => scope_entry::ShellAllowedArgs::Flag(flag),
|
||||
ShellScopeEntryAllowedArgs::List(vec) => scope_entry::ShellAllowedArgs::List(
|
||||
vec.into_iter()
|
||||
.map(|s| match s {
|
||||
ShellScopeEntryAllowedArg::Fixed(fixed) => {
|
||||
scope_entry::ShellAllowedArg::Fixed(fixed)
|
||||
}
|
||||
ShellScopeEntryAllowedArg::Var { validator, raw } => {
|
||||
scope_entry::ShellAllowedArg::Var { validator, raw }
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
},
|
||||
sidecar: false,
|
||||
},
|
||||
ShellScopeEntry::Sidecar {
|
||||
name,
|
||||
args,
|
||||
sidecar,
|
||||
} => scope_entry::EntryRaw {
|
||||
name,
|
||||
command: None,
|
||||
args: match args {
|
||||
ShellScopeEntryAllowedArgs::Flag(flag) => scope_entry::ShellAllowedArgs::Flag(flag),
|
||||
ShellScopeEntryAllowedArgs::List(vec) => scope_entry::ShellAllowedArgs::List(
|
||||
vec.into_iter()
|
||||
.map(|s| match s {
|
||||
ShellScopeEntryAllowedArg::Fixed(fixed) => {
|
||||
scope_entry::ShellAllowedArg::Fixed(fixed)
|
||||
}
|
||||
ShellScopeEntryAllowedArg::Var { validator, raw } => {
|
||||
scope_entry::ShellAllowedArg::Var { validator, raw }
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
},
|
||||
sidecar,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const COMMANDS: &[&str] = &["execute", "spawn", "stdin_write", "kill", "open"];
|
||||
|
||||
fn main() {
|
||||
tauri_plugin::Builder::new(COMMANDS)
|
||||
.global_api_script_path("./api-iife.js")
|
||||
.global_scope_schema(schemars::schema_for!(ShellScopeEntry))
|
||||
.android_path("android")
|
||||
.ios_path("ios")
|
||||
.build();
|
||||
|
||||
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
|
||||
let mobile = target_os == "ios" || target_os == "android";
|
||||
alias("desktop", !mobile);
|
||||
alias("mobile", mobile);
|
||||
}
|
||||
|
||||
// creates a cfg alias if `has_feature` is true.
|
||||
// `alias` must be a snake case string.
|
||||
fn alias(alias: &str, has_feature: bool) {
|
||||
println!("cargo:rustc-check-cfg=cfg({alias})");
|
||||
if has_feature {
|
||||
println!("cargo:rustc-cfg={alias}");
|
||||
}
|
||||
}
|
||||
928
plugins/shell/guest-js/index.ts
Normal file
928
plugins/shell/guest-js/index.ts
Normal file
@@ -0,0 +1,928 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/**
|
||||
* Access the system shell.
|
||||
* Allows you to spawn child processes and manage files and URLs using their default application.
|
||||
*
|
||||
* ## Security
|
||||
*
|
||||
* This API has a scope configuration that forces you to restrict the programs and arguments that can be used.
|
||||
*
|
||||
* ### Restricting access to the {@link open | `open`} API
|
||||
*
|
||||
* On the configuration object, `open: true` means that the {@link open} API can be used with any URL,
|
||||
* as the argument is validated with the `^((mailto:\w+)|(tel:\w+)|(https?://\w+)).+` regex.
|
||||
* You can change that regex by changing the boolean value to a string, e.g. `open: ^https://github.com/`.
|
||||
*
|
||||
* ### Restricting access to the {@link Command | `Command`} APIs
|
||||
*
|
||||
* The plugin permissions object has a `scope` field that defines an array of CLIs that can be used.
|
||||
* Each CLI is a configuration object `{ name: string, cmd: string, sidecar?: bool, args?: boolean | Arg[] }`.
|
||||
*
|
||||
* - `name`: the unique identifier of the command, passed to the {@link Command.create | Command.create function}.
|
||||
* If it's a sidecar, this must be the value defined on `tauri.conf.json > bundle > externalBin`.
|
||||
* - `cmd`: the program that is executed on this configuration. If it's a sidecar, this value is ignored.
|
||||
* - `sidecar`: whether the object configures a sidecar or a system program.
|
||||
* - `args`: the arguments that can be passed to the program. By default no arguments are allowed.
|
||||
* - `true` means that any argument list is allowed.
|
||||
* - `false` means that no arguments are allowed.
|
||||
* - otherwise an array can be configured. Each item is either a string representing the fixed argument value
|
||||
* or a `{ validator: string }` that defines a regex validating the argument value.
|
||||
*
|
||||
* #### Example scope configuration
|
||||
*
|
||||
* CLI: `git commit -m "the commit message"`
|
||||
*
|
||||
* Capability:
|
||||
* ```json
|
||||
* {
|
||||
* "permissions": [
|
||||
* {
|
||||
* "identifier": "shell:allow-execute",
|
||||
* "allow": [
|
||||
* {
|
||||
* "name": "run-git-commit",
|
||||
* "cmd": "git",
|
||||
* "args": ["commit", "-m", { "validator": "\\S+" }]
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
* ```
|
||||
* Usage:
|
||||
* ```typescript
|
||||
* import { Command } from '@tauri-apps/plugin-shell'
|
||||
* Command.create('run-git-commit', ['commit', '-m', 'the commit message'])
|
||||
* ```
|
||||
*
|
||||
* Trying to execute any API with a program not configured on the scope results in a promise rejection due to denied access.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { invoke, Channel } from '@tauri-apps/api/core'
|
||||
|
||||
/**
|
||||
* Options that configure how a child process is spawned.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
interface SpawnOptions {
|
||||
/** Current working directory. */
|
||||
cwd?: string
|
||||
/** Environment variables. set to `null` to clear the process env. */
|
||||
env?: Record<string, string>
|
||||
/**
|
||||
* Character encoding for stdout/stderr
|
||||
*
|
||||
* @since 2.0.0
|
||||
* */
|
||||
encoding?: string
|
||||
}
|
||||
|
||||
/** @ignore */
|
||||
interface InternalSpawnOptions extends SpawnOptions {
|
||||
sidecar?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* The output collected from a child process that ran to completion.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
interface ChildProcess<O extends IOPayload> {
|
||||
/** Exit code of the process. `null` if the process was terminated by a signal on Unix. */
|
||||
code: number | null
|
||||
/** If the process was terminated by a signal, represents that signal. */
|
||||
signal: number | null
|
||||
/** The data that the process wrote to `stdout`. */
|
||||
stdout: O
|
||||
/** The data that the process wrote to `stderr`. */
|
||||
stderr: O
|
||||
}
|
||||
|
||||
/**
|
||||
* A minimal event emitter modeled after Node.js' `EventEmitter`, used by
|
||||
* {@link Command} and by its `stdout` and `stderr` streams.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
class EventEmitter<E extends Record<string, any>> {
|
||||
/** @ignore */
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any
|
||||
private eventListeners: Record<keyof E, Array<(arg: any) => void>> =
|
||||
Object.create(null)
|
||||
|
||||
/**
|
||||
* Alias for `emitter.on(eventName, listener)`.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Command } from '@tauri-apps/plugin-shell';
|
||||
* const command = Command.create('node');
|
||||
* command.addListener('error', (error) => console.error(error));
|
||||
* ```
|
||||
*
|
||||
* @param eventName The name of the event to listen to.
|
||||
* @param listener The callback invoked with the event payload.
|
||||
*
|
||||
* @returns A reference to the `EventEmitter`, so that calls can be chained.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
addListener<N extends keyof E>(
|
||||
eventName: N,
|
||||
listener: (arg: E[typeof eventName]) => void
|
||||
): this {
|
||||
return this.on(eventName, listener)
|
||||
}
|
||||
|
||||
/**
|
||||
* Alias for `emitter.off(eventName, listener)`.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Command } from '@tauri-apps/plugin-shell';
|
||||
* const command = Command.create('node');
|
||||
* const listener = (error: string) => console.error(error);
|
||||
* command.addListener('error', listener);
|
||||
* command.removeListener('error', listener);
|
||||
* ```
|
||||
*
|
||||
* @param eventName The name of the event to stop listening to.
|
||||
* @param listener The exact callback that was registered before.
|
||||
*
|
||||
* @returns A reference to the `EventEmitter`, so that calls can be chained.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
removeListener<N extends keyof E>(
|
||||
eventName: N,
|
||||
listener: (arg: E[typeof eventName]) => void
|
||||
): this {
|
||||
return this.off(eventName, listener)
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the `listener` function to the end of the listeners array for the
|
||||
* event named `eventName`. No checks are made to see if the `listener` has
|
||||
* already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple
|
||||
* times.
|
||||
*
|
||||
* Returns a reference to the `EventEmitter`, so that calls can be chained.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Command } from '@tauri-apps/plugin-shell';
|
||||
* const command = Command.create('node');
|
||||
* command.on('close', (data) => {
|
||||
* console.log(`command finished with code ${data.code}`);
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @param eventName The name of the event to listen to.
|
||||
* @param listener The callback invoked with the event payload.
|
||||
*
|
||||
* @returns A reference to the `EventEmitter`, so that calls can be chained.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
on<N extends keyof E>(
|
||||
eventName: N,
|
||||
listener: (arg: E[typeof eventName]) => void
|
||||
): this {
|
||||
if (eventName in this.eventListeners) {
|
||||
// eslint-disable-next-line security/detect-object-injection
|
||||
this.eventListeners[eventName].push(listener)
|
||||
} else {
|
||||
// eslint-disable-next-line security/detect-object-injection
|
||||
this.eventListeners[eventName] = [listener]
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a **one-time**`listener` function for the event named `eventName`. The
|
||||
* next time `eventName` is triggered, this listener is removed and then invoked.
|
||||
*
|
||||
* Returns a reference to the `EventEmitter`, so that calls can be chained.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Command } from '@tauri-apps/plugin-shell';
|
||||
* const command = Command.create('node');
|
||||
* command.once('close', (data) => {
|
||||
* console.log(`command finished with code ${data.code}`);
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @param eventName The name of the event to listen to once.
|
||||
* @param listener The callback invoked with the event payload.
|
||||
*
|
||||
* @returns A reference to the `EventEmitter`, so that calls can be chained.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
once<N extends keyof E>(
|
||||
eventName: N,
|
||||
listener: (arg: E[typeof eventName]) => void
|
||||
): this {
|
||||
const wrapper = (arg: E[typeof eventName]): void => {
|
||||
this.removeListener(eventName, wrapper)
|
||||
listener(arg)
|
||||
}
|
||||
return this.addListener(eventName, wrapper)
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the all specified listener from the listener array for the event eventName
|
||||
* Returns a reference to the `EventEmitter`, so that calls can be chained.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Command } from '@tauri-apps/plugin-shell';
|
||||
* const command = Command.create('node');
|
||||
* const listener = (error: string) => console.error(error);
|
||||
* command.on('error', listener);
|
||||
* command.off('error', listener);
|
||||
* ```
|
||||
*
|
||||
* @param eventName The name of the event to stop listening to.
|
||||
* @param listener The exact callback that was registered before.
|
||||
*
|
||||
* @returns A reference to the `EventEmitter`, so that calls can be chained.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
off<N extends keyof E>(
|
||||
eventName: N,
|
||||
listener: (arg: E[typeof eventName]) => void
|
||||
): this {
|
||||
if (eventName in this.eventListeners) {
|
||||
// eslint-disable-next-line security/detect-object-injection
|
||||
this.eventListeners[eventName] = this.eventListeners[eventName].filter(
|
||||
(l) => l !== listener
|
||||
)
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes all listeners, or those of the specified eventName.
|
||||
*
|
||||
* Returns a reference to the `EventEmitter`, so that calls can be chained.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Command } from '@tauri-apps/plugin-shell';
|
||||
* const command = Command.create('node');
|
||||
* command.on('error', (error) => console.error(error));
|
||||
* command.removeAllListeners('error');
|
||||
* ```
|
||||
*
|
||||
* @param event The name of the event to remove the listeners of.
|
||||
* When omitted, the listeners of every event are removed.
|
||||
*
|
||||
* @returns A reference to the `EventEmitter`, so that calls can be chained.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
removeAllListeners<N extends keyof E>(event?: N): this {
|
||||
if (event) {
|
||||
// eslint-disable-next-line security/detect-object-injection
|
||||
delete this.eventListeners[event]
|
||||
} else {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
this.eventListeners = Object.create(null)
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronously calls each of the listeners registered for the event named
|
||||
* `eventName`, in the order they were registered, passing the supplied arguments
|
||||
* to each.
|
||||
*
|
||||
* @ignore
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { EventEmitter } from '@tauri-apps/plugin-shell';
|
||||
* const emitter = new EventEmitter<{ data: string }>();
|
||||
* emitter.on('data', (line) => console.log(line));
|
||||
* emitter.emit('data', 'hello');
|
||||
* ```
|
||||
*
|
||||
* @param eventName The name of the event to emit.
|
||||
* @param arg The payload passed to every registered listener.
|
||||
*
|
||||
* @returns `true` if the event had listeners, `false` otherwise.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
emit<N extends keyof E>(eventName: N, arg: E[typeof eventName]): boolean {
|
||||
if (eventName in this.eventListeners) {
|
||||
// eslint-disable-next-line security/detect-object-injection
|
||||
const listeners = this.eventListeners[eventName]
|
||||
for (const listener of listeners) listener(arg)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of listeners listening to the event named `eventName`.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Command } from '@tauri-apps/plugin-shell';
|
||||
* const command = Command.create('node');
|
||||
* command.on('close', () => {});
|
||||
* console.log(command.listenerCount('close')); // 1
|
||||
* ```
|
||||
*
|
||||
* @param eventName The name of the event to count the listeners of.
|
||||
*
|
||||
* @returns The number of listeners registered for the given event.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
listenerCount<N extends keyof E>(eventName: N): number {
|
||||
if (eventName in this.eventListeners)
|
||||
// eslint-disable-next-line security/detect-object-injection
|
||||
return this.eventListeners[eventName].length
|
||||
return 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the `listener` function to the _beginning_ of the listeners array for the
|
||||
* event named `eventName`. No checks are made to see if the `listener` has
|
||||
* already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple
|
||||
* times.
|
||||
*
|
||||
* Returns a reference to the `EventEmitter`, so that calls can be chained.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Command } from '@tauri-apps/plugin-shell';
|
||||
* const command = Command.create('node');
|
||||
* command.prependListener('error', (error) => console.error(error));
|
||||
* ```
|
||||
*
|
||||
* @param eventName The name of the event to listen to.
|
||||
* @param listener The callback invoked with the event payload.
|
||||
*
|
||||
* @returns A reference to the `EventEmitter`, so that calls can be chained.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
prependListener<N extends keyof E>(
|
||||
eventName: N,
|
||||
listener: (arg: E[typeof eventName]) => void
|
||||
): this {
|
||||
if (eventName in this.eventListeners) {
|
||||
// eslint-disable-next-line security/detect-object-injection
|
||||
this.eventListeners[eventName].unshift(listener)
|
||||
} else {
|
||||
// eslint-disable-next-line security/detect-object-injection
|
||||
this.eventListeners[eventName] = [listener]
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a **one-time**`listener` function for the event named `eventName` to the_beginning_ of the listeners array. The next time `eventName` is triggered, this
|
||||
* listener is removed, and then invoked.
|
||||
*
|
||||
* Returns a reference to the `EventEmitter`, so that calls can be chained.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Command } from '@tauri-apps/plugin-shell';
|
||||
* const command = Command.create('node');
|
||||
* command.prependOnceListener('error', (error) => console.error(error));
|
||||
* ```
|
||||
*
|
||||
* @param eventName The name of the event to listen to once.
|
||||
* @param listener The callback invoked with the event payload.
|
||||
*
|
||||
* @returns A reference to the `EventEmitter`, so that calls can be chained.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
prependOnceListener<N extends keyof E>(
|
||||
eventName: N,
|
||||
listener: (arg: E[typeof eventName]) => void
|
||||
): this {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const wrapper = (arg: any): void => {
|
||||
this.removeListener(eventName, wrapper)
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
||||
listener(arg)
|
||||
}
|
||||
return this.prependListener(eventName, wrapper)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A handle to a child process spawned with {@link Command.spawn},
|
||||
* which can be used to write to its `stdin` or to kill it.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
class Child {
|
||||
/** The child process `pid`. */
|
||||
pid: number
|
||||
|
||||
/**
|
||||
* Creates a handle to the child process with the given process id.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Command } from '@tauri-apps/plugin-shell';
|
||||
* // a `Child` is usually obtained by spawning a command:
|
||||
* const child = await Command.create('node').spawn();
|
||||
* console.log(child.pid);
|
||||
* ```
|
||||
*
|
||||
* @param pid The process id of the child process.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
constructor(pid: number) {
|
||||
this.pid = pid
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes `data` to the `stdin`.
|
||||
*
|
||||
* @param data The message to write, either a string or a byte array.
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Command } from '@tauri-apps/plugin-shell';
|
||||
* const command = Command.create('node');
|
||||
* const child = await command.spawn();
|
||||
* await child.write('message');
|
||||
* await child.write([0, 1, 2, 3, 4, 5]);
|
||||
* ```
|
||||
*
|
||||
* @returns A promise indicating the success or failure of the operation.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
async write(data: IOPayload | number[]): Promise<void> {
|
||||
await invoke('plugin:shell|stdin_write', {
|
||||
pid: this.pid,
|
||||
buffer: data
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Kills the child process.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Command } from '@tauri-apps/plugin-shell';
|
||||
* const command = Command.create('node');
|
||||
* const child = await command.spawn();
|
||||
* await child.kill();
|
||||
* ```
|
||||
*
|
||||
* @returns A promise indicating the success or failure of the operation.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
async kill(): Promise<void> {
|
||||
await invoke('plugin:shell|kill', {
|
||||
cmd: 'killChild',
|
||||
pid: this.pid
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The events emitted by a {@link Command} instance.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
interface CommandEvents {
|
||||
/** Emitted when the child process terminated, carrying its exit code and signal. */
|
||||
close: TerminatedPayload
|
||||
/** Emitted when the child process could not be spawned or failed unexpectedly, carrying the error message. */
|
||||
error: string
|
||||
}
|
||||
|
||||
/**
|
||||
* The events emitted by the `stdout` and `stderr` streams of a {@link Command}.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
interface OutputEvents<O extends IOPayload> {
|
||||
/** Emitted for each line the process wrote to the stream, or for each raw chunk when the `raw` encoding is used. */
|
||||
data: O
|
||||
}
|
||||
|
||||
/**
|
||||
* The entry point for spawning child processes.
|
||||
* It emits the `close` and `error` events.
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Command } from '@tauri-apps/plugin-shell';
|
||||
* const command = Command.create('node');
|
||||
* command.on('close', data => {
|
||||
* console.log(`command finished with code ${data.code} and signal ${data.signal}`)
|
||||
* });
|
||||
* command.on('error', error => console.error(`command error: "${error}"`));
|
||||
* command.stdout.on('data', line => console.log(`command stdout: "${line}"`));
|
||||
* command.stderr.on('data', line => console.log(`command stderr: "${line}"`));
|
||||
*
|
||||
* const child = await command.spawn();
|
||||
* console.log('pid:', child.pid);
|
||||
* ```
|
||||
*
|
||||
* @since 2.0.0
|
||||
*
|
||||
*/
|
||||
class Command<O extends IOPayload> extends EventEmitter<CommandEvents> {
|
||||
/** @ignore Program to execute. */
|
||||
private readonly program: string
|
||||
/** @ignore Program arguments */
|
||||
private readonly args: string[]
|
||||
/** @ignore Spawn options. */
|
||||
private readonly options: InternalSpawnOptions
|
||||
/** Event emitter for the `stdout`. Emits the `data` event. */
|
||||
readonly stdout = new EventEmitter<OutputEvents<O>>()
|
||||
/** Event emitter for the `stderr`. Emits the `data` event. */
|
||||
readonly stderr = new EventEmitter<OutputEvents<O>>()
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
* Creates a new `Command` instance.
|
||||
*
|
||||
* @param program The program name to execute.
|
||||
* It must be configured in your project's capabilities.
|
||||
* @param args Program arguments.
|
||||
* @param options Spawn options.
|
||||
*/
|
||||
private constructor(
|
||||
program: string,
|
||||
args: string | string[] = [],
|
||||
options?: SpawnOptions
|
||||
) {
|
||||
super()
|
||||
this.program = program
|
||||
this.args = typeof args === 'string' ? [args] : args
|
||||
this.options = options ?? {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a command to execute the given program, decoding its output as text.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Command } from '@tauri-apps/plugin-shell';
|
||||
* const command = Command.create('my-app', ['run', 'tauri']);
|
||||
* const output = await command.execute();
|
||||
* ```
|
||||
*
|
||||
* @param program The program to execute.
|
||||
* It must be configured in your project's capabilities.
|
||||
* @param args The arguments to pass to the program. Defaults to no arguments.
|
||||
*
|
||||
* @returns The command instance, ready to be spawned or executed.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
static create(program: string, args?: string | string[]): Command<string>
|
||||
/**
|
||||
* Creates a command to execute the given program, keeping its output as raw bytes.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Command } from '@tauri-apps/plugin-shell';
|
||||
* const command = Command.create('my-app', ['run', 'tauri'], { encoding: 'raw' });
|
||||
* const output = await command.execute();
|
||||
* console.log(output.stdout); // a Uint8Array
|
||||
* ```
|
||||
*
|
||||
* @param program The program to execute.
|
||||
* It must be configured in your project's capabilities.
|
||||
* @param args The arguments to pass to the program. Defaults to no arguments.
|
||||
* @param options Spawn options using the `raw` encoding, which makes the process
|
||||
* output be delivered as `Uint8Array` instead of `string`.
|
||||
*
|
||||
* @returns The command instance, ready to be spawned or executed.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
static create(
|
||||
program: string,
|
||||
args?: string | string[],
|
||||
options?: SpawnOptions & { encoding: 'raw' }
|
||||
): Command<Uint8Array>
|
||||
/**
|
||||
* Creates a command to execute the given program with the given spawn options.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Command } from '@tauri-apps/plugin-shell';
|
||||
* const command = Command.create('my-app', ['run', 'tauri'], { cwd: '/path/to/project' });
|
||||
* const output = await command.execute();
|
||||
* ```
|
||||
*
|
||||
* @param program The program to execute.
|
||||
* It must be configured in your project's capabilities.
|
||||
* @param args The arguments to pass to the program. Defaults to no arguments.
|
||||
* @param options Spawn options such as the working directory, the environment
|
||||
* variables and the character encoding of the process output.
|
||||
*
|
||||
* @returns The command instance, ready to be spawned or executed.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
static create(
|
||||
program: string,
|
||||
args?: string | string[],
|
||||
options?: SpawnOptions
|
||||
): Command<string>
|
||||
|
||||
/**
|
||||
* Creates a command to execute the given program.
|
||||
*
|
||||
* @param program The program to execute.
|
||||
* It must be configured in your project's capabilities.
|
||||
* @param args The arguments to pass to the program. Defaults to no arguments.
|
||||
* @param options Spawn options such as the working directory, the environment
|
||||
* variables and the character encoding of the process output.
|
||||
*
|
||||
* @returns The command instance, ready to be spawned or executed.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
static create<O extends IOPayload>(
|
||||
program: string,
|
||||
args: string | string[] = [],
|
||||
options?: SpawnOptions
|
||||
): Command<O> {
|
||||
return new Command(program, args, options)
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a command to execute the given sidecar program, decoding its output as text.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Command } from '@tauri-apps/plugin-shell';
|
||||
* const command = Command.sidecar('my-sidecar');
|
||||
* const output = await command.execute();
|
||||
* ```
|
||||
*
|
||||
* @param program The sidecar program to execute.
|
||||
* It must be configured in your project's capabilities
|
||||
* and defined on `tauri.conf.json > bundle > externalBin`.
|
||||
* @param args The arguments to pass to the program. Defaults to no arguments.
|
||||
*
|
||||
* @returns The command instance, ready to be spawned or executed.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
static sidecar(program: string, args?: string | string[]): Command<string>
|
||||
/**
|
||||
* Creates a command to execute the given sidecar program, keeping its output as raw bytes.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Command } from '@tauri-apps/plugin-shell';
|
||||
* const command = Command.sidecar('my-sidecar', [], { encoding: 'raw' });
|
||||
* const output = await command.execute();
|
||||
* console.log(output.stdout); // a Uint8Array
|
||||
* ```
|
||||
*
|
||||
* @param program The sidecar program to execute.
|
||||
* It must be configured in your project's capabilities
|
||||
* and defined on `tauri.conf.json > bundle > externalBin`.
|
||||
* @param args The arguments to pass to the program. Defaults to no arguments.
|
||||
* @param options Spawn options using the `raw` encoding, which makes the process
|
||||
* output be delivered as `Uint8Array` instead of `string`.
|
||||
*
|
||||
* @returns The command instance, ready to be spawned or executed.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
static sidecar(
|
||||
program: string,
|
||||
args?: string | string[],
|
||||
options?: SpawnOptions & { encoding: 'raw' }
|
||||
): Command<Uint8Array>
|
||||
/**
|
||||
* Creates a command to execute the given sidecar program with the given spawn options.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Command } from '@tauri-apps/plugin-shell';
|
||||
* const command = Command.sidecar('my-sidecar', [], { cwd: '/path/to/project' });
|
||||
* const output = await command.execute();
|
||||
* ```
|
||||
*
|
||||
* @param program The sidecar program to execute.
|
||||
* It must be configured in your project's capabilities
|
||||
* and defined on `tauri.conf.json > bundle > externalBin`.
|
||||
* @param args The arguments to pass to the program. Defaults to no arguments.
|
||||
* @param options Spawn options such as the working directory, the environment
|
||||
* variables and the character encoding of the process output.
|
||||
*
|
||||
* @returns The command instance, ready to be spawned or executed.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
static sidecar(
|
||||
program: string,
|
||||
args?: string | string[],
|
||||
options?: SpawnOptions
|
||||
): Command<string>
|
||||
|
||||
/**
|
||||
* Creates a command to execute the given sidecar program.
|
||||
*
|
||||
* @param program The sidecar program to execute.
|
||||
* It must be configured in your project's capabilities
|
||||
* and defined on `tauri.conf.json > bundle > externalBin`.
|
||||
* @param args The arguments to pass to the program. Defaults to no arguments.
|
||||
* @param options Spawn options such as the working directory, the environment
|
||||
* variables and the character encoding of the process output.
|
||||
*
|
||||
* @returns The command instance, ready to be spawned or executed.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
static sidecar<O extends IOPayload>(
|
||||
program: string,
|
||||
args: string | string[] = [],
|
||||
options?: SpawnOptions
|
||||
): Command<O> {
|
||||
const instance = new Command<O>(program, args, options)
|
||||
instance.options.sidecar = true
|
||||
return instance
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the command as a child process, returning a handle to it.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Command } from '@tauri-apps/plugin-shell';
|
||||
* const command = Command.create('node');
|
||||
* command.stdout.on('data', (line) => console.log(line));
|
||||
* const child = await command.spawn();
|
||||
* console.log('pid:', child.pid);
|
||||
* ```
|
||||
*
|
||||
* @returns A promise resolving to the child process handle.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
async spawn(): Promise<Child> {
|
||||
const program = this.program
|
||||
const args = this.args
|
||||
const options = this.options
|
||||
|
||||
if (typeof args === 'object') {
|
||||
Object.freeze(args)
|
||||
}
|
||||
|
||||
const onEvent = new Channel<CommandEvent<O>>()
|
||||
onEvent.onmessage = (event) => {
|
||||
switch (event.event) {
|
||||
case 'Error':
|
||||
this.emit('error', event.payload)
|
||||
break
|
||||
case 'Terminated':
|
||||
this.emit('close', event.payload)
|
||||
break
|
||||
case 'Stdout':
|
||||
this.stdout.emit('data', event.payload)
|
||||
break
|
||||
case 'Stderr':
|
||||
this.stderr.emit('data', event.payload)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return await invoke<number>('plugin:shell|spawn', {
|
||||
program,
|
||||
args,
|
||||
options,
|
||||
onEvent
|
||||
}).then((pid) => new Child(pid))
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the command as a child process, waiting for it to finish and collecting all of its output.
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Command } from '@tauri-apps/plugin-shell';
|
||||
* const output = await Command.create('echo', 'message').execute();
|
||||
* assert(output.code === 0);
|
||||
* assert(output.signal === null);
|
||||
* assert(output.stdout === 'message');
|
||||
* assert(output.stderr === '');
|
||||
* ```
|
||||
*
|
||||
* @returns A promise resolving to the child process output.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
async execute(): Promise<ChildProcess<O>> {
|
||||
const program = this.program
|
||||
const args = this.args
|
||||
const options = this.options
|
||||
|
||||
if (typeof args === 'object') {
|
||||
Object.freeze(args)
|
||||
}
|
||||
|
||||
return await invoke<ChildProcess<O>>('plugin:shell|execute', {
|
||||
program,
|
||||
args,
|
||||
options
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Describes the event message received from the command.
|
||||
*/
|
||||
interface Event<T, V> {
|
||||
event: T
|
||||
payload: V
|
||||
}
|
||||
|
||||
/**
|
||||
* Payload for the `Terminated` command event.
|
||||
*/
|
||||
interface TerminatedPayload {
|
||||
/** Exit code of the process. `null` if the process was terminated by a signal on Unix. */
|
||||
code: number | null
|
||||
/** If the process was terminated by a signal, represents that signal. */
|
||||
signal: number | null
|
||||
}
|
||||
|
||||
/**
|
||||
* The type of the data a child process writes to `stdout` and `stderr`:
|
||||
* a `string`, or a `Uint8Array` when the `raw` encoding is configured.
|
||||
*/
|
||||
type IOPayload = string | Uint8Array
|
||||
|
||||
/** Events emitted by the child process. */
|
||||
type CommandEvent<O extends IOPayload> =
|
||||
| Event<'Stdout', O>
|
||||
| Event<'Stderr', O>
|
||||
| Event<'Terminated', TerminatedPayload>
|
||||
| Event<'Error', string>
|
||||
|
||||
/**
|
||||
* Opens a path or URL with the system's default app,
|
||||
* or the one specified with `openWith`.
|
||||
*
|
||||
* The `openWith` value must be one of `firefox`, `google chrome`, `chromium` `safari`,
|
||||
* `open`, `start`, `xdg-open`, `gio`, `gnome-open`, `kde-open` or `wslview`.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { open } from '@tauri-apps/plugin-shell';
|
||||
* // opens the given URL on the default browser:
|
||||
* await open('https://github.com/tauri-apps/tauri');
|
||||
* // opens the given URL using `firefox`:
|
||||
* await open('https://github.com/tauri-apps/tauri', 'firefox');
|
||||
* // opens a file using the default program:
|
||||
* await open('/path/to/file');
|
||||
* ```
|
||||
*
|
||||
* @param path The path or URL to open.
|
||||
* This value is matched against the string regex defined on `tauri.conf.json > plugins > shell > open`,
|
||||
* which defaults to `^((mailto:\w+)|(tel:\w+)|(https?://\w+)).+`.
|
||||
* @param openWith The app to open the file or URL with.
|
||||
* Defaults to the system default application for the specified path type.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
async function open(path: string, openWith?: string): Promise<void> {
|
||||
await invoke('plugin:shell|open', {
|
||||
path,
|
||||
with: openWith
|
||||
})
|
||||
}
|
||||
|
||||
export { Command, Child, EventEmitter, open }
|
||||
export type {
|
||||
IOPayload,
|
||||
CommandEvents,
|
||||
TerminatedPayload,
|
||||
OutputEvents,
|
||||
ChildProcess,
|
||||
SpawnOptions
|
||||
}
|
||||
51
plugins/shell/guest-js/init.ts
Normal file
51
plugins/shell/guest-js/init.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/**
|
||||
* Webview script injected by the shell plugin on every page load.
|
||||
*
|
||||
* It installs a `click` listener on `document.body` that intercepts clicks on
|
||||
* `<a target="_blank">` elements whose `href` starts with `http://`, `https://`,
|
||||
* `mailto:` or `tel:`, cancels the navigation and opens the link with the
|
||||
* system's default application through the `plugin:shell|open` command instead.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { invoke } from '@tauri-apps/api/core'
|
||||
|
||||
// open <a href="..."> links with the API
|
||||
function openLinks(): void {
|
||||
document.querySelector('body')?.addEventListener('click', function (e) {
|
||||
let target: HTMLElement | null = e.target as HTMLElement
|
||||
while (target) {
|
||||
if (target.matches('a')) {
|
||||
const t = target
|
||||
if (
|
||||
t.href !== ''
|
||||
&& ['http://', 'https://', 'mailto:', 'tel:'].some((v) =>
|
||||
t.href.startsWith(v)
|
||||
)
|
||||
&& t.target === '_blank'
|
||||
) {
|
||||
void invoke('plugin:shell|open', {
|
||||
path: t.href
|
||||
})
|
||||
e.preventDefault()
|
||||
}
|
||||
break
|
||||
}
|
||||
target = target.parentElement
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (
|
||||
document.readyState === 'complete'
|
||||
|| document.readyState === 'interactive'
|
||||
) {
|
||||
openLinks()
|
||||
} else {
|
||||
window.addEventListener('DOMContentLoaded', openLinks, true)
|
||||
}
|
||||
16
plugins/shell/ios/Package.resolved
Normal file
16
plugins/shell/ios/Package.resolved
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"object": {
|
||||
"pins": [
|
||||
{
|
||||
"package": "SwiftRs",
|
||||
"repositoryURL": "https://github.com/Brendonovich/swift-rs",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "b5ed223fcdab165bc21219c1925dc1e77e2bef5e",
|
||||
"version": "1.0.6"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": 1
|
||||
}
|
||||
34
plugins/shell/ios/Package.swift
Normal file
34
plugins/shell/ios/Package.swift
Normal file
@@ -0,0 +1,34 @@
|
||||
// swift-tools-version:5.3
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "tauri-plugin-shell",
|
||||
platforms: [
|
||||
.macOS(.v10_13),
|
||||
.iOS(.v13),
|
||||
],
|
||||
products: [
|
||||
// Products define the executables and libraries a package produces, and make them visible to other packages.
|
||||
.library(
|
||||
name: "tauri-plugin-shell",
|
||||
type: .static,
|
||||
targets: ["tauri-plugin-shell"])
|
||||
],
|
||||
dependencies: [
|
||||
.package(name: "Tauri", path: "../.tauri/tauri-api")
|
||||
],
|
||||
targets: [
|
||||
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
|
||||
// Targets can depend on other targets in this package, and on products in packages this package depends on.
|
||||
.target(
|
||||
name: "tauri-plugin-shell",
|
||||
dependencies: [
|
||||
.byName(name: "Tauri")
|
||||
],
|
||||
path: "Sources")
|
||||
]
|
||||
)
|
||||
34
plugins/shell/ios/Sources/ShellPlugin.swift
Normal file
34
plugins/shell/ios/Sources/ShellPlugin.swift
Normal file
@@ -0,0 +1,34 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
import SwiftRs
|
||||
import Tauri
|
||||
import UIKit
|
||||
import WebKit
|
||||
|
||||
class ShellPlugin: Plugin {
|
||||
|
||||
@objc public func open(_ invoke: Invoke) throws {
|
||||
do {
|
||||
let urlString = try invoke.parseArgs(String.self)
|
||||
if let url = URL(string: urlString) {
|
||||
if #available(iOS 10, *) {
|
||||
UIApplication.shared.open(url, options: [:])
|
||||
} else {
|
||||
UIApplication.shared.openURL(url)
|
||||
}
|
||||
}
|
||||
invoke.resolve()
|
||||
} catch {
|
||||
invoke.reject(error.localizedDescription)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@_cdecl("init_plugin_shell")
|
||||
func initPlugin() -> Plugin {
|
||||
return ShellPlugin()
|
||||
}
|
||||
29
plugins/shell/package.json
Normal file
29
plugins/shell/package.json
Normal file
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "@tauri-apps/plugin-shell",
|
||||
"version": "2.3.6",
|
||||
"license": "MIT OR Apache-2.0",
|
||||
"authors": [
|
||||
"Tauri Programme within The Commons Conservancy"
|
||||
],
|
||||
"repository": "https://github.com/tauri-apps/plugins-workspace",
|
||||
"type": "module",
|
||||
"types": "./dist-js/index.d.ts",
|
||||
"main": "./dist-js/index.cjs",
|
||||
"module": "./dist-js/index.js",
|
||||
"exports": {
|
||||
"types": "./dist-js/index.d.ts",
|
||||
"import": "./dist-js/index.js",
|
||||
"require": "./dist-js/index.cjs"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "rollup -c"
|
||||
},
|
||||
"files": [
|
||||
"dist-js",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^2.11.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-execute"
|
||||
description = "Enables the execute command without any pre-configured scope."
|
||||
commands.allow = ["execute"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-execute"
|
||||
description = "Denies the execute command without any pre-configured scope."
|
||||
commands.deny = ["execute"]
|
||||
13
plugins/shell/permissions/autogenerated/commands/kill.toml
Normal file
13
plugins/shell/permissions/autogenerated/commands/kill.toml
Normal file
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-kill"
|
||||
description = "Enables the kill command without any pre-configured scope."
|
||||
commands.allow = ["kill"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-kill"
|
||||
description = "Denies the kill command without any pre-configured scope."
|
||||
commands.deny = ["kill"]
|
||||
13
plugins/shell/permissions/autogenerated/commands/open.toml
Normal file
13
plugins/shell/permissions/autogenerated/commands/open.toml
Normal file
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-open"
|
||||
description = "Enables the open command without any pre-configured scope."
|
||||
commands.allow = ["open"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-open"
|
||||
description = "Denies the open command without any pre-configured scope."
|
||||
commands.deny = ["open"]
|
||||
13
plugins/shell/permissions/autogenerated/commands/spawn.toml
Normal file
13
plugins/shell/permissions/autogenerated/commands/spawn.toml
Normal file
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-spawn"
|
||||
description = "Enables the spawn command without any pre-configured scope."
|
||||
commands.allow = ["spawn"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-spawn"
|
||||
description = "Denies the spawn command without any pre-configured scope."
|
||||
commands.deny = ["spawn"]
|
||||
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-stdin-write"
|
||||
description = "Enables the stdin_write command without any pre-configured scope."
|
||||
commands.allow = ["stdin_write"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-stdin-write"
|
||||
description = "Denies the stdin_write command without any pre-configured scope."
|
||||
commands.deny = ["stdin_write"]
|
||||
154
plugins/shell/permissions/autogenerated/reference.md
Normal file
154
plugins/shell/permissions/autogenerated/reference.md
Normal file
@@ -0,0 +1,154 @@
|
||||
## Default Permission
|
||||
|
||||
This permission set configures which
|
||||
shell functionality is exposed by default.
|
||||
|
||||
#### Granted Permissions
|
||||
|
||||
It allows to use the `open` functionality with a reasonable
|
||||
scope pre-configured. It will allow opening `http(s)://`,
|
||||
`tel:` and `mailto:` links.
|
||||
|
||||
#### This default permission set includes the following:
|
||||
|
||||
- `allow-open`
|
||||
|
||||
## Permission Table
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Identifier</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`shell:allow-execute`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the execute command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`shell:deny-execute`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the execute command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`shell:allow-kill`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the kill command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`shell:deny-kill`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the kill command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`shell:allow-open`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the open command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`shell:deny-open`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the open command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`shell:allow-spawn`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the spawn command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`shell:deny-spawn`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the spawn command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`shell:allow-stdin-write`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the stdin_write command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`shell:deny-stdin-write`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the stdin_write command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
15
plugins/shell/permissions/default.toml
Normal file
15
plugins/shell/permissions/default.toml
Normal file
@@ -0,0 +1,15 @@
|
||||
"$schema" = "schemas/schema.json"
|
||||
|
||||
[default]
|
||||
description = """
|
||||
This permission set configures which
|
||||
shell functionality is exposed by default.
|
||||
|
||||
#### Granted Permissions
|
||||
|
||||
It allows to use the `open` functionality with a reasonable
|
||||
scope pre-configured. It will allow opening `http(s)://`,
|
||||
`tel:` and `mailto:` links.
|
||||
"""
|
||||
|
||||
permissions = ["allow-open"]
|
||||
366
plugins/shell/permissions/schemas/schema.json
Normal file
366
plugins/shell/permissions/schemas/schema.json
Normal file
@@ -0,0 +1,366 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "PermissionFile",
|
||||
"description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"default": {
|
||||
"description": "The default permission set for the plugin",
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/definitions/DefaultPermission"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"set": {
|
||||
"description": "A list of permissions sets defined",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/PermissionSet"
|
||||
}
|
||||
},
|
||||
"permission": {
|
||||
"description": "A list of inlined permissions",
|
||||
"default": [],
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Permission"
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"DefaultPermission": {
|
||||
"description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"permissions"
|
||||
],
|
||||
"properties": {
|
||||
"version": {
|
||||
"description": "The version of the permission.",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint64",
|
||||
"minimum": 1.0
|
||||
},
|
||||
"description": {
|
||||
"description": "Human-readable description of what the permission does. Tauri convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"permissions": {
|
||||
"description": "All permissions this set contains.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"PermissionSet": {
|
||||
"description": "A set of direct permissions grouped together under a new name.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"description",
|
||||
"identifier",
|
||||
"permissions"
|
||||
],
|
||||
"properties": {
|
||||
"identifier": {
|
||||
"description": "A unique identifier for the permission.",
|
||||
"type": "string"
|
||||
},
|
||||
"description": {
|
||||
"description": "Human-readable description of what the permission does.",
|
||||
"type": "string"
|
||||
},
|
||||
"permissions": {
|
||||
"description": "All permissions this set contains.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/PermissionKind"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Permission": {
|
||||
"description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"identifier"
|
||||
],
|
||||
"properties": {
|
||||
"version": {
|
||||
"description": "The version of the permission.",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint64",
|
||||
"minimum": 1.0
|
||||
},
|
||||
"identifier": {
|
||||
"description": "A unique identifier for the permission.",
|
||||
"type": "string"
|
||||
},
|
||||
"description": {
|
||||
"description": "Human-readable description of what the permission does. Tauri internal convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"commands": {
|
||||
"description": "Allowed or denied commands when using this permission.",
|
||||
"default": {
|
||||
"allow": [],
|
||||
"deny": []
|
||||
},
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Commands"
|
||||
}
|
||||
]
|
||||
},
|
||||
"scope": {
|
||||
"description": "Allowed or denied scoped when using this permission.",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Scopes"
|
||||
}
|
||||
]
|
||||
},
|
||||
"platforms": {
|
||||
"description": "Target platforms this permission applies. By default all platforms are affected by this permission.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
],
|
||||
"items": {
|
||||
"$ref": "#/definitions/Target"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Commands": {
|
||||
"description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"allow": {
|
||||
"description": "Allowed command.",
|
||||
"default": [],
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"deny": {
|
||||
"description": "Denied command, which takes priority.",
|
||||
"default": [],
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Scopes": {
|
||||
"description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"allow": {
|
||||
"description": "Data that defines what is allowed by the scope.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
],
|
||||
"items": {
|
||||
"$ref": "#/definitions/Value"
|
||||
}
|
||||
},
|
||||
"deny": {
|
||||
"description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
],
|
||||
"items": {
|
||||
"$ref": "#/definitions/Value"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Value": {
|
||||
"description": "All supported ACL values.",
|
||||
"anyOf": [
|
||||
{
|
||||
"description": "Represents a null JSON value.",
|
||||
"type": "null"
|
||||
},
|
||||
{
|
||||
"description": "Represents a [`bool`].",
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"description": "Represents a valid ACL [`Number`].",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Number"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Represents a [`String`].",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"description": "Represents a list of other [`Value`]s.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Value"
|
||||
}
|
||||
},
|
||||
{
|
||||
"description": "Represents a map of [`String`] keys to [`Value`]s.",
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"$ref": "#/definitions/Value"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"Number": {
|
||||
"description": "A valid ACL number.",
|
||||
"anyOf": [
|
||||
{
|
||||
"description": "Represents an [`i64`].",
|
||||
"type": "integer",
|
||||
"format": "int64"
|
||||
},
|
||||
{
|
||||
"description": "Represents a [`f64`].",
|
||||
"type": "number",
|
||||
"format": "double"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Target": {
|
||||
"description": "Platform target.",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "MacOS.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"macOS"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Windows.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"windows"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Linux.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"linux"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Android.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"android"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "iOS.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"iOS"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"PermissionKind": {
|
||||
"type": "string",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "Enables the execute command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-execute",
|
||||
"markdownDescription": "Enables the execute command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the execute command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-execute",
|
||||
"markdownDescription": "Denies the execute command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the kill command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-kill",
|
||||
"markdownDescription": "Enables the kill command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the kill command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-kill",
|
||||
"markdownDescription": "Denies the kill command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the open command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-open",
|
||||
"markdownDescription": "Enables the open command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the open command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-open",
|
||||
"markdownDescription": "Denies the open command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the spawn command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-spawn",
|
||||
"markdownDescription": "Enables the spawn command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the spawn command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-spawn",
|
||||
"markdownDescription": "Denies the spawn command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the stdin_write command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-stdin-write",
|
||||
"markdownDescription": "Enables the stdin_write command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the stdin_write command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-stdin-write",
|
||||
"markdownDescription": "Denies the stdin_write command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "This permission set configures which\nshell functionality is exposed by default.\n\n#### Granted Permissions\n\nIt allows to use the `open` functionality with a reasonable\nscope pre-configured. It will allow opening `http(s)://`,\n`tel:` and `mailto:` links.\n\n#### This default permission set includes:\n\n- `allow-open`",
|
||||
"type": "string",
|
||||
"const": "default",
|
||||
"markdownDescription": "This permission set configures which\nshell functionality is exposed by default.\n\n#### Granted Permissions\n\nIt allows to use the `open` functionality with a reasonable\nscope pre-configured. It will allow opening `http(s)://`,\n`tel:` and `mailto:` links.\n\n#### This default permission set includes:\n\n- `allow-open`"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
22
plugins/shell/rollup.config.js
Normal file
22
plugins/shell/rollup.config.js
Normal file
@@ -0,0 +1,22 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import { createConfig } from '../../shared/rollup.config.js'
|
||||
import { nodeResolve } from '@rollup/plugin-node-resolve'
|
||||
import typescript from '@rollup/plugin-typescript'
|
||||
import terser from '@rollup/plugin-terser'
|
||||
|
||||
export default createConfig({
|
||||
additionalConfigs: {
|
||||
input: 'guest-js/init.ts',
|
||||
output: {
|
||||
file: 'src/init-iife.js',
|
||||
format: 'iife'
|
||||
},
|
||||
plugins: [typescript(), terser(), nodeResolve()],
|
||||
onwarn: (warning) => {
|
||||
throw Object.assign(new Error(), warning)
|
||||
}
|
||||
}
|
||||
})
|
||||
320
plugins/shell/src/commands.rs
Normal file
320
plugins/shell/src/commands.rs
Normal file
@@ -0,0 +1,320 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::{collections::HashMap, future::Future, path::PathBuf, pin::Pin, string::FromUtf8Error};
|
||||
|
||||
use encoding_rs::Encoding;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tauri::{
|
||||
ipc::{Channel, CommandScope, GlobalScope},
|
||||
Manager, Runtime, State, Window,
|
||||
};
|
||||
|
||||
#[allow(deprecated)]
|
||||
use crate::open::Program;
|
||||
use crate::{
|
||||
process::{CommandEvent, TerminatedPayload},
|
||||
scope::ExecuteArgs,
|
||||
Shell,
|
||||
};
|
||||
|
||||
type ChildId = u32;
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(tag = "event", content = "payload")]
|
||||
#[non_exhaustive]
|
||||
pub enum JSCommandEvent {
|
||||
/// Stderr bytes until a newline (\n) or carriage return (\r) is found.
|
||||
Stderr(Buffer),
|
||||
/// Stdout bytes until a newline (\n) or carriage return (\r) is found.
|
||||
Stdout(Buffer),
|
||||
/// An error happened waiting for the command to finish or converting the stdout/stderr bytes to an UTF-8 string.
|
||||
Error(String),
|
||||
/// Command process terminated.
|
||||
Terminated(TerminatedPayload),
|
||||
}
|
||||
|
||||
fn get_event_buffer(line: Vec<u8>, encoding: EncodingWrapper) -> Result<Buffer, FromUtf8Error> {
|
||||
match encoding {
|
||||
EncodingWrapper::Text(character_encoding) => match character_encoding {
|
||||
Some(encoding) => Ok(Buffer::Text(
|
||||
encoding.decode_with_bom_removal(&line).0.into(),
|
||||
)),
|
||||
None => String::from_utf8(line).map(Buffer::Text),
|
||||
},
|
||||
EncodingWrapper::Raw => Ok(Buffer::Raw(line)),
|
||||
}
|
||||
}
|
||||
|
||||
impl JSCommandEvent {
|
||||
pub fn new(event: CommandEvent, encoding: EncodingWrapper) -> Self {
|
||||
match event {
|
||||
CommandEvent::Terminated(payload) => JSCommandEvent::Terminated(payload),
|
||||
CommandEvent::Error(error) => JSCommandEvent::Error(error),
|
||||
CommandEvent::Stderr(line) => get_event_buffer(line, encoding)
|
||||
.map(JSCommandEvent::Stderr)
|
||||
.unwrap_or_else(|e| JSCommandEvent::Error(e.to_string())),
|
||||
CommandEvent::Stdout(line) => get_event_buffer(line, encoding)
|
||||
.map(JSCommandEvent::Stdout)
|
||||
.unwrap_or_else(|e| JSCommandEvent::Error(e.to_string())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(untagged)]
|
||||
#[allow(missing_docs)]
|
||||
pub enum Buffer {
|
||||
Text(String),
|
||||
Raw(Vec<u8>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub enum EncodingWrapper {
|
||||
Raw,
|
||||
Text(Option<&'static Encoding>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CommandOptions {
|
||||
#[serde(default)]
|
||||
sidecar: bool,
|
||||
cwd: Option<PathBuf>,
|
||||
// by default we don't add any env variables to the spawned process
|
||||
// but the env is an `Option` so when it's `None` we clear the env.
|
||||
#[serde(default = "default_env")]
|
||||
env: Option<HashMap<String, String>>,
|
||||
// Character encoding for stdout/stderr
|
||||
encoding: Option<String>,
|
||||
}
|
||||
|
||||
#[allow(clippy::unnecessary_wraps)]
|
||||
fn default_env() -> Option<HashMap<String, String>> {
|
||||
Some(HashMap::default())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn prepare_cmd<R: Runtime>(
|
||||
window: Window<R>,
|
||||
program: String,
|
||||
args: ExecuteArgs,
|
||||
options: CommandOptions,
|
||||
command_scope: CommandScope<crate::scope::ScopeAllowedCommand>,
|
||||
global_scope: GlobalScope<crate::scope::ScopeAllowedCommand>,
|
||||
) -> crate::Result<(crate::process::Command, EncodingWrapper)> {
|
||||
let scope = crate::scope::ShellScope {
|
||||
scopes: command_scope
|
||||
.allows()
|
||||
.iter()
|
||||
.chain(global_scope.allows())
|
||||
.collect(),
|
||||
};
|
||||
|
||||
let mut command = if options.sidecar {
|
||||
let program = PathBuf::from(program);
|
||||
let program_as_string = program.display().to_string();
|
||||
let has_extension = program.extension().is_some_and(|ext| ext == "exe");
|
||||
let program_no_ext_as_string = if has_extension {
|
||||
program.with_extension("").display().to_string()
|
||||
} else {
|
||||
program_as_string.clone()
|
||||
};
|
||||
let configured_sidecar = window
|
||||
.config()
|
||||
.bundle
|
||||
.external_bin
|
||||
.as_ref()
|
||||
.and_then(|bins| {
|
||||
bins.iter()
|
||||
.find(|b| b == &&program_as_string || b == &&program_no_ext_as_string)
|
||||
})
|
||||
.cloned();
|
||||
if let Some(sidecar) = configured_sidecar {
|
||||
scope.prepare_sidecar(&program.to_string_lossy(), &sidecar, args)?
|
||||
} else {
|
||||
return Err(crate::Error::SidecarNotAllowed(program));
|
||||
}
|
||||
} else {
|
||||
match scope.prepare(&program, args) {
|
||||
Ok(cmd) => cmd,
|
||||
Err(e) => {
|
||||
#[cfg(debug_assertions)]
|
||||
eprintln!("{e}");
|
||||
return Err(crate::Error::ProgramNotAllowed(PathBuf::from(program)));
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Some(cwd) = options.cwd {
|
||||
command = command.current_dir(cwd);
|
||||
}
|
||||
if let Some(env) = options.env {
|
||||
command = command.envs(env);
|
||||
} else {
|
||||
command = command.env_clear();
|
||||
}
|
||||
|
||||
let encoding = match options.encoding {
|
||||
Option::None => EncodingWrapper::Text(None),
|
||||
Some(encoding) => match encoding.as_str() {
|
||||
"raw" => {
|
||||
command = command.set_raw_out(true);
|
||||
EncodingWrapper::Raw
|
||||
}
|
||||
_ => {
|
||||
if let Some(text_encoding) = Encoding::for_label(encoding.as_bytes()) {
|
||||
EncodingWrapper::Text(Some(text_encoding))
|
||||
} else {
|
||||
return Err(crate::Error::UnknownEncoding(encoding));
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
Ok((command, encoding))
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(untagged)]
|
||||
enum Output {
|
||||
String(String),
|
||||
Raw(Vec<u8>),
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct ChildProcessReturn {
|
||||
code: Option<i32>,
|
||||
signal: Option<i32>,
|
||||
stdout: Output,
|
||||
stderr: Output,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[tauri::command]
|
||||
pub async fn execute<R: Runtime>(
|
||||
window: Window<R>,
|
||||
program: String,
|
||||
args: ExecuteArgs,
|
||||
options: CommandOptions,
|
||||
command_scope: CommandScope<crate::scope::ScopeAllowedCommand>,
|
||||
global_scope: GlobalScope<crate::scope::ScopeAllowedCommand>,
|
||||
) -> crate::Result<ChildProcessReturn> {
|
||||
let (command, encoding) =
|
||||
prepare_cmd(window, program, args, options, command_scope, global_scope)?;
|
||||
|
||||
let mut command: std::process::Command = command.into();
|
||||
let output = command.output()?;
|
||||
|
||||
let (stdout, stderr) = match encoding {
|
||||
EncodingWrapper::Text(Some(encoding)) => (
|
||||
Output::String(encoding.decode_with_bom_removal(&output.stdout).0.into()),
|
||||
Output::String(encoding.decode_with_bom_removal(&output.stderr).0.into()),
|
||||
),
|
||||
EncodingWrapper::Text(None) => (
|
||||
Output::String(String::from_utf8(output.stdout)?),
|
||||
Output::String(String::from_utf8(output.stderr)?),
|
||||
),
|
||||
EncodingWrapper::Raw => (Output::Raw(output.stdout), Output::Raw(output.stderr)),
|
||||
};
|
||||
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
|
||||
Ok(ChildProcessReturn {
|
||||
code: output.status.code(),
|
||||
#[cfg(windows)]
|
||||
signal: None,
|
||||
#[cfg(unix)]
|
||||
signal: output.status.signal(),
|
||||
stdout,
|
||||
stderr,
|
||||
})
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[tauri::command]
|
||||
pub fn spawn<R: Runtime>(
|
||||
window: Window<R>,
|
||||
shell: State<'_, Shell<R>>,
|
||||
program: String,
|
||||
args: ExecuteArgs,
|
||||
on_event: Channel<JSCommandEvent>,
|
||||
options: CommandOptions,
|
||||
command_scope: CommandScope<crate::scope::ScopeAllowedCommand>,
|
||||
global_scope: GlobalScope<crate::scope::ScopeAllowedCommand>,
|
||||
) -> crate::Result<ChildId> {
|
||||
let (command, encoding) =
|
||||
prepare_cmd(window, program, args, options, command_scope, global_scope)?;
|
||||
|
||||
let (mut rx, child) = command.spawn()?;
|
||||
|
||||
let pid = child.pid();
|
||||
shell.children.lock().unwrap().insert(pid, child);
|
||||
let children = shell.children.clone();
|
||||
|
||||
tauri::async_runtime::spawn(async move {
|
||||
while let Some(event) = rx.recv().await {
|
||||
if matches!(event, crate::process::CommandEvent::Terminated(_)) {
|
||||
children.lock().unwrap().remove(&pid);
|
||||
};
|
||||
let js_event = JSCommandEvent::new(event, encoding);
|
||||
|
||||
if on_event.send(js_event.clone()).is_err() {
|
||||
fn send<'a>(
|
||||
on_event: &'a Channel<JSCommandEvent>,
|
||||
js_event: &'a JSCommandEvent,
|
||||
) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
|
||||
Box::pin(async move {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(15)).await;
|
||||
if on_event.send(js_event.clone()).is_err() {
|
||||
send(on_event, js_event).await;
|
||||
}
|
||||
})
|
||||
}
|
||||
send(&on_event, &js_event).await;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(pid)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn stdin_write<R: Runtime>(
|
||||
_window: Window<R>,
|
||||
shell: State<'_, Shell<R>>,
|
||||
pid: ChildId,
|
||||
buffer: Buffer,
|
||||
) -> crate::Result<()> {
|
||||
if let Some(child) = shell.children.lock().unwrap().get_mut(&pid) {
|
||||
match buffer {
|
||||
Buffer::Text(t) => child.write(t.as_bytes())?,
|
||||
Buffer::Raw(r) => child.write(&r)?,
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn kill<R: Runtime>(
|
||||
_window: Window<R>,
|
||||
shell: State<'_, Shell<R>>,
|
||||
pid: ChildId,
|
||||
) -> crate::Result<()> {
|
||||
if let Some(child) = shell.children.lock().unwrap().remove(&pid) {
|
||||
child.kill()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(deprecated)]
|
||||
#[tauri::command]
|
||||
pub async fn open<R: Runtime>(
|
||||
_window: Window<R>,
|
||||
shell: State<'_, Shell<R>>,
|
||||
path: String,
|
||||
with: Option<Program>,
|
||||
) -> crate::Result<()> {
|
||||
crate::open::open(Some(&shell.open_scope), path, with)
|
||||
}
|
||||
39
plugins/shell/src/config.rs
Normal file
39
plugins/shell/src/config.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
/// Configuration for the shell plugin.
|
||||
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct Config {
|
||||
/// Open URL with the user's default application.
|
||||
#[serde(default)]
|
||||
pub open: ShellAllowlistOpen,
|
||||
}
|
||||
|
||||
/// Defines the `shell > open` api scope.
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Deserialize)]
|
||||
#[serde(untagged, deny_unknown_fields)]
|
||||
#[non_exhaustive]
|
||||
#[derive(Default)]
|
||||
pub enum ShellAllowlistOpen {
|
||||
/// Shell open API allowlist is not defined by the user.
|
||||
/// In this case we add the default validation regex (same as [`Self::Flag(true)`]).
|
||||
#[default]
|
||||
Unset,
|
||||
/// If the shell open API should be enabled.
|
||||
///
|
||||
/// If enabled, the default validation regex (`^((mailto:\w+)|(tel:\w+)|(https?://\w+)).+`) is used.
|
||||
Flag(bool),
|
||||
|
||||
/// Enable the shell open API, with a custom regex that the opened path must match against.
|
||||
///
|
||||
/// The regex string is automatically surrounded by `^...$` to match the full string.
|
||||
/// For example the `https?://\w+` regex would be registered as `^https?://\w+$`.
|
||||
///
|
||||
/// If using a custom regex to support a non-http(s) schema, care should be used to prevent values
|
||||
/// that allow flag-like strings to pass validation. e.g. `--enable-debugging`, `-i`, `/R`.
|
||||
Validate(String),
|
||||
}
|
||||
56
plugins/shell/src/error.rs
Normal file
56
plugins/shell/src/error.rs
Normal file
@@ -0,0 +1,56 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde::{Serialize, Serializer};
|
||||
|
||||
/// Errors returned by the shell plugin.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
/// Failed to invoke the mobile plugin implementation.
|
||||
///
|
||||
/// Only available on mobile.
|
||||
#[cfg(mobile)]
|
||||
#[error(transparent)]
|
||||
PluginInvoke(#[from] tauri::plugin::mobile::PluginInvokeError),
|
||||
/// I/O error, usually raised when spawning a process or reading its output.
|
||||
#[error(transparent)]
|
||||
Io(#[from] std::io::Error),
|
||||
/// The path of the current executable has no parent directory,
|
||||
/// so the path of a sidecar program could not be resolved.
|
||||
#[error("current executable path has no parent")]
|
||||
CurrentExeHasNoParent,
|
||||
/// The string does not match any of the known programs
|
||||
/// accepted by the deprecated `open` API.
|
||||
#[error("unknown program {0}")]
|
||||
UnknownProgramName(String),
|
||||
/// The command is not allowed by the configured shell scope.
|
||||
#[error(transparent)]
|
||||
Scope(#[from] crate::scope::Error),
|
||||
/// Sidecar not allowed by the configuration.
|
||||
#[error("sidecar not configured under `tauri.conf.json > bundle > externalBin`: {0}")]
|
||||
SidecarNotAllowed(PathBuf),
|
||||
/// Program not allowed by the scope.
|
||||
#[error("program not allowed on the configured shell scope: {0}")]
|
||||
ProgramNotAllowed(PathBuf),
|
||||
/// The `encoding` spawn option is neither `raw` nor a label of a known character encoding.
|
||||
#[error("unknown encoding {0}")]
|
||||
UnknownEncoding(String),
|
||||
/// JSON error.
|
||||
#[error(transparent)]
|
||||
Json(#[from] serde_json::Error),
|
||||
/// Utf8 error.
|
||||
#[error(transparent)]
|
||||
Utf8(#[from] std::string::FromUtf8Error),
|
||||
}
|
||||
|
||||
impl Serialize for Error {
|
||||
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
serializer.serialize_str(self.to_string().as_ref())
|
||||
}
|
||||
}
|
||||
1
plugins/shell/src/init-iife.js
Normal file
1
plugins/shell/src/init-iife.js
Normal file
@@ -0,0 +1 @@
|
||||
!function(){"use strict";async function e(e,t={},n){return window.__TAURI_INTERNALS__.invoke(e,t,n)}function t(){document.querySelector("body")?.addEventListener("click",function(t){let n=t.target;for(;n;){if(n.matches("a")){const r=n;""!==r.href&&["http://","https://","mailto:","tel:"].some(e=>r.href.startsWith(e))&&"_blank"===r.target&&(e("plugin:shell|open",{path:r.href}),t.preventDefault());break}n=n.parentElement}})}"function"==typeof SuppressedError&&SuppressedError,"complete"===document.readyState||"interactive"===document.readyState?t():window.addEventListener("DOMContentLoaded",t,!0)}();
|
||||
195
plugins/shell/src/lib.rs
Normal file
195
plugins/shell/src/lib.rs
Normal file
@@ -0,0 +1,195 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//! Access the system shell. Allows you to spawn child processes and manage files and URLs using their default application.
|
||||
|
||||
#![doc(
|
||||
html_logo_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png",
|
||||
html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png"
|
||||
)]
|
||||
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
ffi::OsStr,
|
||||
path::Path,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use process::{Command, CommandChild};
|
||||
use regex::Regex;
|
||||
use tauri::{
|
||||
plugin::{Builder, TauriPlugin},
|
||||
AppHandle, Manager, RunEvent, Runtime,
|
||||
};
|
||||
|
||||
mod commands;
|
||||
mod config;
|
||||
mod error;
|
||||
#[deprecated(since = "2.1.0", note = "Use tauri-plugin-opener instead.")]
|
||||
#[allow(deprecated)]
|
||||
pub mod open;
|
||||
/// Types and helpers to spawn and interact with child processes.
|
||||
pub mod process;
|
||||
mod scope;
|
||||
mod scope_entry;
|
||||
|
||||
pub use error::Error;
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
#[cfg(mobile)]
|
||||
use tauri::plugin::PluginHandle;
|
||||
#[cfg(target_os = "android")]
|
||||
const PLUGIN_IDENTIFIER: &str = "app.tauri.shell";
|
||||
#[cfg(target_os = "ios")]
|
||||
tauri::ios_plugin_binding!(init_plugin_shell);
|
||||
|
||||
type ChildStore = Arc<Mutex<HashMap<u32, CommandChild>>>;
|
||||
|
||||
/// Access to the shell APIs.
|
||||
///
|
||||
/// Get an instance of this type with [`ShellExt::shell`].
|
||||
pub struct Shell<R: Runtime> {
|
||||
#[allow(dead_code)]
|
||||
app: AppHandle<R>,
|
||||
#[cfg(mobile)]
|
||||
mobile_plugin_handle: PluginHandle<R>,
|
||||
open_scope: scope::OpenScope,
|
||||
children: ChildStore,
|
||||
}
|
||||
|
||||
impl<R: Runtime> Shell<R> {
|
||||
/// Creates a new Command for launching the given program.
|
||||
pub fn command(&self, program: impl AsRef<OsStr>) -> Command {
|
||||
Command::new(program)
|
||||
}
|
||||
|
||||
/// Creates a new Command for launching the given sidecar program.
|
||||
///
|
||||
/// A sidecar program is a embedded external binary in order to make your application work
|
||||
/// or to prevent users having to install additional dependencies (e.g. Node.js, Python, etc).
|
||||
pub fn sidecar(&self, program: impl AsRef<Path>) -> Result<Command> {
|
||||
Command::new_sidecar(program)
|
||||
}
|
||||
|
||||
/// Open a (url) path with a default or specific browser opening program.
|
||||
///
|
||||
/// See [`crate::open::open`] for how it handles security-related measures.
|
||||
#[cfg(desktop)]
|
||||
#[deprecated(since = "2.1.0", note = "Use tauri-plugin-opener instead.")]
|
||||
#[allow(deprecated)]
|
||||
pub fn open(&self, path: impl Into<String>, with: Option<open::Program>) -> Result<()> {
|
||||
open::open(None, path.into(), with)
|
||||
}
|
||||
|
||||
/// Open a (url) path with a default or specific browser opening program.
|
||||
///
|
||||
/// See [`crate::open::open`] for how it handles security-related measures.
|
||||
#[cfg(mobile)]
|
||||
#[deprecated(since = "2.1.0", note = "Use tauri-plugin-opener instead.")]
|
||||
pub fn open(&self, path: impl Into<String>, _with: Option<open::Program>) -> Result<()> {
|
||||
self.mobile_plugin_handle
|
||||
.run_mobile_plugin("open", path.into())
|
||||
.map_err(Into::into)
|
||||
}
|
||||
}
|
||||
|
||||
/// Extensions to [`tauri::App`], [`tauri::AppHandle`], [`tauri::WebviewWindow`],
|
||||
/// [`tauri::Webview`] and [`tauri::Window`] to access the shell APIs.
|
||||
pub trait ShellExt<R: Runtime> {
|
||||
/// Gets the shell APIs.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```no_run
|
||||
/// use tauri_plugin_shell::ShellExt;
|
||||
///
|
||||
/// async fn run_echo<R: tauri::Runtime>(app: &tauri::AppHandle<R>) {
|
||||
/// let output = app.shell().command("echo").args(["hello"]).output().await.unwrap();
|
||||
/// println!("{}", String::from_utf8_lossy(&output.stdout));
|
||||
/// }
|
||||
/// ```
|
||||
fn shell(&self) -> &Shell<R>;
|
||||
}
|
||||
|
||||
impl<R: Runtime, T: Manager<R>> ShellExt<R> for T {
|
||||
fn shell(&self) -> &Shell<R> {
|
||||
self.state::<Shell<R>>().inner()
|
||||
}
|
||||
}
|
||||
|
||||
/// Initializes the shell plugin.
|
||||
///
|
||||
/// The plugin state can be accessed with [`ShellExt::shell`],
|
||||
/// and all spawned child processes are killed when the application exits.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```no_run
|
||||
/// fn setup<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri::Builder<R> {
|
||||
/// builder.plugin(tauri_plugin_shell::init())
|
||||
/// }
|
||||
/// ```
|
||||
pub fn init<R: Runtime>() -> TauriPlugin<R, Option<config::Config>> {
|
||||
Builder::<R, Option<config::Config>>::new("shell")
|
||||
.js_init_script(include_str!("init-iife.js").to_string())
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
commands::execute,
|
||||
commands::spawn,
|
||||
commands::stdin_write,
|
||||
commands::kill,
|
||||
commands::open
|
||||
])
|
||||
.setup(|app, api| {
|
||||
let default_config = config::Config::default();
|
||||
let config = api.config().as_ref().unwrap_or(&default_config);
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
let handle = api.register_android_plugin(PLUGIN_IDENTIFIER, "ShellPlugin")?;
|
||||
#[cfg(target_os = "ios")]
|
||||
let handle = api.register_ios_plugin(init_plugin_shell)?;
|
||||
|
||||
app.manage(Shell {
|
||||
app: app.clone(),
|
||||
children: Default::default(),
|
||||
open_scope: open_scope(&config.open),
|
||||
|
||||
#[cfg(mobile)]
|
||||
mobile_plugin_handle: handle,
|
||||
});
|
||||
Ok(())
|
||||
})
|
||||
.on_event(|app, event| {
|
||||
if let RunEvent::Exit = event {
|
||||
let shell = app.state::<Shell<R>>();
|
||||
let children = {
|
||||
let mut lock = shell.children.lock().unwrap();
|
||||
std::mem::take(&mut *lock)
|
||||
};
|
||||
for child in children.into_values() {
|
||||
let _ = child.kill();
|
||||
}
|
||||
}
|
||||
})
|
||||
.build()
|
||||
}
|
||||
|
||||
fn open_scope(open: &config::ShellAllowlistOpen) -> scope::OpenScope {
|
||||
let shell_scope_open = match open {
|
||||
config::ShellAllowlistOpen::Flag(false) => None,
|
||||
// we want to add a basic regex validation even if the config is not set
|
||||
config::ShellAllowlistOpen::Unset | config::ShellAllowlistOpen::Flag(true) => {
|
||||
Some(Regex::new(r"^((mailto:\w+)|(tel:\w+)|(https?://\w+)).+").unwrap())
|
||||
}
|
||||
config::ShellAllowlistOpen::Validate(validator) => {
|
||||
let regex = format!("^{validator}$");
|
||||
let validator =
|
||||
Regex::new(®ex).unwrap_or_else(|e| panic!("invalid regex {regex}: {e}"));
|
||||
Some(validator)
|
||||
}
|
||||
};
|
||||
|
||||
scope::OpenScope {
|
||||
open: shell_scope_open,
|
||||
}
|
||||
}
|
||||
138
plugins/shell/src/open.rs
Normal file
138
plugins/shell/src/open.rs
Normal file
@@ -0,0 +1,138 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//! Types and functions related to shell.
|
||||
|
||||
use serde::{Deserialize, Deserializer};
|
||||
|
||||
use crate::scope::OpenScope;
|
||||
use std::str::FromStr;
|
||||
|
||||
/// Program to use on the [`open()`] call.
|
||||
#[deprecated(since = "2.1.0", note = "Use tauri-plugin-opener instead.")]
|
||||
pub enum Program {
|
||||
/// Use the `open` program.
|
||||
Open,
|
||||
/// Use the `start` program.
|
||||
Start,
|
||||
/// Use the `xdg-open` program.
|
||||
XdgOpen,
|
||||
/// Use the `gio` program.
|
||||
Gio,
|
||||
/// Use the `gnome-open` program.
|
||||
GnomeOpen,
|
||||
/// Use the `kde-open` program.
|
||||
KdeOpen,
|
||||
/// Use the `wslview` program.
|
||||
WslView,
|
||||
/// Use the `Firefox` program.
|
||||
Firefox,
|
||||
/// Use the `Google Chrome` program.
|
||||
Chrome,
|
||||
/// Use the `Chromium` program.
|
||||
Chromium,
|
||||
/// Use the `Safari` program.
|
||||
Safari,
|
||||
}
|
||||
|
||||
impl FromStr for Program {
|
||||
type Err = super::Error;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let p = match s.to_lowercase().as_str() {
|
||||
"open" => Self::Open,
|
||||
"start" => Self::Start,
|
||||
"xdg-open" => Self::XdgOpen,
|
||||
"gio" => Self::Gio,
|
||||
"gnome-open" => Self::GnomeOpen,
|
||||
"kde-open" => Self::KdeOpen,
|
||||
"wslview" => Self::WslView,
|
||||
"firefox" => Self::Firefox,
|
||||
"chrome" | "google chrome" => Self::Chrome,
|
||||
"chromium" => Self::Chromium,
|
||||
"safari" => Self::Safari,
|
||||
_ => return Err(crate::Error::UnknownProgramName(s.to_string())),
|
||||
};
|
||||
Ok(p)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Program {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let s = String::deserialize(deserializer)?;
|
||||
Program::from_str(&s).map_err(|e| serde::de::Error::custom(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
impl Program {
|
||||
pub(crate) fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Open => "open",
|
||||
Self::Start => "start",
|
||||
Self::XdgOpen => "xdg-open",
|
||||
Self::Gio => "gio",
|
||||
Self::GnomeOpen => "gnome-open",
|
||||
Self::KdeOpen => "kde-open",
|
||||
Self::WslView => "wslview",
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
Self::Firefox => "Firefox",
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
Self::Firefox => "firefox",
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
Self::Chrome => "Google Chrome",
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
Self::Chrome => "google-chrome",
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
Self::Chromium => "Chromium",
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
Self::Chromium => "chromium",
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
Self::Safari => "Safari",
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
Self::Safari => "safari",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens path or URL with the program specified in `with`, or system default if `None`.
|
||||
///
|
||||
/// The path will be matched against the shell open validation regex, defaulting to `^((mailto:\w+)|(tel:\w+)|(https?://\w+)).+`.
|
||||
/// A custom validation regex may be supplied in the config in `plugins > shell > scope > open`.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri_plugin_shell::ShellExt;
|
||||
/// tauri::Builder::default()
|
||||
/// .setup(|app| {
|
||||
/// // open the given URL on the system default browser
|
||||
/// app.shell().open("https://github.com/tauri-apps/tauri", None)?;
|
||||
/// Ok(())
|
||||
/// });
|
||||
/// ```
|
||||
#[deprecated(since = "2.1.0", note = "Use tauri-plugin-opener instead.")]
|
||||
pub fn open<P: AsRef<str>>(
|
||||
scope: Option<&OpenScope>,
|
||||
path: P,
|
||||
with: Option<Program>,
|
||||
) -> crate::Result<()> {
|
||||
// validate scope if we have any (JS calls)
|
||||
if let Some(scope) = scope {
|
||||
scope.open(path.as_ref(), with).map_err(Into::into)
|
||||
} else {
|
||||
// when running directly from Rust code we don't need to validate the path
|
||||
match with.map(Program::name) {
|
||||
Some(program) => ::open::with_detached(path.as_ref(), program),
|
||||
None => ::open::that_detached(path.as_ref()),
|
||||
}
|
||||
.map_err(Into::into)
|
||||
}
|
||||
}
|
||||
658
plugins/shell/src/process/mod.rs
Normal file
658
plugins/shell/src/process/mod.rs
Normal file
@@ -0,0 +1,658 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::{
|
||||
ffi::OsStr,
|
||||
io::{BufRead, BufReader, Write},
|
||||
path::{Path, PathBuf},
|
||||
process::{Command as StdCommand, Stdio},
|
||||
sync::{Arc, RwLock},
|
||||
thread::spawn,
|
||||
};
|
||||
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
#[cfg(windows)]
|
||||
use std::os::windows::process::CommandExt;
|
||||
|
||||
#[cfg(windows)]
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
const NEWLINE_BYTE: u8 = b'\n';
|
||||
|
||||
use tauri::async_runtime::{block_on as block_on_task, channel, Receiver, Sender};
|
||||
|
||||
pub use encoding_rs::Encoding;
|
||||
use os_pipe::{pipe, PipeReader, PipeWriter};
|
||||
use serde::Serialize;
|
||||
use shared_child::SharedChild;
|
||||
use tauri::utils::platform;
|
||||
|
||||
/// Payload for the [`CommandEvent::Terminated`] command event.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct TerminatedPayload {
|
||||
/// Exit code of the process.
|
||||
pub code: Option<i32>,
|
||||
/// If the process was terminated by a signal, represents that signal.
|
||||
pub signal: Option<i32>,
|
||||
}
|
||||
|
||||
/// A event sent to the command callback.
|
||||
#[derive(Debug, Clone)]
|
||||
#[non_exhaustive]
|
||||
pub enum CommandEvent {
|
||||
/// If configured for raw output, all bytes written to stderr.
|
||||
/// Otherwise, bytes until a newline (\n) or carriage return (\r) is found.
|
||||
Stderr(Vec<u8>),
|
||||
/// If configured for raw output, all bytes written to stdout.
|
||||
/// Otherwise, bytes until a newline (\n) or carriage return (\r) is found.
|
||||
Stdout(Vec<u8>),
|
||||
/// An error happened waiting for the command to finish or converting the stdout/stderr bytes to a UTF-8 string.
|
||||
Error(String),
|
||||
/// Command process terminated.
|
||||
Terminated(TerminatedPayload),
|
||||
}
|
||||
|
||||
/// The type to spawn commands.
|
||||
#[derive(Debug)]
|
||||
pub struct Command {
|
||||
cmd: StdCommand,
|
||||
raw_out: bool,
|
||||
}
|
||||
|
||||
/// Spawned child process.
|
||||
#[derive(Debug)]
|
||||
pub struct CommandChild {
|
||||
inner: Arc<SharedChild>,
|
||||
stdin_writer: PipeWriter,
|
||||
}
|
||||
|
||||
impl CommandChild {
|
||||
/// Writes to process stdin.
|
||||
pub fn write(&mut self, buf: &[u8]) -> crate::Result<()> {
|
||||
self.stdin_writer.write_all(buf)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Sends a kill signal to the child.
|
||||
pub fn kill(self) -> crate::Result<()> {
|
||||
self.inner.kill()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns the process pid.
|
||||
pub fn pid(&self) -> u32 {
|
||||
self.inner.id()
|
||||
}
|
||||
}
|
||||
|
||||
/// Describes the result of a process after it has terminated.
|
||||
#[derive(Debug)]
|
||||
pub struct ExitStatus {
|
||||
// This field is intentionally left private.
|
||||
// See: https://github.com/tauri-apps/plugins-workspace/pull/3115.
|
||||
code: Option<i32>,
|
||||
}
|
||||
|
||||
impl ExitStatus {
|
||||
/// Returns the exit code of the process, if any.
|
||||
pub fn code(&self) -> Option<i32> {
|
||||
self.code
|
||||
}
|
||||
|
||||
/// Returns true if exit status is zero. Signal termination is not considered a success, and success is defined as a zero exit status.
|
||||
pub fn success(&self) -> bool {
|
||||
self.code == Some(0)
|
||||
}
|
||||
}
|
||||
|
||||
/// The output of a finished process.
|
||||
#[derive(Debug)]
|
||||
pub struct Output {
|
||||
/// The status (exit code) of the process.
|
||||
pub status: ExitStatus,
|
||||
/// The data that the process wrote to stdout.
|
||||
pub stdout: Vec<u8>,
|
||||
/// The data that the process wrote to stderr.
|
||||
pub stderr: Vec<u8>,
|
||||
}
|
||||
|
||||
fn relative_command_path(command: &Path) -> crate::Result<PathBuf> {
|
||||
let exe_path = platform::current_exe()?;
|
||||
|
||||
let exe_dir = exe_path
|
||||
.parent()
|
||||
.ok_or(crate::Error::CurrentExeHasNoParent)?;
|
||||
|
||||
// If a test is being run, the executable is in the "deps" directory, so we need to go up one level.
|
||||
let base_dir = if exe_dir.ends_with("deps") {
|
||||
exe_dir.parent().unwrap_or(exe_dir)
|
||||
} else {
|
||||
exe_dir
|
||||
};
|
||||
|
||||
let mut command_path = base_dir.join(command);
|
||||
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let already_exe = command_path.extension().is_some_and(|ext| ext == "exe");
|
||||
if !already_exe {
|
||||
// do not use with_extension to retain dots in the command filename
|
||||
command_path.as_mut_os_string().push(".exe");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
if command_path.extension().is_some_and(|ext| ext == "exe") {
|
||||
command_path.set_extension("");
|
||||
}
|
||||
}
|
||||
|
||||
Ok(command_path)
|
||||
}
|
||||
|
||||
impl From<Command> for StdCommand {
|
||||
fn from(cmd: Command) -> StdCommand {
|
||||
cmd.cmd
|
||||
}
|
||||
}
|
||||
|
||||
impl Command {
|
||||
pub(crate) fn new<S: AsRef<OsStr>>(program: S) -> Self {
|
||||
log::debug!(
|
||||
"Creating sidecar {}",
|
||||
program.as_ref().to_str().unwrap_or("")
|
||||
);
|
||||
let mut command = StdCommand::new(program);
|
||||
|
||||
command.stdout(Stdio::piped());
|
||||
command.stdin(Stdio::piped());
|
||||
command.stderr(Stdio::piped());
|
||||
#[cfg(windows)]
|
||||
command.creation_flags(CREATE_NO_WINDOW);
|
||||
|
||||
Self {
|
||||
cmd: command,
|
||||
raw_out: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new_sidecar<S: AsRef<Path>>(program: S) -> crate::Result<Self> {
|
||||
Ok(Self::new(relative_command_path(program.as_ref())?))
|
||||
}
|
||||
|
||||
/// Appends an argument to the command.
|
||||
#[must_use]
|
||||
pub fn arg<S: AsRef<OsStr>>(mut self, arg: S) -> Self {
|
||||
self.cmd.arg(arg);
|
||||
self
|
||||
}
|
||||
|
||||
/// Appends arguments to the command.
|
||||
#[must_use]
|
||||
pub fn args<I, S>(mut self, args: I) -> Self
|
||||
where
|
||||
I: IntoIterator<Item = S>,
|
||||
S: AsRef<OsStr>,
|
||||
{
|
||||
self.cmd.args(args);
|
||||
self
|
||||
}
|
||||
|
||||
/// Clears the entire environment map for the child process.
|
||||
#[must_use]
|
||||
pub fn env_clear(mut self) -> Self {
|
||||
self.cmd.env_clear();
|
||||
self
|
||||
}
|
||||
|
||||
/// Inserts or updates an explicit environment variable mapping.
|
||||
#[must_use]
|
||||
pub fn env<K, V>(mut self, key: K, value: V) -> Self
|
||||
where
|
||||
K: AsRef<OsStr>,
|
||||
V: AsRef<OsStr>,
|
||||
{
|
||||
self.cmd.env(key, value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds or updates multiple environment variable mappings.
|
||||
#[must_use]
|
||||
pub fn envs<I, K, V>(mut self, envs: I) -> Self
|
||||
where
|
||||
I: IntoIterator<Item = (K, V)>,
|
||||
K: AsRef<OsStr>,
|
||||
V: AsRef<OsStr>,
|
||||
{
|
||||
self.cmd.envs(envs);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the working directory for the child process.
|
||||
#[must_use]
|
||||
pub fn current_dir<P: AsRef<Path>>(mut self, current_dir: P) -> Self {
|
||||
self.cmd.current_dir(current_dir);
|
||||
self
|
||||
}
|
||||
|
||||
/// Configures the reader to output bytes from the child process exactly as received
|
||||
pub fn set_raw_out(mut self, raw_out: bool) -> Self {
|
||||
self.raw_out = raw_out;
|
||||
self
|
||||
}
|
||||
|
||||
/// Spawns the command.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri_plugin_shell::{process::CommandEvent, ShellExt};
|
||||
/// tauri::Builder::default()
|
||||
/// .setup(|app| {
|
||||
/// let handle = app.handle().clone();
|
||||
/// tauri::async_runtime::spawn(async move {
|
||||
/// let (mut rx, mut child) = handle
|
||||
/// .shell()
|
||||
/// .command("cargo")
|
||||
/// .args(["tauri", "dev"])
|
||||
/// .spawn()
|
||||
/// .expect("Failed to spawn cargo");
|
||||
///
|
||||
/// let mut i = 0;
|
||||
/// while let Some(event) = rx.recv().await {
|
||||
/// if let CommandEvent::Stdout(line) = event {
|
||||
/// println!("got: {}", String::from_utf8(line).unwrap());
|
||||
/// i += 1;
|
||||
/// if i == 4 {
|
||||
/// child.write("message from Rust\n".as_bytes()).unwrap();
|
||||
/// i = 0;
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// });
|
||||
/// Ok(())
|
||||
/// });
|
||||
/// ```
|
||||
///
|
||||
/// Depending on the command you spawn, it might output in a specific encoding, to parse the output lines in this case:
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri_plugin_shell::{process::{CommandEvent, Encoding}, ShellExt};
|
||||
/// tauri::Builder::default()
|
||||
/// .setup(|app| {
|
||||
/// let handle = app.handle().clone();
|
||||
/// tauri::async_runtime::spawn(async move {
|
||||
/// let (mut rx, mut child) = handle
|
||||
/// .shell()
|
||||
/// .command("some-program")
|
||||
/// .arg("some-arg")
|
||||
/// .spawn()
|
||||
/// .expect("Failed to spawn some-program");
|
||||
///
|
||||
/// let encoding = Encoding::for_label(b"windows-1252").unwrap();
|
||||
/// while let Some(event) = rx.recv().await {
|
||||
/// if let CommandEvent::Stdout(line) = event {
|
||||
/// let (decoded, _, _) = encoding.decode(&line);
|
||||
/// println!("got: {decoded}");
|
||||
/// }
|
||||
/// }
|
||||
/// });
|
||||
/// Ok(())
|
||||
/// });
|
||||
/// ```
|
||||
pub fn spawn(self) -> crate::Result<(Receiver<CommandEvent>, CommandChild)> {
|
||||
let raw = self.raw_out;
|
||||
let mut command: StdCommand = self.into();
|
||||
let (stdout_reader, stdout_writer) = pipe()?;
|
||||
let (stderr_reader, stderr_writer) = pipe()?;
|
||||
let (stdin_reader, stdin_writer) = pipe()?;
|
||||
command.stdout(stdout_writer);
|
||||
command.stderr(stderr_writer);
|
||||
command.stdin(stdin_reader);
|
||||
|
||||
let shared_child = SharedChild::spawn(&mut command)?;
|
||||
let child = Arc::new(shared_child);
|
||||
let child_ = child.clone();
|
||||
let guard = Arc::new(RwLock::new(()));
|
||||
|
||||
let (tx, rx) = channel(1);
|
||||
|
||||
spawn_pipe_reader(
|
||||
tx.clone(),
|
||||
guard.clone(),
|
||||
stdout_reader,
|
||||
CommandEvent::Stdout,
|
||||
raw,
|
||||
);
|
||||
spawn_pipe_reader(
|
||||
tx.clone(),
|
||||
guard.clone(),
|
||||
stderr_reader,
|
||||
CommandEvent::Stderr,
|
||||
raw,
|
||||
);
|
||||
|
||||
spawn(move || {
|
||||
let _ = match child_.wait() {
|
||||
Ok(status) => {
|
||||
let _l = guard.write().unwrap();
|
||||
block_on_task(async move {
|
||||
tx.send(CommandEvent::Terminated(TerminatedPayload {
|
||||
code: status.code(),
|
||||
#[cfg(windows)]
|
||||
signal: None,
|
||||
#[cfg(unix)]
|
||||
signal: status.signal(),
|
||||
}))
|
||||
.await
|
||||
})
|
||||
}
|
||||
Err(e) => {
|
||||
let _l = guard.write().unwrap();
|
||||
block_on_task(async move { tx.send(CommandEvent::Error(e.to_string())).await })
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
Ok((
|
||||
rx,
|
||||
CommandChild {
|
||||
inner: child,
|
||||
stdin_writer,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
/// Executes a command as a child process, waiting for it to finish and collecting its exit status.
|
||||
/// Stdin, stdout and stderr are ignored.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```rust,no_run
|
||||
/// use tauri_plugin_shell::ShellExt;
|
||||
/// tauri::Builder::default()
|
||||
/// .setup(|app| {
|
||||
/// let status = tauri::async_runtime::block_on(async move { app.shell().command("which").args(["ls"]).status().await.unwrap() });
|
||||
/// println!("`which` finished with status: {:?}", status.code());
|
||||
/// Ok(())
|
||||
/// });
|
||||
/// ```
|
||||
pub async fn status(self) -> crate::Result<ExitStatus> {
|
||||
let (mut rx, _child) = self.spawn()?;
|
||||
let mut code = None;
|
||||
#[allow(clippy::collapsible_match)]
|
||||
while let Some(event) = rx.recv().await {
|
||||
if let CommandEvent::Terminated(payload) = event {
|
||||
code = payload.code;
|
||||
}
|
||||
}
|
||||
Ok(ExitStatus { code })
|
||||
}
|
||||
|
||||
/// Executes the command as a child process, waiting for it to finish and collecting all of its output.
|
||||
/// Stdin is ignored.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri_plugin_shell::ShellExt;
|
||||
/// tauri::Builder::default()
|
||||
/// .setup(|app| {
|
||||
/// let output = tauri::async_runtime::block_on(async move { app.shell().command("echo").args(["TAURI"]).output().await.unwrap() });
|
||||
/// assert!(output.status.success());
|
||||
/// assert_eq!(String::from_utf8(output.stdout).unwrap(), "TAURI");
|
||||
/// Ok(())
|
||||
/// });
|
||||
/// ```
|
||||
pub async fn output(self) -> crate::Result<Output> {
|
||||
let (mut rx, _child) = self.spawn()?;
|
||||
|
||||
let mut code = None;
|
||||
let mut stdout = Vec::new();
|
||||
let mut stderr = Vec::new();
|
||||
|
||||
while let Some(event) = rx.recv().await {
|
||||
match event {
|
||||
CommandEvent::Terminated(payload) => {
|
||||
code = payload.code;
|
||||
}
|
||||
CommandEvent::Stdout(line) => {
|
||||
stdout.extend(line);
|
||||
stdout.push(NEWLINE_BYTE);
|
||||
}
|
||||
CommandEvent::Stderr(line) => {
|
||||
stderr.extend(line);
|
||||
stderr.push(NEWLINE_BYTE);
|
||||
}
|
||||
CommandEvent::Error(_) => {}
|
||||
}
|
||||
}
|
||||
Ok(Output {
|
||||
status: ExitStatus { code },
|
||||
stdout,
|
||||
stderr,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn read_raw_bytes<F: Fn(Vec<u8>) -> CommandEvent + Send + Copy + 'static>(
|
||||
mut reader: BufReader<PipeReader>,
|
||||
tx: Sender<CommandEvent>,
|
||||
wrapper: F,
|
||||
) {
|
||||
loop {
|
||||
let result = reader.fill_buf();
|
||||
match result {
|
||||
Ok(buf) => {
|
||||
let length = buf.len();
|
||||
if length == 0 {
|
||||
break;
|
||||
}
|
||||
let tx_ = tx.clone();
|
||||
let _ = block_on_task(async move { tx_.send(wrapper(buf.to_vec())).await });
|
||||
reader.consume(length);
|
||||
}
|
||||
Err(e) => {
|
||||
let tx_ = tx.clone();
|
||||
let _ = block_on_task(
|
||||
async move { tx_.send(CommandEvent::Error(e.to_string())).await },
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_line<F: Fn(Vec<u8>) -> CommandEvent + Send + Copy + 'static>(
|
||||
mut reader: BufReader<PipeReader>,
|
||||
tx: Sender<CommandEvent>,
|
||||
wrapper: F,
|
||||
) {
|
||||
loop {
|
||||
let mut buf = Vec::new();
|
||||
match tauri::utils::io::read_line(&mut reader, &mut buf) {
|
||||
Ok(n) => {
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
let tx_ = tx.clone();
|
||||
let _ = block_on_task(async move { tx_.send(wrapper(buf)).await });
|
||||
}
|
||||
Err(e) => {
|
||||
let _ =
|
||||
block_on_task(async move { tx.send(CommandEvent::Error(e.to_string())).await });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_pipe_reader<F: Fn(Vec<u8>) -> CommandEvent + Send + Copy + 'static>(
|
||||
tx: Sender<CommandEvent>,
|
||||
guard: Arc<RwLock<()>>,
|
||||
pipe_reader: PipeReader,
|
||||
wrapper: F,
|
||||
raw_out: bool,
|
||||
) {
|
||||
spawn(move || {
|
||||
let _lock = guard.read().unwrap();
|
||||
let reader = BufReader::new(pipe_reader);
|
||||
|
||||
if raw_out {
|
||||
read_raw_bytes(reader, tx, wrapper);
|
||||
} else {
|
||||
read_line(reader, tx, wrapper);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// tests for the commands functions.
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn relative_command_path_resolves() {
|
||||
let cwd_parent = platform::current_exe()
|
||||
.unwrap()
|
||||
.parent()
|
||||
.unwrap()
|
||||
.parent() // Go up once more to get out of the "deps" directory
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
assert_eq!(
|
||||
relative_command_path(Path::new("Tauri.Example")).unwrap(),
|
||||
cwd_parent.join(if cfg!(windows) {
|
||||
"Tauri.Example.exe"
|
||||
} else {
|
||||
"Tauri.Example"
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
relative_command_path(Path::new("Tauri.Example.exe")).unwrap(),
|
||||
cwd_parent.join(if cfg!(windows) {
|
||||
"Tauri.Example.exe"
|
||||
} else {
|
||||
"Tauri.Example"
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
#[test]
|
||||
fn test_cmd_spawn_output() {
|
||||
let cmd = Command::new("cat").args(["test/test.txt"]);
|
||||
let (mut rx, _) = cmd.spawn().unwrap();
|
||||
|
||||
tauri::async_runtime::block_on(async move {
|
||||
while let Some(event) = rx.recv().await {
|
||||
match event {
|
||||
CommandEvent::Terminated(payload) => {
|
||||
assert_eq!(payload.code, Some(0));
|
||||
}
|
||||
CommandEvent::Stdout(line) => {
|
||||
assert_eq!(String::from_utf8(line).unwrap(), "This is a test doc!");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
#[test]
|
||||
fn test_cmd_spawn_raw_output() {
|
||||
let cmd = Command::new("cat").args(["test/test.txt"]);
|
||||
let (mut rx, _) = cmd.spawn().unwrap();
|
||||
|
||||
tauri::async_runtime::block_on(async move {
|
||||
while let Some(event) = rx.recv().await {
|
||||
match event {
|
||||
CommandEvent::Terminated(payload) => {
|
||||
assert_eq!(payload.code, Some(0));
|
||||
}
|
||||
CommandEvent::Stdout(line) => {
|
||||
assert_eq!(String::from_utf8(line).unwrap(), "This is a test doc!");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
#[test]
|
||||
// test the failure case
|
||||
fn test_cmd_spawn_fail() {
|
||||
let cmd = Command::new("cat").args(["test/"]);
|
||||
let (mut rx, _) = cmd.spawn().unwrap();
|
||||
|
||||
tauri::async_runtime::block_on(async move {
|
||||
while let Some(event) = rx.recv().await {
|
||||
match event {
|
||||
CommandEvent::Terminated(payload) => {
|
||||
assert_eq!(payload.code, Some(1));
|
||||
}
|
||||
CommandEvent::Stderr(line) => {
|
||||
assert_eq!(
|
||||
String::from_utf8(line).unwrap(),
|
||||
"cat: test/: Is a directory\n"
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
#[test]
|
||||
// test the failure case (raw encoding)
|
||||
fn test_cmd_spawn_raw_fail() {
|
||||
let cmd = Command::new("cat").args(["test/"]);
|
||||
let (mut rx, _) = cmd.spawn().unwrap();
|
||||
|
||||
tauri::async_runtime::block_on(async move {
|
||||
while let Some(event) = rx.recv().await {
|
||||
match event {
|
||||
CommandEvent::Terminated(payload) => {
|
||||
assert_eq!(payload.code, Some(1));
|
||||
}
|
||||
CommandEvent::Stderr(line) => {
|
||||
assert_eq!(
|
||||
String::from_utf8(line).unwrap(),
|
||||
"cat: test/: Is a directory\n"
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
#[test]
|
||||
fn test_cmd_output_output() {
|
||||
let cmd = Command::new("cat").args(["test/test.txt"]);
|
||||
let output = tauri::async_runtime::block_on(cmd.output()).unwrap();
|
||||
|
||||
assert_eq!(String::from_utf8(output.stderr).unwrap(), "");
|
||||
assert_eq!(
|
||||
String::from_utf8(output.stdout).unwrap(),
|
||||
"This is a test doc!\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
#[test]
|
||||
fn test_cmd_output_output_fail() {
|
||||
let cmd = Command::new("cat").args(["test/"]);
|
||||
let output = tauri::async_runtime::block_on(cmd.output()).unwrap();
|
||||
|
||||
assert_eq!(String::from_utf8(output.stdout).unwrap(), "");
|
||||
assert_eq!(
|
||||
String::from_utf8(output.stderr).unwrap(),
|
||||
"cat: test/: Is a directory\n\n"
|
||||
);
|
||||
}
|
||||
}
|
||||
322
plugins/shell/src/scope.rs
Normal file
322
plugins/shell/src/scope.rs
Normal file
@@ -0,0 +1,322 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
#[allow(deprecated)]
|
||||
use crate::open::Program;
|
||||
use crate::process::Command;
|
||||
|
||||
use regex::Regex;
|
||||
use tauri::ipc::ScopeObject;
|
||||
use tauri::Manager;
|
||||
|
||||
/// Allowed representation of `Execute` command arguments.
|
||||
#[derive(Debug, Clone, serde::Deserialize)]
|
||||
#[serde(untagged, deny_unknown_fields)]
|
||||
#[non_exhaustive]
|
||||
pub enum ExecuteArgs {
|
||||
/// No arguments
|
||||
None,
|
||||
|
||||
/// A single string argument
|
||||
Single(String),
|
||||
|
||||
/// Multiple string arguments
|
||||
List(Vec<String>),
|
||||
}
|
||||
|
||||
impl ExecuteArgs {
|
||||
/// Whether the argument list is empty or not.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
match self {
|
||||
Self::None => true,
|
||||
Self::Single(s) if s.is_empty() => true,
|
||||
Self::List(l) => l.is_empty(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<()> for ExecuteArgs {
|
||||
fn from(_: ()) -> Self {
|
||||
Self::None
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for ExecuteArgs {
|
||||
fn from(string: String) -> Self {
|
||||
Self::Single(string)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Vec<String>> for ExecuteArgs {
|
||||
fn from(vec: Vec<String>) -> Self {
|
||||
Self::List(vec)
|
||||
}
|
||||
}
|
||||
|
||||
/// A configured scoped shell command.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ScopeAllowedCommand {
|
||||
/// Name of the command (key).
|
||||
pub name: String,
|
||||
|
||||
/// The shell command to be called.
|
||||
pub command: std::path::PathBuf,
|
||||
|
||||
/// The arguments the command is allowed to be called with.
|
||||
pub args: Option<Vec<ScopeAllowedArg>>,
|
||||
|
||||
/// If this command is a sidecar command.
|
||||
pub sidecar: bool,
|
||||
}
|
||||
|
||||
impl ScopeObject for ScopeAllowedCommand {
|
||||
type Error = crate::Error;
|
||||
fn deserialize<R: tauri::Runtime>(
|
||||
app: &tauri::AppHandle<R>,
|
||||
raw: tauri::utils::acl::Value,
|
||||
) -> Result<Self, Self::Error> {
|
||||
let scope = serde_json::from_value::<crate::scope_entry::Entry>(raw.into())?;
|
||||
|
||||
let args = match scope.args.clone() {
|
||||
crate::scope_entry::ShellAllowedArgs::Flag(true) => None,
|
||||
crate::scope_entry::ShellAllowedArgs::Flag(false) => Some(Vec::new()),
|
||||
crate::scope_entry::ShellAllowedArgs::List(list) => {
|
||||
let list = list.into_iter().map(|arg| match arg {
|
||||
crate::scope_entry::ShellAllowedArg::Fixed(fixed) => {
|
||||
crate::scope::ScopeAllowedArg::Fixed(fixed)
|
||||
}
|
||||
crate::scope_entry::ShellAllowedArg::Var { validator, raw } => {
|
||||
let regex = if raw {
|
||||
validator
|
||||
} else {
|
||||
format!("^{validator}$")
|
||||
};
|
||||
let validator = Regex::new(®ex)
|
||||
.unwrap_or_else(|e| panic!("invalid regex {regex}: {e}"));
|
||||
crate::scope::ScopeAllowedArg::Var { validator }
|
||||
}
|
||||
});
|
||||
Some(list.collect())
|
||||
}
|
||||
};
|
||||
|
||||
let command = if let Ok(path) = app.path().parse(&scope.command) {
|
||||
path
|
||||
} else {
|
||||
scope.command.clone()
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
name: scope.name,
|
||||
command,
|
||||
args,
|
||||
sidecar: scope.sidecar,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A configured argument to a scoped shell command.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ScopeAllowedArg {
|
||||
/// A non-configurable argument.
|
||||
Fixed(String),
|
||||
|
||||
/// An argument with a value to be evaluated at runtime, must pass a regex validation.
|
||||
Var {
|
||||
/// The validation that the variable value must pass in order to be called.
|
||||
validator: Regex,
|
||||
},
|
||||
}
|
||||
|
||||
impl ScopeAllowedArg {
|
||||
/// If the argument is fixed.
|
||||
pub fn is_fixed(&self) -> bool {
|
||||
matches!(self, Self::Fixed(_))
|
||||
}
|
||||
}
|
||||
|
||||
/// Scope for the open command
|
||||
pub struct OpenScope {
|
||||
/// The validation regex that `shell > open` paths must match against.
|
||||
/// When set to `None`, no values are accepted.
|
||||
pub open: Option<Regex>,
|
||||
}
|
||||
|
||||
/// Scope for shell process spawning.
|
||||
#[derive(Clone)]
|
||||
pub struct ShellScope<'a> {
|
||||
/// All allowed commands, using their unique command name as the keys.
|
||||
pub scopes: Vec<&'a Arc<ScopeAllowedCommand>>,
|
||||
}
|
||||
|
||||
/// All errors that can happen while validating a scoped command.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
/// At least one argument did not pass input validation.
|
||||
#[error("The scoped command was called with the improper sidecar flag set")]
|
||||
BadSidecarFlag,
|
||||
|
||||
/// The sidecar program validated but failed to find the sidecar path.
|
||||
#[error(
|
||||
"The scoped sidecar command was validated, but failed to create the path to the command: {0}"
|
||||
)]
|
||||
Sidecar(String),
|
||||
|
||||
/// The named command was not found in the scoped config.
|
||||
#[error("Scoped command {0} not found")]
|
||||
NotFound(String),
|
||||
|
||||
/// A command variable has no value set in the arguments.
|
||||
#[error(
|
||||
"Scoped command argument at position {0} must match regex validation {1} but it was not found"
|
||||
)]
|
||||
MissingVar(usize, String),
|
||||
|
||||
/// At least one argument did not pass input validation.
|
||||
#[error("Scoped command argument at position {index} was found, but failed regex validation {validation}")]
|
||||
Validation {
|
||||
/// Index of the variable.
|
||||
index: usize,
|
||||
|
||||
/// Regex that the variable value failed to match.
|
||||
validation: String,
|
||||
},
|
||||
|
||||
/// The format of the passed input does not match the expected shape.
|
||||
///
|
||||
/// This can happen from passing a string or array of strings to a command that is expecting
|
||||
/// named variables, and vice-versa.
|
||||
#[error("Scoped command {0} received arguments in an unexpected format")]
|
||||
InvalidInput(String),
|
||||
|
||||
/// A generic IO error that occurs while executing specified shell commands.
|
||||
#[error("Scoped shell IO error: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
}
|
||||
|
||||
impl OpenScope {
|
||||
/// Open a path in the default (or specified) browser.
|
||||
///
|
||||
/// The path is validated against the `plugins > shell > open` validation regex, which
|
||||
/// defaults to `^((mailto:\w+)|(tel:\w+)|(https?://\w+)).+`.
|
||||
#[allow(deprecated)]
|
||||
pub fn open(&self, path: &str, with: Option<Program>) -> Result<(), Error> {
|
||||
// ensure we pass validation if the configuration has one
|
||||
if let Some(regex) = &self.open {
|
||||
if !regex.is_match(path) {
|
||||
return Err(Error::Validation {
|
||||
index: 0,
|
||||
validation: regex.as_str().into(),
|
||||
});
|
||||
}
|
||||
} else {
|
||||
log::warn!("open() command called but the plugin configuration denies calls from JavaScript; set `tauri.conf.json > plugins > shell > open` to true or a validation regex string");
|
||||
return Err(Error::Validation {
|
||||
index: 0,
|
||||
validation: "tauri^".to_string(), // purposefully impossible regex
|
||||
});
|
||||
}
|
||||
|
||||
// The prevention of argument escaping is handled by the usage of std::process::Command::arg by
|
||||
// the `open` dependency. This behavior should be re-confirmed during upgrades of `open`.
|
||||
match with.map(Program::name) {
|
||||
Some(program) => ::open::with_detached(path, program),
|
||||
None => ::open::that_detached(path),
|
||||
}
|
||||
.map_err(Into::into)
|
||||
}
|
||||
}
|
||||
|
||||
impl ShellScope<'_> {
|
||||
/// Validates argument inputs and creates a Tauri sidecar [`Command`].
|
||||
pub fn prepare_sidecar(
|
||||
&self,
|
||||
command_name: &str,
|
||||
command_script: &str,
|
||||
args: ExecuteArgs,
|
||||
) -> Result<Command, Error> {
|
||||
self._prepare(command_name, args, Some(command_script))
|
||||
}
|
||||
|
||||
/// Validates argument inputs and creates a Tauri [`Command`].
|
||||
pub fn prepare(&self, command_name: &str, args: ExecuteArgs) -> Result<Command, Error> {
|
||||
self._prepare(command_name, args, None)
|
||||
}
|
||||
|
||||
/// Validates argument inputs and creates a Tauri [`Command`].
|
||||
pub fn _prepare(
|
||||
&self,
|
||||
command_name: &str,
|
||||
args: ExecuteArgs,
|
||||
sidecar: Option<&str>,
|
||||
) -> Result<Command, Error> {
|
||||
let command = match self.scopes.iter().find(|s| s.name == command_name) {
|
||||
Some(command) => command,
|
||||
None => return Err(Error::NotFound(command_name.into())),
|
||||
};
|
||||
|
||||
if command.sidecar != sidecar.is_some() {
|
||||
return Err(Error::BadSidecarFlag);
|
||||
}
|
||||
|
||||
let args = match (&command.args, args) {
|
||||
(None, ExecuteArgs::None) => Ok(vec![]),
|
||||
(None, ExecuteArgs::List(list)) => Ok(list),
|
||||
(None, ExecuteArgs::Single(string)) => Ok(vec![string]),
|
||||
(Some(list), ExecuteArgs::List(args)) => list
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, arg)| match arg {
|
||||
ScopeAllowedArg::Fixed(fixed) => Ok(fixed.to_string()),
|
||||
ScopeAllowedArg::Var { validator } => {
|
||||
let value = args
|
||||
.get(i)
|
||||
.ok_or_else(|| Error::MissingVar(i, validator.to_string()))?
|
||||
.to_string();
|
||||
if validator.is_match(&value) {
|
||||
Ok(value)
|
||||
} else {
|
||||
Err(Error::Validation {
|
||||
index: i,
|
||||
validation: validator.to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
(Some(list), arg) if arg.is_empty() && list.iter().all(ScopeAllowedArg::is_fixed) => {
|
||||
list.iter()
|
||||
.map(|arg| match arg {
|
||||
ScopeAllowedArg::Fixed(fixed) => Ok(fixed.to_string()),
|
||||
_ => unreachable!(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
(Some(list), _) if list.is_empty() => Err(Error::InvalidInput(command_name.into())),
|
||||
(Some(_), _) => Err(Error::InvalidInput(command_name.into())),
|
||||
}?;
|
||||
|
||||
let command_s = sidecar
|
||||
.map(|s| {
|
||||
std::path::PathBuf::from(s)
|
||||
.components()
|
||||
.next_back()
|
||||
.unwrap()
|
||||
.as_os_str()
|
||||
.to_string_lossy()
|
||||
.into_owned()
|
||||
})
|
||||
.unwrap_or_else(|| command.command.to_string_lossy().into_owned());
|
||||
let command = if command.sidecar {
|
||||
Command::new_sidecar(command_s).map_err(|e| Error::Sidecar(e.to_string()))?
|
||||
} else {
|
||||
Command::new(command_s)
|
||||
};
|
||||
|
||||
Ok(command.args(args))
|
||||
}
|
||||
}
|
||||
77
plugins/shell/src/scope_entry.rs
Normal file
77
plugins/shell/src/scope_entry.rs
Normal file
@@ -0,0 +1,77 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use serde::{de::Error as DeError, Deserialize, Deserializer};
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// A command allowed to be executed by the webview API.
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub(crate) struct Entry {
|
||||
pub(crate) name: String,
|
||||
pub(crate) command: PathBuf,
|
||||
pub(crate) args: ShellAllowedArgs,
|
||||
pub(crate) sidecar: bool,
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Deserialize)]
|
||||
pub(crate) struct EntryRaw {
|
||||
pub(crate) name: String,
|
||||
#[serde(rename = "cmd")]
|
||||
pub(crate) command: Option<PathBuf>,
|
||||
#[serde(default)]
|
||||
pub(crate) args: ShellAllowedArgs,
|
||||
#[serde(default)]
|
||||
pub(crate) sidecar: bool,
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Entry {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let config = EntryRaw::deserialize(deserializer)?;
|
||||
|
||||
if !config.sidecar && config.command.is_none() {
|
||||
return Err(DeError::custom(
|
||||
"The shell scope `command` value is required.",
|
||||
));
|
||||
}
|
||||
|
||||
Ok(Entry {
|
||||
name: config.name,
|
||||
command: config.command.unwrap_or_default(),
|
||||
args: config.args,
|
||||
sidecar: config.sidecar,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Hash, Deserialize)]
|
||||
#[serde(untagged, deny_unknown_fields)]
|
||||
#[non_exhaustive]
|
||||
pub enum ShellAllowedArgs {
|
||||
Flag(bool),
|
||||
List(Vec<ShellAllowedArg>),
|
||||
}
|
||||
|
||||
impl Default for ShellAllowedArgs {
|
||||
fn default() -> Self {
|
||||
Self::Flag(false)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Hash, Deserialize)]
|
||||
#[serde(untagged, deny_unknown_fields)]
|
||||
#[non_exhaustive]
|
||||
pub enum ShellAllowedArg {
|
||||
Fixed(String),
|
||||
Var {
|
||||
validator: String,
|
||||
#[serde(default)]
|
||||
raw: bool,
|
||||
},
|
||||
}
|
||||
1
plugins/shell/test/test.txt
Normal file
1
plugins/shell/test/test.txt
Normal file
@@ -0,0 +1 @@
|
||||
This is a test doc!
|
||||
7
plugins/shell/tsconfig.json
Normal file
7
plugins/shell/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "guest-js"
|
||||
},
|
||||
"include": ["guest-js/*.ts"]
|
||||
}
|
||||
Reference in New Issue
Block a user