pub struct LocalCommand { /* private fields */ }Implementations§
Source§impl LocalCommand
impl LocalCommand
Sourcepub fn new<S>(program: S) -> Self
pub fn new<S>(program: S) -> Self
Examples found in repository?
More examples
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}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}Sourcepub fn arg<S: AsRef<OsStr>>(self, arg: S) -> Self
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.
Sourcepub fn args<I, S>(self, args: I) -> Self
pub fn args<I, S>(self, args: I) -> Self
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?
More examples
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}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}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}Sourcepub fn env<K, V>(self, key: K, val: V) -> Self
pub fn env<K, V>(self, key: K, val: V) -> Self
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.
Sourcepub fn envs<I, K, V>(self, vars: I) -> Self
pub fn envs<I, K, V>(self, vars: I) -> Self
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.
Sourcepub fn env_remove<K: AsRef<OsStr>>(self, key: K) -> Self
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.
Sourcepub fn env_clear(self) -> Self
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.
Sourcepub fn current_dir<P: AsRef<Path>>(self, dir: P) -> Self
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.
Sourcepub fn get_program(&self) -> &OsStr
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?
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
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}Sourcepub fn get_args(&self) -> CommandArgs<'_>
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?
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
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}Sourcepub fn get_envs(&self) -> CommandEnvs<'_>
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)
]);Sourcepub fn get_current_dir(&self) -> Option<&Path>
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
impl Component for LocalCommand
Source§const STORAGE_TYPE: StorageType = ::bevy::ecs::component::StorageType::Table
const STORAGE_TYPE: StorageType = ::bevy::ecs::component::StorageType::Table
Source§type Mutability = Mutable
type Mutability = Mutable
Component<Mutability = Mutable>,
while immutable components will instead have Component<Mutability = Immutable>. Read moreSource§fn register_required_components(
_requiree: ComponentId,
required_components: &mut RequiredComponentsRegistrator<'_, '_>,
)
fn register_required_components( _requiree: ComponentId, required_components: &mut RequiredComponentsRegistrator<'_, '_>, )
Source§fn clone_behavior() -> ComponentCloneBehavior
fn clone_behavior() -> ComponentCloneBehavior
Source§fn on_add() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
fn on_add() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
Source§fn on_insert() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
fn on_insert() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
Source§fn on_replace() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
fn on_replace() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
Source§fn on_remove() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
fn on_remove() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
Source§fn on_despawn() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
fn on_despawn() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
Source§fn map_entities<E>(_this: &mut Self, _mapper: &mut E)where
E: EntityMapper,
fn map_entities<E>(_this: &mut Self, _mapper: &mut E)where
E: EntityMapper,
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 moreSource§impl Debug for LocalCommand
impl Debug for LocalCommand
Source§impl From<Command> for LocalCommand
impl From<Command> for LocalCommand
Source§impl From<LocalCommand> for Command
impl From<LocalCommand> for Command
Source§fn from(value: LocalCommand) -> Self
fn from(value: LocalCommand) -> Self
Auto Trait Implementations§
impl Freeze for LocalCommand
impl RefUnwindSafe for LocalCommand
impl Send for LocalCommand
impl Sync for LocalCommand
impl Unpin for LocalCommand
impl UnwindSafe for LocalCommand
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<C> Bundle for Cwhere
C: Component,
impl<C> Bundle for Cwhere
C: Component,
fn component_ids( components: &mut ComponentsRegistrator<'_>, ids: &mut impl FnMut(ComponentId), )
Source§fn get_component_ids(
components: &Components,
ids: &mut impl FnMut(Option<ComponentId>),
)
fn get_component_ids( components: &Components, ids: &mut impl FnMut(Option<ComponentId>), )
Source§impl<C> BundleFromComponents for Cwhere
C: Component,
impl<C> BundleFromComponents for Cwhere
C: Component,
Source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
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>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
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)
fn as_any(&self) -> &(dyn Any + 'static)
&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)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&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
impl<T> DowncastSend for T
Source§impl<C> DynamicBundle for Cwhere
C: Component,
impl<C> DynamicBundle for Cwhere
C: Component,
Source§unsafe fn get_components(
ptr: MovingPtr<'_, C>,
func: &mut impl FnMut(StorageType, OwningPtr<'_>),
) -> <C as DynamicBundle>::Effect
unsafe fn get_components( ptr: MovingPtr<'_, C>, func: &mut impl FnMut(StorageType, OwningPtr<'_>), ) -> <C as DynamicBundle>::Effect
Source§unsafe fn apply_effect(
_ptr: MovingPtr<'_, MaybeUninit<C>>,
_entity: &mut EntityWorldMut<'_>,
)
unsafe fn apply_effect( _ptr: MovingPtr<'_, MaybeUninit<C>>, _entity: &mut EntityWorldMut<'_>, )
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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