From 0e8e7737ab9d4ad09a15d4d4dc076b35b2ff339a Mon Sep 17 00:00:00 2001 From: Beth Skurrie Date: Fri, 13 Oct 2023 16:53:46 +1100 Subject: [PATCH] feat: raise an error when an em dash is used instead of a normal dash --- lib/pact_broker/client/cli/custom_thor.rb | 17 +++++++++++++++++ .../pact_broker/client/cli/custom_thor_spec.rb | 12 ++++++++++++ 2 files changed, 29 insertions(+) diff --git a/lib/pact_broker/client/cli/custom_thor.rb b/lib/pact_broker/client/cli/custom_thor.rb index 5af622d..ecf0021 100644 --- a/lib/pact_broker/client/cli/custom_thor.rb +++ b/lib/pact_broker/client/cli/custom_thor.rb @@ -14,12 +14,20 @@ class AuthError < ::Thor::Error; end class CustomThor < ::Thor using PactBroker::Client::HashRefinements + EM_DASH = "\u2014" + no_commands do def self.exit_on_failure? true end + # Provide a wrapper method that can be stubbed in tests + def self.exit_with_error_code + exit(1) + end + def self.start given_args = ARGV, config = {} + check_for_mdash!(given_args) super(massage_args(given_args)) end @@ -52,6 +60,15 @@ def self.handle_help(argv) end end + def self.check_for_mdash!(argv) + if (word_with_mdash = argv.find{ |arg | arg.include?(EM_DASH) }) + # Can't use the `raise Thor::Error` approach here (which is designed to show the error without a backtrace) + # because the exception is not handled within the Thor code, and will show an ugly backtrace. + $stdout.puts "The argument '#{word_with_mdash}' contains an em dash (the long dash you get in Microsoft Word when you type two short dashes in a row). Please replace it with a normal dash and try again." + exit_with_error_code + end + end + # other task names, help, and the help shortcuts def self.known_first_arguments @known_first_arguments ||= tasks.keys + ::Thor::HELP_MAPPINGS + ['help'] diff --git a/spec/lib/pact_broker/client/cli/custom_thor_spec.rb b/spec/lib/pact_broker/client/cli/custom_thor_spec.rb index 8ae970d..3f18eb2 100644 --- a/spec/lib/pact_broker/client/cli/custom_thor_spec.rb +++ b/spec/lib/pact_broker/client/cli/custom_thor_spec.rb @@ -100,6 +100,18 @@ def test_without_parameters TestThor.start(%w{test_pact_broker_client_options}) end + describe "when someone copy pastes from Word and uses an em dash instead of a normal dash" do + before do + allow(TestThor).to receive(:exit_with_error_code) + end + + it "exits with an error message" do + expect($stdout).to receive(:puts).with(/contains an em dash/) + expect(TestThor).to receive(:exit_with_error_code) + TestThor.start(["test_default", "\u2014\u2014bar"]) + end + end + describe ".handle_help" do context "when the last argument is --help or -h" do it "turns it into the form that Thor expects, which is a really odd one" do