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
 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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
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
use {ExitStatus, POLLED_TWICE, Spawn, STDOUT_FILENO};
use env::{AsyncIoEnvironment, FileDescEnvironment, LastStatusEnvironment, ReportErrorEnvironment,
          SubEnvironment};
use error::IsFatalError;
use future::{Async, EnvFuture, Poll};
use futures::future::Future;
use io::{FileDescWrapper, Permissions, Pipe};
use spawn::{ExitResult, Subshell, subshell};
use std::borrow::Cow;
use std::fmt;
use std::io::Error as IoError;
use std::mem;
use tokio_io::AsyncRead;
use tokio_io::io::{ReadToEnd, read_to_end};
use void::unreachable;

/// A future that represents the spawning of a command substitution.
///
/// The standard output of the commands will be captured and
/// trailing newlines trimmed.
#[must_use = "futures do nothing unless polled"]
#[derive(Debug)]
pub struct SubstitutionEnvFuture<I> {
    body: Option<I>,
}

impl<I, S, E> EnvFuture<E> for SubstitutionEnvFuture<I>
    where I: Iterator<Item = S>,
          S: Spawn<E>,
          S::Error: IsFatalError + From<IoError>,
          E: AsyncIoEnvironment + FileDescEnvironment + LastStatusEnvironment + ReportErrorEnvironment + SubEnvironment,
          E::FileHandle: FileDescWrapper,
          E::Read: AsyncRead,
{
    type Item = Substitution<I, E::Read, E>;
    type Error = S::Error;

    fn poll(&mut self, env: &mut E) -> Poll<Self::Item, Self::Error> {
        let body = self.body.take().expect(POLLED_TWICE);
        let Pipe { reader: cmd_output, writer: cmd_stdout_fd } = try!(Pipe::new());

        let mut env = env.sub_env();
        let cmd_stdout_fd: E::FileHandle = cmd_stdout_fd.into();
        env.set_file_desc(STDOUT_FILENO, cmd_stdout_fd, Permissions::Write);

        let subshell = FlattenSubshell::Subshell(subshell(body, &env));
        let read_to_end = read_to_end(env.read_async(cmd_output), Vec::new());
        drop(env);

        Ok(Async::Ready(Substitution {
            inner: JoinSubshellAndReadToEnd {
                subshell: MaybeDone::NotYet(subshell),
                read_to_end: MaybeDone::NotYet(read_to_end),
            },
        }))
    }

    fn cancel(&mut self, _: &mut E) {
        // Nothing to cancel
    }
}

/// A future that represents the execution of a command substitution.
///
/// The standard output of the commands will be captured and
/// trailing newlines trimmed.
#[must_use = "futures do nothing unless polled"]
pub struct Substitution<I, R, E>
    where I: Iterator,
          I::Item: Spawn<E>,
{
    inner: JoinSubshellAndReadToEnd<I, R, E>,
}

impl<I, R, S, E> fmt::Debug for Substitution<I, R, E>
    where E: fmt::Debug,
          I: Iterator<Item = S> + fmt::Debug,
          R: fmt::Debug,
          S: Spawn<E> + fmt::Debug,
          S::EnvFuture: fmt::Debug,
          S::Future: fmt::Debug,
{
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("Substitution")
            .field("inner", &self.inner)
            .finish()
    }
}

impl<I, R, S, E> Future for Substitution<I, R, E>
    where E: LastStatusEnvironment + ReportErrorEnvironment,
          I: Iterator<Item = S>,
          S: Spawn<E>,
          S::Error: IsFatalError + From<IoError>,
          R: AsyncRead,
{
    type Item = String;
    type Error = S::Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        let mut buf = try_ready!(self.inner.poll());

        // Trim the trailing newlines as per POSIX spec
        while Some(&b'\n') == buf.last() {
            buf.pop();
            if Some(&b'\r') == buf.last() {
                buf.pop();
            }
        }

        let ret = match String::from_utf8_lossy(&buf) {
            Cow::Owned(s) => s,
            Cow::Borrowed(_) => unsafe {
                String::from_utf8_unchecked(buf)
            },
        };

        Ok(Async::Ready(ret))
    }
}

enum FlattenSubshell<I, E>
    where I: Iterator,
          I::Item: Spawn<E>,
{
    Subshell(Subshell<I, E>),
    Flatten(ExitResult<<I::Item as Spawn<E>>::Future>),
}

