conch_runtime_pshaw/spawn/
loop_cmd.rs

1use crate::env::LastStatusEnvironment;
2use crate::spawn::Spawn;
3use crate::{ExitStatus, EXIT_SUCCESS};
4use std::future::Future;
5use std::pin::Pin;
6use std::task::{Context, Poll};
7
8/// Spawns a loop command such as `while` or `until` using a guard and a body.
9///
10/// The guard will be repeatedly executed and its exit status used to determine
11/// if the loop should be broken, or if the body should be executed. If
12/// `invert_guard_status == false`, the loop will continue as long as the guard
13/// exits successfully. If `invert_guard_status == true`, the loop will continue
14/// **until** the guard exits successfully.
15// FIXME: implement a `break` built in command to break loops
16pub async fn loop_cmd<G, B, E>(
17    invert_guard_status: bool,
18    guard: G,
19    body: B,
20    env: &mut E,
21) -> Result<ExitStatus, G::Error>
22where
23    G: Spawn<E>,
24    B: Spawn<E, Error = G::Error>,
25    E: ?Sized + LastStatusEnvironment,
26{
27    // bash/zsh will exit loops with a successful status if
28    // loop breaks out of the first round without running the body,
29    // so if it hasn't yet run, consider it a success
30    let mut last_body_status = EXIT_SUCCESS;
31
32    loop {
33        // In case we end up running in a hot loop which is always ready to
34        // do more work, we'll preemptively yield (but signal immediate
35        // readiness) every once in a while so that other futures running on
36        // the same thread get a chance to make some progress too.
37        for _ in 0..20usize {
38            let guard_status = guard.spawn(env).await?.await;
39            let should_continue = guard_status.success() ^ invert_guard_status;
40
41            if !should_continue {
42                // Explicitly set the status here again, in case
43                // we never ran the body of the loop...
44                env.set_last_status(last_body_status);
45                return Ok(last_body_status);
46            }
47
48            // Set the guard status so that the body can access it if needed
49            env.set_last_status(guard_status);
50
51            last_body_status = body.spawn(env).await?.await;
52            env.set_last_status(last_body_status);
53        }
54
55        YieldOnce::new().await
56    }
57}
58
59/// A future which yields once and resolves.
60#[must_use = "futures do nothing unless polled"]
61struct YieldOnce {
62    yielded: bool,
63}
64
65impl YieldOnce {
66    fn new() -> Self {
67        Self { yielded: false }
68    }
69}
70
71impl Future for YieldOnce {
72    type Output = ();
73
74    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
75        if self.yielded {
76            Poll::Ready(())
77        } else {
78            self.yielded = true;
79            cx.waker().wake_by_ref();
80            Poll::Pending
81        }
82    }
83}