diff options
author | Tim Smith <tsmith84@gmail.com> | 2020-06-11 15:02:42 -0700 |
---|---|---|
committer | Tim Smith <tsmith84@gmail.com> | 2020-06-11 15:32:53 -0700 |
commit | 5825eea4b139b9af089c3075d042d5d3160583ec (patch) | |
tree | fd79641ded1857ee4166b6e9ba774a35ab47b06b | |
parent | 3889eddfc9944b23caea412d05c08b9b156cb50f (diff) | |
download | chef-5825eea4b139b9af089c3075d042d5d3160583ec.tar.gz |
Use .match? not =~ when match values aren't necessary
Autocorrected from RuboCop Performance which is now smart enough to detect when you use the match and when you don't. Using match? does not create any objects so it's slightly faster and uses less memory.
Signed-off-by: Tim Smith <tsmith@chef.io>
80 files changed, 118 insertions, 118 deletions
@@ -84,7 +84,7 @@ eval_gemfile("./Gemfile.local") if File.exist?("./Gemfile.local") # # We copy (and overwrite) these files every time "bundle <exec|install>" is # executed, just in case they have changed. -if RUBY_PLATFORM =~ /mswin|mingw|windows/ +if RUBY_PLATFORM.match?(/mswin|mingw|windows/) instance_eval do ruby_exe_dir = RbConfig::CONFIG["bindir"] assemblies = Dir.glob(File.expand_path("distro/ruby_bin_folder", Dir.pwd) + "/*.dll") diff --git a/chef-config/lib/chef-config/config.rb b/chef-config/lib/chef-config/config.rb index 7fc2e2c91e..bbf686af18 100644 --- a/chef-config/lib/chef-config/config.rb +++ b/chef-config/lib/chef-config/config.rb @@ -450,7 +450,7 @@ module ChefConfig default :repo_mode do if local_mode && !chef_zero.osc_compat "hosted_everything" - elsif chef_server_url =~ %r{/+organizations/.+} + elsif %r{/+organizations/.+}.match?(chef_server_url) "hosted_everything" else "everything" @@ -506,7 +506,7 @@ module ChefConfig default(:chef_server_root) do # if the chef_server_url is a path to an organization, aka # 'some_url.../organizations/*' then remove the '/organization/*' by default - if configuration[:chef_server_url] =~ %r{/organizations/\S*$} + if %r{/organizations/\S*$}.match?(configuration[:chef_server_url]) configuration[:chef_server_url].split("/")[0..-3].join("/") elsif configuration[:chef_server_url] # default to whatever chef_server_url is configuration[:chef_server_url] @@ -1118,7 +1118,7 @@ module ChefConfig # proxy before parsing. The regex /^.*:\/\// matches, for example, http://. Reusing proxy # here since we are really just trying to get the string built correctly. proxy = unless proxy_env_var.empty? - if proxy_env_var =~ %r{^.*://} + if %r{^.*://}.match?(proxy_env_var) URI.parse(proxy_env_var) else URI.parse("#{scheme}://#{proxy_env_var}") diff --git a/chef-config/lib/chef-config/path_helper.rb b/chef-config/lib/chef-config/path_helper.rb index 8429a08c1f..570e666e10 100644 --- a/chef-config/lib/chef-config/path_helper.rb +++ b/chef-config/lib/chef-config/path_helper.rb @@ -91,7 +91,7 @@ module ChefConfig def self.windows_max_length_exceeded?(path) # Check to see if paths without the \\?\ prefix are over the maximum allowed length for the Windows API # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx - unless path =~ /^\\\\?\\/ + unless /^\\\\?\\/.match?(path) if path.length > WIN_MAX_PATH return true end @@ -103,7 +103,7 @@ module ChefConfig def self.printable?(string) # returns true if string is free of non-printable characters (escape sequences) # this returns false for whitespace escape sequences as well, e.g. \n\t - if string =~ /[^[:print:]]/ + if /[^[:print:]]/.match?(string) false else true diff --git a/chef-utils/spec/unit/dsl/platform_family_spec.rb b/chef-utils/spec/unit/dsl/platform_family_spec.rb index 2783411d3d..bcd0f3412c 100644 --- a/chef-utils/spec/unit/dsl/platform_family_spec.rb +++ b/chef-utils/spec/unit/dsl/platform_family_spec.rb @@ -209,7 +209,7 @@ RSpec.describe ChefUtils::DSL::PlatformFamily do end context "node-independent windows APIs" do - if RUBY_PLATFORM =~ /mswin|mingw32|windows/ + if RUBY_PLATFORM.match?(/mswin|mingw32|windows/) it "reports true for :windows_ruby?" do expect(described_class.windows_ruby?).to be true end diff --git a/lib/chef/application/base.rb b/lib/chef/application/base.rb index 382fd3d66b..d9dff86795 100644 --- a/lib/chef/application/base.rb +++ b/lib/chef/application/base.rb @@ -363,7 +363,7 @@ class Chef::Application::Base < Chef::Application Chef::Log.trace("Download recipes tarball from #{url} to #{path}") if File.exist?(url) FileUtils.cp(url, path) - elsif url =~ URI.regexp + elsif url&.match?(URI.regexp) File.open(path, "wb") do |f| open(url) do |r| f.write(r.read) diff --git a/lib/chef/application/client.rb b/lib/chef/application/client.rb index ba7f8214ab..af942c0254 100644 --- a/lib/chef/application/client.rb +++ b/lib/chef/application/client.rb @@ -39,7 +39,7 @@ class Chef::Application::Client < Chef::Application::Base long: "--daemonize [WAIT]", description: "Daemonize the process. Accepts an optional integer which is the " \ "number of seconds to wait before the first daemonized run.", - proc: lambda { |wait| wait =~ /^\d+$/ ? wait.to_i : true } + proc: lambda { |wait| /^\d+$/.match?(wait) ? wait.to_i : true } end option :pid_file, diff --git a/lib/chef/application/windows_service_manager.rb b/lib/chef/application/windows_service_manager.rb index 6afb9eec50..25ac72e014 100644 --- a/lib/chef/application/windows_service_manager.rb +++ b/lib/chef/application/windows_service_manager.rb @@ -16,7 +16,7 @@ # limitations under the License. # -if RUBY_PLATFORM =~ /mswin|mingw32|windows/ +if RUBY_PLATFORM.match?(/mswin|mingw32|windows/) require "win32/service" end require_relative "../config" diff --git a/lib/chef/chef_fs/data_handler/data_bag_item_data_handler.rb b/lib/chef/chef_fs/data_handler/data_bag_item_data_handler.rb index bb42b89cfd..4f9a7ae151 100644 --- a/lib/chef/chef_fs/data_handler/data_bag_item_data_handler.rb +++ b/lib/chef/chef_fs/data_handler/data_bag_item_data_handler.rb @@ -55,7 +55,7 @@ class Chef base_name = remove_dot_json(entry.name) if object["raw_data"]["id"] != base_name yield("ID in #{entry.path_for_printing} must be '#{base_name}' (is '#{object["raw_data"]["id"]}')") - elsif entry.parent.name =~ RESERVED_NAMES + elsif RESERVED_NAMES.match?(entry.parent.name) yield("Data bag name ('#{entry.parent.name}') must not match #{RESERVED_NAMES.inspect}") end end diff --git a/lib/chef/chef_fs/path_utils.rb b/lib/chef/chef_fs/path_utils.rb index 31f1f6f12a..1682120c86 100644 --- a/lib/chef/chef_fs/path_utils.rb +++ b/lib/chef/chef_fs/path_utils.rb @@ -118,7 +118,7 @@ class Chef if ancestor.length == path.length "" - elsif path[ancestor.length, 1] =~ /#{PathUtils.regexp_path_separator}/ + elsif /#{PathUtils.regexp_path_separator}/.match?(path[ancestor.length, 1]) path[ancestor.length + 1..-1] else nil diff --git a/lib/chef/cookbook/chefignore.rb b/lib/chef/cookbook/chefignore.rb index 8f5b4516c4..41a0e44c54 100644 --- a/lib/chef/cookbook/chefignore.rb +++ b/lib/chef/cookbook/chefignore.rb @@ -50,7 +50,7 @@ class Chef ignore_globs = [] if @ignore_file && readable_file_or_symlink?(@ignore_file) File.foreach(@ignore_file) do |line| - ignore_globs << line.strip unless line =~ COMMENTS_AND_WHITESPACE + ignore_globs << line.strip unless COMMENTS_AND_WHITESPACE.match?(line) end else Chef::Log.debug("No chefignore file found. No files will be ignored!") diff --git a/lib/chef/cookbook/metadata.rb b/lib/chef/cookbook/metadata.rb index c1393abcab..7f6d972771 100644 --- a/lib/chef/cookbook/metadata.rb +++ b/lib/chef/cookbook/metadata.rb @@ -391,7 +391,7 @@ class Chef def recipes_from_cookbook_version(cookbook) cookbook.fully_qualified_recipe_names.map do |recipe_name| unqualified_name = - if recipe_name =~ /::default$/ + if /::default$/.match?(recipe_name) name.to_s else recipe_name diff --git a/lib/chef/cookbook_version.rb b/lib/chef/cookbook_version.rb index 2e9bb77151..62407aa314 100644 --- a/lib/chef/cookbook_version.rb +++ b/lib/chef/cookbook_version.rb @@ -392,7 +392,7 @@ class Chef platform, version = Chef::Platform.find_platform_and_version(node) rescue ArgumentError => e # Skip platform/version if they were not found by find_platform_and_version - if e.message =~ /Cannot find a (?:platform|version)/ + if /Cannot find a (?:platform|version)/.match?(e.message) platform = "/unknown_platform/" version = "/unknown_platform_version/" else @@ -527,7 +527,7 @@ class Chef cb["version"] end rescue Net::HTTPClientException => e - if e.to_s =~ /^404/ + if /^404/.match?(e.to_s) Chef::Log.error("Cannot find a cookbook named #{cookbook_name}") nil else diff --git a/lib/chef/data_bag.rb b/lib/chef/data_bag.rb index 5715f1970d..6be18dad58 100644 --- a/lib/chef/data_bag.rb +++ b/lib/chef/data_bag.rb @@ -36,10 +36,10 @@ class Chef RESERVED_NAMES = /^(node|role|environment|client)$/.freeze def self.validate_name!(name) - unless name =~ VALID_NAME + unless VALID_NAME.match?(name) raise Exceptions::InvalidDataBagName, "DataBags must have a name matching #{VALID_NAME.inspect}, you gave #{name.inspect}" end - if name =~ RESERVED_NAMES + if RESERVED_NAMES.match?(name) raise Exceptions::InvalidDataBagName, "DataBags may not have a name matching #{RESERVED_NAMES.inspect}, you gave #{name.inspect}" end end diff --git a/lib/chef/file_access_control.rb b/lib/chef/file_access_control.rb index 72e700566a..c192a24d4d 100644 --- a/lib/chef/file_access_control.rb +++ b/lib/chef/file_access_control.rb @@ -26,7 +26,7 @@ class Chef # the values specified by a value object, usually a Chef::Resource. class FileAccessControl - if RUBY_PLATFORM =~ /mswin|mingw|windows/ + if RUBY_PLATFORM.match?(/mswin|mingw|windows/) require_relative "file_access_control/windows" include FileAccessControl::Windows else diff --git a/lib/chef/formatters/error_inspectors/resource_failure_inspector.rb b/lib/chef/formatters/error_inspectors/resource_failure_inspector.rb index dd072909fb..439bcbb8a3 100644 --- a/lib/chef/formatters/error_inspectors/resource_failure_inspector.rb +++ b/lib/chef/formatters/error_inspectors/resource_failure_inspector.rb @@ -79,8 +79,8 @@ class Chef loop do # low rent parser. try to gracefully handle nested blocks in resources - nesting += 1 if lines[current_line] =~ /[\s]+do[\s]*/ - nesting -= 1 if lines[current_line] =~ /end[\s]*$/ + nesting += 1 if /[\s]+do[\s]*/.match?(lines[current_line]) + nesting -= 1 if /end[\s]*$/.match?(lines[current_line]) relevant_lines << format_line(current_line, lines[current_line]) diff --git a/lib/chef/http.rb b/lib/chef/http.rb index 207c616086..2a21aef191 100644 --- a/lib/chef/http.rb +++ b/lib/chef/http.rb @@ -327,7 +327,7 @@ class Chef def create_url(path) return path if path.is_a?(URI) - if path =~ %r{^(http|https|chefzero)://}i + if %r{^(http|https|chefzero)://}i.match?(path) URI.parse(path) elsif path.nil? || path.empty? URI.parse(@url) diff --git a/lib/chef/http/http_request.rb b/lib/chef/http/http_request.rb index 99a9a84d4e..9569c4133a 100644 --- a/lib/chef/http/http_request.rb +++ b/lib/chef/http/http_request.rb @@ -128,7 +128,7 @@ class Chef rescue NoMethodError => e # http://redmine.ruby-lang.org/issues/show/2708 # http://redmine.ruby-lang.org/issues/show/2758 - if e.to_s =~ /#{Regexp.escape(%q{undefined method `closed?' for nil:NilClass})}/ + if /#{Regexp.escape(%q{undefined method `closed?' for nil:NilClass})}/.match?(e.to_s) Chef::Log.trace("Rescued error in http connect, re-raising as Errno::ECONNREFUSED to hide bug in net/http") Chef::Log.trace("#{e.class.name}: #{e}") Chef::Log.trace(e.backtrace.join("\n")) diff --git a/lib/chef/http/json_output.rb b/lib/chef/http/json_output.rb index f2614237c5..bad009bd14 100644 --- a/lib/chef/http/json_output.rb +++ b/lib/chef/http/json_output.rb @@ -47,7 +47,7 @@ class Chef # needed to keep conditional get stuff working correctly. return [http_response, rest_request, return_value] if return_value == false - if http_response["content-type"] =~ /json/ + if /json/.match?(http_response["content-type"]) if http_response.body.nil? return_value = nil elsif raw_output diff --git a/lib/chef/knife.rb b/lib/chef/knife.rb index 2531059d37..88e79b3c2e 100644 --- a/lib/chef/knife.rb +++ b/lib/chef/knife.rb @@ -248,7 +248,7 @@ class Chef category_desc = preferred_category ? preferred_category + " " : "" msg "Available #{category_desc}subcommands: (for details, knife SUB-COMMAND --help)\n\n" subcommand_loader.list_commands(preferred_category).sort.each do |category, commands| - next if category =~ /deprecated/i + next if /deprecated/i.match?(category) msg "** #{category.upcase} COMMANDS **" commands.sort.each do |command| diff --git a/lib/chef/knife/client_bulk_delete.rb b/lib/chef/knife/client_bulk_delete.rb index 1c71b74ca9..38d25583b3 100644 --- a/lib/chef/knife/client_bulk_delete.rb +++ b/lib/chef/knife/client_bulk_delete.rb @@ -44,7 +44,7 @@ class Chef clients_to_delete = {} validators_to_delete = {} all_clients.each do |name, client| - next unless name =~ matcher + next unless name&.match?(matcher) if client.validator validators_to_delete[client.name] = client diff --git a/lib/chef/knife/config_get.rb b/lib/chef/knife/config_get.rb index c194188d2a..47a0040a83 100644 --- a/lib/chef/knife/config_get.rb +++ b/lib/chef/knife/config_get.rb @@ -75,7 +75,7 @@ class Chef # It's a regex. filter_re = Regexp.new($1, $2 ? Regexp::IGNORECASE : 0) config_data.each do |key, value| - output_data[key] = value if key.to_s =~ filter_re + output_data[key] = value if key.to_s&.match?(filter_re) end else # It's a dotted path string. diff --git a/lib/chef/knife/cookbook_delete.rb b/lib/chef/knife/cookbook_delete.rb index 1b184c3ae9..04ecb95cf4 100644 --- a/lib/chef/knife/cookbook_delete.rb +++ b/lib/chef/knife/cookbook_delete.rb @@ -89,7 +89,7 @@ class Chef url_and_version["versions"].map { |url_by_version| url_by_version["version"] } end.flatten rescue Net::HTTPClientException => e - if e.to_s =~ /^404/ + if /^404/.match?(e.to_s) ui.error("Cannot find a cookbook named #{@cookbook_name} to delete.") nil else diff --git a/lib/chef/knife/core/cookbook_scm_repo.rb b/lib/chef/knife/core/cookbook_scm_repo.rb index e5618706f6..31654d2954 100644 --- a/lib/chef/knife/core/cookbook_scm_repo.rb +++ b/lib/chef/knife/core/cookbook_scm_repo.rb @@ -58,7 +58,7 @@ class Chef exit 1 end cmd = git("status --porcelain") - if cmd.stdout =~ DIRTY_REPO + if DIRTY_REPO.match?(cmd.stdout) ui.error "You have uncommitted changes to your cookbook repo (#{repo_path}):" ui.msg cmd.stdout ui.info "Commit or stash your changes before importing cookbooks" diff --git a/lib/chef/knife/data_bag_create.rb b/lib/chef/knife/data_bag_create.rb index 51fb907c34..11448c69b7 100644 --- a/lib/chef/knife/data_bag_create.rb +++ b/lib/chef/knife/data_bag_create.rb @@ -54,7 +54,7 @@ class Chef rest.get("data/#{@data_bag_name}") ui.info("Data bag #{@data_bag_name} already exists") rescue Net::HTTPClientException => e - raise unless e.to_s =~ /^404/ + raise unless /^404/.match?(e.to_s) # if it doesn't exists, try to create it rest.post("data", { "name" => @data_bag_name }) diff --git a/lib/chef/knife/node_bulk_delete.rb b/lib/chef/knife/node_bulk_delete.rb index 0caf5dd604..874509b730 100644 --- a/lib/chef/knife/node_bulk_delete.rb +++ b/lib/chef/knife/node_bulk_delete.rb @@ -39,7 +39,7 @@ class Chef matcher = /#{name_args[0]}/ all_nodes.each do |name, node| - next unless name =~ matcher + next unless name&.match?(matcher) nodes_to_delete[name] = node end diff --git a/lib/chef/knife/node_run_list_remove.rb b/lib/chef/knife/node_run_list_remove.rb index 8331844171..08f4e5d382 100644 --- a/lib/chef/knife/node_run_list_remove.rb +++ b/lib/chef/knife/node_run_list_remove.rb @@ -49,7 +49,7 @@ class Chef node.run_list.remove(e) else ui.warn "#{e} is not in the run list" - unless e =~ /^(recipe|role)\[/ + unless /^(recipe|role)\[/.match?(e) ui.warn "(did you forget recipe[] or role[] around it?)" end end diff --git a/lib/chef/knife/role_bulk_delete.rb b/lib/chef/knife/role_bulk_delete.rb index 9fc8b20fc2..f57ac79619 100644 --- a/lib/chef/knife/role_bulk_delete.rb +++ b/lib/chef/knife/role_bulk_delete.rb @@ -40,7 +40,7 @@ class Chef matcher = /#{@name_args[0]}/ roles_to_delete = {} all_roles.each do |name, role| - next unless name =~ matcher + next unless name&.match?(matcher) roles_to_delete[role.name] = role end diff --git a/lib/chef/knife/ssh.rb b/lib/chef/knife/ssh.rb index ea40cee191..6611421d85 100644 --- a/lib/chef/knife/ssh.rb +++ b/lib/chef/knife/ssh.rb @@ -364,7 +364,7 @@ class Chef ch.on_data do |ichannel, data| print_data(ichannel.connection[:prefix], data) - if data =~ /^knife sudo password: / + if /^knife sudo password: /.match?(data) print_data(ichannel.connection[:prefix], "\n") ichannel.send_data("#{get_password}\n") end diff --git a/lib/chef/knife/supermarket_share.rb b/lib/chef/knife/supermarket_share.rb index 7d3523dfb8..49b3474566 100644 --- a/lib/chef/knife/supermarket_share.rb +++ b/lib/chef/knife/supermarket_share.rb @@ -132,7 +132,7 @@ class Chef res = Chef::JSONCompat.from_json(http_resp.body) if http_resp.code.to_i != 201 if res["error_messages"] - if res["error_messages"][0] =~ /Version already exists/ + if /Version already exists/.match?(res["error_messages"][0]) ui.error "The same version of this cookbook already exists on Supermarket." exit(1) else diff --git a/lib/chef/knife/supermarket_unshare.rb b/lib/chef/knife/supermarket_unshare.rb index 0904a70f57..686d95f47a 100644 --- a/lib/chef/knife/supermarket_unshare.rb +++ b/lib/chef/knife/supermarket_unshare.rb @@ -48,7 +48,7 @@ class Chef begin rest.delete "#{config[:supermarket_site]}/api/v1/cookbooks/#{@name_args[0]}" rescue Net::HTTPClientException => e - raise e unless e.message =~ /Forbidden/ + raise e unless /Forbidden/.match?(e.message) ui.error "Forbidden: You must be the maintainer of #{@cookbook_name} to unshare it." exit 1 diff --git a/lib/chef/log.rb b/lib/chef/log.rb index 88d9bff939..e835c605ba 100644 --- a/lib/chef/log.rb +++ b/lib/chef/log.rb @@ -21,7 +21,7 @@ require "logger" require_relative "monologger" require_relative "exceptions" require "mixlib/log" -require_relative "log/syslog" unless RUBY_PLATFORM =~ /mswin|mingw|windows/ +require_relative "log/syslog" unless RUBY_PLATFORM.match?(/mswin|mingw|windows/) require_relative "log/winevt" class Chef diff --git a/lib/chef/mixin/securable.rb b/lib/chef/mixin/securable.rb index c63e644604..08e92b27b7 100644 --- a/lib/chef/mixin/securable.rb +++ b/lib/chef/mixin/securable.rb @@ -172,14 +172,14 @@ class Chef end end - if RUBY_PLATFORM =~ /mswin|mingw|windows/ + if RUBY_PLATFORM.match?(/mswin|mingw|windows/) include WindowsSecurableAttributes end # Callback that fires when included; will extend the including class # with WindowsMacros and define #rights and #deny_rights on it. def self.included(including_class) - if RUBY_PLATFORM =~ /mswin|mingw|windows/ + if RUBY_PLATFORM.match?(/mswin|mingw|windows/) including_class.extend(WindowsMacros) # create a default 'rights' attribute including_class.rights_attribute(:rights) diff --git a/lib/chef/powershell.rb b/lib/chef/powershell.rb index 9790a3c10f..10765384ff 100644 --- a/lib/chef/powershell.rb +++ b/lib/chef/powershell.rb @@ -34,7 +34,7 @@ class Chef # @param script [String] script to run # @return [Object] output def initialize(script) - raise "Chef::PowerShell can only be used on the Windows platform." unless RUBY_PLATFORM =~ /mswin|mingw32|windows/ + raise "Chef::PowerShell can only be used on the Windows platform." unless RUBY_PLATFORM.match?(/mswin|mingw32|windows/) exec(script) end diff --git a/lib/chef/provider/cron.rb b/lib/chef/provider/cron.rb index a5669b0a4a..8a978b7eca 100644 --- a/lib/chef/provider/cron.rb +++ b/lib/chef/provider/cron.rb @@ -259,8 +259,8 @@ class Chef return "" if new_resource.time_out.empty? str = " timeout" - str << " --preserve-status" if new_resource.time_out["preserve-status"].to_s.downcase == "true" - str << " --foreground" if new_resource.time_out["foreground"].to_s.downcase == "true" + str << " --preserve-status" if new_resource.time_out["preserve-status"].to_s.casecmp("true") == 0 + str << " --foreground" if new_resource.time_out["foreground"].to_s.casecmp("true") == 0 str << " --kill-after #{new_resource.time_out["kill-after"]}" if new_resource.time_out["kill-after"] str << " --signal #{new_resource.time_out["signal"]}" if new_resource.time_out["signal"] str << " #{new_resource.time_out["duration"]};" diff --git a/lib/chef/provider/group/dscl.rb b/lib/chef/provider/group/dscl.rb index b506197dca..824ebe0477 100644 --- a/lib/chef/provider/group/dscl.rb +++ b/lib/chef/provider/group/dscl.rb @@ -39,7 +39,7 @@ class Chef result = dscl(*args) return "" if ( args.first =~ /^delete/ ) && ( result[1].exitstatus != 0 ) raise(Chef::Exceptions::Group, "dscl error: #{result.inspect}") unless result[1].exitstatus == 0 - raise(Chef::Exceptions::Group, "dscl error: #{result.inspect}") if result[2] =~ /No such key: / + raise(Chef::Exceptions::Group, "dscl error: #{result.inspect}") if /No such key: /.match?(result[2]) result[2] end @@ -77,7 +77,7 @@ class Chef gid = nil; next_gid_guess = 200 groups_gids = safe_dscl("list", "/Groups", "gid") while next_gid_guess < search_limit + 200 - if groups_gids =~ Regexp.new("#{Regexp.escape(next_gid_guess.to_s)}\n") + if groups_gids&.match?(Regexp.new("#{Regexp.escape(next_gid_guess.to_s)}\n")) next_gid_guess += 1 else gid = next_gid_guess diff --git a/lib/chef/provider/group/windows.rb b/lib/chef/provider/group/windows.rb index 6dda6a7cc2..45914b16e3 100644 --- a/lib/chef/provider/group/windows.rb +++ b/lib/chef/provider/group/windows.rb @@ -17,7 +17,7 @@ # require_relative "../user" -if RUBY_PLATFORM =~ /mswin|mingw32|windows/ +if RUBY_PLATFORM.match?(/mswin|mingw32|windows/) require_relative "../../util/windows/net_group" end diff --git a/lib/chef/provider/ifconfig.rb b/lib/chef/provider/ifconfig.rb index 79f5bb78fe..cfabe292f9 100644 --- a/lib/chef/provider/ifconfig.rb +++ b/lib/chef/provider/ifconfig.rb @@ -59,12 +59,12 @@ class Chef @net_tools_version = shell_out("ifconfig", "--version") @net_tools_version.stdout.each_line do |line| - if line =~ /^net-tools (\d+\.\d+)/ + if /^net-tools (\d+\.\d+)/.match?(line) @ifconfig_version = line.match(/^net-tools (\d+\.\d+)/)[1] end end @net_tools_version.stderr.each_line do |line| - if line =~ /^net-tools (\d+\.\d+)/ + if /^net-tools (\d+\.\d+)/.match?(line) @ifconfig_version = line.match(/^net-tools (\d+\.\d+)/)[1] end end @@ -88,11 +88,11 @@ class Chef @int_name = line[0..9].strip @interfaces[@int_name] = { "hwaddr" => (line =~ /(HWaddr)/ ? ($') : "nil").strip.chomp } else - @interfaces[@int_name]["inet_addr"] = (line =~ /inet addr:(\S+)/ ? Regexp.last_match(1) : "nil") if line =~ /inet addr:/ - @interfaces[@int_name]["bcast"] = (line =~ /Bcast:(\S+)/ ? Regexp.last_match(1) : "nil") if line =~ /Bcast:/ - @interfaces[@int_name]["mask"] = (line =~ /Mask:(\S+)/ ? Regexp.last_match(1) : "nil") if line =~ /Mask:/ - @interfaces[@int_name]["mtu"] = (line =~ /MTU:(\S+)/ ? Regexp.last_match(1) : "nil") if line =~ /MTU:/ - @interfaces[@int_name]["metric"] = (line =~ /Metric:(\S+)/ ? Regexp.last_match(1) : "nil") if line =~ /Metric:/ + @interfaces[@int_name]["inet_addr"] = (line =~ /inet addr:(\S+)/ ? Regexp.last_match(1) : "nil") if /inet addr:/.match?(line) + @interfaces[@int_name]["bcast"] = (line =~ /Bcast:(\S+)/ ? Regexp.last_match(1) : "nil") if /Bcast:/.match?(line) + @interfaces[@int_name]["mask"] = (line =~ /Mask:(\S+)/ ? Regexp.last_match(1) : "nil") if /Mask:/.match?(line) + @interfaces[@int_name]["mtu"] = (line =~ /MTU:(\S+)/ ? Regexp.last_match(1) : "nil") if /MTU:/.match?(line) + @interfaces[@int_name]["metric"] = (line =~ /Metric:(\S+)/ ? Regexp.last_match(1) : "nil") if /Metric:/.match?(line) end next unless @interfaces.key?(new_resource.device) diff --git a/lib/chef/provider/mount/aix.rb b/lib/chef/provider/mount/aix.rb index 7a80c6511d..2cb29f5858 100644 --- a/lib/chef/provider/mount/aix.rb +++ b/lib/chef/provider/mount/aix.rb @@ -197,7 +197,7 @@ class Chef ::File.open("/etc/filesystems", "r").each_line do |line| case line when %r{^/.+:\s*$} - if line =~ /#{Regexp.escape(@new_resource.mount_point)}+:/ + if /#{Regexp.escape(@new_resource.mount_point)}+:/.match?(line) found_device = true else found_device = false diff --git a/lib/chef/provider/mount/windows.rb b/lib/chef/provider/mount/windows.rb index aea924b07f..81e9ad6b1d 100644 --- a/lib/chef/provider/mount/windows.rb +++ b/lib/chef/provider/mount/windows.rb @@ -17,7 +17,7 @@ # require_relative "../mount" -if RUBY_PLATFORM =~ /mswin|mingw32|windows/ +if RUBY_PLATFORM.match?(/mswin|mingw32|windows/) require_relative "../../util/windows/net_use" require_relative "../../util/windows/volume" end @@ -30,7 +30,7 @@ class Chef provides :mount, os: "windows" def is_volume(name) - name =~ /^\\\\\?\\Volume\{[\w-]+\}\\$/ ? true : false + /^\\\\\?\\Volume\{[\w-]+\}\\$/.match?(name) ? true : false end def initialize(new_resource, run_context) diff --git a/lib/chef/provider/noop.rb b/lib/chef/provider/noop.rb index fec948af54..74e24f6a44 100644 --- a/lib/chef/provider/noop.rb +++ b/lib/chef/provider/noop.rb @@ -26,7 +26,7 @@ class Chef end def method_missing(method_sym, *arguments, &block) - if method_sym.to_s =~ /^action_/ + if /^action_/.match?(method_sym.to_s) logger.trace("NoOp-ing for #{method_sym}") else super diff --git a/lib/chef/provider/package/openbsd.rb b/lib/chef/provider/package/openbsd.rb index 38ff84f105..6e32a424e2 100644 --- a/lib/chef/provider/package/openbsd.rb +++ b/lib/chef/provider/package/openbsd.rb @@ -57,7 +57,7 @@ class Chef end requirements.assert(:all_actions) do |a| a.assertion do - if new_resource.package_name =~ /^(.+?)--(.+)/ + if /^(.+?)--(.+)/.match?(new_resource.package_name) !new_resource.version else true diff --git a/lib/chef/provider/package/portage.rb b/lib/chef/provider/package/portage.rb index 002c1f96d4..3182686c0e 100644 --- a/lib/chef/provider/package/portage.rb +++ b/lib/chef/provider/package/portage.rb @@ -71,7 +71,7 @@ class Chef if pkginfo.exitstatus != 0 pkginfo.stderr.each_line do |line| # cspell:disable-next-line - if line =~ /[Uu]nqualified atom .*match.* multiple/ + if /[Uu]nqualified atom .*match.* multiple/.match?(line) raise_error_for_query("matched multiple packages (please specify a category):\n#{pkginfo.inspect}") end end @@ -88,7 +88,7 @@ class Chef end pkginfo.stdout.chomp! - if pkginfo.stdout =~ /-r\d+$/ + if /-r\d+$/.match?(pkginfo.stdout) # Latest/Best version of the package is a revision (-rX). @candidate_version = pkginfo.stdout.split(/(?<=-)/).last(2).join else diff --git a/lib/chef/provider/package/powershell.rb b/lib/chef/provider/package/powershell.rb index 51cb387cad..54e31bbd1e 100644 --- a/lib/chef/provider/package/powershell.rb +++ b/lib/chef/provider/package/powershell.rb @@ -59,7 +59,7 @@ class Chef names.each_with_index do |name, index| cmd = powershell_out(build_powershell_package_command("Install-Package '#{name}'", versions[index]), timeout: new_resource.timeout) next if cmd.nil? - raise Chef::Exceptions::PowershellCmdletException, "Failed to install package due to catalog signing error, use skip_publisher_check to force install" if cmd.stderr =~ /SkipPublisherCheck/ + raise Chef::Exceptions::PowershellCmdletException, "Failed to install package due to catalog signing error, use skip_publisher_check to force install" if /SkipPublisherCheck/.match?(cmd.stderr) end end diff --git a/lib/chef/provider/package/rubygems.rb b/lib/chef/provider/package/rubygems.rb index fa2b5a66d7..be4f1a149c 100644 --- a/lib/chef/provider/package/rubygems.rb +++ b/lib/chef/provider/package/rubygems.rb @@ -420,7 +420,7 @@ class Chef end def is_omnibus? - if RbConfig::CONFIG["bindir"] =~ %r{/(opscode|chef|chefdk)/embedded/bin} + if %r{/(opscode|chef|chefdk)/embedded/bin}.match?(RbConfig::CONFIG["bindir"]) logger.trace("#{new_resource} detected omnibus installation in #{RbConfig::CONFIG["bindir"]}") # Omnibus installs to a static path because of linking on unix, find it. true @@ -447,7 +447,7 @@ class Chef scheme = URI.parse(new_resource.source).scheme # URI.parse gets confused by MS Windows paths with forward slashes. - scheme = nil if scheme =~ /^[a-z]$/ + scheme = nil if /^[a-z]$/.match?(scheme) %w{http https}.include?(scheme) rescue URI::InvalidURIError logger.trace("#{new_resource} failed to parse source '#{new_resource.source}' as a URI, assuming a local path") diff --git a/lib/chef/provider/package/windows/msi.rb b/lib/chef/provider/package/windows/msi.rb index 0624224f57..1ce8add80d 100644 --- a/lib/chef/provider/package/windows/msi.rb +++ b/lib/chef/provider/package/windows/msi.rb @@ -18,7 +18,7 @@ # TODO: Allow new_resource.source to be a Product Code as a GUID for uninstall / network install -require_relative "../../../win32/api/installer" if RUBY_PLATFORM =~ /mswin|mingw32|windows/ +require_relative "../../../win32/api/installer" if RUBY_PLATFORM.match?(/mswin|mingw32|windows/) require_relative "../../../mixin/shell_out" class Chef @@ -26,7 +26,7 @@ class Chef class Package class Windows class MSI - include Chef::ReservedNames::Win32::API::Installer if RUBY_PLATFORM =~ /mswin|mingw32|windows/ + include Chef::ReservedNames::Win32::API::Installer if RUBY_PLATFORM.match?(/mswin|mingw32|windows/) include Chef::Mixin::ShellOut def initialize(resource, uninstall_entries) @@ -84,7 +84,7 @@ class Chef .map(&:uninstall_string).uniq.each do |uninstall_string| uninstall_string = "msiexec /x #{uninstall_string.match(/{.*}/)}" uninstall_string += expand_options(new_resource.options) - uninstall_string += " /q" unless uninstall_string.downcase =~ %r{ /q} + uninstall_string += " /q" unless %r{ /q}.match?(uninstall_string.downcase) logger.trace("#{new_resource} removing MSI package version using '#{uninstall_string}'") shell_out!(uninstall_string, default_env: false, timeout: new_resource.timeout, returns: new_resource.returns) end diff --git a/lib/chef/provider/package/windows/registry_uninstall_entry.rb b/lib/chef/provider/package/windows/registry_uninstall_entry.rb index 22bc00a9f7..548b911ecb 100644 --- a/lib/chef/provider/package/windows/registry_uninstall_entry.rb +++ b/lib/chef/provider/package/windows/registry_uninstall_entry.rb @@ -17,7 +17,7 @@ # limitations under the License. # -require "win32/registry" if RUBY_PLATFORM =~ /mswin|mingw32|windows/ +require "win32/registry" if RUBY_PLATFORM.match?(/mswin|mingw32|windows/) class Chef class Provider diff --git a/lib/chef/provider/remote_file/http.rb b/lib/chef/provider/remote_file/http.rb index 26332c061f..ef2461848d 100644 --- a/lib/chef/provider/remote_file/http.rb +++ b/lib/chef/provider/remote_file/http.rb @@ -130,7 +130,7 @@ class Chef # which tricks Chef::REST into decompressing the response body. In this # case you'd end up with a tar archive (no gzip) named, e.g., foo.tgz, # which is not what you wanted. - if uri.to_s =~ /gz$/ + if /gz$/.match?(uri.to_s) logger.trace("Turning gzip compression off due to filename ending in gz") opts[:disable_gzip] = true end diff --git a/lib/chef/provider/service/arch.rb b/lib/chef/provider/service/arch.rb index 24064f26ac..fe09baf2d5 100644 --- a/lib/chef/provider/service/arch.rb +++ b/lib/chef/provider/service/arch.rb @@ -33,7 +33,7 @@ class Chef::Provider::Service::Arch < Chef::Provider::Service::Init def load_current_resource raise Chef::Exceptions::Service, "Could not find /etc/rc.conf" unless ::File.exists?("/etc/rc.conf") - raise Chef::Exceptions::Service, "No DAEMONS found in /etc/rc.conf" unless ::File.read("/etc/rc.conf") =~ /DAEMONS=\((.*)\)/m + raise Chef::Exceptions::Service, "No DAEMONS found in /etc/rc.conf" unless /DAEMONS=\((.*)\)/m.match?(::File.read("/etc/rc.conf")) super diff --git a/lib/chef/provider/service/debian.rb b/lib/chef/provider/service/debian.rb index 259652a2d9..a89907bb50 100644 --- a/lib/chef/provider/service/debian.rb +++ b/lib/chef/provider/service/debian.rb @@ -76,9 +76,9 @@ class Chef in_info = false ::File.readlines(path).each_with_object([]) do |line, acc| - if line =~ /^### BEGIN INIT INFO/ + if /^### BEGIN INIT INFO/.match?(line) in_info = true - elsif line =~ /^### END INIT INFO/ + elsif /^### END INIT INFO/.match?(line) break acc elsif in_info if line =~ /Default-(Start|Stop):\s+(\d.*)/ diff --git a/lib/chef/provider/service/openbsd.rb b/lib/chef/provider/service/openbsd.rb index c368815418..fe42e2133c 100644 --- a/lib/chef/provider/service/openbsd.rb +++ b/lib/chef/provider/service/openbsd.rb @@ -91,7 +91,7 @@ class Chef old_services_list = rc_conf_local.match(/^pkg_scripts="(.*)"/) old_services_list = old_services_list ? old_services_list[1].split(" ") : [] new_services_list = old_services_list + [new_resource.service_name] - if rc_conf_local =~ /^pkg_scripts="(.*)"/ + if /^pkg_scripts="(.*)"/.match?(rc_conf_local) new_rcl = rc_conf_local.sub(/^pkg_scripts="(.*)"/, "pkg_scripts=\"#{new_services_list.join(" ")}\"") else new_rcl = rc_conf_local + "\n" + "pkg_scripts=\"#{new_services_list.join(" ")}\"\n" @@ -158,7 +158,7 @@ class Chef result = false var_name = builtin_service_enable_variable_name if var_name - if rc_conf =~ /^#{Regexp.escape(var_name)}=(.*)/ + if /^#{Regexp.escape(var_name)}=(.*)/.match?(rc_conf) result = true end end @@ -170,7 +170,7 @@ class Chef var_name = builtin_service_enable_variable_name if var_name if m = rc_conf.match(/^#{Regexp.escape(var_name)}=(.*)/) - unless m[1] =~ /"?[Nn][Oo]"?/ + unless /"?[Nn][Oo]"?/.match?(m[1]) result = true end end @@ -186,7 +186,7 @@ class Chef if var_name if m = rc_conf_local.match(/^#{Regexp.escape(var_name)}=(.*)/) @enabled_state_found = true - unless m[1] =~ /"?[Nn][Oo]"?/ # e.g. looking for httpd_flags=NO + unless /"?[Nn][Oo]"?/.match?(m[1]) # e.g. looking for httpd_flags=NO result = true end end diff --git a/lib/chef/provider/service/redhat.rb b/lib/chef/provider/service/redhat.rb index 6851e7f150..ec78ef2240 100644 --- a/lib/chef/provider/service/redhat.rb +++ b/lib/chef/provider/service/redhat.rb @@ -87,7 +87,7 @@ class Chef chkconfig.stdout.split(/\s+/)[1..-1].each do |level| index = level.split(":").first status = level.split(":").last - if level =~ CHKCONFIG_ON + if CHKCONFIG_ON.match?(level) @current_run_levels << index.to_i all_levels_match = false unless run_levels.include?(index.to_i) else diff --git a/lib/chef/provider/service/windows.rb b/lib/chef/provider/service/windows.rb index 6c1f7c3583..88bb282be9 100644 --- a/lib/chef/provider/service/windows.rb +++ b/lib/chef/provider/service/windows.rb @@ -20,7 +20,7 @@ require_relative "simple" require_relative "../../win32_service_constants" -if RUBY_PLATFORM =~ /mswin|mingw32|windows/ +if RUBY_PLATFORM.match?(/mswin|mingw32|windows/) require_relative "../../win32/error" require "win32/service" end diff --git a/lib/chef/provider/subversion.rb b/lib/chef/provider/subversion.rb index 270f7457fa..18fc9d3a3c 100644 --- a/lib/chef/provider/subversion.rb +++ b/lib/chef/provider/subversion.rb @@ -122,7 +122,7 @@ class Chef # If the specified revision is an integer, trust it. def revision_int @revision_int ||= begin - if new_resource.revision =~ /^\d+$/ + if /^\d+$/.match?(new_resource.revision) new_resource.revision else command = scm(:info, new_resource.repository, new_resource.svn_info_args, authentication, "-r#{new_resource.revision}") @@ -211,7 +211,7 @@ class Chef def scm(*args) binary = svn_binary - binary = "\"#{binary}\"" if binary =~ /\s/ + binary = "\"#{binary}\"" if /\s/.match?(binary) [binary, *args].compact.join(" ") end diff --git a/lib/chef/provider/user/dscl.rb b/lib/chef/provider/user/dscl.rb index 50030c885f..fade7097b5 100644 --- a/lib/chef/provider/user/dscl.rb +++ b/lib/chef/provider/user/dscl.rb @@ -215,7 +215,7 @@ in 'password', with the associated 'salt' and 'iterations'.") next_uid_guess = base_uid users_uids = run_dscl("list", "/Users", "uid") while next_uid_guess < search_limit + base_uid - if users_uids =~ Regexp.new("#{Regexp.escape(next_uid_guess.to_s)}\n") + if users_uids&.match?(Regexp.new("#{Regexp.escape(next_uid_guess.to_s)}\n")) next_uid_guess += 1 else uid = next_uid_guess @@ -291,7 +291,7 @@ in 'password', with the associated 'salt' and 'iterations'.") end def validate_home_dir_specification! - unless new_resource.home =~ %r{^/} + unless %r{^/}.match?(new_resource.home) raise(Chef::Exceptions::InvalidHomeDirectory, "invalid path spec for User: '#{new_resource.username}', home directory: '#{new_resource.home}'") end end @@ -587,7 +587,7 @@ in 'password', with the associated 'salt' and 'iterations'.") result = shell_out("dscl", ".", "-#{args[0]}", args[1..-1]) return "" if ( args.first =~ /^delete/ ) && ( result.exitstatus != 0 ) raise(Chef::Exceptions::DsclCommandFailed, "dscl error: #{result.inspect}") unless result.exitstatus == 0 - raise(Chef::Exceptions::DsclCommandFailed, "dscl error: #{result.inspect}") if result.stdout =~ /No such key: / + raise(Chef::Exceptions::DsclCommandFailed, "dscl error: #{result.inspect}") if /No such key: /.match?(result.stdout) result.stdout end diff --git a/lib/chef/provider/user/linux.rb b/lib/chef/provider/user/linux.rb index bab8588151..40b5985cb1 100644 --- a/lib/chef/provider/user/linux.rb +++ b/lib/chef/provider/user/linux.rb @@ -96,7 +96,7 @@ class Chef passwd_s = shell_out("passwd", "-S", new_resource.username, returns: [ 0, 1 ]) # checking "does not exist" has to come before exit code handling since centos and ubuntu differ in exit codes - if passwd_s.stderr =~ /does not exist/ + if /does not exist/.match?(passwd_s.stderr) return false if whyrun_mode? raise Chef::Exceptions::User, "User #{new_resource.username} does not exist when checking lock status for #{new_resource}" @@ -108,8 +108,8 @@ class Chef # now the actual output parsing @locked = nil status_line = passwd_s.stdout.split(" ") - @locked = false if status_line[1] =~ /^[PN]/ - @locked = true if status_line[1] =~ /^L/ + @locked = false if /^[PN]/.match?(status_line[1]) + @locked = true if /^L/.match?(status_line[1]) raise Chef::Exceptions::User, "Cannot determine if user #{new_resource.username} is locked for #{new_resource}" if @locked.nil? diff --git a/lib/chef/provider/user/mac.rb b/lib/chef/provider/user/mac.rb index a2561e2ccd..34307aff1e 100644 --- a/lib/chef/provider/user/mac.rb +++ b/lib/chef/provider/user/mac.rb @@ -163,7 +163,7 @@ class Chef # a problem. We'll check stderr and make sure we see that it finished # correctly. res = run_sysadminctl(cmd) - unless res.downcase =~ /creating user/ + unless /creating user/.match?(res.downcase) raise Chef::Exceptions::User, "error when creating user: #{res}" end @@ -309,7 +309,7 @@ class Chef # sysadminctl doesn't exit with a non-zero exit code if it encounters # a problem. We'll check stderr and make sure we see that it finished res = run_sysadminctl(cmd) - unless res.downcase =~ /deleting record|not found/ + unless /deleting record|not found/.match?(res.downcase) raise Chef::Exceptions::User, "error deleting user: #{res}" end @@ -372,7 +372,7 @@ class Chef next_uid_guess = base_uid users_uids = run_dscl("list", "/Users", "uid") while next_uid_guess < search_limit + base_uid - if users_uids =~ Regexp.new("#{Regexp.escape(next_uid_guess.to_s)}\n") + if users_uids&.match?(Regexp.new("#{Regexp.escape(next_uid_guess.to_s)}\n")) next_uid_guess += 1 else uid = next_uid_guess @@ -430,7 +430,7 @@ class Chef # sysadminctl doesn't exit with a non-zero exit code if it encounters # a problem. We'll check stderr and make sure we see that it finished res = run_sysadminctl(cmd) - unless res.downcase =~ /done/ + unless /done/.match?(res.downcase) raise Chef::Exceptions::User, "error when modifying SecureToken: #{res}" end @@ -611,7 +611,7 @@ class Chef result = shell_out("dscl", "-plist", ".", "-#{args[0]}", args[1..-1]) return "" if ( args.first =~ /^delete/ ) && ( result.exitstatus != 0 ) raise(Chef::Exceptions::DsclCommandFailed, "dscl error: #{result.inspect}") unless result.exitstatus == 0 - raise(Chef::Exceptions::DsclCommandFailed, "dscl error: #{result.inspect}") if result.stdout =~ /No such key: / + raise(Chef::Exceptions::DsclCommandFailed, "dscl error: #{result.inspect}") if /No such key: /.match?(result.stdout) result.stdout end diff --git a/lib/chef/resource/freebsd_package.rb b/lib/chef/resource/freebsd_package.rb index 4e0c161094..081adaf702 100644 --- a/lib/chef/resource/freebsd_package.rb +++ b/lib/chef/resource/freebsd_package.rb @@ -42,7 +42,7 @@ class Chef private def assign_provider - @provider = if source.to_s =~ /^ports$/i + @provider = if /^ports$/i.match?(source.to_s) Chef::Provider::Package::Freebsd::Port else Chef::Provider::Package::Freebsd::Pkgng diff --git a/lib/chef/resource/helpers/cron_validations.rb b/lib/chef/resource/helpers/cron_validations.rb index 8e62fa8095..8b5e9a22c4 100644 --- a/lib/chef/resource/helpers/cron_validations.rb +++ b/lib/chef/resource/helpers/cron_validations.rb @@ -35,7 +35,7 @@ class Chef # Lists of individual values, ranges, and step values all share the validity range for type spec.split(%r{\/|-|,}).each do |x| next if x == "*" - return false unless x =~ /^\d+$/ + return false unless /^\d+$/.match?(x) x = x.to_i return false unless x >= min && x <= max diff --git a/lib/chef/resource/mount.rb b/lib/chef/resource/mount.rb index 5154cac3d9..f6dd4f70f0 100644 --- a/lib/chef/resource/mount.rb +++ b/lib/chef/resource/mount.rb @@ -50,7 +50,7 @@ class Chef description: "The type of device: :device, :label, or :uuid", coerce: proc { |arg| arg.is_a?(String) ? arg.to_sym : arg }, default: :device, - equal_to: RUBY_PLATFORM =~ /solaris/i ? %i{ device } : %i{ device label uuid } + equal_to: RUBY_PLATFORM.match?(/solaris/i) ? %i{ device } : %i{ device label uuid } # @todo this should get refactored away: https://github.com/chef/chef/issues/7621 property :mounted, [TrueClass, FalseClass], default: false, skip_docs: true diff --git a/lib/chef/resource/windows_ad_join.rb b/lib/chef/resource/windows_ad_join.rb index b1584d93d8..5eb93579c3 100644 --- a/lib/chef/resource/windows_ad_join.rb +++ b/lib/chef/resource/windows_ad_join.rb @@ -204,7 +204,7 @@ class Chef # links: https://docs.microsoft.com/en-us/windows/win32/ad/naming-properties#userprincipalname https://tools.ietf.org/html/rfc822 # regex: https://rubular.com/r/isAWojpTMKzlnp def sanitize_usename - if new_resource.domain_user =~ /@/ + if /@/.match?(new_resource.domain_user) new_resource.domain_user else "#{new_resource.domain_user}@#{new_resource.domain_name}" diff --git a/lib/chef/resource/windows_font.rb b/lib/chef/resource/windows_font.rb index 007fe5db58..54e1c9669a 100644 --- a/lib/chef/resource/windows_font.rb +++ b/lib/chef/resource/windows_font.rb @@ -42,7 +42,7 @@ class Chef property :source, String, description: "A local filesystem path or URI that is used to source the font file.", - coerce: proc { |x| x =~ /^.:.*/ ? x.tr('\\', "/").gsub("//", "/") : x } + coerce: proc { |x| /^.:.*/.match?(x) ? x.tr('\\', "/").gsub("//", "/") : x } action :install do description "Install a font to the system fonts directory." @@ -84,7 +84,7 @@ class Chef # install the font into the appropriate fonts directory def install_font - require "win32ole" if RUBY_PLATFORM =~ /mswin|mingw32|windows/ + require "win32ole" if RUBY_PLATFORM.match?(/mswin|mingw32|windows/) fonts_dir = Chef::Util::PathHelper.join(ENV["windir"], "fonts") folder = WIN32OLE.new("Shell.Application").Namespace(fonts_dir) converge_by("install font #{new_resource.font_name} to #{fonts_dir}") do @@ -96,7 +96,7 @@ class Chef # # @return [Boolean] Is the font is installed? def font_exists? - require "win32ole" if RUBY_PLATFORM =~ /mswin|mingw32|windows/ + require "win32ole" if RUBY_PLATFORM.match?(/mswin|mingw32|windows/) fonts_dir = WIN32OLE.new("WScript.Shell").SpecialFolders("Fonts") logger.trace("Seeing if the font at #{Chef::Util::PathHelper.join(fonts_dir, new_resource.font_name)} exists") ::File.exist?(Chef::Util::PathHelper.join(fonts_dir, new_resource.font_name)) diff --git a/lib/chef/resource/windows_package.rb b/lib/chef/resource/windows_package.rb index c0e88ddee8..ba5ecd31aa 100644 --- a/lib/chef/resource/windows_package.rb +++ b/lib/chef/resource/windows_package.rb @@ -19,7 +19,7 @@ require_relative "../mixin/uris" require_relative "package" require_relative "../provider/package/windows" -require_relative "../win32/error" if RUBY_PLATFORM =~ /mswin|mingw|windows/ +require_relative "../win32/error" if RUBY_PLATFORM.match?(/mswin|mingw|windows/) require_relative "../dist" class Chef diff --git a/lib/chef/resource/windows_pagefile.rb b/lib/chef/resource/windows_pagefile.rb index 928a8d03e0..90e57993de 100644 --- a/lib/chef/resource/windows_pagefile.rb +++ b/lib/chef/resource/windows_pagefile.rb @@ -113,7 +113,7 @@ class Chef # we do this here and not in the property itself because if automatic_managed # is set then this validation is not necessary / doesn't make sense at all def validate_name - return if /^.:.*.sys/ =~ new_resource.path + return if /^.:.*.sys/.match?(new_resource.path) raise "#{new_resource.path} does not match the format DRIVE:\\path\\file.sys for pagefiles. Example: C:\\pagefile.sys" end diff --git a/lib/chef/resource/windows_shortcut.rb b/lib/chef/resource/windows_shortcut.rb index b5b532cb86..d7f72a9def 100644 --- a/lib/chef/resource/windows_shortcut.rb +++ b/lib/chef/resource/windows_shortcut.rb @@ -56,7 +56,7 @@ class Chef description: "Icon to use for the shortcut. Accepts the format of `path, index`, where index is the icon file to use. See Microsoft's [documentation](https://msdn.microsoft.com/en-us/library/3s9bx7at.aspx) for details" load_current_value do |desired| - require "win32ole" if RUBY_PLATFORM =~ /mswin|mingw32|windows/ + require "win32ole" if RUBY_PLATFORM.match?(/mswin|mingw32|windows/) link = WIN32OLE.new("WScript.Shell").CreateShortcut(desired.shortcut_name) name desired.shortcut_name diff --git a/lib/chef/resource/windows_task.rb b/lib/chef/resource/windows_task.rb index 2dfa22b8ca..4b6b9ba9cf 100644 --- a/lib/chef/resource/windows_task.rb +++ b/lib/chef/resource/windows_task.rb @@ -330,7 +330,7 @@ class Chef # make sure the start_day is in MM/DD/YYYY format: http://rubular.com/r/cgjHemtWl5 if start_day - raise ArgumentError, "`start_day` property must be in the MM/DD/YYYY format." unless %r{^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$} =~ start_day + raise ArgumentError, "`start_day` property must be in the MM/DD/YYYY format." unless %r{^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$}.match?(start_day) end end @@ -338,7 +338,7 @@ class Chef def validate_start_time(start_time, frequency) if start_time raise ArgumentError, "`start_time` property is not supported with `frequency :none`" if frequency == :none - raise ArgumentError, "`start_time` property must be in the HH:mm format (e.g. 6:20pm -> 18:20)." unless /^[0-2][0-9]:[0-5][0-9]$/ =~ start_time + raise ArgumentError, "`start_time` property must be in the HH:mm format (e.g. 6:20pm -> 18:20)." unless /^[0-2][0-9]:[0-5][0-9]$/.match?(start_time) else raise ArgumentError, "`start_time` needs to be provided with `frequency :once`" if frequency == :once end diff --git a/lib/chef/search/query.rb b/lib/chef/search/query.rb index 35f846224d..cd4275e8db 100644 --- a/lib/chef/search/query.rb +++ b/lib/chef/search/query.rb @@ -105,7 +105,7 @@ class Chef private def fuzzify_node_query(query) - if query !~ /:/ + if !/:/.match?(query) "tags:*#{query}* OR roles:*#{query}* OR fqdn:*#{query}* OR addresses:*#{query}* OR policy_name:*#{query}* OR policy_group:*#{query}*" else query diff --git a/lib/chef/util/diff.rb b/lib/chef/util/diff.rb index 30ea838e96..6f10cbde35 100644 --- a/lib/chef/util/diff.rb +++ b/lib/chef/util/diff.rb @@ -171,7 +171,7 @@ class Chef begin return buff !~ /\A[\s[:print:]]*\z/m rescue ArgumentError => e - return true if e.message =~ /invalid byte sequence/ + return true if /invalid byte sequence/.match?(e.message) raise end diff --git a/lib/chef/util/windows/net_user.rb b/lib/chef/util/windows/net_user.rb index 5545ff4ca5..b6767c41c5 100644 --- a/lib/chef/util/windows/net_user.rb +++ b/lib/chef/util/windows/net_user.rb @@ -100,7 +100,7 @@ class Chef::Util::Windows::NetUser < Chef::Util::Windows rescue Chef::Exceptions::Win32APIError => e Chef::Log.trace(e) # we're only interested in the incorrect password failures - if e.to_s =~ /System Error Code: 1326/ + if /System Error Code: 1326/.match?(e.to_s) return false end diff --git a/lib/chef/util/windows/volume.rb b/lib/chef/util/windows/volume.rb index 1b75fe8cb9..e197604c34 100644 --- a/lib/chef/util/windows/volume.rb +++ b/lib/chef/util/windows/volume.rb @@ -25,7 +25,7 @@ class Chef::Util::Windows::Volume < Chef::Util::Windows attr_reader :mount_point def initialize(name) - name += "\\" unless name =~ /\\$/ # trailing slash required + name += "\\" unless /\\$/.match?(name) # trailing slash required @mount_point = name end diff --git a/lib/chef/win32/file.rb b/lib/chef/win32/file.rb index d6f6a61d9a..e051a53e4d 100644 --- a/lib/chef/win32/file.rb +++ b/lib/chef/win32/file.rb @@ -123,7 +123,7 @@ class Chef # Return the link destination (strip off \??\ at the beginning, which is a local filesystem thing) link_dest = reparse_buffer.reparse_buffer.substitute_name - if link_dest =~ /^\\\?\?\\/ + if /^\\\?\?\\/.match?(link_dest) link_dest = link_dest[4..-1] end link_dest diff --git a/lib/chef/win32/registry.rb b/lib/chef/win32/registry.rb index a5c63b571b..c31ae50e0b 100644 --- a/lib/chef/win32/registry.rb +++ b/lib/chef/win32/registry.rb @@ -20,7 +20,7 @@ require_relative "../reserved_names" require_relative "api" require_relative "../mixin/wide_string" -if RUBY_PLATFORM =~ /mswin|mingw32|windows/ +if RUBY_PLATFORM.match?(/mswin|mingw32|windows/) require_relative "../monkey_patches/win32/registry" require_relative "api/registry" require "win32/registry" unless defined?(Win32::Registry) @@ -31,7 +31,7 @@ class Chef class Win32 class Registry - if RUBY_PLATFORM =~ /mswin|mingw32|windows/ + if RUBY_PLATFORM.match?(/mswin|mingw32|windows/) include Chef::ReservedNames::Win32::API::Registry extend Chef::ReservedNames::Win32::API::Registry end diff --git a/lib/chef/win32/security.rb b/lib/chef/win32/security.rb index cebf07208b..3894c65b21 100644 --- a/lib/chef/win32/security.rb +++ b/lib/chef/win32/security.rb @@ -694,7 +694,7 @@ class Chef begin process_token = open_current_process_token(TOKEN_READ) rescue Exception => run_error - return false if run_error.message =~ /Access is denied/ + return false if /Access is denied/.match?(run_error.message) Chef::ReservedNames::Win32::Error.raise! end diff --git a/spec/data/lwrp/providers/buck_passer.rb b/spec/data/lwrp/providers/buck_passer.rb index 0bbd413867..9d764277ce 100644 --- a/spec/data/lwrp/providers/buck_passer.rb +++ b/spec/data/lwrp/providers/buck_passer.rb @@ -4,7 +4,7 @@ def without_deprecation_warnings(&block) old_treat_deprecation_warnings_as_errors = Chef::Config[:treat_deprecation_warnings_as_errors] Chef::Config[:treat_deprecation_warnings_as_errors] = false begin - block.call + yield ensure Chef::Config[:treat_deprecation_warnings_as_errors] = old_treat_deprecation_warnings_as_errors end diff --git a/spec/data/lwrp/providers/buck_passer_2.rb b/spec/data/lwrp/providers/buck_passer_2.rb index 980506c671..0b8f49f7bd 100644 --- a/spec/data/lwrp/providers/buck_passer_2.rb +++ b/spec/data/lwrp/providers/buck_passer_2.rb @@ -2,7 +2,7 @@ def without_deprecation_warnings(&block) old_treat_deprecation_warnings_as_errors = Chef::Config[:treat_deprecation_warnings_as_errors] Chef::Config[:treat_deprecation_warnings_as_errors] = false begin - block.call + yield ensure Chef::Config[:treat_deprecation_warnings_as_errors] = old_treat_deprecation_warnings_as_errors end diff --git a/spec/data/lwrp/providers/embedded_resource_accesses_providers_scope.rb b/spec/data/lwrp/providers/embedded_resource_accesses_providers_scope.rb index d6996da55e..b86dc860d0 100644 --- a/spec/data/lwrp/providers/embedded_resource_accesses_providers_scope.rb +++ b/spec/data/lwrp/providers/embedded_resource_accesses_providers_scope.rb @@ -7,7 +7,7 @@ def without_deprecation_warnings(&block) old_treat_deprecation_warnings_as_errors = Chef::Config[:treat_deprecation_warnings_as_errors] Chef::Config[:treat_deprecation_warnings_as_errors] = false begin - block.call + yield ensure Chef::Config[:treat_deprecation_warnings_as_errors] = old_treat_deprecation_warnings_as_errors end diff --git a/spec/functional/resource/remote_file_spec.rb b/spec/functional/resource/remote_file_spec.rb index 3e38842280..a5ae59d876 100644 --- a/spec/functional/resource/remote_file_spec.rb +++ b/spec/functional/resource/remote_file_spec.rb @@ -134,7 +134,7 @@ describe Chef::Resource::RemoteFile do let(:smb_file_local_file_name) { "smb_file.txt" } let(:smb_file_local_path) { File.join( smb_share_root_directory, smb_file_local_file_name ) } let(:smb_share_name) { "chef_smb_test" } - let(:smb_remote_path) { File.join("//#{ENV["COMPUTERNAME"]}", smb_share_name, smb_file_local_file_name).gsub(%r{/}, "\\") } + let(:smb_remote_path) { File.join("//#{ENV["COMPUTERNAME"]}", smb_share_name, smb_file_local_file_name).tr("/", "\\") } let(:smb_file_content) { "hellofun" } let(:local_destination_path) { File.join(Dir.tmpdir, make_tmpname("chef_remote_file")) } let(:windows_current_user) { ENV["USERNAME"] } @@ -155,7 +155,7 @@ describe Chef::Resource::RemoteFile do before do shell_out("net.exe share #{smb_share_name} /delete") File.write(smb_file_local_path, smb_file_content ) - shell_out!("net.exe share #{smb_share_name}=\"#{smb_share_root_directory.gsub(%r{/}, '\\')}\" /grant:\"authenticated users\",read") + shell_out!("net.exe share #{smb_share_name}=\"#{smb_share_root_directory.tr("/", '\\')}\" /grant:\"authenticated users\",read") end after do diff --git a/spec/support/platform_helpers.rb b/spec/support/platform_helpers.rb index 1d0f8fa2b6..709e137f24 100644 --- a/spec/support/platform_helpers.rb +++ b/spec/support/platform_helpers.rb @@ -108,7 +108,7 @@ def mac_osx? if File.exists? "/usr/bin/sw_vers" result = ShellHelpers.shell_out("/usr/bin/sw_vers") result.stdout.each_line do |line| - if line =~ /^ProductName:\sMac OS X.*$/ + if /^ProductName:\sMac OS X.*$/.match?(line) return true end end diff --git a/spec/support/platforms/win32/spec_service.rb b/spec/support/platforms/win32/spec_service.rb index 95daa97e23..34bb1fe3db 100644 --- a/spec/support/platforms/win32/spec_service.rb +++ b/spec/support/platforms/win32/spec_service.rb @@ -16,7 +16,7 @@ # limitations under the License. # -if RUBY_PLATFORM =~ /mswin|mingw|windows/ +if RUBY_PLATFORM.match?(/mswin|mingw|windows/) require "win32/daemon" class SpecService < ::Win32::Daemon diff --git a/spec/support/shared/functional/execute_resource.rb b/spec/support/shared/functional/execute_resource.rb index e3c5d90cc0..5e0c9e4e28 100644 --- a/spec/support/shared/functional/execute_resource.rb +++ b/spec/support/shared/functional/execute_resource.rb @@ -58,7 +58,7 @@ shared_context "a command that can be executed as an alternate user" do include Chef::Mixin::ShellOut before do - shell_out!("icacls \"#{script_output_dir.gsub(%r{/}, '\\')}\" /grant \"authenticated users:(F)\"") + shell_out!("icacls \"#{script_output_dir.tr("/", '\\')}\" /grant \"authenticated users:(F)\"") end after do diff --git a/spec/unit/util/dsc/configuration_generator_spec.rb b/spec/unit/util/dsc/configuration_generator_spec.rb index dcf460ab4e..eee6adbd07 100644 --- a/spec/unit/util/dsc/configuration_generator_spec.rb +++ b/spec/unit/util/dsc/configuration_generator_spec.rb @@ -161,7 +161,7 @@ describe Chef::Util::DSC::ConfigurationGenerator do dsc = conf_man.send(:configuration_code, "archive{}", "hello", {}) found_configuration = false dsc.split(";").each do |command| - if command.downcase =~ /\s*configuration\s+'hello'\s*\{\s*node\s+'localhost'\s*\{\s*archive\s*\{\s*\}\s*\}\s*\}\s*/ + if /\s*configuration\s+'hello'\s*\{\s*node\s+'localhost'\s*\{\s*archive\s*\{\s*\}\s*\}\s*\}\s*/.match?(command.downcase) found_configuration = true end end |