From 6c257fc7827989c2af2901f974666f0f23611153 Mon Sep 17 00:00:00 2001 From: Jorie Tappa Date: Mon, 24 Sep 2018 15:10:09 -0500 Subject: [PATCH] (maint) Fix simple Lint/AssignmentInConditional rubocop violations. --- .rubocop.yml | 6 - benchmarks/evaluations/benchmarker.rb | 3 +- ext/yaml_nodes.rb | 14 +- lib/hiera_puppet.rb | 3 +- lib/puppet/application/apply.rb | 5 +- lib/puppet/application/doc.rb | 3 +- lib/puppet/application/face_base.rb | 37 +++-- lib/puppet/application/script.rb | 10 +- lib/puppet/configurer.rb | 15 +- lib/puppet/confine_collection.rb | 3 +- lib/puppet/daemon.rb | 5 +- lib/puppet/environments.rb | 9 +- lib/puppet/etc.rb | 2 +- lib/puppet/external/pson/pure/parser.rb | 3 +- lib/puppet/face/epp.rb | 6 +- lib/puppet/face/help.rb | 5 +- lib/puppet/face/module/changes.rb | 3 +- lib/puppet/file_bucket/dipper.rb | 3 +- lib/puppet/file_serving/configuration.rb | 3 +- lib/puppet/file_serving/fileset.rb | 2 +- lib/puppet/file_serving/http_metadata.rb | 6 +- lib/puppet/file_serving/metadata.rb | 3 +- lib/puppet/file_serving/mount/file.rb | 3 +- lib/puppet/file_serving/mount/locales.rb | 3 +- lib/puppet/file_serving/mount/modules.rb | 6 +- lib/puppet/file_serving/mount/pluginfacts.rb | 3 +- lib/puppet/file_serving/mount/plugins.rb | 3 +- lib/puppet/file_serving/mount/tasks.rb | 6 +- lib/puppet/file_system/uniquefile.rb | 6 +- lib/puppet/functions/match.rb | 5 +- lib/puppet/generate/type.rb | 3 +- lib/puppet/graph/relationship_graph.rb | 3 +- lib/puppet/graph/simple_graph.rb | 5 +- lib/puppet/indirector/catalog/compiler.rb | 24 ++-- lib/puppet/indirector/certificate/rest.rb | 3 +- lib/puppet/indirector/face.rb | 4 +- lib/puppet/indirector/file_server.rb | 6 +- lib/puppet/indirector/indirection.rb | 18 ++- lib/puppet/indirector/node/exec.rb | 3 +- lib/puppet/indirector/report/processor.rb | 3 +- lib/puppet/indirector/request.rb | 14 +- lib/puppet/indirector/ssl_file.rb | 18 +-- lib/puppet/indirector/terminus.rb | 9 +- lib/puppet/interface.rb | 3 +- lib/puppet/interface/action.rb | 15 +- lib/puppet/interface/action_manager.rb | 3 +- lib/puppet/interface/documentation.rb | 17 ++- lib/puppet/interface/face_collection.rb | 9 +- lib/puppet/interface/option.rb | 6 +- lib/puppet/interface/option_manager.rb | 6 +- lib/puppet/module_tool.rb | 3 +- .../module_tool/applications/application.rb | 3 +- .../module_tool/applications/installer.rb | 6 +- .../module_tool/applications/upgrader.rb | 6 +- .../module_tool/contents_description.rb | 3 +- lib/puppet/module_tool/metadata.rb | 5 +- lib/puppet/module_tool/shared_behaviors.rb | 3 +- lib/puppet/network/authconfig.rb | 6 +- lib/puppet/network/authstore.rb | 3 +- lib/puppet/network/formats.rb | 3 +- .../network/http/api/indirected_routes.rb | 6 +- lib/puppet/network/http/handler.rb | 3 +- lib/puppet/network/http/request.rb | 3 +- lib/puppet/network/http/route.rb | 3 +- lib/puppet/network/resolver.rb | 5 +- lib/puppet/network/rights.rb | 3 +- lib/puppet/node.rb | 12 +- lib/puppet/pal/compiler.rb | 3 +- lib/puppet/pal/script_compiler.rb | 6 +- lib/puppet/parameter.rb | 6 +- lib/puppet/parameter/value_collection.rb | 16 +-- lib/puppet/parser/ast/pops_bridge.rb | 3 +- lib/puppet/parser/compiler.rb | 15 +- lib/puppet/parser/files.rb | 3 +- lib/puppet/parser/functions.rb | 3 +- lib/puppet/parser/relationship.rb | 3 +- lib/puppet/parser/resource.rb | 9 +- lib/puppet/parser/scope.rb | 10 +- lib/puppet/parser/templatewrapper.rb | 3 +- lib/puppet/parser/type_loader.rb | 3 +- lib/puppet/pops/adaptable.rb | 7 +- .../collectors/exported_collector.rb | 3 +- .../collectors/fixed_set_collector.rb | 3 +- .../evaluator/runtime3_resource_support.rb | 3 +- lib/puppet/pops/evaluator/runtime3_support.rb | 12 +- lib/puppet/pops/loader/base_loader.rb | 6 +- lib/puppet/pops/loader/dependency_loader.rb | 6 +- lib/puppet/pops/loader/gem_support.rb | 6 +- lib/puppet/pops/loader/loader.rb | 6 +- lib/puppet/pops/loader/loader_paths.rb | 3 +- lib/puppet/pops/loader/static_loader.rb | 2 +- lib/puppet/pops/lookup/interpolation.rb | 3 +- lib/puppet/pops/model/factory.rb | 6 +- lib/puppet/pops/parser/epp_support.rb | 3 +- lib/puppet/pops/parser/heredoc_support.rb | 3 +- .../pops/parser/interpolation_support.rb | 15 +- lib/puppet/pops/parser/lexer2.rb | 9 +- lib/puppet/pops/parser/locator.rb | 3 +- lib/puppet/pops/types/type_calculator.rb | 2 +- lib/puppet/pops/types/type_parser.rb | 6 +- lib/puppet/pops/validation.rb | 3 +- lib/puppet/pops/validation/checker4_0.rb | 9 +- lib/puppet/pops/visitor.rb | 18 ++- lib/puppet/property.rb | 35 ++--- lib/puppet/property/ensure.rb | 3 +- lib/puppet/property/keyvalue.rb | 3 +- lib/puppet/property/list.rb | 3 +- lib/puppet/provider.rb | 17 +-- lib/puppet/provider/exec.rb | 11 +- lib/puppet/provider/file/posix.rb | 9 +- lib/puppet/provider/group/groupadd.rb | 3 +- lib/puppet/provider/group/ldap.rb | 11 +- lib/puppet/provider/group/pw.rb | 6 +- lib/puppet/provider/ldap.rb | 12 +- lib/puppet/provider/nameservice.rb | 13 +- .../provider/nameservice/directoryservice.rb | 12 +- lib/puppet/provider/network_device.rb | 6 +- lib/puppet/provider/package.rb | 3 +- lib/puppet/provider/package/aix.rb | 6 +- lib/puppet/provider/package/appdmg.rb | 6 +- lib/puppet/provider/package/apple.rb | 3 +- lib/puppet/provider/package/apt.rb | 6 +- lib/puppet/provider/package/blastwave.rb | 3 +- lib/puppet/provider/package/dpkg.rb | 9 +- lib/puppet/provider/package/fink.rb | 3 +- lib/puppet/provider/package/gem.rb | 6 +- lib/puppet/provider/package/macports.rb | 9 +- lib/puppet/provider/package/nim.rb | 12 +- lib/puppet/provider/package/openbsd.rb | 22 +-- lib/puppet/provider/package/opkg.rb | 3 +- lib/puppet/provider/package/pacman.rb | 3 +- lib/puppet/provider/package/pkgdmg.rb | 6 +- lib/puppet/provider/package/pkgng.rb | 6 +- lib/puppet/provider/package/pkgutil.rb | 3 +- lib/puppet/provider/package/portupgrade.rb | 3 +- lib/puppet/provider/package/rpm.rb | 12 +- .../provider/package/windows/package.rb | 3 +- lib/puppet/provider/parsedfile.rb | 21 ++- lib/puppet/provider/service/base.rb | 11 +- lib/puppet/provider/service/launchd.rb | 6 +- lib/puppet/provider/service/service.rb | 3 +- lib/puppet/provider/service/upstart.rb | 19 +-- lib/puppet/provider/user/directoryservice.rb | 3 +- lib/puppet/provider/user/hpux.rb | 2 +- lib/puppet/provider/user/ldap.rb | 12 +- lib/puppet/provider/user/openbsd.rb | 3 +- lib/puppet/provider/user/pw.rb | 3 +- lib/puppet/provider/user/user_role_add.rb | 6 +- lib/puppet/provider/user/useradd.rb | 11 +- lib/puppet/reference/providers.rb | 3 +- lib/puppet/reference/type.rb | 6 +- lib/puppet/relationship.rb | 13 +- lib/puppet/resource.rb | 21 ++- lib/puppet/resource/capability_finder.rb | 20 +-- lib/puppet/resource/catalog.rb | 76 +++++----- lib/puppet/resource/type.rb | 10 +- lib/puppet/resource/type_collection.rb | 6 +- lib/puppet/settings.rb | 55 +++++--- lib/puppet/settings/base_setting.rb | 3 +- lib/puppet/settings/config_file.rb | 3 +- lib/puppet/settings/file_setting.rb | 3 +- lib/puppet/settings/ini_file.rb | 3 +- lib/puppet/ssl/base.rb | 3 +- lib/puppet/ssl/host.rb | 24 ++-- lib/puppet/ssl/key.rb | 4 +- lib/puppet/transaction/event.rb | 3 +- lib/puppet/transaction/event_manager.rb | 6 +- lib/puppet/transaction/report.rb | 20 +-- lib/puppet/transaction/resource_harness.rb | 6 +- lib/puppet/type.rb | 132 +++++++++++------- lib/puppet/type/component.rb | 3 +- lib/puppet/type/exec.rb | 12 +- lib/puppet/type/file.rb | 24 ++-- lib/puppet/type/file/content.rb | 10 +- lib/puppet/type/file/ctime.rb | 3 +- lib/puppet/type/file/data_sync.rb | 3 +- lib/puppet/type/file/ensure.rb | 17 ++- lib/puppet/type/file/mode.rb | 3 +- lib/puppet/type/file/mtime.rb | 3 +- lib/puppet/type/file/selcontext.rb | 3 +- lib/puppet/type/file/source.rb | 15 +- lib/puppet/type/file/target.rb | 3 +- lib/puppet/type/file/type.rb | 3 +- lib/puppet/type/package.rb | 9 +- lib/puppet/type/resources.rb | 3 +- lib/puppet/type/service.rb | 3 +- lib/puppet/type/tidy.rb | 21 ++- lib/puppet/type/user.rb | 20 ++- lib/puppet/util.rb | 9 +- lib/puppet/util/checksums.rb | 2 +- lib/puppet/util/classgen.rb | 18 ++- lib/puppet/util/command_line.rb | 12 +- lib/puppet/util/connection.rb | 6 +- lib/puppet/util/diff.rb | 6 +- lib/puppet/util/execution.rb | 6 +- lib/puppet/util/feature.rb | 11 +- lib/puppet/util/fileparsing.rb | 103 ++++++++------ lib/puppet/util/filetype.rb | 3 +- lib/puppet/util/http_proxy.rb | 3 +- lib/puppet/util/instance_loader.rb | 3 +- lib/puppet/util/ldap/connection.rb | 6 +- lib/puppet/util/ldap/manager.rb | 9 +- lib/puppet/util/log.rb | 9 +- lib/puppet/util/metric.rb | 3 +- lib/puppet/util/posix.rb | 6 +- lib/puppet/util/rdoc/code_objects.rb | 3 +- .../util/rdoc/generators/puppet_generator.rb | 6 +- lib/puppet/util/selinux.rb | 3 +- lib/puppet/version.rb | 5 +- spec/lib/puppet_spec/modules.rb | 6 +- spec/unit/indirector/request_spec.rb | 11 +- 211 files changed, 1144 insertions(+), 706 deletions(-) diff --git a/.rubocop.yml b/.rubocop.yml index 093fa4bb826..f398c0facb0 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -60,12 +60,6 @@ Style/RedundantParentheses: Lint/AmbiguousOperator: Enabled: false -# DISABLED since for all the checked, we are basically checking nil -# TODO: Change the checking so that if the variable being assigned to has -# a value ALREADY, then raise an error. -Lint/AssignmentInCondition: - Enabled: false - # DISABLED - not useful Layout/SpaceBeforeComment: Enabled: false diff --git a/benchmarks/evaluations/benchmarker.rb b/benchmarks/evaluations/benchmarker.rb index 3fa4558f550..8cc7f2c04d6 100644 --- a/benchmarks/evaluations/benchmarker.rb +++ b/benchmarks/evaluations/benchmarker.rb @@ -45,7 +45,8 @@ def run(args = {}) measurements = [] @micro_benchmarks.each do |name, source| # skip if all but the wanted if a single benchmark is wanted - next unless details == 'all' || match = details.match(/#{name}(?:[\._\s](parse|eval))?$/) + match = details.match(/#{name}(?:[\._\s](parse|eval))?$/) + next unless details == 'all' || match # if name ends with .parse or .eval only do that part, else do both parts ending = match ? match[1] : nil # parse, eval or nil ending unless ending == 'eval' diff --git a/ext/yaml_nodes.rb b/ext/yaml_nodes.rb index 7bd4433beb4..e7d8f9794b1 100755 --- a/ext/yaml_nodes.rb +++ b/ext/yaml_nodes.rb @@ -74,7 +74,7 @@ def read_node(node) # Iterate over any provided parents, merging in there information. parents_seen = [] -while parent = info["parent"] +while parent = info["parent"] #rubocop:disable Lint/AssignmentInCondition raise "Found inheritance loop with parent #{parent}" if parents_seen.include?(parent) parents_seen << parent @@ -84,21 +84,21 @@ def read_node(node) parent_info = read_node(parent) # Include any parent classes in our list. - if pclasses = parent_info["classes"] - info["classes"] += pclasses + if parent_info["classes"] + info["classes"] += parent_info["classes"] info["classes"].uniq! end # And inherit parameters from our parent, while preferring our own values. - if pparams = parent_info["parameters"] + if parent_info["parameters"] # When using Hash#merge, the hash being merged in wins, and we # want the subnode parameters to be the parent node parameters. - info["parameters"] = pparams.merge(info["parameters"]) + info["parameters"] = parent_info["parameters"].merge(info["parameters"]) end # Copy over any parent node name. - if pparent = parent_info["parent"] - info["parent"] = pparent + if parent_info["parent"] + info["parent"] = parent_info["parent"] end end diff --git a/lib/hiera_puppet.rb b/lib/hiera_puppet.rb index a2f749b6bb2..9b1e3581995 100644 --- a/lib/hiera_puppet.rb +++ b/lib/hiera_puppet.rb @@ -58,7 +58,8 @@ def hiera def hiera_config config = {} - if config_file = hiera_config_file + config_file = hiera_config_file + if config_file config = Hiera::Config.load(config_file) end diff --git a/lib/puppet/application/apply.rb b/lib/puppet/application/apply.rb index 1a9b897e5d6..8ec9815178a 100644 --- a/lib/puppet/application/apply.rb +++ b/lib/puppet/application/apply.rb @@ -349,9 +349,8 @@ def get_facts() facts = nil unless Puppet[:node_name_fact].empty? # Collect our facts. - unless facts = Puppet::Node::Facts.indirection.find(Puppet[:node_name_value]) - raise _("Could not find facts for %{node}") % { node: Puppet[:node_name_value] } - end + facts = Puppet::Node::Facts.indirection.find(Puppet[:node_name_value]) + raise _("Could not find facts for %{node}") % { node: Puppet[:node_name_value] } unless facts Puppet[:node_name_value] = facts.values[Puppet[:node_name_fact]] facts.name = Puppet[:node_name_value] diff --git a/lib/puppet/application/doc.rb b/lib/puppet/application/doc.rb index b93745e450d..cc9c3668e3c 100644 --- a/lib/puppet/application/doc.rb +++ b/lib/puppet/application/doc.rb @@ -156,7 +156,8 @@ def other exit_code = 0 require 'puppet/util/reference' options[:references].sort { |a,b| a.to_s <=> b.to_s }.each do |name| - raise _("Could not find reference %{name}") % { name: name } unless section = Puppet::Util::Reference.reference(name) + section = Puppet::Util::Reference.reference(name) + raise _("Could not find reference %{name}") % { name: name } unless section begin # Add the per-section text, but with no ToC diff --git a/lib/puppet/application/face_base.rb b/lib/puppet/application/face_base.rb index 1faba2c9001..c763e27657e 100644 --- a/lib/puppet/application/face_base.rb +++ b/lib/puppet/application/face_base.rb @@ -74,32 +74,38 @@ def parse_options index = -1 until action_name or (index += 1) >= command_line.args.length do item = command_line.args[index] - if item =~ /^-/ then + if item =~ /^-/ option = @face.options.find do |name| item =~ /^-+#{name.to_s.gsub(/[-_]/, '[-_]')}(?:[ =].*)?$/ end - if option then + if option option = @face.get_option(option) # If we have an inline argument, just carry on. We don't need to # care about optional vs mandatory in that case because we do a real # parse later, and that will totally take care of raising the error # when we get there. --daniel 2011-04-04 - if option.takes_argument? and !item.index('=') then + if option.takes_argument? and !item.index('=') index += 1 unless (option.optional_argument? and command_line.args[index + 1] =~ /^-/) end - elsif option = find_global_settings_argument(item) then - unless Puppet.settings.boolean? option.name then - # As far as I can tell, we treat non-bool options as always having - # a mandatory argument. --daniel 2011-04-05 - # ... But, the mandatory argument will not be the next item if an = is - # employed in the long form of the option. --jeffmccune 2012-09-18 - index += 1 unless item =~ /^--#{option.name}=/ - end - elsif option = find_application_argument(item) then - index += 1 if (option[:argument] and not option[:optional]) else - raise OptionParser::InvalidOption.new(item.sub(/=.*$/, '')) + option = find_global_settings_argument(item) + if option + unless Puppet.settings.boolean? option.name + # As far as I can tell, we treat non-bool options as always having + # a mandatory argument. --daniel 2011-04-05 + # ... But, the mandatory argument will not be the next item if an = is + # employed in the long form of the option. --jeffmccune 2012-09-18 + index += 1 unless item =~ /^--#{option.name}=/ + end + else + option = find_application_argument(item) + if option + index += 1 if (option[:argument] and not option[:optional]) + else + raise OptionParser::InvalidOption.new(item.sub(/=.*$/, '')) + end + end end else # Stash away the requested action name for later, and try to fetch the @@ -112,7 +118,8 @@ def parse_options end if @action.nil? - if @action = @face.get_default_action() then + @action = @face.get_default_action() + if @action @is_default_action = true else # First try to handle global command line options diff --git a/lib/puppet/application/script.rb b/lib/puppet/application/script.rb index f46898b73b1..18d7c84003f 100644 --- a/lib/puppet/application/script.rb +++ b/lib/puppet/application/script.rb @@ -140,18 +140,16 @@ def main unless Puppet[:node_name_fact].empty? # Collect the facts specified for that node - unless facts = Puppet::Node::Facts.indirection.find(Puppet[:node_name_value]) - raise _("Could not find facts for %{node}") % { node: Puppet[:node_name_value] } - end + facts = Puppet::Node::Facts.indirection.find(Puppet[:node_name_value]) + raise _("Could not find facts for %{node}") % { node: Puppet[:node_name_value] } unless facts Puppet[:node_name_value] = facts.values[Puppet[:node_name_fact]] facts.name = Puppet[:node_name_value] end # Find the Node - unless node = Puppet::Node.indirection.find(Puppet[:node_name_value]) - raise _("Could not find node %{node}") % { node: Puppet[:node_name_value] } - end + node = Puppet::Node.indirection.find(Puppet[:node_name_value]) + raise _("Could not find node %{node}") % { node: Puppet[:node_name_value] } unless node configured_environment = node.environment || Puppet.lookup(:current_environment) diff --git a/lib/puppet/configurer.rb b/lib/puppet/configurer.rb index 278b16eba31..9afbad4fe16 100644 --- a/lib/puppet/configurer.rb +++ b/lib/puppet/configurer.rb @@ -67,7 +67,8 @@ def initialize(transaction_uuid = nil, job_id = nil) # Get the remote catalog, yo. Returns nil if no catalog can be found. def retrieve_catalog(query_options) query_options ||= {} - if (Puppet[:use_cached_catalog] && result = retrieve_catalog_from_cache(query_options)) + result = retrieve_catalog_from_cache(query_options) if Puppet[:use_cached_catalog] + if result @cached_catalog_status = 'explicitly_requested' Puppet.info _("Using cached catalog from environment '%{environment}'") % { environment: result.environment } @@ -104,7 +105,8 @@ def convert_catalog(result, duration, options = {}) catalog_conversion_time = thinmark do # Will mutate the result and replace all Deferred values with resolved values - if facts = options[:convert_with_facts] + facts = options[:convert_with_facts] + if facts Puppet::Pops::Evaluator::DeferredResolver.resolve_and_replace(facts, result) end @@ -257,7 +259,8 @@ def run_internal(options) Puppet::GettextConfig.reset_text_domain('agent') Puppet::ModuleTranslations.load_from_vardir(Puppet[:vardir]) - if catalog = prepare_and_retrieve_catalog_from_cache(options) + catalog = prepare_and_retrieve_catalog_from_cache(options) + if catalog options[:catalog] = catalog @cached_catalog_status = 'explicitly_requested' @@ -339,7 +342,8 @@ def run_internal(options) query_options[:configured_environment] = configured_environment options[:convert_for_node] = node - unless catalog = prepare_and_retrieve_catalog(options, query_options) + catalog = prepare_and_retrieve_catalog(options, query_options) + unless catalog return nil end @@ -364,7 +368,8 @@ def run_internal(options) query_options = get_facts(options) query_options[:configured_environment] = configured_environment - return nil unless catalog = prepare_and_retrieve_catalog(options, query_options) + catalog = prepare_and_retrieve_catalog(options, query_options) + return nil unless catalog tries += 1 end diff --git a/lib/puppet/confine_collection.rb b/lib/puppet/confine_collection.rb index 7a2eba8b488..daa24f36064 100644 --- a/lib/puppet/confine_collection.rb +++ b/lib/puppet/confine_collection.rb @@ -11,7 +11,8 @@ def confine(hash) for_binary = false end hash.each do |test, values| - if klass = Puppet::Confine.test(test) + klass = Puppet::Confine.test(test) + if klass @confines << klass.new(values) @confines[-1].for_binary = true if for_binary else diff --git a/lib/puppet/daemon.rb b/lib/puppet/daemon.rb index d0b167ca8d4..f1aaaf4ece5 100644 --- a/lib/puppet/daemon.rb +++ b/lib/puppet/daemon.rb @@ -38,7 +38,8 @@ def daemonname # Put the daemon into the background. def daemonize - if pid = fork + pid = fork + if pid Process.detach(pid) exit(0) end @@ -181,7 +182,7 @@ def run_event_loop end signal_loop = Puppet::Scheduler.create_job(SIGNAL_CHECK_INTERVAL) do - while method = @signals.shift + while method = @signals.shift #rubocop:disable Lint/AssignmentInCondition Puppet.notice "Processing #{method}" send(method) end diff --git a/lib/puppet/environments.rb b/lib/puppet/environments.rb index 7a9b0b90069..e77269039ec 100644 --- a/lib/puppet/environments.rb +++ b/lib/puppet/environments.rb @@ -268,7 +268,8 @@ def list # @!macro loader_get def get(name) @loaders.each do |loader| - if env = loader.get(name) + env = loader.get(name) + if env return env end end @@ -278,7 +279,8 @@ def get(name) # @!macro loader_get_conf def get_conf(name) @loaders.each do |loader| - if conf = loader.get_conf(name) + conf = loader.get_conf(name) + if conf return conf end end @@ -349,7 +351,8 @@ def get(name) # This strategy favors smaller memory footprint over environment # retrieval time. clear_all_expired - if result = @cache[name] + result = @cache[name] + if result # found in cache return result.value elsif (result = @loader.get(name)) diff --git a/lib/puppet/etc.rb b/lib/puppet/etc.rb index da282792553..30973c7ee5d 100644 --- a/lib/puppet/etc.rb +++ b/lib/puppet/etc.rb @@ -115,7 +115,7 @@ def group setgrent begin - while cur_group = getgrent + while cur_group = getgrent #rubocop:disable Lint/AssignmentInCondition yield cur_group end ensure diff --git a/lib/puppet/external/pson/pure/parser.rb b/lib/puppet/external/pson/pure/parser.rb index 02943d83885..a48d7b4c30d 100644 --- a/lib/puppet/external/pson/pure/parser.rb +++ b/lib/puppet/external/pson/pure/parser.rb @@ -180,7 +180,8 @@ def parse_string if scan(STRING) return '' if self[1].empty? string = self[1].gsub(%r{(?:\\[\\bfnrt"/]|(?:\\u(?:[A-Fa-f\d]{4}))+|\\[\x20-\xff])}n) do |c| - if u = UNESCAPE_MAP[$MATCH[1]] + u = UNESCAPE_MAP[$MATCH[1]] + if u u else # \uXXXX bytes = '' diff --git a/lib/puppet/face/epp.rb b/lib/puppet/face/epp.rb index 9ba120ea740..662c02039b2 100644 --- a/lib/puppet/face/epp.rb +++ b/lib/puppet/face/epp.rb @@ -402,7 +402,8 @@ def dump_parse(source, filename, options, show_filename = true) def get_values(compiler, options) template_values = nil - if values_file = options[:values_file] + values_file = options[:values_file] + if values_file begin if values_file =~ /\.yaml$/ template_values = Puppet::Util::Yaml.safe_load_file(values_file, [Symbol]) @@ -420,7 +421,8 @@ def get_values(compiler, options) end end - if values = options[:values] + values = options[:values] + if values evaluating_parser = Puppet::Pops::Parser::EvaluatingParser.new result = evaluating_parser.evaluate_string(compiler.topscope, values, 'values-hash') case result diff --git a/lib/puppet/face/help.rb b/lib/puppet/face/help.rb index 2f0600d0286..b27860960b1 100644 --- a/lib/puppet/face/help.rb +++ b/lib/puppet/face/help.rb @@ -182,8 +182,9 @@ 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 - if md = /^puppet-#{appname}\([^\)]+\) -- (.*)$/.match(line) + while line = help.shift do #rubocop:disable Lint/AssignmentInCondition + md = /^puppet-#{appname}\([^\)]+\) -- (.*)$/.match(line) + if md return md[1] end end diff --git a/lib/puppet/face/module/changes.rb b/lib/puppet/face/module/changes.rb index 2e8a08e4c68..e7c1947c598 100644 --- a/lib/puppet/face/module/changes.rb +++ b/lib/puppet/face/module/changes.rb @@ -22,7 +22,8 @@ when_invoked do |path, options| Puppet::ModuleTool.set_option_defaults options - unless root_path = Puppet::ModuleTool.find_module_root(path) + root_path = Puppet::ModuleTool.find_module_root(path) + unless root_path raise ArgumentError, _("Could not find a valid module at %{path}") % { path: path.inspect } end Puppet::ModuleTool::Applications::Checksummer.run(root_path, options) diff --git a/lib/puppet/file_bucket/dipper.rb b/lib/puppet/file_bucket/dipper.rb index 2886260f11b..27ce6cb12d1 100644 --- a/lib/puppet/file_bucket/dipper.rb +++ b/lib/puppet/file_bucket/dipper.rb @@ -126,7 +126,8 @@ def restore(file, sum) end if restore - if newcontents = get_bucket_file(sum) + newcontents = get_bucket_file(sum) + if newcontents newsum = newcontents.checksum_data changed = nil if Puppet::FileSystem.exist?(file_handle) and ! Puppet::FileSystem.writable?(file_handle) diff --git a/lib/puppet/file_serving/configuration.rb b/lib/puppet/file_serving/configuration.rb index 7d8b9fd60aa..7b1d3501a57 100644 --- a/lib/puppet/file_serving/configuration.rb +++ b/lib/puppet/file_serving/configuration.rb @@ -55,7 +55,8 @@ def split_path(request) raise(ArgumentError, _("Cannot find file: Invalid mount '%{mount_name}'") % { mount_name: mount_name }) unless mount_name =~ %r{^[-\w]+$} raise(ArgumentError, _("Cannot find file: Invalid relative path '%{path}'") % { path: path }) if path and path.split('/').include?('..') - return nil unless mount = find_mount(mount_name, request.environment) + mount = find_mount(mount_name, request.environment) + return nil unless mount if mount.name == "modules" and mount_name != "modules" # yay backward-compatibility path = "#{mount_name}/#{path}" diff --git a/lib/puppet/file_serving/fileset.rb b/lib/puppet/file_serving/fileset.rb index 720ce904811..cbfcc751732 100644 --- a/lib/puppet/file_serving/fileset.rb +++ b/lib/puppet/file_serving/fileset.rb @@ -148,7 +148,7 @@ def perform_recursion result = [] - while entry = current_dirs.shift + while entry = current_dirs.shift #rubocop:disable Lint/AssignmentInCondition if continue_recursion_at?(entry.depth + 1) entry.children.each do |child| result << child.path diff --git a/lib/puppet/file_serving/http_metadata.rb b/lib/puppet/file_serving/http_metadata.rb index 8f07d738a18..c6930f2b86f 100644 --- a/lib/puppet/file_serving/http_metadata.rb +++ b/lib/puppet/file_serving/http_metadata.rb @@ -15,13 +15,15 @@ def initialize(http_response, path = '/dev/null') # use a default mtime in case there is no usable HTTP header @checksums[:mtime] = "{mtime}#{Time.now}" - if checksum = http_response['content-md5'] + checksum = http_response['content-md5'] + if checksum # convert base64 digest to hex checksum = checksum.unpack("m0").first.unpack("H*").first @checksums[:md5] = "{md5}#{checksum}" end - if last_modified = http_response['last-modified'] + last_modified = http_response['last-modified'] + if last_modified mtime = DateTime.httpdate(last_modified).to_time @checksums[:mtime] = "{mtime}#{mtime.utc}" end diff --git a/lib/puppet/file_serving/metadata.rb b/lib/puppet/file_serving/metadata.rb index 7956492ca67..03f079931b8 100644 --- a/lib/puppet/file_serving/metadata.rb +++ b/lib/puppet/file_serving/metadata.rb @@ -127,7 +127,8 @@ def initialize(path,data={}) @owner = data.delete('owner') @group = data.delete('group') @mode = data.delete('mode') - if checksum = data.delete('checksum') + checksum = data.delete('checksum') + if checksum @checksum_type = checksum['type'] @checksum = checksum['value'] end diff --git a/lib/puppet/file_serving/mount/file.rb b/lib/puppet/file_serving/mount/file.rb index 849cbd2344e..095da55a5ee 100644 --- a/lib/puppet/file_serving/mount/file.rb +++ b/lib/puppet/file_serving/mount/file.rb @@ -60,7 +60,8 @@ def path=(path) end def search(path, request) - return nil unless path = complete_path(path, request.node) + path = complete_path(path, request.node) + return nil unless path [path] end diff --git a/lib/puppet/file_serving/mount/locales.rb b/lib/puppet/file_serving/mount/locales.rb index f882e5971f6..191d7adb0ce 100644 --- a/lib/puppet/file_serving/mount/locales.rb +++ b/lib/puppet/file_serving/mount/locales.rb @@ -6,7 +6,8 @@ class Puppet::FileServing::Mount::Locales < Puppet::FileServing::Mount # Return an instance of the appropriate class. def find(relative_path, request) - return nil unless mod = request.environment.modules.find { |m| m.locale(relative_path) } + mod = request.environment.modules.find { |m| m.locale(relative_path) } + return nil unless mod path = mod.locale(relative_path) diff --git a/lib/puppet/file_serving/mount/modules.rb b/lib/puppet/file_serving/mount/modules.rb index 94d078a1dc0..c2ebdd5d5df 100644 --- a/lib/puppet/file_serving/mount/modules.rb +++ b/lib/puppet/file_serving/mount/modules.rb @@ -7,13 +7,15 @@ class Puppet::FileServing::Mount::Modules < Puppet::FileServing::Mount def find(path, request) raise _("No module specified") if path.to_s.empty? module_name, relative_path = path.split("/", 2) - return nil unless mod = request.environment.module(module_name) + mod = request.environment.module(module_name) + return nil unless mod mod.file(relative_path) end def search(path, request) - if result = find(path, request) + result = find(path, request) + if result [result] end end diff --git a/lib/puppet/file_serving/mount/pluginfacts.rb b/lib/puppet/file_serving/mount/pluginfacts.rb index eec00d087e2..9ef6e603036 100644 --- a/lib/puppet/file_serving/mount/pluginfacts.rb +++ b/lib/puppet/file_serving/mount/pluginfacts.rb @@ -6,7 +6,8 @@ class Puppet::FileServing::Mount::PluginFacts < Puppet::FileServing::Mount # Return an instance of the appropriate class. def find(relative_path, request) - return nil unless mod = request.environment.modules.find { |m| m.pluginfact(relative_path) } + mod = request.environment.modules.find { |m| m.pluginfact(relative_path) } + return nil unless mod path = mod.pluginfact(relative_path) diff --git a/lib/puppet/file_serving/mount/plugins.rb b/lib/puppet/file_serving/mount/plugins.rb index 60eb003c092..bb17b53d2dc 100644 --- a/lib/puppet/file_serving/mount/plugins.rb +++ b/lib/puppet/file_serving/mount/plugins.rb @@ -6,7 +6,8 @@ class Puppet::FileServing::Mount::Plugins < Puppet::FileServing::Mount # Return an instance of the appropriate class. def find(relative_path, request) - return nil unless mod = request.environment.modules.find { |m| m.plugin(relative_path) } + mod = request.environment.modules.find { |m| m.plugin(relative_path) } + return nil unless mod path = mod.plugin(relative_path) diff --git a/lib/puppet/file_serving/mount/tasks.rb b/lib/puppet/file_serving/mount/tasks.rb index 87a8d048a8a..e296fa79609 100644 --- a/lib/puppet/file_serving/mount/tasks.rb +++ b/lib/puppet/file_serving/mount/tasks.rb @@ -4,13 +4,15 @@ class Puppet::FileServing::Mount::Tasks < Puppet::FileServing::Mount def find(path, request) raise _("No task specified") if path.to_s.empty? module_name, task_path = path.split("/", 2) - return nil unless mod = request.environment.module(module_name) + mod = request.environment.module(module_name) + return nil unless mod mod.task_file(task_path) end def search(path, request) - if result = find(path, request) + result = find(path, request) + if result [result] end end diff --git a/lib/puppet/file_system/uniquefile.rb b/lib/puppet/file_system/uniquefile.rb index fdba62e7a48..07272e5d064 100644 --- a/lib/puppet/file_system/uniquefile.rb +++ b/lib/puppet/file_system/uniquefile.rb @@ -115,7 +115,8 @@ def make_tmpname(prefix_suffix, n) end def create_tmpname(basename, *rest) - if opts = try_convert_to_hash(rest[-1]) + opts = try_convert_to_hash(rest[-1]) + if opts opts = opts.dup if rest.pop.equal?(opts) max_try = opts.delete(:max_try) opts = [opts] @@ -157,7 +158,8 @@ def tmpdir @@systmpdir else for dir in [ Puppet::Util.get_env('TMPDIR'), Puppet::Util.get_env('TMP'), Puppet::Util.get_env('TEMP'), @@systmpdir, '/tmp'] - if dir and stat = File.stat(dir) and stat.directory? and stat.writable? + stat = File.stat(dir) if dir + if stat && stat.directory? && stat.writable? tmp = dir break end rescue nil diff --git a/lib/puppet/functions/match.rb b/lib/puppet/functions/match.rb index 26657cfa481..2df8879ddcf 100644 --- a/lib/puppet/functions/match.rb +++ b/lib/puppet/functions/match.rb @@ -124,8 +124,7 @@ def match_Array(array, s) private def do_match(s, regexp) - if result = regexp.match(s) - result.to_a - end + result = regexp.match(s) + result.to_a if result end end diff --git a/lib/puppet/generate/type.rb b/lib/puppet/generate/type.rb index 58f41fca52d..8dded6bde29 100644 --- a/lib/puppet/generate/type.rb +++ b/lib/puppet/generate/type.rb @@ -195,7 +195,8 @@ def self.generate(inputs, outputdir = nil, force = false) types ||= Puppet::Type.instance_variable_get('@types') # Assume the type follows the naming convention - unless type = types[type_name] + type = types[type_name] + unless type Puppet.err _("Custom type '%{type_name}' was not defined in '%{input}'.") % { type_name: type_name, input: input } next end diff --git a/lib/puppet/graph/relationship_graph.rb b/lib/puppet/graph/relationship_graph.rb index 3d734c9d888..fd9c273f5bc 100644 --- a/lib/puppet/graph/relationship_graph.rb +++ b/lib/puppet/graph/relationship_graph.rb @@ -104,7 +104,8 @@ def traverse(options = {}, &block) teardown = options[:teardown] || lambda {} graph_cycle_handler = options[:graph_cycle_handler] || lambda { [] } - if cycles = report_cycles_in_graph + cycles = report_cycles_in_graph + if cycles graph_cycle_handler.call(cycles) end diff --git a/lib/puppet/graph/simple_graph.rb b/lib/puppet/graph/simple_graph.rb index b944451cbde..dc4dd60bd8d 100644 --- a/lib/puppet/graph/simple_graph.rb +++ b/lib/puppet/graph/simple_graph.rb @@ -208,7 +208,7 @@ def paths_in_cycle(cycle, max_paths = 1) # frame struct is vertex, [path] stack = [[cycle.first, []]] - while frame = stack.shift do + while frame = stack.shift do #rubocop:disable Lint/AssignmentInCondition if frame[1].member?(frame[0]) then found << frame[1] + [frame[0]] break if found.length >= max_paths @@ -343,7 +343,8 @@ def remove_edge!(e) # Find adjacent edges. def adjacent(v, options = {}) - return [] unless ns = (options[:direction] == :in) ? @in_to[v] : @out_from[v] + ns = (options[:direction] == :in) ? @in_to[v] : @out_from[v] + return [] unless ns (options[:type] == :edges) ? ns.values.flatten : ns.keys end diff --git a/lib/puppet/indirector/catalog/compiler.rb b/lib/puppet/indirector/catalog/compiler.rb index 0cf92a2a493..179a4912e03 100644 --- a/lib/puppet/indirector/catalog/compiler.rb +++ b/lib/puppet/indirector/catalog/compiler.rb @@ -18,8 +18,10 @@ class Puppet::Resource::Catalog::Compiler < Puppet::Indirector::Code # (possibly) containing facts # @return [Puppet::Node::Facts] facts object corresponding to facts in request def extract_facts_from_request(request) - return unless text_facts = request.options[:facts] - unless format = request.options[:facts_format] + text_facts = request.options[:facts] + return unless text_facts + format = request.options[:facts_format] + unless format raise ArgumentError, _("Facts but no fact format provided for %{request}") % { request: request.key } end @@ -199,7 +201,8 @@ def inline_metadata(catalog, checksum_type) sources.each do |source| source = Puppet::Type.type(:file).attrclass(:source).normalize(source) - if list_of_data = Puppet::FileServing::Metadata.indirection.search(source, options) + list_of_data = Puppet::FileServing::Metadata.indirection.search(source, options) + if list_of_data basedir_meta = list_of_data.find {|meta| meta.relative_path == '.'} devfail "FileServing::Metadata search should always return the root search path" if basedir_meta.nil? @@ -243,7 +246,8 @@ def inline_metadata(catalog, checksum_type) sources.each do |source| source = Puppet::Type.type(:file).attrclass(:source).normalize(source) - if data = Puppet::FileServing::Metadata.indirection.find(source, options) + data = Puppet::FileServing::Metadata.indirection.find(source, options) + if data metadata = data metadata.source = source break @@ -362,7 +366,8 @@ def find_node(name, environment, transaction_uuid, configured_environment, facts # Extract the node from the request, or use the request # to find the node. def node_from_request(facts, request) - if node = request.options[:use_node] + node = request.options[:use_node] + if node if request.remote? raise Puppet::Error, _("Invalid option use_node for a remote request") else @@ -378,7 +383,8 @@ def node_from_request(facts, request) # node's catalog with only one certificate and a modification to auth.conf # If no key is provided we can only compile the currently connected node. name = request.key || request.node - if node = find_node(name, request.environment, request.options[:transaction_uuid], request.options[:configured_environment], facts) + node = find_node(name, request.environment, request.options[:transaction_uuid], request.options[:configured_environment], facts) + if node return node end @@ -397,7 +403,8 @@ def set_server_facts {"servername" => "fqdn", "serverip" => "ipaddress" }.each do |var, fact| - if value = Facter.value(fact) + value = Facter.value(fact) + if value @server_facts[var] = value else Puppet.warning _("Could not retrieve fact %{fact}") % { fact: fact } @@ -406,7 +413,8 @@ def set_server_facts if @server_facts["servername"].nil? host = Facter.value(:hostname) - if domain = Facter.value(:domain) + domain = Facter.value(:domain) + if domain @server_facts["servername"] = [host, domain].join(".") else @server_facts["servername"] = host diff --git a/lib/puppet/indirector/certificate/rest.rb b/lib/puppet/indirector/certificate/rest.rb index ab18b3542b7..1c61664da53 100644 --- a/lib/puppet/indirector/certificate/rest.rb +++ b/lib/puppet/indirector/certificate/rest.rb @@ -9,7 +9,8 @@ class Puppet::SSL::Certificate::Rest < Puppet::Indirector::REST use_srv_service(:ca) def find(request) - return nil unless result = super + result = super + return nil unless result result.name = request.key unless result.name == request.key result end diff --git a/lib/puppet/indirector/face.rb b/lib/puppet/indirector/face.rb index 34ee9541b2e..6e6d1d443d2 100644 --- a/lib/puppet/indirector/face.rb +++ b/lib/puppet/indirector/face.rb @@ -112,8 +112,8 @@ def call_indirection_method(method, key, options) EOT when_invoked do |options| - if t = indirection.terminus_class - _("Run mode '%{mode}': %{terminus}") % { mode: Puppet.run_mode.name, terminus: t } + if indirection.terminus_class + _("Run mode '%{mode}': %{terminus}") % { mode: Puppet.run_mode.name, terminus: indirection.terminus_class } else _("No default terminus class for run mode '%{mode}'") % { mode: Puppet.run_mode.name } end diff --git a/lib/puppet/indirector/file_server.rb b/lib/puppet/indirector/file_server.rb index 1b4f18f9163..9ecbf5ad0d9 100644 --- a/lib/puppet/indirector/file_server.rb +++ b/lib/puppet/indirector/file_server.rb @@ -34,7 +34,8 @@ def find(request) # The mount checks to see if the file exists, and returns nil # if not. - return nil unless path = mount.find(relative_path, request) + path = mount.find(relative_path, request) + return nil unless path path2instance(request, path) end @@ -43,7 +44,8 @@ def find(request) def search(request) mount, relative_path = configuration.split_path(request) - unless mount and paths = mount.search(relative_path, request) + paths = mount.search(relative_path, request) if mount + unless paths Puppet.info _("Could not find filesystem info for file '%{request}' in environment %{env}") % { request: request.key, env: request.environment } return nil end diff --git a/lib/puppet/indirector/indirection.rb b/lib/puppet/indirector/indirection.rb index 83ad872392e..28ba929b131 100644 --- a/lib/puppet/indirector/indirection.rb +++ b/lib/puppet/indirector/indirection.rb @@ -29,7 +29,8 @@ def self.instances # Find an indirected model by name. This is provided so that Terminus classes # can specifically hook up with the indirections they are associated with. def self.model(name) - return nil unless match = @@indirections.find { |i| i.name == name } + match = @@indirections.find { |i| i.name == name } + return nil unless match match.model end @@ -125,7 +126,8 @@ def terminus(terminus_name = nil) # Determine the terminus class. def terminus_class unless @terminus_class - if setting = self.terminus_setting + setting = self.terminus_setting + if setting self.terminus_class = Puppet.settings[setting] else raise Puppet::DevError, _("No terminus class nor terminus setting was provided for indirection %{name}") % { name: self.name} @@ -163,7 +165,8 @@ def expire(key, options={}) return nil unless cache? && !request.ignore_cache_save? - return nil unless instance = cache.find(request(:find, key, nil, options)) + instance = cache.find(request(:find, key, nil, options)) + return nil unless instance Puppet.info _("Expiring the %{cache} cache of %{instance}") % { cache: self.name, instance: instance.name } @@ -233,7 +236,8 @@ def head(key, options={}) def find_in_cache(request) # See if our instance is in the cache and up to date. - return nil unless cache? and ! request.ignore_cache? and cached = cache.find(request) + cached = cache.find(request) if cache? && ! request.ignore_cache? + return nil unless cached if cached.expired? Puppet.info _("Not using expired %{indirection} for %{request} from cache; expired at %{expiration}") % { indirection: self.name, request: request.key, expiration: cached.expiration } return nil @@ -266,7 +270,8 @@ def search(key, options={}) request = request(:search, key, nil, options) terminus = prepare(request) - if result = terminus.search(request) + result = terminus.search(request) + if result raise Puppet::DevError, _("Search results from terminus %{terminus_name} are not an array") % { terminus_name: terminus.name } unless result.is_a?(Array) result.each do |instance| next unless instance.respond_to? :expiration @@ -332,7 +337,8 @@ def prepare(request) # Create a new terminus instance. def make_terminus(terminus_class) # Load our terminus class. - unless klass = Puppet::Indirector::Terminus.terminus_class(self.name, terminus_class) + klass = Puppet::Indirector::Terminus.terminus_class(self.name, terminus_class) + unless klass raise ArgumentError, _("Could not find terminus %{terminus_class} for indirection %{indirection}") % { terminus_class: terminus_class, indirection: self.name } end klass.new diff --git a/lib/puppet/indirector/node/exec.rb b/lib/puppet/indirector/node/exec.rb index a37809b3eba..91670339191 100644 --- a/lib/puppet/indirector/node/exec.rb +++ b/lib/puppet/indirector/node/exec.rb @@ -39,7 +39,8 @@ def execute(command, arguments) def create_node(name, result, facts = nil) node = Puppet::Node.new(name) [:parameters, :classes, :environment].each do |param| - if value = result[param] + value = result[param] + if value node.send(param.to_s + "=", value) end end diff --git a/lib/puppet/indirector/report/processor.rb b/lib/puppet/indirector/report/processor.rb index 51110e7bd8e..ba97eeb98c7 100644 --- a/lib/puppet/indirector/report/processor.rb +++ b/lib/puppet/indirector/report/processor.rb @@ -49,7 +49,8 @@ def reports def processors(&blk) return [] if Puppet[:reports] == "none" reports.each do |name| - if mod = Puppet::Reports.report(name) + mod = Puppet::Reports.report(name) + if mod yield(mod) else Puppet.warning _("No report named '%{name}'") % { name: name } diff --git a/lib/puppet/indirector/request.rb b/lib/puppet/indirector/request.rb index c76acb0575f..2aee3277171 100644 --- a/lib/puppet/indirector/request.rb +++ b/lib/puppet/indirector/request.rb @@ -99,8 +99,9 @@ def indirection_name=(name) end def model - raise ArgumentError, _("Could not find indirection '%{indirection}'") % { indirection: indirection_name } unless i = indirection - i.model + ind = indirection + raise ArgumentError, _("Could not find indirection '%{indirection}'") % { indirection: indirection_name } unless ind + ind.model end # Are we trying to interact with multiple resources, or just one? @@ -169,7 +170,8 @@ def to_hash result = options.dup OPTION_ATTRIBUTES.each do |attribute| - if value = send(attribute) + value = send(attribute) + if value result[attribute] = value end end @@ -206,7 +208,8 @@ def do_request(srv_service=:puppet, default_server=nil, default_port=nil, &block self.server = default_server else self.server = Puppet.lookup(:server) do - if primary_server = Puppet.settings[:server_list][0] + primary_server = Puppet.settings[:server_list][0] + if primary_server #TRANSLATORS 'server_list' is the name of a setting and should not be translated debug_once _("Selected server from first entry of the `server_list` setting: %{server}") % {server: primary_server[0]} primary_server[0] @@ -222,7 +225,8 @@ def do_request(srv_service=:puppet, default_server=nil, default_port=nil, &block self.port = default_port else self.port = Puppet.lookup(:serverport) do - if primary_server = Puppet.settings[:server_list][0] + primary_server = Puppet.settings[:server_list][0] + if primary_server #TRANSLATORS 'server_list' is the name of a setting and should not be translated debug_once _("Selected port from the first entry of the `server_list` setting: %{port}") % {port: primary_server[1]} primary_server[1] diff --git a/lib/puppet/indirector/ssl_file.rb b/lib/puppet/indirector/ssl_file.rb index 0ce333cf05a..dd7ccb44a53 100644 --- a/lib/puppet/indirector/ssl_file.rb +++ b/lib/puppet/indirector/ssl_file.rb @@ -139,17 +139,19 @@ def write(name, path) # All types serialized to disk contain only ASCII content: # * SSL::Key may be a .export(OpenSSL::Cipher::DES.new(:EDE3, :CBC), pass) or .to_pem # * All other classes are translated to strings by calling .to_pem - if file_location Puppet.settings.setting(self.class.file_setting).open('w:ASCII') { |f| yield f } - elsif setting = self.class.directory_setting - begin - Puppet.settings.setting(setting).open_file(path, 'w:ASCII') { |f| yield f } - rescue => detail - raise Puppet::Error, _("Could not write %{path} to %{setting}: %{detail}") % { path: path, setting: setting, detail: detail }, detail.backtrace - end else - raise Puppet::DevError, _("You must provide a setting to determine where the files are stored") + setting = self.class.directory_setting + if setting + begin + Puppet.settings.setting(setting).open_file(path, 'w:ASCII') { |f| yield f } + rescue => detail + raise Puppet::Error, _("Could not write %{path} to %{setting}: %{detail}") % { path: path, setting: setting, detail: detail }, detail.backtrace + end + else + raise Puppet::DevError, _("You must provide a setting to determine where the files are stored") + end end end end diff --git a/lib/puppet/indirector/terminus.rb b/lib/puppet/indirector/terminus.rb index 73d108e8062..1e68ce3d161 100644 --- a/lib/puppet/indirector/terminus.rb +++ b/lib/puppet/indirector/terminus.rb @@ -29,10 +29,13 @@ def const2name(const) def indirection=(name) if name.is_a?(Puppet::Indirector::Indirection) @indirection = name - elsif ind = Puppet::Indirector::Indirection.instance(name) - @indirection = ind else - raise ArgumentError, _("Could not find indirection instance %{name} for %{terminus}") % { name: name, terminus: self.name } + ind = Puppet::Indirector::Indirection.instance(name) + if ind + @indirection = ind + else + raise ArgumentError, _("Could not find indirection instance %{name} for %{terminus}") % { name: name, terminus: self.name } + end end end diff --git a/lib/puppet/interface.rb b/lib/puppet/interface.rb index bdf9a4499f8..3657d17d1dc 100644 --- a/lib/puppet/interface.rb +++ b/lib/puppet/interface.rb @@ -91,7 +91,8 @@ def face?(name, version) # # @api public def [](name, version) - unless face = Puppet::Interface::FaceCollection[name, version] + face = Puppet::Interface::FaceCollection[name, version] + unless face # REVISIT (#18042) no sense in rechecking if version == :current -- josh if Puppet::Interface::FaceCollection[name, :current] raise Puppet::Error, "Could not find version #{version} of #{name}" diff --git a/lib/puppet/interface/action.rb b/lib/puppet/interface/action.rb index 386e320ccb4..8fb50200ac1 100644 --- a/lib/puppet/interface/action.rb +++ b/lib/puppet/interface/action.rb @@ -277,12 +277,16 @@ def #{@name}(#{decl.join(", ")}) def add_option(option) option.aliases.each do |name| - if conflict = get_option(name) then + conflict = get_option(name) + if conflict raise ArgumentError, _("Option %{option} conflicts with existing option %{conflict}") % { option: option, conflict: conflict } - elsif conflict = @face.get_option(name) then - raise ArgumentError, _("Option %{option} conflicts with existing option %{conflict} on %{face}") % - { option: option, conflict: conflict, face: @face } + else + conflict = @face.get_option(name) + if conflict + raise ArgumentError, _("Option %{option} conflicts with existing option %{conflict} on %{face}") % + { option: option, conflict: conflict, face: @face } + end end end @@ -340,7 +344,8 @@ def validate_and_clean(original) overlap = Hash.new do |h, k| h[k] = [] end unknown = [] original.keys.each do |name| - if option = get_option(name) then + option = get_option(name) + if option canonical = option.name if result.has_key? canonical overlap[canonical] << name diff --git a/lib/puppet/interface/action_manager.rb b/lib/puppet/interface/action_manager.rb index 9e6bfca5aef..2fab6a592d4 100644 --- a/lib/puppet/interface/action_manager.rb +++ b/lib/puppet/interface/action_manager.rb @@ -22,7 +22,8 @@ def action(name, &block) action = Puppet::Interface::ActionBuilder.build(self, name, &block) # REVISIT: (#18042) doesn't this mean we can't redefine the default action? -- josh - if action.default and current = get_default_action + current = get_default_action if action.default + if current raise "Actions #{current.name} and #{name} cannot both be default" end diff --git a/lib/puppet/interface/documentation.rb b/lib/puppet/interface/documentation.rb index 2e047c3c55e..2897e51aed2 100644 --- a/lib/puppet/interface/documentation.rb +++ b/lib/puppet/interface/documentation.rb @@ -318,17 +318,20 @@ def munge_copyright_year(input) when String then input.strip.split(/,/).map do |part| part = part.strip - if part =~ /^\d+$/ then + if part.match(/^\d+$/) part.to_i - elsif found = part.split(/-/) then - unless found.length == 2 and found.all? {|x| x.strip =~ /^\d+$/ } + else + found = part.split(/-/) + if found + unless found.length == 2 and found.all? {|x| x.strip =~ /^\d+$/ } + #TRANSLATORS 'copyright' is an attribute name and should not be translated + raise ArgumentError, _("%{value} is not a good copyright year or range") % { value: part.inspect } + end + Range.new(found[0].to_i, found[1].to_i) + else #TRANSLATORS 'copyright' is an attribute name and should not be translated raise ArgumentError, _("%{value} is not a good copyright year or range") % { value: part.inspect } end - Range.new(found[0].to_i, found[1].to_i) - else - #TRANSLATORS 'copyright' is an attribute name and should not be translated - raise ArgumentError, _("%{value} is not a good copyright year or range") % { value: part.inspect } end end diff --git a/lib/puppet/interface/face_collection.rb b/lib/puppet/interface/face_collection.rb index 6f4eac67891..8baf43a5d3d 100644 --- a/lib/puppet/interface/face_collection.rb +++ b/lib/puppet/interface/face_collection.rb @@ -24,13 +24,16 @@ def self.get_action_for_face(name, action_name, version) # If the version they request specifically doesn't exist, don't search # elsewhere. Usually this will start from :current and all... - return nil unless face = self[name, version] - unless action = face.get_action(action_name) + face = self[name, version] + return nil unless face + action = face.get_action(action_name) + unless action # ...we need to search for it bound to an o{lder,ther} version. Since # we load all actions when the face is first references, this will be in # memory in the known set of versions of the face. (@faces[name].keys - [ :current ]).sort.reverse_each do |vers| - break if action = @faces[name][vers].get_action(action_name) + action = @faces[name][vers].get_action(action_name) + break if action end end diff --git a/lib/puppet/interface/option.rb b/lib/puppet/interface/option.rb index 8a08f907a6a..eeb79bca9f9 100644 --- a/lib/puppet/interface/option.rb +++ b/lib/puppet/interface/option.rb @@ -35,7 +35,8 @@ def initialize(parent, *declaration, &block) if Puppet.settings.include? name then raise ArgumentError, _("%{option}: already defined in puppet") % { option: item.inspect } end - if dup = dups[name] then + dup = dups[name] + if dup raise ArgumentError, _("%{option}: duplicates existing alias %{duplicate} in %{parent}") % { option: item.inspect, duplicate: dup.inspect, parent: @parent } else @@ -84,7 +85,8 @@ def to_s # @api private def optparse_to_optionname(declaration) - unless found = declaration.match(/^-+(?:\[no-\])?([^ =]+)/) then + found = declaration.match(/^-+(?:\[no-\])?([^ =]+)/) + unless found raise ArgumentError, _("Can't find a name in the declaration %{declaration}") % { declaration: declaration.inspect } end found.captures.first diff --git a/lib/puppet/interface/option_manager.rb b/lib/puppet/interface/option_manager.rb index 49e89ffac4b..594e1fd9f5c 100644 --- a/lib/puppet/interface/option_manager.rb +++ b/lib/puppet/interface/option_manager.rb @@ -53,14 +53,16 @@ def add_option(option) @options_hash ||= {} option.aliases.each do |name| - if conflict = get_option(name) then + conflict = get_option(name) + if conflict raise ArgumentError, _("Option %{option} conflicts with existing option %{conflict}") % { option: option, conflict: conflict } end actions.each do |action| action = get_action(action) - if conflict = action.get_option(name) then + conflict = action.get_option(name) + if conflict raise ArgumentError, _("Option %{option} conflicts with existing option %{conflict} on %{action}") % { option: option, conflict: conflict, action: action } end diff --git a/lib/puppet/module_tool.rb b/lib/puppet/module_tool.rb index e64c798e6c1..20203f65ef9 100644 --- a/lib/puppet/module_tool.rb +++ b/lib/puppet/module_tool.rb @@ -31,7 +31,8 @@ def self.artifact?(path) # Return the +username+ and +modname+ for a given +full_module_name+, or raise an # ArgumentError if the argument isn't parseable. def self.username_and_modname_from(full_module_name) - if matcher = full_module_name.match(FULL_MODULE_NAME_PATTERN) + matcher = full_module_name.match(FULL_MODULE_NAME_PATTERN) + if matcher return matcher.captures else raise ArgumentError, _("Not a valid full name: %{full_module_name}") % { full_module_name: full_module_name } diff --git a/lib/puppet/module_tool/applications/application.rb b/lib/puppet/module_tool/applications/application.rb index c3a72945a52..e7031ddabdf 100644 --- a/lib/puppet/module_tool/applications/application.rb +++ b/lib/puppet/module_tool/applications/application.rb @@ -68,7 +68,8 @@ def load_metadata! end def parse_filename(filename) - if match = /^((.*?)-(.*?))-(\d+\.\d+\.\d+.*?)$/.match(File.basename(filename, '.tar.gz')) + match = /^((.*?)-(.*?))-(\d+\.\d+\.\d+.*?)$/.match(File.basename(filename, '.tar.gz')) + if match module_name, author, shortname, version = match.captures else raise ArgumentError, _("Could not parse filename to obtain the username, module name and version. (%{release_name})") % { release_name: @release_name } diff --git a/lib/puppet/module_tool/applications/installer.rb b/lib/puppet/module_tool/applications/installer.rb index b78dc5080d5..a231ec91f21 100644 --- a/lib/puppet/module_tool/applications/installer.rb +++ b/lib/puppet/module_tool/applications/installer.rb @@ -60,7 +60,8 @@ def run results = { :action => :install, :module_name => name, :module_version => version } begin - if installed_module = installed_modules[name] + installed_module = installed_modules[name] + if installed_module unless forced? if Puppet::Module.parse_range(version).include? installed_module.version results[:result] = :noop @@ -136,7 +137,8 @@ def run unless forced? # Check for module name conflicts. releases.each do |rel| - if installed_module = installed_modules_source.by_name[rel.name.split('-').last] + installed_module = installed_modules_source.by_name[rel.name.split('-').last] + if installed_module next if installed_module.has_metadata? && installed_module.forge_name.tr('/', '-') == rel.name if rel.name != name diff --git a/lib/puppet/module_tool/applications/upgrader.rb b/lib/puppet/module_tool/applications/upgrader.rb index 04ec96dbdc0..f9babc13ea4 100644 --- a/lib/puppet/module_tool/applications/upgrader.rb +++ b/lib/puppet/module_tool/applications/upgrader.rb @@ -144,7 +144,8 @@ def installed_release.priority end releases.each do |rel| - if mod = installed_modules_source.by_name[rel.name.split('-').last] + mod = installed_modules_source.by_name[rel.name.split('-').last] + if mod next if mod.has_metadata? && mod.forge_name.tr('/', '-') == rel.name if rel.name != name @@ -189,7 +190,8 @@ def installed_release.priority Puppet.notice _('Upgrading -- do not interrupt ...') releases.each do |release| - if installed = installed_modules[release.name] + installed = installed_modules[release.name] + if installed release.install(Pathname.new(installed.mod.modulepath)) else release.install(dir) diff --git a/lib/puppet/module_tool/contents_description.rb b/lib/puppet/module_tool/contents_description.rb index 2e224c7454e..772a6f0902d 100644 --- a/lib/puppet/module_tool/contents_description.rb +++ b/lib/puppet/module_tool/contents_description.rb @@ -43,7 +43,8 @@ def data end type_names.each do |name| - if type = Puppet::Type.type(name.to_sym) + type = Puppet::Type.type(name.to_sym) + if type type_hash = {:name => name, :doc => type.doc} type_hash[:properties] = attr_doc(type, :property) type_hash[:parameters] = attr_doc(type, :param) diff --git a/lib/puppet/module_tool/metadata.rb b/lib/puppet/module_tool/metadata.rb index 816cd10aab6..20191051444 100644 --- a/lib/puppet/module_tool/metadata.rb +++ b/lib/puppet/module_tool/metadata.rb @@ -66,9 +66,8 @@ def add_dependency(name, version_requirement=nil, repository=nil) validate_name(name) validate_version_range(version_requirement) if version_requirement - if dup = @data['dependencies'].find { |d| d.full_module_name == name && d.version_requirement != version_requirement } - raise ArgumentError, _("Dependency conflict for %{module_name}: Dependency %{name} was given conflicting version requirements %{version_requirement} and %{dup_version}. Verify that there are no duplicates in the metadata.json.") % { module_name: full_module_name, name: name, version_requirement: version_requirement, dup_version: dup.version_requirement } - end + dup = @data['dependencies'].find { |d| d.full_module_name == name && d.version_requirement != version_requirement } + raise ArgumentError, _("Dependency conflict for %{module_name}: Dependency %{name} was given conflicting version requirements %{version_requirement} and %{dup_version}. Verify that there are no duplicates in the metadata.json.") % { module_name: full_module_name, name: name, version_requirement: version_requirement, dup_version: dup.version_requirement } if dup dep = Dependency.new(name, version_requirement, repository) @data['dependencies'].add(dep) diff --git a/lib/puppet/module_tool/shared_behaviors.rb b/lib/puppet/module_tool/shared_behaviors.rb index 0af317577c6..2d0a759cec7 100644 --- a/lib/puppet/module_tool/shared_behaviors.rb +++ b/lib/puppet/module_tool/shared_behaviors.rb @@ -111,7 +111,8 @@ def resolve_constraints(dependencies, source = [{:name => :you}], seen = {}, act valid_versions = versions.select { |x| x[:semver].special == '' } valid_versions = versions if valid_versions.empty? - unless version = valid_versions.last + version = valid_versions.last + unless version req_module = @module_name req_versions = @versions["#{@module_name}"].map { |v| v[:semver] } raise NoVersionsSatisfyError, diff --git a/lib/puppet/network/authconfig.rb b/lib/puppet/network/authconfig.rb index d06267b0e0e..2213cb6961a 100644 --- a/lib/puppet/network/authconfig.rb +++ b/lib/puppet/network/authconfig.rb @@ -54,7 +54,8 @@ def mk_acl(acl) right = @rights.newright(acl[:acl]) right.allow(acl[:allow] || "*") - if method = acl[:method] + method = acl[:method] + if method method = [method] unless method.is_a?(Array) method.each { |m| right.restrict_method(m) } end @@ -65,7 +66,8 @@ def mk_acl(acl) # raise an Puppet::Network::AuthorizedError if the request # is denied. def check_authorization(method, path, params) - if authorization_failure_exception = @rights.is_request_forbidden_and_why?(method, path, params) + authorization_failure_exception = @rights.is_request_forbidden_and_why?(method, path, params) + if authorization_failure_exception Puppet.warning(_("Denying access: %{authorization_failure_exception}") % { authorization_failure_exception: authorization_failure_exception }) raise authorization_failure_exception end diff --git a/lib/puppet/network/authstore.rb b/lib/puppet/network/authstore.rb index 3a08603ad22..7ac302421db 100644 --- a/lib/puppet/network/authstore.rb +++ b/lib/puppet/network/authstore.rb @@ -29,7 +29,8 @@ def allowed?(name, ip) # yay insecure overrides return true if globalallow? - if decl = declarations.find { |d| d.match?(name, ip) } + decl = declarations.find { |d| d.match?(name, ip) } + if decl return decl.result end diff --git a/lib/puppet/network/formats.rb b/lib/puppet/network/formats.rb index 7000859e882..330282a3e4c 100644 --- a/lib/puppet/network/formats.rb +++ b/lib/puppet/network/formats.rb @@ -105,7 +105,8 @@ def render_multiple(instances) # If they pass class information, we want to ignore it. # This is required for compatibility with Puppet 3.x def data_to_instance(klass, data) - if data.is_a?(Hash) and d = data['data'] + d = data['data'] if data.is_a?(Hash) + if d data = d end return data if data.is_a?(klass) diff --git a/lib/puppet/network/http/api/indirected_routes.rb b/lib/puppet/network/http/api/indirected_routes.rb index 5a0af69296e..36a2e40cce5 100644 --- a/lib/puppet/network/http/api/indirected_routes.rb +++ b/lib/puppet/network/http/api/indirected_routes.rb @@ -124,7 +124,8 @@ def uri2indirection(http_method, uri, params) # Execute our find. def do_find(indirection, key, params, request, response) - unless result = indirection.find(key, params) + result = indirection.find(key, params) + unless result raise Puppet::Network::HTTP::Error::HTTPNotFoundError.new(_("Could not find %{value0} %{key}") % { value0: indirection.name, key: key }, Puppet::Network::HTTP::Issues::RESOURCE_NOT_FOUND) end @@ -245,7 +246,8 @@ def indirection_method(http_method, indirection) raise Puppet::Network::HTTP::Error::HTTPMethodNotAllowedError.new( _("No support for http method %{http_method}") % { http_method: http_method }) unless METHOD_MAP[http_method] - unless method = METHOD_MAP[http_method][plurality(indirection)] + method = METHOD_MAP[http_method][plurality(indirection)] + unless method raise Puppet::Network::HTTP::Error::HTTPBadRequestError.new( _("No support for plurality %{indirection} for %{http_method} operations") % { indirection: plurality(indirection), http_method: http_method }) end diff --git a/lib/puppet/network/http/handler.rb b/lib/puppet/network/http/handler.rb index f6696595a8e..6b4f8272c00 100644 --- a/lib/puppet/network/http/handler.rb +++ b/lib/puppet/network/http/handler.rb @@ -105,7 +105,8 @@ def respond_with_http_error(response, exception) end def find_route_or_raise(request) - if route = @routes.find { |r| r.matches?(request) } + route = @routes.find { |r| r.matches?(request) } + if route return route else raise Puppet::Network::HTTP::Error::HTTPNotFoundError.new( diff --git a/lib/puppet/network/http/request.rb b/lib/puppet/network/http/request.rb index a94234c2594..1c78267f418 100644 --- a/lib/puppet/network/http/request.rb +++ b/lib/puppet/network/http/request.rb @@ -20,7 +20,8 @@ def route_into(prefix) end def formatter - if header = headers['content-type'] + header = headers['content-type'] + if header header.gsub!(/\s*;.*$/,'') # strip any charset format = Puppet::Network::FormatHandler.mime(header) diff --git a/lib/puppet/network/http/route.rb b/lib/puppet/network/http/route.rb index 81f31161698..32ce0a8a42b 100644 --- a/lib/puppet/network/http/route.rb +++ b/lib/puppet/network/http/route.rb @@ -83,7 +83,8 @@ def process(request, response) end subrequest = request.route_into(match(request.routing_path).to_s) - if chained_route = @chained.find { |route| route.matches?(subrequest) } + chained_route = @chained.find { |route| route.matches?(subrequest) } + if chained_route chained_route.process(subrequest, response) end end diff --git a/lib/puppet/network/resolver.rb b/lib/puppet/network/resolver.rb index dc5471accfc..9636eb00c51 100644 --- a/lib/puppet/network/resolver.rb +++ b/lib/puppet/network/resolver.rb @@ -71,7 +71,7 @@ def each_srv_record(domain, service_name = :puppet, &block) each_srv_record(domain, :puppet, &block) else each_priority(records) do |recs| - while next_rr = recs.delete(find_weighted_server(recs)) + while next_rr = recs.delete(find_weighted_server(recs)) #rubocop:disable Lint/AssignmentInCondition Puppet.debug "Yielding next server of #{next_rr.target.to_s}:#{next_rr.port}" yield next_rr.target.to_s, next_rr.port end @@ -125,7 +125,8 @@ def ttl(service_name) # @return [Boolean] true if the entry has expired, false otherwise. # Always returns true if the record had no TTL. def expired?(service_name) - if entry = @record_cache[service_name] + entry = @record_cache[service_name] + if entry return Time.now > (entry.resolution_time + entry.ttl) else return true diff --git a/lib/puppet/network/rights.rb b/lib/puppet/network/rights.rb index 84f0443d82b..3cc34360174 100644 --- a/lib/puppet/network/rights.rb +++ b/lib/puppet/network/rights.rb @@ -39,7 +39,8 @@ def is_forbidden_and_why?(name, args = {}) # an acl can return :dunno, which means "I'm not qualified to answer your question, # please ask someone else". This is used when for instance an acl matches, but not for the # current rest method, where we might think some other acl might be more specific. - if match = acl.match?(name) + match = acl.match?(name) + if match args[:match] = match if (res = acl.allowed?(args[:node], args[:ip], args)) != :dunno # return early if we're allowed diff --git a/lib/puppet/node.rb b/lib/puppet/node.rb index 2b120904b5c..dd91127687a 100644 --- a/lib/puppet/node.rb +++ b/lib/puppet/node.rb @@ -61,7 +61,8 @@ def environment if @environment @environment else - if env = parameters[ENVIRONMENT] + env = parameters[ENVIRONMENT] + if env self.environment = env elsif environment_name self.environment = environment_name @@ -101,7 +102,8 @@ def initialize(name, options = {}) raise ArgumentError, _("Node names cannot be nil") unless name @name = name - if classes = options[:classes] + classes = options[:classes] + if classes if classes.is_a?(String) @classes = [classes] else @@ -117,7 +119,8 @@ def initialize(name, options = {}) @server_facts = {} - if env = options[:environment] + env = options[:environment] + if env self.environment = env end @@ -187,7 +190,8 @@ def names names += split_name(name) if name.include?(".") # First, get the fqdn - unless fqdn = parameters["fqdn"] + fqdn = parameters["fqdn"] + unless fqdn if parameters["hostname"] and parameters["domain"] fqdn = parameters["hostname"] + "." + parameters["domain"] else diff --git a/lib/puppet/pal/compiler.rb b/lib/puppet/pal/compiler.rb index 0c8b011e903..1b501c629ca 100644 --- a/lib/puppet/pal/compiler.rb +++ b/lib/puppet/pal/compiler.rb @@ -41,7 +41,8 @@ def call_function(function_name, *args, &block) # def function_signature(function_name) loader = internal_compiler.loaders.private_environment_loader - if func = loader.load(:function, function_name) + func = loader.load(:function, function_name) + if func return FunctionSignature.new(func.class) end # Could not find function diff --git a/lib/puppet/pal/script_compiler.rb b/lib/puppet/pal/script_compiler.rb index dbde059dd09..f9a2b8ced20 100644 --- a/lib/puppet/pal/script_compiler.rb +++ b/lib/puppet/pal/script_compiler.rb @@ -8,7 +8,8 @@ class ScriptCompiler < Compiler # def plan_signature(plan_name) loader = internal_compiler.loaders.private_environment_loader - if func = loader.load(:plan, plan_name) + func = loader.load(:plan, plan_name) + if func return PlanSignature.new(func) end # Could not find plan @@ -40,7 +41,8 @@ def list_plans(filter_regex = nil, error_collector = nil) # def task_signature(task_name) loader = internal_compiler.loaders.private_environment_loader - if task = loader.load(:task, task_name) + task = loader.load(:task, task_name) + if task return TaskSignature.new(task) end # Could not find task diff --git a/lib/puppet/parameter.rb b/lib/puppet/parameter.rb index f7739949309..9c8217c1dae 100644 --- a/lib/puppet/parameter.rb +++ b/lib/puppet/parameter.rb @@ -110,11 +110,13 @@ def doc unless defined?(@addeddocvals) @doc = Puppet::Util::Docs.scrub(@doc) - if vals = value_collection.doc + vals = value_collection.doc + if vals @doc << "\n\n#{vals}" end - if features = self.required_features + features = self.required_features + if features @doc << "\n\nRequires features #{features.flatten.collect { |f| f.to_s }.join(" ")}." end @addeddocvals = true diff --git a/lib/puppet/parameter/value_collection.rb b/lib/puppet/parameter/value_collection.rb index fab3a1429a5..8138c1d9848 100644 --- a/lib/puppet/parameter/value_collection.rb +++ b/lib/puppet/parameter/value_collection.rb @@ -18,9 +18,8 @@ class Puppet::Parameter::ValueCollection # def aliasvalue(name, other) other = other.to_sym - unless value = match?(other) - raise Puppet::DevError, _("Cannot alias nonexistent value %{value}") % { value: other } - end + value = match?(other) + raise Puppet::DevError, _("Cannot alias nonexistent value %{value}") % { value: other } unless value value.alias(name) end @@ -35,7 +34,8 @@ def doc unless values.empty? @doc << "Valid values are " @doc << @strings.collect do |value| - if aliases = value.aliases and ! aliases.empty? + aliases = value.aliases + if aliases && ! aliases.empty? "`#{value.name}` (also called `#{aliases.join(", ")}`)" else "`#{value.name}`" @@ -81,9 +81,8 @@ def initialize # def match?(test_value) # First look for normal values - if value = @strings.find { |v| v.match?(test_value) } - return value - end + value = @strings.find { |v| v.match?(test_value) } + return value if value # Then look for a regex match @regexes.find { |v| v.match?(test_value) } @@ -100,7 +99,8 @@ def match?(test_value) def munge(value) return value if empty? - if instance = match?(value) + instance = match?(value) + if instance if instance.regex? return value else diff --git a/lib/puppet/parser/ast/pops_bridge.rb b/lib/puppet/parser/ast/pops_bridge.rb index 27f6cacd647..fb18c53b43a 100644 --- a/lib/puppet/parser/ast/pops_bridge.rb +++ b/lib/puppet/parser/ast/pops_bridge.rb @@ -176,7 +176,8 @@ def create_type_map(definition) # reused and we may reenter without a scope (which is fine). A debug message is then output in case # there is the need to track down the odd corner case. See {#obtain_scope}. # - if scope = obtain_scope + scope = obtain_scope + if scope typed_parameters.each do |p| result[p.name] = @@evaluator.evaluate(scope, p.type_expr) end diff --git a/lib/puppet/parser/compiler.rb b/lib/puppet/parser/compiler.rb index 0effddc4b8e..e2f5c2a6b00 100644 --- a/lib/puppet/parser/compiler.rb +++ b/lib/puppet/parser/compiler.rb @@ -61,7 +61,8 @@ def self.compile(node, code_id = nil) # Store a resource override. def add_override(override) # If possible, merge the override in immediately. - if resource = @catalog.resource(override.ref) + resource = @catalog.resource(override.ref) + if resource resource.merge(override) else # Otherwise, store the override for later; these @@ -493,7 +494,8 @@ def evaluate_ast_node # Now see if we can find the node. astnode = nil @node.names.each do |name| - break if astnode = krt.node(name.to_s.downcase) + astnode = krt.node(name.to_s.downcase) + break if astnode end unless (astnode ||= krt.node("default")) @@ -627,7 +629,8 @@ def finish resources.each do |resource| # Add in any resource overrides. - if overrides = resource_overrides(resource) + overrides = resource_overrides(resource) + if overrides overrides.each do |over| resource.merge(over) end @@ -645,7 +648,8 @@ def finish protected :finish def add_resource_metaparams - unless main = catalog.resource(:class, :main) + main = catalog.resource(:class, :main) + unless main #TRANSLATORS "main" is a function name and should not be translated raise _("Couldn't find main") end @@ -655,7 +659,8 @@ def add_resource_metaparams end data = {} catalog.walk(main, :out) do |source, target| - if source_data = data[source] || metaparams_as_data(source, names) + source_data = data[source] || metaparams_as_data(source, names) + if source_data # only store anything in the data hash if we've actually got # data data[source] ||= source_data diff --git a/lib/puppet/parser/files.rb b/lib/puppet/parser/files.rb index 1c99767ad8a..ad4f107cbf1 100644 --- a/lib/puppet/parser/files.rb +++ b/lib/puppet/parser/files.rb @@ -14,7 +14,8 @@ module Puppet::Parser::Files def find_manifests_in_modules(pattern, environment) module_name, file_pattern = split_file_path(pattern) - if mod = environment.module(module_name) + mod = environment.module(module_name) + if mod [mod.name, mod.match_manifests(file_pattern)] else [nil, []] diff --git a/lib/puppet/parser/functions.rb b/lib/puppet/parser/functions.rb index c0827ff9c2d..080d945c996 100644 --- a/lib/puppet/parser/functions.rb +++ b/lib/puppet/parser/functions.rb @@ -232,7 +232,8 @@ def self.newfunction(name, options = {}, &block) def self.function(name, environment = Puppet.lookup(:current_environment)) name = name.intern - unless func = get_function(name, environment) + func = get_function(name, environment) + unless func autoloader.delegatee.load(name, environment) func = get_function(name, environment) end diff --git a/lib/puppet/parser/relationship.rb b/lib/puppet/parser/relationship.rb index ce07edb34a9..8bb2d5e279a 100644 --- a/lib/puppet/parser/relationship.rb +++ b/lib/puppet/parser/relationship.rb @@ -36,7 +36,8 @@ def mk_relationship(source, target, catalog) target_ref = canonical_ref(target) rel_param = param_name - unless source_resource = catalog.resource(*source_ref) + source_resource = catalog.resource(*source_ref) + unless source_resource raise ArgumentError, _("Could not find resource '%{source}' for relationship on '%{target}'") % { source: source.to_s, target: target.to_s } end unless catalog.resource(*target_ref) diff --git a/lib/puppet/parser/resource.rb b/lib/puppet/parser/resource.rb index e65ea459d84..1b002069811 100644 --- a/lib/puppet/parser/resource.rb +++ b/lib/puppet/parser/resource.rb @@ -56,7 +56,8 @@ def environment def add_edge_to_stage return unless self.class? - unless stage = catalog.resource(:stage, self[:stage] || (scope && scope.resource && scope.resource[:stage]) || :main) + stage = catalog.resource(:stage, self[:stage] || (scope && scope.resource && scope.resource[:stage]) || :main) + unless stage raise ArgumentError, _("Could not find stage %{stage} specified by %{resource}") % { stage: self[:stage] || :main, resource: self } end @@ -298,7 +299,8 @@ def add_parameters_from_consume # evaluate mappings in that scope resource_type.arguments.keys.each do |name| - if expr = blueprint[:mappings][name] + expr = blueprint[:mappings][name] + if expr # Explicit mapping value = expr.safeevaluate(cns_scope) else @@ -348,7 +350,8 @@ def replace_sensitive_data def override_parameter(param) # This can happen if the override is defining a new parameter, rather # than replacing an existing one. - (set_parameter(param) and return) unless current = @parameters[param.name] + current = @parameters[param.name] + (set_parameter(param) and return) unless current # Parameter is already set - if overriding with a default - simply ignore the setting of the default value return if scope.is_default?(type, param.name, param.value) diff --git a/lib/puppet/parser/scope.rb b/lib/puppet/parser/scope.rb index 66ae7bd0122..071595566fc 100644 --- a/lib/puppet/parser/scope.rb +++ b/lib/puppet/parser/scope.rb @@ -1,4 +1,3 @@ - # The scope class, which handles storing and retrieving variables and types and # such. require 'forwardable' @@ -652,8 +651,10 @@ def has_enclosing_scope? private :has_enclosing_scope? def qualified_scope(classname) - raise _("class %{classname} could not be found") % { classname: classname } unless klass = find_hostclass(classname) - raise _("class %{classname} has not been evaluated") % { classname: classname } unless kscope = class_scope(klass) + klass = find_hostclass(classname) + raise _("class %{classname} could not be found") % { classname: classname } unless klass + kscope = class_scope(klass) + raise _("class %{classname} has not been evaluated") % { classname: classname } unless kscope kscope end private :qualified_scope @@ -881,7 +882,8 @@ def to_s env_path = nil env_path = environment.configuration.path_to_env unless (environment.nil? || environment.configuration.nil?) # check module paths first since they may be in the environment (i.e. they are longer) - if module_path = environment.full_modulepath.detect {|m_path| path.start_with?(m_path) } + module_path = environment.full_modulepath.detect {|m_path| path.start_with?(m_path) } + if module_path path = "" + path[module_path.length..-1] elsif env_path && path && path.start_with?(env_path) path = "" + path[env_path.length..-1] diff --git a/lib/puppet/parser/templatewrapper.rb b/lib/puppet/parser/templatewrapper.rb index d576be2c9a6..01e0fdf64d4 100644 --- a/lib/puppet/parser/templatewrapper.rb +++ b/lib/puppet/parser/templatewrapper.rb @@ -61,7 +61,8 @@ def all_tags # @api private def file=(filename) - unless @__file__ = Puppet::Parser::Files.find_template(filename, scope.compiler.environment) + @__file__ = Puppet::Parser::Files.find_template(filename, scope.compiler.environment) + unless @__file__ raise Puppet::ParseError, _("Could not find template '%{filename}'") % { filename: filename } end end diff --git a/lib/puppet/parser/type_loader.rb b/lib/puppet/parser/type_loader.rb index 731f3f1d5da..32ca242ab02 100644 --- a/lib/puppet/parser/type_loader.rb +++ b/lib/puppet/parser/type_loader.rb @@ -66,7 +66,8 @@ def try_load_fqname(type, fqname) files_to_try_for(fqname).each do |filename| begin imported_types = import_from_modules(filename) - if result = imported_types.find { |t| t.type == type and t.name == fqname } + result = imported_types.find { |t| t.type == type and t.name == fqname } + if result Puppet.debug {"Automatically imported #{fqname} from #{filename} into #{environment}"} return result end diff --git a/lib/puppet/pops/adaptable.rb b/lib/puppet/pops/adaptable.rb index 3072d548aaf..67be92bbc9c 100644 --- a/lib/puppet/pops/adaptable.rb +++ b/lib/puppet/pops/adaptable.rb @@ -94,11 +94,8 @@ def self.get(o) # def self.adapt(o, &block) attr_name = self_attr_name - adapter = if o.instance_variable_defined?(attr_name) && value = o.instance_variable_get(attr_name) - value - else - associate_adapter(create_adapter(o), o) - end + value = o.instance_variable_get(attr_name) if o.instance_variable_defined?(attr_name) + adapter = value || associate_adapter(create_adapter(o), o) if block_given? case block.arity when 1 diff --git a/lib/puppet/pops/evaluator/collectors/exported_collector.rb b/lib/puppet/pops/evaluator/collectors/exported_collector.rb index 60aa754705c..81af29b863a 100644 --- a/lib/puppet/pops/evaluator/collectors/exported_collector.rb +++ b/lib/puppet/pops/evaluator/collectors/exported_collector.rb @@ -44,7 +44,8 @@ def collect found_resources = found.map {|x| x.is_a?(Puppet::Parser::Resource) ? x : x.to_resource(@scope)} found_resources.each do |item| - if existing = @scope.findresource(item.resource_type, item.title) + existing = @scope.findresource(item.resource_type, item.title) + if existing unless existing.collector_id == item.collector_id raise Puppet::ParseError, _("A duplicate resource was found while collecting exported resources, with the type and title %{title}") % { title: item.ref } diff --git a/lib/puppet/pops/evaluator/collectors/fixed_set_collector.rb b/lib/puppet/pops/evaluator/collectors/fixed_set_collector.rb index 86272458453..abc53a28f64 100644 --- a/lib/puppet/pops/evaluator/collectors/fixed_set_collector.rb +++ b/lib/puppet/pops/evaluator/collectors/fixed_set_collector.rb @@ -16,7 +16,8 @@ def initialize(scope, resources) def collect resolved = [] result = @resources.reduce([]) do |memo, ref| - if res = @scope.findresource(ref.to_s) + res = @scope.findresource(ref.to_s) + if res res.virtual = false memo << res resolved << ref diff --git a/lib/puppet/pops/evaluator/runtime3_resource_support.rb b/lib/puppet/pops/evaluator/runtime3_resource_support.rb index b271924afcd..7220cf833b1 100644 --- a/lib/puppet/pops/evaluator/runtime3_resource_support.rb +++ b/lib/puppet/pops/evaluator/runtime3_resource_support.rb @@ -97,7 +97,8 @@ def self.find_builtin_resource_type(scope, type_name) end loader = scope.compiler.loaders.private_environment_loader - if loaded = loader.load(:resource_type_pp, type_name) + loaded = loader.load(:resource_type_pp, type_name) + if loaded return loaded end diff --git a/lib/puppet/pops/evaluator/runtime3_support.rb b/lib/puppet/pops/evaluator/runtime3_support.rb index b3066eda617..2797d35eb62 100644 --- a/lib/puppet/pops/evaluator/runtime3_support.rb +++ b/lib/puppet/pops/evaluator/runtime3_support.rb @@ -252,7 +252,8 @@ def coerce_numeric(v, o, scope) if v.is_a?(Numeric) return v end - unless n = Utils.to_n(v) + n = Utils.to_n(v) + unless n fail(Issues::NOT_NUMERIC, o, {:value => v}) end # this point is reached if there was a conversion @@ -276,7 +277,8 @@ def external_call_function(name, args, scope, &block) # and it does not defined the visibility of functions from a ruby function's perspective. Instead, # this is done from the perspective of the environment. loader = loaders.private_environment_loader - if loader && func = loader.load(:function, name) + func = loader.load(:function, name) if loader + if func Puppet::Util::Profiler.profile(name, [:functions, name]) do return func.call(scope, *args, &block) end @@ -299,7 +301,8 @@ def call_function(name, args, o, scope, &block) # 'ruby -wc' thinks that _func is unused, because the only reference to it # is inside of the Kernel.eval string below. By prefixing it with the # underscore, we let Ruby know to not worry about whether it's unused or not. - if loader && _func = loader.load(:function, name) + _func = loader.load(:function, name) if loader + if _func Puppet::Util::Profiler.profile(name, [:functions, name]) do # Add stack frame when calling. See Puppet::Pops::PuppetStack return Kernel.eval('_func.call(scope, *args, &block)'.freeze, Kernel.binding, file || '', line) @@ -415,7 +418,8 @@ def get_resource_parameter_value(scope, resource, parameter_name) # The defaults must be looked up in the scope where the resource was created (not in the given # scope where the lookup takes place. resource_scope = resource.scope - if val.nil? && resource_scope && defaults = resource_scope.lookupdefaults(resource.type) + defaults = resource_scope.lookupdefaults(resource.type) if val.nil? && resource_scope + if defaults # NOTE: 3x resource keeps defaults as hash using symbol for name as key to Parameter which (again) holds # name and value. # NOTE: meta parameters that are unset ends up here, and there are no defaults for those encoded diff --git a/lib/puppet/pops/loader/base_loader.rb b/lib/puppet/pops/loader/base_loader.rb index 2e0643a1712..d3c80b63e7d 100644 --- a/lib/puppet/pops/loader/base_loader.rb +++ b/lib/puppet/pops/loader/base_loader.rb @@ -69,7 +69,8 @@ def get_entry(typed_name) # def set_entry(typed_name, value, origin = nil) # It is never ok to redefine in the very same loader unless redefining a 'not found' - if entry = @named_values[typed_name] + entry = @named_values[typed_name] + if entry fail_redefine(entry) unless entry.value.nil? end @@ -106,7 +107,8 @@ def remove_entry(typed_name) # def promote_entry(named_entry) typed_name = named_entry.typed_name - if entry = @named_values[typed_name] then fail_redefine(entry); end + entry = @named_values[typed_name] + if entry then fail_redefine(entry); end @named_values[typed_name] = named_entry end diff --git a/lib/puppet/pops/loader/dependency_loader.rb b/lib/puppet/pops/loader/dependency_loader.rb index 8d38416325e..e0e6060ee79 100644 --- a/lib/puppet/pops/loader/dependency_loader.rb +++ b/lib/puppet/pops/loader/dependency_loader.rb @@ -34,7 +34,8 @@ def discover(type, error_collector = nil, name_authority = Puppet::Pops::Pcore:: # def find(typed_name) if typed_name.qualified? - if l = index()[typed_name.name_parts[0]] + l = index()[typed_name.name_parts[0]] + if l l.load_typed(typed_name) else # no module entered as dependency with name matching first segment of wanted name @@ -69,7 +70,8 @@ def to_s def loaded_entry_in_dependency(typed_name, check_dependencies) if typed_name.qualified? - if l = index[typed_name.name_parts[0]] + l = index[typed_name.name_parts[0]] + if l l.loaded_entry(typed_name) else # no module entered as dependency with name matching first segment of wanted name diff --git a/lib/puppet/pops/loader/gem_support.rb b/lib/puppet/pops/loader/gem_support.rb index b2de4753f38..9c4a6e0ad5e 100644 --- a/lib/puppet/pops/loader/gem_support.rb +++ b/lib/puppet/pops/loader/gem_support.rb @@ -26,7 +26,8 @@ def gem_dir(uri_or_string) # TODO: FIND by name raises exception Gem::LoadError with list of all gems on the path # def gem_dir_from_uri(uri) - unless spec = Gem::Specification.find_by_name(uri.hostname) + spec = Gem::Specification.find_by_name(uri.hostname) + unless spec raise ArgumentError, _("Gem not found %{uri}") % { uri: uri } end # if path given append that, else append given subdir @@ -41,7 +42,8 @@ def gem_dir_from_uri(uri) # TODO: FIND by name raises exception Gem::LoadError with list of all gems on the path # def gem_dir_from_name(gem_name) - unless spec = Gem::Specification.find_by_name(gem_name) + spec = Gem::Specification.find_by_name(gem_name) + unless spec raise ArgumentError, _("Gem not found '%{gem_name}'") % { gem_name: gem_name } end spec.full_gem_path diff --git a/lib/puppet/pops/loader/loader.rb b/lib/puppet/pops/loader/loader.rb index 9b935d9229b..7d17bdd9548 100644 --- a/lib/puppet/pops/loader/loader.rb +++ b/lib/puppet/pops/loader/loader.rb @@ -69,7 +69,8 @@ def discover(type, error_collector = nil, name_authority = Pcore::RUNTIME_NAME_A # @api public # def load(type, name) - if result = load_typed(TypedName.new(type, name.to_s)) + result = load_typed(TypedName.new(type, name.to_s)) + if result result.value end end @@ -108,7 +109,8 @@ def loaded_entry(typed_name, check_dependencies = false) # @api private # def [](typed_name) - if found = get_entry(typed_name) + found = get_entry(typed_name) + if found found.value else nil diff --git a/lib/puppet/pops/loader/loader_paths.rb b/lib/puppet/pops/loader/loader_paths.rb index 4b2054de312..6784526b91f 100644 --- a/lib/puppet/pops/loader/loader_paths.rb +++ b/lib/puppet/pops/loader/loader_paths.rb @@ -397,7 +397,8 @@ def initialize(path_based_loader) def effective_paths(type) smart_paths = @smart_paths loader = @loader - unless effective_paths = smart_paths[type] + effective_paths = smart_paths[type] + unless effective_paths # type not yet processed, does the various directories for the type exist ? # Get the relative dirs for the type paths_for_type = LoaderPaths.relative_paths_for_type(type, loader) diff --git a/lib/puppet/pops/loader/static_loader.rb b/lib/puppet/pops/loader/static_loader.rb index c5994245fe6..3e6b78ce4cc 100644 --- a/lib/puppet/pops/loader/static_loader.rb +++ b/lib/puppet/pops/loader/static_loader.rb @@ -44,7 +44,7 @@ def initialize def discover(type, error_collector = nil, name_authority = Pcore::RUNTIME_NAME_AUTHORITY) # Static loader only contains runtime types - return EMPTY_ARRAY unless type == :type && name_authority == name_authority = Pcore::RUNTIME_NAME_AUTHORITY + return EMPTY_ARRAY unless type == :type && name_authority == name_authority = Pcore::RUNTIME_NAME_AUTHORITY #rubocop:disable Lint/AssignmentInCondition typed_names = type == :type && name_authority == Pcore::RUNTIME_NAME_AUTHORITY ? @loaded.keys : EMPTY_ARRAY block_given? ? typed_names.select { |tn| yield(tn) } : typed_names diff --git a/lib/puppet/pops/lookup/interpolation.rb b/lib/puppet/pops/lookup/interpolation.rb index 9dc5a4a083e..a3b520afbb6 100644 --- a/lib/puppet/pops/lookup/interpolation.rb +++ b/lib/puppet/pops/lookup/interpolation.rb @@ -135,7 +135,8 @@ def nil_in_scope?(scope, key) end def get_method_and_data(data, allow_methods) - if match = data.match(/^(\w+)\((?:["]([^"]+)["]|[']([^']+)['])\)$/) + match = data.match(/^(\w+)\((?:["]([^"]+)["]|[']([^']+)['])\)$/) + if match fail(Issues::HIERA_INTERPOLATION_METHOD_SYNTAX_NOT_ALLOWED) unless allow_methods key = match[1].to_sym data = match[2] || match[3] # double or single qouted diff --git a/lib/puppet/pops/model/factory.rb b/lib/puppet/pops/model/factory.rb index 3665c87090e..921bddfa6d4 100644 --- a/lib/puppet/pops/model/factory.rb +++ b/lib/puppet/pops/model/factory.rb @@ -835,7 +835,8 @@ def self.QNAME(name) end def self.NUMBER(name_or_numeric) - if n_radix = Utils.to_n_with_radix(name_or_numeric) + n_radix = Utils.to_n_with_radix(name_or_numeric) + if n_radix val, radix = n_radix if val.is_a?(Float) new(LiteralFloat, val) @@ -853,7 +854,8 @@ def self.NUMBER(name_or_numeric) # Convert input string to either a qualified name, a LiteralInteger with radix, or a LiteralFloat # def self.QNAME_OR_NUMBER(name) - if n_radix = Utils.to_n_with_radix(name) + n_radix = Utils.to_n_with_radix(name) + if n_radix val, radix = n_radix if val.is_a?(Float) new(LiteralFloat, val) diff --git a/lib/puppet/pops/parser/epp_support.rb b/lib/puppet/pops/parser/epp_support.rb index 8b1fe507c6f..03952ae1f6b 100644 --- a/lib/puppet/pops/parser/epp_support.rb +++ b/lib/puppet/pops/parser/epp_support.rb @@ -44,7 +44,8 @@ def scan_epp # This is the lexer's main loop until queue.empty? && scn.eos? do - if token = queue.shift || lex_token + token = queue.shift || lex_token + if token yield [ ctx[:after] = token[0], token[1] ] end end diff --git a/lib/puppet/pops/parser/heredoc_support.rb b/lib/puppet/pops/parser/heredoc_support.rb index 390e783f666..82e820c3a8b 100644 --- a/lib/puppet/pops/parser/heredoc_support.rb +++ b/lib/puppet/pops/parser/heredoc_support.rb @@ -85,7 +85,8 @@ def heredoc while !scn.eos? do one_line = scn.scan_until(/(?:\n|\z)/) raise eof_error unless one_line - if md = one_line.match(endline_pattern) + md = one_line.match(endline_pattern) + if md leading = md[1] has_margin = md[2] == '|' remove_break = md[3] == '-' diff --git a/lib/puppet/pops/parser/interpolation_support.rb b/lib/puppet/pops/parser/interpolation_support.rb index 92d25cfcc7e..57679e289dc 100644 --- a/lib/puppet/pops/parser/interpolation_support.rb +++ b/lib/puppet/pops/parser/interpolation_support.rb @@ -37,7 +37,8 @@ def interpolate_dq enqueue_until count break when '$' - if varname = scn.scan(PATTERN_VARIABLE) + varname = scn.scan(PATTERN_VARIABLE) + if varname # The $ is counted towards the variable enqueue_completed([:DQPRE, text, after-before-1], before) enqueue_completed([:VARIABLE, varname, scn.pos - after + 1], after - 1) @@ -78,7 +79,8 @@ def interpolate_tail_dq enqueue_until count break when '$' - if varname = scn.scan(PATTERN_VARIABLE) + varname = scn.scan(PATTERN_VARIABLE) + if varname # The $ is counted towards the variable enqueue_completed([:DQMID, text, after-before-1], before) enqueue_completed([:VARIABLE, varname, scn.pos - after + 1], after - 1) @@ -122,7 +124,8 @@ def interpolate_uq enqueue_until count break when '$' - if varname = scn.scan(PATTERN_VARIABLE) + varname = scn.scan(PATTERN_VARIABLE) + if varname # The $ is counted towards the variable enqueue_completed([:DQPRE, text, after-before-1], before) enqueue_completed([:VARIABLE, varname, scn.pos - after + 1], after - 1) @@ -162,7 +165,8 @@ def interpolate_tail_uq enqueue_until count break when '$' - if varname = scn.scan(PATTERN_VARIABLE) + varname = scn.scan(PATTERN_VARIABLE) + if varname # The $ is counted towards the variable enqueue_completed([:DQMID, text, after-before-1], before) enqueue_completed([:VARIABLE, varname, scn.pos - after + 1], after - 1) @@ -190,7 +194,8 @@ def enqueue_until brace_count scn.skip(self.class::PATTERN_WS) queue_size = queue.size until scn.eos? do - if token = lex_token + token = lex_token + if token if token.equal?(queue_base) # A nested #interpolate_dq call shifted the queue_base token from the @token_queue. It must # be put back since it is intended for the top level #interpolate_dq call only. diff --git a/lib/puppet/pops/parser/lexer2.rb b/lib/puppet/pops/parser/lexer2.rb index c46b44ce009..0a41fc34d00 100644 --- a/lib/puppet/pops/parser/lexer2.rb +++ b/lib/puppet/pops/parser/lexer2.rb @@ -355,7 +355,8 @@ def initialize() else before = scn.pos # regexp position is a regexp, else a div - if regexp_acceptable? && value = scn.scan(PATTERN_REGEX) + value = scn.scan(PATTERN_REGEX) if regexp_acceptable? + if value # Ensure an escaped / was not matched while escaped_end(value) more = scn.scan_until(PATTERN_REGEX_END) @@ -452,7 +453,8 @@ def initialize() '$' => lambda do scn = @scanner before = scn.pos - if value = scn.scan(PATTERN_DOLLAR_VAR) + value = scn.scan(PATTERN_DOLLAR_VAR) + if value emit_completed([:VARIABLE, value[1..-1].freeze, scn.pos - before], before) else # consume the $ and let higher layer complain about the error instead of getting a syntax error @@ -703,7 +705,8 @@ def scan # This is the lexer's main loop until queue.empty? && scn.eos? do - if token = queue.shift || selector[scn.peek(1)].call + token = queue.shift || selector[scn.peek(1)].call + if token ctx[:after] = token[0] yield token end diff --git a/lib/puppet/pops/parser/locator.rb b/lib/puppet/pops/parser/locator.rb index 3422993761f..bbeecea8075 100644 --- a/lib/puppet/pops/parser/locator.rb +++ b/lib/puppet/pops/parser/locator.rb @@ -177,7 +177,8 @@ def line_for_offset(offset) # use cache return @prev_line end - if line_nbr = ary_bsearch_i(line_index, offset) + line_nbr = ary_bsearch_i(line_index, offset) + if line_nbr # cache @prev_offset = offset @prev_line = line_nbr diff --git a/lib/puppet/pops/types/type_calculator.rb b/lib/puppet/pops/types/type_calculator.rb index c851868531f..663700efeb6 100644 --- a/lib/puppet/pops/types/type_calculator.rb +++ b/lib/puppet/pops/types/type_calculator.rb @@ -464,7 +464,7 @@ def common_type(t1, t2) # Produces the superclasses of the given class, including the class def superclasses(c) result = [c] - while s = c.superclass + while s = c.superclass #rubocop:disable Lint/AssignmentInCondition result << s c = s end diff --git a/lib/puppet/pops/types/type_parser.rb b/lib/puppet/pops/types/type_parser.rb index 9cd8ceaa00b..a4edaabb736 100644 --- a/lib/puppet/pops/types/type_parser.rb +++ b/lib/puppet/pops/types/type_parser.rb @@ -34,7 +34,8 @@ def initialize # def parse(string, context = nil) # quick "peephole" optimization of common data types - if t = self.class.opt_type_map[string] + t = self.class.opt_type_map[string] + if t return t end model = @parser.parse_string(string) @@ -276,7 +277,8 @@ def self.opt_type_map # @api private def interpret_QualifiedReference(name_ast, context) name = name_ast.value - if found = self.class.type_map[name] + found = self.class.type_map[name] + if found found else loader = loader_from_context(name_ast, context) diff --git a/lib/puppet/pops/validation.rb b/lib/puppet/pops/validation.rb index b514580f3e0..efba8bfc8dd 100644 --- a/lib/puppet/pops/validation.rb +++ b/lib/puppet/pops/validation.rb @@ -425,7 +425,8 @@ def accept(diagnostic) def prune(&block) removed = [] @diagnostics.delete_if do |d| - if should_remove = yield(d) + should_remove = yield(d) + if should_remove removed << d end should_remove diff --git a/lib/puppet/pops/validation/checker4_0.rb b/lib/puppet/pops/validation/checker4_0.rb index 2a194953744..37e1d746d1e 100644 --- a/lib/puppet/pops/validation/checker4_0.rb +++ b/lib/puppet/pops/validation/checker4_0.rb @@ -512,7 +512,8 @@ def internal_check_type_ref(o, r) end def internal_check_no_idem_last(o) - if violator = ends_with_idem(o.body) + violator = ends_with_idem(o.body) + if violator acceptor.accept(Issues::IDEM_NOT_ALLOWED_LAST, violator, {:container => o}) unless resource_without_title?(violator) end end @@ -731,7 +732,8 @@ def check_NodeDefinition(o) # Check that hostnames are valid hostnames (or regular expressions) hostname(o.host_matches, o) top(o) - if violator = ends_with_idem(o.body) + violator = ends_with_idem(o.body) + if violator acceptor.accept(Issues::IDEM_NOT_ALLOWED_LAST, violator, {:container => o}) unless resource_without_title?(violator) end unless o.parent.nil? @@ -917,7 +919,8 @@ def hostname_LiteralValue(o, semantic) def hostname_ConcatenatedString(o, semantic) # Puppet 3.1. only accepts a concatenated string without interpolated expressions - if the_expr = o.segments.index {|s| s.is_a?(Model::TextExpression) } + the_expr = o.segments.index {|s| s.is_a?(Model::TextExpression) } + if the_expr acceptor.accept(Issues::ILLEGAL_HOSTNAME_INTERPOLATION, o.segments[the_expr].expr) elsif o.segments.size() != 1 # corner case, bad model, concatenation of several plain strings diff --git a/lib/puppet/pops/visitor.rb b/lib/puppet/pops/visitor.rb index 0bcdec2cb2c..894e0791ad4 100644 --- a/lib/puppet/pops/visitor.rb +++ b/lib/puppet/pops/visitor.rb @@ -36,7 +36,8 @@ def visit_this(receiver, thing, args) if @max_args raise "Visitor Error: Too many arguments passed. max = #{@max_args}" unless args.length <= @max_args end - if method_name = @cache[thing.class] + method_name = @cache[thing.class] + if method_name return receiver.send(method_name, thing, *args) else thing.class.ancestors().each do |ancestor| @@ -57,7 +58,8 @@ def visit_this_class(receiver, clazz, args) if @max_args raise "Visitor Error: Too many arguments passed. max = #{@max_args}" unless args.length <= @max_args end - if method_name = @cache[clazz] + method_name = @cache[clazz] + if method_name return receiver.send(method_name, clazz, *args) else clazz.ancestors().each do |ancestor| @@ -76,7 +78,8 @@ def visit_this_class(receiver, clazz, args) # (This is ~30% faster than calling the general method) # def visit_this_0(receiver, thing) - if method_name = @cache[thing.class] + method_name = @cache[thing.class] + if method_name return receiver.send(method_name, thing) end visit_this(receiver, thing, NO_ARGS) @@ -86,7 +89,8 @@ def visit_this_0(receiver, thing) # (This is ~30% faster than calling the general method) # def visit_this_1(receiver, thing, arg) - if method_name = @cache[thing.class] + method_name = @cache[thing.class] + if method_name return receiver.send(method_name, thing, arg) end visit_this(receiver, thing, [arg]) @@ -96,7 +100,8 @@ def visit_this_1(receiver, thing, arg) # (This is ~30% faster than calling the general method) # def visit_this_2(receiver, thing, arg1, arg2) - if method_name = @cache[thing.class] + method_name = @cache[thing.class] + if method_name return receiver.send(method_name, thing, arg1, arg2) end visit_this(receiver, thing, [arg1, arg2]) @@ -106,7 +111,8 @@ def visit_this_2(receiver, thing, arg1, arg2) # (This is ~30% faster than calling the general method) # def visit_this_3(receiver, thing, arg1, arg2, arg3) - if method_name = @cache[thing.class] + method_name = @cache[thing.class] + if method_name return receiver.send(method_name, thing, arg1, arg2, arg3) end visit_this(receiver, thing, [arg1, arg2, arg3]) diff --git a/lib/puppet/property.rb b/lib/puppet/property.rb index 6676d5e8636..b2615320d20 100644 --- a/lib/puppet/property.rb +++ b/lib/puppet/property.rb @@ -123,9 +123,8 @@ def idempotent=(value) # @api private # def self.value_name(name) - if value = value_collection.match?(name) - value.name - end + value = value_collection.match?(name) + value.name if value end # Returns the value of the given option (set when a valid value with the given "name" was defined). @@ -137,9 +136,8 @@ def self.value_name(name) # @api private # def self.value_option(name, option) - if value = value_collection.value(name) - value.send(option) - end + value = value_collection.value(name) + value.send(option) if value end # Defines a new valid value for this property. @@ -255,9 +253,9 @@ def event_name # @see Puppet::Type#event def event(options = {}) attrs = { :name => event_name, :desired_value => should, :property => self, :source_description => path }.merge(options) - if should and value = self.class.value_collection.match?(should) - attrs[:invalidate_refreshes] = true if value.invalidate_refreshes - end + value = self.class.value_collection.match?(should) if should + + attrs[:invalidate_refreshes] = true if value && value.invalidate_refreshes attrs[:redacted] = @sensitive resource.event attrs end @@ -486,7 +484,8 @@ def retrieve def set(value) # Set a name for looking up associated options like the event. name = self.class.value_name(value) - if method = self.class.value_option(name, :method) and self.respond_to?(method) + method = self.class.value_option(name, :method) + if method && self.respond_to?(method) begin self.send(method) rescue Puppet::Error @@ -498,12 +497,15 @@ def set(value) Puppet.log_exception(detail, error.message) raise error end - elsif block = self.class.value_option(name, :block) - # FIXME It'd be better here to define a method, so that - # the blocks could return values. - self.instance_eval(&block) else - call_provider(value) + block = self.class.value_option(name, :block) + if block + # FIXME It'd be better here to define a method, so that + # the blocks could return values. + self.instance_eval(&block) + else + call_provider(value) + end end end @@ -585,7 +587,8 @@ def unsafe_validate(value) # @api private # def validate_features_per_value(value) - if features = self.class.value_option(self.class.value_name(value), :required_features) + 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(", ") unless provider.satisfies?(features) diff --git a/lib/puppet/property/ensure.rb b/lib/puppet/property/ensure.rb index d57db6d8ad9..5f9d3424cb8 100644 --- a/lib/puppet/property/ensure.rb +++ b/lib/puppet/property/ensure.rb @@ -77,7 +77,8 @@ def retrieve # to get checked, which means that those other properties do not have # @is values set. This seems to be the source of quite a few bugs, # although they're mostly logging bugs, not functional ones. - if prov = @resource.provider and prov.respond_to?(:exists?) + prov = @resource.provider + if prov && prov.respond_to?(:exists?) result = prov.exists? elsif @resource.respond_to?(:exists?) result = @resource.exists? diff --git a/lib/puppet/property/keyvalue.rb b/lib/puppet/property/keyvalue.rb index 1515e703eb5..30cdb1c8d86 100644 --- a/lib/puppet/property/keyvalue.rb +++ b/lib/puppet/property/keyvalue.rb @@ -107,7 +107,8 @@ def delimiter # def retrieve #ok, some 'convention' if the keyvalue property is named properties, provider should implement a properties method - if key_hash = provider.send(name) and key_hash != :absent + key_hash = provider.send(name) + if key_hash != :absent return key_hash else return :absent diff --git a/lib/puppet/property/list.rb b/lib/puppet/property/list.rb index 57cba3eabce..5c0c9c226de 100644 --- a/lib/puppet/property/list.rb +++ b/lib/puppet/property/list.rb @@ -45,7 +45,8 @@ def delimiter def retrieve #ok, some 'convention' if the list property is named groups, provider should implement a groups method - if provider and tmp = provider.send(name) and tmp != :absent + tmp = provider.send(name) if provider + if tmp && tmp != :absent return tmp.split(delimiter) else return :absent diff --git a/lib/puppet/provider.rb b/lib/puppet/provider.rb index 2929963dc9f..5c48ed8a72e 100644 --- a/lib/puppet/provider.rb +++ b/lib/puppet/provider.rb @@ -138,11 +138,9 @@ def self.execfail(*args) def self.command(name) name = name.intern - if defined?(@commands) and command = @commands[name] - # nothing - elsif superclass.respond_to? :command and command = superclass.command(name) - # nothing - else + command = defined?(@commands) && @commands[name] + command ||= superclass.respond_to?(:command) && superclass.command(name) + unless command raise Puppet::DevError, _("No command %{command} defined for provider %{provider}") % { command: name, provider: self.name } end @@ -466,11 +464,13 @@ def self.supports_parameter?(param) if param.is_a?(Class) klass = param else - unless klass = resource_type.attrclass(param) + klass = resource_type.attrclass(param) + unless klass raise Puppet::DevError, _("'%{parameter_name}' is not a valid parameter for %{resource_type}") % { parameter_name: param, resource_type: resource_type.name } end end - return true unless features = klass.required_features + features = klass.required_features + return true unless features !!satisfies?(*features) end @@ -546,7 +546,8 @@ def initialize(resource = nil) # @raise [Puppet::DevError] if no resource is set, or no name defined. # def name - if n = @property_hash[:name] + n = @property_hash[:name] + if n return n elsif self.resource resource.name diff --git a/lib/puppet/provider/exec.rb b/lib/puppet/provider/exec.rb index c69ff3d5090..277d58b1352 100644 --- a/lib/puppet/provider/exec.rb +++ b/lib/puppet/provider/exec.rb @@ -82,11 +82,14 @@ def run(command, check = false) def extractexe(command) if command.is_a? Array command.first - elsif match = /^"([^"]+)"|^'([^']+)'/.match(command) - # extract whichever of the two sides matched the content. - match[1] or match[2] else - command.split(/ /)[0] + match = /^"([^"]+)"|^'([^']+)'/.match(command) + if match + # extract whichever of the two sides matched the content. + match[1] or match[2] + else + command.split(/ /)[0] + end end end diff --git a/lib/puppet/provider/file/posix.rb b/lib/puppet/provider/file/posix.rb index 3bbe769baf9..a4b55e416a1 100644 --- a/lib/puppet/provider/file/posix.rb +++ b/lib/puppet/provider/file/posix.rb @@ -53,7 +53,8 @@ def name2gid(value) end def owner - unless stat = resource.stat + stat = resource.stat + unless stat return :absent end @@ -86,7 +87,8 @@ def owner=(should) end def group - return :absent unless stat = resource.stat + stat = resource.stat + return :absent unless stat currentvalue = stat.gid @@ -117,7 +119,8 @@ def group=(should) end def mode - if stat = resource.stat + stat = resource.stat + if stat return (stat.mode & 007777).to_s(8).rjust(4, '0') else return :absent diff --git a/lib/puppet/provider/group/groupadd.rb b/lib/puppet/provider/group/groupadd.rb index 621ba2eb880..4b0d6774335 100644 --- a/lib/puppet/provider/group/groupadd.rb +++ b/lib/puppet/provider/group/groupadd.rb @@ -73,7 +73,8 @@ def addcmd cmd = [command(:add)] end - if gid = @resource.should(:gid) + gid = @resource.should(:gid) + if gid unless gid == :absent cmd << flag(:gid) << gid end diff --git a/lib/puppet/provider/group/ldap.rb b/lib/puppet/provider/group/ldap.rb index 01ba43d3bd7..0ce91bc9816 100644 --- a/lib/puppet/provider/group/ldap.rb +++ b/lib/puppet/provider/group/ldap.rb @@ -24,9 +24,11 @@ provider = self manager.generates(:gidNumber).with do largest = 500 - if existing = provider.manager.search - existing.each do |hash| - next unless value = hash[:gid] + existing = provider.manager.search + if existing + existing.each do |hash| + value = hash[:gid] + next unless value num = value[0].to_i largest = num if num > largest end @@ -36,7 +38,8 @@ # Convert a group name to an id. def self.name2id(group) - return nil unless result = manager.search("cn=#{group}") and result.length > 0 + result = manager.search("cn=#{group}") + return nil unless result and result.length > 0 # Only use the first result. group = result[0] diff --git a/lib/puppet/provider/group/pw.rb b/lib/puppet/provider/group/pw.rb index 98d99b505e3..c9ea39de966 100644 --- a/lib/puppet/provider/group/pw.rb +++ b/lib/puppet/provider/group/pw.rb @@ -18,13 +18,15 @@ def addcmd cmd = [command(:pw), "groupadd", @resource[:name]] - if gid = @resource.should(:gid) + gid = @resource.should(:gid) + if gid unless gid == :absent cmd << flag(:gid) << gid end end - if members = @resource.should(:members) + members = @resource.should(:members) + if members unless members == :absent if members.is_a?(Array) members = members.join(",") diff --git a/lib/puppet/provider/ldap.rb b/lib/puppet/provider/ldap.rb index d46a7b9a595..c614712a1c3 100644 --- a/lib/puppet/provider/ldap.rb +++ b/lib/puppet/provider/ldap.rb @@ -10,7 +10,8 @@ class << self # Look up all instances at our location. Yay. def self.instances - return [] unless list = manager.search + list = manager.search + return [] unless list list.collect { |entry| new(entry) } end @@ -29,7 +30,8 @@ def self.manages(*args) # Query all of our resources from ldap. def self.prefetch(resources) resources.each do |name, resource| - if result = manager.find(name) + result = manager.find(name) + if result result[:ensure] = :present resource.provider = new(result) else @@ -45,7 +47,8 @@ def manager def create @property_hash[:ensure] = :present self.class.resource_type.validproperties.each do |property| - if val = resource.should(property) + val = resource.should(property) + if val if property.to_s == 'gid' self.gid = val else @@ -126,7 +129,8 @@ def properties # LAK:NOTE This is normally not used, because we rely on prefetching. def query # Use the module function. - unless attributes = manager.find(name) + attributes = manager.find(name) + unless attributes @ldap_properties = {} return nil end diff --git a/lib/puppet/provider/nameservice.rb b/lib/puppet/provider/nameservice.rb index e0411fb03f2..4c98c3dc73b 100644 --- a/lib/puppet/provider/nameservice.rb +++ b/lib/puppet/provider/nameservice.rb @@ -26,7 +26,7 @@ def instances objects = [] begin method = Puppet::Etc.method(:"get#{section}ent") - while ent = method.call + while ent = method.call #rubocop:disable Lint/AssignmentInCondition objects << new(:name => ent.name, :canonical_name => ent.canonical_name, :ensure => :present) end ensure @@ -61,7 +61,7 @@ def listbyname names = [] Puppet::Etc.send("set#{section()}ent") begin - while ent = Puppet::Etc.send("get#{section()}ent") + while ent = Puppet::Etc.send("get#{section()}ent") #rubocop:disable Lint/AssignmentInCondition names << ent.name yield ent.name if block_given? end @@ -124,7 +124,8 @@ def autogen(field) if id_generators[@resource.class.name] == field return self.class.autogen_id(field, @resource.class.name) else - if value = self.class.autogen_default(field) + value = self.class.autogen_default(field) + if value return value elsif respond_to?("autogen_#{field}") return send("autogen_#{field}") @@ -214,7 +215,8 @@ def get(param) end def munge(name, value) - if block = self.class.option(name, :munge) and block.is_a? Proc + block = self.class.option(name, :munge) + if block and block.is_a? Proc block.call(value) else value @@ -222,7 +224,8 @@ def munge(name, value) end def unmunge(name, value) - if block = self.class.option(name, :unmunge) and block.is_a? Proc + block = self.class.option(name, :unmunge) + if block and block.is_a? Proc block.call(value) else value diff --git a/lib/puppet/provider/nameservice/directoryservice.rb b/lib/puppet/provider/nameservice/directoryservice.rb index b9d474a8886..94aa01a837c 100644 --- a/lib/puppet/provider/nameservice/directoryservice.rb +++ b/lib/puppet/provider/nameservice/directoryservice.rb @@ -313,10 +313,13 @@ def ensure=(ensure_value) # have a string and need to convert it to a number if @resource.should(name) @resource.property(name).sync - elsif value = autogen(name) - self.send(name.to_s + "=", value) else - next + value = autogen(name) + if value + self.send(name.to_s + "=", value) + else + next + end end end end @@ -393,7 +396,8 @@ def create fail(_("Could not set GeneratedUID for %{resource} %{name}: %{detail}") % { resource: @resource.class.name, name: @resource.name, detail: detail }) end - if value = @resource.should(:password) and value != "" + value = @resource.should(:password) + if value && value != "" self.class.set_password(@resource[:name], guid, value) end diff --git a/lib/puppet/provider/network_device.rb b/lib/puppet/provider/network_device.rb index fcf5b56dabc..2545123d56f 100644 --- a/lib/puppet/provider/network_device.rb +++ b/lib/puppet/provider/network_device.rb @@ -13,7 +13,8 @@ def self.lookup(device, name) def self.prefetch(resources) resources.each do |name, resource| device = Puppet::Util::NetworkDevice.current || device(resource[:device_url]) - if result = lookup(device, name) + result = lookup(device, name) + if result result[:ensure] = :present resource.provider = new(device, result) else @@ -45,7 +46,8 @@ def initialize(device, *args) def create @property_hash[:ensure] = :present self.class.resource_type.validproperties.each do |property| - if val = resource.should(property) + val = resource.should(property) + if val @property_hash[property] = val end end diff --git a/lib/puppet/provider/package.rb b/lib/puppet/provider/package.rb index 311898f5063..9cdea51c41f 100644 --- a/lib/puppet/provider/package.rb +++ b/lib/puppet/provider/package.rb @@ -2,7 +2,8 @@ class Puppet::Provider::Package < Puppet::Provider # Prefetch our package list, yo. def self.prefetch(packages) instances.each do |prov| - if pkg = packages[prov.name] + pkg = packages[prov.name] + if pkg pkg.provider = prov end end diff --git a/lib/puppet/provider/package/aix.rb b/lib/puppet/provider/package/aix.rb index 5aceef99797..7999615891f 100644 --- a/lib/puppet/provider/package/aix.rb +++ b/lib/puppet/provider/package/aix.rb @@ -81,7 +81,8 @@ def uninstall end def install(useversion = true) - unless source = @resource[:source] + source = @resource[:source] + unless source self.fail _("A directory is required which will be used to find packages") end @@ -101,7 +102,8 @@ def install(useversion = true) def self.pkglist(hash = {}) cmd = [command(:lslpp), "-qLc"] - if name = hash[:pkgname] + name = hash[:pkgname] + if name cmd << name end diff --git a/lib/puppet/provider/package/appdmg.rb b/lib/puppet/provider/package/appdmg.rb index 05bf3094279..487e7c2aa90 100644 --- a/lib/puppet/provider/package/appdmg.rb +++ b/lib/puppet/provider/package/appdmg.rb @@ -98,10 +98,12 @@ def query end def install - unless source = @resource[:source] + source = @resource[:source] + unless source self.fail _("Mac OS X PKG DMGs must specify a package source.") end - unless name = @resource[:name] + name = @resource[:name] + unless name self.fail _("Mac OS X PKG DMGs must specify a package name.") end self.class.installpkgdmg(source,name) diff --git a/lib/puppet/provider/package/apple.rb b/lib/puppet/provider/package/apple.rb index 47d79b20d2e..1a6cecad720 100644 --- a/lib/puppet/provider/package/apple.rb +++ b/lib/puppet/provider/package/apple.rb @@ -37,7 +37,8 @@ def query end def install - unless source = @resource[:source] + source = @resource[:source] + unless source self.fail _("Mac OS X packages must specify a package source") end diff --git a/lib/puppet/provider/package/apt.rb b/lib/puppet/provider/package/apt.rb index 7fba4783499..8b0899f2577 100644 --- a/lib/puppet/provider/package/apt.rb +++ b/lib/puppet/provider/package/apt.rb @@ -49,7 +49,8 @@ def install checkforcdrom cmd = %w{-q -y} - if config = @resource[:configfiles] + config = @resource[:configfiles] + if config if config == :keep cmd << "-o" << 'DPkg::Options::=--force-confold' else @@ -89,7 +90,8 @@ def latest # preseeds answers to dpkg-set-selection from the "responsefile" # def run_preseed - if response = @resource[:responsefile] and Puppet::FileSystem.exist?(response) + response = @resource[:responsefile] + if response && Puppet::FileSystem.exist?(response) self.info(_("Preseeding %{response} to debconf-set-selections") % { response: response }) preseed response diff --git a/lib/puppet/provider/package/blastwave.rb b/lib/puppet/provider/package/blastwave.rb index 1dc709e940f..1ace40fe0e9 100644 --- a/lib/puppet/provider/package/blastwave.rb +++ b/lib/puppet/provider/package/blastwave.rb @@ -93,7 +93,8 @@ def latest end def query - if hash = self.class.blastlist(:justme => @resource[:name]) + hash = self.class.blastlist(:justme => @resource[:name]) + if hash hash else {:ensure => :absent} diff --git a/lib/puppet/provider/package/dpkg.rb b/lib/puppet/provider/package/dpkg.rb index 59ad544549a..f479f4c006e 100644 --- a/lib/puppet/provider/package/dpkg.rb +++ b/lib/puppet/provider/package/dpkg.rb @@ -30,7 +30,8 @@ def self.instances dpkgquery_piped('-W', '--showformat', self::DPKG_QUERY_FORMAT_STRING) do |pipe| # now turn each returned line into a package object pipe.each_line do |line| - if hash = parse_line(line) + hash = parse_line(line) + if hash packages << new(hash) end end @@ -53,7 +54,8 @@ def self.instances def self.parse_line(line) hash = nil - if match = self::FIELDS_REGEX.match(line) + match = self::FIELDS_REGEX.match(line) + if match hash = {} self::FIELDS.zip(match.captures) do |field,value| @@ -78,7 +80,8 @@ def self.parse_line(line) public def install - unless file = @resource[:source] + file = @resource[:source] + unless file raise ArgumentError, _("You cannot install dpkg packages without a source") end args = [] diff --git a/lib/puppet/provider/package/fink.rb b/lib/puppet/provider/package/fink.rb index 304d8c4e0e6..688f3db2c62 100644 --- a/lib/puppet/provider/package/fink.rb +++ b/lib/puppet/provider/package/fink.rb @@ -56,7 +56,8 @@ def latest # preseeds answers to dpkg-set-selection from the "responsefile" # def run_preseed - if response = @resource[:responsefile] and Puppet::FileSystem.exist?(response) + response = @resource[:responsefile] + if response && Puppet::FileSystem.exist?(response) self.info(_("Preseeding %{response} to debconf-set-selections") % { response: response }) preseed response diff --git a/lib/puppet/provider/package/gem.rb b/lib/puppet/provider/package/gem.rb index 9f99fcbed5e..775074af302 100644 --- a/lib/puppet/provider/package/gem.rb +++ b/lib/puppet/provider/package/gem.rb @@ -82,7 +82,8 @@ def self.gemlist(options) if options[:source] command_options << "--source" << options[:source] end - if name = options[:justme] + name = options[:justme] + if name command_options << '\A' + name + '\z' end @@ -161,7 +162,8 @@ def install(useversion = true) command_options << "--no-document" end - if source = resource[:source] + source = resource[:source] + if source begin uri = URI.parse(source) rescue => detail diff --git a/lib/puppet/provider/package/macports.rb b/lib/puppet/provider/package/macports.rb index 9668b21f8a0..ea8d2ce45dd 100644 --- a/lib/puppet/provider/package/macports.rb +++ b/lib/puppet/provider/package/macports.rb @@ -38,7 +38,8 @@ def self.parse_info_query_line(line) def self.hash_from_line(line, regex, fields) hash = {} - if match = regex.match(line) + match = regex.match(line) + if match fields.zip(match.captures) { |field, value| hash[field] = value } @@ -51,7 +52,8 @@ def self.hash_from_line(line, regex, fields) def self.instances packages = [] port("-q", :installed).each_line do |line| - if hash = parse_installed_query_line(line) + hash = parse_installed_query_line(line) + if hash packages << new(hash) end end @@ -82,7 +84,8 @@ def latest info_line = execute([command(:port), "-q", :info, "--line", "--version", "--revision", @resource[:name]], :failonfail => false, :combine => false) return nil if info_line == "" - if newest = self.class.parse_info_query_line(info_line) + newest = self.class.parse_info_query_line(info_line) + if newest current = query # We're doing some fiddling behind the scenes here to cope with updated revisions. # If we're already at the latest version/revision, then just return the version diff --git a/lib/puppet/provider/package/nim.rb b/lib/puppet/provider/package/nim.rb index 838c57d2ee3..b5a12083f53 100644 --- a/lib/puppet/provider/package/nim.rb +++ b/lib/puppet/provider/package/nim.rb @@ -55,7 +55,8 @@ def uninstall end def install(useversion = true) - unless source = @resource[:source] + source = @resource[:source] + unless source self.fail _("An LPP source location is required in 'source'") end @@ -213,7 +214,8 @@ def parse_showres_header_line(line) end def parse_installp_package_string(package_string) - unless match = package_string.match(self.class::INSTALLP_PACKAGE_REGEX) + match = package_string.match(self.class::INSTALLP_PACKAGE_REGEX) + unless match self.fail _("Unable to parse output from nimclient showres: package string does not match expected installp package string format:\n'%{package_string}'") % { package_string: package_string } end package_name = match.captures[0] @@ -222,7 +224,8 @@ def parse_installp_package_string(package_string) end def parse_rpm_package_string(package_string) - unless match = package_string.match(self.class::RPM_PACKAGE_REGEX) + match = package_string.match(self.class::RPM_PACKAGE_REGEX) + unless match self.fail _("Unable to parse output from nimclient showres: package string does not match expected rpm package string format:\n'%{package_string}'") % { package_string: package_string } end package_name = match.captures[0] @@ -231,7 +234,8 @@ def parse_rpm_package_string(package_string) end def parse_showres_package_line(line) - unless match = line.match(self.class::PACKAGE_LINE_REGEX) + match = line.match(self.class::PACKAGE_LINE_REGEX) + unless match self.fail _("Unable to parse output from nimclient showres: line does not match expected package line format:\n'%{line}'") % { line: line } end diff --git a/lib/puppet/provider/package/openbsd.rb b/lib/puppet/provider/package/openbsd.rb index 40b2e564919..89513fd54b0 100644 --- a/lib/puppet/provider/package/openbsd.rb +++ b/lib/puppet/provider/package/openbsd.rb @@ -33,7 +33,8 @@ def self.instances # now turn each returned line into a package object process.each_line { |line| - if match = regex.match(line.split[0]) + match = regex.match(line.split[0]) + if match fields.zip(match.captures) { |field,value| hash[field] = value } @@ -120,13 +121,17 @@ def parse_pkgconf unless @resource[:source] if Puppet::FileSystem.exist?("/etc/pkg.conf") File.open("/etc/pkg.conf", "rb").readlines.each do |line| - if matchdata = line.match(/^installpath\s*=\s*(.+)\s*$/i) + matchdata = line.match(/^installpath\s*=\s*(.+)\s*$/i) + if matchdata @resource[:source] = matchdata[1] - elsif matchdata = line.match(/^installpath\s*\+=\s*(.+)\s*$/i) - if @resource[:source].nil? - @resource[:source] = matchdata[1] - else - @resource[:source] += ":" + matchdata[1] + else + matchdata = line.match(/^installpath\s*\+=\s*(.+)\s*$/i) + if matchdata + if @resource[:source].nil? + @resource[:source] = matchdata[1] + else + @resource[:source] += ":" + matchdata[1] + end end end end @@ -198,7 +203,8 @@ def get_version version = -1 process.each_line do |line| - if match = regex.match(line.split[0]) + match = regex.match(line.split[0]) + if match # now we return the first version, unless ensure is latest version = match.captures[1] return version unless @resource[:ensure] == "latest" diff --git a/lib/puppet/provider/package/opkg.rb b/lib/puppet/provider/package/opkg.rb index a73b4c42d9a..2d0f95e9a03 100644 --- a/lib/puppet/provider/package/opkg.rb +++ b/lib/puppet/provider/package/opkg.rb @@ -16,7 +16,8 @@ def self.instances hash = {} process.each_line { |line| - if match = regex.match(line) + match = regex.match(line) + if match fields.zip(match.captures) { |field,value| hash[field] = value } hash[:provider] = self.name packages << new(hash) diff --git a/lib/puppet/provider/package/pacman.rb b/lib/puppet/provider/package/pacman.rb index ea160b84d1d..7902a7213fb 100644 --- a/lib/puppet/provider/package/pacman.rb +++ b/lib/puppet/provider/package/pacman.rb @@ -78,7 +78,8 @@ def self.get_installed_packages # pacman -Q output is 'packagename version-rel' regex = %r{^(\S+)\s(\S+)} pipe.each_line do |line| - if match = regex.match(line) + match = regex.match(line) + if match packages[match.captures[0]] = match.captures[1] else warning(_("Failed to match line '%{line}'") % { line: line }) diff --git a/lib/puppet/provider/package/pkgdmg.rb b/lib/puppet/provider/package/pkgdmg.rb index 5dcdd89e745..9bacace9a12 100644 --- a/lib/puppet/provider/package/pkgdmg.rb +++ b/lib/puppet/provider/package/pkgdmg.rb @@ -140,10 +140,12 @@ def query end def install - unless source = @resource[:source] + source = @resource[:source] + unless source raise Puppet::Error.new(_("Mac OS X PKG DMGs must specify a package source.")) end - unless name = @resource[:name] + name = @resource[:name] + unless name raise Puppet::Error.new(_("Mac OS X PKG DMGs must specify a package name.")) end self.class.installpkgdmg(source,name) diff --git a/lib/puppet/provider/package/pkgng.rb b/lib/puppet/provider/package/pkgng.rb index c28e873d58d..50ec493083e 100644 --- a/lib/puppet/provider/package/pkgng.rb +++ b/lib/puppet/provider/package/pkgng.rb @@ -29,7 +29,8 @@ def self.get_version_list end def self.get_latest_version(origin) - if latest_version = cached_version_list.lines.find { |l| l =~ /^#{origin} / } + latest_version = cached_version_list.lines.find { |l| l =~ /^#{origin} / } + if latest_version latest_version = latest_version.split(' ').last.split(')').first return latest_version end @@ -74,7 +75,8 @@ def self.instances def self.prefetch(resources) packages = instances resources.each_key do |name| - if provider = packages.find{|p| p.name == name or p.origin == name } + provider = packages.find{|p| p.name == name or p.origin == name } + if provider resources[name].provider = provider end end diff --git a/lib/puppet/provider/package/pkgutil.rb b/lib/puppet/provider/package/pkgutil.rb index 6c443e32ffb..d0815e0260e 100644 --- a/lib/puppet/provider/package/pkgutil.rb +++ b/lib/puppet/provider/package/pkgutil.rb @@ -169,7 +169,8 @@ def latest end def query - if hash = pkgsingle(@resource) + hash = pkgsingle(@resource) + if hash hash else {:ensure => :absent} diff --git a/lib/puppet/provider/package/portupgrade.rb b/lib/puppet/provider/package/portupgrade.rb index 9b6c28be2bd..7c1a81cddc4 100644 --- a/lib/puppet/provider/package/portupgrade.rb +++ b/lib/puppet/provider/package/portupgrade.rb @@ -52,7 +52,8 @@ def self.instances output.split("\n").each { |data| # reset hash to nil for each line hash.clear - if match = regex.match(data) + match = regex.match(data) + if match # Output matched regex fields.zip(match.captures) { |field, value| hash[field] = value diff --git a/lib/puppet/provider/package/rpm.rb b/lib/puppet/provider/package/rpm.rb index 6fc5cea972b..b27fe17b9b9 100644 --- a/lib/puppet/provider/package/rpm.rb +++ b/lib/puppet/provider/package/rpm.rb @@ -126,7 +126,8 @@ def query # Here we just retrieve the version from the file specified in the source. def latest - unless source = @resource[:source] + source = @resource[:source] + unless source @resource.fail _("RPMs must specify a package source") end @@ -138,7 +139,8 @@ def latest end def install - unless source = @resource[:source] + source = @resource[:source] + unless source @resource.fail _("RPMs must specify a package source") end @@ -333,7 +335,8 @@ def rpm_parse_evr(s) if ri v = s[0,ri] r = s[ri+1,s.length] - if arch = r.scan(ARCH_REGEX)[0] + arch = r.scan(ARCH_REGEX)[0] + if arch a = arch.gsub(/\./, '') r.gsub!(ARCH_REGEX, '') end @@ -401,7 +404,8 @@ def self.nevra_to_hash(line) line.strip! hash = {} - if match = self::NEVRA_REGEX.match(line) + match = self::NEVRA_REGEX.match(line) + if match self::NEVRA_FIELDS.zip(match.captures) { |f, v| hash[f] = v } hash[:provider] = self.name hash[:ensure] = "#{hash[:version]}-#{hash[:release]}" diff --git a/lib/puppet/provider/package/windows/package.rb b/lib/puppet/provider/package/windows/package.rb index 7e5a81a794c..db507769b0b 100644 --- a/lib/puppet/provider/package/windows/package.rb +++ b/lib/puppet/provider/package/windows/package.rb @@ -26,7 +26,8 @@ def self.each(&block) name = key.name.match(/^.+\\([^\\]+)$/).captures[0] [MsiPackage, ExePackage].find do |klass| - if pkg = klass.from_registry(name, values) + pkg = klass.from_registry(name, values) + if pkg yield pkg end end diff --git a/lib/puppet/provider/parsedfile.rb b/lib/puppet/provider/parsedfile.rb index a20df0901aa..67afd54ef06 100644 --- a/lib/puppet/provider/parsedfile.rb +++ b/lib/puppet/provider/parsedfile.rb @@ -46,10 +46,13 @@ def self.filetype def self.filetype=(type) if type.is_a?(Class) @filetype = type - elsif klass = Puppet::Util::FileType.filetype(type) - @filetype = klass else - raise ArgumentError, _("Invalid filetype %{type}") % { type: type } + klass = Puppet::Util::FileType.filetype(type) + if klass + @filetype = klass + else + raise ArgumentError, _("Invalid filetype %{type}") % { type: type } + end end end @@ -240,7 +243,8 @@ def self.match_providers_with_resources(resources) if (resource = resource_for_record(record, resources)) resource.provider = new(record) elsif respond_to?(:match) - if resource = match(record, matchers) + resource = match(record, matchers) + if resource matchers.delete(resource.title) record[:name] = resource[:name] resource.provider = new(record) @@ -380,7 +384,8 @@ def self.targets(resources = nil) # Lastly, check the file from any resource instances if resources resources.each do |name, resource| - if value = resource.should(:target) + value = resource.should(:target) + if value targets << value end end @@ -414,7 +419,8 @@ def self.to_file(records) def create @resource.class.validproperties.each do |property| - if value = @resource.should(property) + value = @resource.should(property) + if value @property_hash[property] = value end end @@ -472,7 +478,8 @@ def record_type # Mark both the resource and provider target as modified. def mark_target_modified - if defined?(@resource) and restarget = @resource.should(:target) and restarget != @property_hash[:target] + restarget = @resource.should(:target) if defined?(@resource) + if restarget && restarget != @property_hash[:target] self.class.modified(restarget) end self.class.modified(@property_hash[:target]) if @property_hash[:target] != :absent and @property_hash[:target] diff --git a/lib/puppet/provider/service/base.rb b/lib/puppet/provider/service/base.rb index f41a7436c50..9576398597e 100644 --- a/lib/puppet/provider/service/base.rb +++ b/lib/puppet/provider/service/base.rb @@ -76,11 +76,14 @@ def status else return :stopped end - elsif pid = getpid - self.debug "PID is #{pid}" - return :running else - return :stopped + pid = getpid + if pid + self.debug "PID is #{pid}" + return :running + else + return :stopped + end end end diff --git a/lib/puppet/provider/service/launchd.rb b/lib/puppet/provider/service/launchd.rb index 950fb164e2a..231285f6eb2 100644 --- a/lib/puppet/provider/service/launchd.rb +++ b/lib/puppet/provider/service/launchd.rb @@ -92,7 +92,8 @@ def self.launchd_overrides # clear out our cache when we're done. def self.prefetch(resources) instances.each do |prov| - if resource = resources[prov.name] + resource = resources[prov.name] + if resource resource.provider = prov end end @@ -316,7 +317,8 @@ def enabled? _, job_plist = plist_from_label(resource[:name]) job_plist_disabled = job_plist["Disabled"] if job_plist.has_key?("Disabled") - if FileTest.file?(self.class.launchd_overrides) and overrides = self.class.read_overrides + overrides = self.class.read_overrides if FileTest.file?(self.class.launchd_overrides) + if overrides if overrides.has_key?(resource[:name]) if self.class.get_os_version < 14 overrides_disabled = overrides[resource[:name]]["Disabled"] if overrides[resource[:name]].has_key?("Disabled") diff --git a/lib/puppet/provider/service/service.rb b/lib/puppet/provider/service/service.rb index 1b955425480..2d3747f9dde 100644 --- a/lib/puppet/provider/service/service.rb +++ b/lib/puppet/provider/service/service.rb @@ -31,7 +31,8 @@ def texecute(type, command, fof = true, squelch = false, combine = true) # Use either a specified command or the default for our provider. def ucommand(type, fof = true) - if c = @resource[type] + c = @resource[type] + if c cmd = [c] else cmd = [send("#{type}cmd")].flatten diff --git a/lib/puppet/provider/service/upstart.rb b/lib/puppet/provider/service/upstart.rb index f7b97f6f6ce..ac781b9ee43 100644 --- a/lib/puppet/provider/service/upstart.rb +++ b/lib/puppet/provider/service/upstart.rb @@ -76,14 +76,17 @@ def self.get_services(exclude=[]) # network-interface (lo) start/running # network-interface (eth0) start/running # network-interface-security start/running - name = \ - if matcher = line.match(/^(network-interface)\s\(([^\)]+)\)/) - "#{matcher[1]} INTERFACE=#{matcher[2]}" - elsif matcher = line.match(/^(network-interface-security)\s\(([^\)]+)\)/) - "#{matcher[1]} JOB=#{matcher[2]}" - else - line.split.first - end + matcher = line.match(/^(network-interface)\s\(([^\)]+)\)/) + name = if matcher + "#{matcher[1]} INTERFACE=#{matcher[2]}" + else + matcher = line.match(/^(network-interface-security)\s\(([^\)]+)\)/) + if matcher + "#{matcher[1]} JOB=#{matcher[2]}" + else + line.split.first + end + end instances << new(:name => name) } } diff --git a/lib/puppet/provider/user/directoryservice.rb b/lib/puppet/provider/user/directoryservice.rb index 4742d2c2bbe..4216a2ceedb 100644 --- a/lib/puppet/provider/user/directoryservice.rb +++ b/lib/puppet/provider/user/directoryservice.rb @@ -71,7 +71,8 @@ def self.ns_to_ds_attribute_map # takes time and front-loads your Puppet run. def self.prefetch(resources) instances.each do |prov| - if resource = resources[prov.name] + resource = resources[prov.name] + if resource resource.provider = prov end end diff --git a/lib/puppet/provider/user/hpux.rb b/lib/puppet/provider/user/hpux.rb index 6cf5045ed5d..f551059db03 100644 --- a/lib/puppet/provider/user/hpux.rb +++ b/lib/puppet/provider/user/hpux.rb @@ -46,7 +46,7 @@ def modifycmd(param,value) def password # Password management routine for trusted and non-trusted systems #temp="" - while ent = Etc.getpwent() do + while ent = Etc.getpwent() do # rubocop:disable Lint/AssignmentInCondition if ent.name == resource.name temp=ent.name break diff --git a/lib/puppet/provider/user/ldap.rb b/lib/puppet/provider/user/ldap.rb index 9828325d127..829ffb87172 100644 --- a/lib/puppet/provider/user/ldap.rb +++ b/lib/puppet/provider/user/ldap.rb @@ -34,9 +34,11 @@ provider = self manager.generates(:uidNumber).with do largest = 500 - if existing = provider.manager.search + existing = provider.manager.search + if existing existing.each do |hash| - next unless value = hash[:uid] + value = hash[:uid] + next unless value num = value[0].to_i largest = num if num > largest end @@ -56,7 +58,8 @@ def groups # We want to cache the current result, so we know if we # have to remove old values. unless @property_hash[:groups] - unless result = group_manager.search("memberUid=#{name}") + result = group_manager.search("memberUid=#{name}") + unless result return @property_hash[:groups] = :absent end @@ -88,7 +91,8 @@ def groups=(values) end modes.each do |group, form| - self.fail "Could not find ldap group #{group}" unless ldap_group = group_manager.find(group) + ldap_group = group_manager.find(group) + self.fail "Could not find ldap group #{group}" unless ldap_group current = ldap_group[:members] diff --git a/lib/puppet/provider/user/openbsd.rb b/lib/puppet/provider/user/openbsd.rb index f95baae4307..1b550226e1a 100644 --- a/lib/puppet/provider/user/openbsd.rb +++ b/lib/puppet/provider/user/openbsd.rb @@ -39,7 +39,8 @@ [:expiry, :password, :loginclass].each do |shadow_property| define_method(shadow_property) do if Puppet.features.libshadow? - if ent = Shadow::Passwd.getspnam(@resource.name) + ent = Shadow::Passwd.getspnam(@resource.name) + if ent method = self.class.option(shadow_property, :method) # ruby-shadow may not be new enough (< 2.4.1) and therefore lack the # sp_loginclass field. diff --git a/lib/puppet/provider/user/pw.rb b/lib/puppet/provider/user/pw.rb index de4db94bd13..933b28bfa40 100644 --- a/lib/puppet/provider/user/pw.rb +++ b/lib/puppet/provider/user/pw.rb @@ -31,7 +31,8 @@ def addcmd cmd = [command(:pw), "useradd", @resource[:name]] @resource.class.validproperties.each do |property| next if property == :ensure or property == :password - if value = @resource.should(property) and value != "" + value = @resource.should(property) + if value and value != "" cmd << flag(property) << munge(property,value) end end diff --git a/lib/puppet/provider/user/user_role_add.rb b/lib/puppet/provider/user/user_role_add.rb index eb49fb356c7..7090a021f06 100644 --- a/lib/puppet/provider/user/user_role_add.rb +++ b/lib/puppet/provider/user/user_role_add.rb @@ -53,7 +53,8 @@ def add_properties # 1680 Now you can set the hashed passwords on solaris:lib/puppet/provider/user/user_role_add.rb # the value needs to be quoted, mostly because -c might # have spaces in it - if value = @resource.should(property) and value != "" + value = @resource.should(property) + if value && value != "" if property == :keys cmd += build_keys_cmd(value) else @@ -99,7 +100,8 @@ def create run(transition("normal"), "transition role to") else run(addcmd, "create") - if cmd = passcmd + cmd = passcmd + if cmd run(cmd, "change password policy for") end end diff --git a/lib/puppet/provider/user/useradd.rb b/lib/puppet/provider/user/useradd.rb index 0ff187cc5d8..73a3e956a35 100644 --- a/lib/puppet/provider/user/useradd.rb +++ b/lib/puppet/provider/user/useradd.rb @@ -151,9 +151,11 @@ def add_properties next if property_manages_password_age?(property) next if (property == :groups) && @resource.forcelocal? next if (property == :expiry) && @resource.forcelocal? - # the value needs to be quoted, mostly because -c might - # have spaces in it - if (value = @resource.should(property)) && (value != "") + + value = @resource.should(property) + if value && value != "" + # the value needs to be quoted, mostly because -c might + # have spaces in it cmd << flag(property) << munge(property, value) end end @@ -228,7 +230,8 @@ def passcmd [:expiry, :password_min_age, :password_max_age, :password_warn_days, :password].each do |shadow_property| define_method(shadow_property) do if Puppet.features.libshadow? - if ent = Shadow::Passwd.getspnam(@canonical_name) + ent = Shadow::Passwd.getspnam(@canonical_name) + if ent method = self.class.option(shadow_property, :method) return unmunge(shadow_property, ent.send(method)) end diff --git a/lib/puppet/reference/providers.rb b/lib/puppet/reference/providers.rb index 8868adc09cb..d53e6c7fe64 100644 --- a/lib/puppet/reference/providers.rb +++ b/lib/puppet/reference/providers.rb @@ -41,7 +41,8 @@ provider = type.provider(pname) # Add the suitability note - if missing = provider.suitable?(false) and missing.empty? + missing = provider.suitable?(false) + if missing && missing.empty? data << "*X*" suit = true functional = true diff --git a/lib/puppet/reference/type.rb b/lib/puppet/reference/type.rb index e9cfdb98722..7cd60ff5672 100644 --- a/lib/puppet/reference/type.rb +++ b/lib/puppet/reference/type.rb @@ -63,7 +63,8 @@ str << scrub(type.doc) + "\n\n" # Handle the feature docs. - if featuredocs = type.featuredocs + featuredocs = type.featuredocs + if featuredocs str << markdown_header("Features", 4) str << featuredocs end @@ -79,7 +80,8 @@ raise _("Could not retrieve property %{sname} on type %{type_name}") % { sname: sname, type_name: type.name } unless property - unless doc = property.doc + doc = property.doc + unless doc $stderr.puts _("No docs for %{type}[%{sname}]") % { type: type, sname: sname } next end diff --git a/lib/puppet/relationship.rb b/lib/puppet/relationship.rb index 97248e48778..c3380c847ed 100644 --- a/lib/puppet/relationship.rb +++ b/lib/puppet/relationship.rb @@ -19,12 +19,8 @@ def self.from_data_hash(data) target = data['target'] args = {} - if event = data["event"] - args[:event] = :"#{event}" - end - if callback = data["callback"] - args[:callback] = :"#{callback}" - end + args[:event] = :"#{data['event']}" if data["event"] + args[:callback] = :"#{data['callback']}" if data["callback"] new(source, target, args) end @@ -40,9 +36,8 @@ def initialize(source, target, options = {}) options = (options || {}).inject({}) { |h,a| h[a[0].to_sym] = a[1]; h } [:callback, :event].each do |option| - if value = options[option] - send(option.to_s + "=", value) - end + value = options[option] + send(option.to_s + "=", value) if value end end diff --git a/lib/puppet/resource.rb b/lib/puppet/resource.rb index ddf4df81b9e..804b65af232 100644 --- a/lib/puppet/resource.rb +++ b/lib/puppet/resource.rb @@ -44,11 +44,14 @@ def self.from_data_hash(data) end def initialize_from_hash(data) - raise ArgumentError, _('No resource type provided in serialized data') unless type = data['type'] - raise ArgumentError, _('No resource title provided in serialized data') unless title = data['title'] + type = data['type'] + raise ArgumentError, _('No resource type provided in serialized data') unless type + title = data['title'] + raise ArgumentError, _('No resource title provided in serialized data') unless title @type, @title = self.class.type_and_title(type, title) - if params = data['parameters'] + params = data['parameters'] + if params params = Puppet::Pops::Serialization::FromDataConverter.convert(params) @parameters = {} params.each { |param, value| self[param] = value } @@ -56,13 +59,15 @@ def initialize_from_hash(data) @parameters = EMPTY_HASH end - if sensitives = data['sensitive_parameters'] + sensitives = data['sensitive_parameters'] + if sensitives @sensitive_parameters = sensitives.map(&:to_sym) else @sensitive_parameters = EMPTY_ARRAY end - if tags = data['tags'] + tags = data['tags'] + if tags tag(*tags) end @@ -554,7 +559,8 @@ def validate_complete arg_types = resource_type.argument_types # Parameters is a map from name, to parameter, and the parameter again has name and value parameters.each do |name, value| - next unless t = arg_types[name.to_s] # untyped, and parameters are symbols here (aargh, strings in the type) + t = arg_types[name.to_s] # untyped, and parameters are symbols here (aargh, strings in the type) + next unless t unless Puppet::Pops::Types::TypeCalculator.instance?(t, value.value) inferred_type = Puppet::Pops::Types::TypeCalculator.infer_set(value.value) actual = inferred_type.generalize() @@ -658,7 +664,8 @@ def parse_title type = resource_type if type.respond_to?(:title_patterns) && !type.title_patterns.nil? type.title_patterns.each { |regexp, symbols_and_lambdas| - if captures = regexp.match(title.to_s) + captures = regexp.match(title.to_s) + if captures symbols_and_lambdas.zip(captures[1..-1]).each do |symbol_and_lambda,capture| symbol, proc = symbol_and_lambda # Many types pass "identity" as the proc; we might as well give diff --git a/lib/puppet/resource/capability_finder.rb b/lib/puppet/resource/capability_finder.rb index eba99265dd1..d1a4307a112 100644 --- a/lib/puppet/resource/capability_finder.rb +++ b/lib/puppet/resource/capability_finder.rb @@ -38,14 +38,17 @@ def self.find(environment, code_id, cap) Puppet.debug "Could not find capability resource #{cap} in PuppetDB" elsif resources.size == 1 resource_hash = resources.first - elsif code_id_resource = disambiguate_by_code_id(environment, code_id, cap) - resource_hash = code_id_resource else - #TRANSLATOR PuppetDB is a product name and should not be translated - message = _("Unexpected response from PuppetDB when looking up %{capability}:") % { capability: cap } - message += "\n" + _("expected exactly one resource but got %{count};") % { count: resources.size } - message += "\n" + _("returned data is:\n%{resources}") % { resources: resources.inspect } - raise Puppet::DevError, message + code_id_resource = disambiguate_by_code_id(environment, code_id, cap) + if code_id_resource + resource_hash = code_id_resource + else + #TRANSLATOR PuppetDB is a product name and should not be translated + message = _("Unexpected response from PuppetDB when looking up %{capability}:") % { capability: cap } + message += "\n" + _("expected exactly one resource but got %{count};") % { count: resources.size } + message += "\n" + _("returned data is:\n%{resources}") % { resources: resources.inspect } + raise Puppet::DevError, message + end end if resource_hash @@ -138,7 +141,8 @@ def self.instantiate_resource(resource_hash) real_type.parameters.each do |param| param = param.to_s next if param == 'name' - if value = resource_hash['parameters'][param] + value = resource_hash['parameters'][param] + if value resource[param] = value else Puppet.debug "No capability value for #{resource}->#{param}" diff --git a/lib/puppet/resource/catalog.rb b/lib/puppet/resource/catalog.rb index d82458a435a..c5eeb1ad68e 100644 --- a/lib/puppet/resource/catalog.rb +++ b/lib/puppet/resource/catalog.rb @@ -197,7 +197,8 @@ def alias(resource, key) # because sometimes an alias is created before the resource is # added to the catalog, so comparing inside the below if block # isn't sufficient. - if existing = @resource_table[newref] + existing = @resource_table[newref] + if existing return if existing == resource resource_declaration = Puppet::Util::Errors.error_location(resource.file, resource.line) msg = if resource_declaration.empty? @@ -286,10 +287,12 @@ def classes # Create a new resource and register it in the catalog. def create_resource(type, options) - unless klass = Puppet::Type.type(type) + klass = Puppet::Type.type(type) + unless klass raise ArgumentError, _("Unknown resource type %{type}") % { type: type } end - return unless resource = klass.new(options) + resource = klass.new(options) + return unless resource add_resource(resource) resource @@ -342,7 +345,8 @@ def make_default_resources Puppet::Type.type(:schedule).mkdefaultschedules.each { |res| add_resource(res) unless resource(res.ref) } # And filebuckets - if bucket = Puppet::Type.type(:filebucket).mkdefaultbucket + bucket = Puppet::Type.type(:filebucket).mkdefaultbucket + if bucket add_resource(bucket) unless resource(bucket.ref) end end @@ -355,7 +359,8 @@ def remove_resource(*resources) ref = resource.ref title_key = title_key_for_ref(ref) @resource_table.delete(title_key) - if aliases = @aliases[ref] + aliases = @aliases[ref] + if aliases aliases.each { |res_alias| @resource_table.delete(res_alias) } @aliases.delete(ref) end @@ -415,45 +420,36 @@ def resources def self.from_data_hash(data) result = new(data['name'], Puppet::Node::Environment::NONE) - if tags = data['tags'] - result.tag(*tags) - end - - if version = data['version'] - result.version = version - end - - if code_id = data['code_id'] - result.code_id = code_id - end - - if catalog_uuid = data['catalog_uuid'] - result.catalog_uuid = catalog_uuid - end - + result.tag(*data['tags']) if data['tags'] + result.version = data['version'] if data['version'] + result.code_id = data['code_id'] if data['code_id'] + result.catalog_uuid = data['catalog_uuid'] if data['catalog_uuid'] result.catalog_format = data['catalog_format'] || 0 - if environment = data['environment'] + environment = data['environment'] + if environment result.environment = environment result.environment_instance = Puppet::Node::Environment.remote(environment.to_sym) end - if resources = data['resources'] - result.add_resource(*resources.collect do |res| + result.add_resource( + *data['resources'].collect do |res| Puppet::Resource.from_data_hash(res) - end) - end + end + ) if data['resources'] - if edges = data['edges'] - edges.each do |edge_hash| + if data['edges'] + data['edges'].each do |edge_hash| edge = Puppet::Relationship.from_data_hash(edge_hash) - unless source = result.resource(edge.source) + source = result.resource(edge.source) + unless source raise ArgumentError, _("Could not intern from data: Could not find relationship source %{source} for %{target}") % { source: edge.source.inspect, target: edge.target.to_s } end edge.source = source - unless target = result.resource(edge.target) + target = result.resource(edge.target) + unless target raise ArgumentError, _("Could not intern from data: Could not find relationship target %{target} for %{source}") % { target: edge.target.inspect, source: edge.source.to_s } end @@ -463,15 +459,12 @@ def self.from_data_hash(data) end end - if classes = data['classes'] - result.add_class(*classes) - end + result.add_class(*data['classes']) if data['classes'] - if metadata = data['metadata'] - result.metadata = metadata.inject({}) { |h, (k, v)| h[k] = Puppet::FileServing::Metadata.from_data_hash(v); h } - end + result.metadata = data['metadata'].inject({}) { |h, (k, v)| h[k] = Puppet::FileServing::Metadata.from_data_hash(v); h } if data['metadata'] - if recursive_metadata = data['recursive_metadata'] + recursive_metadata = data['recursive_metadata'] + if recursive_metadata result.recursive_metadata = recursive_metadata.inject({}) do |h, (title, source_to_meta_hash)| h[title] = source_to_meta_hash.inject({}) do |inner_h, (source, metas)| inner_h[source] = metas.map {|meta| Puppet::FileServing::Metadata.from_data_hash(meta)} @@ -592,7 +585,8 @@ def create_transaction(options) # Verify that the given resource isn't declared elsewhere. def fail_on_duplicate_type_and_title(resource, title_key) # Short-circuit the common case, - return unless existing_resource = @resource_table[title_key] + existing_resource = @resource_table[title_key] + return unless existing_resource # If we've gotten this far, it's a real conflict error_location_str = Puppet::Util::Errors.error_location(existing_resource.file, existing_resource.line) @@ -646,11 +640,13 @@ def to_catalog(convert) next if virtual_not_exported?(edge.target) next if block_given? and yield edge.target - unless source = map[edge.source.ref] + source = map[edge.source.ref] + unless source raise Puppet::DevError, _("Could not find resource %{resource} when converting %{message} resources") % { resource: edge.source.ref, message: message } end - unless target = map[edge.target.ref] + target = map[edge.target.ref] + unless target raise Puppet::DevError, _("Could not find resource %{resource} when converting %{message} resources") % { resource: edge.target.ref, message: message } end diff --git a/lib/puppet/resource/type.rb b/lib/puppet/resource/type.rb index 80326f2a4a0..a4c87419fc0 100644 --- a/lib/puppet/resource/type.rb +++ b/lib/puppet/resource/type.rb @@ -89,7 +89,8 @@ def evaluate_produces(resource, scope) produced_resource.resource_type.parameters.each do |name| next if name == :name - if expr = blueprint[:mappings][name.to_s] + expr = blueprint[:mappings][name.to_s] + if expr produced_resource[name] = expr.safeevaluate(scope) else produced_resource[name] = scope[name.to_s] @@ -147,7 +148,8 @@ def initialize(type, name, options = {}) set_name_and_namespace(name) [:code, :doc, :line, :file, :parent].each do |param| - next unless value = options[param] + value = options[param] + next unless value send(param.to_s + '=', value) end @@ -453,7 +455,9 @@ def convert_from_ast(name) end def evaluate_parent_type(resource) - return unless klass = parent_type(resource.scope) and parent_resource = resource.scope.compiler.catalog.resource(:class, klass.name) || resource.scope.compiler.catalog.resource(:node, klass.name) + klass = parent_type(resource.scope) + parent_resource = resource.scope.compiler.catalog.resource(:class, klass.name) || resource.scope.compiler.catalog.resource(:node, klass.name) if klass + return unless klass && parent_resource parent_resource.evaluate unless parent_resource.evaluated? parent_scope(resource.scope, klass) end diff --git a/lib/puppet/resource/type_collection.rb b/lib/puppet/resource/type_collection.rb index c4770f8f2da..4aac4f9837f 100644 --- a/lib/puppet/resource/type_collection.rb +++ b/lib/puppet/resource/type_collection.rb @@ -124,7 +124,8 @@ def loader def node(name) name = munge_name(name) - if node = @nodes[name] + node = @nodes[name] + if node return node end @@ -250,7 +251,8 @@ def munge_name(name) end def dupe_check(instance, hash) - return unless dupe = hash[instance.name] + dupe = hash[instance.name] + return unless dupe message = yield dupe instance.fail Puppet::ParseError, message end diff --git a/lib/puppet/settings.rb b/lib/puppet/settings.rb index 48226af6f7e..5a08bd13963 100644 --- a/lib/puppet/settings.rb +++ b/lib/puppet/settings.rb @@ -298,7 +298,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 + while option_index = args.index('--run_mode') do #rubocop:disable Lint/AssignmentInCondition args.delete_at option_index args.delete_at option_index end @@ -380,7 +380,8 @@ def call_hooks_deferred_to_application_initialization(options = {}) # Return a value's description. def description(name) - if obj = @config[name.to_sym] + obj = @config[name.to_sym] + if obj obj.desc else nil @@ -436,7 +437,8 @@ def handlearg(opt, value = nil) end end - if s = @config[str] + s = @config[str] + if s @deprecated_settings_that_have_been_configured << s if s.completely_deprecated? end @@ -651,7 +653,8 @@ def apply_metadata # and I'm too lazy to only set the metadata once. if @configuration_file searchpath(nil, preferred_run_mode).reverse_each do |source| - if source.type == :section && section = @configuration_file.sections[source.name] + section = @configuration_file.sections[source.name] if source.type == :section + if section apply_metadata_from_section(section) end end @@ -661,7 +664,8 @@ def apply_metadata def apply_metadata_from_section(section) section.settings.each do |setting| - if setting.has_metadata? && type = @config[setting.name] + type = @config[setting.name] if setting.has_metadata? + if type type.set_meta(setting.meta) end end @@ -695,8 +699,10 @@ def newsetting(hash) klass = nil hash[:section] = hash[:section].to_sym if hash[:section] - if type = hash[:type] - unless klass = SETTING_TYPES[type] + type = hash[:type] + if type + klass = SETTING_TYPES[type] + unless klass raise ArgumentError, _("Invalid setting type '%{type}'") % { type: type } end hash.delete(:type) @@ -728,7 +734,8 @@ def persection(section) # Reparse our config file, if necessary. def reparse_config_files if files - if filename = any_files_changed? + filename = any_files_changed? + if filename Puppet.notice "Config file #{filename} changed; triggering re-parse of all config files." parse_config_files reuse @@ -835,7 +842,8 @@ def searchpath_values(source) when :values @value_sets[source.name] when :section - if @configuration_file && section = @configuration_file.sections[source.name] + section = @configuration_file.sections[source.name] if @configuration_file + if section ValuesFromSection.new(source.name, section) end when :environment @@ -850,7 +858,8 @@ def searchpath_values(source) def set_by_config?(param, environment = nil, run_mode = preferred_run_mode) param = param.to_sym configsearchpath(environment, run_mode).any? do |source| - if vals = searchpath_values(source) + vals = searchpath_values(source) + if vals vals.lookup(param) end end @@ -910,8 +919,10 @@ def define_settings(section, defs) hash[:section] = section raise ArgumentError, _("Setting %{name} is already defined") % { name: name } if @config.include?(name) tryconfig = newsetting(hash) - if short = tryconfig.short - if other = @shortnames[short] + short = tryconfig.short + if short + other = @shortnames[short] + if other raise ArgumentError, _("Setting %{name} is already using short name '%{short}'") % { name: other.name, short: short } end @shortnames[short] = tryconfig @@ -946,7 +957,8 @@ def to_catalog(*sections) file = @config[key] next if file.value.nil? next unless (sections.nil? or sections.include?(file.section)) - next unless resource = file.to_resource + resource = file.to_resource + next unless resource next if catalog.resource(resource.ref) Puppet.debug {"Using settings: adding file resource '#{key}': '#{resource.inspect}'"} @@ -1147,7 +1159,8 @@ def screen_non_puppet_conf_settings(puppet_conf) def record_deprecations_from_puppet_conf(puppet_conf) puppet_conf.sections.values.each do |section| section.settings.each do |conf_setting| - if setting = self.setting(conf_setting.name) + setting = self.setting(conf_setting.name) + if setting @deprecated_settings_that_have_been_configured << setting if setting.deprecated? end end @@ -1209,12 +1222,14 @@ def add_user_resources(catalog, sections) next unless setting.respond_to?(:owner) next unless sections.nil? or sections.include?(setting.section) - if user = setting.owner and user != "root" and catalog.resource(:user, user).nil? + user = setting.owner + if user && user != "root" && catalog.resource(:user, user).nil? resource = Puppet::Resource.new(:user, user, :parameters => {:ensure => :present}) resource[:gid] = self[:group] if self[:group] catalog.add_resource resource end - if group = setting.group and ! %w{root wheel}.include?(group) and catalog.resource(:group, group).nil? + group = setting.group + if group && ! %w{root wheel}.include?(group) && catalog.resource(:group, group).nil? catalog.add_resource Puppet::Resource.new(:group, group, :parameters => {:ensure => :present}) end end @@ -1478,9 +1493,11 @@ def lookup(name) end def conf - @conf ||= if environments = Puppet.lookup(:environments) { nil } - environments.get_conf(@environment_name) - end + unless @conf + environments = Puppet.lookup(:environments) { nil } + @conf = environments.get_conf(@environment_name) if environments + end + @conf end def inspect diff --git a/lib/puppet/settings/base_setting.rb b/lib/puppet/settings/base_setting.rb index 2777a0ca3c2..203aef85a8e 100644 --- a/lib/puppet/settings/base_setting.rb +++ b/lib/puppet/settings/base_setting.rb @@ -59,7 +59,8 @@ def has_hook? # Create the new element. Pretty much just sets the name. def initialize(args = {}) - unless @settings = args.delete(:settings) + @settings = args.delete(:settings) + unless @settings raise ArgumentError.new("You must refer to a settings object") end diff --git a/lib/puppet/settings/config_file.rb b/lib/puppet/settings/config_file.rb index 87abc7de455..f8ab50d423b 100644 --- a/lib/puppet/settings/config_file.rb +++ b/lib/puppet/settings/config_file.rb @@ -109,7 +109,8 @@ def parse_setting(setting, section) # Check to see if this is a file argument and it has extra options begin - if value.is_a?(String) and options = extract_fileinfo(value) + options = extract_fileinfo(value) if value.is_a?(String) + if options section.with_setting(var, options[:value], Meta.new(options[:owner], options[:group], options[:mode])) diff --git a/lib/puppet/settings/file_setting.rb b/lib/puppet/settings/file_setting.rb index 90010cd09c2..e0b40331887 100644 --- a/lib/puppet/settings/file_setting.rb +++ b/lib/puppet/settings/file_setting.rb @@ -125,7 +125,8 @@ def type # Turn our setting thing into a Puppet::Resource instance. def to_resource - return nil unless type = self.type + type = self.type + return nil unless type path = self.value diff --git a/lib/puppet/settings/ini_file.rb b/lib/puppet/settings/ini_file.rb index 56c0310ab9e..9d05a77c77d 100644 --- a/lib/puppet/settings/ini_file.rb +++ b/lib/puppet/settings/ini_file.rb @@ -96,7 +96,8 @@ def section_exists_with_default_section_name? end def set_default_section_write_sectionline(value) - if index = @lines.find_index { |line| line.is_a?(DefaultSection) } + index = @lines.find_index { |line| line.is_a?(DefaultSection) } + if index @lines[index].write_sectionline = true end end diff --git a/lib/puppet/ssl/base.rb b/lib/puppet/ssl/base.rb index c35d7e81b18..bf2963a38d9 100644 --- a/lib/puppet/ssl/base.rb +++ b/lib/puppet/ssl/base.rb @@ -135,7 +135,8 @@ def digest_algorithm /sha\d*/i ) ln = content.signature_algorithm - if match = digest_re.match(ln) + match = digest_re.match(ln) + if match match[0].downcase else raise Puppet::Error, _("Unknown signature algorithm '%{ln}'") % { ln: ln } diff --git a/lib/puppet/ssl/host.rb b/lib/puppet/ssl/host.rb index 08c8f6bd2cf..1a1865c56fb 100644 --- a/lib/puppet/ssl/host.rb +++ b/lib/puppet/ssl/host.rb @@ -179,10 +179,14 @@ def download_host_certificate # @return [Puppet::SSL::CertificateRequest, nil] def certificate_request unless @certificate_request - if csr = load_certificate_request_from_file - @certificate_request = csr - elsif csr = download_csr_from_ca + csr = load_certificate_request_from_file + if csr @certificate_request = csr + else + csr = download_csr_from_ca + if csr + @certificate_request = csr + end end end @certificate_request @@ -389,13 +393,17 @@ def download_and_save_crl_bundle(store=nil) # no certificate could be found. # @return [Puppet::SSL::Certificate, nil] def get_host_certificate - if cert = check_for_certificate_on_disk(name) - return cert - elsif cert = download_certificate_from_ca(name) - save_host_certificate(cert) + cert = check_for_certificate_on_disk(name) + if cert return cert else - return nil + cert = download_certificate_from_ca(name) + if cert + save_host_certificate(cert) + return cert + else + return nil + end end end diff --git a/lib/puppet/ssl/key.rb b/lib/puppet/ssl/key.rb index bd98a8a30df..2076b465ed0 100644 --- a/lib/puppet/ssl/key.rb +++ b/lib/puppet/ssl/key.rb @@ -50,8 +50,8 @@ def read(path) end def to_s - if pass = password - @content.export(OpenSSL::Cipher::DES.new(:EDE3, :CBC), pass) + if password + @content.export(OpenSSL::Cipher::DES.new(:EDE3, :CBC), password) else return super end diff --git a/lib/puppet/transaction/event.rb b/lib/puppet/transaction/event.rb index da5111a2b20..1229a27a8f8 100644 --- a/lib/puppet/transaction/event.rb +++ b/lib/puppet/transaction/event.rb @@ -109,7 +109,8 @@ def property=(prop) end def resource=(res) - if res.respond_to?(:[]) and level = res[:loglevel] + level = res[:loglevel] if res.respond_to?(:[]) + if level @default_log_level = level end @resource = res.to_s diff --git a/lib/puppet/transaction/event_manager.rb b/lib/puppet/transaction/event_manager.rb index 9d9e4628676..27602ccfc3c 100644 --- a/lib/puppet/transaction/event_manager.rb +++ b/lib/puppet/transaction/event_manager.rb @@ -68,7 +68,8 @@ def queue_events(resource, events) received = (event.name != :restarted) relationship_graph.matching_edges(event, resource).each do |edge| received ||= true unless edge.target.is_a?(Puppet::Type.type(:whit)) - next unless method = edge.callback + method = edge.callback + next unless method next unless edge.target.respond_to?(method) queue_events_for_resource(resource, edge.target, method, list) @@ -114,7 +115,8 @@ def queue_events_for_resource(source, target, callback, events) end def queued_events(resource) - return unless callbacks = @event_queues[resource] + callbacks = @event_queues[resource] + return unless callbacks callbacks.each do |callback, events| yield callback, events unless events.empty? end diff --git a/lib/puppet/transaction/report.rb b/lib/puppet/transaction/report.rb index c944cff2f19..fb1f3c85280 100644 --- a/lib/puppet/transaction/report.rb +++ b/lib/puppet/transaction/report.rb @@ -256,24 +256,24 @@ def initialize_from_hash(data) @time = data['time'] @corrective_change = data['corrective_change'] - if master_used = data['master_used'] - @master_used = master_used + if data['master_used'] + @master_used = data['master_used'] end - if catalog_uuid = data['catalog_uuid'] - @catalog_uuid = catalog_uuid + if data['catalog_uuid'] + @catalog_uuid = data['catalog_uuid'] end - if job_id = data['job_id'] - @job_id = job_id + if data['job_id'] + @job_id = data['job_id'] end - if code_id = data['code_id'] - @code_id = code_id + if data['code_id'] + @code_id = data['code_id'] end - if cached_catalog_status = data['cached_catalog_status'] - @cached_catalog_status = cached_catalog_status + if data['cached_catalog_status'] + @cached_catalog_status = data['cached_catalog_status'] end if @time.is_a? String diff --git a/lib/puppet/transaction/resource_harness.rb b/lib/puppet/transaction/resource_harness.rb index 8bd928e5946..27efe7ba5be 100644 --- a/lib/puppet/transaction/resource_harness.rb +++ b/lib/puppet/transaction/resource_harness.rb @@ -35,7 +35,8 @@ def evaluate(resource) def scheduled?(resource) return true if Puppet[:ignoreschedules] - return true unless schedule = schedule(resource) + schedule = schedule(resource) + return true unless schedule # We use 'checked' here instead of 'synced' because otherwise we'll # end up checking most resources most times, because they will generally @@ -51,7 +52,8 @@ def schedule(resource) return nil end - return nil unless name = resource[:schedule] + name = resource[:schedule] + return nil unless name resource.catalog.resource(:schedule, name) || resource.fail(_("Could not find schedule %{name}") % { name: name }) end diff --git a/lib/puppet/type.rb b/lib/puppet/type.rb index 3bf394f049e..e0d711dad22 100644 --- a/lib/puppet/type.rb +++ b/lib/puppet/type.rb @@ -511,7 +511,8 @@ def self.newproperty(name, options = {}, &block) raise Puppet::DevError, _("Class %{class_name} already has a property named %{property}") % { class_name: self.name, property: name } if @validproperties.include?(name) - if parent = options[:parent] + parent = options[:parent] + if parent options.delete(:parent) else parent = Puppet::Property @@ -644,11 +645,13 @@ def [](name) name = name.intern fail("Invalid parameter #{name}(#{name.inspect})") unless self.class.validattr?(name) - if name == :name && nv = name_var - name = nv + if name == :name + nv = name_var + name = nv if nv end - if obj = @parameters[name] + obj = @parameters[name] + if obj # Note that if this is a property, then the value is the "should" value, # not the current value. obj.value @@ -667,8 +670,9 @@ def []=(name,value) fail("no parameter named '#{name}'") unless self.class.validattr?(name) - if name == :name && nv = name_var - name = nv + if name == :name + nv = name_var + name = nv if nv end raise Puppet::Error.new("Got nil value for #{name}") if value.nil? @@ -745,8 +749,12 @@ def event(options = {}) # @return [Object, nil] Returns the 'should' (wanted state) value for a specified property, or nil if the # given attribute name is not a property (i.e. if it is a parameter, meta-parameter, or does not exist). def should(name) - name = name.intern - (prop = @parameters[name] and prop.is_a?(Puppet::Property)) ? prop.should : nil + prop = @parameters[name.intern] + if prop && prop.is_a?(Puppet::Property) + prop.should + else + nil + end end # Registers an attribute to this resource type instance. @@ -768,7 +776,8 @@ def newattr(name) name = klass.name end - unless klass = self.class.attrclass(name) + klass = self.class.attrclass(name) + unless klass raise Puppet::Error, "Resource type #{self.class.name} does not support parameter #{name}" end @@ -819,7 +828,12 @@ def propertydefined?(name) # this one should probably go away at some point. - Does this mean it should be deprecated ? # @return [Puppet::Property] the property with the given name, or nil if not a property or does not exist. def property(name) - (obj = @parameters[name.intern] and obj.is_a?(Puppet::Property)) ? obj : nil + obj = @parameters[name.intern] + if obj && obj.is_a?(Puppet::Property) + obj + else + nil + end end # @todo comment says "For any parameters or properties that have defaults and have not yet been @@ -831,14 +845,17 @@ def property(name) # @return [void] # def set_default(attr) - return unless klass = self.class.attrclass(attr) + klass = self.class.attrclass(attr) + return unless klass # TODO this is not a necessary check, as we define a class level attr_reader return unless klass.method_defined?(:default) return if @parameters.include?(klass.name) - return unless parameter = newattr(klass.name) + parameter = newattr(klass.name) + return unless parameter - if value = parameter.default and ! value.nil? + value = parameter.default + if value and ! value.nil? parameter.value = value else @parameters.delete(parameter.name) @@ -880,7 +897,12 @@ def type def value(name) name = name.intern - (obj = @parameters[name] and obj.respond_to?(:value)) ? obj.value : nil + obj = @parameters[name] + if obj && obj.respond_to?(:value) + obj.value + else + nil + end end # @todo What is this used for? Needs a better explanation. @@ -1023,7 +1045,8 @@ def flush def insync?(is) insync = true - if property = @parameters[:ensure] + property = @parameters[:ensure] + if property unless is.include? property #TRANSLATORS 'is' is a variable name and should not be translated raise Puppet::DevError, _("The 'is' value is not in the 'is' array for '%{name}'") % { name: property.name } @@ -1073,7 +1096,12 @@ def retrieve # Provide the name, so we know we'll always refer to a real thing result[:name] = self[:name] unless self[:name] == title - if ensure_prop = property(:ensure) or (self.class.needs_ensure_retrieved and self.class.validattr?(:ensure) and ensure_prop = newattr(:ensure)) + ensure_prop = property(:ensure) + if !ensure_prop && self.class.needs_ensure_retrieved && self.class.validattr?(:ensure) + ensure_prop = newattr(:ensure) + end + + if ensure_prop result[:ensure] = ensure_state = ensure_prop.retrieve else ensure_state = nil @@ -1171,7 +1199,8 @@ def self.instances provider.instances.collect do |instance| # We always want to use the "first" provider instance we find, unless the resource # is already managed and has a different provider set - if other = provider_instances[instance.name] + other = provider_instances[instance.name] + if other Puppet.debug "%s %s found in both %s and %s; skipping the %s version" % [self.name.to_s.capitalize, instance.name, other.class.name, instance.class.name, instance.class.name] next @@ -1219,7 +1248,8 @@ def self.hash2resource(hash) resource = Puppet::Resource.new(self, title) resource.catalog = hash.delete(:catalog) - if sensitive = hash.delete(:sensitive_parameters) + sensitive = hash.delete(:sensitive_parameters) + if sensitive resource.sensitive_parameters = sensitive end @@ -1236,7 +1266,8 @@ def self.hash2resource(hash) # # @api private def pathbuilder - if p = parent + p = parent + if p [p.pathbuilder, self.ref].flatten else [self.ref] @@ -1425,7 +1456,8 @@ def properties_to_audit(list) raise(ArgumentError, _("Cannot add aliases without a catalog")) unless @resource.catalog aliases.each do |other| - if obj = @resource.catalog.resource(@resource.class.name, other) + obj = @resource.catalog.resource(@resource.class.name, other) + if obj unless obj.object_id == @resource.object_id self.fail("#{@resource.title} can not create alias #{other}: object already exists") end @@ -1526,7 +1558,8 @@ def to_edges # Either of the two retrieval attempts could have returned # nil. - unless related_resource = reference.resolve + related_resource = reference.resolve + unless related_resource self.fail "Could not retrieve dependency '#{reference}' of #{@resource.ref}" end @@ -1540,7 +1573,8 @@ def to_edges target = related_resource end - if method = self.class.callback + method = self.class.callback + if method subargs = { :event => self.class.events, :callback => method @@ -1851,12 +1885,14 @@ def self.provide(name, options = {}, &block) Puppet.debug "Reloading #{name} #{self.name} provider" end - parent = if pname = options[:parent] + pname = options[:parent] + parent = if pname options.delete(:parent) if pname.is_a? Class pname else - if provider = self.provider(pname) + provider = self.provider(pname) + if provider provider else raise Puppet::DevError, _("Could not find parent provider %{parent} of %{name}") % { parent: pname, name: name } @@ -2015,10 +2051,13 @@ def provider=(name) if name.is_a?(Puppet::Provider) @provider = name @provider.resource = self - elsif klass = self.class.provider(name) - @provider = klass.new(self) else - raise ArgumentError, _("Could not find %{name} provider of %{provider}") % { name: name, provider: self.class.name } + klass = self.class.provider(name) + if klass + @provider = klass.new(self) + else + raise ArgumentError, _("Could not find %{name} provider of %{provider}") % { name: name, provider: self.class.name } + end end end @@ -2146,8 +2185,9 @@ def autorelation(rel_type, rel_catalog = nil) next unless Puppet::Type.type(type) # Retrieve the list of names from the block. - next unless list = self.instance_eval(&block) - list = [list] unless list.is_a?(Array) + list = self.instance_eval(&block) + next unless list + list = Array(list) # Collect the current prereqs list.each { |dep| @@ -2156,9 +2196,8 @@ def autorelation(rel_type, rel_catalog = nil) # Support them passing objects directly, to save some effort. unless dep.is_a?(Puppet::Type) # Skip autorelation that we aren't managing - unless dep = rel_catalog.resource(type, dep) - next - end + dep = rel_catalog.resource(type, dep) + next unless dep end if [:require, :subscribe].include?(rel_type) @@ -2194,9 +2233,8 @@ def autonotify(rel_catalog = nil) def builddepends # Handle the requires self.class.relationship_params.collect do |klass| - if param = @parameters[klass.name] - param.to_edges - end + param = @parameters[klass.name] + param.to_edges if param end.flatten.reject { |r| r.nil? } end @@ -2386,9 +2424,8 @@ def initialize(resource) [:file, :line, :catalog, :exported, :virtual].each do |getter| setter = getter.to_s + "=" - if val = resource.send(getter) - self.send(setter, val) - end + val = resource.send(getter) + self.send(setter, val) if val end merge_tags_from(resource) @@ -2536,9 +2573,8 @@ def finish # Make sure all of our relationships are valid. Again, must be done # when the entire catalog is instantiated. self.class.relationship_params.collect do |klass| - if param = @parameters[klass.name] - param.validate_relationship - end + param = @parameters[klass.name] + param.validate_relationship if param end.flatten.reject { |r| r.nil? } end @@ -2560,13 +2596,13 @@ def name # resource. def parent return nil unless catalog - - @parent ||= - if parents = catalog.adjacent(self, :direction => :in) - parents.shift - else - nil - end + return @parent if @parent + parents = catalog.adjacent(self, :direction => :in) + @parent = if parents + parents.shift + else + nil + end end # Returns a reference to this as a string in "Type[name]" format. diff --git a/lib/puppet/type/component.rb b/lib/puppet/type/component.rb index c9f7f8ef29b..c2bf3046239 100644 --- a/lib/puppet/type/component.rb +++ b/lib/puppet/type/component.rb @@ -38,7 +38,8 @@ def pathbuilder else myname = reference.to_s end - if p = self.parent + p = self.parent + if p return [p.pathbuilder, myname] else return [myname] diff --git a/lib/puppet/type/exec.rb b/lib/puppet/type/exec.rb index 01a2c6c2e10..af5e1419b1d 100644 --- a/lib/puppet/type/exec.rb +++ b/lib/puppet/type/exec.rb @@ -141,7 +141,8 @@ def sync self.fail Puppet::Error, _("Command exceeded timeout"), $! end - if log = @resource[:logoutput] + log = @resource[:logoutput] + if log case log when :true log = @resource[:loglevel] @@ -548,7 +549,8 @@ def check(value) } [:onlyif, :unless].each { |param| - next unless tmp = self[param] + tmp = self[param] + next unless tmp tmp = [tmp] unless tmp.is_a? Array @@ -570,7 +572,8 @@ def check(value) autorequire(:user) do # Autorequire users if they are specified by name - if user = self[:user] and user !~ /^\d+$/ + user = self[:user] + if user !~ /^\d+$/ user end end @@ -616,7 +619,8 @@ def output # Run the command, or optionally run a separately-specified command. def refresh if self.check_all_attributes(true) - if cmd = self[:refresh] + cmd = self[:refresh] + if cmd provider.run(cmd) else self.property(:returns).sync diff --git a/lib/puppet/type/file.rb b/lib/puppet/type/file.rb index c7e67ca85c0..7facfc429e1 100644 --- a/lib/puppet/type/file.rb +++ b/lib/puppet/type/file.rb @@ -361,7 +361,8 @@ def self.title_patterns if !path.root? # Start at our parent, to avoid autorequiring ourself parents = path.parent.enum_for(:ascend) - if found = parents.find { |p| catalog.resource(:file, p.to_s) } + found = parents.find { |p| catalog.resource(:file, p.to_s) } + if found req << found.to_s end end @@ -375,7 +376,8 @@ def self.title_patterns autorequire(type) do if @parameters.include?(property) # The user/group property automatically converts to IDs - next unless should = @parameters[property].shouldorig + should = @parameters[property].shouldorig + next unless should val = should[0] if val.is_a?(Integer) or val =~ /^\d+$/ nil @@ -458,7 +460,8 @@ def bucket fail _("Can not find filebucket for backups without a catalog") end - unless catalog and filebucket = catalog.resource(:filebucket, backup) or backup == "puppet" + filebucket = catalog.resource(:filebucket, backup) if catalog + if !catalog || (!filebucket && backup != 'puppet') fail _("Could not find filebucket %{backup} specified in backup") % { backup: backup } end @@ -569,7 +572,8 @@ def newchild(path) def pathbuilder # We specifically need to call the method here, so it looks # up our parent in the catalog graph. - if parent = parent() + parent = parent() + if parent # We only need to behave specially when our parent is also # a file if parent.is_a?(self.class) @@ -692,14 +696,16 @@ def recurse_remote_metadata total = self[:source].collect do |source| # For each inlined file resource, the catalog contains a hash mapping # source path to lists of metadata returned by a server-side search. - if recursive_metadata = catalog.recursive_metadata[title] + recursive_metadata = catalog.recursive_metadata[title] + if recursive_metadata result = recursive_metadata[source] else result = perform_recursion(source) end next unless result - return [] if top = result.find { |r| r.relative_path == "." } and top.ftype != "directory" + top = result.find { |r| r.relative_path == "." } + return [] if top && top.ftype != "directory" result.each do |data| if data.relative_path == '.' data.source = source @@ -823,12 +829,12 @@ def should_be_file? return true if self[:ensure] == :file # I.e., it's set to something like "directory" - return false if e = self[:ensure] and e != :present + return false if self[:ensure] && self[:ensure] != :present # The user doesn't really care, apparently if self[:ensure] == :present - return true unless s = stat - return(s.ftype == "file" ? true : false) + return true unless stat + return(stat.ftype == "file" ? true : false) end # If we've gotten here, then :ensure isn't set diff --git a/lib/puppet/type/file/content.rb b/lib/puppet/type/file/content.rb index b0f1a94b1ca..73872c5ac29 100644 --- a/lib/puppet/type/file/content.rb +++ b/lib/puppet/type/file/content.rb @@ -71,7 +71,9 @@ module Puppet # Checksums need to invert how changes are printed. def change_to_s(currentvalue, newvalue) # Our "new" checksum value is provided by the source. - if source = resource.parameter(:source) and tmp = source.checksum + source = resource.parameter(:source) + tmp = source.checksum if source + if tmp newvalue = tmp end if currentvalue == :absent @@ -107,7 +109,8 @@ def insync?(is) def property_matches?(current, desired) # If checksum_value is specified, it overrides comparing the content field. checksum_type = resource.parameter(:checksum).value - if checksum_value = resource.parameter(:checksum_value) + checksum_value = resource.parameter(:checksum_value) + if checksum_value desired = "{#{checksum_type}}#{checksum_value.value}" end @@ -161,7 +164,8 @@ def content_is_really_a_checksum? end def read_file_from_filebucket - raise "Could not get filebucket from file" unless dipper = resource.bucket + dipper = resource.bucket + raise "Could not get filebucket from file" unless dipper sum = should.sub(/\{\w+\}/, '') dipper.getfile(sum) diff --git a/lib/puppet/type/file/ctime.rb b/lib/puppet/type/file/ctime.rb index e9fbdaf98b0..ccc68b73e1a 100644 --- a/lib/puppet/type/file/ctime.rb +++ b/lib/puppet/type/file/ctime.rb @@ -6,7 +6,8 @@ module Puppet def retrieve current_value = :absent - if stat = @resource.stat + stat = @resource.stat + if stat current_value = stat.ctime end current_value diff --git a/lib/puppet/type/file/data_sync.rb b/lib/puppet/type/file/data_sync.rb index f045b824451..b7fa3e94f0f 100644 --- a/lib/puppet/type/file/data_sync.rb +++ b/lib/puppet/type/file/data_sync.rb @@ -71,7 +71,8 @@ def date_matches?(checksum_type, current, desired) end def retrieve_checksum(resource) - return :absent unless stat = resource.stat + stat = resource.stat + return :absent unless stat ftype = stat.ftype # Don't even try to manage the content on directories or links return nil if ["directory","link"].include?(ftype) diff --git a/lib/puppet/type/file/ensure.rb b/lib/puppet/type/file/ensure.rb index 8042d31d6de..78a3a947ad7 100644 --- a/lib/puppet/type/file/ensure.rb +++ b/lib/puppet/type/file/ensure.rb @@ -62,9 +62,8 @@ module Puppet newvalue(:file, :event => :file_created) do # Make sure we're not managing the content some other way - if property = @resource.property(:content) - property.sync - elsif property = @resource.property(:checksum_value) + property = @resource.property(:content) || @resource.property(:checksum_value) + if property property.sync else @resource.write @@ -99,7 +98,8 @@ module Puppet newvalue(:link, :event => :link_created, :required_features => :manages_symlinks) do - fail "Cannot create a symlink without a target" unless property = resource.property(:target) + property = resource.property(:target) + fail "Cannot create a symlink without a target" unless property property.retrieve property.mklink end @@ -120,11 +120,13 @@ module Puppet def change_to_s(currentvalue, newvalue) return super unless [:file, :present].include?(newvalue) - return super unless property = @resource.property(:content) + property = @resource.property(:content) + return super unless property # We know that content is out of sync if we're here, because # it's essentially equivalent to 'ensure' in the transaction. - if source = @resource.parameter(:source) + source = @resource.parameter(:source) + if source should = source.checksum else should = property.should @@ -166,7 +168,8 @@ def insync?(currentvalue) end def retrieve - if stat = @resource.stat + stat = @resource.stat + if stat return stat.ftype.intern else if self.should == :false diff --git a/lib/puppet/type/file/mode.rb b/lib/puppet/type/file/mode.rb index 9f8528682bd..e900ba7a01a 100644 --- a/lib/puppet/type/file/mode.rb +++ b/lib/puppet/type/file/mode.rb @@ -121,7 +121,8 @@ def insync?(currentvalue) return false if munged_mode.nil? currentvalue = munged_mode end - if stat = @resource.stat and stat.ftype == "link" and @resource[:links] != :follow + stat = @resource.stat + if stat && stat.ftype == "link" && @resource[:links] != :follow self.debug _("Not managing symlink mode") return true else diff --git a/lib/puppet/type/file/mtime.rb b/lib/puppet/type/file/mtime.rb index 3d57a4998e2..415b4cc6f03 100644 --- a/lib/puppet/type/file/mtime.rb +++ b/lib/puppet/type/file/mtime.rb @@ -5,7 +5,8 @@ module Puppet def retrieve current_value = :absent - if stat = @resource.stat + stat = @resource.stat + if stat current_value = stat.mtime end current_value diff --git a/lib/puppet/type/file/selcontext.rb b/lib/puppet/type/file/selcontext.rb index a5a58f22cee..bc277510823 100644 --- a/lib/puppet/type/file/selcontext.rb +++ b/lib/puppet/type/file/selcontext.rb @@ -42,7 +42,8 @@ def retrieve_default_context(property) return nil end - unless context = self.get_selinux_default_context(@resource[:path]) + context = self.get_selinux_default_context(@resource[:path]) + unless context return nil end diff --git a/lib/puppet/type/file/source.rb b/lib/puppet/type/file/source.rb index 5667a97b7af..ff112242c46 100644 --- a/lib/puppet/type/file/source.rb +++ b/lib/puppet/type/file/source.rb @@ -134,7 +134,8 @@ def content return @content if @content raise Puppet::DevError, _("No source for content was stored with the metadata") unless metadata.source - unless tmp = Puppet::FileServing::Content.indirection.find(metadata.source, :environment => resource.catalog.environment_instance, :links => resource[:links]) + tmp = Puppet::FileServing::Content.indirection.find(metadata.source, :environment => resource.catalog.environment_instance, :links => resource[:links]) + unless tmp self.fail "Could not find any content at %s" % metadata.source end @content = tmp.content @@ -183,12 +184,9 @@ def copy_source_values # if we can't find data about this host, and fail if there are any # problems in our query. def metadata + @metadata ||= resource.catalog.metadata[resource.title] return @metadata if @metadata - if @metadata = resource.catalog.metadata[resource.title] - return @metadata - end - return nil unless value value.each do |source| begin @@ -199,7 +197,8 @@ def metadata :source_permissions => resource[:source_permissions] } - if data = Puppet::FileServing::Metadata.indirection.find(source, options) + data = Puppet::FileServing::Metadata.indirection.find(source, options) + if data @metadata = data @metadata.source = source break @@ -286,8 +285,10 @@ def each_chunk_from def chunk_file_from_disk File.open(full_path, "rb") do |src| - while chunk = src.read(8192) + chunk = src.read(8192) + while chunk yield chunk + chunk = src.read(8192) end end end diff --git a/lib/puppet/type/file/target.rb b/lib/puppet/type/file/target.rb index bdd36bc3abb..b3884774bf8 100644 --- a/lib/puppet/type/file/target.rb +++ b/lib/puppet/type/file/target.rb @@ -72,7 +72,8 @@ def insync?(currentvalue) def retrieve - if stat = @resource.stat + stat = @resource.stat + if stat if stat.ftype == "link" return Puppet::FileSystem.readlink(@resource[:path]) else diff --git a/lib/puppet/type/file/type.rb b/lib/puppet/type/file/type.rb index 38f3015735d..a313c1a6ee4 100644 --- a/lib/puppet/type/file/type.rb +++ b/lib/puppet/type/file/type.rb @@ -5,7 +5,8 @@ module Puppet def retrieve current_value = :absent - if stat = @resource.stat + stat = @resource.stat + if stat current_value = stat.ftype end current_value diff --git a/lib/puppet/type/package.rb b/lib/puppet/type/package.rb index 08603339ccd..933cb55d4d7 100644 --- a/lib/puppet/type/package.rb +++ b/lib/puppet/type/package.rb @@ -544,12 +544,14 @@ def change_to_s(currentvalue, newvalue) autorequire(:file) do autos = [] [:responsefile, :adminfile].each { |param| - if val = self[param] + val = self[param] + if val autos << val end } - if source = self[:source] and absolute_path?(source) + source = self[:source] + if absolute_path?(source) autos << source end autos @@ -557,7 +559,8 @@ def change_to_s(currentvalue, newvalue) # This only exists for testing. def clear - if obj = @parameters[:ensure] + obj = @parameters[:ensure] + if obj obj.latest = nil end end diff --git a/lib/puppet/type/resources.rb b/lib/puppet/type/resources.rb index 22684f2193a..51c102c5f43 100644 --- a/lib/puppet/type/resources.rb +++ b/lib/puppet/type/resources.rb @@ -132,7 +132,8 @@ def generate def resource_type unless defined?(@resource_type) - unless type = Puppet::Type.type(self[:name]) + type = Puppet::Type.type(self[:name]) + unless type raise Puppet::DevError, _("Could not find resource type") end @resource_type = type diff --git a/lib/puppet/type/service.rb b/lib/puppet/type/service.rb index 506e8859dfc..5417af03e66 100644 --- a/lib/puppet/type/service.rb +++ b/lib/puppet/type/service.rb @@ -115,7 +115,8 @@ def retrieve def sync event = super() - if property = @resource.property(:enable) + property = @resource.property(:enable) + if property val = property.retrieve property.sync unless property.safe_insync?(val) end diff --git a/lib/puppet/type/tidy.rb b/lib/puppet/type/tidy.rb index 9408c566317..e134ad3492e 100644 --- a/lib/puppet/type/tidy.rb +++ b/lib/puppet/type/tidy.rb @@ -118,7 +118,8 @@ def tidy?(path, stat) } def convert(unit, multi) - if num = AgeConvertors[unit] + num = AgeConvertors[unit] + if num return num * multi else self.fail _("Invalid age unit '%{unit}'") % { unit: unit } @@ -157,7 +158,8 @@ def tidy?(path, stat) be used." def convert(unit, multi) - if num = { :b => 0, :k => 1, :m => 2, :g => 3, :t => 4 }[unit] + num = { :b => 0, :k => 1, :m => 2, :g => 3, :t => 4 }[unit] + if num result = multi num.times do result *= 1024 end return result @@ -236,7 +238,8 @@ def mkfile(path) def retrieve # Our ensure property knows how to retrieve everything for us. - if obj = @parameters[:ensure] + obj = @parameters[:ensure] + if obj return obj.retrieve else return {} @@ -282,7 +285,8 @@ def generate files_by_name.keys.sort { |a,b| b <=> a }.each do |path| dir = ::File.dirname(path) - next unless resource = files_by_name[dir] + resource = files_by_name[dir] + next unless resource if resource[:require] resource[:require] << Puppet::Resource.new(:file, path) else @@ -314,17 +318,20 @@ def tidy?(path) # those files anyway return false if catalog.resource(:file, path) - return false unless stat = self.stat(path) + stat = self.stat(path) + return false unless stat return false if stat.ftype == "directory" and ! rmdirs? # The 'matches' parameter isn't OR'ed with the other tests -- # it's just used to reduce the list of files we can match. - return false if param = parameter(:matches) and ! param.tidy?(path, stat) + param = parameter(:matches) + return false if param && ! param.tidy?(path, stat) tested = false [:age, :size].each do |name| - next unless param = parameter(name) + param = parameter(name) + next unless param tested = true return true if param.tidy?(path, stat) end diff --git a/lib/puppet/type/user.rb b/lib/puppet/type/user.rb index d68e11af3a5..8fc02c055c6 100644 --- a/lib/puppet/type/user.rb +++ b/lib/puppet/type/user.rb @@ -147,7 +147,7 @@ def insync?(is) # We know the 'is' is a number, so we need to convert the 'should' to a number, # too. @should.each do |value| - return true if number = Puppet::Util.gid(value) and is == number + return true if is == Puppet::Util.gid(value) end false @@ -156,7 +156,8 @@ def insync?(is) def sync found = false @should.each do |value| - if number = Puppet::Util.gid(value) + number = Puppet::Util.gid(value) + if number provider.gid = number found = true break @@ -444,7 +445,9 @@ def insync?(current) autorequire(:group) do autos = [] - if obj = @parameters[:gid] and groups = obj.shouldorig + obj = @parameters[:gid] + groups = obj.shouldorig if obj + if groups groups = groups.collect { |group| if group =~ /^\d+$/ Integer(group) @@ -455,7 +458,8 @@ def insync?(current) groups.each { |group| case group when Integer - if resource = catalog.resources.find { |r| r.is_a?(Puppet::Type.type(:group)) and r.should(:gid) == group } + resource = catalog.resources.find { |r| r.is_a?(Puppet::Type.type(:group)) && r.should(:gid) == group } + if resource autos << resource end else @@ -464,7 +468,9 @@ def insync?(current) } end - if obj = @parameters[:groups] and groups = obj.should + obj = @parameters[:groups] + groups = obj.should if obj + if groups autos += groups.split(",") end @@ -522,7 +528,9 @@ def membership autorequire(:user) do reqs = [] - if roles_property = @parameters[:roles] and roles = roles_property.should + roles_property = @parameters[:roles] + roles = roles_property.should if roles_property + if roles reqs += roles.split(',') end diff --git a/lib/puppet/util.rb b/lib/puppet/util.rb index 74c120b10d7..af32c2b1027 100644 --- a/lib/puppet/util.rb +++ b/lib/puppet/util.rb @@ -148,7 +148,8 @@ def self.withumask(mask) # Change the process to a different user def self.chuser - if group = Puppet[:group] + group = Puppet[:group] + if group begin Puppet::Util::SUIDManager.change_group(group, true) rescue => detail @@ -161,7 +162,8 @@ def self.chuser end end - if user = Puppet[:user] + user = Puppet[:user] + if user begin Puppet::Util::SUIDManager.change_user(user, true) rescue => detail @@ -324,7 +326,8 @@ def path_to_uri(path) if Puppet::Util::Platform.windows? path = path.gsub(/\\/, '/') - if unc = /^\/\/([^\/]+)(\/.+)/.match(path) + unc = /^\/\/([^\/]+)(\/.+)/.match(path) + if unc params[:host] = unc[1] path = unc[2] elsif path =~ /^[a-z]:\//i diff --git a/lib/puppet/util/checksums.rb b/lib/puppet/util/checksums.rb index 531f23f389b..d7cdb785d72 100644 --- a/lib/puppet/util/checksums.rb +++ b/lib/puppet/util/checksums.rb @@ -344,7 +344,7 @@ def <<(str) def checksum_file(digest, filename, lite = false) buffer = lite ? 512 : 4096 File.open(filename, 'rb') do |file| - while content = file.read(buffer) + while content = file.read(buffer) #rubocop:disable Lint/AssignmentInCondition digest << content break if lite end diff --git a/lib/puppet/util/classgen.rb b/lib/puppet/util/classgen.rb index 7c080e15dfd..5ae20850d31 100644 --- a/lib/puppet/util/classgen.rb +++ b/lib/puppet/util/classgen.rb @@ -70,7 +70,8 @@ def rmclass(name, options) retval = true end - if hash = options[:hash] and hash.include? name + hash = options[:hash] + if hash && hash.include?(name) hash.delete(name) retval = true end @@ -84,7 +85,8 @@ def rmclass(name, options) # Generates the constant to create or remove. # @api private def genconst_string(name, options) - unless const = options[:constant] + const = options[:constant] + unless const prefix = options[:prefix] || "" const = prefix + name2const(name) end @@ -169,7 +171,8 @@ def handleclassconst(klass, name, options) def initclass(klass, options) klass.initvars if klass.respond_to? :initvars - if attrs = options[:attributes] + attrs = options[:attributes] + if attrs attrs.each do |param, value| method = param.to_s + "=" klass.send(method, value) if klass.respond_to? method @@ -177,7 +180,8 @@ def initclass(klass, options) end [:include, :extend].each do |method| - if set = options[method] + set = options[method] + if set set = [set] unless set.is_a?(Array) set.each do |mod| klass.send(method, mod) @@ -197,7 +201,8 @@ def name2const(name) # Store the class in the appropriate places. # @api private def storeclass(klass, klassname, options) - if hash = options[:hash] + hash = options[:hash] + if hash if hash.include? klassname and ! options[:overwrite] raise Puppet::SubclassAlreadyDefined, _("Already a generated class named %{klassname}") % { klassname: klassname } @@ -207,7 +212,8 @@ def storeclass(klass, klassname, options) end # If we were told to stick it in a hash, then do so - if array = options[:array] + array = options[:array] + if array if (klass.respond_to? :name and array.find { |c| c.name == klassname } and ! options[:overwrite]) diff --git a/lib/puppet/util/command_line.rb b/lib/puppet/util/command_line.rb index 999f0b016c0..e1e07766339 100644 --- a/lib/puppet/util/command_line.rb +++ b/lib/puppet/util/command_line.rb @@ -93,10 +93,13 @@ def find_subcommand end elsif Puppet::Application.available_application_names.include?(subcommand_name) ApplicationSubcommand.new(subcommand_name, self) - elsif path_to_subcommand = external_subcommand - ExternalSubcommand.new(path_to_subcommand, self) else - UnknownSubcommand.new(subcommand_name, self) + path_to_subcommand = external_subcommand + if path_to_subcommand + ExternalSubcommand.new(path_to_subcommand, self) + else + UnknownSubcommand.new(subcommand_name, self) + end end end @@ -121,7 +124,8 @@ def run # If we cannot find the configured environment, which may not exist, # we do not attempt to add plugin directories to the load path. unless @subcommand_name == 'master' || @subcommand_name == 'agent' || (@subcommand_name == 'device' && (['--apply', '--facts', '--resource'] - @command_line.args).empty?) - if configured_environment = Puppet.lookup(:environments).get(Puppet[:environment]) + configured_environment = Puppet.lookup(:environments).get(Puppet[:environment]) + if configured_environment configured_environment.each_plugin_directory do |dir| $LOAD_PATH << dir unless $LOAD_PATH.include?(dir) end diff --git a/lib/puppet/util/connection.rb b/lib/puppet/util/connection.rb index b0d641e5af5..0e4a82ff7e4 100644 --- a/lib/puppet/util/connection.rb +++ b/lib/puppet/util/connection.rb @@ -29,7 +29,8 @@ def self.determine_server(setting) Puppet[setting] else server = Puppet.lookup(:server) do - if primary_server = Puppet.settings[:server_list][0] + primary_server = Puppet.settings[:server_list][0] + if primary_server #TRANSLATORS 'server_list' is the name of a setting and should not be translated debug_once _("Dynamically-bound server lookup failed; using first entry from the `server_list` setting: %{server}") % {server: primary_server[0]} primary_server[0] @@ -60,7 +61,8 @@ def self.determine_port(port_setting, server_setting) Puppet.settings[port_setting].to_i else port = Puppet.lookup(:serverport) do - if primary_server = Puppet.settings[:server_list][0] + primary_server = Puppet.settings[:server_list][0] + if primary_server # Port might not be set, so we want to fallback in that # case. We know we don't need to use `setting` here, since # the default value of every port setting is `masterport` diff --git a/lib/puppet/util/diff.rb b/lib/puppet/util/diff.rb index c3c74403ab5..335f59c3c60 100644 --- a/lib/puppet/util/diff.rb +++ b/lib/puppet/util/diff.rb @@ -6,10 +6,12 @@ module Puppet::Util::Diff require 'tempfile' def diff(old, new) - return '' unless diff_cmd = Puppet[:diff] and diff_cmd != "" + diff_cmd = Puppet[:diff] + return '' unless diff_cmd && diff_cmd != "" command = [diff_cmd] - if args = Puppet[:diff_args] and args != "" + args = Puppet[:diff_args] + if args && args != "" args.split(' ').each do|arg| command << arg end diff --git a/lib/puppet/util/execution.rb b/lib/puppet/util/execution.rb index fe94b806af9..31e236cd29a 100644 --- a/lib/puppet/util/execution.rb +++ b/lib/puppet/util/execution.rb @@ -216,7 +216,8 @@ def self.execute(command, options = NoOptionsSpecified) # We close stdin/stdout/stderr immediately after fork/exec as they're no longer needed by # this process. In most cases they could be closed later, but when `stdout` is the "writer" # pipe we must close it or we'll never reach eof on the `reader` pipe. - if execution_stub = Puppet::Util::ExecutionStub.current_value + execution_stub = Puppet::Util::ExecutionStub.current_value + if execution_stub child_pid = execution_stub.call(*exec_args) [stdin, stdout, stderr].each {|io| io.close rescue nil} return child_pid @@ -231,7 +232,8 @@ def self.execute(command, options = NoOptionsSpecified) # Use non-blocking read to check for data. After each attempt, # check whether the child is done. This is done in case the child # forks and inherits stdout, as happens in `foo &`. - until results = Process.waitpid2(child_pid, Process::WNOHANG) + + until results = Process.waitpid2(child_pid, Process::WNOHANG) #rubocop:disable Lint/AssignmentInCondition # If not done, wait for data to read with a timeout # This timeout is selected to keep activity low while waiting on diff --git a/lib/puppet/util/feature.rb b/lib/puppet/util/feature.rb index 5ca712059d8..df05512c088 100644 --- a/lib/puppet/util/feature.rb +++ b/lib/puppet/util/feature.rb @@ -93,11 +93,14 @@ def test(name, options, &block) end @results[name] = result result - elsif libs = options[:libs] - libs = [libs] unless libs.is_a?(Array) - libs.all? { |lib| load_library(lib, name) } ? true : nil else - true + libs = options[:libs] + if libs + libs = [libs] unless libs.is_a?(Array) + libs.all? { |lib| load_library(lib, name) } ? true : nil + else + true + end end end diff --git a/lib/puppet/util/fileparsing.rb b/lib/puppet/util/fileparsing.rb index b567f4d81c9..22da68f684b 100644 --- a/lib/puppet/util/fileparsing.rb +++ b/lib/puppet/util/fileparsing.rb @@ -150,7 +150,8 @@ def clear_records end def fields(type) - if record = record_type(type) + record = record_type(type) + if record record.fields.dup else nil @@ -171,60 +172,65 @@ def handle_text_line(line, record) def handle_record_line(line, record) ret = nil if record.respond_to?(:process) - if ret = record.send(:process, line.dup) + ret = record.send(:process, line.dup) + if ret unless ret.is_a?(Hash) raise Puppet::DevError, _("Process record type %{record_name} returned non-hash") % { record_name: record.name } end else return nil end - elsif regex = record.match - # In this case, we try to match the whole line and then use the - # match captures to get our fields. - if match = regex.match(line) + else + regex = record.match + if regex + # In this case, we try to match the whole line and then use the + # match captures to get our fields. + match = regex.match(line) + if match + ret = {} + record.fields.zip(match.captures).each do |field, value| + if value == record.absent + ret[field] = :absent + else + ret[field] = value + end + end + else + nil + end + else ret = {} - record.fields.zip(match.captures).each do |field, value| - if value == record.absent - ret[field] = :absent + sep = record.separator + + # String "helpfully" replaces ' ' with /\s+/ in splitting, so we + # have to work around it. + if sep == " " + sep = / / + end + line_fields = line.split(sep) + record.fields.each do |param| + value = line_fields.shift + if value and value != record.absent + ret[param] = value else - ret[field] = value + ret[param] = :absent end end - else - nil - end - else - ret = {} - sep = record.separator - - # String "helpfully" replaces ' ' with /\s+/ in splitting, so we - # have to work around it. - if sep == " " - sep = / / - end - line_fields = line.split(sep) - record.fields.each do |param| - value = line_fields.shift - if value and value != record.absent - ret[param] = value - else - ret[param] = :absent + + if record.rollup and ! line_fields.empty? + last_field = record.fields[-1] + val = ([ret[last_field]] + line_fields).join(record.joiner) + ret[last_field] = val end end - - if record.rollup and ! line_fields.empty? - last_field = record.fields[-1] - val = ([ret[last_field]] + line_fields).join(record.joiner) - ret[last_field] = val + + if ret + ret[:record_type] = record.name + return ret + else + return nil end end - - if ret - ret[:record_type] = record.name - return ret - else - return nil - end end def line_separator @@ -245,7 +251,8 @@ def parse(text) count = 1 lines(text).collect do |line| count += 1 - if val = parse_line(line) + val = parse_line(line) + if val val else error = Puppet::ResourceError.new(_("Could not parse line %{line}") % { line: line.inspect }) @@ -263,7 +270,8 @@ def parse_line(line) # These are basically either text or record lines. method = "handle_#{record.type}_line" if respond_to?(method) - if result = send(method, line, record) + result = send(method, line, record) + if result record.send(:post_parse, result) if record.respond_to?(:post_parse) return result end @@ -324,7 +332,8 @@ def to_file(records) # Convert our parsed record into a text record. def to_line(details) - unless record = record_type(details[:record_type]) + record = record_type(details[:record_type]) + unless record raise ArgumentError, _("Invalid record type %{record_type}") % { record_type: details[:record_type].inspect } end @@ -340,7 +349,8 @@ def to_line(details) line = record.join(details) - if regex = record.rts + regex = record.rts + if regex # If they say true, then use whitespace; else, use their regex. if regex == true regex = /\s+$/ @@ -363,7 +373,8 @@ def trailing_separator def valid_attr?(type, attr) type = type.intern - if record = record_type(type) and record.fields.include?(attr.intern) + record = record_type(type) + if record && record.fields.include?(attr.intern) return true else if attr.intern == :ensure diff --git a/lib/puppet/util/filetype.rb b/lib/puppet/util/filetype.rb index 60b6151842e..41d5a964765 100644 --- a/lib/puppet/util/filetype.rb +++ b/lib/puppet/util/filetype.rb @@ -88,7 +88,8 @@ def initialize(path, default_mode = nil) # to the target user if the target user and the current user are not # the same def cronargs - if uid = Puppet::Util.uid(@path) and uid == Puppet::Util::SUIDManager.uid + uid = Puppet::Util.uid(@path) + if uid && uid == Puppet::Util::SUIDManager.uid {:failonfail => true, :combine => true} else {:failonfail => true, :combine => true, :uid => @path} diff --git a/lib/puppet/util/http_proxy.rb b/lib/puppet/util/http_proxy.rb index 4854df0867c..884c83ff2af 100644 --- a/lib/puppet/util/http_proxy.rb +++ b/lib/puppet/util/http_proxy.rb @@ -33,7 +33,8 @@ def self.http_proxy_env # .example.com # We'll accommodate both here. def self.no_proxy?(dest) - unless no_proxy_env = ENV["no_proxy"] || ENV["NO_PROXY"] + no_proxy_env = ENV["no_proxy"] || ENV["NO_PROXY"] + unless no_proxy_env return false end diff --git a/lib/puppet/util/instance_loader.rb b/lib/puppet/util/instance_loader.rb index 0a95f1ff833..082dbd8ebcb 100644 --- a/lib/puppet/util/instance_loader.rb +++ b/lib/puppet/util/instance_loader.rb @@ -45,7 +45,8 @@ def instance_loader(type) # Retrieve an already-loaded instance, or attempt to load our instance. def loaded_instance(type, name) name = name.intern - return nil unless instances = instance_hash(type) + instances = instance_hash(type) + return nil unless instances unless instances.include? name if instance_loader(type).load(name, Puppet.lookup(:current_environment)) unless instances.include? name diff --git a/lib/puppet/util/ldap/connection.rb b/lib/puppet/util/ldap/connection.rb index 5c0b9970054..27dbd312964 100644 --- a/lib/puppet/util/ldap/connection.rb +++ b/lib/puppet/util/ldap/connection.rb @@ -17,9 +17,11 @@ def self.instance options = {} options[:ssl] = ssl - if user = Puppet.settings[:ldapuser] and user != "" + user = Puppet.settings[:ldapuser] + if user && user != "" options[:user] = user - if pass = Puppet.settings[:ldappassword] and pass != "" + pass = Puppet.settings[:ldappassword] + if pass && pass != "" options[:password] = pass end end diff --git a/lib/puppet/util/ldap/manager.rb b/lib/puppet/util/ldap/manager.rb index 2999e7417d7..65cba2dca2f 100644 --- a/lib/puppet/util/ldap/manager.rb +++ b/lib/puppet/util/ldap/manager.rb @@ -56,10 +56,12 @@ def connect ssl = false end options = {:ssl => ssl} - if user = Puppet[:ldapuser] and user != "" + user = Puppet[:ldapuser] + if user && user != "" options[:user] = user end - if password = Puppet[:ldappassword] and password != "" + password = Puppet[:ldappassword] + if password && password != "" options[:password] = password end @connection = Puppet::Util::Ldap::Connection.new(Puppet[:ldapserver], Puppet[:ldapport], options) @@ -138,7 +140,8 @@ def generate(values) next if values[generator.name] if generator.source - unless value = values[generator.source] + value = values[generator.source] + unless value raise ArgumentError, _("%{source} must be defined to generate %{name}") % { source: generator.source, name: generator.name } end diff --git a/lib/puppet/util/log.rb b/lib/puppet/util/log.rb index 3084718c2e5..535f609229d 100644 --- a/lib/puppet/util/log.rb +++ b/lib/puppet/util/log.rb @@ -300,13 +300,15 @@ def initialize(args) @time = Time.now - if tags = args[:tags] + tags = args[:tags] + if tags tags.each { |t| self.tag(t) } end # Don't add these unless defined (preserve 3.x API as much as possible) [:file, :line, :pos, :issue_code, :environment, :node, :backtrace].each do |attr| - next unless value = args[attr] + value = args[attr] + next unless value send(attr.to_s + '=', value) end @@ -324,7 +326,8 @@ def initialize_from_hash(data) end # Don't add these unless defined (preserve 3.x API as much as possible) %w(file line pos issue_code environment node backtrace).each do |name| - next unless value = data[name] + value = data[name] + next unless value send(name + '=', value) end end diff --git a/lib/puppet/util/metric.rb b/lib/puppet/util/metric.rb index 9605380ba10..2c30aeefae8 100644 --- a/lib/puppet/util/metric.rb +++ b/lib/puppet/util/metric.rb @@ -32,7 +32,8 @@ def to_data_hash # Return a specific value def [](name) - if value = @values.find { |v| v[0] == name } + value = @values.find { |v| v[0] == name } + if value return value[2] else return 0 diff --git a/lib/puppet/util/posix.rb b/lib/puppet/util/posix.rb index e0c1f73476c..1b0718b12ef 100644 --- a/lib/puppet/util/posix.rb +++ b/lib/puppet/util/posix.rb @@ -134,11 +134,13 @@ def get_posix_value(location, id_field, field) # pass end if field.is_a?(Integer) - return nil unless name = get_posix_field(location, :name, field) + name = get_posix_field(location, :name, field) + return nil unless name id = get_posix_field(location, id_field, name) check_value = id else - return nil unless id = get_posix_field(location, id_field, field) + id = get_posix_field(location, id_field, field) + return nil unless id name = get_posix_field(location, :name, id) check_value = name end diff --git a/lib/puppet/util/rdoc/code_objects.rb b/lib/puppet/util/rdoc/code_objects.rb index b67480e8e24..5cfef51eda4 100644 --- a/lib/puppet/util/rdoc/code_objects.rb +++ b/lib/puppet/util/rdoc/code_objects.rb @@ -64,7 +64,8 @@ def add_fact(fact) # Adds a module called __nodes__ and adds nodes to it as classes # def add_node(name,superclass) - if cls = @nodes[name] + cls = @nodes[name] + if cls return cls end @node_container ||= add_module(NormalModule, "__nodes__") diff --git a/lib/puppet/util/rdoc/generators/puppet_generator.rb b/lib/puppet/util/rdoc/generators/puppet_generator.rb index cb7a265719f..1200dd561b3 100644 --- a/lib/puppet/util/rdoc/generators/puppet_generator.rb +++ b/lib/puppet/util/rdoc/generators/puppet_generator.rb @@ -162,8 +162,10 @@ def build_indices # scan all classes to create the child's references @allclasses.values.each do |klass| - if superklass = klass.context.superclass - if superklass = AllReferences[superklass] and (superklass.is_a?(HTMLPuppetClass) or superklass.is_a?(HTMLPuppetNode)) + superklass = klass.context.superclass + if superklass + superklass = AllReferences[superklass] + if superklass && (superklass.is_a?(HTMLPuppetClass) || superklass.is_a?(HTMLPuppetNode)) superklass.context.add_child(klass.context) end end diff --git a/lib/puppet/util/selinux.rb b/lib/puppet/util/selinux.rb index 710dcec6498..58bd15c516d 100644 --- a/lib/puppet/util/selinux.rb +++ b/lib/puppet/util/selinux.rb @@ -232,7 +232,8 @@ def read_mounts # Internal helper function to return which type of filesystem a given file # path resides on def find_fs(path) - return nil unless mounts = read_mounts + mounts = read_mounts + return nil unless mounts # cleanpath eliminates useless parts of the path (like '.', or '..', or # multiple slashes), without touching the filesystem, and without diff --git a/lib/puppet/version.rb b/lib/puppet/version.rb index 1b991b2c8a5..f0f267393f2 100644 --- a/lib/puppet/version.rb +++ b/lib/puppet/version.rb @@ -61,10 +61,7 @@ module Puppet def self.version version_file = File.join(File.dirname(__FILE__), 'VERSION') return @puppet_version if @puppet_version - if version = read_version_file(version_file) - @puppet_version = version - end - @puppet_version ||= PUPPETVERSION + @puppet_version = read_version_file(version_file) || PUPPETVERSION end # @return [String] containing the puppet version to minor specificity, e.g. "3.0" diff --git a/spec/lib/puppet_spec/modules.rb b/spec/lib/puppet_spec/modules.rb index 2cdd0d2bca0..5b272128c14 100644 --- a/spec/lib/puppet_spec/modules.rb +++ b/spec/lib/puppet_spec/modules.rb @@ -6,7 +6,8 @@ def create(name, dir, options = {}) environment = options[:environment] - if metadata = options[:metadata] + metadata = options[:metadata] + if metadata metadata[:source] ||= 'github' metadata[:author] ||= 'puppetlabs' metadata[:version] ||= '9.9.9' @@ -20,7 +21,8 @@ def create(name, dir, options = {}) end end - if tasks = options[:tasks] + tasks = options[:tasks] + if tasks tasks_dir = File.join(module_dir, 'tasks') FileUtils.mkdir_p(tasks_dir) tasks.each do |task_files| diff --git a/spec/unit/indirector/request_spec.rb b/spec/unit/indirector/request_spec.rb index 5a15279c998..af3319fdf00 100644 --- a/spec/unit/indirector/request_spec.rb +++ b/spec/unit/indirector/request_spec.rb @@ -231,13 +231,12 @@ end it "should use its uri, if it has one, as its description" do - Puppet.override({ - :environments => Puppet::Environments::Static.new( - Puppet::Node::Environment.create(:baz, []) - )}, - "Static loader for spec") do + Puppet.override( + { :environments => Puppet::Environments::Static.new(Puppet::Node::Environment.create(:baz, [])) }, + "Static loader for spec" + ) do expect(Puppet::Indirector::Request.new(:myind, :find, "foo://bar/baz", nil).description).to eq("foo://bar/baz") - end + end end it "should use its indirection name and key, if it has no uri, as its description" do