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
//! `challenge_prompt` makes the user pause before doing something.
//!
//! A "challenge" prompt introduces a hurdle the user has to pass before
//! continuing. This is useful in deployment scripts or in scary commands to
//! make sure they were not typed by rote or pulled out of a shell history by
//! mistake.
//!
//! Available prompts are:
//! - arithmetic: Asks the user to solve a problem like `(12 + 7) mod 4`,
//! - phrase: Asks the user to type in a phrase like "I am probably making a
//!   mistake" exactly,
//! - yes: Asks the user to type in 'y' or 'yes'.
//!
//! This crate is both a library and a small command line application for use in
//! shell scripts.
//!
//! ## Command-line example
//!
//! ```ignore
//! $ cargo install challenge-prompt
//! $ challenge-prompt
//! Solve: (5 + 9) mod 6 = ?
//! ```
//!
//! ## Library example
//!
//! ```toml
//! [dependencies]
//! challenge_prompt = "0.2"
//! ```
//!
//! ```no_run
//! extern crate challenge_prompt;
//!
//! if !challenge_prompt::Challenge::Arithmetic.prompt() {
//!    panic!("user failed the challenge")
//! }
//! ```

extern crate rand;

#[derive(Debug)]
pub enum Challenge {
    Arithmetic,
    Phrase(String),
    Yes,
}

pub const DEFAULT_PHRASE: &str = "I am probably making a mistake.";

impl Challenge {
    /// Prompt the user with the challenge and return whether they passed or
    /// not.
    pub fn prompt(self: &Self) -> bool {
        use rand;
        use Challenge::*;
        match self {
            Arithmetic => {
                let a = rand::random::<u32>() % 20;
                let b = rand::random::<u32>() % 20;
                let c = rand::random::<u32>() % 18 + 2;
                prompt_gen(
                    &format!("Solve: ({} + {}) mod {} = ?", a, b, c),
                    &[&format!("{}", (a + b) % c)],
                )
            }
            Phrase(str) => prompt_gen(
                &format!("Enter the following exactly to continue: {}", str),
                &[str],
            ),
            Yes => prompt_gen("Continue? [y]", &["y", "yes"]),
        }
    }
}

/// Generic prompt implementation: print out the `prompt`, read a line of input,
/// and return whether it matches `expected` or not.
pub fn prompt_gen(prompt: &str, expected: &[&str]) -> bool {
    use std::io;
    println!("{}", prompt);
    let mut input = String::new();
    loop {
        if io::stdin().read_line(&mut input).is_ok() {
            let input = input.trim();
            return expected.iter().any(|&e| e == input);
        }
    }
}

#[cfg(test)]
mod tests {
    extern crate assert_cmd;
    extern crate predicates;

    use super::*;
    use std::process::Command;
    use tests::assert_cmd::prelude::*;
    use tests::predicates::prelude::*;

    #[test]
    fn arithmetic_challenge() {
        Command::main_binary()
            .unwrap()
            .assert()
            .stdout(predicate::str::contains("Solve:").from_utf8())
            .code(1);
        Command::main_binary()
            .unwrap()
            .arg("-a")
            .assert()
            .stdout(predicate::str::contains("Solve:").from_utf8())
            .code(1);
        Command::main_binary()
            .unwrap()
            .arg("--arithmetic")
            .assert()
            .stdout(predicate::str::contains("Solve:").from_utf8())
            .code(1);
        Command::main_binary()
            .unwrap()
            .with_stdin()
            .buffer("100") // No prompt ever returns 100
            .assert()
            .code(1);
    }

    #[test]
    fn phrase_challenge() {
        Command::main_binary()
            .unwrap()
            .arg("-p")
            .with_stdin()
            .buffer(DEFAULT_PHRASE)
            .assert()
            .stdout(predicate::str::contains(DEFAULT_PHRASE).from_utf8())
            .code(0);
        Command::main_binary()
            .unwrap()
            .arg("-p")
            .with_stdin()
            .buffer("This is the wrong phrase.\n")
            .assert()
            .code(1);
        Command::main_binary()
            .unwrap()
            .arg("--phrase")
            .arg("To be or not to be")
            .with_stdin()
            .buffer("  To be or not to be \n")
            .assert()
            .code(0);
    }

    #[test]
    fn yes_no_challenge() {
        Command::main_binary()
            .unwrap()
            .arg("-y")
            .assert()
            .stdout(predicate::str::contains("[y]").from_utf8())
            .code(1);
        Command::main_binary()
            .unwrap()
            .arg("-y")
            .with_stdin()
            .buffer("y")
            .assert()
            .code(0);
        Command::main_binary()
            .unwrap()
            .arg("-y")
            .with_stdin()
            .buffer("yes")
            .assert()
            .code(0);
        Command::main_binary()
            .unwrap()
            .arg("--yes")
            .with_stdin()
            .buffer("n")
            .assert()
            .code(1);
        Command::main_binary()
            .unwrap()
            .arg("--yes")
            .with_stdin()
            .buffer("nooooo")
            .assert()
            .code(1);
    }
}