1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
use {ExitStatus, EXIT_SUCCESS, Spawn};
use error::IsFatalError;
use env::{LastStatusEnvironment, ReportErrorEnvironment};
use future::{Async, EnvFuture, Poll};
use spawn::{EnvFutureExt, ExitResult, FlattenedEnvFuture, SwallowNonFatal,
            swallow_non_fatal_errors};
use std::iter::Peekable;

/// A command which conditionally runs based on the exit status of the previous command.
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum AndOr<T> {
    /// A compound command which should run only if the previously run command succeeded.
    And(T),
    /// A compound command which should run only if the previously run command failed.
    Or(T),
}

/// A future representing the execution of a list of `And`/`Or` commands.
#[must_use = "futures do nothing unless polled"]
#[derive(Debug)]
pub struct AndOrList<T, I, E: ?Sized>
    where I: Iterator<Item = AndOr<T>>,
          T: Spawn<E>
{
    last_status: ExitStatus,
    current: SwallowNonFatal<FlattenedEnvFuture<T::EnvFuture, T::Future>>,
    rest: Peekable<I>,
}

/// Spawns an `And`/`Or` list of commands from an initial command and an iterator.
pub fn and_or_list<T, I, E: ?Sized>(first: T, rest: I, env: &E)
    -> AndOrList<T, I::IntoIter, E>
    where E: LastStatusEnvironment + ReportErrorEnvironment,
          T: Spawn<E>,
          T::Error: IsFatalError,
          I: IntoIterator<Item = AndOr<T>>,
{
    AndOrList {
        last_status: EXIT_SUCCESS,
        current: swallow_non_fatal_errors(first.spawn(env).flatten_future()),
        rest: rest.into_iter().peekable(),
    }
}

impl<T, I, E: ?Sized> EnvFuture<E> for AndOrList<T, I, E>
    where T: Spawn<E>,
          T::Error: IsFatalError,
          I: Iterator<Item = AndOr<T>>,
          E: LastStatusEnvironment + ReportErrorEnvironment,
{
    type Item = ExitResult<T::Future>;
    type Error = T::Error;

    fn poll(&mut self, env: &mut E) -> Poll<Self::Item, Self::Error> {
        loop {
            // If we have no further commands to process, we can return the
            // current command's future (so the caller may drop the environment)
            if self.rest.peek().is_none() {
                if let FlattenedEnvFuture::Future(_) = *self.current.as_ref() {
                    return Ok(Async::Ready(ExitResult::Pending(self.current.as_mut().take_future())));
                }
            }

            self.last_status = try_ready!(self.current.poll(env));
            env.set_last_status(self.last_status);

            'find_next: loop {
                match (self.rest.next(), self.last_status.success()) {
                    (None, _) => return Ok(Async::Ready(ExitResult::Ready(self.last_status))),

                    (Some(AndOr::And(next)), true) |
                    (Some(AndOr::Or(next)), false) => {
                        let next = next.spawn(env).flatten_future();
                        self.current = swallow_non_fatal_errors(next);
                        // Break the inner loop, outer loop will ensure we poll
                        // the newly spawned future
                        break 'find_next;
                    },

                    // Keep looping until we find a command we can spawn
                    _ => {},
                };
            }
        }
    }

    fn cancel(&mut self, env: &mut E) {
        self.current.cancel(env)
    }
}