LocalCommand

Struct LocalCommand 

Source
pub struct LocalCommand { /* private fields */ }

Implementations§

Source§

impl LocalCommand

Source

pub fn new<S>(program: S) -> Self
where S: AsRef<OsStr>,

Examples found in repository?
examples/error.rs (line 13)
12fn startup(mut commands: Commands) {
13    commands.spawn(LocalCommand::new("commandthatdoesnotexist"));
14}
More examples
Hide additional examples
examples/simple.rs (line 15)
12fn startup(mut commands: Commands) {
13    // Choose the command based on the OS
14    #[cfg(not(windows))]
15    let cmd = LocalCommand::new("sh").args(["-c", "echo Sleeping for 1s && sleep 1 && echo Done"]);
16    #[cfg(windows)]
17    let cmd = LocalCommand::new("powershell").args(["echo 'Sleeping for 1s'; sleep 1; echo Done"]);
18
19    let id = commands.spawn(cmd).id();
20    println!("Spawned the command as entity {id:?}");
21}
examples/despawn_on_completion.rs (line 15)
12fn startup(mut commands: Commands) {
13    // Choose the command based on the OS
14    #[cfg(not(windows))]
15    let cmd = LocalCommand::new("sh").args(["-c", "echo Sleeping for 1s && sleep 1 && echo Done"]);
16    #[cfg(windows)]
17    let cmd = LocalCommand::new("powershell").args(["echo 'Sleeping for 1s'; sleep 1; echo Done"]);
18
19    let id = commands.spawn((cmd, Cleanup::DespawnEntity)).id();
20    println!("Spawned the command as entity {id:?}");
21}
examples/input.rs (line 18)
14fn startup(mut commands: Commands) {
15    // Choose the command based on the OS
16    #[cfg(not(windows))]
17    let cmd =
18        LocalCommand::new("sh").args(["-c", "echo 'Enter Name:' && read NAME && echo Hello $NAME"]);
19    #[cfg(windows)]
20    let cmd = LocalCommand::new("powershell")
21        .args(["$name = Read-Host 'Enter Name'; echo \"Name Entered: $name\""]);
22    let id = commands.spawn(cmd).id();
23    println!("Spawned the command as entity {id:?}");
24}
examples/retries_and_remove.rs (line 17)
14fn startup(mut commands: Commands) {
15    // Choose the command based on the OS
16    #[cfg(not(windows))]
17    let cmd = LocalCommand::new("sh").args(["-c", "echo Sleeping for 1s && sleep 1 && INVALID "]);
18    #[cfg(windows)]
19    let cmd = LocalCommand::new("cmd").args(["/C", "echo Sleeping for 1s && timeout 1 && INVALID"]);
20
21    let id = commands
22        .spawn((cmd, Retry::Attempts(3), Cleanup::RemoveComponents))
23        .id();
24    println!("Spawned the command as temporary entity {id:?} with 3 retries");
25}
examples/kill.rs (line 21)
18fn startup(mut commands: Commands) {
19    // Choose the command based on the OS
20    #[cfg(not(windows))]
21    let cmd = LocalCommand::new("sh").args([
22        "-c",
23        "echo Sleeping for 4s && sleep 4 && echo This should not print or execute && sleep 100",
24    ]);
25    #[cfg(windows)]
26    let cmd = LocalCommand::new("powershell").args([
27        "echo 'Sleeping for 4s'; sleep 4; echo 'This should not print or execute'; sleep 100",
28    ]);
29
30    let id = commands.spawn(cmd).id();
31    println!("Spawned the command as entity {id:?}")
32}
Source

pub fn arg<S: AsRef<OsStr>>(self, arg: S) -> Self

Adds an argument to pass to the program.

Only one argument can be passed per use. So instead of:

.arg("-C /path/to/repo")

usage would be:

.arg("-C")
.arg("/path/to/repo")

To pass multiple arguments see args.

Note that the argument is not passed through a shell, but given literally to the program. This means that shell syntax like quotes, escaped characters, word splitting, glob patterns, variable substitution, etc. have no effect.

Source

