inquirer 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 87b38fc113ac1f89445bafc60e609d926001dc6f
4
+ data.tar.gz: 3f7eee7eb98008b46b5ce6798e57456a34466c3e
5
+ SHA512:
6
+ metadata.gz: ef24d43a99b02195d37d108f66604909afe5bfdfc0d501f05db06ff19abdd802ac5c2746499b63ac02a2b2928a285c7af72641d85c9dc844624d7d6dcc6f9e82
7
+ data.tar.gz: daf1443759ec6c44137a7752ab57633589a612338a23fcd491da2317e415b7ebe99b63666aa67d3e36dffd6e55517399de4624c61c414f875593c336e75c5eab
data/.travis.yml ADDED
@@ -0,0 +1,7 @@
1
+ language: ruby
2
+ script: "bundle exec rake"
3
+ rvm:
4
+ - "1.9.3"
5
+ - "2.0.0"
6
+ - "rbx-2.1.1"
7
+ - "rbx-2.2.1"
data/CHANGELOG.md ADDED
@@ -0,0 +1,24 @@
1
+ ## 0.1.1
2
+
3
+ * feature: add (and verify) rubinius 2.1 + 2.2 support
4
+ * bugfix: default rendering options when invoking the module with .ask must be set
5
+ * bugfix: add utf-8 encoding hints
6
+ * bugfix: extract version information into a separate independent file
7
+
8
+ ## 0.1.0
9
+
10
+ * feature: add list selection
11
+ * feature: add checkbox selection
12
+ * feature: add colors
13
+ * improvement: extract style into its own module
14
+ * improvement: implement interface for all prompts under Ask module
15
+ * improvement: moved prompt rendering to IOHelper
16
+ * improvement: separate the looping of user input out of the list and move it to the IOHelper
17
+ * improvement: separate selector from item rendering
18
+ * improvement: separate list rendering from processing
19
+ * bugfix: don't do anything if checkbox has no items
20
+ * bugfix: don't render the list if there is no item in it
21
+ * bugfix: create the Inquirer module first, before including any of its implementations
22
+ * bugfix: make simple checkbox selected colored
23
+ * bugfix: select checkbox items based on space keypress
24
+
data/Gemfile ADDED
@@ -0,0 +1,8 @@
1
+ source 'https://rubygems.org'
2
+
3
+ gemspec
4
+
5
+ group :development do
6
+ gem 'rake'
7
+ gem 'minitest'
8
+ end
data/LICENSE ADDED
@@ -0,0 +1,176 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
data/README.md ADDED
@@ -0,0 +1,48 @@
1
+ # inquirer.rb
2
+
3
+ [![Build Status](https://travis-ci.org/arlimus/inquirer.rb.png)](https://travis-ci.org/arlimus/inquirer.rb)
4
+
5
+ Interactive user prompts on CLI for ruby.
6
+
7
+ ## Examples
8
+
9
+ ```ruby
10
+ idx = Ask.list "Look behind you...", [
11
+ "a three-headed monkey!",
12
+ "a pink pony",
13
+ "Godzilla"
14
+ ]
15
+ # idx is the selected index
16
+ ```
17
+
18
+ ![List example](example/list.png)
19
+
20
+ ```ruby
21
+ idx = Ask.checkbox "Monkey see, monkey...", [
22
+ "don't",
23
+ "eats Banana",
24
+ "do"
25
+ ]
26
+ # idx is an array containing the selections
27
+ ```
28
+
29
+ ![Checkbox example](example/checkbox.png)
30
+
31
+ ## Compatibility
32
+
33
+ | Ruby | Linux | OS X | Windows |
34
+ |----------------|:-----:|:----:|:-------:|
35
+ | MRI 1.9.3 | ✔ | ✔ | ✘ |
36
+ | MRI 2.0.0 | ✔ | ✔ | ✘ |
37
+ | Rubinius 2.1.1 | ✔ | ✔ | ✘ |
38
+ | Rubinius 2.2.1 | ✔ | ✔ | ✘ |
39
+ | JRuby 1.7.x | ✘ | ✘ | ✘ |
40
+
41
+ ## Credit
42
+
43
+ This is basically the wonderful [Inquirer.js](https://github.com/SBoudrias/Inquirer.js), just done for ruby. I was unable to find a good gem to handle user interaction in ruby as well as this module does in JS.
44
+
45
+ ## License
46
+
47
+ Apache v2
48
+ Author: Dominik Richter
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ require "rake/testtask"
2
+ Rake::TestTask.new do |t|
3
+ t.libs << "test"
4
+ t.pattern = "test/classes/*_spec.rb"
5
+ t.verbose = true
6
+ end
7
+
8
+ task default: [:test]
Binary file
@@ -0,0 +1,7 @@
1
+ require_relative '../lib/inquirer'
2
+ idx = Ask.checkbox "Monkey see, monkey...", [
3
+ "don't",
4
+ "eats Banana",
5
+ "do"
6
+ ]
7
+ puts "you selected #{idx}"
data/example/list.png ADDED
Binary file
data/example/list.rb ADDED
@@ -0,0 +1,7 @@
1
+ require_relative '../lib/inquirer'
2
+ idx = Ask.list "Look behind you...", [
3
+ "a three-headed monkey!",
4
+ "a pink pony",
5
+ "Godzilla"
6
+ ]
7
+ puts "you selected #{idx}"
data/inquirer.gemspec ADDED
@@ -0,0 +1,27 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib/', __FILE__)
3
+ $:.unshift lib unless $:.include?(lib)
4
+ require 'inquirer/version'
5
+
6
+ spec = Gem::Specification.new do |s|
7
+ s.name = 'inquirer'
8
+ s.licenses = ['Apache v2']
9
+ s.version = Inquirer::VERSION
10
+ s.platform = Gem::Platform::RUBY
11
+ s.summary = "Interactive user prompts on CLI for ruby."
12
+ s.description = s.summary
13
+ s.author = "Dominik Richter"
14
+ s.email = "dominik.richter@googlemail.com"
15
+ s.homepage = 'https://github.com/arlimus/livecd'
16
+
17
+ s.add_dependency 'term-ansicolor', '>= 1.2.2'
18
+ if( RUBY_ENGINE == "rbx" )
19
+ s.add_dependency 'rubysl-mutex_m'
20
+ s.add_dependency 'rubysl-singleton'
21
+ s.add_dependency 'rubysl-io-console'
22
+ end
23
+
24
+ s.files = `git ls-files`.split("\n")
25
+ s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
26
+ s.require_paths = ["lib"]
27
+ end
data/lib/inquirer.rb ADDED
@@ -0,0 +1,15 @@
1
+ require 'inquirer/version'
2
+ require 'inquirer/utils/iohelper'
3
+ require 'inquirer/prompts/list'
4
+ require 'inquirer/prompts/checkbox'
5
+
6
+ module Ask
7
+ extend self
8
+ # implement prompts
9
+ def list *args
10
+ List.ask *args
11
+ end
12
+ def checkbox *args
13
+ Checkbox.ask *args
14
+ end
15
+ end
@@ -0,0 +1,97 @@
1
+ require 'term/ansicolor'
2
+ require 'inquirer/style'
3
+
4
+ # Base rendering for simple lists
5
+ module CheckboxRenderer
6
+ def render heading = nil, list = [], footer = nil
7
+ # render the heading
8
+ ( heading.nil? ? "" : @heading % heading ) +
9
+ # render the list
10
+ list.map do |li|
11
+ render_item li
12
+ end.join("") +
13
+ # render the footer
14
+ ( footer.nil? ? "" : @footer % footer )
15
+ end
16
+
17
+ private
18
+
19
+ def render_item x
20
+ ( x["selected"] ? @selector : " " ) +
21
+ ( x["active"] ? @checkbox_on : @checkbox_off ) +
22
+ " " +
23
+ ( x["active"] ? @active_item : @item ) % x["value"]
24
+ end
25
+
26
+ end
27
+
28
+ # Formatting for rendering
29
+ class CheckboxDefault
30
+ include CheckboxRenderer
31
+ C = Term::ANSIColor
32
+ def initialize( style )
33
+ @heading = "%s:\n"
34
+ @footer = "%s\n"
35
+ @item = "%s\n"
36
+ @active_item = "%s" + "\n"
37
+ @selector = C.cyan style.selector
38
+ @checkbox_on = C.cyan style.checkbox_on
39
+ @checkbox_off = style.checkbox_off
40
+ end
41
+ end
42
+
43
+ class Checkbox
44
+ def initialize question = nil, elements = [], renderer = nil
45
+ @elements = elements
46
+ @question = question
47
+ @pos = 0
48
+ @active = elements.map{|i| false}
49
+ @prompt = ""
50
+ @renderer = renderer || CheckboxDefault.new( Inquirer::Style::Default )
51
+ end
52
+
53
+ def update_prompt
54
+ # transform the list into
55
+ # {"value"=>..., "selected"=> true|false, "active"=> true|false }
56
+ e = @elements.
57
+ # attach the array position
58
+ map.with_index(0).
59
+ map do |c,pos|
60
+ { "value"=>c, "selected" => pos == @pos, "active" => @active[pos] }
61
+ end
62
+ # call the renderer
63
+ @prompt = @renderer.render(@question, e)
64
+ end
65
+
66
+ # Run the list selection, wait for the user to select an item and return
67
+ # the selected index
68
+ # Params:
69
+ # +clear+:: +Bool+ whether to clear the selection prompt once this is done
70
+ # defaults to true; set it to false if you want the prompt to remain after
71
+ # the user is done with selecting
72
+ def run clear = true
73
+ # finish if there's nothing to do
74
+ return @active if Array(@elements).empty?
75
+ # render the
76
+ IOHelper.render( update_prompt )
77
+ # loop through user input
78
+ IOHelper.read_key_while do |key|
79
+ @pos = (@pos - 1) % @elements.length if key == "up"
80
+ @pos = (@pos + 1) % @elements.length if key == "down"
81
+ @active[@pos] = !@active[@pos] if key == "space"
82
+ IOHelper.rerender( update_prompt )
83
+ # we are done if the user hits return
84
+ key != "return"
85
+ end
86
+ # clear the final prompt and the line
87
+ IOHelper.clear if clear
88
+ # return the index of the selected item
89
+ @active
90
+ end
91
+
92
+ def self.ask question = nil, elements = [], opts = { clear: true }
93
+ l = Checkbox.new question, elements, opts[:renderer]
94
+ l.run opts[:clear]
95
+ end
96
+
97
+ end
@@ -0,0 +1,89 @@
1
+ require 'term/ansicolor'
2
+
3
+ # Base rendering for simple lists
4
+ module ListRenderer
5
+ def render heading = nil, list = [], footer = nil
6
+ # render the heading
7
+ ( heading.nil? ? "" : @heading % heading ) +
8
+ # render the list
9
+ list.map do |li|
10
+ render_item li
11
+ end.join("") +
12
+ # render the footer
13
+ ( footer.nil? ? "" : @footer % footer )
14
+ end
15
+
16
+ private
17
+
18
+ def render_item x
19
+ ( x["selected"] ? @selector : " " ) + " " +
20
+ ( x["selected"] ? @selected_item : @item ) % x["value"]
21
+ end
22
+ end
23
+
24
+ # Default formatting for list rendering
25
+ class ListDefault
26
+ include ListRenderer
27
+ C = Term::ANSIColor
28
+ def initialize( style )
29
+ @heading = "%s:\n"
30
+ @footer = "%s\n"
31
+ @item = "%s\n"
32
+ @selected_item = C.cyan("%s") + "\n"
33
+ @selector = C.cyan style.selector
34
+ end
35
+ end
36
+
37
+ class List
38
+ def initialize question = nil, elements = [], renderer = nil
39
+ @elements = elements
40
+ @question = question
41
+ @pos = 0
42
+ @prompt = ""
43
+ @renderer = renderer || ListDefault.new( Inquirer::Style::Default )
44
+ end
45
+
46
+ def update_prompt
47
+ # transform the list into
48
+ # {"value"=>..., "selected"=> true|false}
49
+ e = @elements.
50
+ # attach the array position
51
+ map.with_index(0).
52
+ map do |c,pos|
53
+ { "value"=>c, "selected" => pos == @pos }
54
+ end
55
+ # call the renderer
56
+ @prompt = @renderer.render(@question, e)
57
+ end
58
+
59
+ # Run the list selection, wait for the user to select an item and return
60
+ # the selected index
61
+ # Params:
62
+ # +clear+:: +Bool+ whether to clear the selection prompt once this is done
63
+ # defaults to true; set it to false if you want the prompt to remain after
64
+ # the user is done with selecting
65
+ def run clear = true
66
+ # finish if there's nothing to do
67
+ return nil if Array(@elements).empty?
68
+ # render the
69
+ IOHelper.render( update_prompt )
70
+ # loop through user input
71
+ IOHelper.read_key_while do |key|
72
+ @pos = (@pos - 1) % @elements.length if key == "up"
73
+ @pos = (@pos + 1) % @elements.length if key == "down"
74
+ IOHelper.rerender( update_prompt )
75
+ # we are done if the user hits return
76
+ key != "return"
77
+ end
78
+ # clear the final prompt and the line
79
+ IOHelper.clear if clear
80
+ # return the index of the selected item
81
+ @pos
82
+ end
83
+
84
+ def self.ask question = nil, elements = [], opts = { clear: true }
85
+ l = List.new question, elements, opts[:renderer]
86
+ l.run opts[:clear]
87
+ end
88
+
89
+ end
@@ -0,0 +1,17 @@
1
+ # encoding: utf-8
2
+ module Inquirer::Style
3
+ Style = Struct.new(:selector, :checkbox_on, :checkbox_off)
4
+ extend self
5
+
6
+ Simple = Style.new(
7
+ ">",
8
+ "[x]",
9
+ "[ ]"
10
+ )
11
+
12
+ Default = Style.new(
13
+ "‣",
14
+ "⬢",
15
+ "⬡"
16
+ )
17
+ end
@@ -0,0 +1,120 @@
1
+ require 'io/console'
2
+
3
+ module IOHelper
4
+ extend self
5
+
6
+ @rendered = ""
7
+
8
+ KEYS = {
9
+ " " => "space",
10
+ "\t" => "tab",
11
+ "\r" => "return",
12
+ "\n" => "linefeed",
13
+ "\e" => "escape",
14
+ "\e[A" => "up",
15
+ "\e[B" => "down",
16
+ "\e[C" => "right",
17
+ "\e[D" => "left",
18
+ "\177" => "backspace",
19
+ # ctrl + c
20
+ "\003" => "ctrl-c",
21
+ # ctrl + d
22
+ "\004" => "ctrl-d"
23
+ }
24
+
25
+ # Read a character the user enters on console. This call is synchronous blocking.
26
+ # This is taken from: http://www.alecjacobson.com/weblog/?p=75
27
+ def read_char
28
+ begin
29
+ # save previous state of stty
30
+ old_state = `stty -g`
31
+ # disable echoing and enable raw (not having to press enter)
32
+ system "stty raw -echo"
33
+ c = STDIN.getc.chr
34
+ # gather next two characters of special keys
35
+ if(c=="\e")
36
+ extra_thread = Thread.new{
37
+ c = c + STDIN.getc.chr
38
+ c = c + STDIN.getc.chr
39
+ }
40
+ # wait just long enough for special keys to get swallowed
41
+ extra_thread.join(0.00001)
42
+ # kill thread so not-so-long special keys don't wait on getc
43
+ extra_thread.kill
44
+ end
45
+ rescue => ex
46
+ puts "#{ex.class}: #{ex.message}"
47
+ puts ex.backtrace
48
+ ensure
49
+ # restore previous state of stty
50
+ system "stty #{old_state}"
51
+ end
52
+ return c
53
+ end
54
+
55
+ # Read a keypress on console. Return the key name (e.g. "space", "a", "B")
56
+ # Params:
57
+ # +with_exit_codes+:: +Bool+ whether to throw Interrupts when the user presses
58
+ # ctrl-c and ctrl-d. (true by default)
59
+ def read_key with_exit_codes = true
60
+ raw = read_key_raw
61
+ raise Interrupt if with_exit_codes and ( raw == "ctrl-c" or raw == "ctrl-d" )
62
+ raw
63
+ end
64
+
65
+ # Get each key the user presses and hand it one by one to the block. Do this
66
+ # as long as the block returns truthy
67
+ # Params:
68
+ # +&block+:: +Proc+ a block that receives a user key and returns truthy or falsy
69
+ def read_key_while &block
70
+ STDIN.noecho do
71
+ # as long as the block doen't return falsy,
72
+ # read the user input key and sned it to the block
73
+ while block.( IOHelper.read_key )
74
+ end
75
+ end
76
+ end
77
+
78
+ # Get the console window size
79
+ # Returns: [width, height]
80
+ def winsize
81
+ STDIN.winsize
82
+ end
83
+
84
+ # Render a text to the prompt
85
+ def render prompt
86
+ @rendered = prompt
87
+ print prompt
88
+ end
89
+
90
+ # Clear the prompt and render the update
91
+ def rerender prompt
92
+ clear
93
+ render prompt
94
+ end
95
+
96
+ # clear the console based on the last text rendered
97
+ def clear
98
+ # get console window height and width
99
+ h,w = IOHelper.winsize
100
+ # determine how many lines to move up
101
+ n = @rendered.scan(/\n/).length
102
+ # jump back to the first position and clear the line
103
+ print carriage_return + ( line_up * n ) + clear_line
104
+ end
105
+
106
+ def carriage_return; "\r" end
107
+ def line_up; "\e[A" end
108
+ def clear_line; "\e[0K" end
109
+
110
+ private
111
+
112
+ def read_key_raw
113
+ c = read_char
114
+ # try to get the key name from the character
115
+ k = KEYS[c]
116
+ # return either the character or key name
117
+ ( k.nil? ) ? c : k
118
+ end
119
+
120
+ end
@@ -0,0 +1,3 @@
1
+ module Inquirer
2
+ VERSION = "0.1.1"
3
+ end
@@ -0,0 +1,58 @@
1
+ # encoding: utf-8
2
+ require 'minitest_helper'
3
+
4
+ describe Checkbox do
5
+ before :each do
6
+ IOHelper.output = ""
7
+ IOHelper.keys = nil
8
+ end
9
+
10
+ it "finishes rendering with a clear" do
11
+ Checkbox.ask "select", ["one","two","three"]
12
+ IOHelper.output.must_equal ""
13
+ end
14
+
15
+ it "doesn't render the dialog with 0 items" do
16
+ Checkbox.ask "select", [], clear: false
17
+ IOHelper.output.must_equal ""
18
+ end
19
+
20
+ it "renders the dialog with 3 items" do
21
+ Checkbox.ask "select", ["one","two","three"], clear: false
22
+ IOHelper.output.must_equal "select:\n\e[36m‣\e[0m⬡ one\n ⬡ two\n ⬡ three\n"
23
+ end
24
+
25
+ it "it finishes selection on pressing enter" do
26
+ IOHelper.keys = "enter"
27
+ Checkbox.ask( "select", ["one","two","three"], clear: false
28
+ ).must_equal [false,false,false]
29
+ end
30
+
31
+ it "selects and renders other items correctly (press down, press up, space, cycle)" do
32
+ IOHelper.keys = ["down","space","enter"]
33
+ Checkbox.ask( "select", ["one","two","three"], clear: false
34
+ ).must_equal [false,true,false]
35
+ IOHelper.output.must_equal "select:\n ⬡ one\n\e[36m‣\e[0m\e[36m⬢\e[0m two\n ⬡ three\n"
36
+
37
+ IOHelper.keys = ["space","down","space","enter"]
38
+ Checkbox.ask( "select", ["one","two","three"], clear: false
39
+ ).must_equal [true,true,false]
40
+ IOHelper.output.must_equal "select:\n \e[36m⬢\e[0m one\n\e[36m‣\e[0m\e[36m⬢\e[0m two\n ⬡ three\n"
41
+
42
+ IOHelper.keys = ["space","down","space","down","space","enter"]
43
+ Checkbox.ask( "select", ["one","two","three"], clear: false
44
+ ).must_equal [true,true,true]
45
+ IOHelper.output.must_equal "select:\n \e[36m⬢\e[0m one\n \e[36m⬢\e[0m two\n\e[36m‣\e[0m\e[36m⬢\e[0m three\n"
46
+
47
+ IOHelper.keys = ["down","down","down","space","enter"]
48
+ Checkbox.ask( "select", ["one","two","three"], clear: false
49
+ ).must_equal [true,false,false]
50
+ IOHelper.output.must_equal "select:\n\e[36m‣\e[0m\e[36m⬢\e[0m one\n ⬡ two\n ⬡ three\n"
51
+
52
+ IOHelper.keys = ["up","space","enter"]
53
+ Checkbox.ask( "select", ["one","two","three"], clear: false
54
+ ).must_equal [false,false,true]
55
+ IOHelper.output.must_equal "select:\n ⬡ one\n ⬡ two\n\e[36m‣\e[0m\e[36m⬢\e[0m three\n"
56
+ end
57
+
58
+ end
@@ -0,0 +1,58 @@
1
+ # encoding: utf-8
2
+ require 'minitest_helper'
3
+
4
+ describe List do
5
+ before :each do
6
+ IOHelper.output = ""
7
+ IOHelper.keys = nil
8
+ end
9
+
10
+ it "finishes rendering with a clear" do
11
+ List.ask "select", ["one","two","three"]
12
+ IOHelper.output.must_equal ""
13
+ end
14
+
15
+ it "doesn't render the dialog with 0 items" do
16
+ List.ask "select", [], clear: false
17
+ IOHelper.output.must_equal ""
18
+ end
19
+
20
+ it "renders the dialog with 3 items" do
21
+ List.ask "select", ["one","two","three"], clear: false
22
+ IOHelper.output.must_equal "select:\n\e[36m‣\e[0m \e[36mone\e[0m\n two\n three\n"
23
+ end
24
+
25
+ it "it finishes selection on pressing enter" do
26
+ IOHelper.keys = "enter"
27
+ List.ask( "select", ["one","two","three"], clear: false
28
+ ).must_equal 0
29
+ end
30
+
31
+ it "selects and renders other items correctly (press down, press up, cycle)" do
32
+ IOHelper.keys = ["down","enter"]
33
+ List.ask( "select", ["one","two","three"], clear: false
34
+ ).must_equal 1
35
+ IOHelper.output.must_equal "select:\n one\n\e[36m‣\e[0m \e[36mtwo\e[0m\n three\n"
36
+
37
+ IOHelper.keys = ["down","down","enter"]
38
+ List.ask( "select", ["one","two","three"], clear: false
39
+ ).must_equal 2
40
+ IOHelper.output.must_equal "select:\n one\n two\n\e[36m‣\e[0m \e[36mthree\e[0m\n"
41
+
42
+ IOHelper.keys = ["down","down","down","enter"]
43
+ List.ask( "select", ["one","two","three"], clear: false
44
+ ).must_equal 0
45
+ IOHelper.output.must_equal "select:\n\e[36m‣\e[0m \e[36mone\e[0m\n two\n three\n"
46
+
47
+ IOHelper.keys = ["down","up","enter"]
48
+ List.ask( "select", ["one","two","three"], clear: false
49
+ ).must_equal 0
50
+ IOHelper.output.must_equal "select:\n\e[36m‣\e[0m \e[36mone\e[0m\n two\n three\n"
51
+
52
+ IOHelper.keys = ["up","enter"]
53
+ List.ask( "select", ["one","two","three"], clear: false
54
+ ).must_equal 2
55
+ IOHelper.output.must_equal "select:\n one\n two\n\e[36m‣\e[0m \e[36mthree\e[0m\n"
56
+ end
57
+
58
+ end
@@ -0,0 +1,40 @@
1
+ require 'minitest/autorun'
2
+ require 'inquirer'
3
+
4
+ begin
5
+ require 'turn'
6
+ Turn.config do |c|
7
+ # use one of output formats:
8
+ # :outline - turn's original case/test outline mode [default]
9
+ # :progress - indicates progress with progress bar
10
+ # :dotted - test/unit's traditional dot-progress mode
11
+ # :pretty - new pretty reporter
12
+ # :marshal - dump output as YAML (normal run mode only)
13
+ # :cue - interactive testing
14
+ c.format = :pretty
15
+ # turn on invoke/execute tracing, enable full backtrace
16
+ # c.trace = true
17
+ # use humanized test names (works only with :outline format)
18
+ c.natural = true
19
+ end
20
+ rescue LoadError
21
+ end
22
+
23
+ # overload all necessary methods of iohelper
24
+ # this will serve as a mock helper to read input and output
25
+ module IOHelper
26
+ extend self
27
+ attr_accessor :output, :keys
28
+ def render sth
29
+ @output += sth
30
+ end
31
+ def clear
32
+ @output = ""
33
+ end
34
+ def rerender sth
35
+ @output = sth
36
+ end
37
+ def read_key_while &block
38
+ Array(@keys).each{|key| block.(key)}
39
+ end
40
+ end
metadata ADDED
@@ -0,0 +1,78 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: inquirer
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - Dominik Richter
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2013-12-22 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: term-ansicolor
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - '>='
18
+ - !ruby/object:Gem::Version
19
+ version: 1.2.2
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - '>='
25
+ - !ruby/object:Gem::Version
26
+ version: 1.2.2
27
+ description: Interactive user prompts on CLI for ruby.
28
+ email: dominik.richter@googlemail.com
29
+ executables: []
30
+ extensions: []
31
+ extra_rdoc_files: []
32
+ files:
33
+ - .travis.yml
34
+ - CHANGELOG.md
35
+ - Gemfile
36
+ - LICENSE
37
+ - README.md
38
+ - Rakefile
39
+ - example/checkbox.png
40
+ - example/checkbox.rb
41
+ - example/list.png
42
+ - example/list.rb
43
+ - inquirer.gemspec
44
+ - lib/inquirer.rb
45
+ - lib/inquirer/prompts/checkbox.rb
46
+ - lib/inquirer/prompts/list.rb
47
+ - lib/inquirer/style.rb
48
+ - lib/inquirer/utils/iohelper.rb
49
+ - lib/inquirer/version.rb
50
+ - test/classes/checkbox_spec.rb
51
+ - test/classes/list_spec.rb
52
+ - test/minitest_helper.rb
53
+ homepage: https://github.com/arlimus/livecd
54
+ licenses:
55
+ - Apache v2
56
+ metadata: {}
57
+ post_install_message:
58
+ rdoc_options: []
59
+ require_paths:
60
+ - lib
61
+ required_ruby_version: !ruby/object:Gem::Requirement
62
+ requirements:
63
+ - - '>='
64
+ - !ruby/object:Gem::Version
65
+ version: '0'
66
+ required_rubygems_version: !ruby/object:Gem::Requirement
67
+ requirements:
68
+ - - '>='
69
+ - !ruby/object:Gem::Version
70
+ version: '0'
71
+ requirements: []
72
+ rubyforge_project:
73
+ rubygems_version: 2.0.14
74
+ signing_key:
75
+ specification_version: 4
76
+ summary: Interactive user prompts on CLI for ruby.
77
+ test_files: []
78
+ has_rdoc: