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
//! A simple utility to prompt users of your CLI app.
//!
//! ## Examples
//!
//! ```no-run
//! extern crate trompt;
//!
//! use trompt::Trompt;
//!
//! let std::io::stdin = stdin();
//! let mut input = stdin.lock();
//! let mut output = std::io::stdout();
//!
//! let username = Trompt::new(&mut input, &mut output).prompt("Username: ");
//! let password = Trompt::new(&mut input, &mut output).silent(true).prompt("Password: ");
//! let confirmed = Trompt::new(&mut input, &mut output).prompt("Are you sure [yn]? ");
//! ```

extern crate libc;
extern crate termios;

use std::io::{self, BufRead, Write};


pub struct Trompt<'a, R: 'a + BufRead, W: 'a + Write> {
    input: &'a mut R,
    output: &'a mut W,
    silent: bool,
    message: String,
}

impl<'a, R: 'a + BufRead, W: 'a + Write> Trompt<'a, R, W> {
    /// Start a new prompter with default values.
    pub fn new(input: &'a mut R, output: &'a mut W) -> Trompt<'a, R, W> {
        Trompt {
            silent: false,
            message: "".to_owned(),
            input: input,
            output: output,
        }
    }

    /// Set the message before the input.
    pub fn message(&mut self, message: &str) -> &mut Trompt<'a, R, W> {
        self.message = message.to_owned();
        self
    }

    /// Set to true if you want to hide the user input. For example
    /// for passwords.
    pub fn silent(&mut self, silent: bool) -> &mut Trompt<'a, R, W> {
        self.silent = silent;
        self
    }

    /// Send the request to the user.
    pub fn send(&mut self) -> io::Result<String> {
        write!(*self.output, "{}", self.message)?;
        self.output.flush()?;

        let should_restore = if self.silent {
            Some(silent()?)
        } else {
            None
        };

        let mut response = String::new();
        if let Err(err) = self.input.read_line(&mut response) {
            if let Some(restore) = should_restore {
                let _ = restore();
            }

            return Err(err);
        };

        if let Some(restore) = should_restore {
            restore()?;
        }

        response.pop();

        Ok(response)
    }

    /// A helper. Same as `.message(message).send()`.
    pub fn prompt(&mut self, message: &str) -> io::Result<String> {
        self.message(message).send()
    }

    /// A helper for retrieving confirmation from the user. Maps `y`
    /// and `yes` case insensitively to true and `n` and `no` to
    /// false.
    pub fn confirm(&mut self, message: &str) -> io::Result<bool> {
        self.prompt(message).and_then(|result| match result.to_lowercase().as_str() {
            "y" | "yes" => Ok(true),
            "n" | "no" => Ok(false),
            _ => Err(io::Error::new(io::ErrorKind::Other, "Unexpected input")),
        })
    }
}

fn silent() -> io::Result<Box<Fn() -> io::Result<()>>> {
    use libc::STDIN_FILENO;
    use termios::{ECHO, ECHONL, TCSANOW, Termios, tcsetattr};

    let mut term = Termios::from_fd(STDIN_FILENO)?;
    let orig_term = term;

    // Don't echo anything except new lines
    term.c_lflag &= !ECHO;
    term.c_lflag |= ECHONL;

    tcsetattr(STDIN_FILENO, TCSANOW, &term)?;

    Ok(Box::new(move || tcsetattr(STDIN_FILENO, TCSANOW, &orig_term)))
}


#[cfg(test)]
mod tests {
    use Trompt;
    use std::io::Cursor;

    #[test]
    fn defaults() {
        let mut input = Cursor::new(Vec::new());
        let mut output = Cursor::new(Vec::new());
        let prompter = Trompt::new(&mut input, &mut output);

        assert_eq!(prompter.message, "");
        assert_eq!(prompter.silent, false);
    }

    #[test]
    fn message() {
        let mut input = Cursor::new(Vec::new());
        let mut output = Cursor::new(Vec::new());

        let mut prompter = Trompt::new(&mut input, &mut output);
        prompter.message("foo");

        assert_eq!(prompter.message, "foo");
    }

    #[test]
    fn silent() {
        let mut input = Cursor::new(Vec::new());
        let mut output = Cursor::new(Vec::new());

        let mut prompter = Trompt::new(&mut input, &mut output);
        prompter.silent(true);

        assert_eq!(prompter.silent, true);
    }

    #[test]
    fn send_message_to_output() {
        let mut input = Cursor::new(Vec::new());
        let mut output = Cursor::new(Vec::new());

        let _ = Trompt::new(&mut input, &mut output).message("foo").send();

        assert_eq!(output.into_inner(), b"foo");
    }

    #[test]
    fn send_collects_from_input() {
        let mut input = Cursor::new(b"bar\n");
        let mut output = Cursor::new(Vec::new());

        let result = Trompt::new(&mut input, &mut output).send();

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "bar");
    }

    #[test]
    fn send_collects_a_line() {
        let mut input = Cursor::new(b"bar\nbaz");
        let mut output = Cursor::new(Vec::new());

        let result = Trompt::new(&mut input, &mut output).send();

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "bar");
        assert_eq!(input.position(), 4);
    }

    #[test]
    fn prompt() {
        let mut input = Cursor::new(b"bar\n");
        let mut output = Cursor::new(Vec::new());

        let result = Trompt::new(&mut input, &mut output).prompt("foo");

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "bar");
        assert_eq!(output.into_inner(), b"foo");
    }

    #[test]
    fn confirm() {
        let mut input = Cursor::new(b"y\n");
        let mut output = Cursor::new(Vec::new());

        let result = Trompt::new(&mut input, &mut output).confirm("should I?");

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), true);
        assert_eq!(output.into_inner(), b"should I?");
    }

    #[test]
    fn confirm_case_insensitive() {
        let mut input = Cursor::new(b"No\n");
        let mut output = Cursor::new(Vec::new());

        let result = Trompt::new(&mut input, &mut output).confirm("should I?");

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), false);
        assert_eq!(output.into_inner(), b"should I?");
    }
}