pub fn args<I, S>(self, args: I) -> Self
where I: IntoIterator<Item = S>, S: AsRef<OsStr>,

Adds multiple arguments to pass to the program.

To pass a single argument see arg.

Note that the arguments are not passed through a shell, but given literally to the program. This means that shell syntax like quotes, escaped characters, word splitting, glob patterns, variable substitution, etc. have no effect.

Examples found in repository?
examples/simple.rs (line 15)
12fn startup(mut commands: Commands) {
13    // Choose the command based on the OS
14    #[cfg(not(windows))]
15    let cmd = LocalCommand::new("sh").args(["-c", "echo Sleeping for 1s && sleep 1 && echo Done"]);
16    #[cfg(windows)]
17    let cmd = LocalCommand::new("powershell").args(["echo 'Sleeping for 1s'; sleep 1; echo Done"]);
18
19    let id = commands.spawn(cmd).id();
20    println!("Spawned the command as entity {id:?}");
21}
More examples
Hide additional examples
examples/despawn_on_completion.rs (line 15)
12fn startup(mut commands: Commands) {
13    // Choose the command based on the OS
14    #[cfg(not(windows))]
15    let cmd = LocalCommand::new("sh").args(["-c", "echo Sleeping for 1s && sleep 1 && echo Done"]);
16    #[cfg(windows)]
17    let cmd = LocalCommand::new("powershell").args(["echo 'Sleeping for 1s'; sleep 1; echo Done"]);
18
19    let id = commands.spawn((cmd, Cleanup::DespawnEntity)).id();
20    println!("Spawned the command as entity {id:?}");
21}
examples/input.rs (line 18)
14fn startup(mut commands: Commands) {
15    // Choose the command based on the OS
16    #[cfg(not(windows))]
17    let cmd =
18        LocalCommand::new("sh").args(["-c", "echo 'Enter Name:' && read NAME && echo Hello $NAME"]);
19    #[cfg(windows)]
20    let cmd = LocalCommand::new("powershell")
21        .args(["$name = Read-Host 'Enter Name'; echo \"Name Entered: $name\""]);
22    let id = commands.spawn(cmd).id();
23    println!("Spawned the command as entity {id:?}");
24}
examples/retries_and_remove.rs (line 17)
14fn startup(mut commands: Commands) {
15    // Choose the command based on the OS
16    #[cfg(not(windows))]
17    let cmd = LocalCommand::new("sh").args(["-c", "echo Sleeping for 1s && sleep 1 && INVALID "]);
18    #[cfg(windows)]
19    let cmd = LocalCommand::new("cmd").args(["/C", "echo Sleeping for 1s && timeout 1 && INVALID"]);
20
21    let id = commands
22        .spawn((cmd, Retry::Attempts(3), Cleanup::RemoveComponents))
23        .id();
24    println!("Spawned the command as temporary entity {id:?} with 3 retries");
25}
examples/kill.rs (lines 21-24)
18fn startup(mut commands: Commands) {
19    // Choose the command based on the OS
20    #[cfg(not(windows))]
21    let cmd = LocalCommand::new("sh").args([
22        "-c",
23        "echo Sleeping for 4s && sleep 4 && echo This should not print or execute && sleep 100",
24    ]);
25    #[cfg(windows)]
26    let cmd = LocalCommand::new("powershell").args([
27        "echo 'Sleeping for 4s'; sleep 4; echo 'This should not print or execute'; sleep 100",
28    ]);
29
30    let id = commands.spawn(cmd).id();
31    println!("Spawned the command as entity {id:?}")
32}
examples/retries_and_delay.rs (line 19)
15fn startup(mut commands: Commands) {
16    // Choose the command based on the OS
17    #[cfg(not(windows))]
18    let cmd =
19        LocalCommand::new("sh").args(["-c", "echo Sleeping for 1s && sleep 1 && THIS SHOULD FAIL"]);
20    #[cfg(windows)]
21    let cmd = LocalCommand::new("cmd").args([
22        "/C",
23        "echo Sleeping for 1s && timeout 1 && THIS SHOULD FAIL",
24    ]);
25
26    let id = commands
27        .spawn((
28            cmd,
29            Retry::Attempts(2),
30            Delay::Fixed(Duration::from_secs(2)),
31        ))
32        .id();
33    println!("Spawned the command as entity {id:?} with 2 retries and a 2s delay");
34}
Source

