Skip to content
Browse files

Take parse_commandline_args from Alf

  • Loading branch information...
1 parent 4510299 commit c3303bd8511d34a913ed13cfd82345fde42bfcd8 @blambeau committed Jul 28, 2011
Showing with 88 additions and 2 deletions.
  1. +5 −0 CHANGELOG.md
  2. +31 −2 lib/quickl.rb
  3. +52 −0 spec/quickl/test_parse_commandline_args.rb
View
5 CHANGELOG.md
@@ -5,6 +5,11 @@
* A single dash option (e.g. -v) is now correctly recognized by a Delegator
command ("No such command -v" was previously raised)
+* Enhancements
+
+ * Added Quickl.parse_commandline_args that converts a commandline string to
+ an ARGV array. This is mainly provided for testing purposes.
+
* Deprecations
The following methods are deprecated and will be removed in 0.4.0 (run with
View
33 lib/quickl.rb
@@ -101,6 +101,35 @@ def self.valid_read_file!(file, error_class = nil, msg = nil)
raise error_class, msg, caller
end
end
+
+ #
+ # Parse a string with commandline arguments and returns an array.
+ #
+ # Example:
+ #
+ # parse_commandline_args("--text --size=10") # => ['--text', '--size=10']
+ #
+ def self.parse_commandline_args(args)
+ args = args.split(/\s+/)
+ result = []
+ until args.empty?
+ quote = ['"', "'"].find{|q| q == args.first[0,1]}
+ if quote
+ if args.first[-1,1] == quote
+ result << args.shift[1...-1]
+ else
+ block = [ args.shift[1..-1] ]
+ while args.first[-1,1] != quote
+ block << args.shift
+ end
+ block << args.shift[0...-1]
+ result << block.join(" ")
+ end
+ else
+ result << args.shift
+ end
+ end
+ result
+ end
-
-end # module Quickl
+end # module Quickl
View
52 spec/quickl/test_parse_commandline_args.rb
@@ -0,0 +1,52 @@
+require 'spec_helper'
+describe "Quickl#parse_commandline_args" do
+
+ subject{ Quickl.parse_commandline_args(args) }
+
+ describe "on empty string" do
+ let(:args){ "" }
+ it { should eq([]) }
+ end
+
+ describe "on pseudo empty string" do
+ let(:args){ " " }
+ it { should eq([]) }
+ end
+
+ describe "on a single arg" do
+ let(:args){ "--text" }
+ it { should eq(["--text"]) }
+ end
+
+ describe "on a multiple args" do
+ let(:args){ "--text --size=10" }
+ it { should eq(["--text", "--size=10"]) }
+ end
+
+ describe "on single quoted arg" do
+ let(:args){ "'hello'" }
+ it { should eq(["hello"]) }
+ end
+
+ describe "on single quoted arg with spacing" do
+ let(:args){ "'hello the world'" }
+ it { should eq(["hello the world"]) }
+ end
+
+ describe "on double quoted arg" do
+ let(:args){ '"hello"' }
+ it { should eq(["hello"]) }
+ end
+
+ describe "on double quoted arg with spacing" do
+ let(:args){ "'hello the world'" }
+ it { should eq(['hello the world']) }
+ end
+
+ describe "on typical example" do
+ let(:args){ %q{--verbose 'hello the world' -g -Ilib --term='none'}}
+ it{ should eq(["--verbose", 'hello the world', "-g", "-Ilib", "--term='none'"]) }
+ end
+
+
+end

0 comments on commit c3303bd

Please sign in to comment.
Something went wrong with that request. Please try again.