impl<I, S, E> fmt::Debug for FlattenSubshell<I, E>
    where E: fmt::Debug,
          I: Iterator<Item = S> + fmt::Debug,
          S: Spawn<E> + fmt::Debug,
          S::EnvFuture: fmt::Debug,
          S::Future: fmt::Debug,
{
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            FlattenSubshell::Subshell(ref s) => {
                fmt.debug_tuple("FlattenSubshell::Subshell")
                    .field(s)
                    .finish()
            },
            FlattenSubshell::Flatten(ref f) => {
                fmt.debug_tuple("FlattenSubshell::Flatten")
                    .field(f)
                    .finish()
            },
        }
    }
}

impl<I, S, E> Future for FlattenSubshell<I, E>
    where E: LastStatusEnvironment + ReportErrorEnvironment,
          I: Iterator<Item = S>,
          S: Spawn<E>,
          S::Error: IsFatalError,
{
    type Item = ExitStatus;
    type Error = S::Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        loop {
            let inner = match *self {
                FlattenSubshell::Subshell(ref mut s) => match s.poll() {
                    Ok(Async::Ready(inner)) => inner,
                    Ok(Async::NotReady) => return Ok(Async::NotReady),
                    Err(void) => unreachable(void),
                },
                FlattenSubshell::Flatten(ref mut f) => return f.poll(),
            };

            *self = FlattenSubshell::Flatten(inner);
        }
    }
}

#[derive(Debug)]
enum MaybeDone<F, T> {
    NotYet(F),
    Done(T),
    Gone,
}

impl<F: Future> MaybeDone<F, F::Item> {
    fn poll(&mut self) -> Result<bool, F::Error> {
        let res = match *self {
            MaybeDone::NotYet(ref mut f) => try!(f.poll()),
            MaybeDone::Done(_) => return Ok(true),
            MaybeDone::Gone => panic!(POLLED_TWICE),
        };
        match res {
            Async::Ready(res) => {
                *self = MaybeDone::Done(res);
                Ok(true)
            }
            Async::NotReady => Ok(false),
        }
    }

    fn take(&mut self) -> F::Item {
        match mem::replace(self, MaybeDone::Gone) {
            MaybeDone::Done(f) => f,
            _ => panic!(POLLED_TWICE),
        }
    }
}

#[must_use = "futures do nothing unless polled"]
struct JoinSubshellAndReadToEnd<I, R, E>
    where I: Iterator,
          I::Item: Spawn<E>,
{
    read_to_end: MaybeDone<ReadToEnd<R>, (R, Vec<u8>)>,
    subshell: MaybeDone<FlattenSubshell<I, E>, ExitStatus>,
}

impl<I, R, S, E> fmt::Debug for JoinSubshellAndReadToEnd<I, R, E>
    where E: fmt::Debug,
          I: Iterator<Item = S> + fmt::Debug,
          R: fmt::Debug,
          S: Spawn<E> + fmt::Debug,
          S::EnvFuture: fmt::Debug,
          S::Future: fmt::Debug,
{
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("JoinSubshellAndReadToEnd")
            .field("read_to_end", &self.read_to_end)
            .field("subshell", &self.subshell)
            .finish()
    }
}

impl<I, R, E> JoinSubshellAndReadToEnd<I, R, E>
    where I: Iterator,
          I::Item: Spawn<E>,
{
    fn erase(&mut self) {
        self.subshell = MaybeDone::Gone;
        self.read_to_end = MaybeDone::Gone;
    }
}

impl<I, S, R, E> Future for JoinSubshellAndReadToEnd<I, R, E>
    where E: LastStatusEnvironment + ReportErrorEnvironment,
          I: Iterator<Item = S>,
          S: Spawn<E>,
          S::Error: IsFatalError + From<IoError>,
          R: AsyncRead,
{
    type Item = Vec<u8>;
    type Error = S::Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        let all_done = match self.read_to_end.poll() {
            Ok(done) => done,
            Err(e) => {
                self.erase();
                return Err(e.into());
            },
        };

        let all_done = match self.subshell.poll() {
            Ok(done) => all_done && done,
            Err(e) => {
                self.erase();
                return Err(e);
            },
        };

        if all_done {
            Ok(Async::Ready(self.read_to_end.take().1))
        } else {
            Ok(Async::NotReady)
        }
    }
}

/// Spawns any iterable collection of sequential items whose standard output
/// will be captured (and trailing newlines trimmed).
pub fn substitution<I>(body: I) -> SubstitutionEnvFuture<I::IntoIter>
    where I: IntoIterator,
{
    SubstitutionEnvFuture {
        body: Some(body.into_iter()),
    }
}