pargser 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: e3dffd531e9a47357559aa2315aaf5f3151b52e9
4
+ data.tar.gz: 5c9236c175de9fcb1af91409cd53c77720f0fcfe
5
+ SHA512:
6
+ metadata.gz: fa192889e980aef25e0691b026879ac977d69d25ad1b843d37a04876338ce372fcfda7abaa1e0ef9c6c6e9a3981beb88c51865910b49f486b0f60294f040bfd4
7
+ data.tar.gz: a75e25d2a6d8d370cbaae90e107b4cb512bda23dd2cbe03af0097484975553c473d5540b41ce18bb4ccf802830f0cfaabab985bfc069a89f49a4f08a5dd55667
data/.gitignore ADDED
@@ -0,0 +1,15 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ *.bundle
11
+ *.so
12
+ *.o
13
+ *.a
14
+ mkmf.log
15
+ .idea
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --color
2
+ --require spec_helper
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in pargser.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2015 sergeych
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,79 @@
1
+ # Pargser
2
+
3
+ The ruby way to write CLI tools without headache of parsing command line options. Let you not to
4
+ spend time on it and focus on functionality.
5
+
6
+ ## Installation
7
+
8
+ Add this line to your application's Gemfile:
9
+
10
+ ```ruby
11
+ gem 'pargser'
12
+ ```
13
+
14
+ And then execute:
15
+
16
+ $ bundle
17
+
18
+ Or install it yourself as:
19
+
20
+ $ gem install pargser
21
+
22
+ ## Usage
23
+
24
+ Very straightforward
25
+
26
+ p = Pargser.new.key('-f', '--fantastic') {
27
+ @fantastic = true
28
+ }
29
+ .key('--omit-me', doc: 'the description is optional') {
30
+ @omit = true
31
+ }
32
+ .key('--this-is', '-t', needs_value: true, doc: 'you should specify it!') { |value|
33
+ # Note that this key has no default, e.g. required
34
+ @this_is = value
35
+ }
36
+ .key('--pargser', '-p', default: 'rules!') { |value|
37
+ # There is a default so it is ok to omit it in CL
38
+ @pargser = value
39
+ }
40
+
41
+ # Parse, and return non-key arguments as array in order of appearance
42
+ command_line = %w|-f --this-is just_fine foo bar|
43
+ p.parse(command_line).should == ['foo', 'bar']
44
+
45
+ # or you can use it with blocks if you prefer to:
46
+ args = []
47
+ p.parse(command_line) { |file|
48
+ args << file
49
+ }
50
+ args.should == ['foo', 'bar']
51
+
52
+ # values now are set as requested:
53
+ @fantastic.should be_truthy
54
+ @omit.should be_falsey
55
+ @this_is.should == 'just_fine'
56
+ @pargser.should == 'rules!'
57
+
58
+ # It can easily generate also specifications:
59
+
60
+ expected_docs = <<END
61
+ -f,--fantastic
62
+ --omit-me
63
+ the description is optional
64
+ --this-is,-t value (optional)
65
+ you should specify it!
66
+ --pargser,-p value (default: rules!)
67
+ END
68
+
69
+ p.keys_doc.should == expected_docs
70
+
71
+ For details please consult documentation:
72
+
73
+ ## Contributing
74
+
75
+ 1. Fork it ( https://github.com/[my-github-username]/pargser/fork )
76
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
77
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
78
+ 4. Push to the branch (`git push origin my-new-feature`)
79
+ 5. Create a new Pull Request
data/Rakefile ADDED
@@ -0,0 +1,2 @@
1
+ require "bundler/gem_tasks"
2
+
data/lib/pargser.rb ADDED
@@ -0,0 +1,151 @@
1
+ require "pargser"
2
+
3
+ # The Ruby-Style (e,g, nice and laconic) command line parser that easily supports:
4
+ #
5
+ # --keys
6
+ # optional keys with any number of aliases aliases
7
+ # -name value
8
+ # key that wants value (next agrument), optionally with default value
9
+ # --
10
+ # no more keys past double dash
11
+ #
12
+ # and regular (all other) arguments.
13
+ #
14
+ # Also supports automatic documentation generation
15
+ #
16
+ class Pargser
17
+
18
+ VERSION = "0.1.0"
19
+
20
+ # The pargser errors, e.g. wrong usage or command line does not fit specified
21
+ # keys ocnstraints.
22
+ class Error < ArgumentError;
23
+ end
24
+
25
+ # Create parser instance with a list of arguments. Otherwise, arguments can
26
+ # be passed to #parse call.
27
+ #
28
+ # @param [Array] args arguments
29
+ def initialize args=[]
30
+ @args = args
31
+ @keys = {}
32
+ @required = Set.new
33
+ @docs = []
34
+ end
35
+
36
+ # Register key handler.
37
+ # When #parse handler blocks will be called in order of appearance in
38
+ # arguments array
39
+ #
40
+ #
41
+ # @param [String] name key name
42
+ #
43
+ # @param [Array(String)] aliases for the key
44
+ #
45
+ # @param [Boolean] :needs_value if set then the parser wants a value argument after the
46
+ # key which will be passed to block as an argument. if default param is not set and
47
+ # the key will not be detected, Pargser::Error will be raised
48
+ #
49
+ # @param [String] :default value. if set, needs_value parameter can be omitted - the handler
50
+ # block will be passed either with this value or with one specified in args.
51
+ #
52
+ # @param [String] :doc optional documentation string that will be used in #keys_doc
53
+ #
54
+ # @yield block if the key is found with optional value argument
55
+ #
56
+ def key name, *aliases, needs_value: false, doc: nil, ** kwargs, &block
57
+ k = name.to_s
58
+
59
+ default_set = false
60
+ default = nil
61
+ if kwargs.include?(:default)
62
+ default = kwargs[:default]
63
+ needs_value = true
64
+ default_set = true
65
+ end
66
+
67
+ @keys.include?(k) and raise Error, "Duplicate key registration #{k}"
68
+ data = @keys[k] = OpenStruct.new required: false,
69
+ needs_value: needs_value,
70
+ block: block,
71
+ doc: doc,
72
+ key: k,
73
+ aliases: aliases,
74
+ default: default,
75
+ default_set: default_set
76
+ @docs << data
77
+ aliases.each { |a| @keys[a.to_s] = data }
78
+ @required.add(data) if needs_value
79
+ self
80
+ end
81
+
82
+ # Process command line and call key handlers in the order of
83
+ # appearance. Then call handlers that keys which need values
84
+ # and were not called and have defaults, or raise error.
85
+ #
86
+ # The rest of arguments (non-keys) are either yielded or returned
87
+ # as an array.
88
+ #
89
+ # You can optionally set other arguments than specified in constructor
90
+ #
91
+ # @param [Array] args to parse. If specified, arguments passed to constructor
92
+ # will be ignored and lost
93
+ # @return [Array] non-keys arguments (keys afer '--' or other arguments)
94
+ # @yield [String] non keys argumenrs (same as returned)
95
+ def parse args=nil
96
+ @args = args.clone if args
97
+ no_more_keys = false
98
+ rest = []
99
+ required_keys = @required.clone
100
+
101
+ while !@args.empty?
102
+ a = @args.shift
103
+ case
104
+ when no_more_keys
105
+ rest << a
106
+ when (data = @keys[a])
107
+ required_keys.delete data
108
+ if data.needs_value
109
+ value = @args.shift or raise "Value needed for key #{a}"
110
+ data.block.call value
111
+ else
112
+ data.block.call
113
+ end
114
+ when a == '--'
115
+ no_more_keys = true
116
+ when a[0] == '-'
117
+ raise Error, "Unknown key #{a}"
118
+ else
119
+ rest << a
120
+ end
121
+ end
122
+ required_keys.each { |data|
123
+ raise Error, "Required key is missing: #{data.key}" if !data.default_set
124
+ data.block.call data.default
125
+ }
126
+ block_given? and rest.each { |a| yield a }
127
+ rest
128
+ end
129
+
130
+ # Generate keys documentation multiline text
131
+ def keys_doc
132
+ res = []
133
+ @docs.each { |d|
134
+ keys = [d.key] + d.aliases
135
+ str = "\t#{keys.join(',')}"
136
+ if d.needs_value
137
+ str += " value"
138
+ if d.default
139
+ str += " (default: #{d.default})" if d.default
140
+ else
141
+ str += ' (optional)'
142
+ end
143
+ end
144
+ res << str
145
+ d.doc and d.doc.split("\n").each { |l| res << "\t\t#{l}" }
146
+ }
147
+ res.join("\n")+"\n"
148
+ end
149
+
150
+ end
151
+
data/pargser.gemspec ADDED
@@ -0,0 +1,25 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'pargser'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "pargser"
8
+ spec.version = Pargser::VERSION
9
+ spec.authors = ["sergeych"]
10
+ spec.email = ["sergeych"]
11
+ spec.summary = %q{Very Ruby-style command line parser}
12
+ spec.description = %q{Allows to write CLI in ruby without headache of arguments parsing and
13
+ usage writing}
14
+ spec.homepage = ""
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0")
18
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
19
+ spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
20
+ spec.require_paths = ["lib"]
21
+
22
+ spec.add_development_dependency "bundler", "~> 1.7"
23
+ spec.add_development_dependency "rspec", '~> 3.1'
24
+ spec.add_development_dependency "rake", "~> 10.0"
25
+ end
@@ -0,0 +1,116 @@
1
+ require 'spec_helper'
2
+ require 'pargser'
3
+ require 'ostruct'
4
+
5
+ describe 'pargser' do
6
+
7
+ it 'should parse keys' do
8
+ parser = Pargser.new "-a -b -v value! other data".split
9
+ parser.key('-a', doc: 'flag to perform a action') {
10
+ @a_called = true
11
+ }
12
+ .key('-c', '-b') {
13
+ @b_called = true
14
+ }
15
+ .key('--some', default: 'test') { |v|
16
+ @defvalue = v
17
+ }
18
+ .key('-v', needs_value: true) { |v|
19
+ @v = v
20
+ }
21
+ expect(-> { parser.key('-a') }).to raise_error(Pargser::Error)
22
+
23
+ passed = []
24
+ rest = parser.parse { |a| passed << a }
25
+ rest.should == passed
26
+ rest.should == ['other', 'data']
27
+
28
+ @a_called.should be_truthy
29
+ @b_called.should be_truthy
30
+ @v.should == 'value!'
31
+ @defvalue.should == 'test'
32
+
33
+ doc = "\t-a\n\t\tflag to perform a action\n\t-c,-b\n\t--some value (default: test)\n\t-v value (optional)\n"
34
+ parser.keys_doc.should == doc
35
+ end
36
+
37
+ it 'should detect required keys' do
38
+ parser = Pargser.new ['hello']
39
+ parser.key('-c', needs_value: true) {}
40
+ expect(-> { parser.parse }).to raise_error(Pargser::Error, 'Required key is missing: -c')
41
+ end
42
+
43
+ it 'should detect strange keys' do
44
+ parser = Pargser.new '-l hello'.split
45
+ expect(-> { parser.parse }).to raise_error(Pargser::Error, 'Unknown key -l')
46
+ end
47
+
48
+ it 'should pass data that looks like keys' do
49
+ res = Pargser.new('-- -a --b'.split).parse
50
+ res.should == ['-a', '--b']
51
+ end
52
+
53
+ it 'should provide empty defaults' do
54
+ parser = Pargser.new('hello'.split)
55
+ @t == 'wrong'
56
+ parser.key('-t', default: nil) { |val|
57
+ @t = val
58
+ }
59
+ parser.key('-q', default: false) { |val|
60
+ @q = val
61
+ }
62
+ parser.parse.should == ['hello']
63
+ @t.should == nil
64
+ @q.should == false
65
+ end
66
+
67
+ it 'should run usage example' do
68
+
69
+ p = Pargser.new.key('-f', '--fantastic') {
70
+ @fantastic = true
71
+ }
72
+ .key('--omit-me', doc: 'the description is optional') {
73
+ @omit = true
74
+ }
75
+ .key('--this-is', '-t', needs_value: true, doc: 'you should specify it!') { |value|
76
+ # Note that this key has no default, e.g. required
77
+ @this_is = value
78
+ }
79
+ .key('--pargser', '-p', default: 'rules!') { |value|
80
+ # There is a default so it is ok to omit it in CL
81
+ @pargser = value
82
+ }
83
+
84
+ # Parse, and return non-key arguments as array in order of appearance
85
+ command_line = %w|-f --this-is just_fine foo bar|
86
+ p.parse(command_line).should == ['foo', 'bar']
87
+
88
+ # or you can use it with blocks if you prefer to:
89
+ args = []
90
+ p.parse(command_line) { |file|
91
+ args << file
92
+ }
93
+ args.should == ['foo', 'bar']
94
+
95
+ # values now are set as requested:
96
+ @fantastic.should be_truthy
97
+ @omit.should be_falsey
98
+ @this_is.should == 'just_fine'
99
+ @pargser.should == 'rules!'
100
+
101
+ # It can easily generate also specifications:
102
+
103
+ expected_docs = <<END
104
+ -f,--fantastic
105
+ --omit-me
106
+ the description is optional
107
+ --this-is,-t value (optional)
108
+ you should specify it!
109
+ --pargser,-p value (default: rules!)
110
+ END
111
+
112
+ p.keys_doc.should == expected_docs
113
+
114
+ end
115
+
116
+ end
@@ -0,0 +1,91 @@
1
+ # This file was generated by the `rspec --init` command. Conventionally, all
2
+ # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
3
+ # The generated `.rspec` file contains `--require spec_helper` which will cause this
4
+ # file to always be loaded, without a need to explicitly require it in any files.
5
+ #
6
+ # Given that it is always loaded, you are encouraged to keep this file as
7
+ # light-weight as possible. Requiring heavyweight dependencies from this file
8
+ # will add to the boot time of your test suite on EVERY test run, even for an
9
+ # individual file that may not need all of that loaded. Instead, consider making
10
+ # a separate helper file that requires the additional dependencies and performs
11
+ # the additional setup, and require it from the spec files that actually need it.
12
+ #
13
+ # The `.rspec` file also contains a few flags that are not defaults but that
14
+ # users commonly want.
15
+ #
16
+ # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
17
+ RSpec.configure do |config|
18
+ # rspec-expectations config goes here. You can use an alternate
19
+ # assertion/expectation library such as wrong or the stdlib/minitest
20
+ # assertions if you prefer.
21
+ config.expect_with :rspec do |expectations|
22
+ # This option will default to `true` in RSpec 4. It makes the `description`
23
+ # and `failure_message` of custom matchers include text for helper methods
24
+ # defined using `chain`, e.g.:
25
+ # be_bigger_than(2).and_smaller_than(4).description
26
+ # # => "be bigger than 2 and smaller than 4"
27
+ # ...rather than:
28
+ # # => "be bigger than 2"
29
+ expectations.include_chain_clauses_in_custom_matcher_descriptions = true
30
+ expectations.syntax = [:should, :expect]
31
+
32
+ end
33
+
34
+ # rspec-mocks config goes here. You can use an alternate test double
35
+ # library (such as bogus or mocha) by changing the `mock_with` option here.
36
+ config.mock_with :rspec do |mocks|
37
+ # Prevents you from mocking or stubbing a method that does not exist on
38
+ # a real object. This is generally recommended, and will default to
39
+ # `true` in RSpec 4.
40
+ mocks.verify_partial_doubles = true
41
+ end
42
+
43
+ # The settings below are suggested to provide a good initial experience
44
+ # with RSpec, but feel free to customize to your heart's content.
45
+ =begin
46
+ # These two settings work together to allow you to limit a spec run
47
+ # to individual examples or groups you care about by tagging them with
48
+ # `:focus` metadata. When nothing is tagged with `:focus`, all examples
49
+ # get run.
50
+ config.filter_run :focus
51
+ config.run_all_when_everything_filtered = true
52
+
53
+ # Limits the available syntax to the non-monkey patched syntax that is recommended.
54
+ # For more details, see:
55
+ # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax
56
+ # - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
57
+ # - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching
58
+ config.disable_monkey_patching!
59
+
60
+ # This setting enables warnings. It's recommended, but in some cases may
61
+ # be too noisy due to issues in dependencies.
62
+ config.warnings = true
63
+
64
+ # Many RSpec users commonly either run the entire suite or an individual
65
+ # file, and it's useful to allow more verbose output when running an
66
+ # individual spec file.
67
+ if config.files_to_run.one?
68
+ # Use the documentation formatter for detailed output,
69
+ # unless a formatter has already been configured
70
+ # (e.g. via a command-line flag).
71
+ config.default_formatter = 'doc'
72
+ end
73
+
74
+ # Print the 10 slowest examples and example groups at the
75
+ # end of the spec run, to help surface which specs are running
76
+ # particularly slow.
77
+ config.profile_examples = 10
78
+
79
+ # Run specs in random order to surface order dependencies. If you find an
80
+ # order dependency and want to debug it, you can fix the order by providing
81
+ # the seed, which is printed after each run.
82
+ # --seed 1234
83
+ config.order = :random
84
+
85
+ # Seed global randomization in this process using the `--seed` CLI option.
86
+ # Setting this allows you to use `--seed` to deterministically reproduce
87
+ # test failures related to randomization by passing the same `--seed` value
88
+ # as the one that triggered the failure.
89
+ Kernel.srand config.seed
90
+ =end
91
+ end
metadata ADDED
@@ -0,0 +1,100 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: pargser
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - sergeych
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2015-01-08 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.7'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.7'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rspec
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '3.1'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '3.1'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '10.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '10.0'
55
+ description: |-
56
+ Allows to write CLI in ruby without headache of arguments parsing and
57
+ usage writing
58
+ email:
59
+ - sergeych
60
+ executables: []
61
+ extensions: []
62
+ extra_rdoc_files: []
63
+ files:
64
+ - ".gitignore"
65
+ - ".rspec"
66
+ - Gemfile
67
+ - LICENSE.txt
68
+ - README.md
69
+ - Rakefile
70
+ - lib/pargser.rb
71
+ - pargser.gemspec
72
+ - spec/pargser_spec.rb
73
+ - spec/spec_helper.rb
74
+ homepage: ''
75
+ licenses:
76
+ - MIT
77
+ metadata: {}
78
+ post_install_message:
79
+ rdoc_options: []
80
+ require_paths:
81
+ - lib
82
+ required_ruby_version: !ruby/object:Gem::Requirement
83
+ requirements:
84
+ - - ">="
85
+ - !ruby/object:Gem::Version
86
+ version: '0'
87
+ required_rubygems_version: !ruby/object:Gem::Requirement
88
+ requirements:
89
+ - - ">="
90
+ - !ruby/object:Gem::Version
91
+ version: '0'
92
+ requirements: []
93
+ rubyforge_project:
94
+ rubygems_version: 2.4.5
95
+ signing_key:
96
+ specification_version: 4
97
+ summary: Very Ruby-style command line parser
98
+ test_files:
99
+ - spec/pargser_spec.rb
100
+ - spec/spec_helper.rb