pub struct Command { /* private fields */ }
process-command-api
only.Expand description
The type to spawn commands.
Implementations§
source§impl Command
impl Command
sourcepub fn new<S: Into<String>>(program: S) -> Self
pub fn new<S: Into<String>>(program: S) -> Self
Creates a new Command for launching the given program.
Examples found in repository?
More examples
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
pub fn _prepare(
&self,
command_name: &str,
args: ExecuteArgs,
sidecar: Option<&str>,
) -> Result<Command, ScopeError> {
let command = match self.0.scopes.get(command_name) {
Some(command) => command,
None => return Err(ScopeError::NotFound(command_name.into())),
};
if command.sidecar != sidecar.is_some() {
return Err(ScopeError::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(|| ScopeError::MissingVar(i, validator.to_string()))?
.to_string();
if validator.is_match(&value) {
Ok(value)
} else {
Err(ScopeError::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(ScopeError::InvalidInput(command_name.into())),
(Some(_), _) => Err(ScopeError::InvalidInput(command_name.into())),
}?;
let command_s = sidecar
.map(|s| {
std::path::PathBuf::from(s)
.components()
.last()
.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(ScopeError::Sidecar)?
} else {
Command::new(command_s)
};
Ok(command.args(args))
}
sourcepub fn new_sidecar<S: Into<String>>(program: S) -> Result<Self>
pub fn new_sidecar<S: Into<String>>(program: S) -> Result<Self>
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).
Examples found in repository?
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
pub fn _prepare(
&self,
command_name: &str,
args: ExecuteArgs,
sidecar: Option<&str>,
) -> Result<Command, ScopeError> {
let command = match self.0.scopes.get(command_name) {
Some(command) => command,
None => return Err(ScopeError::NotFound(command_name.into())),
};
if command.sidecar != sidecar.is_some() {
return Err(ScopeError::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(|| ScopeError::MissingVar(i, validator.to_string()))?
.to_string();
if validator.is_match(&value) {
Ok(value)
} else {
Err(ScopeError::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(ScopeError::InvalidInput(command_name.into())),
(Some(_), _) => Err(ScopeError::InvalidInput(command_name.into())),
}?;
let command_s = sidecar
.map(|s| {
std::path::PathBuf::from(s)
.components()
.last()
.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(ScopeError::Sidecar)?
} else {
Command::new(command_s)
};
Ok(command.args(args))
}
sourcepub fn args<I, S>(self, args: I) -> Selfwhere
I: IntoIterator<Item = S>,
S: AsRef<str>,
pub fn args<I, S>(self, args: I) -> Selfwhere
I: IntoIterator<Item = S>,
S: AsRef<str>,
Appends arguments to the command.
Examples found in repository?
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
pub fn _prepare(
&self,
command_name: &str,
args: ExecuteArgs,
sidecar: Option<&str>,
) -> Result<Command, ScopeError> {
let command = match self.0.scopes.get(command_name) {
Some(command) => command,
None => return Err(ScopeError::NotFound(command_name.into())),
};
if command.sidecar != sidecar.is_some() {
return Err(ScopeError::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(|| ScopeError::MissingVar(i, validator.to_string()))?
.to_string();
if validator.is_match(&value) {
Ok(value)
} else {
Err(ScopeError::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(ScopeError::InvalidInput(command_name.into())),
(Some(_), _) => Err(ScopeError::InvalidInput(command_name.into())),
}?;
let command_s = sidecar
.map(|s| {
std::path::PathBuf::from(s)
.components()
.last()
.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(ScopeError::Sidecar)?
} else {
Command::new(command_s)
};
Ok(command.args(args))
}
sourcepub fn env_clear(self) -> Self
pub fn env_clear(self) -> Self
Clears the entire environment map for the child process.
Examples found in repository?
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
fn execute<R: Runtime>(
context: InvokeContext<R>,
program: String,
args: ExecuteArgs,
on_event_fn: CallbackFn,
options: CommandOptions,
) -> super::Result<ChildId> {
let mut command = if options.sidecar {
#[cfg(not(shell_sidecar))]
return Err(crate::Error::ApiNotAllowlisted("shell > sidecar".to_string()).into_anyhow());
#[cfg(shell_sidecar)]
{
let program = PathBuf::from(program);
let program_as_string = program.display().to_string();
let program_no_ext_as_string = program.with_extension("").display().to_string();
let configured_sidecar = context
.config
.tauri
.bundle
.external_bin
.as_ref()
.map(|bins| {
bins
.iter()
.find(|b| b == &&program_as_string || b == &&program_no_ext_as_string)
})
.unwrap_or_default();
if let Some(sidecar) = configured_sidecar {
context
.window
.state::<Scopes>()
.shell
.prepare_sidecar(&program.to_string_lossy(), sidecar, args)
.map_err(crate::error::into_anyhow)?
} else {
return Err(crate::Error::SidecarNotAllowed(program).into_anyhow());
}
}
} else {
#[cfg(not(shell_execute))]
return Err(crate::Error::ApiNotAllowlisted("shell > execute".to_string()).into_anyhow());
#[cfg(shell_execute)]
match context
.window
.state::<Scopes>()
.shell
.prepare(&program, args)
{
Ok(cmd) => cmd,
Err(e) => {
#[cfg(debug_assertions)]
eprintln!("{}", e);
return Err(crate::Error::ProgramNotAllowed(PathBuf::from(program)).into_anyhow());
}
}
};
#[cfg(any(shell_execute, shell_sidecar))]
{
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();
}
if let Some(encoding) = options.encoding {
if let Some(encoding) = crate::api::process::Encoding::for_label(encoding.as_bytes()) {
command = command.encoding(encoding);
} else {
return Err(anyhow::anyhow!(format!("unknown encoding {}", encoding)));
}
}
let (mut rx, child) = command.spawn()?;
let pid = child.pid();
command_child_store().lock().unwrap().insert(pid, child);
crate::async_runtime::spawn(async move {
while let Some(event) = rx.recv().await {
if matches!(event, crate::api::process::CommandEvent::Terminated(_)) {
command_child_store().lock().unwrap().remove(&pid);
}
let js = crate::api::ipc::format_callback(on_event_fn, &event)
.expect("unable to serialize CommandEvent");
let _ = context.window.eval(js.as_str());
}
});
Ok(pid)
}
}
sourcepub fn envs(self, env: HashMap<String, String>) -> Self
pub fn envs(self, env: HashMap<String, String>) -> Self
Adds or updates multiple environment variable mappings.
Examples found in repository?
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
fn execute<R: Runtime>(
context: InvokeContext<R>,
program: String,
args: ExecuteArgs,
on_event_fn: CallbackFn,
options: CommandOptions,
) -> super::Result<ChildId> {
let mut command = if options.sidecar {
#[cfg(not(shell_sidecar))]
return Err(crate::Error::ApiNotAllowlisted("shell > sidecar".to_string()).into_anyhow());
#[cfg(shell_sidecar)]
{
let program = PathBuf::from(program);
let program_as_string = program.display().to_string();
let program_no_ext_as_string = program.with_extension("").display().to_string();
let configured_sidecar = context
.config
.tauri
.bundle
.external_bin
.as_ref()
.map(|bins| {
bins
.iter()
.find(|b| b == &&program_as_string || b == &&program_no_ext_as_string)
})
.unwrap_or_default();
if let Some(sidecar) = configured_sidecar {
context
.window
.state::<Scopes>()
.shell
.prepare_sidecar(&program.to_string_lossy(), sidecar, args)
.map_err(crate::error::into_anyhow)?
} else {
return Err(crate::Error::SidecarNotAllowed(program).into_anyhow());
}
}
} else {
#[cfg(not(shell_execute))]
return Err(crate::Error::ApiNotAllowlisted("shell > execute".to_string()).into_anyhow());
#[cfg(shell_execute)]
match context
.window
.state::<Scopes>()
.shell
.prepare(&program, args)
{
Ok(cmd) => cmd,
Err(e) => {
#[cfg(debug_assertions)]
eprintln!("{}", e);
return Err(crate::Error::ProgramNotAllowed(PathBuf::from(program)).into_anyhow());
}
}
};
#[cfg(any(shell_execute, shell_sidecar))]
{
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();
}
if let Some(encoding) = options.encoding {
if let Some(encoding) = crate::api::process::Encoding::for_label(encoding.as_bytes()) {
command = command.encoding(encoding);
} else {
return Err(anyhow::anyhow!(format!("unknown encoding {}", encoding)));
}
}
let (mut rx, child) = command.spawn()?;
let pid = child.pid();
command_child_store().lock().unwrap().insert(pid, child);
crate::async_runtime::spawn(async move {
while let Some(event) = rx.recv().await {
if matches!(event, crate::api::process::CommandEvent::Terminated(_)) {
command_child_store().lock().unwrap().remove(&pid);
}
let js = crate::api::ipc::format_callback(on_event_fn, &event)
.expect("unable to serialize CommandEvent");
let _ = context.window.eval(js.as_str());
}
});
Ok(pid)
}
}
sourcepub fn current_dir(self, current_dir: PathBuf) -> Self
pub fn current_dir(self, current_dir: PathBuf) -> Self
Sets the working directory for the child process.
Examples found in repository?
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
fn execute<R: Runtime>(
context: InvokeContext<R>,
program: String,
args: ExecuteArgs,
on_event_fn: CallbackFn,
options: CommandOptions,
) -> super::Result<ChildId> {
let mut command = if options.sidecar {
#[cfg(not(shell_sidecar))]
return Err(crate::Error::ApiNotAllowlisted("shell > sidecar".to_string()).into_anyhow());
#[cfg(shell_sidecar)]
{
let program = PathBuf::from(program);
let program_as_string = program.display().to_string();
let program_no_ext_as_string = program.with_extension("").display().to_string();
let configured_sidecar = context
.config
.tauri
.bundle
.external_bin
.as_ref()
.map(|bins| {
bins
.iter()
.find(|b| b == &&program_as_string || b == &&program_no_ext_as_string)
})
.unwrap_or_default();
if let Some(sidecar) = configured_sidecar {
context
.window
.state::<Scopes>()
.shell
.prepare_sidecar(&program.to_string_lossy(), sidecar, args)
.map_err(crate::error::into_anyhow)?
} else {
return Err(crate::Error::SidecarNotAllowed(program).into_anyhow());
}
}
} else {
#[cfg(not(shell_execute))]
return Err(crate::Error::ApiNotAllowlisted("shell > execute".to_string()).into_anyhow());
#[cfg(shell_execute)]
match context
.window
.state::<Scopes>()
.shell
.prepare(&program, args)
{
Ok(cmd) => cmd,
Err(e) => {
#[cfg(debug_assertions)]
eprintln!("{}", e);
return Err(crate::Error::ProgramNotAllowed(PathBuf::from(program)).into_anyhow());
}
}
};
#[cfg(any(shell_execute, shell_sidecar))]
{
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();
}
if let Some(encoding) = options.encoding {
if let Some(encoding) = crate::api::process::Encoding::for_label(encoding.as_bytes()) {
command = command.encoding(encoding);
} else {
return Err(anyhow::anyhow!(format!("unknown encoding {}", encoding)));
}
}
let (mut rx, child) = command.spawn()?;
let pid = child.pid();
command_child_store().lock().unwrap().insert(pid, child);
crate::async_runtime::spawn(async move {
while let Some(event) = rx.recv().await {
if matches!(event, crate::api::process::CommandEvent::Terminated(_)) {
command_child_store().lock().unwrap().remove(&pid);
}
let js = crate::api::ipc::format_callback(on_event_fn, &event)
.expect("unable to serialize CommandEvent");
let _ = context.window.eval(js.as_str());
}
});
Ok(pid)
}
}
sourcepub fn encoding(self, encoding: &'static Encoding) -> Self
pub fn encoding(self, encoding: &'static Encoding) -> Self
Sets the character encoding for stdout/stderr.
Examples found in repository?
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
fn execute<R: Runtime>(
context: InvokeContext<R>,
program: String,
args: ExecuteArgs,
on_event_fn: CallbackFn,
options: CommandOptions,
) -> super::Result<ChildId> {
let mut command = if options.sidecar {
#[cfg(not(shell_sidecar))]
return Err(crate::Error::ApiNotAllowlisted("shell > sidecar".to_string()).into_anyhow());
#[cfg(shell_sidecar)]
{
let program = PathBuf::from(program);
let program_as_string = program.display().to_string();
let program_no_ext_as_string = program.with_extension("").display().to_string();
let configured_sidecar = context
.config
.tauri
.bundle
.external_bin
.as_ref()
.map(|bins| {
bins
.iter()
.find(|b| b == &&program_as_string || b == &&program_no_ext_as_string)
})
.unwrap_or_default();
if let Some(sidecar) = configured_sidecar {
context
.window
.state::<Scopes>()
.shell
.prepare_sidecar(&program.to_string_lossy(), sidecar, args)
.map_err(crate::error::into_anyhow)?
} else {
return Err(crate::Error::SidecarNotAllowed(program).into_anyhow());
}
}
} else {
#[cfg(not(shell_execute))]
return Err(crate::Error::ApiNotAllowlisted("shell > execute".to_string()).into_anyhow());
#[cfg(shell_execute)]
match context
.window
.state::<Scopes>()
.shell
.prepare(&program, args)
{
Ok(cmd) => cmd,
Err(e) => {
#[cfg(debug_assertions)]
eprintln!("{}", e);
return Err(crate::Error::ProgramNotAllowed(PathBuf::from(program)).into_anyhow());
}
}
};
#[cfg(any(shell_execute, shell_sidecar))]
{
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();
}
if let Some(encoding) = options.encoding {
if let Some(encoding) = crate::api::process::Encoding::for_label(encoding.as_bytes()) {
command = command.encoding(encoding);
} else {
return Err(anyhow::anyhow!(format!("unknown encoding {}", encoding)));
}
}
let (mut rx, child) = command.spawn()?;
let pid = child.pid();
command_child_store().lock().unwrap().insert(pid, child);
crate::async_runtime::spawn(async move {
while let Some(event) = rx.recv().await {
if matches!(event, crate::api::process::CommandEvent::Terminated(_)) {
command_child_store().lock().unwrap().remove(&pid);
}
let js = crate::api::ipc::format_callback(on_event_fn, &event)
.expect("unable to serialize CommandEvent");
let _ = context.window.eval(js.as_str());
}
});
Ok(pid)
}
}
sourcepub fn spawn(self) -> Result<(Receiver<CommandEvent>, CommandChild)>
pub fn spawn(self) -> Result<(Receiver<CommandEvent>, CommandChild)>
Spawns the command.
Examples
use tauri::api::process::{Command, CommandEvent};
tauri::async_runtime::spawn(async move {
let (mut rx, mut child) = Command::new("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: {}", line);
i += 1;
if i == 4 {
child.write("message from Rust\n".as_bytes()).unwrap();
i = 0;
}
}
}
});
Examples found in repository?
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
pub fn status(self) -> crate::api::Result<ExitStatus> {
let (mut rx, _child) = self.spawn()?;
let code = crate::async_runtime::safe_block_on(async move {
let mut code = None;
#[allow(clippy::collapsible_match)]
while let Some(event) = rx.recv().await {
if let CommandEvent::Terminated(payload) = event {
code = payload.code;
}
}
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::api::process::Command;
/// let output = Command::new("echo").args(["TAURI"]).output().unwrap();
/// assert!(output.status.success());
/// assert_eq!(output.stdout, "TAURI");
/// ```
pub fn output(self) -> crate::api::Result<Output> {
let (mut rx, _child) = self.spawn()?;
let output = crate::async_runtime::safe_block_on(async move {
let mut code = None;
let mut stdout = String::new();
let mut stderr = String::new();
while let Some(event) = rx.recv().await {
match event {
CommandEvent::Terminated(payload) => {
code = payload.code;
}
CommandEvent::Stdout(line) => {
stdout.push_str(line.as_str());
stdout.push('\n');
}
CommandEvent::Stderr(line) => {
stderr.push_str(line.as_str());
stderr.push('\n');
}
CommandEvent::Error(_) => {}
}
}
Output {
status: ExitStatus { code },
stdout,
stderr,
}
});
Ok(output)
}
More examples
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
fn execute<R: Runtime>(
context: InvokeContext<R>,
program: String,
args: ExecuteArgs,
on_event_fn: CallbackFn,
options: CommandOptions,
) -> super::Result<ChildId> {
let mut command = if options.sidecar {
#[cfg(not(shell_sidecar))]
return Err(crate::Error::ApiNotAllowlisted("shell > sidecar".to_string()).into_anyhow());
#[cfg(shell_sidecar)]
{
let program = PathBuf::from(program);
let program_as_string = program.display().to_string();
let program_no_ext_as_string = program.with_extension("").display().to_string();
let configured_sidecar = context
.config
.tauri
.bundle
.external_bin
.as_ref()
.map(|bins| {
bins
.iter()
.find(|b| b == &&program_as_string || b == &&program_no_ext_as_string)
})
.unwrap_or_default();
if let Some(sidecar) = configured_sidecar {
context
.window
.state::<Scopes>()
.shell
.prepare_sidecar(&program.to_string_lossy(), sidecar, args)
.map_err(crate::error::into_anyhow)?
} else {
return Err(crate::Error::SidecarNotAllowed(program).into_anyhow());
}
}
} else {
#[cfg(not(shell_execute))]
return Err(crate::Error::ApiNotAllowlisted("shell > execute".to_string()).into_anyhow());
#[cfg(shell_execute)]
match context
.window
.state::<Scopes>()
.shell
.prepare(&program, args)
{
Ok(cmd) => cmd,
Err(e) => {
#[cfg(debug_assertions)]
eprintln!("{}", e);
return Err(crate::Error::ProgramNotAllowed(PathBuf::from(program)).into_anyhow());
}
}
};
#[cfg(any(shell_execute, shell_sidecar))]
{
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();
}
if let Some(encoding) = options.encoding {
if let Some(encoding) = crate::api::process::Encoding::for_label(encoding.as_bytes()) {
command = command.encoding(encoding);
} else {
return Err(anyhow::anyhow!(format!("unknown encoding {}", encoding)));
}
}
let (mut rx, child) = command.spawn()?;
let pid = child.pid();
command_child_store().lock().unwrap().insert(pid, child);
crate::async_runtime::spawn(async move {
while let Some(event) = rx.recv().await {
if matches!(event, crate::api::process::CommandEvent::Terminated(_)) {
command_child_store().lock().unwrap().remove(&pid);
}
let js = crate::api::ipc::format_callback(on_event_fn, &event)
.expect("unable to serialize CommandEvent");
let _ = context.window.eval(js.as_str());
}
});
Ok(pid)
}
}
sourcepub fn status(self) -> Result<ExitStatus>
pub fn status(self) -> Result<ExitStatus>
Executes a command as a child process, waiting for it to finish and collecting its exit status. Stdin, stdout and stderr are ignored.
Examples
use tauri::api::process::Command;
let status = Command::new("which").args(["ls"]).status().unwrap();
println!("`which` finished with status: {:?}", status.code());
sourcepub fn output(self) -> Result<Output>
pub fn output(self) -> Result<Output>
Executes the command as a child process, waiting for it to finish and collecting all of its output. Stdin is ignored.
Examples
use tauri::api::process::Command;
let output = Command::new("echo").args(["TAURI"]).output().unwrap();
assert!(output.status.success());
assert_eq!(output.stdout, "TAURI");