From ad4a8caf673a4de1eb02e82c0463bb3da834704f Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Mon, 15 Aug 2022 12:11:48 +0900 Subject: [PATCH] [Fix #10921] Fix an error when processing configuration file Fixes #10921. This PR fixes an error when ERB pre-processing of the configuration file. --- .../fix_an_error_when_using_erb_in_confi.md | 1 + lib/rubocop/server/cache.rb | 17 ++++++++------- spec/rubocop/server/cache_spec.rb | 21 +++++++++++++++++++ 3 files changed, 31 insertions(+), 8 deletions(-) create mode 100644 changelog/fix_an_error_when_using_erb_in_confi.md diff --git a/changelog/fix_an_error_when_using_erb_in_confi.md b/changelog/fix_an_error_when_using_erb_in_confi.md new file mode 100644 index 00000000000..aaebb656813 --- /dev/null +++ b/changelog/fix_an_error_when_using_erb_in_confi.md @@ -0,0 +1 @@ +* [#10921](https://github.com/rubocop/rubocop/issues/10921): Fix an error when ERB pre-processing of the configuration file. ([@koic][]) diff --git a/lib/rubocop/server/cache.rb b/lib/rubocop/server/cache.rb index ce1861eebef..226cdf6ad6b 100644 --- a/lib/rubocop/server/cache.rb +++ b/lib/rubocop/server/cache.rb @@ -62,17 +62,18 @@ def cache_root_dir_from_config # `RuboCop::ConfigStore` has heavy dependencies, this is a lightweight implementation # so that only the necessary `CacheRootDirectory` can be obtained. require 'yaml' - config_path = ConfigFinder.find_config_path(Dir.pwd) - # Ruby 3.1+ - config_yaml = if Gem::Version.new(Psych::VERSION) >= Gem::Version.new('4.0.0') - YAML.safe_load_file(config_path, permitted_classes: [Regexp, Symbol]) - else - config = YAML.load_file(config_path) + require 'erb' + file_contents = File.read(config_path) + yaml_code = ERB.new(file_contents).result + + config_yaml = YAML.safe_load(yaml_code, permitted_classes: [Regexp, Symbol]) - config == false ? nil : config - end + # For compatibility with Ruby 3.0 or lower. + if Gem::Version.new(Psych::VERSION) < Gem::Version.new('4.0.0') + config_yaml == false ? nil : config_yaml + end config_yaml&.dig('AllCops', 'CacheRootDirectory') end diff --git a/spec/rubocop/server/cache_spec.rb b/spec/rubocop/server/cache_spec.rb index 5a3487a9db6..02d3b11910c 100644 --- a/spec/rubocop/server/cache_spec.rb +++ b/spec/rubocop/server/cache_spec.rb @@ -219,5 +219,26 @@ end end end + + context 'when ERB pre-processing of the configuration file', :isolated_environment do + context 'when cache root path is not specified path' do + before do + cache_class.cache_root_path = nil + end + + it 'does not raise an error' do + create_file('.rubocop.yml', <<~YAML) + Style/Encoding: + Enabled: <%= 1 == 1 %> + Exclude: + <% Dir['*.rb'].sort.each do |name| %> + - <%= name %> + <% end %> + YAML + + expect { cache_class.cache_path }.not_to raise_error + end + end + end end end