diff --git a/.rubocop.yml b/.rubocop.yml index c90343844a7..aaffd75a30c 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -33,6 +33,24 @@ Layout/IndentationWidth: Layout/LineEndStringConcatenationIndentation: Enabled: true +# Enabling this cop will remove raising RuntimeErrors and cause spec test +# failures +Style/RedundantException: + Exclude: + - 'lib/puppet/file_bucket/dipper.rb' + - 'lib/puppet/forge.rb' + - 'lib/puppet/module_tool/applications/unpacker.rb' + - 'lib/puppet/module_tool/local_tarball.rb' + - 'lib/puppet/module_tool/tar.rb' + - 'lib/puppet/pops/types/class_loader.rb' + +# Enabling this cop causes a plethora of failed rspec tests, mostly +# Errno::ENAMETOOLONG and Puppet::Context::UndefinedBindingError: Unable to +# lookup 'environments' errors +Style/RedundantSelfAssignment: + Exclude: + - 'lib/puppet/context.rb' + # Explicitly enables this cop new in 1.7 Layout/SpaceBeforeBrackets: Enabled: true diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index ac883a54eab..628247db22d 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -128,6 +128,12 @@ Lint/RedundantDirGlobSort: # new in 1.8 Lint/RedundantRegexpQuantifiers: # new in 1.53 Enabled: false +# Unsure how the changes in portage.rb from Lint/RedundantSplatExpansion impact +# the code +Lint/RedundantSplatExpansion: + Exclude: + - 'lib/puppet/provider/package/portage.rb' + Lint/RefinementImportMethods: # new in 1.27 Enabled: false @@ -646,76 +652,10 @@ Style/OptionalBooleanParameter: Style/PreferredHashMethods: Enabled: false -# This cop supports safe auto-correction (--auto-correct). -Style/RedundantConditional: - Exclude: - - 'lib/puppet/type/exec.rb' - - 'lib/puppet/type/file.rb' - -# This cop supports safe auto-correction (--auto-correct). -Style/RedundantException: - Exclude: - - 'lib/puppet/file_bucket/dipper.rb' - - 'lib/puppet/forge.rb' - - 'lib/puppet/module_tool/applications/unpacker.rb' - - 'lib/puppet/module_tool/local_tarball.rb' - - 'lib/puppet/module_tool/tar.rb' - - 'lib/puppet/pops/types/class_loader.rb' - # This cop supports unsafe auto-correction (--auto-correct-all). -# Configuration parameters: SafeForConstants. -Style/RedundantFetchBlock: - Exclude: - - 'lib/puppet/pops/types/p_sem_ver_range_type.rb' - -# This cop supports safe auto-correction (--auto-correct). -Style/RedundantFileExtensionInRequire: - Exclude: - - 'lib/puppet/parser.rb' - - 'lib/puppet/type/file/content.rb' - - 'lib/puppet/util/rdoc/parser.rb' - - 'lib/puppet/util/rdoc/parser/puppet_parser_rdoc2.rb' - -# This cop supports safe auto-correction (--auto-correct). Style/RedundantInterpolation: Enabled: false -# This cop supports safe auto-correction (--auto-correct). -Style/RedundantParentheses: - Enabled: false - -# This cop supports safe auto-correction (--auto-correct). -Style/RedundantPercentQ: - Exclude: - - 'lib/puppet/defaults.rb' - - 'lib/puppet/indirector/catalog/store_configs.rb' - - 'lib/puppet/indirector/facts/store_configs.rb' - - 'lib/puppet/indirector/node/store_configs.rb' - - 'lib/puppet/indirector/resource/store_configs.rb' - - 'lib/puppet/provider/package/dpkg.rb' - - 'lib/puppet/provider/package/rpm.rb' - - 'lib/puppet/type.rb' - - 'lib/puppet/util/at_fork/solaris.rb' - -# This cop supports safe auto-correction (--auto-correct). -Style/RedundantRegexpCharacterClass: - Exclude: - - 'lib/puppet/application/apply.rb' - - 'lib/puppet/module.rb' - - 'lib/puppet/pops/lookup/interpolation.rb' - - 'lib/puppet/pops/parser/lexer2.rb' - - 'lib/puppet/pops/parser/slurp_support.rb' - - 'lib/puppet/pops/patterns.rb' - - 'lib/puppet/pops/pcore.rb' - - 'lib/puppet/provider/package/openbsd.rb' - - 'lib/puppet/settings/config_file.rb' - - 'lib/puppet/type/exec.rb' - - 'lib/puppet/util/command_line/trollop.rb' - -# This cop supports safe auto-correction (--auto-correct). -Style/RedundantRegexpEscape: - Enabled: false - # This cop supports safe auto-correction (--auto-correct). # Configuration parameters: AllowMultipleReturnValues. Style/RedundantReturn: @@ -725,44 +665,6 @@ Style/RedundantReturn: Style/RedundantSelf: Enabled: false -# This cop supports unsafe auto-correction (--auto-correct-all). -Style/RedundantSelfAssignment: - Exclude: - - 'lib/puppet/context.rb' - -# This cop supports unsafe auto-correction (--auto-correct-all). -Style/RedundantSort: - Exclude: - - 'lib/puppet/interface/face_collection.rb' - - 'lib/puppet/module/plan.rb' - - 'lib/puppet/module_tool/applications/unpacker.rb' - - 'lib/puppet/provider/package/apt.rb' - - 'lib/puppet/provider/package/yum.rb' - - 'lib/puppet/provider/package/zypper.rb' - -# This cop supports safe auto-correction (--auto-correct). -# Configuration parameters: EnforcedStyle, AllowInnerSlashes. -# SupportedStyles: slashes, percent_r, mixed -Style/RegexpLiteral: - Enabled: false - -# This cop supports safe auto-correction (--auto-correct). -Style/RescueModifier: - Exclude: - - 'lib/puppet/file_serving/metadata.rb' - - 'lib/puppet/file_system/uniquefile.rb' - - 'lib/puppet/file_system/windows.rb' - - 'lib/puppet/module_tool/applications/application.rb' - - 'lib/puppet/module_tool/applications/installer.rb' - - 'lib/puppet/module_tool/applications/upgrader.rb' - - 'lib/puppet/module_tool/metadata.rb' - - 'lib/puppet/module_tool/shared_behaviors.rb' - - 'lib/puppet/provider/file/posix.rb' - - 'lib/puppet/util.rb' - - 'lib/puppet/util/execution.rb' - - 'lib/puppet/util/reference.rb' - - 'lib/puppet/util/windows/adsi.rb' - # This cop supports safe auto-correction (--auto-correct). # Configuration parameters: EnforcedStyle. # SupportedStyles: implicit, explicit diff --git a/lib/puppet/application/agent.rb b/lib/puppet/application/agent.rb index b63ad4b7ed0..5d9876ba82c 100644 --- a/lib/puppet/application/agent.rb +++ b/lib/puppet/application/agent.rb @@ -509,7 +509,7 @@ def enable_disable_client(agent) end def setup_agent - agent = Puppet::Agent.new(Puppet::Configurer, (!(Puppet[:onetime]))) + agent = Puppet::Agent.new(Puppet::Configurer, !(Puppet[:onetime])) enable_disable_client(agent) if options[:enable] or options[:disable] diff --git a/lib/puppet/application/apply.rb b/lib/puppet/application/apply.rb index 9b1237e3867..b5355a6bf18 100644 --- a/lib/puppet/application/apply.rb +++ b/lib/puppet/application/apply.rb @@ -224,7 +224,7 @@ def main $stderr.puts _("%{file} is not readable") % { file: file } exit(63) end - node.classes = Puppet::FileSystem.read(file, :encoding => 'utf-8').split(/[\s]+/) + node.classes = Puppet::FileSystem.read(file, :encoding => 'utf-8').split(/\s+/) end end diff --git a/lib/puppet/application/describe.rb b/lib/puppet/application/describe.rb index 95b2fe0cbbd..7e2969878f7 100644 --- a/lib/puppet/application/describe.rb +++ b/lib/puppet/application/describe.rb @@ -11,7 +11,7 @@ def wrap(txt, opts) return "" unless txt && !txt.empty? work = (opts[:scrub] ? scrub(txt) : txt) - indent = (opts[:indent] || 0) + indent = opts[:indent] || 0 textLen = @width - indent patt = Regexp.new("\\A(.{0,#{textLen}})[ \n]") prefix = " " * indent diff --git a/lib/puppet/application/face_base.rb b/lib/puppet/application/face_base.rb index eeb3a633efe..8e81025c070 100644 --- a/lib/puppet/application/face_base.rb +++ b/lib/puppet/application/face_base.rb @@ -205,7 +205,7 @@ def setup @arguments << options # If we don't have a rendering format, set one early. - self.render_as ||= (@action.render_as || :console) + self.render_as ||= @action.render_as || :console end def main diff --git a/lib/puppet/defaults.rb b/lib/puppet/defaults.rb index bb978cc30d7..5cc805a5089 100644 --- a/lib/puppet/defaults.rb +++ b/lib/puppet/defaults.rb @@ -77,7 +77,7 @@ def self.default_vendormoduledir # see the docs for Settings.define_settings ############################################################################################ - AS_DURATION = %q{This setting can be a time interval in seconds (30 or 30s), minutes (30m), hours (6h), days (2d), or years (5y).} + AS_DURATION = 'This setting can be a time interval in seconds (30 or 30s), minutes (30m), hours (6h), days (2d), or years (5y).' # @api public # @param args [Puppet::Settings] the settings object to define default settings for @@ -489,7 +489,7 @@ def self.initialize_default_settings!(settings) }, :daemonize => { :type => :boolean, - :default => (!Puppet::Util::Platform.windows?), + :default => !Puppet::Util::Platform.windows?, :desc => "Whether to send the process into the background. This defaults to true on POSIX systems, and to false on Windows (where Puppet currently cannot daemonize).", @@ -650,7 +650,7 @@ def self.initialize_default_settings!(settings) :http_proxy_password =>{ :default => "none", :hook => proc do |value| - if value =~ /[@!# \/]/ + if value =~ %r{[@!# /]} raise "Passwords set in the http_proxy_password setting must be valid as part of a URL, and any reserved characters must be URL-encoded. We received: #{value}" end end, diff --git a/lib/puppet/face/help.rb b/lib/puppet/face/help.rb index 1f56354101e..adcdce764b1 100644 --- a/lib/puppet/face/help.rb +++ b/lib/puppet/face/help.rb @@ -147,7 +147,7 @@ def erb(name) # Return a list of applications that are not simply just stubs for Faces. def legacy_applications Puppet::Application.available_application_names.reject do |appname| - (is_face_app?(appname)) or (exclude_from_docs?(appname)) + is_face_app?(appname) or exclude_from_docs?(appname) end.sort end @@ -208,7 +208,7 @@ def horribly_extract_summary_from(appname) # formatted. If we can't match the pattern we expect we return the empty # string to ensure we don't blow up in the summary. --daniel 2011-04-11 while line = help.shift do # rubocop:disable Lint/AssignmentInCondition - md = /^puppet-#{appname}\([^\)]+\) -- (.*)$/.match(line) + md = /^puppet-#{appname}\([^)]+\) -- (.*)$/.match(line) if md return md[1] end diff --git a/lib/puppet/file_serving/configuration.rb b/lib/puppet/file_serving/configuration.rb index 2587b03b09b..c5442f3515f 100644 --- a/lib/puppet/file_serving/configuration.rb +++ b/lib/puppet/file_serving/configuration.rb @@ -56,7 +56,7 @@ def split_path(request) mount_name, path = request.key.split(File::Separator, 2) - raise(ArgumentError, _("Cannot find file: Invalid mount '%{mount_name}'") % { mount_name: mount_name }) unless mount_name =~ %r{^[-\w]+$} + raise(ArgumentError, _("Cannot find file: Invalid mount '%{mount_name}'") % { mount_name: mount_name }) unless mount_name =~ /^[-\w]+$/ raise(ArgumentError, _("Cannot find file: Invalid relative path '%{path}'") % { path: path }) if path and path.split('/').include?('..') mount = find_mount(mount_name, request.environment) @@ -71,7 +71,7 @@ def split_path(request) path = nil elsif path # Remove any double slashes that might have occurred - path = path.gsub(/\/+/, "/") + path = path.gsub(%r{/+}, "/") end return mount, path diff --git a/lib/puppet/file_serving/fileset.rb b/lib/puppet/file_serving/fileset.rb index 75c82285dc8..84cc0ac8f54 100644 --- a/lib/puppet/file_serving/fileset.rb +++ b/lib/puppet/file_serving/fileset.rb @@ -29,7 +29,7 @@ def self.merge(*filesets) def initialize(path, options = {}) if Puppet::Util::Platform.windows? # REMIND: UNC path - path = path.chomp(File::SEPARATOR) unless path =~ /^[A-Za-z]:\/$/ + path = path.chomp(File::SEPARATOR) unless path =~ %r{^[A-Za-z]:/$} else path = path.chomp(File::SEPARATOR) unless path == File::SEPARATOR end diff --git a/lib/puppet/file_serving/metadata.rb b/lib/puppet/file_serving/metadata.rb index 51fe3298c0b..6edfec97f84 100644 --- a/lib/puppet/file_serving/metadata.rb +++ b/lib/puppet/file_serving/metadata.rb @@ -47,7 +47,7 @@ class MetaStat def initialize(stat, source_permissions) @stat = stat - @source_permissions_ignore = (!source_permissions || source_permissions == :ignore) + @source_permissions_ignore = !source_permissions || source_permissions == :ignore end def owner @@ -111,16 +111,20 @@ def collect(source_permissions = nil) case stat.ftype when "file" - @checksum = ("{#{@checksum_type}}") + send("#{@checksum_type}_file", real_path).to_s + @checksum = "{#{@checksum_type}}" + send("#{@checksum_type}_file", real_path).to_s when "directory" # Always just timestamp the directory. @checksum_type = "ctime" - @checksum = ("{#{@checksum_type}}") + send("#{@checksum_type}_file", path).to_s + @checksum = "{#{@checksum_type}}" + send("#{@checksum_type}_file", path).to_s when "link" @destination = Puppet::FileSystem.readlink(real_path) - @checksum = ("{#{@checksum_type}}") + send("#{@checksum_type}_file", real_path).to_s rescue nil + @checksum = begin + "{#{@checksum_type}}" + send("#{@checksum_type}_file", real_path).to_s + rescue + nil + end when "fifo", "socket" @checksum_type = "none" - @checksum = ("{#{@checksum_type}}") + send("#{@checksum_type}_file", real_path).to_s + @checksum = "{#{@checksum_type}}" + send("#{@checksum_type}_file", real_path).to_s else raise ArgumentError, _("Cannot manage files of type %{file_type}") % { file_type: stat.ftype } end diff --git a/lib/puppet/file_serving/mount.rb b/lib/puppet/file_serving/mount.rb index 64a33187aff..954cf5b388d 100644 --- a/lib/puppet/file_serving/mount.rb +++ b/lib/puppet/file_serving/mount.rb @@ -18,7 +18,7 @@ def find(path, options) # Create our object. It must have a name. def initialize(name) - unless name =~ %r{^[-\w]+$} + unless name =~ /^[-\w]+$/ raise ArgumentError, _("Invalid mount name format '%{name}'") % { name: name } end diff --git a/lib/puppet/file_system/path_pattern.rb b/lib/puppet/file_system/path_pattern.rb index cd16c1c2498..a5f29839ce0 100644 --- a/lib/puppet/file_system/path_pattern.rb +++ b/lib/puppet/file_system/path_pattern.rb @@ -8,7 +8,7 @@ class PathPattern class InvalidPattern < Puppet::Error; end DOTDOT = '..' - ABSOLUTE_UNIX = /^\// + ABSOLUTE_UNIX = %r{^/} ABSOLUTE_WINDOWS = /^[a-z]:/i CURRENT_DRIVE_RELATIVE_WINDOWS = /^\\/ diff --git a/lib/puppet/file_system/uniquefile.rb b/lib/puppet/file_system/uniquefile.rb index 83a5b783267..4a192e7b40d 100644 --- a/lib/puppet/file_system/uniquefile.rb +++ b/lib/puppet/file_system/uniquefile.rb @@ -151,10 +151,14 @@ def tmpdir tmp = '.' [ENV.fetch('TMPDIR', nil), ENV.fetch('TMP', nil), ENV.fetch('TEMP', nil), @@systmpdir, '/tmp'].each do |dir| stat = File.stat(dir) if dir - if stat && stat.directory? && stat.writable? - tmp = dir - break - end rescue nil + begin + if stat && stat.directory? && stat.writable? + tmp = dir + break + end + rescue + nil + end end File.expand_path(tmp) end diff --git a/lib/puppet/file_system/windows.rb b/lib/puppet/file_system/windows.rb index 82c35c10d94..988d6245b04 100644 --- a/lib/puppet/file_system/windows.rb +++ b/lib/puppet/file_system/windows.rb @@ -78,11 +78,19 @@ def unlink(*file_names) file_names.each do |file_name| file_name = file_name.to_s # handle PathName - stat = Puppet::Util::Windows::File.stat(file_name) rescue nil + stat = begin + Puppet::Util::Windows::File.stat(file_name) + rescue + nil + end # sigh, Ruby + Windows :( if !stat - ::File.unlink(file_name) rescue Dir.rmdir(file_name) + begin + ::File.unlink(file_name) + rescue + Dir.rmdir(file_name) + end elsif stat.ftype == 'directory' if Puppet::Util::Windows::File.symlink?(file_name) Dir.rmdir(file_name) diff --git a/lib/puppet/forge.rb b/lib/puppet/forge.rb index 8d12613d46a..8f084766627 100644 --- a/lib/puppet/forge.rb +++ b/lib/puppet/forge.rb @@ -231,7 +231,7 @@ def unpack(file, destination) end def deprecated? - @data['module'] && (!@data['module']['deprecated_at'].nil?) + @data['module'] && !@data['module']['deprecated_at'].nil? end end diff --git a/lib/puppet/functions/abs.rb b/lib/puppet/functions/abs.rb index 9751f876120..bb4d491a46a 100644 --- a/lib/puppet/functions/abs.rb +++ b/lib/puppet/functions/abs.rb @@ -53,9 +53,9 @@ def on_string(x) # version of this function. # case x - when %r{^-?(?:\d+)(?:\.\d+){1}$} + when /^-?(?:\d+)(?:\.\d+){1}$/ x.to_f.abs - when %r{^-?\d+$} + when /^-?\d+$/ x.to_i.abs else raise(ArgumentError, 'abs(): Requires float or integer to work with - was given non decimal string') diff --git a/lib/puppet/functions/max.rb b/lib/puppet/functions/max.rb index fab3b8313c8..6e84af3c909 100644 --- a/lib/puppet/functions/max.rb +++ b/lib/puppet/functions/max.rb @@ -146,7 +146,7 @@ def on_string(*args) assert_arg_count(args) args.max do |a, b| - if a.to_s =~ %r{\A^-?\d+([._eE]\d+)?\z} && b.to_s =~ %r{\A-?\d+([._eE]\d+)?\z} + if a.to_s =~ /\A^-?\d+([._eE]\d+)?\z/ && b.to_s =~ /\A-?\d+([._eE]\d+)?\z/ Puppet.warn_once('deprecations', 'max_function_numeric_coerce_string', _("The max() function's auto conversion of String to Numeric is deprecated - change to convert input before calling, or use lambda")) a.to_f <=> b.to_f @@ -232,7 +232,7 @@ def on_any(*args) args.max do |a, b| as = a.to_s bs = b.to_s - if as =~ %r{\A^-?\d+([._eE]\d+)?\z} && bs =~ %r{\A-?\d+([._eE]\d+)?\z} + if as =~ /\A^-?\d+([._eE]\d+)?\z/ && bs =~ /\A-?\d+([._eE]\d+)?\z/ Puppet.warn_once('deprecations', 'max_function_numeric_coerce_string', _("The max() function's auto conversion of String to Numeric is deprecated - change to convert input before calling, or use lambda")) a.to_f <=> b.to_f diff --git a/lib/puppet/functions/min.rb b/lib/puppet/functions/min.rb index 8a1c7a7f495..0c1dc9d9dd3 100644 --- a/lib/puppet/functions/min.rb +++ b/lib/puppet/functions/min.rb @@ -145,7 +145,7 @@ def on_string(*args) assert_arg_count(args) args.min do |a, b| - if a.to_s =~ %r{\A^-?\d+([._eE]\d+)?\z} && b.to_s =~ %r{\A-?\d+([._eE]\d+)?\z} + if a.to_s =~ /\A^-?\d+([._eE]\d+)?\z/ && b.to_s =~ /\A-?\d+([._eE]\d+)?\z/ Puppet.warn_once('deprecations', 'min_function_numeric_coerce_string', _("The min() function's auto conversion of String to Numeric is deprecated - change to convert input before calling, or use lambda")) a.to_f <=> b.to_f @@ -231,7 +231,7 @@ def on_any(*args) args.min do |a, b| as = a.to_s bs = b.to_s - if as =~ %r{\A^-?\d+([._eE]\d+)?\z} && bs =~ %r{\A-?\d+([._eE]\d+)?\z} + if as =~ /\A^-?\d+([._eE]\d+)?\z/ && bs =~ /\A-?\d+([._eE]\d+)?\z/ Puppet.warn_once('deprecations', 'min_function_numeric_coerce_string', _("The min() function's auto conversion of String to Numeric is deprecated - change to convert input before calling, or use lambda")) a.to_f <=> b.to_f diff --git a/lib/puppet/functions/regsubst.rb b/lib/puppet/functions/regsubst.rb index 72ab84d7f4b..af27fb8777a 100644 --- a/lib/puppet/functions/regsubst.rb +++ b/lib/puppet/functions/regsubst.rb @@ -92,7 +92,7 @@ def regsubst_string(target, pattern, replacement, flags = nil, encoding = nil) end def regsubst_regexp(target, pattern, replacement, flags = nil) - pattern = (pattern.pattern || '') if pattern.is_a?(Puppet::Pops::Types::PRegexpType) + pattern = pattern.pattern || '' if pattern.is_a?(Puppet::Pops::Types::PRegexpType) inner_regsubst(target, pattern, replacement, flags == 'G' ? :gsub : :sub) end diff --git a/lib/puppet/http/proxy.rb b/lib/puppet/http/proxy.rb index ce2329cabfb..cb01e3fbe2d 100644 --- a/lib/puppet/http/proxy.rb +++ b/lib/puppet/http/proxy.rb @@ -56,10 +56,10 @@ def self.no_proxy?(dest) # If this no_proxy entry specifies a port, we want to match it against # the destination port. Otherwise just match hosts. if port - no_proxy_regex = %r{#{host}:#{port}$} + no_proxy_regex = /#{host}:#{port}$/ dest_string = "#{dest.host}:#{dest.port}" else - no_proxy_regex = %r{#{host}$} + no_proxy_regex = /#{host}$/ dest_string = "#{dest.host}" end diff --git a/lib/puppet/http/service/file_server.rb b/lib/puppet/http/service/file_server.rb index 0c5d25f7f7c..d52d0cd7bc6 100644 --- a/lib/puppet/http/service/file_server.rb +++ b/lib/puppet/http/service/file_server.rb @@ -11,7 +11,7 @@ class Puppet::HTTP::Service::FileServer < Puppet::HTTP::Service API = '/puppet/v3' # @return [RegEx] RegEx used to determine if a path contains a leading slash - PATH_REGEX = /^\// + PATH_REGEX = %r{^/} # Use `Puppet::HTTP::Session.route_to(:fileserver)` to create or get an instance of this class. # diff --git a/lib/puppet/indirector/catalog/compiler.rb b/lib/puppet/indirector/catalog/compiler.rb index d0196674028..15e1f7e4a6a 100644 --- a/lib/puppet/indirector/catalog/compiler.rb +++ b/lib/puppet/indirector/catalog/compiler.rb @@ -169,7 +169,7 @@ def inlineable?(resource, sources) when sources.empty? # TRANSLATORS Inlining refers to adding additional metadata (in this case we are not inlining) return Puppet::Util::Profiler.profile(_("Not inlining resource without sources"), [:compiler, :static_compile_inlining, :skipped_file_metadata, :no_sources]) { false } - when (!(sources.all? { |source| source =~ /^puppet:/ })) + when !(sources.all? { |source| source =~ /^puppet:/ }) # TRANSLATORS Inlining refers to adding additional metadata (in this case we are not inlining) return Puppet::Util::Profiler.profile(_("Not inlining unsupported source scheme"), [:compiler, :static_compile_inlining, :skipped_file_metadata, :unsupported_scheme]) { false } else @@ -185,8 +185,8 @@ def inlineable_metadata?(metadata, source, environment_path) location = Puppet::Module::FILETYPES['files'] - !!(source_as_uri.path =~ /^\/modules\// && - metadata.full_path =~ /#{environment_path}\/[^\/]+\/[^\/]+\/#{location}\/.+/) + !!(source_as_uri.path =~ %r{^/modules/} && + metadata.full_path =~ %r{#{environment_path}/[^/]+/[^/]+/#{location}/.+}) end # Helper method to log file resources that could not be inlined because they diff --git a/lib/puppet/indirector/catalog/store_configs.rb b/lib/puppet/indirector/catalog/store_configs.rb index 12d9fc7560e..d40f38dc9df 100644 --- a/lib/puppet/indirector/catalog/store_configs.rb +++ b/lib/puppet/indirector/catalog/store_configs.rb @@ -4,5 +4,5 @@ require_relative '../../../puppet/resource/catalog' class Puppet::Resource::Catalog::StoreConfigs < Puppet::Indirector::StoreConfigs - desc %q(Part of the "storeconfigs" feature. Should not be directly set by end users.) + desc 'Part of the "storeconfigs" feature. Should not be directly set by end users.' end diff --git a/lib/puppet/indirector/facts/store_configs.rb b/lib/puppet/indirector/facts/store_configs.rb index 77794fb441c..ee903342a38 100644 --- a/lib/puppet/indirector/facts/store_configs.rb +++ b/lib/puppet/indirector/facts/store_configs.rb @@ -4,7 +4,7 @@ require_relative '../../../puppet/indirector/store_configs' class Puppet::Node::Facts::StoreConfigs < Puppet::Indirector::StoreConfigs - desc %q(Part of the "storeconfigs" feature. Should not be directly set by end users.) + desc 'Part of the "storeconfigs" feature. Should not be directly set by end users.' def allow_remote_requests? false diff --git a/lib/puppet/indirector/file_bucket_file/file.rb b/lib/puppet/indirector/file_bucket_file/file.rb index 46f4f5b82ad..72eb127eb4b 100644 --- a/lib/puppet/indirector/file_bucket_file/file.rb +++ b/lib/puppet/indirector/file_bucket_file/file.rb @@ -202,7 +202,7 @@ def save_to_disk(bucket_file, files_original_path, contents_file, paths_file) end def request_to_checksum_and_path(request) - checksum_type, checksum, path = request.key.split(/\//, 3) + checksum_type, checksum, path = request.key.split(%r{/}, 3) if path == '' # Treat "md5//" like "md5/" path = nil end diff --git a/lib/puppet/indirector/node/store_configs.rb b/lib/puppet/indirector/node/store_configs.rb index 431a52f922c..2a2cccaed5f 100644 --- a/lib/puppet/indirector/node/store_configs.rb +++ b/lib/puppet/indirector/node/store_configs.rb @@ -4,5 +4,5 @@ require_relative '../../../puppet/node' class Puppet::Node::StoreConfigs < Puppet::Indirector::StoreConfigs - desc %q(Part of the "storeconfigs" feature. Should not be directly set by end users.) + desc 'Part of the "storeconfigs" feature. Should not be directly set by end users.' end diff --git a/lib/puppet/indirector/request.rb b/lib/puppet/indirector/request.rb index 12238a0ee4b..121afcf5b13 100644 --- a/lib/puppet/indirector/request.rb +++ b/lib/puppet/indirector/request.rb @@ -80,7 +80,7 @@ def initialize(indirection_name, method, key, instance, options = {}) # info out in the REST class, but it seemed bad design for the REST # class to rewrite the key. - if key.to_s =~ /^\w+:\// and !Puppet::Util.absolute_path?(key.to_s) # it's a URI + if key.to_s =~ %r{^\w+:/} and !Puppet::Util.absolute_path?(key.to_s) # it's a URI set_uri_key(key) else @key = key @@ -192,6 +192,6 @@ def set_uri_key(key) @protocol = uri.scheme end - @key = Puppet::Util.uri_unescape(uri.path.sub(/^\//, '')) + @key = Puppet::Util.uri_unescape(uri.path.sub(%r{^/}, '')) end end diff --git a/lib/puppet/indirector/resource/store_configs.rb b/lib/puppet/indirector/resource/store_configs.rb index fb61a1a44fe..206d3b7fb71 100644 --- a/lib/puppet/indirector/resource/store_configs.rb +++ b/lib/puppet/indirector/resource/store_configs.rb @@ -6,7 +6,7 @@ class Puppet::Resource::StoreConfigs < Puppet::Indirector::StoreConfigs include Puppet::Resource::Validator - desc %q(Part of the "storeconfigs" feature. Should not be directly set by end users.) + desc 'Part of the "storeconfigs" feature. Should not be directly set by end users.' def allow_remote_requests? false diff --git a/lib/puppet/interface/face_collection.rb b/lib/puppet/interface/face_collection.rb index f95fe1572b3..3bf86cb7e9f 100644 --- a/lib/puppet/interface/face_collection.rb +++ b/lib/puppet/interface/face_collection.rb @@ -55,7 +55,7 @@ def self.get_face(name, pattern) end def self.find_matching(range, versions) - versions.select { |v| range === v }.sort.last + versions.select { |v| range === v }.max end # try to load the face, and return it. @@ -95,7 +95,7 @@ def self.load_face(name, version) # versions here and return the last item in that set. # # --daniel 2011-04-06 - latest_ver = @faces[name].keys.sort.last + latest_ver = @faces[name].keys.max @faces[name][:current] = @faces[name][latest_ver] end end @@ -113,12 +113,12 @@ def self.safely_require(name, version = nil) require path true rescue LoadError => e - raise unless e.message =~ %r{-- #{path}$} + raise unless e.message =~ /-- #{path}$/ # ...guess we didn't find the file; return a much better problem. nil rescue SyntaxError => e - raise unless e.message =~ %r{#{path}\.rb:\d+: } + raise unless e.message =~ /#{path}\.rb:\d+: / Puppet.err _("Failed to load face %{name}:\n%{detail}") % { name: name, detail: e } # ...but we just carry on after complaining. diff --git a/lib/puppet/interface/option_manager.rb b/lib/puppet/interface/option_manager.rb index 0be7d73c52f..75ee85e2d2c 100644 --- a/lib/puppet/interface/option_manager.rb +++ b/lib/puppet/interface/option_manager.rb @@ -28,7 +28,7 @@ def all_display_global_options # @api private def walk_inheritance_tree(start, sym) - result = (start || []) + result = start || [] if self.is_a?(Class) and superclass.respond_to?(sym) result = superclass.send(sym) + result elsif self.class.respond_to?(sym) diff --git a/lib/puppet/module.rb b/lib/puppet/module.rb index 34cb93f2b8e..ed71cddc335 100644 --- a/lib/puppet/module.rb +++ b/lib/puppet/module.rb @@ -58,7 +58,7 @@ def self.is_module_directory_name?(name) def self.is_module_namespaced_name?(name) # it must match the full module name according to forge validator - return true if name =~ /^[a-zA-Z0-9]+[-][a-z][a-z0-9_]*$/ + return true if name =~ /^[a-zA-Z0-9]+-[a-z][a-z0-9_]*$/ return false end diff --git a/lib/puppet/module/plan.rb b/lib/puppet/module/plan.rb index 00cf10e85f2..ec8cf7ace28 100644 --- a/lib/puppet/module/plan.rb +++ b/lib/puppet/module/plan.rb @@ -89,7 +89,7 @@ def self.find_implementations(name, plan_files) implementations = plan_files.select { |impl| File.basename(impl, '.*') == basename } # Select .pp before .yaml, since .pp comes before .yaml alphabetically. - chosen = implementations.sort.first + chosen = implementations.min [{ "name" => File.basename(chosen), "path" => chosen }] end diff --git a/lib/puppet/module_tool.rb b/lib/puppet/module_tool.rb index de8435509bb..1d52cb3e5bf 100644 --- a/lib/puppet/module_tool.rb +++ b/lib/puppet/module_tool.rb @@ -13,7 +13,7 @@ module ModuleTool # Directory and names that should not be checksummed. ARTIFACTS = ['pkg', /^\./, /^~/, /^#/, 'coverage', 'checksums.json', 'REVISION'] - FULL_MODULE_NAME_PATTERN = /\A([^-\/|.]+)[-|\/](.+)\z/ + FULL_MODULE_NAME_PATTERN = %r{\A([^-/|.]+)[-|/](.+)\z} REPOSITORY_URL = Puppet.settings[:module_repository] # Is this a directory that shouldn't be checksummed? @@ -102,7 +102,7 @@ def self.build_tree(mods, dir) mod[:text] = "#{mod[:name]} (#{colorize(:cyan, version_string)})" mod[:text] += " [#{mod[:path]}]" unless mod[:path].to_s == dir.to_s - deps = (mod[:dependencies] || []) + deps = mod[:dependencies] || [] deps.sort_by! { |a| a[:name] } build_tree(deps, dir) end diff --git a/lib/puppet/module_tool/applications/application.rb b/lib/puppet/module_tool/applications/application.rb index 50544607027..c04f1ddaff3 100644 --- a/lib/puppet/module_tool/applications/application.rb +++ b/lib/puppet/module_tool/applications/application.rb @@ -28,7 +28,11 @@ def discuss(response, success, failure) when Net::HTTPOK, Net::HTTPCreated Puppet.notice success else - errors = Puppet::Util::Json.load(response.body)['error'] rescue "HTTP #{response.code}, #{response.body}" + errors = begin + Puppet::Util::Json.load(response.body)['error'] + rescue + "HTTP #{response.code}, #{response.body}" + end Puppet.warning "#{failure} (#{errors})" end end diff --git a/lib/puppet/module_tool/applications/installer.rb b/lib/puppet/module_tool/applications/installer.rb index 4f557c95de9..1d6d2f9da56 100644 --- a/lib/puppet/module_tool/applications/installer.rb +++ b/lib/puppet/module_tool/applications/installer.rb @@ -72,7 +72,11 @@ def run results[:version] = installed_module.version return results else - changes = Checksummer.run(installed_modules[name].mod.path) rescue [] + changes = begin + Checksummer.run(installed_modules[name].mod.path) + rescue + [] + end raise AlreadyInstalledError, :module_name => name, :installed_version => installed_modules[name].version, diff --git a/lib/puppet/module_tool/applications/unpacker.rb b/lib/puppet/module_tool/applications/unpacker.rb index 0f9eacdcec9..443a87d59e7 100644 --- a/lib/puppet/module_tool/applications/unpacker.rb +++ b/lib/puppet/module_tool/applications/unpacker.rb @@ -64,7 +64,7 @@ def root_dir return @root_dir if @root_dir # Grab the first directory containing a metadata.json file - metadata_file = Dir["#{tmpdir}/**/metadata.json"].sort_by(&:length)[0] + metadata_file = Dir["#{tmpdir}/**/metadata.json"].min_by(&:length) if metadata_file @root_dir = Pathname.new(metadata_file).dirname diff --git a/lib/puppet/module_tool/applications/upgrader.rb b/lib/puppet/module_tool/applications/upgrader.rb index f0a0fe54eb7..90af3094d2b 100644 --- a/lib/puppet/module_tool/applications/upgrader.rb +++ b/lib/puppet/module_tool/applications/upgrader.rb @@ -76,7 +76,11 @@ def installed_release.priority vstring = mod.version ? "v#{mod.version}" : '???' Puppet.notice _("Found '%{name}' (%{version}) in %{dir} ...") % { name: name, version: colorize(:cyan, vstring), dir: dir } unless @ignore_changes - changes = Checksummer.run(mod.path) rescue [] + changes = begin + Checksummer.run(mod.path) + rescue + [] + end if mod.has_metadata? && !changes.empty? raise LocalChangesError, :action => :upgrade, diff --git a/lib/puppet/module_tool/metadata.rb b/lib/puppet/module_tool/metadata.rb index 509ff63d2ab..6ca5ff45ce4 100644 --- a/lib/puppet/module_tool/metadata.rb +++ b/lib/puppet/module_tool/metadata.rb @@ -102,7 +102,11 @@ def to_json data = @data.dup.merge('dependencies' => dependencies) contents = data.keys.map do |k| - value = (Puppet::Util::Json.dump(data[k], :pretty => true) rescue data[k].to_json) + value = begin + Puppet::Util::Json.dump(data[k], :pretty => true) + rescue + data[k].to_json + end %Q("#{k}": #{value}) end @@ -121,7 +125,7 @@ def method_missing(name, *args) # Do basic validation and parsing of the name parameter. def process_name(data) validate_name(data['name']) - author, @module_name = data['name'].split(/[-\/]/, 2) + author, @module_name = data['name'].split(%r{[-/]}, 2) data['author'] ||= author if @data['author'] == DEFAULTS['author'] end @@ -149,7 +153,7 @@ def process_source(data) source_uri.scheme = 'https' source_uri.path.sub!(/\.git$/, '') data['project_page'] ||= @data['project_page'] || source_uri.to_s - data['issues_url'] ||= @data['issues_url'] || source_uri.to_s.sub(/\/*$/, '') + '/issues' + data['issues_url'] ||= @data['issues_url'] || source_uri.to_s.sub(%r{/*$}, '') + '/issues' end rescue URI::Error return @@ -167,9 +171,9 @@ def merge_dependencies(data) # Validates that the given module name is both namespaced and well-formed. def validate_name(name) - return if name =~ /\A[a-z0-9]+[-\/][a-z][a-z0-9_]*\Z/i + return if name =~ %r{\A[a-z0-9]+[-/][a-z][a-z0-9_]*\Z}i - namespace, modname = name.split(/[-\/]/, 2) + namespace, modname = name.split(%r{[-/]}, 2) modname = :namespace_missing if namespace == '' err = case modname diff --git a/lib/puppet/module_tool/shared_behaviors.rb b/lib/puppet/module_tool/shared_behaviors.rb index d408a83390f..4225676e9b6 100644 --- a/lib/puppet/module_tool/shared_behaviors.rb +++ b/lib/puppet/module_tool/shared_behaviors.rb @@ -38,7 +38,11 @@ def get_remote_constraints(forge) mod_name, releases = pair mod_name = mod_name.tr('/', '-') releases.each do |rel| - semver = SemanticPuppet::Version.parse(rel['version']) rescue SemanticPuppet::Version::MIN + semver = begin + SemanticPuppet::Version.parse(rel['version']) + rescue + SemanticPuppet::Version::MIN + end @versions[mod_name] << { :vstring => rel['version'], :semver => semver } @versions[mod_name].sort_by! { |a| a[:semver] } @urls["#{mod_name}@#{rel['version']}"] = rel['file'] @@ -79,10 +83,16 @@ def resolve_constraints(dependencies, source = [{ :name => :you }], seen = {}, a } if forced? - range = Puppet::Module.parse_range(@version) rescue Puppet::Module.parse_range('>= 0.0.0') + range = begin + Puppet::Module.parse_range(@version) + rescue + Puppet::Module.parse_range('>= 0.0.0') + end else range = (@conditions[mod]).map do |r| - Puppet::Module.parse_range(r[:dependency]) rescue Puppet::Module.parse_range('>= 0.0.0') + Puppet::Module.parse_range(r[:dependency]) + rescue + Puppet::Module.parse_range('>= 0.0.0') end.inject(&:&) end diff --git a/lib/puppet/network/http/api/server/v3.rb b/lib/puppet/network/http/api/server/v3.rb index 5ad6f35b324..e8926f3b3cc 100644 --- a/lib/puppet/network/http/api/server/v3.rb +++ b/lib/puppet/network/http/api/server/v3.rb @@ -28,7 +28,7 @@ def self.wrap(&block) .get(wrap { Environments.new(Puppet.lookup(:environments)) }) def self.routes - Puppet::Network::HTTP::Route.path(%r{v3}) + Puppet::Network::HTTP::Route.path(/v3/) .any .chain(ENVIRONMENTS, INDIRECTED) end diff --git a/lib/puppet/network/http/connection.rb b/lib/puppet/network/http/connection.rb index ccef476dca3..9840cdb8789 100644 --- a/lib/puppet/network/http/connection.rb +++ b/lib/puppet/network/http/connection.rb @@ -245,7 +245,7 @@ def resolve_ssl_context end def to_url(path) - if path =~ /^https?:\/\// + if path =~ %r{^https?://} # The old Connection class accepts a URL as the request path, and sends # it in "absolute-form" in the request line, e.g. GET https://puppet:8140/. # See https://httpwg.org/specs/rfc7230.html#absolute-form. It just so happens diff --git a/lib/puppet/parser.rb b/lib/puppet/parser.rb index 2194bdc0bcb..3f8389601a7 100644 --- a/lib/puppet/parser.rb +++ b/lib/puppet/parser.rb @@ -16,7 +16,7 @@ module Puppet::Parser; end require_relative '../puppet/resource/type' require 'monitor' -require_relative 'parser/compiler/catalog_validator/relationship_validator.rb' +require_relative 'parser/compiler/catalog_validator/relationship_validator' # PUP-3274 This should probably go someplace else class Puppet::LexError < RuntimeError; end diff --git a/lib/puppet/parser/functions/create_resources.rb b/lib/puppet/parser/functions/create_resources.rb index 7df54660a77..9e0f1e03d4b 100644 --- a/lib/puppet/parser/functions/create_resources.rb +++ b/lib/puppet/parser/functions/create_resources.rb @@ -61,10 +61,10 @@ end raise ArgumentError, (_("create_resources(): wrong number of arguments (%{count}; must be 2 or 3)") % { count: args.length }) if args.length > 3 - raise ArgumentError, (_('create_resources(): second argument must be a hash')) unless args[1].is_a?(Hash) + raise ArgumentError, _('create_resources(): second argument must be a hash') unless args[1].is_a?(Hash) if args.length == 3 - raise ArgumentError, (_('create_resources(): third argument, if provided, must be a hash')) unless args[2].is_a?(Hash) + raise ArgumentError, _('create_resources(): third argument, if provided, must be a hash') unless args[2].is_a?(Hash) end type, instances, defaults = args diff --git a/lib/puppet/parser/functions/generate.rb b/lib/puppet/parser/functions/generate.rb index e5a419f23f0..b81b5c04cab 100644 --- a/lib/puppet/parser/functions/generate.rb +++ b/lib/puppet/parser/functions/generate.rb @@ -17,9 +17,9 @@ raise Puppet::ParseError, _("Generators must be fully qualified") unless Puppet::Util.absolute_path?(args[0]) if Puppet::Util::Platform.windows? - valid = args[0] =~ /^[a-z]:(?:[\/\\][-.~\w]+)+$/i + valid = args[0] =~ %r{^[a-z]:(?:[/\\][-.~\w]+)+$}i else - valid = args[0] =~ /^[-\/\w.+]+$/ + valid = args[0] =~ %r{^[-/\w.+]+$} end unless valid diff --git a/lib/puppet/parser/templatewrapper.rb b/lib/puppet/parser/templatewrapper.rb index cbeb2b891b0..2026c418c22 100644 --- a/lib/puppet/parser/templatewrapper.rb +++ b/lib/puppet/parser/templatewrapper.rb @@ -100,6 +100,6 @@ def result(string = nil) end def to_s - "template[#{(@__file__ || "inline")}]" + "template[#{@__file__ || "inline"}]" end end diff --git a/lib/puppet/pops/loader/ruby_data_type_instantiator.rb b/lib/puppet/pops/loader/ruby_data_type_instantiator.rb index 79547958d47..71a75532a51 100644 --- a/lib/puppet/pops/loader/ruby_data_type_instantiator.rb +++ b/lib/puppet/pops/loader/ruby_data_type_instantiator.rb @@ -15,7 +15,7 @@ class Puppet::Pops::Loader::RubyDataTypeInstantiator # @return [Puppet::Pops::Types::PAnyType] - an instantiated data type associated with the given loader # def self.create(loader, typed_name, source_ref, ruby_code_string) - unless ruby_code_string.is_a?(String) && ruby_code_string =~ /Puppet\:\:DataTypes\.create_type/ + unless ruby_code_string.is_a?(String) && ruby_code_string =~ /Puppet::DataTypes\.create_type/ raise ArgumentError, _("The code loaded from %{source_ref} does not seem to be a Puppet 5x API data type - no create_type call.") % { source_ref: source_ref } end diff --git a/lib/puppet/pops/loader/ruby_function_instantiator.rb b/lib/puppet/pops/loader/ruby_function_instantiator.rb index f6d0f1c0692..6d4ccde3020 100644 --- a/lib/puppet/pops/loader/ruby_function_instantiator.rb +++ b/lib/puppet/pops/loader/ruby_function_instantiator.rb @@ -15,7 +15,7 @@ class Puppet::Pops::Loader::RubyFunctionInstantiator # @return [Puppet::Pops::Functions.Function] - an instantiated function with global scope closure associated with the given loader # def self.create(loader, typed_name, source_ref, ruby_code_string) - unless ruby_code_string.is_a?(String) && ruby_code_string =~ /Puppet\:\:Functions\.create_function/ + unless ruby_code_string.is_a?(String) && ruby_code_string =~ /Puppet::Functions\.create_function/ raise ArgumentError, _("The code loaded from %{source_ref} does not seem to be a Puppet 4x API function - no create_function call.") % { source_ref: source_ref } end diff --git a/lib/puppet/pops/lookup/explainer.rb b/lib/puppet/pops/lookup/explainer.rb index 1893770b709..7f9ceac4aac 100644 --- a/lib/puppet/pops/lookup/explainer.rb +++ b/lib/puppet/pops/lookup/explainer.rb @@ -469,7 +469,7 @@ def initialize(explain_options = false, only_explain_options = false) end def push(qualifier_type, qualifier) - node = case (qualifier_type) + node = case qualifier_type when :global ExplainGlobal.new(@current, qualifier) when :location diff --git a/lib/puppet/pops/lookup/hiera_config.rb b/lib/puppet/pops/lookup/hiera_config.rb index 56446e635ed..84708456acd 100644 --- a/lib/puppet/pops/lookup/hiera_config.rb +++ b/lib/puppet/pops/lookup/hiera_config.rb @@ -105,7 +105,7 @@ def self.config_exist?(config_root) end def self.symkeys_to_string(struct) - case (struct) + case struct when Hash map = {} struct.each_pair { |k, v| map[k.is_a?(Symbol) ? k.to_s : k] = symkeys_to_string(v) } diff --git a/lib/puppet/pops/lookup/interpolation.rb b/lib/puppet/pops/lookup/interpolation.rb index 06cf09ea555..c48e24fbffa 100644 --- a/lib/puppet/pops/lookup/interpolation.rb +++ b/lib/puppet/pops/lookup/interpolation.rb @@ -48,7 +48,7 @@ def interpolate(value, context, allow_methods) def interpolate_string(subject, context, allow_methods) lookup_invocation = context.is_a?(Invocation) ? context : context.invocation lookup_invocation.with(:interpolate, subject) do - subject.gsub(/%\{([^\}]*)\}/) do |match| + subject.gsub(/%\{([^}]*)\}/) do |match| expr = ::Regexp.last_match(1) # Leading and trailing spaces inside an interpolation expression are insignificant expr.strip! @@ -144,7 +144,7 @@ def nil_in_scope?(scope, key) end def get_method_and_data(data, allow_methods) - match = data.match(/^(\w+)\((?:["]([^"]+)["]|[']([^']+)['])\)$/) + match = data.match(/^(\w+)\((?:"([^"]+)"|'([^']+)')\)$/) if match fail(Issues::HIERA_INTERPOLATION_METHOD_SYNTAX_NOT_ALLOWED) unless allow_methods diff --git a/lib/puppet/pops/lookup/sub_lookup.rb b/lib/puppet/pops/lookup/sub_lookup.rb index fa84fc50b86..ee67491292b 100644 --- a/lib/puppet/pops/lookup/sub_lookup.rb +++ b/lib/puppet/pops/lookup/sub_lookup.rb @@ -3,7 +3,7 @@ module Puppet::Pops module Lookup module SubLookup - SPECIAL = /['"\.]/ + SPECIAL = /['".]/ # Split key into segments. A segment may be a quoted string (both single and double quotes can # be used) and the segment separator is the '.' character. Whitespace will be trimmed off on diff --git a/lib/puppet/pops/parser/heredoc_support.rb b/lib/puppet/pops/parser/heredoc_support.rb index 4f9a1519471..80e4f6b6e51 100644 --- a/lib/puppet/pops/parser/heredoc_support.rb +++ b/lib/puppet/pops/parser/heredoc_support.rb @@ -8,7 +8,7 @@ module HeredocSupport # Pattern for heredoc `@(endtag[:syntax][/escapes]) # Produces groups for endtag (group 1), syntax (group 2), and escapes (group 3) # - PATTERN_HEREDOC = %r{@\(([^:/\r\n\)]+)(?::[[:blank:]]*([a-z][a-zA-Z0-9_+]+)[[:blank:]]*)?(?:/((?:\w|[$])*)[[:blank:]]*)?\)} + PATTERN_HEREDOC = %r{@\(([^:/\r\n)]+)(?::[[:blank:]]*([a-z][a-zA-Z0-9_+]+)[[:blank:]]*)?(?:/((?:\w|[$])*)[[:blank:]]*)?\)} def heredoc scn = @scanner @@ -81,7 +81,7 @@ def heredoc # that terminates the heredoc is found. # (Endline in EBNF form): WS* ('|' WS*)? ('-' WS*)? endtag WS* \r? (\n|$) - endline_pattern = /([[:blank:]]*)(?:([|])[[:blank:]]*)?(?:(\-)[[:blank:]]*)?#{Regexp.escape(endtag)}[[:blank:]]*\r?(?:\n|\z)/ + endline_pattern = /([[:blank:]]*)(?:([|])[[:blank:]]*)?(?:(-)[[:blank:]]*)?#{Regexp.escape(endtag)}[[:blank:]]*\r?(?:\n|\z)/ lines = [] until scn.eos? do one_line = scn.scan_until(/(?:\n|\z)/) diff --git a/lib/puppet/pops/parser/interpolation_support.rb b/lib/puppet/pops/parser/interpolation_support.rb index d1d003b940d..4e90edb60cb 100644 --- a/lib/puppet/pops/parser/interpolation_support.rb +++ b/lib/puppet/pops/parser/interpolation_support.rb @@ -7,7 +7,7 @@ # of passing parameters and evaluating conditional logic has a negative impact on performance. # module Puppet::Pops::Parser::InterpolationSupport - PATTERN_VARIABLE = %r{(::)?(\w+::)*\w+} + PATTERN_VARIABLE = /(::)?(\w+::)*\w+/ # This is the starting point for a double quoted string with possible interpolation # The structure mimics that of the grammar. diff --git a/lib/puppet/pops/parser/lexer2.rb b/lib/puppet/pops/parser/lexer2.rb index d4987e329e3..972d6d984e2 100644 --- a/lib/puppet/pops/parser/lexer2.rb +++ b/lib/puppet/pops/parser/lexer2.rb @@ -150,11 +150,11 @@ class Lexer2 KEYWORDS.each { |k, v| KEYWORD_NAMES[v[0]] = k } KEYWORD_NAMES.freeze - PATTERN_WS = %r{[[:blank:]\r]+} - PATTERN_NON_WS = %r{\w+\b?} + PATTERN_WS = /[[:blank:]\r]+/ + PATTERN_NON_WS = /\w+\b?/ # The single line comment includes the line ending. - PATTERN_COMMENT = %r{#.*\r?} + PATTERN_COMMENT = /#.*\r?/ PATTERN_MLCOMMENT = %r{/\*(.*?)\*/}m PATTERN_REGEX = %r{/[^/]*/} @@ -170,13 +170,13 @@ class Lexer2 # The NAME and CLASSREF in 4x are strict. Each segment must start with # a letter a-z and may not contain dashes (\w includes letters, digits and _). # - PATTERN_CLASSREF = %r{((::){0,1}[A-Z][\w]*)+} - PATTERN_NAME = %r{^((::)?[a-z][\w]*)(::[a-z][\w]*)*$} + PATTERN_CLASSREF = /((::){0,1}[A-Z]\w*)+/ + PATTERN_NAME = /^((::)?[a-z]\w*)(::[a-z]\w*)*$/ - PATTERN_BARE_WORD = %r{((?:::){0,1}(?:[a-z_](?:[\w-]*[\w])?))+} + PATTERN_BARE_WORD = /((?:::){0,1}(?:[a-z_](?:[\w-]*\w)?))+/ - PATTERN_DOLLAR_VAR = %r{\$(::)?(\w+::)*\w+} - PATTERN_NUMBER = %r{\b(?:0[xX][0-9A-Fa-f]+|0?\d+(?:\.\d+)?(?:[eE]-?\d+)?)\b} + PATTERN_DOLLAR_VAR = /\$(::)?(\w+::)*\w+/ + PATTERN_NUMBER = /\b(?:0[xX][0-9A-Fa-f]+|0?\d+(?:\.\d+)?(?:[eE]-?\d+)?)\b/ # PERFORMANCE NOTE: # Comparison against a frozen string is faster (than unfrozen). diff --git a/lib/puppet/pops/parser/slurp_support.rb b/lib/puppet/pops/parser/slurp_support.rb index 14e815a662e..ea9f0b48e41 100644 --- a/lib/puppet/pops/parser/slurp_support.rb +++ b/lib/puppet/pops/parser/slurp_support.rb @@ -13,9 +13,9 @@ module Parser module SlurpSupport include LexerSupport - SLURP_SQ_PATTERN = /(?:[^\\]|^)(?:[\\]{2})*[']/ - SLURP_DQ_PATTERN = /(?:[^\\]|^)(?:[\\]{2})*(["]|[$]\{?)/ - SLURP_UQ_PATTERN = /(?:[^\\]|^)(?:[\\]{2})*([$]\{?|\z)/ + SLURP_SQ_PATTERN = /(?:[^\\]|^)(?:\\{2})*'/ + SLURP_DQ_PATTERN = /(?:[^\\]|^)(?:\\{2})*("|[$]\{?)/ + SLURP_UQ_PATTERN = /(?:[^\\]|^)(?:\\{2})*([$]\{?|\z)/ # unquoted, no escapes SLURP_UQNE_PATTERN = /(\$\{?|\z)/m SLURP_ALL_PATTERN = /.*(\z)/m @@ -76,7 +76,7 @@ def slurp(scanner, pattern, escapes, ignore_invalid_escapes) # If later a \u is found it is warned not to be a unicode escape if escapes.include?('u') # gsub must be repeated to cater for adjacent escapes - while str.gsub!(/((?:[^\\]|^)(?:[\\]{2})*)\\u(?:([\da-fA-F]{4})|\{([\da-fA-F]{1,6})\})/m) { ::Regexp.last_match(1) + [(::Regexp.last_match(2) || ::Regexp.last_match(3)).hex].pack("U") } + while str.gsub!(/((?:[^\\]|^)(?:\\{2})*)\\u(?:([\da-fA-F]{4})|\{([\da-fA-F]{1,6})\})/m) { ::Regexp.last_match(1) + [(::Regexp.last_match(2) || ::Regexp.last_match(3)).hex].pack("U") } # empty block. Everything happens in the gsub block end end diff --git a/lib/puppet/pops/patterns.rb b/lib/puppet/pops/patterns.rb index 28c71eae564..bf0de6c95a3 100644 --- a/lib/puppet/pops/patterns.rb +++ b/lib/puppet/pops/patterns.rb @@ -13,48 +13,48 @@ module Puppet::Pops::Patterns # Thus, a hex number has group 3 value, an octal value has group 4 (if it starts with 0), and no group 3 # and a floating point value has group 4 and group 5. # - NUMERIC = %r{\A[[:blank:]]*([-+]?)[[:blank:]]*((0[xX][0-9A-Fa-f]+)|(0?\d+)((?:\.\d+)?(?:[eE]-?\d+)?))[[:blank:]]*\z} + NUMERIC = /\A[[:blank:]]*([-+]?)[[:blank:]]*((0[xX][0-9A-Fa-f]+)|(0?\d+)((?:\.\d+)?(?:[eE]-?\d+)?))[[:blank:]]*\z/ # Special expression that tests if there is whitespace between sign and number. The expression is used # to strip such whitespace when normal Float or Integer conversion fails. - WS_BETWEEN_SIGN_AND_NUMBER = %r{\A([+-])[[:blank:]]+(.*)\z} + WS_BETWEEN_SIGN_AND_NUMBER = /\A([+-])[[:blank:]]+(.*)\z/ # ILLEGAL_P3_1_HOSTNAME matches if a hostname contains illegal characters. # This check does not prevent pathological names like 'a....b', '.....', "---". etc. - ILLEGAL_HOSTNAME_CHARS = %r{[^-\w.]} + ILLEGAL_HOSTNAME_CHARS = /[^-\w.]/ # NAME matches a name the same way as the lexer. - NAME = %r{\A((::)?[a-z]\w*)(::[a-z]\w*)*\z} + NAME = /\A((::)?[a-z]\w*)(::[a-z]\w*)*\z/ # CLASSREF_EXT matches a class reference the same way as the lexer - i.e. the external source form # where each part must start with a capital letter A-Z. # - CLASSREF_EXT = %r{\A((::){0,1}[A-Z][\w]*)+\z} + CLASSREF_EXT = /\A((::){0,1}[A-Z]\w*)+\z/ # Same as CLASSREF_EXT but cannot start with '::' # - CLASSREF_EXT_DECL = %r{\A[A-Z][\w]*(?:::[A-Z][\w]*)*\z} + CLASSREF_EXT_DECL = /\A[A-Z]\w*(?:::[A-Z]\w*)*\z/ # CLASSREF matches a class reference the way it is represented internally in the # model (i.e. in lower case). # - CLASSREF = %r{\A((::){0,1}[a-z][\w]*)+\z} + CLASSREF = /\A((::){0,1}[a-z]\w*)+\z/ # Same as CLASSREF but cannot start with '::' # - CLASSREF_DECL = %r{\A[a-z][\w]*(?:::[a-z][\w]*)*\z} + CLASSREF_DECL = /\A[a-z]\w*(?:::[a-z]\w*)*\z/ # DOLLAR_VAR matches a variable name including the initial $ character - DOLLAR_VAR = %r{\$(::)?(\w+::)*\w+} + DOLLAR_VAR = /\$(::)?(\w+::)*\w+/ # VAR_NAME matches the name part of a variable (The $ character is not included) # Note, that only the final segment may start with an underscore. # Note, regexp sensitive to backtracking - VAR_NAME = %r{\A(?:::)?(?:[a-z]\w*::)*[a-z_]\w*\z} + VAR_NAME = /\A(?:::)?(?:[a-z]\w*::)*[a-z_]\w*\z/ # PARAM_NAME matches the name part of a parameter (The $ character is not included) - PARAM_NAME = %r{\A[a-z_]\w*\z} + PARAM_NAME = /\A[a-z_]\w*\z/ # A Numeric var name must be the decimal number 0, or a decimal number not starting with 0 - NUMERIC_VAR_NAME = %r{\A(?:0|(?:[1-9][0-9]*))\z} + NUMERIC_VAR_NAME = /\A(?:0|(?:[1-9][0-9]*))\z/ end diff --git a/lib/puppet/pops/pcore.rb b/lib/puppet/pops/pcore.rb index f54360b14cf..26200eead5d 100644 --- a/lib/puppet/pops/pcore.rb +++ b/lib/puppet/pops/pcore.rb @@ -10,7 +10,7 @@ module Pcore TYPE_URI = Types::TypeFactory.pattern(TYPE_URI_RX) TYPE_URI_ALIAS = Types::PTypeAliasType.new('Pcore::URI', nil, TYPE_URI) TYPE_SIMPLE_TYPE_NAME = Types::TypeFactory.pattern(/\A[A-Z]\w*\z/) - TYPE_QUALIFIED_REFERENCE = Types::TypeFactory.pattern(/\A[A-Z][\w]*(?:::[A-Z][\w]*)*\z/) + TYPE_QUALIFIED_REFERENCE = Types::TypeFactory.pattern(/\A[A-Z]\w*(?:::[A-Z]\w*)*\z/) TYPE_MEMBER_NAME = Types::PPatternType.new([Types::PRegexpType.new(Patterns::PARAM_NAME)]) KEY_PCORE_URI = 'pcore_uri' diff --git a/lib/puppet/pops/types/p_sem_ver_range_type.rb b/lib/puppet/pops/types/p_sem_ver_range_type.rb index eb416731701..6f8410add7a 100644 --- a/lib/puppet/pops/types/p_sem_ver_range_type.rb +++ b/lib/puppet/pops/types/p_sem_ver_range_type.rb @@ -158,7 +158,7 @@ def from_versions(min, max = :default, exclude_max = false) end def from_hash(hash) - from_versions(hash['min'], hash.fetch('max') { :default }, hash.fetch('exclude_max') { false }) + from_versions(hash['min'], hash.fetch('max', :default), hash.fetch('exclude_max', false)) end end end diff --git a/lib/puppet/pops/types/type_mismatch_describer.rb b/lib/puppet/pops/types/type_mismatch_describer.rb index c32610a488f..854b2098207 100644 --- a/lib/puppet/pops/types/type_mismatch_describer.rb +++ b/lib/puppet/pops/types/type_mismatch_describer.rb @@ -894,7 +894,7 @@ def describe_argument_tuple(expected, actual, path) end def describe_tuple(expected, original, actual, path, size_mismatch_class) - return EMPTY_ARRAY if expected == actual || expected.types.empty? && (actual.is_a?(PArrayType)) + return EMPTY_ARRAY if expected == actual || expected.types.empty? && actual.is_a?(PArrayType) expected_size = expected.size_type || TypeFactory.range(*expected.size_range) diff --git a/lib/puppet/provider/file/posix.rb b/lib/puppet/provider/file/posix.rb index 1fd5e1498d3..2b3de8d3d4d 100644 --- a/lib/puppet/provider/file/posix.rb +++ b/lib/puppet/provider/file/posix.rb @@ -35,7 +35,9 @@ def uid2name(id) # Determine if the user is valid, and if so, return the UID def name2uid(value) - Integer(value) rescue uid(value) || false + Integer(value) + rescue + uid(value) || false end def gid2name(id) @@ -56,7 +58,9 @@ def gid2name(id) end def name2gid(value) - Integer(value) rescue gid(value) || false + Integer(value) + rescue + gid(value) || false end def owner diff --git a/lib/puppet/provider/nameservice.rb b/lib/puppet/provider/nameservice.rb index b4d6f25e86f..1efce56b939 100644 --- a/lib/puppet/provider/nameservice.rb +++ b/lib/puppet/provider/nameservice.rb @@ -98,7 +98,7 @@ def verify(name, error, &block) private def op(property) - @ops[property.name] || ("-#{property.name}") + @ops[property.name] || "-#{property.name}" end end diff --git a/lib/puppet/provider/package.rb b/lib/puppet/provider/package.rb index 9aa45a900ae..6e7e17b912d 100644 --- a/lib/puppet/provider/package.rb +++ b/lib/puppet/provider/package.rb @@ -25,7 +25,7 @@ def properties # Purged is the "most uninstalled" a package can be, so a purged package will be in-sync with # either `ensure => absent` or `ensure => purged`; an absent package will be out of sync with `ensure => purged`. default_status = self.class.feature?(:purgeable) ? :purged : :absent - @property_hash = query || { :ensure => (default_status) } + @property_hash = query || { :ensure => default_status } @property_hash[:ensure] = default_status if @property_hash.empty? end @property_hash.dup diff --git a/lib/puppet/provider/package/appdmg.rb b/lib/puppet/provider/package/appdmg.rb index 4ee6968c739..7176724971f 100644 --- a/lib/puppet/provider/package/appdmg.rb +++ b/lib/puppet/provider/package/appdmg.rb @@ -57,7 +57,7 @@ def self.installpkgdmg(source, name) cached_source = source tmpdir = Dir.mktmpdir begin - if %r{\A[A-Za-z][A-Za-z0-9+\-\.]*://} =~ cached_source + if %r{\A[A-Za-z][A-Za-z0-9+\-.]*://} =~ cached_source cached_source = File.join(tmpdir, name) begin curl "-o", cached_source, "-C", "-", "-L", "-s", "--url", source diff --git a/lib/puppet/provider/package/apt.rb b/lib/puppet/provider/package/apt.rb index 479b2c736df..f08ad339b90 100644 --- a/lib/puppet/provider/package/apt.rb +++ b/lib/puppet/provider/package/apt.rb @@ -108,7 +108,7 @@ def best_version(should_range) end end - return versions.sort.last if versions.any? + return versions.max if versions.any? Puppet.debug("No available version for package #{@resource[:name]} is included in range #{should_range}") should_range diff --git a/lib/puppet/provider/package/aptrpm.rb b/lib/puppet/provider/package/aptrpm.rb index c82fba0d5b1..78b5a110c17 100644 --- a/lib/puppet/provider/package/aptrpm.rb +++ b/lib/puppet/provider/package/aptrpm.rb @@ -53,7 +53,7 @@ def latest if output =~ /Versions:\s*\n((\n|.)+)^$/ versions = Regexp.last_match(1) available_versions = versions.split(/\n/).filter_map { |version| - if version =~ /^([^\(]+)\(/ + if version =~ /^([^(]+)\(/ Regexp.last_match(1) else self.warning _("Could not match version '%{version}'") % { version: version } diff --git a/lib/puppet/provider/package/dpkg.rb b/lib/puppet/provider/package/dpkg.rb index dc77635ee2c..581c1645dd6 100644 --- a/lib/puppet/provider/package/dpkg.rb +++ b/lib/puppet/provider/package/dpkg.rb @@ -45,10 +45,10 @@ def self.instances # Note: self:: is required here to keep these constants in the context of what will # eventually become this Puppet::Type::Package::ProviderDpkg class. - self::DPKG_QUERY_FORMAT_STRING = %q('${Status} ${Package} ${Version}\\n') - self::DPKG_QUERY_PROVIDES_FORMAT_STRING = %q('${Status} ${Package} ${Version} [${Provides}]\\n') - self::FIELDS_REGEX = %r{^'?(\S+) +(\S+) +(\S+) (\S+) (\S*)$} - self::FIELDS_REGEX_WITH_PROVIDES = %r{^'?(\S+) +(\S+) +(\S+) (\S+) (\S*) \[.*\]$} + self::DPKG_QUERY_FORMAT_STRING = "'${Status} ${Package} ${Version}\\n'" + self::DPKG_QUERY_PROVIDES_FORMAT_STRING = "'${Status} ${Package} ${Version} [${Provides}]\\n'" + self::FIELDS_REGEX = /^'?(\S+) +(\S+) +(\S+) (\S+) (\S*)$/ + self::FIELDS_REGEX_WITH_PROVIDES = /^'?(\S+) +(\S+) +(\S+) (\S+) (\S*) \[.*\]$/ self::FIELDS = [:desired, :error, :status, :name, :ensure] def self.defaultto_allow_virtual diff --git a/lib/puppet/provider/package/freebsd.rb b/lib/puppet/provider/package/freebsd.rb index 70c27883be1..48eff7f3653 100644 --- a/lib/puppet/provider/package/freebsd.rb +++ b/lib/puppet/provider/package/freebsd.rb @@ -18,7 +18,7 @@ def self.listcmd end def install - if @resource[:source] =~ /\/$/ + if @resource[:source] =~ %r{/$} if @resource[:source] =~ /^(ftp|https?):/ Puppet::Util.withenv :PACKAGESITE => @resource[:source] do pkgadd "-r", @resource[:name] diff --git a/lib/puppet/provider/package/openbsd.rb b/lib/puppet/provider/package/openbsd.rb index f3beb72ce0d..5ecd73b58b5 100644 --- a/lib/puppet/provider/package/openbsd.rb +++ b/lib/puppet/provider/package/openbsd.rb @@ -30,7 +30,7 @@ def self.instances begin execpipe(listcmd) do |process| # our regex for matching pkg_info output - regex = /^(.*)-(\d[^-]*)[-]?([\w-]*)(.*)$/ + regex = /^(.*)-(\d[^-]*)-?([\w-]*)(.*)$/ fields = [:name, :ensure, :flavor] hash = {} @@ -89,15 +89,15 @@ def latest return version else # Remove all fuzzy matches first. - output = output.split.select { |p| p =~ /^#{resource[:name]}-(\d[^-]*)[-]?(\w*)/ }.join + output = output.split.select { |p| p =~ /^#{resource[:name]}-(\d[^-]*)-?(\w*)/ }.join debug "pkg_info -Q for #{resource[:name]}: #{output}" end - if output =~ /^#{resource[:name]}-(\d[^-]*)[-]?(\w*) \(installed\)$/ + if output =~ /^#{resource[:name]}-(\d[^-]*)-?(\w*) \(installed\)$/ debug "Package is already the latest available" return version else - match = /^(.*)-(\d[^-]*)[-]?(\w*)$/.match(output) + match = /^(.*)-(\d[^-]*)-?(\w*)$/.match(output) debug "Latest available for #{resource[:name]}: #{match[2]}" if version.to_sym == :absent || version.to_sym == :purged @@ -201,7 +201,7 @@ def get_full_name(latest = false) def get_version execpipe([command(:pkginfo), "-I", @resource[:name]]) do |process| # our regex for matching pkg_info output - regex = /^(.*)-(\d[^-]*)[-]?(\w*)(.*)$/ + regex = /^(.*)-(\d[^-]*)-?(\w*)(.*)$/ master_version = 0 version = -1 diff --git a/lib/puppet/provider/package/opkg.rb b/lib/puppet/provider/package/opkg.rb index 4b2ef103b35..44bae199e01 100644 --- a/lib/puppet/provider/package/opkg.rb +++ b/lib/puppet/provider/package/opkg.rb @@ -13,7 +13,7 @@ def self.instances packages = [] execpipe("#{command(:opkg)} list-installed") do |process| - regex = %r{^(\S+) - (\S+)} + regex = /^(\S+) - (\S+)/ fields = [:name, :ensure] hash = {} diff --git a/lib/puppet/provider/package/pacman.rb b/lib/puppet/provider/package/pacman.rb index 282fa77b41e..324f0182bb8 100644 --- a/lib/puppet/provider/package/pacman.rb +++ b/lib/puppet/provider/package/pacman.rb @@ -75,7 +75,7 @@ def self.get_installed_packages packages = {} execpipe([command(:pacman), "-Q"]) do |pipe| # pacman -Q output is 'packagename version-rel' - regex = %r{^(\S+)\s(\S+)} + regex = /^(\S+)\s(\S+)/ pipe.each_line do |line| match = regex.match(line) if match diff --git a/lib/puppet/provider/package/pkgdmg.rb b/lib/puppet/provider/package/pkgdmg.rb index 0b8d45d8da9..5127a793e77 100644 --- a/lib/puppet/provider/package/pkgdmg.rb +++ b/lib/puppet/provider/package/pkgdmg.rb @@ -85,7 +85,7 @@ def self.installpkgdmg(source, name) tmpdir = Dir.mktmpdir ext = /(\.dmg|\.pkg)$/i.match(source)[0] begin - if %r{\A[A-Za-z][A-Za-z0-9+\-\.]*://} =~ cached_source + if %r{\A[A-Za-z][A-Za-z0-9+\-.]*://} =~ cached_source cached_source = File.join(tmpdir, "#{name}#{ext}") args = ["-o", cached_source, "-C", "-", "-L", "-s", "--fail", "--url", source] if http_proxy_host and http_proxy_port diff --git a/lib/puppet/provider/package/pkgng.rb b/lib/puppet/provider/package/pkgng.rb index 4cd4c46b264..a4d24fe5b69 100644 --- a/lib/puppet/provider/package/pkgng.rb +++ b/lib/puppet/provider/package/pkgng.rb @@ -113,7 +113,7 @@ def install # just 'curl'), drop the category prefix. pkgng doesn't support version # pinning with the origin syntax (pkg install curl-1.2.3 is valid, but # pkg install www/curl-1.2.3 is not). - if resource[:name] =~ /\// + if resource[:name] =~ %r{/} installname = resource[:name].split('/')[1] + '-' + resource[:ensure] else installname = resource[:name] + '-' + resource[:ensure] diff --git a/lib/puppet/provider/package/portage.rb b/lib/puppet/provider/package/portage.rb index 79c024f1daa..c8e40b20119 100644 --- a/lib/puppet/provider/package/portage.rb +++ b/lib/puppet/provider/package/portage.rb @@ -121,7 +121,7 @@ def qatom else search = '=' + @resource[:name] + '-' + "#{should}" end - search_output = qatom_bin(*([search, '--format', output_format])) + search_output = qatom_bin(*[search, '--format', output_format]) # verify if the search found anything match = result_format.match(search_output) if match @@ -147,7 +147,7 @@ def qatom_output_format end def qatom_result_format - /^\"\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\](.*)\"$/ + /^"\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\](.*)"$/ end def qatom_result_fields @@ -155,7 +155,7 @@ def qatom_result_fields end def self.get_sets - @sets ||= @sets = emerge(*(['--list-sets'])) + @sets ||= @sets = emerge(*['--list-sets']) end def query diff --git a/lib/puppet/provider/package/ports.rb b/lib/puppet/provider/package/ports.rb index 765ce2661c3..4afe20e9628 100644 --- a/lib/puppet/provider/package/ports.rb +++ b/lib/puppet/provider/package/ports.rb @@ -72,8 +72,8 @@ def latest def query # support portorigin_glob such as "mail/postfix" name = self.name - if name =~ /\// - name = self.name.split(/\//).slice(1) + if name =~ %r{/} + name = self.name.split(%r{/}).slice(1) end self.class.instances.each do |instance| if instance.name == name diff --git a/lib/puppet/provider/package/portupgrade.rb b/lib/puppet/provider/package/portupgrade.rb index c38a25e5af8..cb4cfeeafe7 100644 --- a/lib/puppet/provider/package/portupgrade.rb +++ b/lib/puppet/provider/package/portupgrade.rb @@ -35,7 +35,7 @@ def self.instances Puppet.debug "portupgrade.rb Building packages list from installed ports" # regex to match output from pkg_info - regex = %r{^(\S+)-([^-\s]+):(\S+)$} + regex = /^(\S+)-([^-\s]+):(\S+)$/ # Corresponding field names fields = [:portname, :ensure, :portorigin] # define Temporary hash used, packages array of hashes diff --git a/lib/puppet/provider/package/puppetserver_gem.rb b/lib/puppet/provider/package/puppetserver_gem.rb index 7c0572f3c64..9958dd33960 100644 --- a/lib/puppet/provider/package/puppetserver_gem.rb +++ b/lib/puppet/provider/package/puppetserver_gem.rb @@ -167,7 +167,7 @@ def self.execute_rubygems_list_command(command_options) # There is no method exclude default gems from the local gem list, # for example: psych (default: 2.2.2) # but default gems should not be managed by this (or any) provider. - gem_list = gem_out.lines.reject { |gem| gem =~ / \(default\: / } + gem_list = gem_out.lines.reject { |gem| gem =~ / \(default: / } gem_list.join("\n") end end diff --git a/lib/puppet/provider/package/rpm.rb b/lib/puppet/provider/package/rpm.rb index fd6dd459a65..33b1b8a8ea8 100644 --- a/lib/puppet/provider/package/rpm.rb +++ b/lib/puppet/provider/package/rpm.rb @@ -24,8 +24,8 @@ # Note: self:: is required here to keep these constants in the context of what will # eventually become this Puppet::Type::Package::ProviderRpm class. # The query format by which we identify installed packages - self::NEVRA_FORMAT = %q(%{NAME} %|EPOCH?{%{EPOCH}}:{0}| %{VERSION} %{RELEASE} %{ARCH}\\n) - self::NEVRA_REGEX = %r{^'?(\S+) (\S+) (\S+) (\S+) (\S+)$} + self::NEVRA_FORMAT = '%{NAME} %|EPOCH?{%{EPOCH}}:{0}| %{VERSION} %{RELEASE} %{ARCH}\\n' + self::NEVRA_REGEX = /^'?(\S+) (\S+) (\S+) (\S+) (\S+)$/ self::NEVRA_FIELDS = [:name, :epoch, :version, :release, :arch] self::MULTIVERSION_SEPARATOR = "; " diff --git a/lib/puppet/provider/package/rug.rb b/lib/puppet/provider/package/rug.rb index 80ed6ced128..ac666718f15 100644 --- a/lib/puppet/provider/package/rug.rb +++ b/lib/puppet/provider/package/rug.rb @@ -35,7 +35,7 @@ def latest # rug can only get a list of *all* available packages? output = rug "list-updates" - if output =~ /#{Regexp.escape @resource[:name]}\s*\|\s*([^\s\|]+)/ + if output =~ /#{Regexp.escape @resource[:name]}\s*\|\s*([^\s|]+)/ return Regexp.last_match(1) else # rug didn't find updates, pretend the current diff --git a/lib/puppet/provider/package/yum.rb b/lib/puppet/provider/package/yum.rb index 0a2d25b52a6..3d44e44c07c 100644 --- a/lib/puppet/provider/package/yum.rb +++ b/lib/puppet/provider/package/yum.rb @@ -217,7 +217,7 @@ def best_version(should) Puppet.debug("Cannot parse #{version} as a RPM version") end - version = versions.sort.last if versions.any? + version = versions.max if versions.any? if version version = version.to_s.sub(/^\d+:/, '') diff --git a/lib/puppet/provider/package/zypper.rb b/lib/puppet/provider/package/zypper.rb index 1f8d5f6558b..91f8ef91b8a 100644 --- a/lib/puppet/provider/package/zypper.rb +++ b/lib/puppet/provider/package/zypper.rb @@ -82,7 +82,7 @@ def best_version(should) end end - return versions.sort.last if versions.any? + return versions.max if versions.any? Puppet.debug("No available version for package #{@resource[:name]} is included in range #{should_range}") should diff --git a/lib/puppet/provider/package_targetable.rb b/lib/puppet/provider/package_targetable.rb index d0704ea7dac..452a3cdf7ac 100644 --- a/lib/puppet/provider/package_targetable.rb +++ b/lib/puppet/provider/package_targetable.rb @@ -34,7 +34,7 @@ def self.prefetch(packages) catalog_packages.each do |catalog_package| if catalog_package[:name] == instance.name && catalog_package.original_parameters[:command] == command catalog_package.provider = instance - self.debug "Prefetched instance: %{name} via command: %{cmd}" % { name: instance.name, cmd: (command || :default) } + self.debug "Prefetched instance: %{name} via command: %{cmd}" % { name: instance.name, cmd: command || :default } end end end diff --git a/lib/puppet/provider/service/freebsd.rb b/lib/puppet/provider/service/freebsd.rb index dee9465fbce..f0d1642e64a 100644 --- a/lib/puppet/provider/service/freebsd.rb +++ b/lib/puppet/provider/service/freebsd.rb @@ -75,7 +75,7 @@ def rc_replace(service, rcvar, yesno) next unless Puppet::FileSystem.exist?(filename) s = File.read(filename) - next unless s.gsub!(/^(#{rcvar}(_enable)?)=\"?(YES|NO)\"?/, "\\1=\"#{yesno}\"") + next unless s.gsub!(/^(#{rcvar}(_enable)?)="?(YES|NO)"?/, "\\1=\"#{yesno}\"") Puppet::FileSystem.replace_file(filename) { |f| f << s } self.debug("Replaced in #{filename}") diff --git a/lib/puppet/provider/service/systemd.rb b/lib/puppet/provider/service/systemd.rb index 7ca4e60f7a7..b1668845e23 100644 --- a/lib/puppet/provider/service/systemd.rb +++ b/lib/puppet/provider/service/systemd.rb @@ -117,7 +117,7 @@ def enabled? return :false if output == 'indirect' return :true if code == 0 - if (output.empty?) && (code > 0) && (Puppet.runtime[:facter].value('os.family').casecmp('debian').zero?) + if output.empty? && (code > 0) && Puppet.runtime[:facter].value('os.family').casecmp('debian').zero? ret = debian_enabled? return ret if ret end diff --git a/lib/puppet/provider/service/upstart.rb b/lib/puppet/provider/service/upstart.rb index 4cf6299ff06..6222dfe4b5f 100644 --- a/lib/puppet/provider/service/upstart.rb +++ b/lib/puppet/provider/service/upstart.rb @@ -77,11 +77,11 @@ def self.get_services(exclude = []) # network-interface (lo) start/running # network-interface (eth0) start/running # network-interface-security start/running - matcher = line.match(/^(network-interface)\s\(([^\)]+)\)/) + matcher = line.match(/^(network-interface)\s\(([^)]+)\)/) name = if matcher "#{matcher[1]} INTERFACE=#{matcher[2]}" else - matcher = line.match(/^(network-interface-security)\s\(([^\)]+)\)/) + matcher = line.match(/^(network-interface-security)\s\(([^)]+)\)/) if matcher "#{matcher[1]} JOB=#{matcher[2]}" else @@ -99,7 +99,7 @@ def self.defpath end def upstart_version - @upstart_version ||= initctl("--version").match(/initctl \(upstart ([^\)]*)\)/)[1] + @upstart_version ||= initctl("--version").match(/initctl \(upstart ([^)]*)\)/)[1] end # Where is our override script? @@ -185,7 +185,7 @@ def status end output = status_exec(@resource[:name].split) - if output =~ /start\// + if output =~ %r{start/} return :running else return :stopped @@ -195,7 +195,7 @@ def status private def is_upstart?(script = initscript) - Puppet::FileSystem.exist?(script) && script.match(/\/etc\/init\/\S+\.conf/) + Puppet::FileSystem.exist?(script) && script.match(%r{/etc/init/\S+\.conf}) end def version_is_pre_0_6_7 diff --git a/lib/puppet/provider/user/directoryservice.rb b/lib/puppet/provider/user/directoryservice.rb index fc1920738bf..76f2d9e3367 100644 --- a/lib/puppet/provider/user/directoryservice.rb +++ b/lib/puppet/provider/user/directoryservice.rb @@ -547,7 +547,7 @@ def write_password_to_users_plist(value) # variable IS a Hash and contains the 'SALTED-SHA512' key (indicating an # older 10.7-style password hash), it will be deleted and a newer # 10.8-style (PBKDF2) password hash will be generated. - if (shadow_hash_data.instance_of?(Hash)) && (shadow_hash_data.has_key?('SALTED-SHA512')) + if shadow_hash_data.instance_of?(Hash) && shadow_hash_data.has_key?('SALTED-SHA512') shadow_hash_data.delete('SALTED-SHA512') end diff --git a/lib/puppet/provider/user/user_role_add.rb b/lib/puppet/provider/user/user_role_add.rb index a478fc1e926..ecfdd97f23b 100644 --- a/lib/puppet/provider/user/user_role_add.rb +++ b/lib/puppet/provider/user/user_role_add.rb @@ -76,7 +76,7 @@ def flush end def command(cmd) - cmd = ("role_#{cmd}").intern if is_role? or (!exists? and @resource[:ensure] == :role) + cmd = "role_#{cmd}".intern if is_role? or (!exists? and @resource[:ensure] == :role) super(cmd) end diff --git a/lib/puppet/provider/user/useradd.rb b/lib/puppet/provider/user/useradd.rb index 05eb6dc3bb2..8cf8cfde222 100644 --- a/lib/puppet/provider/user/useradd.rb +++ b/lib/puppet/provider/user/useradd.rb @@ -235,11 +235,11 @@ def check_allow_dup # because by default duplicates are allowed. This check is # to ensure consistent behaviour of the useradd provider when # using both useradd and luseradd - if (!@resource.allowdupe?) && @resource.forcelocal? + if !@resource.allowdupe? && @resource.forcelocal? if @resource.should(:uid) && finduser(:uid, @resource.should(:uid).to_s) raise(Puppet::Error, "UID #{@resource.should(:uid)} already exists, use allowdupe to force user creation") end - elsif @resource.allowdupe? && (!@resource.forcelocal?) + elsif @resource.allowdupe? && !@resource.forcelocal? return ["-o"] end [] @@ -324,7 +324,7 @@ def addcmd else cmd = [command(:add)] end - if (!@resource.should(:gid)) && Puppet::Util.gid(@resource[:name]) + if !@resource.should(:gid) && Puppet::Util.gid(@resource[:name]) cmd += ["-g", @resource[:name]] end cmd += add_properties diff --git a/lib/puppet/settings.rb b/lib/puppet/settings.rb index e8d67e18f4f..b9ef2a95af1 100644 --- a/lib/puppet/settings.rb +++ b/lib/puppet/settings.rb @@ -517,7 +517,7 @@ def include?(name) def print_config_options if Puppet::Util::Log.sendlevel?(:info) Puppet::Util::Log.newdestination(:console) - message = (_("Using --configprint is deprecated. Use 'puppet config ' instead.")) + message = _("Using --configprint is deprecated. Use 'puppet config ' instead.") Puppet.deprecation_warning(message) end diff --git a/lib/puppet/settings/config_file.rb b/lib/puppet/settings/config_file.rb index 4ddf1852a64..68de98c58b8 100644 --- a/lib/puppet/settings/config_file.rb +++ b/lib/puppet/settings/config_file.rb @@ -125,7 +125,7 @@ def extract_fileinfo(string) value = string.sub(/\{\s*([^}]+)\s*\}/) do params = ::Regexp.last_match(1) params.split(/\s*,\s*/).each do |str| - if str =~ /^\s*(\w+)\s*=\s*([\w]+)\s*$/ + if str =~ /^\s*(\w+)\s*=\s*(\w+)\s*$/ param = ::Regexp.last_match(1).intern value = ::Regexp.last_match(2) result[param] = value diff --git a/lib/puppet/settings/environment_conf.rb b/lib/puppet/settings/environment_conf.rb index 67734c2de8d..49ee488941d 100644 --- a/lib/puppet/settings/environment_conf.rb +++ b/lib/puppet/settings/environment_conf.rb @@ -174,7 +174,7 @@ def get_setting(setting_name, default = nil) def expand_glob(path) return nil if path.nil? - if path =~ /[*?\[\{]/ + if path =~ /[*?\[{]/ Dir.glob(path) else path diff --git a/lib/puppet/settings/file_or_directory_setting.rb b/lib/puppet/settings/file_or_directory_setting.rb index 6dc071efa81..9c7edc971d6 100644 --- a/lib/puppet/settings/file_or_directory_setting.rb +++ b/lib/puppet/settings/file_or_directory_setting.rb @@ -12,7 +12,7 @@ def type # Overrides munge to be able to read the un-munged value (the FileSetting.munch removes trailing slash) # def munge(value) - if value.is_a?(String) && value =~ /[\\\/]$/ + if value.is_a?(String) && value =~ %r{[\\/]$} @path_ends_with_slash = true end super diff --git a/lib/puppet/settings/file_setting.rb b/lib/puppet/settings/file_setting.rb index 01b81415f11..37a9b992f4a 100644 --- a/lib/puppet/settings/file_setting.rb +++ b/lib/puppet/settings/file_setting.rb @@ -134,7 +134,7 @@ def to_resource path = File.expand_path(path) return nil unless type == :directory || Puppet::FileSystem.exist?(path) - return nil if path =~ /^\/dev/ || path =~ /^[A-Z]:\/dev/i + return nil if path =~ %r{^/dev} || path =~ %r{^[A-Z]:/dev}i resource = Puppet::Resource.new(:file, path) diff --git a/lib/puppet/transaction.rb b/lib/puppet/transaction.rb index 8dead10af2f..57b5484b6b4 100644 --- a/lib/puppet/transaction.rb +++ b/lib/puppet/transaction.rb @@ -312,7 +312,7 @@ def failed_dependencies?(resource) @failed_class_dependencies_already_notified.merge(class_dependencies_to_be_notified) else unless @merge_dependency_warnings || is_puppet_class - s.failed_dependencies.find_all { |d| !(@failed_dependencies_already_notified.include?(d.ref)) }.each do |dep| + s.failed_dependencies.find_all { |d| !@failed_dependencies_already_notified.include?(d.ref) }.each do |dep| resource.notice _("Dependency %{dep} has failures: %{status}") % { dep: dep, status: resource_status(dep).failed } @failed_dependencies_already_notified.add(dep.ref) end @@ -414,7 +414,7 @@ def skip?(resource) unless resource.instance_of?(Puppet::Type.type(:whit)) if @merge_dependency_warnings && resource.parent && failed_dependencies?(resource.parent) ps = resource_status(resource.parent) - ps.failed_dependencies.find_all { |d| !(@failed_class_dependencies_already_warned.include?(d.ref)) }.each do |dep| + ps.failed_dependencies.find_all { |d| !@failed_class_dependencies_already_warned.include?(d.ref) }.each do |dep| resource.parent.warning _("Skipping resources in class because of failed class dependencies") @failed_class_dependencies_already_warned.add(dep.ref) end diff --git a/lib/puppet/type.rb b/lib/puppet/type.rb index f90e125d9c9..2494ea12490 100644 --- a/lib/puppet/type.rb +++ b/lib/puppet/type.rb @@ -1375,7 +1375,7 @@ def properties_to_audit(list) end newmetaparam(:alias) do - desc %q{Creates an alias for the resource. Puppet uses this internally when you + desc "Creates an alias for the resource. Puppet uses this internally when you provide a symbolic title and an explicit namevar value: file { 'sshdconfig': @@ -1411,7 +1411,7 @@ def properties_to_audit(list) There's no way here for the Puppet parser to know that these two stanzas should be affecting the same file. - } + " munge do |aliases| aliases = [aliases] unless aliases.is_a?(Array) @@ -1772,7 +1772,7 @@ def self.providers def self.validprovider?(name) name = name.intern - (provider_hash.has_key?(name) && provider_hash[name].suitable?) + provider_hash.has_key?(name) && provider_hash[name].suitable? end # Creates a new provider of a type. diff --git a/lib/puppet/type/exec.rb b/lib/puppet/type/exec.rb index 08c5f3a9efb..639d7141437 100644 --- a/lib/puppet/type/exec.rb +++ b/lib/puppet/type/exec.rb @@ -353,7 +353,7 @@ def value=(*values) munge do |value| if value.is_a?(String) - unless value =~ /^[\d]+$/ + unless value =~ /^\d+$/ raise ArgumentError, _("Tries must be an integer") end diff --git a/lib/puppet/type/file.rb b/lib/puppet/type/file.rb index 8bb0705da42..ec642d4e09a 100644 --- a/lib/puppet/type/file.rb +++ b/lib/puppet/type/file.rb @@ -461,7 +461,7 @@ def self.title_patterns def self.[](path) return nil unless path - super(path.gsub(/\/+/, '/').sub(/\/$/, '')) + super(path.gsub(%r{/+}, '/').sub(%r{/$}, '')) end def self.instances diff --git a/lib/puppet/type/file/content.rb b/lib/puppet/type/file/content.rb index f2f7bc0af6d..6cf44e5ba10 100644 --- a/lib/puppet/type/file/content.rb +++ b/lib/puppet/type/file/content.rb @@ -5,7 +5,7 @@ require 'tempfile' require_relative '../../../puppet/util/checksums' -require_relative '../../../puppet/type/file/data_sync.rb' +require_relative '../../../puppet/type/file/data_sync' module Puppet Puppet::Type.type(:file).newproperty(:content) do diff --git a/lib/puppet/util.rb b/lib/puppet/util.rb index 51930993c97..e697aa6056a 100644 --- a/lib/puppet/util.rb +++ b/lib/puppet/util.rb @@ -248,7 +248,7 @@ def which(bin) # Escape once for the string literal, and once for the regex. slash = '[\\\\/]' label = '[^\\\\/]+' - AbsolutePathWindows = %r{^(?:(?:[A-Z]:#{slash})|(?:#{slash}#{slash}#{label}#{slash}#{label})|(?:#{slash}#{slash}\?#{slash}#{label}))}io + AbsolutePathWindows = /^(?:(?:[A-Z]:#{slash})|(?:#{slash}#{slash}#{label}#{slash}#{label})|(?:#{slash}#{slash}\?#{slash}#{label}))/io AbsolutePathPosix = %r{^/} def absolute_path?(path, platform = nil) unless path.is_a?(String) @@ -286,11 +286,11 @@ def path_to_uri(path) if Puppet::Util::Platform.windows? path = path.tr('\\', '/') - unc = /^\/\/([^\/]+)(\/.+)/.match(path) + unc = %r{^//([^/]+)(/.+)}.match(path) if unc params[:host] = unc[1] path = unc[2] - elsif path =~ /^[a-z]:\//i + elsif path =~ %r{^[a-z]:/}i path = '/' + path end end @@ -322,7 +322,7 @@ def uri_to_path(uri) if uri.host && !uri.host.empty? path = "//#{uri.host}" + path # UNC else - path.sub!(/^\//, '') + path.sub!(%r{^/}, '') end end @@ -330,7 +330,7 @@ def uri_to_path(uri) end module_function :uri_to_path - RFC_3986_URI_REGEX = /^(?(?:[^:\/?#]+):)?(?\/\/(?:[^\/?#]*))?(?[^?#]*)(?:\?(?[^#]*))?(?:#(?.*))?$/ + RFC_3986_URI_REGEX = %r{^(?(?:[^:/?#]+):)?(?//(?:[^/?#]*))?(?[^?#]*)(?:\?(?[^#]*))?(?:#(?.*))?$} # Percent-encodes a URI query parameter per RFC3986 - https://tools.ietf.org/html/rfc3986 # @@ -480,11 +480,21 @@ def safe_posix_fork(stdin = $stdin, stdout = $stdout, stderr = $stderr, &block) begin Dir.foreach('/proc/self/fd') do |f| if f != '.' && f != '..' && f.to_i >= 3 - IO.new(f.to_i).close rescue nil + begin + IO.new(f.to_i).close + rescue + nil + end end end rescue Errno::ENOENT, Errno::ENOTDIR # /proc/self/fd not found, /proc/self not a dir - 3.upto(256) { |fd| IO.new(fd).close rescue nil } + 3.upto(256) { |fd| + begin + IO.new(fd).close + rescue + nil + end + } end block.call if block @@ -540,7 +550,11 @@ def self.format_backtrace_array(primary_stack, puppetstack = []) def self.resolve_stackframe(frame) _, path, rest = /^(.*):(\d+.*)$/.match(frame).to_a if path - path = Pathname(path).realpath rescue path + path = begin + Pathname(path).realpath + rescue + path + end "#{path}:#{rest}" else frame diff --git a/lib/puppet/util/at_fork/solaris.rb b/lib/puppet/util/at_fork/solaris.rb index a36445174d7..e7ee9507c95 100644 --- a/lib/puppet/util/at_fork/solaris.rb +++ b/lib/puppet/util/at_fork/solaris.rb @@ -47,8 +47,8 @@ class Puppet::Util::AtFork::Solaris end CTFS_PR_ROOT = File.join('', %w[system contract process]) - CTFS_PR_TEMPLATE = File.join(CTFS_PR_ROOT, %q(template)) - CTFS_PR_LATEST = File.join(CTFS_PR_ROOT, %q(latest)) + CTFS_PR_TEMPLATE = File.join(CTFS_PR_ROOT, 'template') + CTFS_PR_LATEST = File.join(CTFS_PR_ROOT, 'latest') CT_PR_PGRPONLY = 0x4 CT_PR_EV_HWERR = 0x20 @@ -129,7 +129,7 @@ def abandon_latest_child_contract return if ctid.nil? begin - ctl = File.new(File.join(CTFS_PR_ROOT, ctid.to_s, %q(ctl)), File::WRONLY) + ctl = File.new(File.join(CTFS_PR_ROOT, ctid.to_s, 'ctl'), File::WRONLY) begin raise_if_error { ct_ctl_abandon(ctl.fileno) } diff --git a/lib/puppet/util/backups.rb b/lib/puppet/util/backups.rb index 61d8f84a4d9..c3322e785ea 100644 --- a/lib/puppet/util/backups.rb +++ b/lib/puppet/util/backups.rb @@ -19,7 +19,7 @@ def perform_backup(file = nil) private def perform_backup_with_bucket(fileobj) - file = (fileobj.instance_of?(String)) ? fileobj : fileobj.name + file = fileobj.instance_of?(String) ? fileobj : fileobj.name case Puppet::FileSystem.lstat(file).ftype when "directory" # we don't need to backup directories when recurse is on @@ -34,7 +34,7 @@ def perform_backup_with_bucket(fileobj) end def perform_backup_with_backuplocal(fileobj, backup) - file = (fileobj.instance_of?(String)) ? fileobj : fileobj.name + file = fileobj.instance_of?(String) ? fileobj : fileobj.name newfile = file + backup remove_backup(newfile) diff --git a/lib/puppet/util/colors.rb b/lib/puppet/util/colors.rb index 617881614cc..df63901a3a0 100644 --- a/lib/puppet/util/colors.rb +++ b/lib/puppet/util/colors.rb @@ -97,6 +97,6 @@ def console_color(color, str) def html_color(color, str) span = '' % Colormap[color][:html] - "#{span}%s" % str.gsub(//, "\\0#{span}") + "#{span}%s" % str.gsub(%r{}, "\\0#{span}") end end diff --git a/lib/puppet/util/command_line/trollop.rb b/lib/puppet/util/command_line/trollop.rb index 54cf42fe8f8..9c13e9c0fa6 100644 --- a/lib/puppet/util/command_line/trollop.rb +++ b/lib/puppet/util/command_line/trollop.rb @@ -33,10 +33,10 @@ class HelpNeeded < StandardError; end class VersionNeeded < StandardError; end ## Regex for floating point numbers - FLOAT_RE = /^-?((\d+(\.\d+)?)|(\.\d+))([eE][-+]?[\d]+)?$/ + FLOAT_RE = /^-?((\d+(\.\d+)?)|(\.\d+))([eE][-+]?\d+)?$/ ## Regex for parameters - PARAM_RE = /^-(-|\.$|[^\d\.])/ + PARAM_RE = /^-(-|\.$|[^\d.])/ ## The commandline parser. In typical usage, the methods in this class ## will be handled internally by Trollop::options. In this case, only the diff --git a/lib/puppet/util/execution.rb b/lib/puppet/util/execution.rb index a5440c6272b..e0b116f658b 100644 --- a/lib/puppet/util/execution.rb +++ b/lib/puppet/util/execution.rb @@ -212,13 +212,25 @@ def self.execute(command, options = NoOptionsSpecified) execution_stub = Puppet::Util::ExecutionStub.current_value if execution_stub child_pid = execution_stub.call(*exec_args) - [stdin, stdout, stderr].each { |io| io.close rescue nil } + [stdin, stdout, stderr].each { |io| + begin + io.close + rescue + nil + end + } return child_pid elsif Puppet.features.posix? child_pid = nil begin child_pid = execute_posix(*exec_args) - [stdin, stdout, stderr].each { |io| io.close rescue nil } + [stdin, stdout, stderr].each { |io| + begin + io.close + rescue + nil + end + } if options[:squelch] exit_status = Process.waitpid2(child_pid).last.exitstatus else @@ -276,7 +288,13 @@ def self.execute(command, options = NoOptionsSpecified) elsif Puppet::Util::Platform.windows? process_info = execute_windows(*exec_args) begin - [stdin, stderr].each { |io| io.close rescue nil } + [stdin, stderr].each { |io| + begin + io.close + rescue + nil + end + } exit_status = Puppet::Util::Windows::Process.wait_process(process_info.process_handle) # read output in if required @@ -295,7 +313,13 @@ def self.execute(command, options = NoOptionsSpecified) end ensure # Make sure all handles are closed in case an exception was thrown attempting to execute. - [stdin, stdout, stderr].each { |io| io.close rescue nil } + [stdin, stdout, stderr].each { |io| + begin + io.close + rescue + nil + end + } unless options[:squelch] # if we opened a pipe, we need to clean it up. reader.close if reader diff --git a/lib/puppet/util/inifile.rb b/lib/puppet/util/inifile.rb index f4eb7c84251..f6e4750c68b 100644 --- a/lib/puppet/util/inifile.rb +++ b/lib/puppet/util/inifile.rb @@ -150,7 +150,7 @@ def read ) INI_CONTINUATION = /^[ \t\r\n\f]/ INI_SECTION_NAME = /^\[([^\]]+)\]/ - INI_PROPERTY = /^\s*([^\s=]+)\s*\=\s*(.*)$/ + INI_PROPERTY = /^\s*([^\s=]+)\s*=\s*(.*)$/ # @api private def parse(text) diff --git a/lib/puppet/util/log.rb b/lib/puppet/util/log.rb index 3e7aeac1715..5a0d3f64f01 100644 --- a/lib/puppet/util/log.rb +++ b/lib/puppet/util/log.rb @@ -224,7 +224,7 @@ def Log.flushqueue # error scenario. # @return nil def Log.force_flushqueue - if @destinations.empty? and !(@queued.empty?) + if @destinations.empty? and !@queued.empty? newdestination(:console) end flushqueue diff --git a/lib/puppet/util/logging.rb b/lib/puppet/util/logging.rb index 3958be1ce86..8febaf6f8b2 100644 --- a/lib/puppet/util/logging.rb +++ b/lib/puppet/util/logging.rb @@ -160,7 +160,7 @@ def puppet_deprecation_warning(message, options = {}) file = options[:file] line = options[:line] # TRANSLATORS the literals ":file", ":line", and ":key" should not be translated - raise Puppet::DevError, _("Need either :file and :line, or :key") if (key.nil?) && (file.nil? || line.nil?) + raise Puppet::DevError, _("Need either :file and :line, or :key") if key.nil? && (file.nil? || line.nil?) key ||= "#{file}:#{line}" issue_deprecation_warning(message, key, file, line, false) @@ -243,7 +243,7 @@ def log_deprecations_to_file(deprecations_file, pattern = nil) next if $logged_deprecation_warnings.has_key?(offender) $logged_deprecation_warnings[offender] = true - next unless (pattern.nil?) || (message =~ pattern) + next unless pattern.nil? || (message =~ pattern) f.puts(message) f.puts(offender) diff --git a/lib/puppet/util/package.rb b/lib/puppet/util/package.rb index a2d38807dea..072b8333164 100644 --- a/lib/puppet/util/package.rb +++ b/lib/puppet/util/package.rb @@ -35,7 +35,7 @@ def versioncmp(version_a, version_b, ignore_trailing_zeroes = false) def self.normalize(version) version = version.split('-') - version.first.sub!(/([\.0]+)$/, '') + version.first.sub!(/([.0]+)$/, '') version.join('-') end diff --git a/lib/puppet/util/package/version/debian.rb b/lib/puppet/util/package/version/debian.rb index 41ee080b4ae..4fd7c439dee 100644 --- a/lib/puppet/util/package/version/debian.rb +++ b/lib/puppet/util/package/version/debian.rb @@ -163,7 +163,7 @@ def match_digits(a) end def match_non_letters(a) - a.match(/^([\.\+-]+)/) + a.match(/^([.+-]+)/) end def match_tildes(a) diff --git a/lib/puppet/util/package/version/pip.rb b/lib/puppet/util/package/version/pip.rb index 19f54a19bd4..f8cbb2d8fc1 100644 --- a/lib/puppet/util/package/version/pip.rb +++ b/lib/puppet/util/package/version/pip.rb @@ -38,7 +38,7 @@ class Pip def self.parse(version) raise ValidationFailure, version.to_s unless version.is_a? String - matched = version.match(Regexp.new(("^\\s*") + VERSION_PATTERN + ("\\s*$"), Regexp::EXTENDED | Regexp::MULTILINE | Regexp::IGNORECASE)) + matched = version.match(Regexp.new("^\\s*" + VERSION_PATTERN + "\\s*$", Regexp::EXTENDED | Regexp::MULTILINE | Regexp::IGNORECASE)) raise ValidationFailure, version unless matched new(matched) diff --git a/lib/puppet/util/plist.rb b/lib/puppet/util/plist.rb index 2dc06a6ef8f..a9f3b9ddb9d 100644 --- a/lib/puppet/util/plist.rb +++ b/lib/puppet/util/plist.rb @@ -56,7 +56,7 @@ def read_plist_file(file_path) # Read plist text using the CFPropertyList gem. def parse_plist(plist_data, file_path = '') - bad_xml_doctype = /^.* { Ref => { name => 'cars', version_range => '1.x' } } OBJECT expect { parse_type_set('MySet', ts) }.to raise_error(TypeAssertionError, - /entry 'references' entry 'Ref' entry 'name' expects a match for Pattern\[\/\\A\[A-Z\]\[\\w\]\*\(\?:::\[A-Z\]\[\\w\]\*\)\*\\z\/\], got 'cars'/) + /entry 'references' entry 'Ref' entry 'name' expects a match for Pattern\[\/\\A\[A-Z\]\\w\*\(\?:::\[A-Z\]\\w\*\)\*\\z\/\], got 'cars'/) end it 'has a version_range that is not a valid SemVer range' do