pub fn env<K, V>(self, key: K, val: V) -> Self
where K: AsRef<OsStr>, V: AsRef<OsStr>,

Inserts or updates an explicit environment variable mapping.

This method allows you to add an environment variable mapping to the spawned process or overwrite a previously set value. You can use LocalCommand::envs to set multiple environment variables simultaneously.

Child processes will inherit environment variables from their parent process by default. Environment variables explicitly set using LocalCommand::env take precedence over inherited variables. You can disable environment variable inheritance entirely using LocalCommand::env_clear or for a single key using LocalCommand::env_remove.

Note that environment variable names are case-insensitive (but case-preserving) on Windows and case-sensitive on all other platforms.

Source

pub fn envs<I, K, V>(self, vars: I) -> Self
where I: IntoIterator<Item = (K, V)>, K: AsRef<OsStr>, V: AsRef<OsStr>,

Inserts or updates multiple explicit environment variable mappings.

This method allows you to add multiple environment variable mappings to the spawned process or overwrite previously set values. You can use LocalCommand::env to set a single environment variable.

Child processes will inherit environment variables from their parent process by default. Environment variables explicitly set using LocalCommand::envs take precedence over inherited variables. You can disable environment variable inheritance entirely using LocalCommand::env_clear or for a single key using LocalCommand::env_remove.

Note that environment variable names are case-insensitive (but case-preserving) on Windows and case-sensitive on all other platforms.

Source

pub fn env_remove<K: AsRef<OsStr>>(self, key: K) -> Self

Removes an explicitly set environment variable and prevents inheriting it from a parent process.

This method will remove the explicit value of an environment variable set via LocalCommand::env or LocalCommand::envs. In addition, it will prevent the spawned child process from inheriting that environment variable from its parent process.

After calling LocalCommand::env_remove, the value associated with its key from LocalCommand::get_envs will be None.

To clear all explicitly set environment variables and disable all environment variable inheritance, you can use LocalCommand::env_clear.

Source

pub fn env_clear(self) -> Self

Clears all explicitly set environment variables and prevents inheriting any parent process environment variables.

This method will remove all explicitly added environment variables set via LocalCommand::env or LocalCommand::envs. In addition, it will prevent the spawned child process from inheriting any environment variable from its parent process.

After calling LocalCommand::env_clear, the iterator from LocalCommand::get_envs will be empty.

You can use LocalCommand::env_remove to clear a single mapping.

Source

pub fn current_dir<P: AsRef<Path>>(self, dir: P) -> Self

Sets the working directory for the child process.

§Platform-specific behavior

If the program path is relative (e.g., "./script.sh"), it’s ambiguous whether it should be interpreted relative to the parent’s working directory or relative to current_dir. The behavior in this case is platform specific and unstable, and it’s recommended to use canonicalize to get an absolute program path instead.

Source

pub fn get_program(&self) -> &OsStr

Returns the path to the program that was given to LocalCommand::new.

§Examples
use bevy_local_commands::LocalCommand;

