### Shell Plugin Configuration Example Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/errors.md Example configuration for defining allowed shell commands and their argument constraints. ```json { "permissions": [ { "identifier": "shell:allow-execute", "allow": [ { "name": "my-app", "cmd": "git", "args": false } ] } ] } ``` -------------------------------- ### Install JavaScript Dependency Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/quick-start.md Install the plugin package using your preferred package manager. ```bash npm install @tauri-apps/plugin-shell # or pnpm add @tauri-apps/plugin-shell # or yarn add @tauri-apps/plugin-shell ``` -------------------------------- ### Command.create Usage Examples Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/command-class.md Demonstrates creating commands with string arguments, array arguments, and raw binary output. ```typescript import { Command } from '@tauri-apps/plugin-shell'; // Basic usage with string output const cmd = Command.create('echo', 'hello world'); const output = await cmd.execute(); console.log(output.stdout); // With array arguments const gitCmd = Command.create('git', ['commit', '-m', 'test']); // With raw binary output const rawCmd = Command.create('hexdump', ['-C', 'file.bin'], { encoding: 'raw' }); const result = await rawCmd.execute(); console.log(result.stdout instanceof Uint8Array); ``` -------------------------------- ### Configuration Examples Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/open-function.md JSON configuration for enabling or customizing the open function validation regex in tauri.conf.json. ```json { "plugins": { "shell": { "open": true } } } ``` ```json { "plugins": { "shell": { "open": "^https?://github\\.com/.*" } } } ``` -------------------------------- ### Access Shell in Setup Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/shell-rust-struct.md Use the ShellExt trait to access shell operations within the application setup builder. ```rust use tauri::Manager; use tauri_plugin_shell::ShellExt; tauri::Builder::default() .setup(|app| { let shell = app.shell(); // Now you can use shell operations Ok(()) }); ``` -------------------------------- ### Command.sidecar Usage Examples Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/command-class.md Demonstrates executing sidecars with string output and custom environment variables. ```typescript import { Command } from '@tauri-apps/plugin-shell'; // Execute a sidecar with string output const sidecar = Command.sidecar('my-sidecar', ['--version']); const output = await sidecar.execute(); // With environment variables const cmd = Command.sidecar('python-bin', ['script.py'], { env: { PYTHONPATH: '/app/lib' } }); ``` -------------------------------- ### Usage Examples Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/open-function.md Common usage patterns for opening URLs, files, and handling potential errors. ```typescript import { open } from '@tauri-apps/plugin-shell'; // Open a URL with the default browser await open('https://github.com/tauri-apps/tauri'); // Open a URL with a specific browser await open('https://github.com/tauri-apps/tauri', 'firefox'); // Open a file with its default application await open('/path/to/document.pdf'); // Open an email client await open('mailto:user@example.com'); // Open phone app (on mobile or supported platforms) await open('tel:1234567890'); // Error handling try { await open('https://example.com'); } catch (error) { console.error('Failed to open URL:', error); } ``` -------------------------------- ### Install Rust Dependency Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/quick-start.md Add the plugin dependency to your Cargo.toml file. ```toml [dependencies] tauri-plugin-shell = "2.3" ``` -------------------------------- ### Install JavaScript Guest Bindings Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/README.md Instructions for installing the JavaScript guest bindings for the Tauri Plugin Shell using common package managers like pnpm, npm, or yarn. ```sh pnpm add @tauri-apps/plugin-shell # or npm add @tauri-apps/plugin-shell # or yarn add @tauri-apps/plugin-shell ``` -------------------------------- ### Argument Validation Execution Examples Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/errors.md Examples showing how argument validation rules affect command execution outcomes. ```typescript // OK: matches fixed args await Command.create('git-commit', ['commit', '-m', 'test']).execute(); // ERROR: missing required argument await Command.create('git-commit', ['commit']).execute(); // Message: "Scoped command argument at position 2 must match regex validation \\S+ but it was not found" // ERROR: regex validation failed await Command.create('git-commit', ['commit', '-m', '']).execute(); // Message: "Scoped command argument at position 2 was found, but failed regex validation \\S+" ``` -------------------------------- ### Configure regex validator Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/scope-and-permissions.md Example configuration for a regex validator that is compiled at initialization. ```json { "validator": "^[a-zA-Z0-9]+$", "raw": false } ``` -------------------------------- ### init() Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/shell-rust-struct.md Initializes the shell plugin for use within a Tauri application. This function must be registered with the Tauri builder during application setup. ```APIDOC ## init() ### Description Initializes the shell plugin. Must be registered with the Tauri builder. ### Signature `pub fn init() -> TauriPlugin>` ### Returns `TauriPlugin>` — The initialized plugin ### Example ```rust fn main() { tauri::Builder::default() .plugin(tauri_plugin_shell::init()) .run(tauri::generate_context!()) .expect("error while running tauri application"); } ``` ``` -------------------------------- ### EventEmitter on() Usage Examples Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/event-emitter-class.md Demonstrates listening to process events, stdout data, and chaining multiple listeners. ```typescript import { Command } from '@tauri-apps/plugin-shell'; const cmd = Command.create('npm', ['start']); // Listen to close event cmd.on('close', (data) => { console.log(`Process exited with code ${data.code}`); }); // Listen to stdout data cmd.stdout.on('data', (line) => { console.log(`stdout: ${line}`); }); // Chain multiple listeners cmd.on('error', (err) => console.error(err)) .stdout.on('data', (line) => console.log(line)); ``` -------------------------------- ### EventEmitter once() Usage Examples Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/event-emitter-class.md Demonstrates setting up one-time listeners for data and process completion. ```typescript import { Command } from '@tauri-apps/plugin-shell'; const cmd = Command.create('cp', ['source.txt', 'dest.txt']); // Listen for first data event only cmd.stdout.once('data', (line) => { console.log('First output line:', line); }); // Listen for process close once cmd.once('close', (data) => { console.log('Process finished'); }); await cmd.spawn(); ``` -------------------------------- ### Configure Shell Plugin Open API Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/configuration.md Examples of enabling, restricting, or disabling the open API via the shell plugin configuration. ```json { "plugins": { "shell": { "open": true } } } ``` ```json { "plugins": { "shell": { "open": "https?://github\\.com/.*" } } } ``` ```json { "plugins": { "shell": { "open": "(https://.*|mailto:.*)" } } } ``` ```json { "plugins": { "shell": { "open": false } } } ``` -------------------------------- ### Retrieve child process PID Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/command-child-rust.md Example of accessing the process ID of a spawned child. ```rust use tauri_plugin_shell::process::Command; let (mut rx, child) = Command::new("bash") .spawn()?; println!("Child process PID: {}", child.pid()); // Store PID for later let pid = child.pid(); // Continue processing while let Some(_event) = rx.recv().await {} Ok::<(), crate::Error>(()) ``` -------------------------------- ### Process Regex Validator Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/scope-and-permissions.md Examples of how regex configurations are compiled into Rust Regex objects based on the raw flag. ```json { "validator": "\\d+", "raw": false } ``` ```rust Regex::new("^\\d+$")? // Match entire value ``` ```json { "validator": ".*pattern.*", "raw": true } ``` ```rust Regex::new(".*pattern.*")? // Match as-is ``` -------------------------------- ### Install Tauri Plugin Shell (Rust) Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/README.md This snippet shows how to add the Tauri Plugin Shell to your Rust project's Cargo.toml file. It supports installation from crates.io or directly from a Git repository. ```toml [dependencies] tauri-plugin-shell = "2.0.0" # alternatively with Git: tauri-plugin-shell = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" } ``` -------------------------------- ### Write to child process stdin Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/command-child-rust.md Example of writing data to a child process's stdin and processing output events. ```rust use tauri_plugin_shell::process::{Command, CommandEvent}; let (mut rx, mut child) = Command::new("python3") .spawn()?; // Write Python code to stdin child.write(b"print('hello from rust')\n")?; child.write(b"exit()\n")?; // Process events while let Some(event) = rx.recv().await { match event { CommandEvent::Stdout(line) => { println!("Output: {}", String::from_utf8_lossy(&line)); } CommandEvent::Terminated(_) => break, _ => {} } } Ok::<(), crate::Error>(()) ``` -------------------------------- ### Execute a command and get output Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/README.md Executes a command and waits for the result. Requires the command to be defined in the application's capabilities. ```typescript import { Command } from '@tauri-apps/plugin-shell'; const output = await Command.create('echo', 'hello').execute(); ``` -------------------------------- ### Terminate child process Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/command-child-rust.md Example of killing a child process after a specified duration. ```rust use tauri_plugin_shell::process::Command; use std::time::Duration; let (mut rx, child) = Command::new("sleep") .arg("300") .spawn()?; // Spawn a task to kill the process after 5 seconds tauri::async_runtime::spawn(async move { tokio::time::sleep(Duration::from_secs(5)).await; let _ = child.kill(); }); // Wait for termination while let Some(_event) = rx.recv().await { // Process events } Ok::<(), crate::Error>(()) ``` -------------------------------- ### Use Command API (JavaScript) Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/README.md An example of using the Command API from the Tauri Plugin Shell in JavaScript. This allows you to create and execute shell commands from your frontend code. ```javascript import { Command } from '@tauri-apps/plugin-shell' Command.create('git', ['commit', '-m', 'the commit message']) ``` -------------------------------- ### Execute Commands Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/shell-rust-struct.md Demonstrates creating commands with and without arguments using the shell instance. ```rust use tauri::Manager; use tauri_plugin_shell::ShellExt; tauri::Builder::default() .setup(|app| { let shell = app.shell(); // Create a command for 'ls' let cmd = shell.command("ls"); // Create a command with arguments let cmd = shell.command("git") .arg("clone") .arg("https://github.com/tauri-apps/tauri"); Ok(()) }); ``` -------------------------------- ### Initialize a new Command Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/command-rust-struct.md Create a new command instance for a system program. Stdout, stdin, and stderr are configured as piped by default. ```rust use tauri_plugin_shell::process::Command; let cmd = Command::new("git"); let cmd_with_path = Command::new("/usr/bin/git"); ``` -------------------------------- ### Execute and Display Output with TypeScript Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/README.md Demonstrates running a simple command and capturing its standard output. Requires the Command class from @tauri-apps/plugin-shell. ```typescript import { Command } from '@tauri-apps/plugin-shell'; async function showGitStatus() { try { const output = await Command.create('git', ['status']).execute(); console.log('Git status:', output.stdout); } catch (error) { console.error('Error:', error); } } ``` -------------------------------- ### command(program: impl AsRef) Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/shell-rust-struct.md Creates a new Command builder for launching a system program. ```APIDOC ## command(program: impl AsRef) ### Description Creates a new `Command` for launching the given program. This returns a command builder that can be configured further with arguments or environment variables. ### Parameters - **program** (impl AsRef) - Required - Program name or path to execute ### Returns - **Command** - A command builder instance ``` -------------------------------- ### View project file structure Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/INDEX.md Displays the directory layout of the documentation files. ```text output/ ├── README.md # Main entry point ├── INDEX.md # This file ├── quick-start.md # Setup and common patterns ├── configuration.md # Plugin setup and capabilities ├── types.md # Type definitions ├── errors.md # Error catalog ├── scope-and-permissions.md # Security and permissions └── api-reference/ ├── command-class.md # JS/TS Command class ├── child-class.md # JS/TS Child class ├── event-emitter-class.md # JS/TS EventEmitter ├── open-function.md # JS/TS open() (deprecated) ├── shell-rust-struct.md # Rust Shell struct ├── command-rust-struct.md # Rust Command builder ├── command-child-rust.md # Rust CommandChild └── process-module.md # Rust process module ``` -------------------------------- ### EventEmitter off() Usage Example Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/event-emitter-class.md Demonstrates removing a previously attached listener function. ```typescript import { Command } from '@tauri-apps/plugin-shell'; const cmd = Command.create('tail', ['-f', 'log.txt']); const dataHandler = (line) => { console.log('Log:', line); }; cmd.stdout.on('data', dataHandler); // Later, remove the listener cmd.stdout.off('data', dataHandler); ``` -------------------------------- ### open(path: impl Into, with: Option) Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/shell-rust-struct.md Opens a URL or path using the system default or a specified program. ```APIDOC ## open(path: impl Into, with: Option) ### Description Opens a URL or path with a default or specific browser opening program. Note: This method is deprecated since v2.1.0; use `tauri-plugin-opener` instead. ### Parameters - **path** (impl Into) - Required - Path or URL to open - **with** (Option) - Optional - Specific program to use (None for system default) ### Returns - **Result<()>** - Success or an error ``` -------------------------------- ### sidecar(program: impl AsRef) Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/shell-rust-struct.md Creates a new Command builder for launching an embedded sidecar binary. ```APIDOC ## sidecar(program: impl AsRef) ### Description Creates a new `Command` for launching a sidecar program. A sidecar is an embedded external binary that is bundled with the application. ### Parameters - **program** (impl AsRef) - Required - Path to the sidecar program relative to the executable directory ### Returns - **Result** - A command builder or an error if the sidecar path cannot be resolved ### Errors - Returns `crate::Error` if the sidecar path cannot be computed ``` -------------------------------- ### spawn() Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/command-class.md Executes the command as a child process in the background, returning a handle to interact with the process and monitor its output. ```APIDOC ## spawn() ### Description Executes the command as a child process, returning a handle to it. The process continues running in the background, and you can monitor stdout/stderr via event listeners and interact with stdin. ### Returns - **Promise** - A promise resolving to a child process handle with a pid property. ### Throws - Rejects if the command cannot be spawned due to scope violations or system errors. ``` -------------------------------- ### Command.create() Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/command-class.md Creates a command instance to execute a system program configured in the application capabilities. ```APIDOC ## Command.create(program, args?, options?) ### Description Creates a command to execute the given system program. The program must be explicitly configured in the application's capabilities. ### Parameters - **program** (string) - Required - The name of the program to execute. - **args** (string | string[]) - Optional - Program arguments as a single string or an array of strings. - **options** (SpawnOptions) - Optional - Configuration options including cwd, env, and encoding. ### Returns - **Command** (default) or **Command** (if encoding is 'raw'). ``` -------------------------------- ### Trigger UnknownProgramName Error Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/errors.md Example of an error triggered when an unrecognized program name is passed to the open command. ```typescript await open('https://example.com', 'unknown-browser'); // Error: "unknown program unknown-browser" ``` -------------------------------- ### async function open(path: string, openWith?: string): Promise Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/open-function.md Opens a path or URL with the system's default application or a specified program. Note: This function is deprecated since v2.1.0; use @tauri-apps/plugin-opener instead. ```APIDOC ## async function open(path: string, openWith?: string): Promise ### Description Opens a path or URL with the system's default application or a specified program. The path must match the validation regex defined in the shell plugin configuration. ### Parameters - **path** (string) - Required - The path or URL to open. Must match the validation regex defined in tauri.conf.json. - **openWith** (string) - Optional - The application to use to open the path. Defaults to the system default application. ### Returns - **Promise** - Resolves when the file or URL has been opened. ### Throws - Rejects if the path fails validation or if the open operation fails. ### Example ```typescript import { open } from '@tauri-apps/plugin-shell'; // Open a URL with the default browser await open('https://github.com/tauri-apps/tauri'); // Open a URL with a specific browser await open('https://github.com/tauri-apps/tauri', 'firefox'); ``` ``` -------------------------------- ### Initialize encoding in Rust Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/README.md Shows how to retrieve an encoding instance for a specific label using the plugin's Encoding API. ```rust use tauri_plugin_shell::process::{Command, CommandEvent, Encoding}; let encoding = Encoding::for_label(b"windows-1252").unwrap(); ``` -------------------------------- ### Trigger Scope Errors Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/errors.md Examples of errors triggered when command execution violates scope configuration or argument validation rules. ```typescript // Error: "Scoped command my-command not found" await Command.create('my-command').execute(); // If 'my-command' is not in scope // Error: "Scoped command argument at position 0 was found, but failed regex validation ^[a-z]+$" await Command.create('echo', ['123']).execute(); // If args are restricted to lowercase letters // Error: "Scoped command argument at position 2 must match regex validation \d+ but it was not found" // When a command expects 3 arguments but only 2 are provided ``` -------------------------------- ### Configure Sidecar Binaries Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/quick-start.md Register external binaries in the bundle configuration. ```json { "bundle": { "externalBin": [ "python-bin", "node-bin" ] } } ``` -------------------------------- ### Get command exit status in Rust Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/command-rust-struct.md Executes a command and waits for it to finish, returning only the exit status. Stdin, stdout, and stderr are ignored. ```rust pub async fn status(self) -> crate::Result ``` ```rust use tauri_plugin_shell::process::Command; let status = Command::new("which") .args(["ls"]) .status() .await?; println!("Exit code: {:?}", status.code()); println!("Success: {}", status.success()); ``` -------------------------------- ### Initialize a sidecar Command Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/command-rust-struct.md Create a command instance for a sidecar program, resolving the path relative to the current executable directory. ```rust use tauri_plugin_shell::process::Command; let cmd = Command::new_sidecar("python-bin")?; ``` -------------------------------- ### Execute commands with specific encodings in TypeScript Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/README.md Demonstrates creating and executing commands with 'raw' and 'windows-1252' encodings to handle binary and specific character sets. ```typescript const rawCmd = Command.create('hexdump', ['-C', 'file'], { encoding: 'raw' }); const output = await rawCmd.execute(); // output.stdout is Uint8Array const winCmd = Command.create('program', [], { encoding: 'windows-1252' }); const output = await winCmd.execute(); // output.stdout is string ``` -------------------------------- ### Configure sidecar commands Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/configuration.md Define sidecar execution in capabilities and register the binary in the bundle configuration. ```json { "name": "python-script", "sidecar": true } ``` ```json { "build": { "beforeBuildCommand": "pnpm build", "beforeDevCommand": "pnpm dev", "devPath": "http://localhost:1430", "frontendDist": "../dist" }, "bundle": { "externalBin": [ "python-bin" ] } } ``` -------------------------------- ### Define Shell Capabilities Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/README.md Configure allowed commands and arguments in the capabilities JSON file. ```json { "permissions": [ { "identifier": "shell:allow-execute", "allow": [ { "name": "echo", "cmd": "echo", "args": true } ] } ] } ``` -------------------------------- ### Command.sidecar() Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/command-class.md Creates a command instance to execute an embedded sidecar binary. ```APIDOC ## Command.sidecar(program, args?, options?) ### Description Creates a command to execute a sidecar program. Sidecars are external binaries packaged with the application and must be configured in `tauri.conf.json > bundle > externalBin`. ### Parameters - **program** (string) - Required - The name of the sidecar binary. - **args** (string | string[]) - Optional - Program arguments as a single string or an array of strings. - **options** (SpawnOptions) - Optional - Configuration options including cwd, env, and encoding. ### Returns - **Command** (default) or **Command** (if encoding is 'raw'). ``` -------------------------------- ### Define Shell Permissions Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/00-START-HERE.md Configure allowed commands and arguments within the capabilities JSON file. ```json // Capabilities: src-tauri/capabilities/default.json { "permissions": [ { "identifier": "shell:allow-execute", "allow": [{ "name": "echo", "cmd": "echo", "args": true }] } ] } ``` -------------------------------- ### Configure shell capabilities Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/configuration.md Define allowed shell commands and URL access in the default capabilities file. ```json { "version": 1, "identifier": "main-capability", "description": "Main capability for the app", "windows": ["main"], "permissions": [ { "identifier": "shell:allow-execute", "allow": [ { "name": "git-commit", "cmd": "git", "args": ["commit", "-m", { "validator": "\\S+" }] } ] }, { "identifier": "shell:allow-open", "allow": [{ "url": "https?://.*" }] } ] } ``` -------------------------------- ### Configure mixed arguments Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/configuration.md Combine fixed and variable arguments for precise command control. ```json { "name": "git-commit", "cmd": "git", "args": ["commit", "-m", { "validator": "\\S+" }] } ``` -------------------------------- ### Execute Sidecar Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/quick-start.md Run a sidecar binary configured in tauri.conf.json. ```typescript import { Command } from '@tauri-apps/plugin-shell'; async function runSidecar() { // Sidecar must be configured in tauri.conf.json > bundle > externalBin // and in capabilities const output = await Command.sidecar('my-python-bin', ['script.py']).execute(); console.log('Output:', output.stdout); } runSidecar().catch(console.error); ``` -------------------------------- ### Spawn a child process with Command.spawn() Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/command-class.md Executes a command in the background and attaches event listeners to monitor stdout, stderr, and process lifecycle. ```typescript import { Command } from '@tauri-apps/plugin-shell'; // Spawn and monitor output const cmd = Command.create('npm', ['start']); cmd.on('close', (data) => { console.log(`Process exited with code ${data.code}`); }); cmd.stdout.on('data', (line) => { console.log(`stdout: ${line}`); }); cmd.stderr.on('data', (line) => { console.error(`stderr: ${line}`); }); const child = await cmd.spawn(); console.log('Process started with PID:', child.pid); // Error handling try { const child = await cmd.spawn(); } catch (error) { console.error('Failed to spawn process:', error); } ``` -------------------------------- ### Command Static Factory Methods Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/command-class.md Overloaded signatures for creating commands with string or raw binary output. ```typescript static create(program: string, args?: string | string[]): Command static create( program: string, args?: string | string[], options?: SpawnOptions & { encoding: 'raw' } ): Command static create( program: string, args: string | string[] = [], options?: SpawnOptions ): Command ``` -------------------------------- ### Define Command struct Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/types.md Acts as a builder for system commands. ```rust pub struct Command { cmd: StdCommand, raw_out: bool, } ``` -------------------------------- ### Define Execute Command Arguments Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/types.md Represents the allowed formats for command arguments, supporting none, a single string, or a list of strings. ```rust pub enum ExecuteArgs { None, Single(String), List(Vec), } ``` -------------------------------- ### Prepare Command Runtime Validation in Rust Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/scope-and-permissions.md Internal function signature for validating programs and arguments against defined scopes before command execution. ```rust fn prepare_cmd( window: Window, program: String, args: ExecuteArgs, options: CommandOptions, command_scope: CommandScope, global_scope: GlobalScope, ) -> crate::Result<(crate::process::Command, EncodingWrapper)> ``` -------------------------------- ### Configure variable arguments Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/configuration.md Use regex validators to allow dynamic arguments, such as specific file extensions. ```json { "name": "run-script", "cmd": "bash", "args": [{ "validator": ".*\\.sh$" }] } ``` ```typescript await Command.create('run-script', ['script.sh']).execute(); // OK await Command.create('run-script', ['other.py']).execute(); // ERROR ``` -------------------------------- ### args() Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/command-rust-struct.md Appends multiple arguments to the command. ```APIDOC ## pub fn args(mut self, args: I) -> Self ### Description Appends multiple arguments to the command. ### Parameters - **args** (impl IntoIterator) - Required - Iterator of arguments to append ### Returns - **Self** - The command for method chaining ``` -------------------------------- ### Configure Open API in tauri.conf.json Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/quick-start.md Enable the open API or restrict it using a regex pattern. ```json { "plugins": { "shell": { "open": true } } } ``` ```json { "plugins": { "shell": { "open": "https?://.*" } } } ``` -------------------------------- ### Define Open Method Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/shell-rust-struct.md The open method is used to open URLs or paths, though it is deprecated in favor of tauri-plugin-opener. ```rust #[deprecated(since = "2.1.0", note = "Use tauri-plugin-opener instead.")] pub fn open(&self, path: impl Into, with: Option) -> Result<()> ``` -------------------------------- ### Initialize Shell Plugin Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/shell-rust-struct.md Defines the initialization function signature for the shell plugin. ```rust pub fn init() -> TauriPlugin> ``` -------------------------------- ### Shell::command Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/process-module.md Spawns an external command. This method allows for configuring arguments, setting raw output mode, and executing the process. ```APIDOC ## Shell::command ### Description Creates a new command builder for the specified program. This is the entry point for executing external processes. ### Methods - **arg(arg: &str)**: Adds an argument to the command. - **set_raw_out(raw: bool)**: Enables or disables raw output mode. When enabled, stdout and stderr contain all bytes received. - **spawn()**: Spawns the command and returns a receiver for CommandEvents and the child process handle. - **output()**: Executes the command as a child process, waits for it to finish, and collects all output. ``` -------------------------------- ### Configure raw output mode Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/command-rust-struct.md Use set_raw_out() to toggle between raw byte output and line-buffered text output. ```rust use tauri_plugin_shell::process::Command; // Raw binary output let cmd = Command::new("hexdump") .arg("-C") .arg("file.bin") .set_raw_out(true); // Line-buffered text output (default) let cmd = Command::new("cat") .arg("file.txt") .set_raw_out(false); ``` -------------------------------- ### Set the working directory Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/command-rust-struct.md Use current_dir() to specify the directory in which the command should execute. ```rust use tauri_plugin_shell::process::Command; let cmd = Command::new("npm") .arg("install") .current_dir("/app/project"); ``` -------------------------------- ### Manage Backend Processes in Rust Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/README.md Utilizes ShellExt to spawn a command and process events asynchronously in the Rust backend. Requires handling CommandEvent variants. ```rust use tauri::{Manager, RunEvent}; use tauri_plugin_shell::{ShellExt, process::CommandEvent}; async fn manage_service(app: &tauri::AppHandle) -> Result<(), Box> { let shell = app.shell(); let (mut rx, child) = shell.command("myservice") .arg("start") .spawn()?; println!("Service started with PID: {}", child.pid()); while let Some(event) = rx.recv().await { match event { CommandEvent::Stdout(line) => { println!("Service: {}", String::from_utf8_lossy(&line)); } CommandEvent::Terminated(payload) => { println!("Service exited: {:?}", payload.code); break; } _ => {} } } Ok(()) } ``` -------------------------------- ### output() Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/command-rust-struct.md Executes the command as a child process, waits for it to finish, and collects all stdout and stderr output. ```APIDOC ## output() ### Description Executes the command as a child process, waits for it to finish, and collects all stdout and stderr output. ### Signature `pub async fn output(self) -> crate::Result` ### Returns - `Output` - Structure containing status (ExitStatus), stdout (Vec), and stderr (Vec) ``` -------------------------------- ### execute() Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/command-class.md Executes the command, waits for it to finish, and collects all output into a single result object. ```APIDOC ## execute() ### Description Executes the command as a child process, waits for it to finish, and collects all output. This is a convenience method that combines spawn with output collection. ### Returns - **Promise>** - A promise resolving to output containing: - **code** (number | null) - Exit code of the process - **signal** (number | null) - Signal that terminated the process (Unix only, null on Windows) - **stdout** (O) - Collected stdout output - **stderr** (O) - Collected stderr output ### Throws - Rejects if the command cannot be executed due to scope violations or system errors. ``` -------------------------------- ### Execute Command Synchronously Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/process-module.md Spawns a command and waits for it to complete before returning the output. ```rust use tauri_plugin_shell::ShellExt; use tauri::Manager; async fn run_command(app: &tauri::AppHandle) -> crate::Result<()> { let shell = app.shell(); let output = shell.command("echo") .arg("hello") .output() .await?; if output.status.success() { println!("Output: {}", String::from_utf8(output.stdout)?); } Ok(()) } ``` -------------------------------- ### envs() Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/command-rust-struct.md Adds or updates multiple environment variable mappings. ```APIDOC ## pub fn envs(mut self, envs: I) -> Self ### Description Adds or updates multiple environment variable mappings. ### Parameters - **envs** (impl IntoIterator) - Required - Pairs of environment variable names and values ### Returns - **Self** - The command for method chaining ``` -------------------------------- ### Stream output from a process Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/00-START-HERE.md Spawns a process and listens to its standard output stream. ```typescript const cmd = Command.create('npm', ['start']); cmd.stdout.on('data', (line) => console.log(line)); await cmd.spawn(); ``` -------------------------------- ### Register Shell Plugin in Main Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/shell-rust-struct.md Registers the shell plugin within the Tauri builder during application startup. ```rust fn main() { tauri::Builder::default() .plugin(tauri_plugin_shell::init()) .run(tauri::generate_context!()) .expect("error while running tauri application"); } ``` -------------------------------- ### Configure Shell Capabilities Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/scope-and-permissions.md Defines allowed shell commands, specific arguments with regex validation, and sidecar execution permissions. ```json { "version": 1, "identifier": "main-capability", "permissions": [ { "identifier": "shell:allow-execute", "allow": [ { "name": "git-clone", "cmd": "git", "args": ["clone", { "validator": "^https?://[\\w\\-./]+" }] }, { "name": "git-commit", "cmd": "git", "args": ["commit", "-m", { "validator": "\\S+" }] }, { "name": "npm-install", "cmd": "npm", "args": ["install"] }, { "name": "echo-test", "cmd": "echo", "args": true }, { "name": "python-sidecar", "sidecar": true } ] } ] } ``` -------------------------------- ### Execute a Command in Rust Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/quick-start.md Run a shell command and capture its output asynchronously. ```rust use tauri::{Manager, RunEvent}; use tauri_plugin_shell::ShellExt; tauri::Builder::default() .plugin(tauri_plugin_shell::init()) .setup(|app| { let handle = app.handle().clone(); tauri::async_runtime::spawn(async move { let shell = handle.shell(); match shell.command("echo").arg("hello").output().await { Ok(output) => { if output.status.success() { let text = String::from_utf8(output.stdout).unwrap(); println!("Output: {}", text); } } Err(e) => eprintln!("Error: {}", e), } }); Ok(()) }) .run(tauri::generate_context!()) .expect("error while running tauri application"); ``` -------------------------------- ### Handle Shell Command Errors in Rust Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/errors.md Shows how to check command exit status and use pattern matching to handle specific plugin error variants. ```rust use tauri_plugin_shell::{ShellExt, Error}; async fn run_command(app: &tauri::AppHandle) -> Result<(), Error> { let shell = app.shell(); let cmd = shell.command("echo") .arg("hello"); let output = cmd.output().await?; // Check exit status if !output.status.success() { eprintln!("Command failed with exit code {:?}", output.status.code()); } println!("Output: {}", String::from_utf8(output.stdout)?); Ok(()) } // Pattern matching match some_operation() { Ok(result) => println!("Success: {:?}", result), Err(Error::SidecarNotAllowed(path)) => { eprintln!("Sidecar not configured: {:?}", path); } Err(Error::ProgramNotAllowed(path)) => { eprintln!("Program not allowed: {:?}", path); } Err(Error::Io(io_err)) => { eprintln!("I/O error: {}", io_err); } Err(e) => eprintln!("Other error: {}", e), } ``` -------------------------------- ### Execute a command to completion with Command.execute() Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/command-class.md Runs a command and waits for it to finish, returning the exit code and collected output. ```typescript import { Command } from '@tauri-apps/plugin-shell'; // Simple execution const output = await Command.create('echo', 'message').execute(); if (output.code === 0) { console.log('Success:', output.stdout); } else { console.error('Failed with code:', output.code, 'stderr:', output.stderr); } // With error handling try { const result = await Command.create('ls', ['-la', '/tmp']).execute(); console.log(`Exit code: ${result.code}`); console.log(`Output: ${result.stdout}`); } catch (error) { console.error('Command execution failed:', error); } ``` -------------------------------- ### Define SpawnOptions interface Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/types.md Configuration options for spawning child processes, including working directory, environment variables, and encoding. ```typescript interface SpawnOptions { cwd?: string env?: Record encoding?: string } ``` -------------------------------- ### Open URL Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/quick-start.md Open a URL or mailto link in the default system browser or application. ```typescript import { open } from '@tauri-apps/plugin-shell'; async function openURL() { // Note: Deprecated in v2.1.0 — use @tauri-apps/plugin-opener instead await open('https://github.com/tauri-apps/tauri'); await open('mailto:user@example.com'); } openURL().catch(console.error); ``` -------------------------------- ### Stream Command Output Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/process-module.md Spawns a process and processes stdout, stderr, and termination events in real time. ```rust use tauri_plugin_shell::{ShellExt, process::CommandEvent}; use tauri::Manager; async fn stream_output(app: &tauri::AppHandle) -> crate::Result<()> { let shell = app.shell(); let (mut rx, _child) = shell.command("npm") .arg("start") .spawn()?; while let Some(event) = rx.recv().await { match event { CommandEvent::Stdout(line) => { println!("stdout: {}", String::from_utf8_lossy(&line)); } CommandEvent::Stderr(line) => { eprintln!("stderr: {}", String::from_utf8_lossy(&line)); } CommandEvent::Terminated(payload) => { println!("Process exited: {:?}", payload.code); break; } CommandEvent::Error(err) => { eprintln!("Error: {}", err); break; } } } Ok(()) } ``` -------------------------------- ### write() Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/command-child-rust.md Writes data to the child process's stdin. ```APIDOC ## pub fn write(&mut self, buf: &[u8]) -> crate::Result<()> ### Description Writes data to the child process's stdin. ### Parameters - **buf** (&[u8]) - Required - Bytes to write to stdin ### Returns - **Result<()>** - Success or an I/O error ### Throws - Returns `crate::Error::Io` if the write fails (e.g., broken pipe, process terminated) ``` -------------------------------- ### Rust backend usage Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/README.md Executes commands directly from the Rust backend using the ShellExt trait. Requires the plugin to be registered in the Tauri app builder. ```rust use tauri_plugin_shell::ShellExt; let shell = app.shell(); let output = shell.command("echo").arg("hello").output().await?; ``` -------------------------------- ### Set environment variables for a command Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/command-rust-struct.md Use env() to define individual environment variables for the child process. ```rust use tauri_plugin_shell::process::Command; let cmd = Command::new("python") .env("PYTHONPATH", "/app/lib") .env("DEBUG", "1"); ``` -------------------------------- ### status() Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/command-rust-struct.md Executes the command as a child process, waits for it to finish, and collects its exit status. ```APIDOC ## status() ### Description Executes the command as a child process, waits for it to finish, and collects its exit status. Stdin, stdout, and stderr are ignored. ### Signature `pub async fn status(self) -> crate::Result` ### Returns - `ExitStatus` - Exit status information ``` -------------------------------- ### Command Execution Trigger Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/errors.md Demonstrates successful and failed command execution based on scope configuration. ```typescript // OK: matches "my-app" await Command.create('my-app').execute(); // ERROR: "Scoped command unknown not found" await Command.create('unknown').execute(); ``` -------------------------------- ### write(data: IOPayload | number[]): Promise Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/child-class.md Writes data to the child process's stdin. Accepts strings, Uint8Array, or arrays of bytes. ```APIDOC ## write(data: IOPayload | number[]): Promise ### Description Writes data to the child process's stdin. Resolves when the write is complete. ### Parameters - **data** (IOPayload | number[]) - Required - Data to write (string, Uint8Array, or array of bytes) ### Returns - **Promise** - Resolves when the write is complete. ### Throws - Rejects if the write fails (e.g., if the process has already terminated). ``` -------------------------------- ### Set multiple environment variables using a map Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/command-rust-struct.md Use envs() to apply a collection of environment variables to the command. ```rust use tauri_plugin_shell::process::Command; use std::collections::HashMap; let mut env = HashMap::new(); env.insert("PATH", "/custom/bin"); env.insert("HOME", "/root"); let cmd = Command::new("sh").envs(env); ``` -------------------------------- ### Interact with Running Process Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/process-module.md Writes input to a spawned process and monitors its output stream. ```rust use tauri_plugin_shell::{ShellExt, process::CommandEvent}; use tauri::Manager; async fn interactive_process(app: &tauri::AppHandle) -> crate::Result<()> { let shell = app.shell(); let (mut rx, mut child) = shell.command("python3") .spawn()?; // Send input child.write(b"print('hello')\n")?; child.write(b"exit()\n")?; // Process output while let Some(event) = rx.recv().await { if let CommandEvent::Stdout(line) = event { println!("Output: {}", String::from_utf8_lossy(&line)); } } Ok(()) } ``` -------------------------------- ### prependOnceListener() Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/event-emitter-class.md Adds a one-time listener function to the beginning of the listeners array for the specified event. ```APIDOC ## prependOnceListener(eventName, listener) ### Description Adds a one-time listener function to the beginning of the listeners array for the event. The listener is automatically removed after the event is emitted once. ### Parameters - **eventName** (keyof E) - Required - Name of the event - **listener** ((arg) => void) - Required - Callback function to add once at the beginning ### Returns - **this** - Reference to the emitter for method chaining ``` -------------------------------- ### Command Struct Signature Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/process-module.md The primary builder structure used for spawning system processes. ```rust pub struct Command { ... } ``` -------------------------------- ### Interactive process lifecycle Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/api-reference/command-child-rust.md Pattern for running an interactive process, writing to stdin, and handling various event types. ```rust use tauri_plugin_shell::process::{Command, CommandEvent}; async fn run_interactive_process() -> crate::Result<()> { let (mut rx, mut child) = Command::new("node") .spawn()?; // Write to stdin child.write(b"console.log('test')\n")?; // Process output events while let Some(event) = rx.recv().await { match event { CommandEvent::Stdout(line) => { println!("stdout: {}", String::from_utf8_lossy(&line)); } CommandEvent::Stderr(line) => { eprintln!("stderr: {}", String::from_utf8_lossy(&line)); } CommandEvent::Terminated(payload) => { println!("Process exited: {:?}", payload.code); break; } CommandEvent::Error(err) => { eprintln!("Error: {}", err); break; } } } Ok(()) } ``` -------------------------------- ### Configure Command Scope in capabilities Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/quick-start.md Define allowed commands and sidecars within the application capabilities file. ```json { "permissions": [ { "identifier": "shell:allow-execute", "allow": [ { "name": "my-git-commit", "cmd": "git", "args": ["commit", "-m", { "validator": "\\S+" }] }, { "name": "my-sidecar", "sidecar": true } ] } ] } ``` -------------------------------- ### Handle Shell Command Errors in TypeScript Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/errors.md Demonstrates executing commands with try-catch blocks and monitoring runtime errors via event listeners. ```typescript import { Command } from '@tauri-apps/plugin-shell'; try { const output = await Command.create('echo', 'hello').execute(); console.log('Output:', output.stdout); } catch (error) { // error is a string message console.error('Command failed:', error); // Check error message pattern if (error.includes('program not allowed')) { console.error('Permission denied'); } else if (error.includes('unknown encoding')) { console.error('Invalid encoding option'); } } // Monitoring for runtime errors const cmd = Command.create('long-running-process'); cmd.on('error', (error: string) => { console.error('Process error:', error); }); try { await cmd.spawn(); } catch (error) { console.error('Spawn failed:', error); } ``` -------------------------------- ### Configure fixed arguments Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/configuration.md Restrict command execution to specific, hardcoded arguments. ```json { "name": "ls-home", "cmd": "ls", "args": ["-la", "/home"] } ``` -------------------------------- ### Run a sidecar Source: https://github.com/tauri-apps/tauri-plugin-shell/blob/v2/_autodocs/README.md Executes a sidecar binary bundled with the application. Sidecars must be configured in the project settings. ```typescript const output = await Command.sidecar('my-python-bin', ['script.py']).execute(); ```