operator based command spawning and direction in rust (wip)
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
#![allow(non_camel_case_types)]
use std::{
    ffi::{OsStr, OsString},
    io::{self, Read, Write},
    ops::{BitOr, Shr},
    process::{self, Child, ChildStderr, ChildStdin, ChildStdout, Stdio},
};
mod output;
mod processor;
mod util;
pub use output::null;
use processor::Io;
pub use processor::{Process, Processor};
pub use util::echo;

/// generates a impl of $a | $b => [`Processor`].
macro_rules! imp {
    (Processor,$b:ty) => {
        impl BitOr<$b> for Processor {
            type Output = Processor;
            fn bitor(mut self, rhs: $b) -> Self::Output {
                self.add(rhs);
                self
            }
        }
    };
    ($a:ty,$b:ty) => {
        impl BitOr<$b> for $a {
            type Output = Processor;
            fn bitor(self, rhs: $b) -> Self::Output {
                let mut p = Processor::new(512);
                p.add(self);
                p.add(rhs);
                p
            }
        }
    };
    (output $from:ty) => {
        impl Shr<&mut String> for $from {
            type Output = anyhow::Result<()>;
            fn shr(self, rhs: &mut String) -> Self::Output {
                let mut p = Processor::new(512);
                p.add(self);
                p >> rhs
            }
        }

        impl Shr<()> for $from {
            type Output = anyhow::Result<String>;
            fn shr(self, _: ()) -> Self::Output {
                let mut s = String::new();
                (self >> &mut s)?;
                Ok(s)
            }
        }
    };
}

// imp!(Command, grep); // cargo | grep
// imp!(echo, grep); // echo | grep
// imp!(Processor, grep); // a | b | grep
imp!(Command, Command); // command | command
imp!(echo, Command); // echo | command
imp!(Processor, Command); // a | b | command
imp!(output Command);
imp!(output echo);

impl Shr<&mut String> for Processor {
    type Output = anyhow::Result<()>;

    fn shr(mut self, rhs: &mut String) -> Self::Output {
        self.add(output::StringOut(rhs as *mut _));
        self.complete()?;
        Ok(())
    }
}

impl Shr<()> for Processor {
    type Output = anyhow::Result<String>;

    fn shr(self, _: ()) -> Self::Output {
        let mut s = String::new();
        (self >> &mut s)?;
        Ok(s)
    }
}

#[derive(Debug)]
pub struct Command {
    stdout: ChildStdout,
    stderr: ChildStderr,
    stdin: ChildStdin,
    proc: Child,
}

unsafe impl Process for Command {
    fn run(&mut self, on: processor::Io) -> anyhow::Result<usize> {
        match on {
            Io::First(b) => Ok(self.stdout.read(b)?),
            Io::Middle(i, o) => {
                self.stdin.write(i)?;
                Ok(self.stdout.read(o)?)
            }
            Io::Last(i) => {
                self.stdin.write(i)?;
                Ok(0)
            }
        }
    }

    fn done(&mut self, _: Option<bool>) -> anyhow::Result<bool> {
        Ok(self.proc.try_wait()?.is_some())
    }
}

#[derive(Debug)]
pub struct CommandBuilder {
    command: OsString,
    args: Vec<OsString>,
}

impl CommandBuilder {
    pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut CommandBuilder {
        self.args.push(arg.as_ref().to_os_string());
        self
    }

    pub fn args(&mut self, args: impl IntoIterator<Item = impl AsRef<OsStr>> + ExactSizeIterator) {
        self.args.reserve(self.args.len() + args.len());
        for arg in args {
            self.args.push(arg.as_ref().to_os_string());
        }
    }

    pub fn spawn(&mut self) -> io::Result<Command> {
        let mut proc = process::Command::new(&self.command)
            .args(&self.args)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .stdin(Stdio::piped())
            .spawn()?;
        Ok(Command {
            stdout: proc.stdout.take().unwrap(),
            stderr: proc.stderr.take().unwrap(),
            stdin: proc.stdin.take().unwrap(),
            proc,
        })
    }
}

impl Command {
    pub fn new(command: impl AsRef<OsStr>) -> CommandBuilder {
        CommandBuilder {
            command: command.as_ref().to_os_string(),
            args: vec![],
        }
    }
}

#[test]
fn usage() {
    let o = ((Command::new("cargo").spawn().unwrap()
        | Command::new("grep").arg("test").spawn().unwrap())
        >> ())
        .unwrap();
    assert_eq!(o, "");
}