let cmd = LocalCommand::new("echo");
assert_eq!(cmd.get_program(), "echo");
Examples found in repository?
examples/retries_and_delay.rs (line 45)
36fn update(
37    mut process_completed_event: MessageReader<ProcessCompleted>,
38    query: Query<&LocalCommand, With<Retry>>,
39    mut retry_events: MessageReader<RetryEvent>,
40) {
41    if let Some(process_completed) = process_completed_event.read().last() {
42        if let Ok(local_command) = query.get(process_completed.entity) {
43            println!(
44                "Command {:?} {:?} completed (Success - {})",
45                local_command.get_program(),
46                local_command.get_args(),
47                process_completed.exit_status.success()
48            );
49        } else {
50            println!("Retry component removed from entity, exiting");
51            std::process::exit(0);
52        }
53    }
54    for retry_event in retry_events.read() {
55        println!("Retry event triggered: {:?}", retry_event);
56    }
57}
More examples
Hide additional examples
examples/retries_and_delay_and_cleanup.rs (line 46)
37fn update(
38    mut process_completed_event: MessageReader<ProcessCompleted>,
39    query: Query<&LocalCommand, With<Retry>>,
40    mut retry_events: MessageReader<RetryEvent>,
41) {
42    if let Some(process_completed) = process_completed_event.read().last() {
43        if let Ok(local_command) = query.get(process_completed.entity) {
44            println!(
45                "Command {:?} {:?} completed (Success - {})",
46                local_command.get_program(),
47                local_command.get_args(),
48                process_completed.exit_status.success()
49            );
50        } else {
51            println!("Retry component removed from entity, exiting");
52            std::process::exit(0);
53        }
54    }
55    for retry_event in retry_events.read() {
56        println!("Retry event triggered: {:?}", retry_event);
57    }
58}
Source

pub fn get_args(&self) -> CommandArgs<'_>

Returns an iterator of the arguments that will be passed to the program.

This does not include the path to the program as the first argument; it only includes the arguments specified with LocalCommand::arg and LocalCommand::args.

§Examples
use std::ffi::OsStr;
use bevy_local_commands::LocalCommand;

let mut cmd = LocalCommand::new("echo").arg("first").arg("second");
let args: Vec<&OsStr> = cmd.get_args().collect();
assert_eq!(args, &["first", "second"]);
Examples found in repository?
examples/retries_and_delay.rs (line 46)
36fn update(
37    mut process_completed_event: MessageReader<ProcessCompleted>,
38    query: Query<&LocalCommand, With<Retry>>,
39    mut retry_events: MessageReader<RetryEvent>,
40) {
41    if let Some(process_completed) = process_completed_event.read().last() {
42        if let Ok(local_command) = query.get(process_completed.entity) {
43            println!(
44                "Command {:?} {:?} completed (Success - {})",
45                local_command.get_program(),
46                local_command.get_args(),
47                process_completed.exit_status.success()
48            );
49        } else {
50            println!("Retry component removed from entity, exiting");
51            std::process::exit(0);
52        }
53    }
54    for retry_event in retry_events.read() {
55        println!("Retry event triggered: {:?}", retry_event);
56    }
57}
More examples
Hide additional examples
examples/retries_and_delay_and_cleanup.rs (line 47)
37fn update(
38    mut process_completed_event: MessageReader<ProcessCompleted>,
39    query: Query<&LocalCommand, With<Retry>>,
40    mut retry_events: MessageReader<RetryEvent>,
41) {
42    if let Some(process_completed) = process_completed_event.read().last() {
43        if let Ok(local_command) = query.get(process_completed.entity) {
44            println!(
45                "Command {:?} {:?} completed (Success - {})",
46                local_command.get_program(),
47                local_command.get_args(),
48                process_completed.exit_status.success()
49            );
50        } else {
51            println!("Retry component removed from entity, exiting");
52            std::process::exit(0);
53        }
54    }
55    for retry_event in retry_events.read() {
56        println!("Retry event triggered: {:?}", retry_event);
57    }
58}
Source

pub fn get_envs(&self) -> CommandEnvs<'_>

Returns an iterator of the environment variables explicitly set for the child process.

Environment variables explicitly set using LocalCommand::env, LocalCommand::envs, and LocalCommand::env_remove can be retrieved with this method.

Note that this output does not include environment variables inherited from the parent process.

Each element is a tuple key/value pair (&OsStr, Option<&OsStr>). A None value indicates its key was explicitly removed via LocalCommand::env_remove. The associated key for the None value will no longer inherit from its parent process.

An empty iterator can indicate that no explicit mappings were added or that LocalCommand::env_clear was called. After calling LocalCommand::env_clear, the child process will not inherit any environment variables from its parent process.

§Examples
use std::ffi::OsStr;
use bevy_local_commands::LocalCommand;

