mixlib-cli 1.0.4

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.
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,75 @@
1
+ == Mixlib::CLI
2
+
3
+ Mixlib::CLI provides a class-based command line option parsing object, like the one used in Chef, Ohai and Relish. To use in your project:
4
+
5
+ require 'rubygems'
6
+ require 'mixlib/cli'
7
+
8
+ class MyCLI
9
+ include Mixlib::CLI
10
+
11
+ option :config_file,
12
+ :short => "-c CONFIG",
13
+ :long => "--config CONFIG",
14
+ :default => 'config.rb',
15
+ :description => "The configuration file to use"
16
+
17
+ option :log_level,
18
+ :short => "-l LEVEL",
19
+ :long => "--log_level LEVEL",
20
+ :description => "Set the log level (debug, info, warn, error, fatal)",
21
+ :required => true,
22
+ :proc => Proc.new { |l| l.to_sym }
23
+
24
+ option :help,
25
+ :short => "-h",
26
+ :long => "--help",
27
+ :description => "Show this message",
28
+ :on => :tail,
29
+ :boolean => true,
30
+ :show_options => true,
31
+ :exit => 0
32
+
33
+ end
34
+
35
+ # ARGV = [ '-c', 'foo.rb', '-l', 'debug' ]
36
+ cli = MyCLI.new
37
+ cli.parse_options
38
+ cli.config[:config_file] # 'foo.rb'
39
+ cli.config[:log_level] # :debug
40
+
41
+ If you are using this in conjunction with Mixlib::Config, you can do something like this (building on the above definition):
42
+
43
+ class MyConfig
44
+ extend(Mixlib::Config)
45
+
46
+ log_level :info
47
+ config_file "default.rb"
48
+ end
49
+
50
+ class MyCLI
51
+ def run(argv=ARGV)
52
+ parse_options(argv)
53
+ MyConfig.merge!(config)
54
+ end
55
+ end
56
+
57
+ c = MyCLI.new
58
+ # ARGV = [ '-l', 'debug' ]
59
+ c.run
60
+ MyConfig[:log_level] # :debug
61
+
62
+ Available arguments to 'option':
63
+
64
+ :short:: The short option, just like from optparse. Example: "-l LEVEL"
65
+ :long:: The long option, just like from optparse. Example: "--level LEVEL"
66
+ :description:: The description for this item, just like from optparse.
67
+ :default:: A default value for this option
68
+ :required:: Prints a message informing the user of the missing requirement, and exits. Default is false.
69
+ :on:: Set to :tail to appear at the end, or :head to appear at the top.
70
+ :boolean:: If this option takes no arguments, set this to true.
71
+ :show_options:: If you want the option list printed when this option is called, set this to true.
72
+ :exit:: Exit your program with the exit code when this option is specified. Example: 0
73
+ :proc:: If set, the configuration value will be set to the return value of this proc.
74
+
75
+ Have fun!
@@ -0,0 +1,55 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+
4
+ begin
5
+ require 'jeweler'
6
+ Jeweler::Tasks.new do |gem|
7
+ gem.name = "mixlib-cli"
8
+ gem.summary = "A simple mixin for CLI interfaces, including option parsing"
9
+ gem.email = "info@opscode.com"
10
+ gem.homepage = "http://www.opscode.com"
11
+ gem.authors = ["Opscode, Inc."]
12
+ end
13
+ rescue LoadError
14
+ puts "Jeweler not available. Install it with: sudo gem install technicalpickles-jeweler -s http://gems.github.com"
15
+ end
16
+
17
+ require 'spec/rake/spectask'
18
+ Spec::Rake::SpecTask.new(:spec) do |spec|
19
+ spec.libs << 'lib' << 'spec'
20
+ spec.spec_opts = ['--options', "\"#{File.dirname(__FILE__)}/spec/spec.opts\""]
21
+ spec.spec_files = FileList['spec/**/*_spec.rb']
22
+ end
23
+
24
+ Spec::Rake::SpecTask.new(:rcov) do |spec|
25
+ spec.libs << 'lib' << 'spec'
26
+ spec.pattern = 'spec/**/*_spec.rb'
27
+ spec.rcov = true
28
+ end
29
+
30
+ begin
31
+ require 'cucumber/rake/task'
32
+ Cucumber::Rake::Task.new(:features)
33
+ rescue LoadError
34
+ task :features do
35
+ abort "Cucumber is not available. In order to run features, you must: sudo gem install cucumber"
36
+ end
37
+ end
38
+
39
+ task :default => :spec
40
+
41
+ require 'rake/rdoctask'
42
+ Rake::RDocTask.new do |rdoc|
43
+ if File.exist?('VERSION.yml')
44
+ config = YAML.load(File.read('VERSION.yml'))
45
+ version = "#{config[:major]}.#{config[:minor]}.#{config[:patch]}"
46
+ else
47
+ version = ""
48
+ end
49
+
50
+ rdoc.rdoc_dir = 'rdoc'
51
+ rdoc.title = "mixlib-cli #{version}"
52
+ rdoc.rdoc_files.include('README*')
53
+ rdoc.rdoc_files.include('lib/**/*.rb')
54
+ end
55
+
@@ -0,0 +1,4 @@
1
+ ---
2
+ :major: 1
3
+ :minor: 0
4
+ :patch: 4
@@ -0,0 +1,196 @@
1
+ #
2
+ # Author:: Adam Jacob (<adam@opscode.com>)
3
+ # Copyright:: Copyright (c) 2008 Opscode, Inc.
4
+ # License:: Apache License, Version 2.0
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ #
18
+
19
+ require 'optparse'
20
+
21
+ module Mixlib
22
+ module CLI
23
+ module ClassMethods
24
+ # Add a command line option.
25
+ #
26
+ # === Parameters
27
+ # name<Symbol>:: The name of the option to add
28
+ # args<Hash>:: A hash of arguments for the option, specifying how it should be parsed.
29
+ # === Returns
30
+ # true:: Always returns true.
31
+ def option(name, args)
32
+ @options ||= {}
33
+ raise(ArgumentError, "Option name must be a symbol") unless name.kind_of?(Symbol)
34
+ @options[name.to_sym] = args
35
+ end
36
+
37
+ # Get the hash of current options.
38
+ #
39
+ # === Returns
40
+ # @options<Hash>:: The current options hash.
41
+ def options
42
+ @options ||= {}
43
+ @options
44
+ end
45
+
46
+ # Set the current options hash
47
+ #
48
+ # === Parameters
49
+ # val<Hash>:: The hash to set the options to
50
+ #
51
+ # === Returns
52
+ # @options<Hash>:: The current options hash.
53
+ def options=(val)
54
+ raise(ArgumentError, "Options must recieve a hash") unless val.kind_of?(Hash)
55
+ @options = val
56
+ end
57
+
58
+ # Change the banner. Defaults to:
59
+ # Usage: #{0} (options)
60
+ #
61
+ # === Parameters
62
+ # bstring<String>:: The string to set the banner to
63
+ #
64
+ # === Returns
65
+ # @banner<String>:: The current banner
66
+ def banner(bstring=nil)
67
+ if bstring
68
+ @banner = bstring
69
+ else
70
+ @banner ||= "Usage: #{$0} (options)"
71
+ @banner
72
+ end
73
+ end
74
+ end
75
+
76
+ attr_accessor :options, :config, :banner, :opt_parser
77
+
78
+ # Create a new Mixlib::CLI class. If you override this, make sure you call super!
79
+ #
80
+ # === Parameters
81
+ # *args<Array>:: The array of arguments passed to the initializer
82
+ #
83
+ # === Returns
84
+ # object<Mixlib::Config>:: Returns an instance of whatever you wanted :)
85
+ def initialize(*args)
86
+ @options = Hash.new
87
+ @config = Hash.new
88
+
89
+ # Set the banner
90
+ @banner = self.class.banner
91
+
92
+ # Dupe the class options for this instance
93
+ klass_options = self.class.options
94
+ klass_options.keys.inject(@options) { |memo, key| memo[key] = klass_options[key].dup; memo }
95
+
96
+ # Set the default configuration values for this instance
97
+ @options.each do |config_key, config_opts|
98
+ config_opts[:on] ||= :on
99
+ config_opts[:boolean] ||= false
100
+ config_opts[:required] ||= false
101
+ config_opts[:proc] ||= nil
102
+ config_opts[:show_options] ||= false
103
+ config_opts[:exit] ||= nil
104
+
105
+ if config_opts.has_key?(:default)
106
+ @config[config_key] = config_opts[:default]
107
+ end
108
+ end
109
+
110
+ super(*args)
111
+ end
112
+
113
+ # Parses an array, by default ARGV, for command line options (as configured at
114
+ # the class level).
115
+ # === Parameters
116
+ # argv<Array>:: The array of arguments to parse; defaults to ARGV
117
+ #
118
+ # === Returns
119
+ # argv<Array>:: Returns any un-parsed elements.
120
+ def parse_options(argv=ARGV)
121
+ @opt_parser = OptionParser.new do |opts|
122
+ # Set the banner
123
+ opts.banner = banner
124
+
125
+ # Create new options
126
+ options.sort { |a, b| a[0].to_s <=> b[0].to_s }.each do |opt_key, opt_val|
127
+ opt_args = build_option_arguments(opt_val)
128
+
129
+ opt_method = case opt_val[:on]
130
+ when :on
131
+ :on
132
+ when :tail
133
+ :on_tail
134
+ when :head
135
+ :on_head
136
+ else
137
+ raise ArgumentError, "You must pass :on, :tail, or :head to :on"
138
+ end
139
+
140
+ parse_block = case opt_val[:boolean]
141
+ when true
142
+ Proc.new() do
143
+ config[opt_key] = (opt_val[:proc] && opt_val[:proc].call(true)) || true
144
+ puts opts if opt_val[:show_options]
145
+ exit opt_val[:exit] if opt_val[:exit]
146
+ end
147
+ when false
148
+ Proc.new() do |c|
149
+ config[opt_key] = (opt_val[:proc] && opt_val[:proc].call(c)) || c
150
+ puts opts if opt_val[:show_options]
151
+ exit opt_val[:exit] if opt_val[:exit]
152
+ end
153
+ end
154
+
155
+ full_opt = [ opt_method ]
156
+ opt_args.inject(full_opt) { |memo, arg| memo << arg; memo }
157
+ full_opt << parse_block
158
+ opts.send(*full_opt)
159
+ end
160
+ end
161
+ @opt_parser.parse!(argv)
162
+
163
+ # Deal with any required values
164
+ options.each do |opt_key, opt_value|
165
+ if opt_value[:required]
166
+ reqarg = opt_value[:short] || opt_value[:long]
167
+ puts "You must supply #{reqarg}!"
168
+ puts @opt_parser
169
+ exit 2
170
+ end
171
+ end
172
+
173
+ argv
174
+ end
175
+
176
+ def build_option_arguments(opt_setting)
177
+ arguments = Array.new
178
+
179
+ arguments << opt_setting[:short] if opt_setting.has_key?(:short)
180
+ arguments << opt_setting[:long] if opt_setting.has_key?(:long)
181
+
182
+ if opt_setting.has_key?(:description)
183
+ description = opt_setting[:description]
184
+ description << " (required)" if opt_setting[:required]
185
+ arguments << description
186
+ end
187
+
188
+ arguments
189
+ end
190
+
191
+ def self.included(receiver)
192
+ receiver.extend(Mixlib::CLI::ClassMethods)
193
+ end
194
+
195
+ end
196
+ end
@@ -0,0 +1,197 @@
1
+ #
2
+ # Author:: Adam Jacob (<adam@opscode.com>)
3
+ # Copyright:: Copyright (c) 2008 Opscode, Inc.
4
+ # License:: Apache License, Version 2.0
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ #
18
+
19
+ require File.expand_path(File.join(File.dirname(__FILE__), "..", "spec_helper"))
20
+
21
+ describe Mixlib::CLI do
22
+ after(:each) do
23
+ TestCLI.options = {}
24
+ TestCLI.banner("Usage: #{$0} (options)")
25
+ end
26
+
27
+ describe "class method" do
28
+ describe "option" do
29
+ it "should allow you to set a config option with a hash" do
30
+ TestCLI.option(:config_file, :short => '-c CONFIG').should == { :short => '-c CONFIG' }
31
+ end
32
+ end
33
+
34
+ describe "options" do
35
+ it "should return the current options hash" do
36
+ TestCLI.option(:config_file, :short => '-c CONFIG')
37
+ TestCLI.options.should == { :config_file => { :short => '-c CONFIG' } }
38
+ end
39
+ end
40
+
41
+ describe "options=" do
42
+ it "should allow you to set the full options with a single hash" do
43
+ TestCLI.options = { :config_file => { :short => '-c CONFIG' } }
44
+ TestCLI.options.should == { :config_file => { :short => '-c CONFIG' } }
45
+ end
46
+ end
47
+
48
+ describe "banner" do
49
+ it "should have a default value" do
50
+ TestCLI.banner.should =~ /^Usage: (.+) \(options\)$/
51
+ end
52
+
53
+ it "should allow you to set the banner" do
54
+ TestCLI.banner("Usage: foo")
55
+ TestCLI.banner.should == "Usage: foo"
56
+ end
57
+ end
58
+ end
59
+
60
+ describe "instance methods" do
61
+
62
+ before(:each) do
63
+ @cli = TestCLI.new
64
+ end
65
+
66
+ describe "initialize" do
67
+ it "should set the banner to the class defined banner" do
68
+ @cli.banner.should == TestCLI.banner
69
+ end
70
+
71
+ it "should set the options to the class defined options, plus defaults" do
72
+ TestCLI.option(:config_file, :short => "-l LOG")
73
+ cli = TestCLI.new
74
+ cli.options.should == {
75
+ :config_file => {
76
+ :short => "-l LOG",
77
+ :on => :on,
78
+ :boolean => false,
79
+ :required => false,
80
+ :proc => nil,
81
+ :show_options => false,
82
+ :exit => nil
83
+ }
84
+ }
85
+ end
86
+
87
+ it "should set the default config value for any options that include it" do
88
+ TestCLI.option(:config_file, :short => "-l LOG", :default => :debug)
89
+ @cli = TestCLI.new
90
+ @cli.config[:config_file].should == :debug
91
+ end
92
+ end
93
+
94
+ describe "parse_options" do
95
+ it "should set the banner in opt_parse" do
96
+ @cli.parse_options([])
97
+ @cli.opt_parser.banner.should == @cli.banner
98
+ end
99
+
100
+ it "should present the arguments in the banner" do
101
+ TestCLI.option(:config_file, :short => "-l LOG")
102
+ @cli = TestCLI.new
103
+ @cli.parse_options([])
104
+ @cli.opt_parser.to_s.should =~ /-l LOG/
105
+ end
106
+
107
+ it "should honor :on => :tail options in the banner" do
108
+ TestCLI.option(:config_file, :short => "-l LOG")
109
+ TestCLI.option(:help, :short => "-h", :boolean => true, :on => :tail)
110
+ @cli = TestCLI.new
111
+ @cli.parse_options([])
112
+ @cli.opt_parser.to_s.split("\n").last.should =~ /-h/
113
+ end
114
+
115
+ it "should honor :on => :head options in the banner" do
116
+ TestCLI.option(:config_file, :short => "-l LOG")
117
+ TestCLI.option(:help, :short => "-h", :boolean => true, :on => :head)
118
+ @cli = TestCLI.new
119
+ @cli.parse_options([])
120
+ @cli.opt_parser.to_s.split("\n")[1].should =~ /-h/
121
+ end
122
+
123
+ it "should present the arguments in alphabetical order in the banner" do
124
+ TestCLI.option(:alpha, :short => "-a ALPHA")
125
+ TestCLI.option(:beta, :short => "-b BETA")
126
+ TestCLI.option(:zeta, :short => "-z ZETA")
127
+ @cli = TestCLI.new
128
+ @cli.parse_options([])
129
+ output_lines = @cli.opt_parser.to_s.split("\n")
130
+ output_lines[1].should =~ /-a ALPHA/
131
+ output_lines[2].should =~ /-b BETA/
132
+ output_lines[3].should =~ /-z ZETA/
133
+ end
134
+
135
+ it "should set the corresponding config value for non-boolean arguments" do
136
+ TestCLI.option(:config_file, :short => "-c CONFIG")
137
+ @cli = TestCLI.new
138
+ @cli.parse_options([ '-c', 'foo.rb' ])
139
+ @cli.config[:config_file].should == 'foo.rb'
140
+ end
141
+
142
+ it "should set the corresponding config value according to a supplied proc" do
143
+ TestCLI.option(:number,
144
+ :short => "-n NUMBER",
145
+ :proc => Proc.new { |config| config.to_i + 2 }
146
+ )
147
+ @cli = TestCLI.new
148
+ @cli.parse_options([ "-n", "2" ])
149
+ @cli.config[:number].should == 4
150
+ end
151
+
152
+ it "should set the corresponding config value to true for boolean arguments" do
153
+ TestCLI.option(:i_am_boolean, :short => "-i", :boolean => true)
154
+ @cli = TestCLI.new
155
+ @cli.parse_options([ '-i' ])
156
+ @cli.config[:i_am_boolean].should == true
157
+ end
158
+
159
+ it "should exit if a config option has :exit set" do
160
+ TestCLI.option(:i_am_exit, :short => "-x", :boolean => true, :exit => 0)
161
+ @cli = TestCLI.new
162
+ lambda { @cli.parse_options(["-x"]) }.should raise_error(SystemExit)
163
+ end
164
+
165
+ it "should exit if a required option is missing" do
166
+ TestCLI.option(:require_me, :short => "-r", :boolean => true, :required => true)
167
+ @cli = TestCLI.new
168
+ lambda { @cli.parse_options([]) }.should raise_error(SystemExit)
169
+ end
170
+
171
+ end
172
+ end
173
+
174
+ end
175
+
176
+
177
+ # option :config_file,
178
+ # :short => "-c CONFIG",
179
+ # :long => "--config CONFIG",
180
+ # :default => 'config.rb',
181
+ # :description => "The configuration file to use"
182
+ #
183
+ # option :log_level,
184
+ # :short => "-l LEVEL",
185
+ # :long => "--log_level LEVEL",
186
+ # :description => "Set the log level (debug, info, warn, error, fatal)",
187
+ # :required => true,
188
+ # :proc => nil
189
+ #
190
+ # option :help,
191
+ # :short => "-h",
192
+ # :long => "--help",
193
+ # :description => "Show this message",
194
+ # :on => :tail,
195
+ # :boolean => true,
196
+ # :show_options => true,
197
+ # :exit => 0
@@ -0,0 +1,9 @@
1
+ $TESTING=true
2
+ $:.push File.join(File.dirname(__FILE__), '..', 'lib')
3
+
4
+ require 'mixlib/cli'
5
+
6
+ class TestCLI
7
+ include Mixlib::CLI
8
+ end
9
+
metadata ADDED
@@ -0,0 +1,63 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: mixlib-cli
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.4
5
+ platform: ruby
6
+ authors:
7
+ - Opscode, Inc.
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+
12
+ date: 2009-05-12 00:00:00 +12:00
13
+ default_executable:
14
+ dependencies: []
15
+
16
+ description:
17
+ email: info@opscode.com
18
+ executables: []
19
+
20
+ extensions: []
21
+
22
+ extra_rdoc_files:
23
+ - LICENSE
24
+ - README.rdoc
25
+ files:
26
+ - LICENSE
27
+ - README.rdoc
28
+ - Rakefile
29
+ - VERSION.yml
30
+ - lib/mixlib/cli.rb
31
+ - spec/mixlib/cli_spec.rb
32
+ - spec/spec_helper.rb
33
+ has_rdoc: true
34
+ homepage: http://www.opscode.com
35
+ licenses: []
36
+
37
+ post_install_message:
38
+ rdoc_options:
39
+ - --charset=UTF-8
40
+ require_paths:
41
+ - lib
42
+ required_ruby_version: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: "0"
47
+ version:
48
+ required_rubygems_version: !ruby/object:Gem::Requirement
49
+ requirements:
50
+ - - ">="
51
+ - !ruby/object:Gem::Version
52
+ version: "0"
53
+ version:
54
+ requirements: []
55
+
56
+ rubyforge_project:
57
+ rubygems_version: 1.3.5
58
+ signing_key:
59
+ specification_version: 3
60
+ summary: A simple mixin for CLI interfaces, including option parsing
61
+ test_files:
62
+ - spec/mixlib/cli_spec.rb
63
+ - spec/spec_helper.rb