1 /**
2  * Copyright: Copyright (c) 2011 Nick Sabalausky. All rights reserved.
3  * Authors: Nick Sabalausky
4  * Version: Initial created: Jun 4, 2011
5  * License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost Software License 1.0)
6  */
7 module dvm.io.Console;
8 
9 import tango.io.Console;
10 import tango.io.Stdout;
11 import tango.text.Util;
12 
13 import mambo.core._;
14 import dvm.dvm.Options;
15 import dvm.util.Util;
16 
17 /++
18 Easy general-purpose function to prompt user for input.
19 Optionally supports custom validation.
20 
21 Get input from the user:
22     auto result = prompt("Enter Text>");
23 
24 Get validated input. Won't return until user enters valid input:
25     bool accept(string input)
26     {
27         input = toLower(input);
28         return input == "coffee" || input == "tea";
29     }
30     auto result = prompt("What beverage?", &accept, "Not on menu, try again!");
31 +/
32 string prompt(string promptMsg, bool delegate(const(char)[]) accept=null, string rejectedMsg="")
33 {
34     char[] input;
35     while (true)
36     {
37         Stdout(promptMsg).flush;
38         Cin.readln(input);
39         input = trim(input);
40 
41         if (accept is null)
42             break;
43         else
44         {
45             if (accept(input))
46                 break;
47             else
48             {
49                 Stdout.newline;
50                 if (rejectedMsg != "")
51                     Stdout.formatln(rejectedMsg, input);
52             }
53         }
54     }
55 
56     return input.assumeUnique;
57 }
58 
59 /// Returns 'true' for "Yes"
60 /// Obeys --force and --decline
61 bool promptYesNo()
62 {
63     bool matches(char ch, const(char)[] str)
64     {
65         str = toLower(str);
66         return str != "" && str[0] == ch;
67     }
68 
69     bool accept(const(char)[] str)
70     {
71         return matches('y', str) || matches('n', str);
72     }
73 
74     auto options = Options.instance;
75 
76     if (options.decline)
77     {
78         println("[Declining, 'no']");
79         return false;
80     }
81 
82     if (options.force)
83     {
84         println("[Forcing, 'yes']");
85         return true;
86     }
87 
88     auto response = prompt("Yes/No?>", &accept);
89     return matches('y', response);
90 }