let mut cmd = LocalCommand::new("ls").env("TERM", "dumb").env_remove("TZ");
let envs: Vec<(&OsStr, Option<&OsStr>)> = cmd.get_envs().collect();
assert_eq!(envs, &[
    (OsStr::new("TERM"), Some(OsStr::new("dumb"))),
    (OsStr::new("TZ"), None)
]);
Source

pub fn get_current_dir(&self) -> Option<&Path>

Returns the working directory for the child process.

This returns None if the working directory will not be changed.

§Examples
use std::path::Path;
use bevy_local_commands::LocalCommand;

let mut cmd = LocalCommand::new("ls");
assert_eq!(cmd.get_current_dir(), None);
cmd = cmd.current_dir("/bin");
assert_eq!(cmd.get_current_dir(), Some(Path::new("/bin")));

Trait Implementations§

Source§

impl Component for LocalCommand
where Self: Send + Sync + 'static,

Source§

const STORAGE_TYPE: StorageType = ::bevy::ecs::component::StorageType::Table

A constant indicating the storage type used for this component.
Source§

type Mutability = Mutable

A marker type to assist Bevy with determining if this component is mutable, or immutable. Mutable components will have Component<Mutability = Mutable>, while immutable components will instead have Component<Mutability = Immutable>. Read more
Source§

fn register_required_components( _requiree: ComponentId, required_components: &mut RequiredComponentsRegistrator<'_, '_>, )

Registers required components. Read more
Source§

fn clone_behavior() -> ComponentCloneBehavior

Called when registering this component, allowing to override clone function (or disable cloning altogether) for this component. Read more
Source§

fn on_add() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_add ComponentHook for this Component if one is defined.
Source§

fn on_insert() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_insert ComponentHook for this Component if one is defined.
Source§

fn on_replace() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_replace ComponentHook for this Component if one is defined.
Source§

fn on_remove() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_remove ComponentHook for this Component if one is defined.
Source§

fn on_despawn() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_despawn ComponentHook for this Component if one is defined.
Source§

fn map_entities<E>(_this: &mut Self, _mapper: &mut E)
where E: EntityMapper,

Maps the entities on this component using the given EntityMapper. This is used to remap entities in contexts like scenes and entity cloning. When deriving Component, this is populated by annotating fields containing entities with #[entities] Read more
Source§

impl Debug for LocalCommand

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl From<Command> for LocalCommand

Source§

fn from(command: Command) -> Self

Converts to this type from the input type.
Source§

impl From<LocalCommand> for Command

Source§

fn from(value: LocalCommand) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<C> Bundle for C
where C: Component,

Source§

fn component_ids( components: &mut ComponentsRegistrator<'_>, ids: &mut impl FnMut(ComponentId), )

Source§

fn get_component_ids( components: &Components, ids: &mut impl FnMut(Option<ComponentId>), )

Gets this Bundle’s component ids. This will be None if the component has not been registered.
Source§

impl<C> BundleFromComponents for C
where C: Component,

Source§

unsafe fn from_components<T, F>(ctx: &mut T, func: &mut F) -> C
where F: for<'a> FnMut(&'a mut T) -> OwningPtr<'a>,

Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<C> DynamicBundle for C
where C: Component,

Source§

type Effect = ()

An operation on the entity that happens after inserting this bundle.
Source§

unsafe fn get_components( ptr: MovingPtr<'_, C>, func: &mut impl FnMut(StorageType, OwningPtr<'_>), ) -> <C as DynamicBundle>::Effect

Moves the components out of the bundle. Read more
Source§

unsafe fn apply_effect( _ptr: MovingPtr<'_, MaybeUninit<C>>, _entity: &mut EntityWorldMut<'_>, )

Applies the after-effects of spawning this bundle. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoResult<T> for T

Source§

fn into_result(self) -> Result<T, RunSystemError>

Converts this type into the system output type.
Source§

impl<A> Is for A
where A: Any,

Source§

fn is<T>() -> bool
where T: Any,

Checks if the current type “is” another type, using a TypeId equality comparison. This is most useful in the context of generic logic. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ConditionalSend for T
where T: Send,