Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent duplicate arguments/options #143

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions lib/dry/cli/command.rb
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,12 @@ def self.example(*examples)
# # Options:
# # --help, -h # Print this help
def self.argument(name, options = {})
@arguments << Argument.new(name, options)
new_arg = Argument.new(name, options)

duplicate_index = @arguments.find_index { _1.name == new_arg.name }
@arguments.delete_at(duplicate_index) unless duplicate_index.nil?

@arguments << new_arg
end

# Command line option (aka optional argument)
Expand Down Expand Up @@ -309,7 +314,12 @@ def self.argument(name, options = {})
# # Options:
# # --port=VALUE, -p VALUE
def self.option(name, options = {})
@options << Option.new(name, options)
new_op = Option.new(name, options)

duplicate_index = @options.find_index { _1.name == new_op.name }
@options.delete_at(duplicate_index) unless duplicate_index.nil?

@options << new_op
end

# @since 0.1.0
Expand Down
33 changes: 33 additions & 0 deletions spec/unit/dry/cli/command_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# frozen_string_literal: true

RSpec.describe "Command" do
describe "option definition" do
class CommandWithDuplicateOpts < Dry::CLI::Command
option :engine, desc: "1", values: %w[irb pry ripl]
option :engine, desc: "2", values: %w[test1 test2 test3]
end

it "prevents duplicate options" do
opts = CommandWithDuplicateOpts.options
expect(opts.size).to eq(1)
op = opts.first
expect(op.name).to eq(:engine)
expect(op.desc).to eq("2: (test1/test2/test3)")
end
end

describe "argument definition" do
class CommandWithDuplicateArgs < Dry::CLI::Command
argument :version, desc: "1"
argument :version, desc: "2"
end

it "prevents duplicate arguments" do
opts = CommandWithDuplicateArgs.arguments
expect(opts.size).to eq(1)
op = opts.first
expect(op.name).to eq(:version)
expect(op.desc).to eq("2")
end
end
end