diff --git a/.rubocop.yml b/.rubocop.yml index aaffd75a30c..ab9fb23dda4 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -51,6 +51,12 @@ Style/RedundantSelfAssignment: Exclude: - 'lib/puppet/context.rb' +# Enabling this cop causes failures in rb_tree_map_spec relating to important +# function slike being unable to delete nodes and returning nil when the key +# cannot be found +Style/PreferredHashMethods: + Enabled: false + # Explicitly enables this cop new in 1.7 Layout/SpaceBeforeBrackets: Enabled: true diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index d6f6bd063ad..5f033075e75 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -646,12 +646,6 @@ Style/NumericPredicate: Style/OptionalBooleanParameter: Enabled: false -# This cop supports unsafe auto-correction (--auto-correct-all). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: short, verbose -Style/PreferredHashMethods: - Enabled: false - # This cop supports safe auto-correction (--auto-correct). # Configuration parameters: EnforcedStyle. # SupportedStyles: implicit, explicit @@ -664,19 +658,6 @@ Style/RescueStandardError: Style/SafeNavigation: Enabled: false -# This cop supports safe auto-correction (--auto-correct). -Style/SelfAssignment: - Exclude: - - 'lib/puppet/pops/evaluator/access_operator.rb' - - 'lib/puppet/pops/evaluator/collectors/fixed_set_collector.rb' - - 'lib/puppet/pops/evaluator/epp_evaluator.rb' - - 'lib/puppet/pops/parser/epp_parser.rb' - - 'lib/puppet/pops/parser/parser_support.rb' - - 'lib/puppet/pops/time/timestamp.rb' - - 'lib/puppet/pops/types/recursion_guard.rb' - - 'lib/puppet/property/ordered_list.rb' - - 'lib/puppet/util/autoload.rb' - # This cop supports safe auto-correction (--auto-correct). # Configuration parameters: AllowAsExpressionSeparator. Style/Semicolon: @@ -712,12 +693,6 @@ Style/SingleLineMethods: Style/SoleNestedConditional: Enabled: false -# This cop supports safe auto-correction (--auto-correct). -# Configuration parameters: RequireEnglish, EnforcedStyle. -# SupportedStyles: use_perl_names, use_english_names, use_builtin_english_names -Style/SpecialGlobalVars: - Enabled: false - # This cop supports safe auto-correction (--auto-correct). Style/StderrPuts: Exclude: @@ -747,77 +722,18 @@ Style/StringConcatenation: Style/StringLiterals: Enabled: false -# This cop supports safe auto-correction (--auto-correct). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: single_quotes, double_quotes -Style/StringLiteralsInInterpolation: - Enabled: false - -# This cop supports safe auto-correction (--auto-correct). -Style/StructInheritance: - Exclude: - - 'lib/puppet/settings.rb' - # This cop supports safe auto-correction (--auto-correct). # Configuration parameters: EnforcedStyle, MinSize. # SupportedStyles: percent, brackets Style/SymbolArray: Enabled: false -# This cop supports safe auto-correction (--auto-correct). -Style/SymbolLiteral: - Exclude: - - 'lib/puppet/functions/defined.rb' - -# This cop supports unsafe auto-correction (--auto-correct-all). -# Configuration parameters: AllowMethodsWithArguments, IgnoredMethods, AllowComments. -# IgnoredMethods: respond_to, define_method -Style/SymbolProc: - Enabled: false - # This cop supports safe auto-correction (--auto-correct). # Configuration parameters: EnforcedStyle, AllowSafeAssignment. # SupportedStyles: require_parentheses, require_no_parentheses, require_parentheses_when_complex Style/TernaryParentheses: Enabled: false -# This cop supports safe auto-correction (--auto-correct). -# Configuration parameters: EnforcedStyleForMultiline. -# SupportedStylesForMultiline: comma, consistent_comma, no_comma -Style/TrailingCommaInArguments: - Exclude: - - 'lib/puppet/defaults.rb' - - 'lib/puppet/ffi/windows/functions.rb' - - 'lib/puppet/ffi/windows/structs.rb' - - 'lib/puppet/http/service/compiler.rb' - - 'lib/puppet/http/service/report.rb' - - 'lib/puppet/indirector/file_bucket_file/rest.rb' - - 'lib/puppet/indirector/file_content/rest.rb' - - 'lib/puppet/indirector/file_metadata/rest.rb' - - 'lib/puppet/pops/types/p_uri_type.rb' - - 'lib/puppet/util/windows/adsi.rb' - - 'lib/puppet/util/windows/service.rb' - -# This cop supports safe auto-correction (--auto-correct). -# Configuration parameters: EnforcedStyleForMultiline. -# SupportedStylesForMultiline: comma, consistent_comma, no_comma -Style/TrailingCommaInArrayLiteral: - Exclude: - - 'ext/windows/service/daemon.rb' - - 'lib/puppet/functions.rb' - - 'lib/puppet/parser/compiler.rb' - - 'lib/puppet/pops/types/p_uri_type.rb' - - 'lib/puppet/pops/types/string_converter.rb' - - 'lib/puppet/pops/types/types.rb' - - 'lib/puppet/provider/package/windows/exe_package.rb' - - 'lib/puppet/provider/service/upstart.rb' - - 'lib/puppet/settings.rb' - - 'lib/puppet/ssl/certificate_request.rb' - - 'lib/puppet/ssl/oids.rb' - - 'lib/puppet/transaction/persistence.rb' - - 'lib/puppet/util/at_fork/solaris.rb' - - 'lib/puppet/util/windows/registry.rb' - # This cop supports safe auto-correction (--auto-correct). # Configuration parameters: EnforcedStyleForMultiline. # SupportedStylesForMultiline: comma, consistent_comma, no_comma @@ -846,39 +762,10 @@ Style/TrailingUnderscoreVariable: Style/TrivialAccessors: Enabled: false -# This cop supports safe auto-correction (--auto-correct). -Style/UnlessElse: - Exclude: - - 'lib/puppet/application/lookup.rb' - - 'lib/puppet/pops/evaluator/evaluator_impl.rb' - - 'lib/puppet/pops/types/type_mismatch_describer.rb' - - 'lib/puppet/provider/package/aix.rb' - - 'lib/puppet/provider/package/yum.rb' - - 'lib/puppet/ssl/openssl_loader.rb' - - 'lib/puppet/type/exec.rb' - - 'lib/puppet/util/command_line/trollop.rb' - -# This cop supports safe auto-correction (--auto-correct). -Style/UnpackFirst: - Exclude: - - 'lib/puppet/file_serving/http_metadata.rb' - - 'lib/puppet/provider/nameservice/directoryservice.rb' - - 'lib/puppet/provider/user/directoryservice.rb' - -# This cop supports safe auto-correction (--auto-correct). -Style/VariableInterpolation: - Exclude: - - 'lib/puppet/util/command_line/trollop.rb' - - 'lib/puppet/util/rdoc/generators/puppet_generator.rb' - # This cop supports safe auto-correction (--auto-correct). Style/WhenThen: Enabled: false -# This cop supports safe auto-correction (--auto-correct). -Style/WhileUntilDo: - Enabled: false - # This cop supports safe auto-correction (--auto-correct). Style/WhileUntilModifier: Exclude: @@ -889,12 +776,6 @@ Style/WhileUntilModifier: - 'lib/puppet/pops/types/p_object_type.rb' - 'lib/puppet/util/windows/process.rb' -# This cop supports safe auto-correction (--auto-correct). -# Configuration parameters: EnforcedStyle, MinSize, WordRegex. -# SupportedStyles: percent, brackets -Style/WordArray: - Enabled: false - # This cop supports unsafe auto-correction (--auto-correct-all). # Configuration parameters: EnforcedStyle. # SupportedStyles: forbid_for_all_comparison_operators, forbid_for_equality_operators_only, require_for_all_comparison_operators, require_for_equality_operators_only diff --git a/ext/windows/service/daemon.rb b/ext/windows/service/daemon.rb index 1bb2be1bb78..d8cf6e34620 100755 --- a/ext/windows/service/daemon.rb +++ b/ext/windows/service/daemon.rb @@ -75,7 +75,7 @@ def service_main(*argsv) service = self @run_thread = Thread.new do - while service.running? do + while service.running? runinterval = service.parse_runinterval(ruby_puppet_cmd) if service.state == RUNNING or service.state == IDLE @@ -197,7 +197,7 @@ def load_env(base_dir) ENV['SSL_CERT_FILE'] = File.join(base_dir, 'puppet', 'ssl', 'cert.pem').tr('/', '\\') ENV['Path'] = [ File.join(base_dir, 'puppet', 'bin'), - File.join(base_dir, 'bin'), + File.join(base_dir, 'bin') ].join(';').tr('/', '\\') + ';' + ENV.fetch('Path', nil) # ENV that uses forward slashes @@ -207,6 +207,6 @@ def load_env(base_dir) end end -if __FILE__ == $0 +if __FILE__ == $PROGRAM_NAME WindowsDaemon.mainloop end diff --git a/lib/puppet/application/face_base.rb b/lib/puppet/application/face_base.rb index b3a7363db52..b245be9c640 100644 --- a/lib/puppet/application/face_base.rb +++ b/lib/puppet/application/face_base.rb @@ -74,7 +74,7 @@ def parse_options # non-option word to use as the action. action_name = nil index = -1 - until action_name or (index += 1) >= command_line.args.length do + until action_name or (index += 1) >= command_line.args.length item = command_line.args[index] if item =~ /^-/ option = @face.options.find do |name| diff --git a/lib/puppet/application/lookup.rb b/lib/puppet/application/lookup.rb index d0df5ade289..384c99f2c5b 100644 --- a/lib/puppet/application/lookup.rb +++ b/lib/puppet/application/lookup.rb @@ -8,7 +8,7 @@ class Puppet::Application::Lookup < Puppet::Application RUN_HELP = _("Run 'puppet lookup --help' for more details").freeze DEEP_MERGE_OPTIONS = '--knock-out-prefix, --sort-merged-arrays, and --merge-hash-arrays' - TRUSTED_INFORMATION_FACTS = ["hostname", "domain", "fqdn", "clientcert"].freeze + TRUSTED_INFORMATION_FACTS = %w[hostname domain fqdn clientcert].freeze run_mode :server @@ -369,7 +369,9 @@ def generate_scope end end - unless node.is_a?(Puppet::Node) # to allow unit tests to pass a node instance + if node.is_a?(Puppet::Node) + node.add_extra_facts(given_facts) if given_facts + else # to allow unit tests to pass a node instance facts = retrieve_node_facts(node, given_facts) ni = Puppet::Node.indirection tc = ni.terminus_class @@ -399,8 +401,6 @@ def generate_scope node = ni.find(node, facts: facts, environment: Puppet[:environment]) ni.terminus_class = tc end - else - node.add_extra_facts(given_facts) if given_facts end node.environment = Puppet[:environment] if Puppet.settings.set_by_cli?(:environment) Puppet[:code] = 'undef' unless options[:compile] diff --git a/lib/puppet/coercion.rb b/lib/puppet/coercion.rb index 2b7d9a4f23b..02c7899c51d 100644 --- a/lib/puppet/coercion.rb +++ b/lib/puppet/coercion.rb @@ -37,6 +37,6 @@ def self.boolean(value) # @raise # @api private def self.boolean_values - ['true', 'false', 'yes', 'no'] + %w[true false yes no] end end diff --git a/lib/puppet/confine/feature.rb b/lib/puppet/confine/feature.rb index 66d28fb72bd..669eacdbaa3 100644 --- a/lib/puppet/confine/feature.rb +++ b/lib/puppet/confine/feature.rb @@ -4,7 +4,7 @@ class Puppet::Confine::Feature < Puppet::Confine def self.summarize(confines) - confines.collect { |c| c.values }.flatten.uniq.find_all { |value| !confines[0].pass?(value) } + confines.collect(&:values).flatten.uniq.find_all { |value| !confines[0].pass?(value) } end # Is the named feature available? diff --git a/lib/puppet/confine/variable.rb b/lib/puppet/confine/variable.rb index 3a194f1c424..4b5d1f71b67 100644 --- a/lib/puppet/confine/variable.rb +++ b/lib/puppet/confine/variable.rb @@ -29,7 +29,7 @@ def initialize(values) end def message(value) - "facter value '#{test_value}' for '#{name}' not in required list '#{values.join(",")}'" + "facter value '#{test_value}' for '#{name}' not in required list '#{values.join(',')}'" end # Compare the passed-in value to the retrieved value. diff --git a/lib/puppet/daemon.rb b/lib/puppet/daemon.rb index 5ea3d46c8c3..ce7fddbef1a 100644 --- a/lib/puppet/daemon.rb +++ b/lib/puppet/daemon.rb @@ -83,7 +83,7 @@ def close_streams def reexec raise Puppet::DevError, _("Cannot reexec unless ARGV arguments are set") unless argv - command = $0 + " " + argv.join(" ") + command = $PROGRAM_NAME + " " + argv.join(" ") Puppet.notice "Restarting with '#{command}'" stop(:exit => false) exec(command) diff --git a/lib/puppet/defaults.rb b/lib/puppet/defaults.rb index 5cc805a5089..f6542f1bb06 100644 --- a/lib/puppet/defaults.rb +++ b/lib/puppet/defaults.rb @@ -132,7 +132,7 @@ def self.initialize_default_settings!(settings) :log_level => { :default => 'notice', :type => :enum, - :values => ["debug","info","notice","warning","err","alert","emerg","crit"], + :values => %w[debug info notice warning err alert emerg crit], :desc => "Default logging level for messages from Puppet. Allowed values are: * debug @@ -1298,7 +1298,7 @@ def self.initialize_default_settings!(settings) :sourceaddress => { :default => nil, :desc => "The address the agent should use to initiate requests.", - }, + } ) settings.define_settings(:environment, diff --git a/lib/puppet/environments.rb b/lib/puppet/environments.rb index 29536d529e0..e0a158c7c99 100644 --- a/lib/puppet/environments.rb +++ b/lib/puppet/environments.rb @@ -313,7 +313,7 @@ def get_conf(name) end def clear_all - @loaders.each { |loader| loader.clear_all } + @loaders.each(&:clear_all) end end diff --git a/lib/puppet/external/dot.rb b/lib/puppet/external/dot.rb index c8177a4424d..b1372b1c601 100644 --- a/lib/puppet/external/dot.rb +++ b/lib/puppet/external/dot.rb @@ -100,17 +100,17 @@ def change_tab(t) # options for graph declaration - GRAPH_OPTS = [ - 'bgcolor', - 'center', 'clusterrank', 'color', 'concentrate', - 'fontcolor', 'fontname', 'fontsize', - 'label', 'layerseq', - 'margin', 'mclimit', - 'nodesep', 'nslimit', - 'ordering', 'orientation', - 'page', - 'rank', 'rankdir', 'ranksep', 'ratio', - 'size' + GRAPH_OPTS = %w[ + bgcolor + center clusterrank color concentrate + fontcolor fontname fontsize + label layerseq + margin mclimit + nodesep nslimit + ordering orientation + page + rank rankdir ranksep ratio + size ] # a root class for any element in dot notation diff --git a/lib/puppet/face/catalog/select.rb b/lib/puppet/face/catalog/select.rb index 15463801b0c..1d33fb97284 100644 --- a/lib/puppet/face/catalog/select.rb +++ b/lib/puppet/face/catalog/select.rb @@ -44,7 +44,7 @@ if value.nil? then _("no matching resources found") else - value.map { |x| x.to_s }.join("\n") + value.map(&:to_s).join("\n") end end end diff --git a/lib/puppet/face/help.rb b/lib/puppet/face/help.rb index cfd71c902fc..0e49758ac35 100644 --- a/lib/puppet/face/help.rb +++ b/lib/puppet/face/help.rb @@ -207,7 +207,7 @@ def horribly_extract_summary_from(appname) # depends on the implementation coincidence of how our pages are # 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 + while line = help.shift # rubocop:disable Lint/AssignmentInCondition md = /^puppet-#{appname}\([^)]+\) -- (.*)$/.match(line) if md return md[1] diff --git a/lib/puppet/face/module/changes.rb b/lib/puppet/face/module/changes.rb index 66256a29a8d..35051073c09 100644 --- a/lib/puppet/face/module/changes.rb +++ b/lib/puppet/face/module/changes.rb @@ -38,9 +38,7 @@ else Puppet.warning _("%{count} files modified") % { count: return_value.size } end - return_value.map do |changed_file| - changed_file.to_s - end.join("\n") + return_value.map(&:to_s).join("\n") end end end diff --git a/lib/puppet/face/module/list.rb b/lib/puppet/face/module/list.rb index f6fb03b0fb0..fc8562a0e19 100644 --- a/lib/puppet/face/module/list.rb +++ b/lib/puppet/face/module/list.rb @@ -117,7 +117,7 @@ def unmet_dependencies(environment) end # Prepare the unmet dependencies for display on the console. - environment.modules.sort_by { |mod| mod.name }.each do |mod| + environment.modules.sort_by(&:name).each do |mod| unmet_grouped = Hash.new { |h, k| h[k] = [] } unmet_grouped = mod.unmet_dependencies.each_with_object(unmet_grouped) do |dep, acc| acc[dep[:reason]] << dep diff --git a/lib/puppet/ffi/windows/functions.rb b/lib/puppet/ffi/windows/functions.rb index 41e9c98f5ab..235cbaa5a29 100644 --- a/lib/puppet/ffi/windows/functions.rb +++ b/lib/puppet/ffi/windows/functions.rb @@ -287,7 +287,7 @@ module Functions # LPDWORD pcbBytesNeeded # ); SC_STATUS_TYPE = enum( - :SC_STATUS_PROCESS_INFO, 0, + :SC_STATUS_PROCESS_INFO, 0 ) ffi_lib :advapi32 attach_function_private :QueryServiceStatusEx, @@ -425,7 +425,7 @@ module Functions # LPCWSTR pszGroupName # ); SC_ENUM_TYPE = enum( - :SC_ENUM_PROCESS_INFO, 0, + :SC_ENUM_PROCESS_INFO, 0 ) ffi_lib :advapi32 attach_function_private :EnumServicesStatusExW, diff --git a/lib/puppet/ffi/windows/structs.rb b/lib/puppet/ffi/windows/structs.rb index 542ba19ec1c..824e5c6dc1b 100644 --- a/lib/puppet/ffi/windows/structs.rb +++ b/lib/puppet/ffi/windows/structs.rb @@ -198,7 +198,7 @@ class SERVICE_STATUS < FFI::Struct :dwWin32ExitCode, :dword, :dwServiceSpecificExitCode, :dword, :dwCheckPoint, :dword, - :dwWaitHint, :dword, + :dwWaitHint, :dword ) end @@ -223,7 +223,7 @@ class QUERY_SERVICE_CONFIGW < FFI::Struct :dwTagId, :dword, :lpDependencies, :pointer, :lpServiceStartName, :pointer, - :lpDisplayName, :pointer, + :lpDisplayName, :pointer ) end diff --git a/lib/puppet/file_serving/fileset.rb b/lib/puppet/file_serving/fileset.rb index da4981dfc0c..df106165189 100644 --- a/lib/puppet/file_serving/fileset.rb +++ b/lib/puppet/file_serving/fileset.rb @@ -104,8 +104,8 @@ def initialize_from_hash(options) method = option.to_s + "=" begin send(method, value) - rescue NoMethodError - raise ArgumentError, _("Invalid option '%{option}'") % { option: option }, $!.backtrace + rescue NoMethodError => e + raise ArgumentError, _("Invalid option '%{option}'") % { option: option }, e.backtrace end end end diff --git a/lib/puppet/file_serving/http_metadata.rb b/lib/puppet/file_serving/http_metadata.rb index 86da3fc8c26..0d9a00a14e5 100644 --- a/lib/puppet/file_serving/http_metadata.rb +++ b/lib/puppet/file_serving/http_metadata.rb @@ -20,7 +20,7 @@ def initialize(http_response, path = '/dev/null') checksum = http_response['content-md5'] if checksum # convert base64 digest to hex - checksum = checksum.unpack("m").first.unpack("H*").first + checksum = checksum.unpack1("m").unpack1("H*") @checksums[:md5] = "{md5}#{checksum}" end diff --git a/lib/puppet/file_serving/mount/locales.rb b/lib/puppet/file_serving/mount/locales.rb index 70243552bf0..c938614de2e 100644 --- a/lib/puppet/file_serving/mount/locales.rb +++ b/lib/puppet/file_serving/mount/locales.rb @@ -17,7 +17,7 @@ def find(relative_path, request) def search(relative_path, request) # We currently only support one kind of search on locales - return # them all. - paths = request.environment.modules.find_all { |mod| mod.locales? }.collect { |mod| mod.locale_directory } + paths = request.environment.modules.find_all(&:locales?).collect(&:locale_directory) if paths.empty? # If the modulepath is valid then we still need to return a valid root # directory for the search, but make sure nothing inside it is diff --git a/lib/puppet/file_serving/mount/pluginfacts.rb b/lib/puppet/file_serving/mount/pluginfacts.rb index 425a4fa7cae..fbf0461c755 100644 --- a/lib/puppet/file_serving/mount/pluginfacts.rb +++ b/lib/puppet/file_serving/mount/pluginfacts.rb @@ -17,7 +17,7 @@ def find(relative_path, request) def search(relative_path, request) # We currently only support one kind of search on plugins - return # them all. - paths = request.environment.modules.find_all { |mod| mod.pluginfacts? }.collect { |mod| mod.plugin_fact_directory } + paths = request.environment.modules.find_all(&:pluginfacts?).collect(&:plugin_fact_directory) if paths.empty? # If the modulepath is valid then we still need to return a valid root # directory for the search, but make sure nothing inside it is diff --git a/lib/puppet/file_serving/mount/plugins.rb b/lib/puppet/file_serving/mount/plugins.rb index 606ab24108e..5fdbf82c32b 100644 --- a/lib/puppet/file_serving/mount/plugins.rb +++ b/lib/puppet/file_serving/mount/plugins.rb @@ -17,7 +17,7 @@ def find(relative_path, request) def search(relative_path, request) # We currently only support one kind of search on plugins - return # them all. - paths = request.environment.modules.find_all { |mod| mod.plugins? }.collect { |mod| mod.plugin_directory } + paths = request.environment.modules.find_all(&:plugins?).collect(&:plugin_directory) if paths.empty? # If the modulepath is valid then we still need to return a valid root # directory for the search, but make sure nothing inside it is diff --git a/lib/puppet/file_system/uniquefile.rb b/lib/puppet/file_system/uniquefile.rb index 4a192e7b40d..c54db61469c 100644 --- a/lib/puppet/file_system/uniquefile.rb +++ b/lib/puppet/file_system/uniquefile.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true +require 'English' require_relative '../../puppet/file_system' require 'delegate' require 'tmpdir' @@ -110,7 +111,7 @@ def make_tmpname(prefix_suffix, n) raise ArgumentError, _("unexpected prefix_suffix: %{value}") % { value: prefix_suffix.inspect } end t = Time.now.strftime("%Y%m%d") - path = "#{prefix}#{t}-#{$$}-#{rand(0x100000000).to_s(36)}" + path = "#{prefix}#{t}-#{$PROCESS_ID}-#{rand(0x100000000).to_s(36)}" path << "-#{n}" if n path << suffix end diff --git a/lib/puppet/forge.rb b/lib/puppet/forge.rb index 9fad982ae5e..53d999699ee 100644 --- a/lib/puppet/forge.rb +++ b/lib/puppet/forge.rb @@ -200,9 +200,7 @@ def tmpdir end def tmpfile - @file ||= Tempfile.new(name, Puppet::Forge::Cache.base_path).tap do |f| - f.binmode - end + @file ||= Tempfile.new(name, Puppet::Forge::Cache.base_path).tap(&:binmode) end # rubocop:enable Naming/MemoizedInstanceVariableName diff --git a/lib/puppet/forge/cache.rb b/lib/puppet/forge/cache.rb index 17d91422d41..f0bc619a122 100644 --- a/lib/puppet/forge/cache.rb +++ b/lib/puppet/forge/cache.rb @@ -43,7 +43,7 @@ def read_retrieve(uri) # Return Pathname for repository's cache directory, create it if needed. def path - (self.class.base_path + @repository.cache_key).tap { |o| o.mkpath } + (self.class.base_path + @repository.cache_key).tap(&:mkpath) end # Return the base Pathname for all the caches. diff --git a/lib/puppet/functions.rb b/lib/puppet/functions.rb index c033f058f67..74a0f3f46f7 100644 --- a/lib/puppet/functions.rb +++ b/lib/puppet/functions.rb @@ -685,10 +685,10 @@ class Function3x < InternalFunction PARAM_NAMES = [ [], ['p0'].freeze, - ['p0', 'p1'].freeze, - ['p0', 'p1', 'p2'].freeze, - ['p0', 'p1', 'p2', 'p3'].freeze, - ['p0', 'p1', 'p2', 'p3', 'p4'].freeze, + %w[p0 p1].freeze, + %w[p0 p1 p2].freeze, + %w[p0 p1 p2 p3].freeze, + %w[p0 p1 p2 p3 p4].freeze ] # Creates an anonymous Function3x class that wraps a 3x function diff --git a/lib/puppet/functions/camelcase.rb b/lib/puppet/functions/camelcase.rb index c87c437e915..d95b585553c 100644 --- a/lib/puppet/functions/camelcase.rb +++ b/lib/puppet/functions/camelcase.rb @@ -49,7 +49,7 @@ def on_numeric(n) end def on_string(s) - s.split('_').map { |x| x.capitalize }.join('') + s.split('_').map(&:capitalize).join('') end def on_iterable(a) diff --git a/lib/puppet/functions/defined.rb b/lib/puppet/functions/defined.rb index ef62e13966f..a06ed50b717 100644 --- a/lib/puppet/functions/defined.rb +++ b/lib/puppet/functions/defined.rb @@ -101,7 +101,7 @@ # @since 3.8.1 type specific requests with future parser # @since 4.0.0 # -Puppet::Functions.create_function(:'defined', Puppet::Functions::InternalFunction) do +Puppet::Functions.create_function(:defined, Puppet::Functions::InternalFunction) do dispatch :is_defined do scope_param required_repeated_param 'Variant[String, Type[CatalogEntry], Type[Type[CatalogEntry]]]', :vals diff --git a/lib/puppet/generate/type.rb b/lib/puppet/generate/type.rb index ea33b45c20b..6c06eba3e7b 100644 --- a/lib/puppet/generate/type.rb +++ b/lib/puppet/generate/type.rb @@ -135,7 +135,7 @@ def self.find_inputs(format = :pcore, environment = Puppet.lookup(:current_envir end # Sort the inputs by path - inputs.sort_by! { |input| input.path } + inputs.sort_by!(&:path) end def self.bad_input? @@ -155,7 +155,7 @@ def self.bad_input? def self.generate(inputs, outputdir = nil, force = false) # remove files for non existing inputs unless outputdir.nil? - filenames_to_keep = inputs.map { |i| i.output_name } + filenames_to_keep = inputs.map(&:output_name) existing_files = Puppet::FileSystem.children(outputdir).map { |f| Puppet::FileSystem.basename(f) } files_to_remove = existing_files - filenames_to_keep files_to_remove.each do |f| diff --git a/lib/puppet/graph/simple_graph.rb b/lib/puppet/graph/simple_graph.rb index 308ae18d6cd..0688e8365cd 100644 --- a/lib/puppet/graph/simple_graph.rb +++ b/lib/puppet/graph/simple_graph.rb @@ -106,7 +106,7 @@ def tarjan(root, s) # decent Ruby stack. recur = [{ :node => root }] - until recur.empty? do + until recur.empty? frame = recur.last vertex = frame[:node] @@ -186,9 +186,7 @@ def find_cycles_in_graph # time-scale. state[:scc].select do |component| multi_vertex_component?(component) || single_vertex_referring_to_self?(component) - end.map do |component| - component.sort - end.sort + end.map(&:sort).sort end # Perform a BFS on the sub graph representing the cycle, with a view to @@ -212,7 +210,7 @@ def paths_in_cycle(cycle, max_paths = 1) # frame struct is vertex, [path] stack = [[cycle.first, []]] - while frame = stack.shift do # rubocop:disable Lint/AssignmentInCondition + while frame = stack.shift # rubocop:disable Lint/AssignmentInCondition if frame[1].member?(frame[0]) then found << frame[1] + [frame[0]] break if found.length >= max_paths @@ -330,7 +328,7 @@ def edge?(source, target) end def edges - @in_to.values.collect { |x| x.values }.flatten + @in_to.values.collect(&:values).flatten end def each_edge diff --git a/lib/puppet/http/client.rb b/lib/puppet/http/client.rb index fcbe339dce8..f061f773486 100644 --- a/lib/puppet/http/client.rb +++ b/lib/puppet/http/client.rb @@ -365,7 +365,7 @@ def execute_streaming(request, options: {}, &block) response = nil done = false - until done do + until done connect(request.uri, options: options) do |http| apply_auth(request, basic_auth) if redirects.zero? diff --git a/lib/puppet/http/service/compiler.rb b/lib/puppet/http/service/compiler.rb index 688f7b2f9cd..3bf2d12dff3 100644 --- a/lib/puppet/http/service/compiler.rb +++ b/lib/puppet/http/service/compiler.rb @@ -118,7 +118,7 @@ def post_catalog(name, facts:, environment:, configured_environment: nil, check_ body, headers: headers, # for legacy reasons we always send environment as a query parameter too - params: { environment: environment }, + params: { environment: environment } ) if (compiler = response['X-Puppet-Compiler-Name']) @@ -248,7 +248,7 @@ def put_facts(name, environment:, facts:) with_base_url("/facts/#{name}"), serialize(formatter, facts), headers: headers, - params: { environment: environment }, + params: { environment: environment } ) process_response(response) diff --git a/lib/puppet/http/service/report.rb b/lib/puppet/http/service/report.rb index 3b86482080b..ce28b482002 100644 --- a/lib/puppet/http/service/report.rb +++ b/lib/puppet/http/service/report.rb @@ -47,7 +47,7 @@ def put_report(name, report, environment:) with_base_url("/report/#{name}"), serialize(formatter, report), headers: headers, - params: { environment: environment }, + params: { environment: environment } ) # override parent's process_response handling diff --git a/lib/puppet/indirector/catalog/compiler.rb b/lib/puppet/indirector/catalog/compiler.rb index 0ef64b3e304..7694949ecf1 100644 --- a/lib/puppet/indirector/catalog/compiler.rb +++ b/lib/puppet/indirector/catalog/compiler.rb @@ -89,7 +89,7 @@ def find(request) # filter-out a catalog to remove exported resources def filter(catalog) - return catalog.filter { |r| r.virtual? } if catalog.respond_to?(:filter) + return catalog.filter(&:virtual?) if catalog.respond_to?(:filter) catalog end @@ -139,7 +139,7 @@ def add_node_data(node) # If no match is found, return nil. def common_checksum_type(agent_checksum_type) if agent_checksum_type - agent_checksum_types = agent_checksum_type.split('.').map { |type| type.to_sym } + agent_checksum_types = agent_checksum_type.split('.').map(&:to_sym) checksum_type = agent_checksum_types.drop_while do |type| !known_checksum_types.include? type end.first diff --git a/lib/puppet/indirector/face.rb b/lib/puppet/indirector/face.rb index 5db462ae6d3..7cea172c3d7 100644 --- a/lib/puppet/indirector/face.rb +++ b/lib/puppet/indirector/face.rb @@ -32,11 +32,11 @@ class Puppet::Indirector::Face < Puppet::Face end def self.indirections - Puppet::Indirector::Indirection.instances.collect { |t| t.to_s }.sort + Puppet::Indirector::Indirection.instances.collect(&:to_s).sort end def self.terminus_classes(indirection) - Puppet::Indirector::Terminus.terminus_classes(indirection.to_sym).collect { |t| t.to_s }.sort + Puppet::Indirector::Terminus.terminus_classes(indirection.to_sym).collect(&:to_s).sort end def call_indirection_method(method, key, options) diff --git a/lib/puppet/indirector/facts/facter.rb b/lib/puppet/indirector/facts/facter.rb index 9d3aac33f98..8eb847db6d1 100644 --- a/lib/puppet/indirector/facts/facter.rb +++ b/lib/puppet/indirector/facts/facter.rb @@ -57,7 +57,7 @@ def find(request) def self.setup_search_paths(request) # Add any per-module fact directories to facter's search path dirs = request.environment.modulepath.collect do |dir| - ['lib', 'plugins'].map do |subdirectory| + %w[lib plugins].map do |subdirectory| Dir.glob("#{dir}/*/#{subdirectory}/facter") end end.flatten + Puppet[:factpath].split(File::PATH_SEPARATOR) diff --git a/lib/puppet/indirector/file_bucket_file/rest.rb b/lib/puppet/indirector/file_bucket_file/rest.rb index dd135ac24de..ec33c651c15 100644 --- a/lib/puppet/indirector/file_bucket_file/rest.rb +++ b/lib/puppet/indirector/file_bucket_file/rest.rb @@ -13,7 +13,7 @@ def head(request) api.head_filebucket_file( request.key, environment: request.environment.to_s, - bucket_path: request.options[:bucket_path], + bucket_path: request.options[:bucket_path] ) rescue Puppet::HTTP::ResponseError => e return nil if e.response.code == 404 @@ -31,7 +31,7 @@ def find(request) diff_with: request.options[:diff_with], list_all: request.options[:list_all], fromdate: request.options[:fromdate], - todate: request.options[:todate], + todate: request.options[:todate] ) filebucket_file rescue Puppet::HTTP::ResponseError => e @@ -44,7 +44,7 @@ def save(request) api.put_filebucket_file( request.key, body: request.instance.render, - environment: request.environment.to_s, + environment: request.environment.to_s ) rescue Puppet::HTTP::ResponseError => e raise convert_to_http_error(e.response) diff --git a/lib/puppet/indirector/file_content/rest.rb b/lib/puppet/indirector/file_content/rest.rb index d940c6c1313..90e3ea75be3 100644 --- a/lib/puppet/indirector/file_content/rest.rb +++ b/lib/puppet/indirector/file_content/rest.rb @@ -17,7 +17,7 @@ def find(request) api.get_file_content( path: Puppet::Util.uri_unescape(url.path), - environment: request.environment.to_s, + environment: request.environment.to_s ) do |data| content << data end diff --git a/lib/puppet/indirector/file_metadata/rest.rb b/lib/puppet/indirector/file_metadata/rest.rb index a393ae99291..1ed2855e7c2 100644 --- a/lib/puppet/indirector/file_metadata/rest.rb +++ b/lib/puppet/indirector/file_metadata/rest.rb @@ -46,7 +46,7 @@ def search(request) ignore: request.options[:ignore], links: request.options[:links], checksum_type: request.options[:checksum_type], - source_permissions: request.options[:source_permissions], + source_permissions: request.options[:source_permissions] ) file_metadatas rescue Puppet::HTTP::ResponseError => e diff --git a/lib/puppet/indirector/indirection.rb b/lib/puppet/indirector/indirection.rb index d1f354bbcde..35996b6290c 100644 --- a/lib/puppet/indirector/indirection.rb +++ b/lib/puppet/indirector/indirection.rb @@ -26,7 +26,7 @@ def self.instance(name) # Return a list of all known indirections. Used to generate the # reference. def self.instances - @@indirections.collect { |i| i.name } + @@indirections.collect(&:name) end # Find an indirected model by name. This is provided so that Terminus classes diff --git a/lib/puppet/indirector/resource/ral.rb b/lib/puppet/indirector/resource/ral.rb index 7f608833361..486a85c374f 100644 --- a/lib/puppet/indirector/resource/ral.rb +++ b/lib/puppet/indirector/resource/ral.rb @@ -14,7 +14,7 @@ def allow_remote_requests? def find(request) # find by name res = type(request).instances.find { |o| o.name == resource_name(request) } - res ||= type(request).new(:name => resource_name(request), :audit => type(request).properties.collect { |s| s.name }) + res ||= type(request).new(:name => resource_name(request), :audit => type(request).properties.collect(&:name)) res.to_resource end @@ -23,9 +23,7 @@ def search(request) conditions = request.options.dup conditions[:name] = resource_name(request) if resource_name(request) - type(request).instances.map do |res| - res.to_resource - end.find_all do |res| + type(request).instances.map(&:to_resource).find_all do |res| conditions.all? do |property, value| # even though `res` is an instance of Puppet::Resource, calling # `res[:name]` on it returns nil, and for some reason it is necessary diff --git a/lib/puppet/indirector/terminus.rb b/lib/puppet/indirector/terminus.rb index 129b5860c75..ece138533b5 100644 --- a/lib/puppet/indirector/terminus.rb +++ b/lib/puppet/indirector/terminus.rb @@ -24,7 +24,7 @@ def abstract_terminus? # Convert a constant to a short name. def const2name(const) - const.sub(/^[A-Z]/) { |i| i.downcase }.gsub(/[A-Z]/) { |i| "_#{i.downcase}" }.intern + const.sub(/^[A-Z]/, &:downcase).gsub(/[A-Z]/) { |i| "_#{i.downcase}" }.intern end # Look up the indirection if we were only provided a name. @@ -57,7 +57,7 @@ def inherited(subclass) names = longname.split("::") # Convert everything to a lower-case symbol, converting camelcase to underscore word separation. - name = names.pop.sub(/^[A-Z]/) { |i| i.downcase }.gsub(/[A-Z]/) { |i| "_#{i.downcase}" }.intern + name = names.pop.sub(/^[A-Z]/, &:downcase).gsub(/[A-Z]/) { |i| "_#{i.downcase}" }.intern subclass.name = name @@ -75,7 +75,7 @@ def inherited(subclass) # This subclass is specifically associated with an indirection. raise("Invalid name #{longname}") unless names.length > 0 - processed_name = names.pop.sub(/^[A-Z]/) { |i| i.downcase }.gsub(/[A-Z]/) { |i| "_#{i.downcase}" } + processed_name = names.pop.sub(/^[A-Z]/, &:downcase).gsub(/[A-Z]/) { |i| "_#{i.downcase}" } if processed_name.empty? raise Puppet::DevError, _("Could not discern indirection model from class constant") diff --git a/lib/puppet/interface/action.rb b/lib/puppet/interface/action.rb index c08090cc1eb..e330ed6e0ba 100644 --- a/lib/puppet/interface/action.rb +++ b/lib/puppet/interface/action.rb @@ -254,7 +254,7 @@ def when_invoked=(block) file = __FILE__ + "+eval[wrapper]" line = __LINE__ + 2 # <== points to the same line as 'def' in the wrapper. wrapper = <<~WRAPPER - def #{@name}(#{decl.join(", ")}) + def #{@name}(#{decl.join(', ')}) #{optn} args = #{args} action = get_action(#{name.inspect}) diff --git a/lib/puppet/interface/action_manager.rb b/lib/puppet/interface/action_manager.rb index 13c1e13ec41..f2c8a83baad 100644 --- a/lib/puppet/interface/action_manager.rb +++ b/lib/puppet/interface/action_manager.rb @@ -78,9 +78,9 @@ def get_action(name) # @return [Puppet::Interface::Action] # @api private def get_default_action - default = actions.map { |x| get_action(x) }.select { |x| x.default } + default = actions.map { |x| get_action(x) }.select(&:default) if default.length > 1 - raise "The actions #{default.map(&:name).join(", ")} cannot all be default" + raise "The actions #{default.map(&:name).join(', ')} cannot all be default" end default.first diff --git a/lib/puppet/module_tool/applications/installer.rb b/lib/puppet/module_tool/applications/installer.rb index ff37ce2ff7f..9e86fff2b65 100644 --- a/lib/puppet/module_tool/applications/installer.rb +++ b/lib/puppet/module_tool/applications/installer.rb @@ -218,7 +218,7 @@ def run end Puppet.info _("Preparing to install ...") - releases.each { |release| release.prepare } + releases.each(&:prepare) Puppet.notice _('Installing -- do not interrupt ...') releases.each do |release| diff --git a/lib/puppet/module_tool/applications/upgrader.rb b/lib/puppet/module_tool/applications/upgrader.rb index b4c4ef230dc..9186e496d12 100644 --- a/lib/puppet/module_tool/applications/upgrader.rb +++ b/lib/puppet/module_tool/applications/upgrader.rb @@ -172,7 +172,7 @@ def installed_release.priority unless forced? if child.version == results[:installed_version] - versions = graph.dependencies[name].map { |r| r.version } + versions = graph.dependencies[name].map(&:version) newer_versions = versions.select { |v| v > results[:installed_version] } raise VersionAlreadyInstalledError, @@ -190,7 +190,7 @@ def installed_release.priority end Puppet.info _("Preparing to upgrade ...") - releases.each { |release| release.prepare } + releases.each(&:prepare) Puppet.notice _('Upgrading -- do not interrupt ...') releases.each do |release| diff --git a/lib/puppet/network/http/handler.rb b/lib/puppet/network/http/handler.rb index b90c62b2e62..1f5cd180193 100644 --- a/lib/puppet/network/http/handler.rb +++ b/lib/puppet/network/http/handler.rb @@ -13,7 +13,7 @@ module Puppet::Network::HTTP::Handler # These shouldn't be allowed to be set by clients # in the query string, for security reasons. - DISALLOWED_KEYS = ["node", "ip"] + DISALLOWED_KEYS = %w[node ip] def register(routes) # There's got to be a simpler way to do this, right? @@ -21,7 +21,7 @@ def register(routes) routes.each { |r| dupes[r.path_matcher] = (dupes[r.path_matcher] || 0) + 1 } dupes = dupes.filter_map { |pm, count| pm if count > 1 } if dupes.count > 0 - raise ArgumentError, _("Given multiple routes with identical path regexes: %{regexes}") % { regexes: dupes.map { |rgx| rgx.inspect }.join(', ') } + raise ArgumentError, _("Given multiple routes with identical path regexes: %{regexes}") % { regexes: dupes.map(&:inspect).join(', ') } end @routes = routes diff --git a/lib/puppet/node/environment.rb b/lib/puppet/node/environment.rb index 54a3bc5fd7a..08ef63f2750 100644 --- a/lib/puppet/node/environment.rb +++ b/lib/puppet/node/environment.rb @@ -518,7 +518,7 @@ def to_s # @api public def inspect - %Q(<#{self.class}:#{object_id} @name="#{name}" @manifest="#{manifest}" @modulepath="#{full_modulepath.join(":")}" >) + %Q(<#{self.class}:#{object_id} @name="#{name}" @manifest="#{manifest}" @modulepath="#{full_modulepath.join(':')}" >) end # @return [Symbol] The `name` value, cast to a string, then cast to a symbol. diff --git a/lib/puppet/pal/json_catalog_encoder.rb b/lib/puppet/pal/json_catalog_encoder.rb index f813025f636..cce47e2a951 100644 --- a/lib/puppet/pal/json_catalog_encoder.rb +++ b/lib/puppet/pal/json_catalog_encoder.rb @@ -67,7 +67,7 @@ def encode_resource(type, title) # @api private # rubocop:disable Naming/MemoizedInstanceVariableName def possibly_filtered_catalog - @filtered ||= (exclude_virtual ? catalog.filter { |r| r.virtual? } : catalog) + @filtered ||= (exclude_virtual ? catalog.filter(&:virtual?) : catalog) end private :possibly_filtered_catalog # rubocop:enable Naming/MemoizedInstanceVariableName diff --git a/lib/puppet/pal/plan_signature.rb b/lib/puppet/pal/plan_signature.rb index b0e7a0907e0..593aa9139b5 100644 --- a/lib/puppet/pal/plan_signature.rb +++ b/lib/puppet/pal/plan_signature.rb @@ -51,7 +51,7 @@ def callable_with?(args_hash) return true if errors.empty? if block_given? - yield errors.map { |e| e.format }.join("\n") + yield errors.map(&:format).join("\n") end false end diff --git a/lib/puppet/pal/task_signature.rb b/lib/puppet/pal/task_signature.rb index c341aaae6dd..bdc45ff23ea 100644 --- a/lib/puppet/pal/task_signature.rb +++ b/lib/puppet/pal/task_signature.rb @@ -37,7 +37,7 @@ def runnable_with?(args_hash) else tm.describe_struct_signature(params_type, args_hash) .flatten - .map { |e| e.format } + .map(&:format) .join("\n") end yield "Task #{@task.name}:\n#{error}" diff --git a/lib/puppet/parameter.rb b/lib/puppet/parameter.rb index 9f4db03ec40..be72e8024af 100644 --- a/lib/puppet/parameter.rb +++ b/lib/puppet/parameter.rb @@ -121,7 +121,7 @@ def doc features = required_features if features - @doc << "\n\nRequires features #{features.flatten.collect { |f| f.to_s }.join(" ")}." + @doc << "\n\nRequires features #{features.flatten.collect(&:to_s).join(' ')}." end @addeddocvals = true end diff --git a/lib/puppet/parameter/value_collection.rb b/lib/puppet/parameter/value_collection.rb index 8e25e3921f5..9a62705276a 100644 --- a/lib/puppet/parameter/value_collection.rb +++ b/lib/puppet/parameter/value_collection.rb @@ -37,7 +37,7 @@ def doc @doc << @strings.collect do |value| aliases = value.aliases if aliases && !aliases.empty? - "`#{value.name}` (also called `#{aliases.join(", ")}`)" + "`#{value.name}` (also called `#{aliases.join(', ')}`)" else "`#{value.name}`" end @@ -45,7 +45,7 @@ def doc end unless regexes.empty? - @doc << "Values can match `#{regexes.join("`, `")}`." + @doc << "Values can match `#{regexes.join('`, `')}`." end end @@ -208,6 +208,6 @@ def value(name) # @api private # def values - @strings.collect { |s| s.name } + @strings.collect(&:name) end end diff --git a/lib/puppet/parser/ast/block_expression.rb b/lib/puppet/parser/ast/block_expression.rb index 8e7dc391bd8..08eda3d5a4d 100644 --- a/lib/puppet/parser/ast/block_expression.rb +++ b/lib/puppet/parser/ast/block_expression.rb @@ -12,6 +12,6 @@ def sequence_with(other) end def to_s - "[" + @children.collect { |c| c.to_s }.join(', ') + "]" + "[" + @children.collect(&:to_s).join(', ') + "]" end end diff --git a/lib/puppet/parser/ast/pops_bridge.rb b/lib/puppet/parser/ast/pops_bridge.rb index 87ceab951e7..e825a80c228 100644 --- a/lib/puppet/parser/ast/pops_bridge.rb +++ b/lib/puppet/parser/ast/pops_bridge.rb @@ -152,7 +152,7 @@ def create_type_map(definition) return result unless definition.parameters.size > 0 # No need to do anything if there are no typed parameters - typed_parameters = definition.parameters.select { |p| p.type_expr } + typed_parameters = definition.parameters.select(&:type_expr) return result if typed_parameters.empty? # If there are typed parameters, they need to be evaluated to produce the corresponding type diff --git a/lib/puppet/parser/compiler.rb b/lib/puppet/parser/compiler.rb index 10a373e4d6a..f65769a65bc 100644 --- a/lib/puppet/parser/compiler.rb +++ b/lib/puppet/parser/compiler.rb @@ -28,12 +28,12 @@ def self.compile(node, code_id = nil) errors.each { |e| Puppet.err(e) } if errors.size > 1 errmsg = [ _("Compilation has been halted because: %{error}") % { error: errors.first }, - _("For more information, see https://puppet.com/docs/puppet/latest/environments_about.html"), + _("For more information, see https://puppet.com/docs/puppet/latest/environments_about.html") ] raise(Puppet::Error, errmsg.join(' ')) end - new(node, :code_id => code_id).compile { |resulting_catalog| resulting_catalog.to_resource } + new(node, :code_id => code_id).compile(&:to_resource) rescue Puppet::ParseErrorWithIssue => detail detail.node = node.name Puppet.log_exception(detail) diff --git a/lib/puppet/parser/functions.rb b/lib/puppet/parser/functions.rb index c22a1e710f4..570ea0afd18 100644 --- a/lib/puppet/parser/functions.rb +++ b/lib/puppet/parser/functions.rb @@ -263,7 +263,7 @@ def self.functiondocs(environment = Puppet.lookup(:current_environment)) ret = ''.dup merged_functions(environment).sort { |a, b| a[0].to_s <=> b[0].to_s }.each do |name, hash| - ret << "#{name}\n#{"-" * name.to_s.length}\n" + ret << "#{name}\n#{'-' * name.to_s.length}\n" if hash[:doc] ret << Puppet::Util::Docs.scrub(hash[:doc]) else diff --git a/lib/puppet/parser/functions/fail.rb b/lib/puppet/parser/functions/fail.rb index 7d8dae1c28e..910fb3b3b9e 100644 --- a/lib/puppet/parser/functions/fail.rb +++ b/lib/puppet/parser/functions/fail.rb @@ -8,6 +8,6 @@ concatenated, and passed to the exception-handler. DOC ) do |vals| - vals = vals.collect { |s| s.to_s }.join(" ") if vals.is_a? Array + vals = vals.collect(&:to_s).join(" ") if vals.is_a? Array raise Puppet::ParseError, vals.to_s end diff --git a/lib/puppet/parser/resource.rb b/lib/puppet/parser/resource.rb index b623f3b7bf8..b0a9dc34c2a 100644 --- a/lib/puppet/parser/resource.rb +++ b/lib/puppet/parser/resource.rb @@ -21,7 +21,7 @@ class Puppet::Parser::Resource < Puppet::Resource # Determine whether the provided parameter name is a relationship parameter. def self.relationship_parameter?(name) - @relationship_names ||= Puppet::Type.relationship_params.collect { |p| p.name } + @relationship_names ||= Puppet::Type.relationship_params.collect(&:name) @relationship_names.include?(name) end diff --git a/lib/puppet/parser/scope.rb b/lib/puppet/parser/scope.rb index 4d3436d264b..8a63566a851 100644 --- a/lib/puppet/parser/scope.rb +++ b/lib/puppet/parser/scope.rb @@ -17,7 +17,7 @@ class Puppet::Parser::Scope extend Forwardable # Variables that always exist with nil value even if not set - BUILT_IN_VARS = ['module_name', 'caller_module_name'].freeze + BUILT_IN_VARS = %w[module_name caller_module_name].freeze EMPTY_HASH = {}.freeze Puppet::Util.logmethods(self) @@ -260,7 +260,7 @@ def as_read_only end def to_hash - @params.select { |_, access| access.assigned? }.transform_values { |access| access.value } + @params.select { |_, access| access.assigned? }.transform_values(&:value) end end diff --git a/lib/puppet/parser/templatewrapper.rb b/lib/puppet/parser/templatewrapper.rb index 2026c418c22..6e27a27302c 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/evaluator/access_operator.rb b/lib/puppet/pops/evaluator/access_operator.rb index eb09455666a..26f56a46464 100644 --- a/lib/puppet/pops/evaluator/access_operator.rb +++ b/lib/puppet/pops/evaluator/access_operator.rb @@ -67,7 +67,7 @@ def access_String(o, scope, keys) k2 = k2 < 0 ? o.length - k1 + k2 + 1 : k2 # abs length (negative k2 is length from pos to end count) # if k1 is outside, adjust to first position, and adjust length if k1 < 0 - k2 = k2 + k1 + k2 += k1 k1 = 0 end o[k1, k2] @@ -116,7 +116,7 @@ def access_Array(o, scope, keys) k2 = k2 < 0 ? o.length - k1 + k2 + 1 : k2 # abs length (negative k2 is length from pos to end count) # if k1 is outside, adjust to first position, and adjust length if k1 < 0 - k2 = k2 + k1 + k2 += k1 k1 = 0 end # Help ruby always return empty array when asking for a sub array diff --git a/lib/puppet/pops/evaluator/collectors/fixed_set_collector.rb b/lib/puppet/pops/evaluator/collectors/fixed_set_collector.rb index 1a3f8131152..184a9fae70b 100644 --- a/lib/puppet/pops/evaluator/collectors/fixed_set_collector.rb +++ b/lib/puppet/pops/evaluator/collectors/fixed_set_collector.rb @@ -25,7 +25,7 @@ def collect resolved << ref end - @resources = @resources - resolved + @resources -= resolved @scope.compiler.delete_collection(self) if @resources.empty? diff --git a/lib/puppet/pops/evaluator/epp_evaluator.rb b/lib/puppet/pops/evaluator/epp_evaluator.rb index 5b0d5b28f89..c69c64daa1b 100644 --- a/lib/puppet/pops/evaluator/epp_evaluator.rb +++ b/lib/puppet/pops/evaluator/epp_evaluator.rb @@ -31,7 +31,7 @@ def self.epp(scope, file, env_name, template_args = nil) unless Puppet::FileSystem.exist?(file) unless file =~ /\.epp$/ - file = file + ".epp" + file += ".epp" end end diff --git a/lib/puppet/pops/evaluator/evaluator_impl.rb b/lib/puppet/pops/evaluator/evaluator_impl.rb index 3c8a3562f03..eb8f3e07bb7 100644 --- a/lib/puppet/pops/evaluator/evaluator_impl.rb +++ b/lib/puppet/pops/evaluator/evaluator_impl.rb @@ -1064,10 +1064,10 @@ def eval_IfExpression o, scope # Evaluates Puppet DSL `unless` def eval_UnlessExpression o, scope scope.with_guarded_scope do - unless is_true?(evaluate(o.test, scope), o.test) - evaluate(o.then_expr, scope) - else + if is_true?(evaluate(o.test, scope), o.test) evaluate(o.else_expr, scope) + else + evaluate(o.then_expr, scope) end end end diff --git a/lib/puppet/pops/evaluator/runtime3_converter.rb b/lib/puppet/pops/evaluator/runtime3_converter.rb index 6eda49f549c..19ca00f2e8d 100644 --- a/lib/puppet/pops/evaluator/runtime3_converter.rb +++ b/lib/puppet/pops/evaluator/runtime3_converter.rb @@ -70,7 +70,7 @@ def convert_Integer(o, scope, undef_value) return o unless o < MIN_INTEGER || o > MAX_INTEGER range_end = o > MAX_INTEGER ? 'max' : 'min' - raise Puppet::Error, "Use of a Ruby Integer outside of Puppet Integer #{range_end} range, got '#{"0x%x" % o}'" + raise Puppet::Error, "Use of a Ruby Integer outside of Puppet Integer #{range_end} range, got '#{'0x%x' % o}'" end def convert_BigDecimal(o, scope, undef_value) diff --git a/lib/puppet/pops/functions/dispatcher.rb b/lib/puppet/pops/functions/dispatcher.rb index 4e357c448e3..cf621ec63ed 100644 --- a/lib/puppet/pops/functions/dispatcher.rb +++ b/lib/puppet/pops/functions/dispatcher.rb @@ -62,15 +62,15 @@ def to_type # make a copy to make sure it can be contained by someone else (even if it is not contained here, it # should be treated as immutable). # - callables = dispatchers.map { |dispatch| dispatch.type } + callables = dispatchers.map(&:type) # multiple signatures, produce a Variant type of Callable1-n (must copy them) # single signature, produce single Callable - callables.size > 1 ? Puppet::Pops::Types::TypeFactory.variant(*callables) : callables.pop + callables.size > 1 ? Puppet::Pops::Types::TypeFactory.variant(*callables) : callables.pop end # @api private def signatures - @dispatchers.reject { |dispatcher| dispatcher.argument_mismatch_handler? } + @dispatchers.reject(&:argument_mismatch_handler?) end end diff --git a/lib/puppet/pops/loader/dependency_loader.rb b/lib/puppet/pops/loader/dependency_loader.rb index 3b26303101b..ce26fba1207 100644 --- a/lib/puppet/pops/loader/dependency_loader.rb +++ b/lib/puppet/pops/loader/dependency_loader.rb @@ -62,7 +62,7 @@ def loaded_entry(typed_name, check_dependencies = false) end def to_s - "(DependencyLoader '#{@loader_name}' [" + @dependency_loaders.map { |loader| loader.to_s }.join(' ,') + "])" + "(DependencyLoader '#{@loader_name}' [" + @dependency_loaders.map(&:to_s).join(' ,') + "])" end private diff --git a/lib/puppet/pops/loader/static_loader.rb b/lib/puppet/pops/loader/static_loader.rb index 95449a66ca6..04f04308b81 100644 --- a/lib/puppet/pops/loader/static_loader.rb +++ b/lib/puppet/pops/loader/static_loader.rb @@ -24,7 +24,7 @@ class StaticLoader < Loader Whit ].freeze - BUILTIN_TYPE_NAMES_LC = Set.new(BUILTIN_TYPE_NAMES.map { |n| n.downcase }).freeze + BUILTIN_TYPE_NAMES_LC = Set.new(BUILTIN_TYPE_NAMES.map(&:downcase)).freeze BUILTIN_ALIASES = { 'Data' => 'Variant[ScalarData,Undef,Hash[String,Data],Array[Data]]', diff --git a/lib/puppet/pops/loaders.rb b/lib/puppet/pops/loaders.rb index f47afb79851..873b99e5e82 100644 --- a/lib/puppet/pops/loaders.rb +++ b/lib/puppet/pops/loaders.rb @@ -518,7 +518,7 @@ def []=(name, module_data) end def all_module_loaders - @all_module_loaders ||= @index.values.map { |md| md.public_loader } + @all_module_loaders ||= @index.values.map(&:public_loader) end def resolve(module_data) diff --git a/lib/puppet/pops/lookup/explainer.rb b/lib/puppet/pops/lookup/explainer.rb index 7f9ceac4aac..0ae470b43ee 100644 --- a/lib/puppet/pops/lookup/explainer.rb +++ b/lib/puppet/pops/lookup/explainer.rb @@ -15,7 +15,7 @@ def branches def to_hash hash = {} - hash[:branches] = @branches.map { |b| b.to_hash } unless @branches.nil? || @branches.empty? + hash[:branches] = @branches.map(&:to_hash) unless @branches.nil? || @branches.empty? hash end diff --git a/lib/puppet/pops/lookup/hiera_config.rb b/lib/puppet/pops/lookup/hiera_config.rb index 84708456acd..254b6fde4fd 100644 --- a/lib/puppet/pops/lookup/hiera_config.rb +++ b/lib/puppet/pops/lookup/hiera_config.rb @@ -723,7 +723,7 @@ def has_default_hierarchy? @config.include?(KEY_DEFAULT_HIERARCHY) end - RESERVED_OPTION_KEYS = ['path', 'uri'].freeze + RESERVED_OPTION_KEYS = %w[path uri].freeze DEFAULT_CONFIG_HASH = { KEY_VERSION => 5, diff --git a/lib/puppet/pops/lookup/location_resolver.rb b/lib/puppet/pops/lookup/location_resolver.rb index 768c859887d..c122da5db07 100644 --- a/lib/puppet/pops/lookup/location_resolver.rb +++ b/lib/puppet/pops/lookup/location_resolver.rb @@ -43,7 +43,7 @@ module LocationResolver def expand_globs(datadir, declared_globs, lookup_invocation) declared_globs.map do |declared_glob| glob = datadir + interpolate(declared_glob, lookup_invocation, false) - Pathname.glob(glob).reject { |path| path.directory? }.map { |path| ResolvedLocation.new(glob.to_s, path, true) } + Pathname.glob(glob).reject(&:directory?).map { |path| ResolvedLocation.new(glob.to_s, path, true) } end.flatten end diff --git a/lib/puppet/pops/parser/epp_parser.rb b/lib/puppet/pops/parser/epp_parser.rb index 804f34c5e09..65342921d01 100644 --- a/lib/puppet/pops/parser/epp_parser.rb +++ b/lib/puppet/pops/parser/epp_parser.rb @@ -14,7 +14,7 @@ def initvars def parse_file(file) unless FileTest.exist?(file) unless file =~ /\.epp$/ - file = file + ".epp" + file += ".epp" end end @lexer.file = file diff --git a/lib/puppet/pops/parser/epp_support.rb b/lib/puppet/pops/parser/epp_support.rb index 8347966c8d2..86c98e0b1a5 100644 --- a/lib/puppet/pops/parser/epp_support.rb +++ b/lib/puppet/pops/parser/epp_support.rb @@ -44,7 +44,7 @@ def scan_epp interpolate_epp # This is the lexer's main loop - until queue.empty? && scn.eos? do + until queue.empty? && scn.eos? token = queue.shift || lex_token if token yield [ctx[:after] = token[0], token[1]] diff --git a/lib/puppet/pops/parser/heredoc_support.rb b/lib/puppet/pops/parser/heredoc_support.rb index 80e4f6b6e51..33f621f70f4 100644 --- a/lib/puppet/pops/parser/heredoc_support.rb +++ b/lib/puppet/pops/parser/heredoc_support.rb @@ -83,7 +83,7 @@ def heredoc # (Endline in EBNF form): WS* ('|' WS*)? ('-' WS*)? endtag WS* \r? (\n|$) endline_pattern = /([[:blank:]]*)(?:([|])[[:blank:]]*)?(?:(-)[[:blank:]]*)?#{Regexp.escape(endtag)}[[:blank:]]*\r?(?:\n|\z)/ lines = [] - until scn.eos? do + until scn.eos? one_line = scn.scan_until(/(?:\n|\z)/) raise eof_error unless one_line diff --git a/lib/puppet/pops/parser/interpolation_support.rb b/lib/puppet/pops/parser/interpolation_support.rb index 4e90edb60cb..779c77353bf 100644 --- a/lib/puppet/pops/parser/interpolation_support.rb +++ b/lib/puppet/pops/parser/interpolation_support.rb @@ -194,7 +194,7 @@ def enqueue_until brace_count scn.skip(self.class::PATTERN_WS) queue_size = queue.size - until scn.eos? do + until scn.eos? token = lex_token if token if token.equal?(queue_base) @@ -242,7 +242,7 @@ def transform_to_variable(token) def interpolate_uq_to(lexer) interpolate_uq queue = @token_queue - until queue.empty? do + until queue.empty? lexer.enqueue(queue.shift) end end diff --git a/lib/puppet/pops/parser/lexer2.rb b/lib/puppet/pops/parser/lexer2.rb index 972d6d984e2..d8d9754ba33 100644 --- a/lib/puppet/pops/parser/lexer2.rb +++ b/lib/puppet/pops/parser/lexer2.rb @@ -714,7 +714,7 @@ def scan scn.skip(PATTERN_WS) # This is the lexer's main loop - until queue.empty? && scn.eos? do + until queue.empty? && scn.eos? token = queue.shift || selector[scn.peek(1)].call if token ctx[:after] = token[0] diff --git a/lib/puppet/pops/parser/lexer_support.rb b/lib/puppet/pops/parser/lexer_support.rb index 2e9464ec271..80cdef65bbe 100644 --- a/lib/puppet/pops/parser/lexer_support.rb +++ b/lib/puppet/pops/parser/lexer_support.rb @@ -200,7 +200,7 @@ def assert_not_bom(content) lex_error_without_pos( Puppet::Pops::Issues::ILLEGAL_BOM, { :format_name => name, - :bytes => "[#{bom.values[0, size].map { |b| "%X" % b }.join(" ")}]" } + :bytes => "[#{bom.values[0, size].map { |b| '%X' % b }.join(' ')}]" } ) end diff --git a/lib/puppet/pops/parser/locator.rb b/lib/puppet/pops/parser/locator.rb index 0d469a33a36..61d363ce6c3 100644 --- a/lib/puppet/pops/parser/locator.rb +++ b/lib/puppet/pops/parser/locator.rb @@ -141,7 +141,7 @@ def ary_bsearch_i(ary, value) satisfied = false v = nil - while low < high do + while low < high mid = low + ((high - low) / 2) v = (ary[mid] > value) if v == true diff --git a/lib/puppet/pops/parser/parser_support.rb b/lib/puppet/pops/parser/parser_support.rb index 4dbf04f7948..40ad98cfa52 100644 --- a/lib/puppet/pops/parser/parser_support.rb +++ b/lib/puppet/pops/parser/parser_support.rb @@ -77,7 +77,7 @@ def error(semantic, message) def parse_file(file) unless Puppet::FileSystem.exist?(file) unless file =~ /\.pp$/ - file = file + ".pp" + file += ".pp" end end @lexer.file = file diff --git a/lib/puppet/pops/parser/pn_parser.rb b/lib/puppet/pops/parser/pn_parser.rb index 16f6bd187fc..2405ee0fe37 100644 --- a/lib/puppet/pops/parser/pn_parser.rb +++ b/lib/puppet/pops/parser/pn_parser.rb @@ -196,7 +196,7 @@ def next_token end def consume_identifier(s) - while @char_types[peek_cp] >= TYPE_IDENTIFIER do + while @char_types[peek_cp] >= TYPE_IDENTIFIER @pos += 1 end id = @text[s...@pos] @@ -287,7 +287,7 @@ def skip_decimal_digits c = peek_cp end - while @char_types[c] == TYPE_DIGIT do + while @char_types[c] == TYPE_DIGIT @pos += 1 c = peek_cp count += 1 @@ -296,7 +296,7 @@ def skip_decimal_digits end def skip_white - while @char_types[peek_cp] == TYPE_WS do + while @char_types[peek_cp] == TYPE_WS @pos += 1 end end diff --git a/lib/puppet/pops/pn.rb b/lib/puppet/pops/pn.rb index 7059e33e9c9..2667696ea97 100644 --- a/lib/puppet/pops/pn.rb +++ b/lib/puppet/pops/pn.rb @@ -116,7 +116,7 @@ def format(indent, b) end def to_data - { '^' => [@name] + @elements.map { |e| e.to_data } } + { '^' => [@name] + @elements.map(&:to_data) } end end @@ -166,7 +166,7 @@ def format(indent, b) end def to_data - @elements.map { |e| e.to_data } + @elements.map(&:to_data) end end diff --git a/lib/puppet/pops/time/timestamp.rb b/lib/puppet/pops/time/timestamp.rb index 1b6feb4b0bf..c8f506bf4c6 100644 --- a/lib/puppet/pops/time/timestamp.rb +++ b/lib/puppet/pops/time/timestamp.rb @@ -107,7 +107,7 @@ def self.parse(str, format = :default, timezone = nil) fraction = parsed[:sec_fraction] # Convert msec rational found in _strptime hash to usec - fraction = fraction * 1_000_000 unless fraction.nil? + fraction *= 1_000_000 unless fraction.nil? # Create the Time instance and adjust for timezone parsed_time = ::Time.utc(parsed[:year], parsed[:mon], parsed[:mday], parsed[:hour], parsed[:min], parsed[:sec], fraction) diff --git a/lib/puppet/pops/types/p_object_type.rb b/lib/puppet/pops/types/p_object_type.rb index 38f576543df..31c0388595e 100644 --- a/lib/puppet/pops/types/p_object_type.rb +++ b/lib/puppet/pops/types/p_object_type.rb @@ -901,7 +901,7 @@ def _pcore_init_hash(include_name = true) tc = TypeCalculator.singleton constants, others = @attributes.partition do |_, a| a.kind == ATTRIBUTE_KIND_CONSTANT && a.type == tc.infer(a.value).generalize - end.map { |ha| ha.to_h } + end.map(&:to_h) result[KEY_ATTRIBUTES] = compressed_members_hash(others) unless others.empty? unless constants.empty? @@ -1111,7 +1111,7 @@ def compressed_members_hash(features) # @return [PObjectType] the topmost parent who's #equality_attributes include the given _attr_ def find_equality_definer_of(attr) type = self - until type.nil? do + until type.nil? p = type.resolved_parent return type unless p.is_a?(PObjectType) return type unless p.equality_attributes.include?(attr.name) diff --git a/lib/puppet/pops/types/p_type_set_type.rb b/lib/puppet/pops/types/p_type_set_type.rb index 7c07497ab09..68279c5eb4d 100644 --- a/lib/puppet/pops/types/p_type_set_type.rb +++ b/lib/puppet/pops/types/p_type_set_type.rb @@ -183,7 +183,7 @@ def _pcore_init_hash result[KEY_NAME] = @name result[KEY_VERSION] = @version.to_s unless @version.nil? result[KEY_TYPES] = @types unless @types.empty? - result[KEY_REFERENCES] = @references.transform_values { |ref| ref._pcore_init_hash } unless @references.empty? + result[KEY_REFERENCES] = @references.transform_values(&:_pcore_init_hash) unless @references.empty? result end diff --git a/lib/puppet/pops/types/p_uri_type.rb b/lib/puppet/pops/types/p_uri_type.rb index 6222b41cd10..2264716f637 100644 --- a/lib/puppet/pops/types/p_uri_type.rb +++ b/lib/puppet/pops/types/p_uri_type.rb @@ -34,7 +34,7 @@ class PURIType < PAnyType TypeFactory.optional(PATH) => PStringType::NON_EMPTY, TypeFactory.optional(QUERY) => PStringType::NON_EMPTY, TypeFactory.optional(FRAGMENT) => PStringType::NON_EMPTY, - TypeFactory.optional(OPAQUE) => PStringType::NON_EMPTY, + TypeFactory.optional(OPAQUE) => PStringType::NON_EMPTY ) TYPE_STRING_PARAM = @@ -46,7 +46,7 @@ class PURIType < PAnyType TypeFactory.type_type(PPatternType::DEFAULT), TypeFactory.type_type(PEnumType::DEFAULT), TypeFactory.type_type(PNotUndefType::DEFAULT), - TypeFactory.type_type(PUndefType::DEFAULT), + TypeFactory.type_type(PUndefType::DEFAULT) ])) TYPE_INTEGER_PARAM = @@ -55,7 +55,7 @@ class PURIType < PAnyType .new([ PIntegerType.new(0), TypeFactory.type_type(PNotUndefType::DEFAULT), - TypeFactory.type_type(PUndefType::DEFAULT), + TypeFactory.type_type(PUndefType::DEFAULT) ])) TYPE_URI_PARAM_HASH_TYPE = TypeFactory.struct( @@ -66,7 +66,7 @@ class PURIType < PAnyType TypeFactory.optional(PATH) => TYPE_STRING_PARAM, TypeFactory.optional(QUERY) => TYPE_STRING_PARAM, TypeFactory.optional(FRAGMENT) => TYPE_STRING_PARAM, - TypeFactory.optional(OPAQUE) => TYPE_STRING_PARAM, + TypeFactory.optional(OPAQUE) => TYPE_STRING_PARAM ) TYPE_URI_PARAM_TYPE = PVariantType.new([PStringType::NON_EMPTY, TYPE_URI_PARAM_HASH_TYPE]) diff --git a/lib/puppet/pops/types/recursion_guard.rb b/lib/puppet/pops/types/recursion_guard.rb index 10be5603076..d1e8671274e 100644 --- a/lib/puppet/pops/types/recursion_guard.rb +++ b/lib/puppet/pops/types/recursion_guard.rb @@ -46,7 +46,7 @@ def recursive_that?(instance) def with_this(instance) if (@state & SELF_RECURSION_IN_THIS) == 0 tc = this_count - @state = @state | SELF_RECURSION_IN_THIS if this_put(instance) + @state |= SELF_RECURSION_IN_THIS if this_put(instance) if tc < this_count # recursive state detected result = yield(@state) @@ -66,7 +66,7 @@ def with_this(instance) def with_that(instance) if (@state & SELF_RECURSION_IN_THAT) == 0 tc = that_count - @state = @state | SELF_RECURSION_IN_THAT if that_put(instance) + @state |= SELF_RECURSION_IN_THAT if that_put(instance) if tc < that_count # recursive state detected result = yield(@state) @@ -85,7 +85,7 @@ def with_that(instance) # @return [Integer] the resulting state def add_this(instance) if (@state & SELF_RECURSION_IN_THIS) == 0 - @state = @state | SELF_RECURSION_IN_THIS if this_put(instance) + @state |= SELF_RECURSION_IN_THIS if this_put(instance) end @state end @@ -95,7 +95,7 @@ def add_this(instance) # @return [Integer] the resulting state def add_that(instance) if (@state & SELF_RECURSION_IN_THAT) == 0 - @state = @state | SELF_RECURSION_IN_THAT if that_put(instance) + @state |= SELF_RECURSION_IN_THAT if that_put(instance) end @state end diff --git a/lib/puppet/pops/types/ruby_generator.rb b/lib/puppet/pops/types/ruby_generator.rb index 861e92fbe99..c91d4cc5631 100644 --- a/lib/puppet/pops/types/ruby_generator.rb +++ b/lib/puppet/pops/types/ruby_generator.rb @@ -220,7 +220,7 @@ def class_body(obj, segments, bld) end init_params = others.reject { |a| a.kind == PObjectType::ATTRIBUTE_KIND_DERIVED } - opt, non_opt = init_params.partition { |ip| ip.value? } + opt, non_opt = init_params.partition(&:value?) derived_attrs, obj_attrs = others.select { |a| a.container.equal?(obj) }.partition { |ip| ip.kind == PObjectType::ATTRIBUTE_KIND_DERIVED } include_type = obj.equality_include_type? && !(obj.parent.is_a?(PObjectType) && obj.parent.equality_include_type?) diff --git a/lib/puppet/pops/types/string_converter.rb b/lib/puppet/pops/types/string_converter.rb index f633a986e8e..02533cbcdc3 100644 --- a/lib/puppet/pops/types/string_converter.rb +++ b/lib/puppet/pops/types/string_converter.rb @@ -89,7 +89,7 @@ class Format FMT_PATTERN_STR = '^%([\s\[+#0{<(|-]*)([1-9][0-9]*)?(?:\.([0-9]+))?([a-zA-Z])$' FMT_PATTERN = Regexp.compile(FMT_PATTERN_STR) - DELIMITERS = ['[', '{', '(', '<', '|',] + DELIMITERS = ['[', '{', '(', '<', '|'] DELIMITER_MAP = { '[' => ['[', ']'], '{' => ['{', '}'], @@ -830,7 +830,7 @@ def string_PStringType(val_type, val, format_map, _) f.alt? ? apply_string_flags(f, puppet_quote(c_val)) : Kernel.format(f.orig_fmt.tr('c', 's'), c_val) when :C - c_val = val.split('::').map { |s| s.capitalize }.join('::') + c_val = val.split('::').map(&:capitalize).join('::') f.alt? ? apply_string_flags(f, puppet_quote(c_val)) : Kernel.format(f.orig_fmt.tr('C', 's'), c_val) when :u diff --git a/lib/puppet/pops/types/type_mismatch_describer.rb b/lib/puppet/pops/types/type_mismatch_describer.rb index 19c97cdee69..e6ce3d310e8 100644 --- a/lib/puppet/pops/types/type_mismatch_describer.rb +++ b/lib/puppet/pops/types/type_mismatch_describer.rb @@ -287,7 +287,7 @@ def message(variant, position) if e.is_a?(Array) if report_detailed?(e, a) a = detailed_actual_to_s(e, a) - e = e.map { |t| t.to_alias_expanded_s } + e = e.map(&:to_alias_expanded_s) else e = e.map { |t| short_name(t) }.uniq a = short_name(a) @@ -535,7 +535,7 @@ def validate_parameters(subject, params_struct, given_hash, missing_ok = false, when 1 raise Puppet::ParseError, "#{subject}:#{errors[0].format}" else - errors_str = errors.map { |error| error.format }.join("\n ") + errors_str = errors.map(&:format).join("\n ") raise Puppet::ParseError, "#{subject}:\n #{errors_str}" end end @@ -556,7 +556,7 @@ def describe_mismatch(name, expected, actual, tense = :ignored) when 1 errors[0].format.strip else - errors.map { |error| error.format }.join("\n ") + errors.map(&:format).join("\n ") end end @@ -576,7 +576,7 @@ def validate_default_parameter(subject, param_name, param_type, value, tense = : when 1 raise Puppet::ParseError, "#{subject}:#{errors[0].format}" else - errors_str = errors.map { |error| error.format }.join("\n ") + errors_str = errors.map(&:format).join("\n ") raise Puppet::ParseError, "#{subject}:\n #{errors_str}" end end @@ -954,9 +954,7 @@ def describe_PCallableType(expected, original, actual, path) if param_errors.empty? this_return_t = expected.return_type || PAnyType::DEFAULT that_return_t = actual.return_type || PAnyType::DEFAULT - unless this_return_t.assignable?(that_return_t) - [TypeMismatch.new(path + [ReturnTypeElement.new], this_return_t, that_return_t)] - else + if this_return_t.assignable?(that_return_t) # names are ignored, they are just information # Blocks must be compatible this_block_t = expected.block_type || PUndefType::DEFAULT @@ -966,6 +964,8 @@ def describe_PCallableType(expected, original, actual, path) else [TypeMismatch.new(path + [BlockPathElement.new], this_block_t, that_block_t)] end + else + [TypeMismatch.new(path + [ReturnTypeElement.new], this_return_t, that_return_t)] end else param_errors diff --git a/lib/puppet/pops/types/types.rb b/lib/puppet/pops/types/types.rb index 41885f2d006..c055bb8d002 100644 --- a/lib/puppet/pops/types/types.rb +++ b/lib/puppet/pops/types/types.rb @@ -57,7 +57,7 @@ def self.create_ptype(loader, ir, parent_name, attributes_hash = EMPTY_HASH) def self.register_ptypes(loader, ir) types = [ Annotation.register_ptype(loader, ir), - RubyMethod.register_ptype(loader, ir), + RubyMethod.register_ptype(loader, ir) ] Types.constants.each do |c| next if c == :PType || c == :PHostClassType @@ -1820,7 +1820,7 @@ def _assignable?(o, guard) else # the string in String type must match one of the patterns in Pattern type, # or Pattern represents all Patterns == all Strings - regexps = @patterns.map { |p| p.regexp } + regexps = @patterns.map(&:regexp) regexps.empty? || regexps.any? { |re| re.match(v) } end when PEnumType @@ -1831,7 +1831,7 @@ def _assignable?(o, guard) else # all strings in String/Enum type must match one of the patterns in Pattern type, # or Pattern represents all Patterns == all Strings - regexps = @patterns.map { |p| p.regexp } + regexps = @patterns.map(&:regexp) regexps.empty? || o.values.all? { |s| regexps.any? { |re| re.match(s) } } end when PPatternType @@ -2049,8 +2049,8 @@ def iterable_type(guard = nil) else PIterableType.new( PTupleType.new([ - PVariantType.maybe_create(@elements.map { |se| se.key_type }), - PVariantType.maybe_create(@elements.map { |se| se.value_type }) + PVariantType.maybe_create(@elements.map(&:key_type)), + PVariantType.maybe_create(@elements.map(&:value_type)) ], PHashType::KEY_PAIR_TUPLE_SIZE) ) @@ -3058,7 +3058,7 @@ def swap_not_undefs(array) not_undefs = parts[0] if not_undefs.size > 1 others = parts[1] - others << PNotUndefType.new(PVariantType.maybe_create(not_undefs.map { |not_undef| not_undef.type }).normalize) + others << PNotUndefType.new(PVariantType.maybe_create(not_undefs.map(&:type)).normalize) array = others end end @@ -3101,7 +3101,7 @@ def merge_patterns(array) patterns = parts[0] if patterns.size > 1 others = parts[1] - others << PPatternType.new(patterns.map { |pattern| pattern.patterns }.flatten.uniq) + others << PPatternType.new(patterns.map(&:patterns).flatten.uniq) array = others end end diff --git a/lib/puppet/pops/validation/tasks_checker.rb b/lib/puppet/pops/validation/tasks_checker.rb index 49934018f04..4f83ca61612 100644 --- a/lib/puppet/pops/validation/tasks_checker.rb +++ b/lib/puppet/pops/validation/tasks_checker.rb @@ -8,7 +8,7 @@ class TasksChecker < Checker4_0 def in_ApplyExpression? top = container(0) step = -1 - until container(step) == top do + until container(step) == top return true if container(step).is_a? Puppet::Pops::Model::ApplyBlockExpression step -= 1 diff --git a/lib/puppet/property.rb b/lib/puppet/property.rb index f5f50db26df..29bd3cbd9a3 100644 --- a/lib/puppet/property.rb +++ b/lib/puppet/property.rb @@ -589,7 +589,7 @@ def validate_features_per_value(value) features = self.class.value_option(self.class.value_name(value), :required_features) if features features = Array(features) - needed_features = features.collect { |f| f.to_s }.join(", ") + needed_features = features.collect(&:to_s).join(", ") unless provider.satisfies?(features) # TRANSLATORS 'Provider' refers to a Puppet provider class raise ArgumentError, _("Provider %{provider} must have features '%{needed_features}' to set '%{property}' to '%{value}'") % diff --git a/lib/puppet/property/ordered_list.rb b/lib/puppet/property/ordered_list.rb index 2cfa49d8ef3..96f94e45a79 100644 --- a/lib/puppet/property/ordered_list.rb +++ b/lib/puppet/property/ordered_list.rb @@ -17,7 +17,7 @@ def add_should_with_current(should, current) # tricky trick # Preserve all the current items in the list # but move them to the back of the line - should = should + (current - should) + should += (current - should) end should end diff --git a/lib/puppet/provider/exec.rb b/lib/puppet/provider/exec.rb index a0e28750adc..2257077f3b5 100644 --- a/lib/puppet/provider/exec.rb +++ b/lib/puppet/provider/exec.rb @@ -45,7 +45,7 @@ def run(command, check = false) checkexe(command) - debug "Executing#{check ? " check" : ""} '#{sensitive ? '[redacted]' : command}'" + debug "Executing#{check ? ' check' : ''} '#{sensitive ? '[redacted]' : command}'" # Ruby 2.1 and later interrupt execution in a way that bypasses error # handling by default. Passing Timeout::Error causes an exception to be diff --git a/lib/puppet/provider/nameservice/directoryservice.rb b/lib/puppet/provider/nameservice/directoryservice.rb index 3b3f8804617..85159cc0e8e 100644 --- a/lib/puppet/provider/nameservice/directoryservice.rb +++ b/lib/puppet/provider/nameservice/directoryservice.rb @@ -264,7 +264,7 @@ def self.get_password(guid, username) # string. The password_hash provided as a resource attribute is a # hex value. We need to convert the Base64 encoded string to a # hex value and provide it back to Puppet. - converted_hash_plist['SALTED-SHA512'].unpack("H*")[0] + converted_hash_plist['SALTED-SHA512'].unpack1("H*") end end diff --git a/lib/puppet/provider/package/aix.rb b/lib/puppet/provider/package/aix.rb index 2f046fd20ca..aff3fbec4c0 100644 --- a/lib/puppet/provider/package/aix.rb +++ b/lib/puppet/provider/package/aix.rb @@ -152,12 +152,12 @@ def self.instances def latest upd = latest_info - unless upd.nil? - (upd[:version]).to_s - else + if upd.nil? raise Puppet::DevError, _("Tried to get latest on a missing package") if properties[:ensure] == :absent properties[:ensure] + else + (upd[:version]).to_s end end diff --git a/lib/puppet/provider/package/dpkg.rb b/lib/puppet/provider/package/dpkg.rb index f91b5df5cc0..c2ca0079356 100644 --- a/lib/puppet/provider/package/dpkg.rb +++ b/lib/puppet/provider/package/dpkg.rb @@ -73,7 +73,7 @@ def self.parse_line(line, regex = self::FIELDS_REGEX) if hash[:status] == 'not-installed' hash[:ensure] = :purged - elsif ['config-files', 'half-installed', 'unpacked', 'half-configured'].include?(hash[:status]) + elsif %w[config-files half-installed unpacked half-configured].include?(hash[:status]) hash[:ensure] = :absent end hash[:mark] = hash[:desired] == 'hold' ? :hold : :none diff --git a/lib/puppet/provider/package/nim.rb b/lib/puppet/provider/package/nim.rb index 6c84a3a5e85..64503e0a857 100644 --- a/lib/puppet/provider/package/nim.rb +++ b/lib/puppet/provider/package/nim.rb @@ -202,7 +202,7 @@ def parse_showres_output(showres_output) # leading or trailing whitespace (including newlines) from the resulting # strings and then returns them as an array. def split_into_paragraphs(showres_output) - showres_output.split(/^\s*$/).map { |p| p.strip! } + showres_output.split(/^\s*$/).map(&:strip!) end def parse_showres_header_line(line) diff --git a/lib/puppet/provider/package/openbsd.rb b/lib/puppet/provider/package/openbsd.rb index 6e05ef03934..c230fe41099 100644 --- a/lib/puppet/provider/package/openbsd.rb +++ b/lib/puppet/provider/package/openbsd.rb @@ -104,7 +104,7 @@ def latest return match[2] end - vcmp = version.split('.').map { |s| s.to_i } <=> match[2].split('.').map { |s| s.to_i } + vcmp = version.split('.').map(&:to_i) <=> match[2].split('.').map(&:to_i) if vcmp > 0 # The locally installed package may actually be newer than what a mirror # has. Log it at debug, but ignore it otherwise. diff --git a/lib/puppet/provider/package/pacman.rb b/lib/puppet/provider/package/pacman.rb index abfa24849cf..0c132309d8f 100644 --- a/lib/puppet/provider/package/pacman.rb +++ b/lib/puppet/provider/package/pacman.rb @@ -133,7 +133,7 @@ def latest resource_name = @resource[:name] # If target is a group, construct the group version - return pacman("-Sp", "--print-format", "%n %v", resource_name).lines.map { |line| line.chomp }.sort.join(', ') if self.class.group?(resource_name) + return pacman("-Sp", "--print-format", "%n %v", resource_name).lines.map(&:chomp).sort.join(', ') if self.class.group?(resource_name) # Start by querying with pacman first # If that fails, retry using yaourt against the AUR diff --git a/lib/puppet/provider/package/pip.rb b/lib/puppet/provider/package/pip.rb index 7c00c73b7b7..c7352a36e5f 100644 --- a/lib/puppet/provider/package/pip.rb +++ b/lib/puppet/provider/package/pip.rb @@ -39,7 +39,7 @@ def self.cmd if Puppet::Util::Platform.windows? ["pip.exe"] else - ["pip", "pip-python", "pip2", "pip-2"] + %w[pip pip-python pip2 pip-2] end end diff --git a/lib/puppet/provider/package/pkg.rb b/lib/puppet/provider/package/pkg.rb index 7dacfcbbff7..68b0d68cab7 100644 --- a/lib/puppet/provider/package/pkg.rb +++ b/lib/puppet/provider/package/pkg.rb @@ -242,7 +242,7 @@ def install(nofail = false) tries = 1 # pkg install exits with code 7 when the image is currently in use by another process and cannot be modified r = exec_cmd(command(:pkg), command, *args, name) - while r[:exit] == 7 do + while r[:exit] == 7 if tries > 4 raise Puppet::Error, _("Pkg could not install %{name} after %{tries} tries. Aborting run") % { name: name, tries: tries } end diff --git a/lib/puppet/provider/package/pkgdmg.rb b/lib/puppet/provider/package/pkgdmg.rb index ec9bfb29f5d..145cce2512c 100644 --- a/lib/puppet/provider/package/pkgdmg.rb +++ b/lib/puppet/provider/package/pkgdmg.rb @@ -95,9 +95,9 @@ def self.installpkgdmg(source, name) end begin curl(*args) - Puppet.debug "Success: curl transferred [#{name}] (via: curl #{args.join(" ")})" + Puppet.debug "Success: curl transferred [#{name}] (via: curl #{args.join(' ')})" rescue Puppet::ExecutionFailure - Puppet.debug "curl #{args.join(" ")} did not transfer [#{name}]. Falling back to local file." # This used to fall back to open-uri. -NF + Puppet.debug "curl #{args.join(' ')} did not transfer [#{name}]. Falling back to local file." # This used to fall back to open-uri. -NF cached_source = source end end diff --git a/lib/puppet/provider/package/ports.rb b/lib/puppet/provider/package/ports.rb index 4afe20e9628..52cd1b212ff 100644 --- a/lib/puppet/provider/package/ports.rb +++ b/lib/puppet/provider/package/ports.rb @@ -29,8 +29,8 @@ def latest begin output = portversion(*cmd) - rescue Puppet::ExecutionFailure - raise Puppet::Error.new(output, $!) + rescue Puppet::ExecutionFailure => e + raise Puppet::Error.new(output, e) end line = output.split("\n").pop diff --git a/lib/puppet/provider/package/portupgrade.rb b/lib/puppet/provider/package/portupgrade.rb index 763866bd6b5..b80ae275567 100644 --- a/lib/puppet/provider/package/portupgrade.rb +++ b/lib/puppet/provider/package/portupgrade.rb @@ -46,8 +46,8 @@ def self.instances cmdline = ["-aoQ"] begin output = portinfo(*cmdline) - rescue Puppet::ExecutionFailure - raise Puppet::Error.new(output, $!) + rescue Puppet::ExecutionFailure => e + raise Puppet::Error.new(output, e) end # split output and match it and populate temp hash @@ -88,8 +88,8 @@ def install # FIXME: it's possible that portinstall prompts for data so locks up. begin output = portinstall(*cmdline) - rescue Puppet::ExecutionFailure - raise Puppet::Error.new(output, $!) + rescue Puppet::ExecutionFailure => e + raise Puppet::Error.new(output, e) end if output =~ /\*\* No such / @@ -111,8 +111,8 @@ def latest begin output = portversion(*cmdline) - rescue Puppet::ExecutionFailure - raise Puppet::Error.new(output, $!) + rescue Puppet::ExecutionFailure => e + raise Puppet::Error.new(output, e) end # Check: output format. @@ -166,8 +166,8 @@ def query cmdline = ["-qO", @resource[:name]] begin output = portinfo(*cmdline) - rescue Puppet::ExecutionFailure - raise Puppet::Error.new(output, $!) + rescue Puppet::ExecutionFailure => e + raise Puppet::Error.new(output, e) end # Check: if output isn't in the right format, return nil @@ -196,8 +196,8 @@ def uninstall cmdline = ["-qO", @resource[:name]] begin output = portinfo(*cmdline) - rescue Puppet::ExecutionFailure - raise Puppet::Error.new(output, $!) + rescue Puppet::ExecutionFailure => e + raise Puppet::Error.new(output, e) end if output =~ /^(\S+)/ @@ -214,8 +214,8 @@ def update cmdline = ["-qO", @resource[:name]] begin output = portinfo(*cmdline) - rescue Puppet::ExecutionFailure - raise Puppet::Error.new(output, $!) + rescue Puppet::ExecutionFailure => e + raise Puppet::Error.new(output, e) end if output =~ /^(\S+)/ @@ -223,8 +223,8 @@ def update cmdline = ["-M BATCH=yes", Regexp.last_match(1)] begin output = portupgrade(*cmdline) - rescue Puppet::ExecutionFailure - raise Puppet::Error.new(output, $!) + rescue Puppet::ExecutionFailure => e + raise Puppet::Error.new(output, e) end end end diff --git a/lib/puppet/provider/package/puppetserver_gem.rb b/lib/puppet/provider/package/puppetserver_gem.rb index 1482d2e9993..83582c7b247 100644 --- a/lib/puppet/provider/package/puppetserver_gem.rb +++ b/lib/puppet/provider/package/puppetserver_gem.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true +require 'English' unless Puppet::Util::Platform.jruby_fips? require 'rubygems/commands/list_command' end @@ -37,7 +38,7 @@ def self.provider_command end def self.gemlist(options) - command_options = ['gem', 'list'] + command_options = %w[gem list] if options[:local] command_options << '--local' @@ -81,7 +82,7 @@ def self.gemlist(options) end def install(useversion = true) - command_options = ['gem', 'install'] + command_options = %w[gem install] command_options += install_options if resource[:install_options] command_options << '-v' << resource[:ensure] if (!resource[:ensure].is_a? Symbol) && useversion @@ -118,7 +119,7 @@ def install(useversion = true) end def uninstall - command_options = ['gem', 'uninstall'] + command_options = %w[gem uninstall] command_options << '--executables' << '--all' << resource[:name] command_options += uninstall_options if resource[:uninstall_options] @@ -158,7 +159,7 @@ def self.execute_rubygems_list_command(command_options) gem_env['GEM_HOME'] = puppetserver_conf['jruby-puppet'].key?('gem-home') ? puppetserver_conf['jruby-puppet']['gem-home'] : puppetserver_default_gem_home gem_env['GEM_PATH'] = puppetserver_conf['jruby-puppet'].key?('gem-path') ? puppetserver_conf['jruby-puppet']['gem-path'].join(':') : puppetserver_default_gem_path end - gem_env['GEM_SPEC_CACHE'] = "/tmp/#{$$}" + gem_env['GEM_SPEC_CACHE'] = "/tmp/#{$PROCESS_ID}" # Remove the 'gem' from the command_options command_options.shift diff --git a/lib/puppet/provider/package/rpm.rb b/lib/puppet/provider/package/rpm.rb index 6065f72983d..72880f41185 100644 --- a/lib/puppet/provider/package/rpm.rb +++ b/lib/puppet/provider/package/rpm.rb @@ -71,8 +71,8 @@ def self.instances # now turn each returned line into a package object nevra_to_multiversion_hash(process).each { |hash| packages << new(hash) } } - rescue Puppet::ExecutionFailure - raise Puppet::Error, _("Failed to list packages"), $!.backtrace + rescue Puppet::ExecutionFailure => e + raise Puppet::Error, _("Failed to list packages"), e.backtrace end packages diff --git a/lib/puppet/provider/package/windows/exe_package.rb b/lib/puppet/provider/package/windows/exe_package.rb index b927b8480f9..b52a66e3327 100644 --- a/lib/puppet/provider/package/windows/exe_package.rb +++ b/lib/puppet/provider/package/windows/exe_package.rb @@ -16,7 +16,7 @@ class ExePackage < Puppet::Provider::Package::Windows::Package 'Security Update', 'Update Rollup', 'Hotfix', - 'WindowsInstaller', + 'WindowsInstaller' ] def self.register(path) diff --git a/lib/puppet/provider/package/windows/msi_package.rb b/lib/puppet/provider/package/windows/msi_package.rb index f949f1b7cc8..79c47be465c 100644 --- a/lib/puppet/provider/package/windows/msi_package.rb +++ b/lib/puppet/provider/package/windows/msi_package.rb @@ -13,9 +13,9 @@ class MsiPackage < Puppet::Provider::Package::Windows::Package # registry values to load under each product entry in # HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall # for this provider - REG_VALUE_NAMES = [ - 'DisplayVersion', - 'WindowsInstaller' + REG_VALUE_NAMES = %w[ + DisplayVersion + WindowsInstaller ] # Get the COM installer object, it's in a separate method for testing diff --git a/lib/puppet/provider/package/windows/package.rb b/lib/puppet/provider/package/windows/package.rb index a989f3f2b6f..96a582a4446 100644 --- a/lib/puppet/provider/package/windows/package.rb +++ b/lib/puppet/provider/package/windows/package.rb @@ -13,7 +13,7 @@ class Package attr_reader :name, :version - REG_DISPLAY_VALUE_NAMES = ['DisplayName', 'QuietDisplayName'] + REG_DISPLAY_VALUE_NAMES = %w[DisplayName QuietDisplayName] def self.reg_value_names_to_load REG_DISPLAY_VALUE_NAMES | diff --git a/lib/puppet/provider/package/yum.rb b/lib/puppet/provider/package/yum.rb index 7b2b206514c..15bc372c6b3 100644 --- a/lib/puppet/provider/package/yum.rb +++ b/lib/puppet/provider/package/yum.rb @@ -333,17 +333,17 @@ def install # What's the latest package version available? def latest upd = self.class.latest_package_version(@resource[:name], disablerepo, enablerepo, disableexcludes) - unless upd.nil? - # FIXME: there could be more than one update for a package - # because of multiarch - "#{upd[:epoch]}:#{upd[:version]}-#{upd[:release]}" - else + if upd.nil? # Yum didn't find updates, pretend the current version is the latest debug "Yum didn't find updates, current version (#{properties[:ensure]}) is the latest" version = properties[:ensure] raise Puppet::DevError, _("Tried to get latest on a missing package") if version == :absent || version == :purged version + else + # FIXME: there could be more than one update for a package + # because of multiarch + "#{upd[:epoch]}:#{upd[:version]}-#{upd[:release]}" end end diff --git a/lib/puppet/provider/package/zypper.rb b/lib/puppet/provider/package/zypper.rb index f5690d31c8b..b19c87c5f6c 100644 --- a/lib/puppet/provider/package/zypper.rb +++ b/lib/puppet/provider/package/zypper.rb @@ -112,7 +112,7 @@ def install # Assume that this will work on newer zypper versions # extract version numbers and convert to integers - major, minor, patch = zypper_version.scan(/\d+/).map { |x| x.to_i } + major, minor, patch = zypper_version.scan(/\d+/).map(&:to_i) debug "Detected zypper version #{major}.#{minor}.#{patch}" # zypper version < 1.0 does not support --quiet flag @@ -164,7 +164,7 @@ def update def uninstall # extract version numbers and convert to integers - major, minor, _ = zypper_version.scan(/\d+/).map { |x| x.to_i } + major, minor, _ = zypper_version.scan(/\d+/).map(&:to_i) if major < 1 super diff --git a/lib/puppet/provider/service/base.rb b/lib/puppet/provider/service/base.rb index 796e1135369..943ba28f898 100644 --- a/lib/puppet/provider/service/base.rb +++ b/lib/puppet/provider/service/base.rb @@ -122,8 +122,8 @@ def stop end begin output = kill pid - rescue Puppet::ExecutionFailure - @resource.fail Puppet::Error, "Could not kill #{name}, PID #{pid}: #{output}", $! + rescue Puppet::ExecutionFailure => e + @resource.fail Puppet::Error, "Could not kill #{name}, PID #{pid}: #{output}", e end true end diff --git a/lib/puppet/provider/service/daemontools.rb b/lib/puppet/provider/service/daemontools.rb index 046ce959a7d..b055d8adffa 100644 --- a/lib/puppet/provider/service/daemontools.rb +++ b/lib/puppet/provider/service/daemontools.rb @@ -159,8 +159,8 @@ def enable Puppet::FileSystem.symlink(daemon, service) end end - rescue Puppet::ExecutionFailure - raise Puppet::Error.new("No daemon directory found for #{service}", $!) + rescue Puppet::ExecutionFailure => e + raise Puppet::Error.new("No daemon directory found for #{service}", e) end def disable @@ -175,8 +175,8 @@ def disable Puppet::FileSystem.unlink(service) end end - rescue Puppet::ExecutionFailure - raise Puppet::Error.new("No daemon directory found for #{service}", $!) + rescue Puppet::ExecutionFailure => e + raise Puppet::Error.new("No daemon directory found for #{service}", e) end stop end diff --git a/lib/puppet/provider/service/debian.rb b/lib/puppet/provider/service/debian.rb index 013f41c6dc8..975c2a28b93 100644 --- a/lib/puppet/provider/service/debian.rb +++ b/lib/puppet/provider/service/debian.rb @@ -21,8 +21,8 @@ confine :false => Puppet::FileSystem.exist?('/proc/1/comm') && Puppet::FileSystem.read('/proc/1/comm').include?('systemd') - defaultfor 'os.name' => :cumuluslinux, 'os.release.major' => ['1', '2'] - defaultfor 'os.name' => :debian, 'os.release.major' => ['5', '6', '7'] + defaultfor 'os.name' => :cumuluslinux, 'os.release.major' => %w[1 2] + defaultfor 'os.name' => :debian, 'os.release.major' => %w[5 6 7] defaultfor 'os.name' => :devuan # Remove the symlinks diff --git a/lib/puppet/provider/service/gentoo.rb b/lib/puppet/provider/service/gentoo.rb index c787484eafa..78425f397af 100644 --- a/lib/puppet/provider/service/gentoo.rb +++ b/lib/puppet/provider/service/gentoo.rb @@ -16,8 +16,8 @@ def disable output = update :del, @resource[:name], :default - rescue Puppet::ExecutionFailure - raise Puppet::Error, "Could not disable #{name}: #{output}", $!.backtrace + rescue Puppet::ExecutionFailure => e + raise Puppet::Error, "Could not disable #{name}: #{output}", e.backtrace end def enabled? @@ -41,7 +41,7 @@ def enabled? def enable output = update :add, @resource[:name], :default - rescue Puppet::ExecutionFailure - raise Puppet::Error, "Could not enable #{name}: #{output}", $!.backtrace + rescue Puppet::ExecutionFailure => e + raise Puppet::Error, "Could not enable #{name}: #{output}", e.backtrace end end diff --git a/lib/puppet/provider/service/init.rb b/lib/puppet/provider/service/init.rb index 5929f52a636..d7097f1b0da 100644 --- a/lib/puppet/provider/service/init.rb +++ b/lib/puppet/provider/service/init.rb @@ -21,7 +21,7 @@ def self.defpath end # Debian and Ubuntu should use the Debian provider. - confine :false => ['Debian', 'Ubuntu'].include?(Puppet.runtime[:facter].value('os.name')) + confine :false => %w[Debian Ubuntu].include?(Puppet.runtime[:facter].value('os.name')) # RedHat systems should use the RedHat provider. confine :false => Puppet.runtime[:facter].value('os.family') == 'RedHat' diff --git a/lib/puppet/provider/service/launchd.rb b/lib/puppet/provider/service/launchd.rb index 7a40868cea7..697bdef8783 100644 --- a/lib/puppet/provider/service/launchd.rb +++ b/lib/puppet/provider/service/launchd.rb @@ -192,8 +192,8 @@ def self.job_list output.split("\n").each do |line| @job_list[line.split(/\s/).last] = :running end - rescue Puppet::ExecutionFailure - raise Puppet::Error.new("Unable to determine status of #{resource[:name]}", $!) + rescue Puppet::ExecutionFailure => e + raise Puppet::Error.new("Unable to determine status of #{resource[:name]}", e) end @job_list end @@ -287,8 +287,8 @@ def start cmds << job_path begin execute(cmds) - rescue Puppet::ExecutionFailure - raise Puppet::Error.new("Unable to start service: #{resource[:name]} at path: #{job_path}", $!) + rescue Puppet::ExecutionFailure => e + raise Puppet::Error.new("Unable to start service: #{resource[:name]} at path: #{job_path}", e) end # As load -w clears the Disabled flag, we need to add it in after disable if did_enable_job and resource[:enable] == :false @@ -310,8 +310,8 @@ def stop cmds << job_path begin execute(cmds) - rescue Puppet::ExecutionFailure - raise Puppet::Error.new("Unable to stop service: #{resource[:name]} at path: #{job_path}", $!) + rescue Puppet::ExecutionFailure => e + raise Puppet::Error.new("Unable to stop service: #{resource[:name]} at path: #{job_path}", e) end # As unload -w sets the Disabled flag, we need to add it in after enable if did_disable_job and resource[:enable] == :true diff --git a/lib/puppet/provider/service/redhat.rb b/lib/puppet/provider/service/redhat.rb index 535c13a2fe7..e03634acc12 100644 --- a/lib/puppet/provider/service/redhat.rb +++ b/lib/puppet/provider/service/redhat.rb @@ -10,9 +10,9 @@ commands :chkconfig => "/sbin/chkconfig", :service => "/sbin/service" - defaultfor 'os.name' => :amazon, 'os.release.major' => ["2017", "2018"] + defaultfor 'os.name' => :amazon, 'os.release.major' => %w[2017 2018] defaultfor 'os.name' => :redhat, 'os.release.major' => (4..6).to_a - defaultfor 'os.family' => :suse, 'os.release.major' => ["10", "11"] + defaultfor 'os.family' => :suse, 'os.release.major' => %w[10 11] # Remove the symlinks def disable diff --git a/lib/puppet/provider/service/smf.rb b/lib/puppet/provider/service/smf.rb index 1d03f0607d5..59be2179da9 100644 --- a/lib/puppet/provider/service/smf.rb +++ b/lib/puppet/provider/service/smf.rb @@ -208,9 +208,9 @@ def status # use that for the state comparison. states = service_states state = states[:next] || states[:current] - rescue Puppet::ExecutionFailure + rescue Puppet::ExecutionFailure => e # TODO (PUP-8957): Should this be set back to INFO ? - debug "Could not get status on service #{name} #{$!}" + debug "Could not get status on service #{name} #{e}" return :stopped end @@ -262,7 +262,7 @@ def flush fmri = service_fmri # Useful constants for operations involving multiple states - stopped = ['offline', 'disabled', 'uninitialized'] + stopped = %w[offline disabled uninitialized] # Get the current state of the service. cur_state = status diff --git a/lib/puppet/provider/service/systemd.rb b/lib/puppet/provider/service/systemd.rb index 932bf6dd927..54a1639bdc6 100644 --- a/lib/puppet/provider/service/systemd.rb +++ b/lib/puppet/provider/service/systemd.rb @@ -22,15 +22,15 @@ defaultfor 'os.family' => :suse defaultfor 'os.family' => :coreos defaultfor 'os.family' => :gentoo - notdefaultfor 'os.name' => :amazon, 'os.release.major' => ["2017", "2018"] - defaultfor 'os.name' => :amazon, 'os.release.major' => ["2", "2023"] + notdefaultfor 'os.name' => :amazon, 'os.release.major' => %w[2017 2018] + defaultfor 'os.name' => :amazon, 'os.release.major' => %w[2 2023] defaultfor 'os.name' => :debian - notdefaultfor 'os.name' => :debian, 'os.release.major' => ["5", "6", "7"] # These are using the "debian" method + notdefaultfor 'os.name' => :debian, 'os.release.major' => %w[5 6 7] # These are using the "debian" method defaultfor 'os.name' => :LinuxMint - notdefaultfor 'os.name' => :LinuxMint, 'os.release.major' => ["10", "11", "12", "13", "14", "15", "16", "17"] # These are using upstart + notdefaultfor 'os.name' => :LinuxMint, 'os.release.major' => %w[10 11 12 13 14 15 16 17] # These are using upstart defaultfor 'os.name' => :ubuntu notdefaultfor 'os.name' => :ubuntu, 'os.release.major' => ["10.04", "12.04", "14.04", "14.10"] # These are using upstart - defaultfor 'os.name' => :cumuluslinux, 'os.release.major' => ["3", "4"] + defaultfor 'os.name' => :cumuluslinux, 'os.release.major' => %w[3 4] def self.instances i = [] @@ -72,8 +72,8 @@ def enabled_insync?(current) # @param action [String,Symbol] One of 'enable', 'disable', 'mask' or 'unmask' def systemctl_change_enable(action) output = systemctl(action, '--', @resource[:name]) - rescue - raise Puppet::Error, "Could not #{action} #{name}: #{output}", $!.backtrace + rescue => e + raise Puppet::Error, "Could not #{action} #{name}: #{output}", e.backtrace ensure @cached_enabled = nil end diff --git a/lib/puppet/provider/service/upstart.rb b/lib/puppet/provider/service/upstart.rb index 39597b3544c..fac33ae9c4c 100644 --- a/lib/puppet/provider/service/upstart.rb +++ b/lib/puppet/provider/service/upstart.rb @@ -15,11 +15,11 @@ Puppet.runtime[:facter].value('os.name') == 'Ubuntu', (Puppet.runtime[:facter].value('os.family') == 'RedHat' and Puppet.runtime[:facter].value('os.release.full') =~ /^6\./), (Puppet.runtime[:facter].value('os.name') == 'Amazon' and Puppet.runtime[:facter].value('os.release.major') =~ /\d{4}/), - Puppet.runtime[:facter].value('os.name') == 'LinuxMint', + Puppet.runtime[:facter].value('os.name') == 'LinuxMint' ] defaultfor 'os.name' => :ubuntu, 'os.release.major' => ["10.04", "12.04", "14.04", "14.10"] - defaultfor 'os.name' => :LinuxMint, 'os.release.major' => ["10", "11", "12", "13", "14", "15", "16", "17"] + defaultfor 'os.name' => :LinuxMint, 'os.release.major' => %w[10 11 12 13 14 15 16 17] commands :start => "/sbin/start", :stop => "/sbin/stop", diff --git a/lib/puppet/provider/user/directoryservice.rb b/lib/puppet/provider/user/directoryservice.rb index 006083fa1e4..40e3ca2c29e 100644 --- a/lib/puppet/provider/user/directoryservice.rb +++ b/lib/puppet/provider/user/directoryservice.rb @@ -205,7 +205,7 @@ def self.convert_binary_to_hash(plist_data) # The salted-SHA512 password hash in 10.7 is stored in the 'SALTED-SHA512' # key as binary data. That data is extracted and converted to a hex string. def self.get_salted_sha512(embedded_binary_plist) - embedded_binary_plist['SALTED-SHA512'].unpack("H*")[0] + embedded_binary_plist['SALTED-SHA512'].unpack1("H*") end # This method reads the passed embedded_binary_plist hash and returns values @@ -220,7 +220,7 @@ def self.get_salted_sha512_pbkdf2(field, embedded_binary_plist, user_name = "") raise Puppet::Error, "Invalid #{field} given for user #{user_name}" end - value.unpack('H*').first + value.unpack1('H*') when 'iterations' Integer(embedded_binary_plist['SALTED-SHA512-PBKDF2'][field]) else @@ -448,7 +448,7 @@ def salt=(value) # In the event that the user doesn't HAVE a value for the attribute, the # provider should use the -create option with dscl to add the attribute value # for the user record - ['home', 'uid', 'gid', 'comment', 'shell'].each do |setter_method| + %w[home uid gid comment shell].each do |setter_method| define_method("#{setter_method}=") do |value| if @property_hash[setter_method.intern] if %w[home uid].include?(setter_method) diff --git a/lib/puppet/provider/user/hpux.rb b/lib/puppet/provider/user/hpux.rb index ff3358a321a..2a55d6fc77b 100644 --- a/lib/puppet/provider/user/hpux.rb +++ b/lib/puppet/provider/user/hpux.rb @@ -48,7 +48,7 @@ def modifycmd(param, value) def password # Password management routine for trusted and non-trusted systems # temp="" - while ent = Etc.getpwent() do # rubocop:disable Lint/AssignmentInCondition + while ent = Etc.getpwent() # rubocop:disable Lint/AssignmentInCondition if ent.name == resource.name temp = ent.name break diff --git a/lib/puppet/reference/providers.rb b/lib/puppet/reference/providers.rb index e7c180eacc1..e8bfbc78ccc 100644 --- a/lib/puppet/reference/providers.rb +++ b/lib/puppet/reference/providers.rb @@ -30,7 +30,7 @@ ret << "\n" # add a trailing newline # Now build up a table of provider suitability. - headers = %w[Provider Suitable?] + features.collect { |f| f.to_s }.sort + headers = %w[Provider Suitable?] + features.collect(&:to_s).sort table_data = {} @@ -71,7 +71,7 @@ when :false details << _(" - Got %{values} false tests that should have been true\n") % { values: values } when :feature - details << _(" - Missing features %{values}\n") % { values: values.collect { |f| f.to_s }.join(",") } + details << _(" - Missing features %{values}\n") % { values: values.collect(&:to_s).join(",") } end end notes << details diff --git a/lib/puppet/reports.rb b/lib/puppet/reports.rb index 24240b951fb..51132ab264b 100644 --- a/lib/puppet/reports.rb +++ b/lib/puppet/reports.rb @@ -78,7 +78,7 @@ def self.reportdocs instance_loader(:report).loadall(Puppet.lookup(:current_environment)) loaded_instances(:report).sort_by(&:to_s).each do |name| mod = report(name) - docs << "#{name}\n#{"-" * name.to_s.length}\n" + docs << "#{name}\n#{'-' * name.to_s.length}\n" docs << Puppet::Util::Docs.scrub(mod.doc) << "\n\n" end diff --git a/lib/puppet/resource.rb b/lib/puppet/resource.rb index 3e907a61137..4b51cdc2980 100644 --- a/lib/puppet/resource.rb +++ b/lib/puppet/resource.rb @@ -432,7 +432,7 @@ def uniqueness_key name = h[namevar] || h[:name] || self.name h[namevar] ||= name h[:name] ||= name - h.values_at(*key_attributes.sort_by { |k| k.to_s }) + h.values_at(*key_attributes.sort_by(&:to_s)) end def key_attributes diff --git a/lib/puppet/resource/catalog.rb b/lib/puppet/resource/catalog.rb index 12cc6e72b53..a793f231883 100644 --- a/lib/puppet/resource/catalog.rb +++ b/lib/puppet/resource/catalog.rb @@ -272,7 +272,7 @@ def relationship_graph(given_prioritizer = nil) def clear(remove_resources = true) super() # We have to do this so that the resources clean themselves up. - @resource_table.values.each { |resource| resource.remove } if remove_resources + @resource_table.values.each(&:remove) if remove_resources @resource_table.clear @resources = [] @@ -304,7 +304,7 @@ def create_resource(type, options) def finalize make_default_resources - @resource_table.values.each { |resource| resource.finish } + @resource_table.values.each(&:finish) write_graph(:resources) end @@ -467,10 +467,10 @@ def self.from_data_hash(data) end def to_data_hash - metadata_hash = metadata.transform_values { |v| v.to_data_hash; } + metadata_hash = metadata.transform_values(&:to_data_hash) recursive_metadata_hash = recursive_metadata.transform_values do |source_to_meta_hash| source_to_meta_hash.transform_values do |metas| - metas.map { |meta| meta.to_data_hash } + metas.map(&:to_data_hash) end end @@ -483,7 +483,7 @@ def to_data_hash 'catalog_format' => catalog_format, 'environment' => environment.to_s, 'resources' => @resources.map { |v| @resource_table[v].to_data_hash }, - 'edges' => edges.map { |e| e.to_data_hash }, + 'edges' => edges.map(&:to_data_hash), 'classes' => classes, }.merge(metadata_hash.empty? ? {} : { 'metadata' => metadata_hash }).merge(recursive_metadata_hash.empty? ? diff --git a/lib/puppet/resource/status.rb b/lib/puppet/resource/status.rb index 08cfde9c0b1..c57e4ac58bd 100644 --- a/lib/puppet/resource/status.rb +++ b/lib/puppet/resource/status.rb @@ -222,7 +222,7 @@ def to_data_hash 'skipped' => @skipped, 'change_count' => @change_count, 'out_of_sync_count' => @out_of_sync_count, - 'events' => @events.map { |event| event.to_data_hash }, + 'events' => @events.map(&:to_data_hash), 'corrective_change' => @corrective_change, } end diff --git a/lib/puppet/resource/type.rb b/lib/puppet/resource/type.rb index 4129ef4e5de..24ba6416d20 100644 --- a/lib/puppet/resource/type.rb +++ b/lib/puppet/resource/type.rb @@ -189,7 +189,7 @@ def instantiate_resource(scope, resource) parent_type(scope).ensure_in_catalog(scope) end - if ['Class', 'Node'].include? resource.type + if %w[Class Node].include? resource.type scope.catalog.merge_tags_from(resource) end end diff --git a/lib/puppet/settings.rb b/lib/puppet/settings.rb index f1b48bc3753..a99cffd886a 100644 --- a/lib/puppet/settings.rb +++ b/lib/puppet/settings.rb @@ -50,7 +50,7 @@ class Puppet::Settings REQUIRED_APP_SETTINGS = [:logdir, :confdir, :vardir, :codedir] # The acceptable sections of the puppet.conf configuration file. - ALLOWED_SECTION_NAMES = ['main', 'server', 'master', 'agent', 'user'].freeze + ALLOWED_SECTION_NAMES = %w[main server master agent user].freeze NONE = 'none' @@ -361,7 +361,7 @@ def parse_global_options(args) # remove run_mode options from the arguments so that later parses don't think # it is an unknown option. - while option_index = args.index('--run_mode') do # rubocop:disable Lint/AssignmentInCondition + while option_index = args.index('--run_mode') # rubocop:disable Lint/AssignmentInCondition args.delete_at option_index args.delete_at option_index end @@ -841,7 +841,7 @@ def reuse use(*new) end - class SearchPathElement < Struct.new(:name, :type); end + SearchPathElement = Struct.new(:name, :type) # The order in which to search for values, without defaults. # @@ -852,7 +852,7 @@ class SearchPathElement < Struct.new(:name, :type); end def configsearchpath(environment = nil, run_mode = preferred_run_mode) searchpath = [ SearchPathElement.new(:memory, :values), - SearchPathElement.new(:cli, :values), + SearchPathElement.new(:cli, :values) ] searchpath << SearchPathElement.new(environment.intern, :environment) if environment @@ -1124,7 +1124,7 @@ def to_manifest # you can 'use' a section as many times as you want. def use(*sections) if Puppet[:settings_catalog] - sections = sections.collect { |s| s.to_sym } + sections = sections.collect(&:to_sym) sections = sections.reject { |s| @used.include?(s) } Puppet.warning(":master section deprecated in favor of :server section") if sections.include?(:master) @@ -1132,7 +1132,7 @@ def use(*sections) # add :server if sections include :master or :master if sections include :server sections |= [:master, :server] if (sections & [:master, :server]).any? - sections = sections.collect { |s| s.to_sym } + sections = sections.collect(&:to_sym) sections = sections.reject { |s| @used.include?(s) } return if sections.empty? @@ -1149,7 +1149,7 @@ def use(*sections) catalog.apply do |transaction| if transaction.any_failed? report = transaction.report - status_failures = report.resource_statuses.values.select { |r| r.failed? } + status_failures = report.resource_statuses.values.select(&:failed?) status_fail_msg = status_failures .collect(&:events) .flatten @@ -1271,7 +1271,7 @@ def parse_file(file, allowed_sections = []) def screen_non_puppet_conf_settings(puppet_conf) puppet_conf.sections.values.each do |section| forbidden = section.settings.select { |setting| Puppet::Settings::EnvironmentConf::ENVIRONMENT_CONF_ONLY_SETTINGS.include?(setting.name) } - raise(SettingsError, "Cannot set #{forbidden.map { |s| s.name }.join(", ")} settings in puppet.conf") unless forbidden.empty? + raise(SettingsError, "Cannot set #{forbidden.map(&:name).join(', ')} settings in puppet.conf") unless forbidden.empty? end end diff --git a/lib/puppet/ssl/base.rb b/lib/puppet/ssl/base.rb index 22e450cfa5e..7e9ccb866b8 100644 --- a/lib/puppet/ssl/base.rb +++ b/lib/puppet/ssl/base.rb @@ -17,7 +17,7 @@ def self.from_multiple_s(text) end def self.to_multiple_s(instances) - instances.collect { |inst| inst.to_s }.join(SEPARATOR) + instances.collect(&:to_s).join(SEPARATOR) end def self.wraps(klass) diff --git a/lib/puppet/ssl/certificate_request.rb b/lib/puppet/ssl/certificate_request.rb index b838e524e5a..e825e7cfc69 100644 --- a/lib/puppet/ssl/certificate_request.rb +++ b/lib/puppet/ssl/certificate_request.rb @@ -209,7 +209,7 @@ def custom_attributes # we need to prevent that field from being written to directly. PRIVATE_CSR_ATTRIBUTES = [ 'extReq', '1.2.840.113549.1.9.14', - 'msExtReq', '1.3.6.1.4.1.311.2.1.14', + 'msExtReq', '1.3.6.1.4.1.311.2.1.14' ] def add_csr_attributes(csr, csr_attributes) @@ -229,7 +229,7 @@ def add_csr_attributes(csr, csr_attributes) end PRIVATE_EXTENSIONS = [ - 'subjectAltName', '2.5.29.17', + 'subjectAltName', '2.5.29.17' ] # @api private diff --git a/lib/puppet/ssl/oids.rb b/lib/puppet/ssl/oids.rb index 8e5040957dc..0807d22f0ab 100644 --- a/lib/puppet/ssl/oids.rb +++ b/lib/puppet/ssl/oids.rb @@ -73,7 +73,7 @@ module Puppet::SSL::Oids ["1.3.6.1.4.1.34380.1.3.1", 'pp_authorization', 'Certificate Extension Authorization'], ["1.3.6.1.4.1.34380.1.3.2", 'pp_auth_auto_renew', 'Auto-Renew Certificate Attribute'], ["1.3.6.1.4.1.34380.1.3.13", 'pp_auth_role', 'Puppet Node Role Name for Authorization'], - ["1.3.6.1.4.1.34380.1.3.39", 'pp_cli_auth', 'Puppetserver CA CLI Authorization'], + ["1.3.6.1.4.1.34380.1.3.39", 'pp_cli_auth', 'Puppetserver CA CLI Authorization'] ] @did_register_puppet_oids = false diff --git a/lib/puppet/ssl/openssl_loader.rb b/lib/puppet/ssl/openssl_loader.rb index 41843adde08..8b11de0cd68 100644 --- a/lib/puppet/ssl/openssl_loader.rb +++ b/lib/puppet/ssl/openssl_loader.rb @@ -7,10 +7,7 @@ # core Puppet code to load correctly in JRuby environments that do not # have a functioning openssl (eg a FIPS enabled one). -unless Puppet::Util::Platform.jruby_fips? - require 'openssl' - require 'net/https' -else +if Puppet::Util::Platform.jruby_fips? # Even in JRuby we need to define the constants that are wrapped in # Indirections: Puppet::SSL::{Key, Certificate, CertificateRequest} module OpenSSL @@ -23,4 +20,7 @@ class Request; end class Certificate; end end end +else + require 'openssl' + require 'net/https' end diff --git a/lib/puppet/transaction.rb b/lib/puppet/transaction.rb index 4becb2795ef..27d5152997f 100644 --- a/lib/puppet/transaction.rb +++ b/lib/puppet/transaction.rb @@ -218,7 +218,7 @@ def any_failed? # Find all of the changed resources. def changed? - report.resource_statuses.values.find_all { |status| status.changed }.collect { |status| catalog.resource(status.resource) } + report.resource_statuses.values.find_all(&:changed).collect { |status| catalog.resource(status.resource) } end def relationship_graph @@ -400,9 +400,9 @@ def scheduled?(resource) # Should this resource be skipped? def skip?(resource) if skip_tags?(resource) - resource.debug "Skipping with skip tags #{skip_tags.join(", ")}" + resource.debug "Skipping with skip tags #{skip_tags.join(', ')}" elsif missing_tags?(resource) - resource.debug "Not tagged with #{tags.join(", ")}" + resource.debug "Not tagged with #{tags.join(', ')}" elsif !scheduled?(resource) resource.debug "Not scheduled" elsif failed_dependencies?(resource) diff --git a/lib/puppet/transaction/event_manager.rb b/lib/puppet/transaction/event_manager.rb index 49706857dda..1aa29c5d90d 100644 --- a/lib/puppet/transaction/event_manager.rb +++ b/lib/puppet/transaction/event_manager.rb @@ -79,7 +79,7 @@ def queue_events(resource, events) queue_events_for_resource(resource, resource, :refresh, [event]) if resource.self_refresh? and !resource.deleting? end - dequeue_events_for_resource(resource, :refresh) if events.detect { |e| e.invalidate_refreshes } + dequeue_events_for_resource(resource, :refresh) if events.detect(&:invalidate_refreshes) end def dequeue_all_events_for_resource(target) diff --git a/lib/puppet/transaction/persistence.rb b/lib/puppet/transaction/persistence.rb index bb7903f6322..88e188e69db 100644 --- a/lib/puppet/transaction/persistence.rb +++ b/lib/puppet/transaction/persistence.rb @@ -21,7 +21,7 @@ def self.allowed_classes Puppet::Pops::Time::Timestamp, Puppet::Pops::Time::TimeData, Puppet::Pops::Time::Timespan, - Puppet::Pops::Types::PBinaryType::Binary, + Puppet::Pops::Types::PBinaryType::Binary # Puppet::Pops::Types::PSensitiveType::Sensitive values are excluded from # the persistence store, ignore it. ].freeze diff --git a/lib/puppet/transaction/report.rb b/lib/puppet/transaction/report.rb index 4ef546445e0..578d748178c 100644 --- a/lib/puppet/transaction/report.rb +++ b/lib/puppet/transaction/report.rb @@ -344,8 +344,8 @@ def to_data_hash 'noop' => @noop, 'noop_pending' => @noop_pending, 'environment' => @environment, - 'logs' => @logs.map { |log| log.to_data_hash }, - 'metrics' => @metrics.transform_values { |metric| metric.to_data_hash }, + 'logs' => @logs.map(&:to_data_hash), + 'metrics' => @metrics.transform_values(&:to_data_hash), 'resource_statuses' => calculate_resource_statuses, 'corrective_change' => @corrective_change, } diff --git a/lib/puppet/transaction/resource_harness.rb b/lib/puppet/transaction/resource_harness.rb index 0b656b8d4c0..3d770b5dad0 100644 --- a/lib/puppet/transaction/resource_harness.rb +++ b/lib/puppet/transaction/resource_harness.rb @@ -310,7 +310,7 @@ def self.from_resource(resource, status) ResourceApplicationContext.new(resource, resource.retrieve_resource.to_hash, Puppet::Util::Storage.cache(resource).dup, - (resource[:audit] || []).map { |p| p.to_sym }, + (resource[:audit] || []).map(&:to_sym), [], status, resource.parameters.select { |_n, p| p.is_a?(Puppet::Property) && !p.sensitive }) diff --git a/lib/puppet/type.rb b/lib/puppet/type.rb index e6797599b51..ce4719d54e4 100644 --- a/lib/puppet/type.rb +++ b/lib/puppet/type.rb @@ -123,7 +123,7 @@ class << self # @return [Array] all type attribute names in a defined order. # def self.allattrs - key_attributes | (parameters & [:provider]) | properties.collect { |property| property.name } | parameters | metaparams + key_attributes | (parameters & [:provider]) | properties.collect(&:name) | parameters | metaparams end # Returns the class associated with the given attribute name. @@ -304,7 +304,7 @@ def self.metaparamclass(name) # @return [Array] all meta-parameter names # def self.metaparams - @@metaparams.collect { |param| param.name } + @@metaparams.collect(&:name) end # Returns the documentation for a given meta-parameter of this type. @@ -389,7 +389,7 @@ def self.key_attribute_parameters def self.key_attributes # This is a cache miss around 0.05 percent of the time. --daniel 2012-07-17 # rubocop:disable Naming/MemoizedInstanceVariableName - @key_attributes_cache ||= key_attribute_parameters.collect { |p| p.name } + @key_attributes_cache ||= key_attribute_parameters.collect(&:name) # rubocop:enable Naming/MemoizedInstanceVariableName end @@ -443,7 +443,7 @@ def self.title_patterns # @return [Object] an object that is a _uniqueness_key_ for this object # def uniqueness_key - self.class.key_attributes.sort_by { |attribute_name| attribute_name.to_s }.map { |attribute_name| self[attribute_name] } + self.class.key_attributes.sort_by(&:to_s).map { |attribute_name| self[attribute_name] } end # Creates a new parameter. @@ -553,7 +553,7 @@ def self.paramdoc(param) def self.parameters return [] unless defined?(@parameters) - @parameters.collect { |klass| klass.name } + @parameters.collect(&:name) end # @return [Puppet::Parameter] Returns the parameter class associated with the given parameter name. @@ -1309,7 +1309,7 @@ def pathbuilder and the second run will log the edit made by Puppet.)" validate do |list| - list = Array(list).collect { |p| p.to_sym } + list = Array(list).collect(&:to_sym) unless list == [:all] list.each do |param| next if @resource.class.validattr?(param) @@ -1330,16 +1330,14 @@ def pathbuilder def all_properties resource.class.properties.find_all do |property| resource.provider.nil? or resource.provider.class.supports_parameter?(property) - end.collect do |property| - property.name - end + end.collect(&:name) end def properties_to_audit(list) if !list.is_a?(Array) && list.to_sym == :all all_properties else - Array(list).collect { |p| p.to_sym } + Array(list).collect(&:to_sym) end end end @@ -1711,11 +1709,11 @@ def self.defaultprovider suitable = suitableprovider # Find which providers are a default for this system. - defaults = suitable.find_all { |provider| provider.default? } + defaults = suitable.find_all(&:default?) # If we don't have any default we use suitable providers defaults = suitable if defaults.empty? - max = defaults.collect { |provider| provider.specificity }.max + max = defaults.collect(&:specificity).max defaults = defaults.find_all { |provider| provider.specificity == max } if defaults.length > 1 diff --git a/lib/puppet/type/exec.rb b/lib/puppet/type/exec.rb index daaa0d88d1a..b062a65ec63 100644 --- a/lib/puppet/type/exec.rb +++ b/lib/puppet/type/exec.rb @@ -85,9 +85,7 @@ def self.checks newproperty(:returns, :array_matching => :all, :event => :executed_command) do |_property| include Puppet::Util::Execution - munge do |value| - value.to_s - end + munge(&:to_s) def event_name :executed_command @@ -155,8 +153,8 @@ def sync sleep try_sleep end end - rescue Timeout::Error - self.fail Puppet::Error, _("Command exceeded timeout"), $! + rescue Timeout::Error => e + self.fail Puppet::Error, _("Command exceeded timeout"), e end log = @resource[:logoutput] @@ -165,10 +163,10 @@ def sync when :true log = @resource[:loglevel] when :on_failure - unless should.include?(@status.exitstatus.to_s) - log = @resource[:loglevel] - else + if should.include?(@status.exitstatus.to_s) log = :false + else + log = @resource[:loglevel] end end unless log == :false @@ -336,8 +334,8 @@ def value=(*values) value = value.shift if value.is_a?(Array) begin value = Float(value) - rescue ArgumentError - raise ArgumentError, _("The timeout must be a number."), $!.backtrace + rescue ArgumentError => e + raise ArgumentError, _("The timeout must be a number."), e.backtrace end [value, 0.0].max end diff --git a/lib/puppet/type/file.rb b/lib/puppet/type/file.rb index d74d9b650ae..fc7526f6756 100644 --- a/lib/puppet/type/file.rb +++ b/lib/puppet/type/file.rb @@ -432,7 +432,7 @@ def self.title_patterns end creator_count += 1 if @parameters.include?(:source) - self.fail _("You cannot specify more than one of %{creators}") % { creators: CREATORS.collect { |p| p.to_s }.join(", ") } if creator_count > 1 + self.fail _("You cannot specify more than one of %{creators}") % { creators: CREATORS.collect(&:to_s).join(", ") } if creator_count > 1 self.fail _("You cannot specify a remote recursion without a source") if !self[:source] && self[:recurse] == :remote diff --git a/lib/puppet/type/file/data_sync.rb b/lib/puppet/type/file/data_sync.rb index e1b05857e7a..5430535ba03 100644 --- a/lib/puppet/type/file/data_sync.rb +++ b/lib/puppet/type/file/data_sync.rb @@ -83,7 +83,7 @@ def retrieve_checksum(resource) ftype = stat.ftype # Don't even try to manage the content on directories or links - return nil if ['directory', 'link', 'fifo', 'socket'].include?(ftype) + return nil if %w[directory link fifo socket].include?(ftype) begin resource.parameter(:checksum).sum_file(resource[:path]) diff --git a/lib/puppet/type/file/source.rb b/lib/puppet/type/file/source.rb index 15242d2ef41..133e45865a5 100644 --- a/lib/puppet/type/file/source.rb +++ b/lib/puppet/type/file/source.rb @@ -205,7 +205,7 @@ def metadata rescue => detail self.fail Puppet::Error, "Could not retrieve file metadata for #{source}: #{detail}", detail end - self.fail "Could not retrieve information from environment #{resource.catalog.environment} source(s) #{value.join(", ")}" unless @metadata + self.fail "Could not retrieve information from environment #{resource.catalog.environment} source(s) #{value.join(', ')}" unless @metadata @metadata end diff --git a/lib/puppet/type/resources.rb b/lib/puppet/type/resources.rb index aa88180bdc7..56f832972ad 100644 --- a/lib/puppet/type/resources.rb +++ b/lib/puppet/type/resources.rb @@ -18,7 +18,7 @@ raise ArgumentError, _("Could not find resource type '%{name}'") % { name: name } unless Puppet::Type.type(name) end - munge { |v| v.to_s } + munge(&:to_s) end newparam(:purge, :boolean => true, :parent => Puppet::Parameter::Boolean) do diff --git a/lib/puppet/type/schedule.rb b/lib/puppet/type/schedule.rb index 55c110fe176..4ad5e8eef58 100644 --- a/lib/puppet/type/schedule.rb +++ b/lib/puppet/type/schedule.rb @@ -116,7 +116,7 @@ module Puppet # Split each range value into a hour, minute, second triad value.split(/\s*-\s*/).each { |val| # Add the values as an array. - range << val.split(":").collect { |n| n.to_i } + range << val.split(":").collect(&:to_i) } self.fail _("Invalid range %{value}") % { value: value } if range.length != 2 diff --git a/lib/puppet/util/at_fork/solaris.rb b/lib/puppet/util/at_fork/solaris.rb index e7ee9507c95..d7cdfda9d20 100644 --- a/lib/puppet/util/at_fork/solaris.rb +++ b/lib/puppet/util/at_fork/solaris.rb @@ -36,7 +36,7 @@ class Puppet::Util::AtFork::Solaris [:ct_status_read, Fiddle::TYPE_INT, Fiddle::TYPE_INT, Fiddle::TYPE_INT, Fiddle::TYPE_VOIDP], [:ct_status_get_id, Fiddle::TYPE_INT, Fiddle::TYPE_VOIDP], - [:ct_status_free, Fiddle::TYPE_VOID, Fiddle::TYPE_VOIDP], + [:ct_status_free, Fiddle::TYPE_VOID, Fiddle::TYPE_VOIDP] ], }.each do |library, functions| libhandle = Fiddle::Handle.new(library) diff --git a/lib/puppet/util/autoload.rb b/lib/puppet/util/autoload.rb index fb86b5fb609..ce2c9b0ae3b 100644 --- a/lib/puppet/util/autoload.rb +++ b/lib/puppet/util/autoload.rb @@ -111,7 +111,7 @@ def reload_changed(env) # returns nil if no file is found # @api private def get_file(name, env) - name = name + '.rb' unless name =~ /\.rb$/ + name += '.rb' unless name =~ /\.rb$/ path = search_directories(env).find { |dir| Puppet::FileSystem.exist?(File.join(dir, name)) } path and File.join(path, name) end diff --git a/lib/puppet/util/command_line.rb b/lib/puppet/util/command_line.rb index 91e06209ced..903a4697476 100644 --- a/lib/puppet/util/command_line.rb +++ b/lib/puppet/util/command_line.rb @@ -31,7 +31,7 @@ class CommandLine # @param zero [String] the name of the executable # @param argv [Array] the arguments passed on the command line # @param stdin [IO] (unused) - def initialize(zero = $0, argv = ARGV, stdin = STDIN) + def initialize(zero = $PROGRAM_NAME, argv = ARGV, stdin = STDIN) @command = File.basename(zero, '.rb') @argv = argv end diff --git a/lib/puppet/util/command_line/trollop.rb b/lib/puppet/util/command_line/trollop.rb index 9c13e9c0fa6..8b0fba147aa 100644 --- a/lib/puppet/util/command_line/trollop.rb +++ b/lib/puppet/util/command_line/trollop.rb @@ -417,7 +417,7 @@ def parse cmdline = ARGV when :float, :floats vals[sym] = params.map { |pg| pg.map { |p| parse_float_parameter p, arg } } when :string, :strings - vals[sym] = params.map { |pg| pg.map { |p| p.to_s } } + vals[sym] = params.map { |pg| pg.map(&:to_s) } when :io, :ios vals[sym] = params.map { |pg| pg.map { |p| parse_io_parameter p, arg } } when :date, :dates @@ -425,13 +425,13 @@ def parse cmdline = ARGV end if SINGLE_ARG_TYPES.include?(opts[:type]) - unless opts[:multi] # single parameter - vals[sym] = vals[sym][0][0] - else # multiple options, each with a single parameter + if opts[:multi] # multiple options, each with a single parameter vals[sym] = vals[sym].map { |p| p[0] } + else # single parameter + vals[sym] = vals[sym][0][0] end elsif MULTI_ARG_TYPES.include?(opts[:type]) && !opts[:multi] - vals[sym] = vals[sym][0] # single option, with multiple parameters + vals[sym] = vals[sym][0] # single option, with multiple parameters end # else: multiple options, with multiple parameters @@ -459,8 +459,8 @@ def parse_date_parameter param, arg # :nodoc: # chronic is not available end time ? Date.new(time.year, time.month, time.day) : Date.parse(param) - rescue ArgumentError - raise CommandlineError, _("option '%{arg}' needs a date") % { arg: arg }, $!.backtrace + rescue ArgumentError => e + raise CommandlineError, _("option '%{arg}' needs a date") % { arg: arg }, e.backtrace end ## Print the help message to +stream+. @@ -487,11 +487,11 @@ def educate stream = $stdout end end - leftcol_width = left.values.map { |s| s.length }.max || 0 + leftcol_width = left.values.map(&:length).max || 0 rightcol_start = leftcol_width + 6 # spaces unless @order.size > 0 && @order.first.first == :text - stream.puts "#@version\n" if @version + stream.puts "#{@version}\n" if @version stream.puts _("Options:") end @@ -584,7 +584,10 @@ def each_arg args i += 1 when /^--(\S+)$/ # long argument params = collect_argument_parameters(args, i + 1) - unless params.empty? + if params.empty? # long argument no parameter + yield args[i], nil + i += 1 + else num_params_taken = yield args[i], params unless num_params_taken if @stop_on_unknown @@ -595,16 +598,16 @@ def each_arg args end end i += 1 + num_params_taken - else # long argument no parameter - yield args[i], nil - i += 1 end when /^-(\S+)$/ # one or more short arguments shortargs = ::Regexp.last_match(1).split(//) shortargs.each_with_index do |a, j| if j == (shortargs.length - 1) params = collect_argument_parameters(args, i + 1) - unless params.empty? + if params.empty? # argument no parameter + yield "-#{a}", nil + i += 1 + else num_params_taken = yield "-#{a}", params unless num_params_taken if @stop_on_unknown @@ -615,9 +618,6 @@ def each_arg args end end i += 1 + num_params_taken - else # argument no parameter - yield "-#{a}", nil - i += 1 end else yield "-#{a}", nil @@ -665,7 +665,7 @@ def parse_io_parameter param, arg def collect_argument_parameters args, start_at params = [] pos = start_at - while args[pos] && args[pos] !~ PARAM_RE && !@stop_words.member?(args[pos]) do + while args[pos] && args[pos] !~ PARAM_RE && !@stop_words.member?(args[pos]) params << args[pos] pos += 1 end diff --git a/lib/puppet/util/constant_inflector.rb b/lib/puppet/util/constant_inflector.rb index 8522c16ab4c..d950de6c91e 100644 --- a/lib/puppet/util/constant_inflector.rb +++ b/lib/puppet/util/constant_inflector.rb @@ -12,7 +12,7 @@ module Puppet module Util module ConstantInflector def file2constant(file) - file.split("/").collect { |name| name.capitalize }.join("::").gsub(/_+(.)/) { |_term| ::Regexp.last_match(1).capitalize } + file.split("/").collect(&:capitalize).join("::").gsub(/_+(.)/) { |_term| ::Regexp.last_match(1).capitalize } end module_function :file2constant diff --git a/lib/puppet/util/diff.rb b/lib/puppet/util/diff.rb index 5e62ee08cb4..fd72013ac90 100644 --- a/lib/puppet/util/diff.rb +++ b/lib/puppet/util/diff.rb @@ -32,8 +32,8 @@ def lcs_diff(data_old, data_new, format = :unified, context_lines = 3) Puppet.warning _("Cannot provide diff without the diff/lcs Ruby library") return "" end - data_old = data_old.split(/\n/).map! { |e| e.chomp } - data_new = data_new.split(/\n/).map! { |e| e.chomp } + data_old = data_old.split(/\n/).map!(&:chomp) + data_new = data_new.split(/\n/).map!(&:chomp) output = ''.dup diff --git a/lib/puppet/util/docs.rb b/lib/puppet/util/docs.rb index 61ece32fceb..83555b438f9 100644 --- a/lib/puppet/util/docs.rb +++ b/lib/puppet/util/docs.rb @@ -125,7 +125,7 @@ def scrub(text) text = text.gsub(/^#{indent}/, '') end # Clean trailing space - text.lines.map { |line| line.rstrip }.join("\n").rstrip + text.lines.map(&:rstrip).join("\n").rstrip end module_function :scrub diff --git a/lib/puppet/util/fileparsing.rb b/lib/puppet/util/fileparsing.rb index c6db6f8b233..6cc328c7d44 100644 --- a/lib/puppet/util/fileparsing.rb +++ b/lib/puppet/util/fileparsing.rb @@ -121,9 +121,7 @@ def join(details) # Customize this so we can do a bit of validation. def optional=(optional) - @optional = optional.collect do |field| - field.intern - end + @optional = optional.collect(&:intern) end # Create a hook that modifies the hash resulting from parsing. diff --git a/lib/puppet/util/inifile.rb b/lib/puppet/util/inifile.rb index 98a4655ce68..6444d798c16 100644 --- a/lib/puppet/util/inifile.rb +++ b/lib/puppet/util/inifile.rb @@ -275,9 +275,7 @@ def read(file) end def store - @files.values.each do |file| - file.store - end + @files.values.each(&:store) end def each_section(&block) diff --git a/lib/puppet/util/ldap/connection.rb b/lib/puppet/util/ldap/connection.rb index 972244d05ab..0dbeb66d87b 100644 --- a/lib/puppet/util/ldap/connection.rb +++ b/lib/puppet/util/ldap/connection.rb @@ -48,7 +48,7 @@ def initialize(host, port, user: nil, password: nil, reset: nil, ssl: nil) # Create a per-connection unique name. def name - [host, port, user, password, ssl].collect { |p| p.to_s }.join("/") + [host, port, user, password, ssl].collect(&:to_s).join("/") end # Should we reset the connection? diff --git a/lib/puppet/util/ldap/manager.rb b/lib/puppet/util/ldap/manager.rb index f1a08e85a61..b94398b17c2 100644 --- a/lib/puppet/util/ldap/manager.rb +++ b/lib/puppet/util/ldap/manager.rb @@ -31,7 +31,7 @@ def create(name, attributes) attributes = attributes.dup # Add the objectclasses - attributes["objectClass"] = objectclasses.collect { |o| o.to_s } + attributes["objectClass"] = objectclasses.collect(&:to_s) attributes["objectClass"] << "top" unless attributes["objectClass"].include?("top") attributes[rdn.to_s] = [name] @@ -151,7 +151,7 @@ def generate(values) end result = [result] unless result.is_a?(Array) - result = result.collect { |r| r.to_s } + result = result.collect(&:to_s) values[generator.name] = result end @@ -276,7 +276,7 @@ def valid? # getting rid of :ensure and making sure everything's an array of strings. def ldap_convert(attributes) attributes.reject { |param, value| value == :absent or param == :ensure }.each_with_object({}) do |ary, result| - value = (ary[1].is_a?(Array) ? ary[1] : [ary[1]]).collect { |v| v.to_s } + value = (ary[1].is_a?(Array) ? ary[1] : [ary[1]]).collect(&:to_s) result[ldap_name(ary[0])] = value end end diff --git a/lib/puppet/util/log/destinations.rb b/lib/puppet/util/log/destinations.rb index 5b32468b9cc..ddd5757b548 100644 --- a/lib/puppet/util/log/destinations.rb +++ b/lib/puppet/util/log/destinations.rb @@ -19,8 +19,8 @@ def initialize str = Puppet[:syslogfacility] begin facility = Syslog.const_get("LOG_#{str.upcase}") - rescue NameError - raise Puppet::Error, _("Invalid syslog facility %{str}") % { str: str }, $!.backtrace + rescue NameError => e + raise Puppet::Error, _("Invalid syslog facility %{str}") % { str: str }, e.backtrace end @syslog = Syslog.open(name, options, facility) diff --git a/lib/puppet/util/monkey_patches.rb b/lib/puppet/util/monkey_patches.rb index e4ad9e707c0..0f72188cc10 100644 --- a/lib/puppet/util/monkey_patches.rb +++ b/lib/puppet/util/monkey_patches.rb @@ -17,7 +17,7 @@ module RDoc def self.caller(skip = nil) in_gem_wrapper = false Kernel.caller.reject { |call| - in_gem_wrapper ||= call =~ /#{Regexp.escape $0}:\d+:in `load'/ + in_gem_wrapper ||= call =~ /#{Regexp.escape $PROGRAM_NAME}:\d+:in `load'/ } end end @@ -82,7 +82,7 @@ def set_default_paths unless @puppet_certs_loaded @puppet_certs_loaded = true - Puppet::Util::Windows::RootCerts.instance.to_a.uniq { |cert| cert.to_der }.each do |x509| + Puppet::Util::Windows::RootCerts.instance.to_a.uniq(&:to_der).each do |x509| add_cert(x509) rescue OpenSSL::X509::StoreError warn "Failed to add #{x509.subject.to_utf8}" diff --git a/lib/puppet/util/package/version/pip.rb b/lib/puppet/util/package/version/pip.rb index f8cbb2d8fc1..d30009d4207 100644 --- a/lib/puppet/util/package/version/pip.rb +++ b/lib/puppet/util/package/version/pip.rb @@ -59,7 +59,7 @@ def to_s parts.push(@pre_data.join) if @pre_data parts.push(".post#{@post_data[1]}") if @post_data parts.push(".dev#{@dev_data[1]}") if @dev_data - parts.push("+#{@local_data.join(".")}") if @local_data + parts.push("+#{@local_data.join('.')}") if @local_data parts.join end @@ -100,9 +100,9 @@ def parse_letter_version(letter, number) letter = "a" elsif letter == "beta" letter = "b" - elsif ["c", "pre", "preview"].include?(letter) + elsif %w[c pre preview].include?(letter) letter = "rc" - elsif ["rev", "r"].include?(letter) + elsif %w[rev r].include?(letter) letter = "post" end diff --git a/lib/puppet/util/posix.rb b/lib/puppet/util/posix.rb index 71cb241d6af..6c1121b4842 100644 --- a/lib/puppet/util/posix.rb +++ b/lib/puppet/util/posix.rb @@ -3,12 +3,12 @@ # Utility methods for interacting with POSIX objects; mostly user and group module Puppet::Util::POSIX # This is a list of environment variables that we will set when we want to override the POSIX locale - LOCALE_ENV_VARS = ['LANG', 'LC_ALL', 'LC_MESSAGES', 'LANGUAGE', - 'LC_COLLATE', 'LC_CTYPE', 'LC_MONETARY', 'LC_NUMERIC', 'LC_TIME'] + LOCALE_ENV_VARS = %w[LANG LC_ALL LC_MESSAGES LANGUAGE + LC_COLLATE LC_CTYPE LC_MONETARY LC_NUMERIC LC_TIME] # This is a list of user-related environment variables that we will unset when we want to provide a pristine # environment for "exec" runs - USER_ENV_VARS = ['HOME', 'USER', 'LOGNAME'] + USER_ENV_VARS = %w[HOME USER LOGNAME] class << self # Returns an array of all the groups that the user's a member of. diff --git a/lib/puppet/util/rdoc/generators/puppet_generator.rb b/lib/puppet/util/rdoc/generators/puppet_generator.rb index d79114c027e..ce2bb6dd13b 100644 --- a/lib/puppet/util/rdoc/generators/puppet_generator.rb +++ b/lib/puppet/util/rdoc/generators/puppet_generator.rb @@ -242,7 +242,7 @@ def gen_class_index gen_composite_index( file, RDoc::Page::COMBO_INDEX, - "#{MODULE_DIR}/fr_#{file["file"].context.module_name}.html" + "#{MODULE_DIR}/fr_#{file['file'].context.module_name}.html" ) end end diff --git a/lib/puppet/util/rdoc/parser/puppet_parser_core.rb b/lib/puppet/util/rdoc/parser/puppet_parser_core.rb index cdb03fe16b3..ddb9e4a4e08 100644 --- a/lib/puppet/util/rdoc/parser/puppet_parser_core.rb +++ b/lib/puppet/util/rdoc/parser/puppet_parser_core.rb @@ -106,7 +106,7 @@ def scan_top_level(container, environment) %w[README README.rdoc].each do |rfile| readme = File.join(File.dirname(File.dirname(@input_file_name)), rfile) # module README should be UTF-8, not default system encoding - comment = File.open(readme, "r:UTF-8") { |f| f.read } if FileTest.readable?(readme) + comment = File.open(readme, "r:UTF-8", &:read) if FileTest.readable?(readme) end look_for_directives_in(container, comment) unless comment.empty? diff --git a/lib/puppet/util/rpm_compare.rb b/lib/puppet/util/rpm_compare.rb index a10b7977015..75d89996555 100644 --- a/lib/puppet/util/rpm_compare.rb +++ b/lib/puppet/util/rpm_compare.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true +require 'English' module Puppet::Util::RpmCompare ARCH_LIST = %w[ noarch i386 i686 ppc ppc64 armv3l armv4b armv4l armv4tl armv5tel @@ -52,14 +53,14 @@ def rpmvercmp(str1, str2) # if the first char of str1 is a digit, grab the chunk of continuous digits from each string if str1 =~ /^[0-9]+/ if str1 =~ /^[0-9]+/ - segment1 = $~.to_s - str1 = $~.post_match + segment1 = $LAST_MATCH_INFO.to_s + str1 = $LAST_MATCH_INFO.post_match else segment1 = '' end if str2 =~ /^[0-9]+/ - segment2 = $~.to_s - str2 = $~.post_match + segment2 = $LAST_MATCH_INFO.to_s + str2 = $LAST_MATCH_INFO.post_match else segment2 = '' end @@ -67,14 +68,14 @@ def rpmvercmp(str1, str2) # else grab the chunk of continuous alphas from each string (which may be '') else if str1 =~ /^[A-Za-z]+/ - segment1 = $~.to_s - str1 = $~.post_match + segment1 = $LAST_MATCH_INFO.to_s + str1 = $LAST_MATCH_INFO.post_match else segment1 = '' end if str2 =~ /^[A-Za-z]+/ - segment2 = $~.to_s - str2 = $~.post_match + segment2 = $LAST_MATCH_INFO.to_s + str2 = $LAST_MATCH_INFO.post_match else segment2 = '' end diff --git a/lib/puppet/util/selinux.rb b/lib/puppet/util/selinux.rb index 44976924059..cd2c636f2e7 100644 --- a/lib/puppet/util/selinux.rb +++ b/lib/puppet/util/selinux.rb @@ -215,7 +215,7 @@ def selinux_label_support?(file) fstype = find_fs(file) return false if fstype.nil? - filesystems = ['ext2', 'ext3', 'ext4', 'gfs', 'gfs2', 'xfs', 'jfs', 'btrfs', 'tmpfs', 'zfs'] + filesystems = %w[ext2 ext3 ext4 gfs gfs2 xfs jfs btrfs tmpfs zfs] filesystems.include?(fstype) end diff --git a/lib/puppet/util/windows/adsi.rb b/lib/puppet/util/windows/adsi.rb index 61f31346c32..9f4df839406 100644 --- a/lib/puppet/util/windows/adsi.rb +++ b/lib/puppet/util/windows/adsi.rb @@ -377,12 +377,12 @@ def remove_from_groups(*group_names) alias remove_from_group remove_from_groups def add_group_sids(*sids) - group_names = sids.map { |s| s.domain_account } + group_names = sids.map(&:domain_account) add_to_groups(*group_names) end def remove_group_sids(*sids) - group_names = sids.map { |s| s.domain_account } + group_names = sids.map(&:domain_account) remove_from_groups(*group_names) end diff --git a/lib/puppet/util/windows/daemon.rb b/lib/puppet/util/windows/daemon.rb index 83ff582706e..4c8c949aee0 100644 --- a/lib/puppet/util/windows/daemon.rb +++ b/lib/puppet/util/windows/daemon.rb @@ -176,11 +176,11 @@ class Daemon SetEvent(@@hStartEvent) # Main loop for the service. - while WaitForSingleObject(@@hStopEvent, 1000) != WAIT_OBJECT_0 do + while WaitForSingleObject(@@hStopEvent, 1000) != WAIT_OBJECT_0 end # Main loop for the service. - while WaitForSingleObject(@@hStopCompletedEvent, 1000) != WAIT_OBJECT_0 do + while WaitForSingleObject(@@hStopCompletedEvent, 1000) != WAIT_OBJECT_0 end ensure # Stop the service. @@ -265,7 +265,7 @@ def mainloop events.put_pointer(0, FFI::Pointer.new(hThread)) events.put_pointer(FFI::Pointer.size, FFI::Pointer.new(@@hStartEvent)) - while (index = WaitForMultipleObjects(2, events, 0, 1000)) == WAIT_TIMEOUT do + while (index = WaitForMultipleObjects(2, events, 0, 1000)) == WAIT_TIMEOUT end if index == WAIT_FAILED diff --git a/lib/puppet/util/windows/registry.rb b/lib/puppet/util/windows/registry.rb index 6c0d7579d63..90966eaedc4 100644 --- a/lib/puppet/util/windows/registry.rb +++ b/lib/puppet/util/windows/registry.rb @@ -21,8 +21,8 @@ module Registry def root(name) Win32::Registry.const_get(name) - rescue NameError - raise Puppet::Error, _("Invalid registry key '%{name}'") % { name: name }, $!.backtrace + rescue NameError => e + raise Puppet::Error, _("Invalid registry key '%{name}'") % { name: name }, e.backtrace end def open(name, path, mode = KEY_READ | KEY64, &block) @@ -203,7 +203,7 @@ def reg_query_info_key_max_lengths(key) result = [ # Unicode characters *not* including trailing NULL max_subkey_name_length_ptr.read_dword + 1, - max_value_name_length_ptr.read_dword + 1, + max_value_name_length_ptr.read_dword + 1 ] end end diff --git a/lib/puppet/util/windows/service.rb b/lib/puppet/util/windows/service.rb index cbccb438ce9..e451e4c6eea 100644 --- a/lib/puppet/util/windows/service.rb +++ b/lib/puppet/util/windows/service.rb @@ -541,7 +541,7 @@ def set_optional_parameter(service_name, change, value) success = ChangeServiceConfig2W( service, change, # dwInfoLevel - value, # lpInfo + value # lpInfo ) if success == FFI::WIN32_FALSE raise Puppet::Util.windows::Error, _("Failed to update service %{change} configuration") % { change: change } diff --git a/util/rspec_grouper b/util/rspec_grouper index 71721ee840a..71b08e07767 100755 --- a/util/rspec_grouper +++ b/util/rspec_grouper @@ -69,7 +69,7 @@ def print_usage puts 'usage: rspec_grouper ' end -if __FILE__ == $0 +if __FILE__ == $PROGRAM_NAME if ARGV.length != 1 print_usage else diff --git a/util/rspec_runner b/util/rspec_runner index 611a5898870..842ec1d3ef4 100755 --- a/util/rspec_runner +++ b/util/rspec_runner @@ -54,7 +54,7 @@ def print_usage puts 'usage: rspec_runner []' end -if __FILE__ == $0 +if __FILE__ == $PROGRAM_NAME if ARGV.length < 1 print_usage elsif ARGV.length == 1