diff options
author | Lamont Granquist <lamont@scriptkiddie.org> | 2017-01-09 10:47:17 -0800 |
---|---|---|
committer | Lamont Granquist <lamont@scriptkiddie.org> | 2017-02-11 15:13:31 -0800 |
commit | 67c44883fda6097385a7d378930177a9c85643b8 (patch) | |
tree | 4ebd7be6e31182006607b360f13e763044bed136 /lib | |
parent | 4bea26334396755625b3094272d9852b400bb053 (diff) | |
download | chef-67c44883fda6097385a7d378930177a9c85643b8.tar.gz |
package provider cleanuplcg/package-cleanup
- cleans up a lot of ivar usage
- converts most providers to shell_out_compact_timeout!
- almost deprecates a few APIs, but can't quite yet
- windows providers need mixlib-shellout to take an argv
Signed-off-by: Lamont Granquist <lamont@scriptkiddie.org>
Diffstat (limited to 'lib')
40 files changed, 709 insertions, 669 deletions
diff --git a/lib/chef/deprecated.rb b/lib/chef/deprecated.rb index 76f66f723b..e5026d2317 100644 --- a/lib/chef/deprecated.rb +++ b/lib/chef/deprecated.rb @@ -196,6 +196,16 @@ class Chef end end + class PackageMisc < Base + def id + 15 + end + + def target + "package_misc.html" + end + end + class ResourceCloning < Base def id 3694 diff --git a/lib/chef/mixin/get_source_from_package.rb b/lib/chef/mixin/get_source_from_package.rb index 555dd634f8..96cef058ed 100644 --- a/lib/chef/mixin/get_source_from_package.rb +++ b/lib/chef/mixin/get_source_from_package.rb @@ -37,9 +37,9 @@ class Chef return if new_resource.package_name.is_a?(Array) # if we're passed something that looks like a filesystem path, with no source, use it # - require at least one '/' in the path to avoid gem_package "foo" breaking if a file named 'foo' exists in the cwd - if new_resource.source.nil? && new_resource.package_name.match(/#{::File::SEPARATOR}/) && ::File.exists?(new_resource.package_name) + if new_resource.source.nil? && new_resource.package_name.match(/#{::File::SEPARATOR}/) && ::File.exist?(new_resource.package_name) Chef::Log.debug("No package source specified, but #{new_resource.package_name} exists on the filesystem, copying to package source") - new_resource.source(@new_resource.package_name) + new_resource.source(new_resource.package_name) end end end diff --git a/lib/chef/mixin/shell_out.rb b/lib/chef/mixin/shell_out.rb index dfdb19821f..92518a1e11 100644 --- a/lib/chef/mixin/shell_out.rb +++ b/lib/chef/mixin/shell_out.rb @@ -1,6 +1,6 @@ #-- # Author:: Daniel DeLeo (<dan@chef.io>) -# Copyright:: Copyright 2010-2016, Chef Software Inc. +# Copyright:: Copyright 2010-2017, Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,6 +16,7 @@ # limitations under the License. require "mixlib/shellout" +require "chef/deprecated" class Chef module Mixin @@ -75,6 +76,24 @@ class Chef end end + # helper sugar for resources that support passing timeouts to shell_out + + def shell_out_compact_timeout(*args, **options) + raise "object is not a resource that supports timeouts" unless respond_to?(:new_resource) && new_resource.respond_to?(:timeout) + options_dup = options.dup + options_dup[:timeout] = new_resource.timeout if new_resource.timeout + options_dup[:timeout] = 900 unless options_dup.key?(:timeout) + shell_out_compact(*args, **options_dup) + end + + def shell_out_compact_timeout!(*args, **options) + raise "object is not a resource that supports timeouts" unless respond_to?(:new_resource) && new_resource.respond_to?(:timeout) + options_dup = options.dup + options_dup[:timeout] = new_resource.timeout if new_resource.timeout + options_dup[:timeout] = 900 unless options_dup.key?(:timeout) + shell_out_compact!(*args, **options_dup) + end + # shell_out! runs a command on the system and will raise an error if the command fails, which is what you want # for debugging, shell_out and shell_out! both will display command output to the tty when the log level is debug # Generally speaking, 'extend Chef::Mixin::ShellOut' in your recipes and include 'Chef::Mixin::ShellOut' in your LWRPs @@ -139,7 +158,8 @@ class Chef # @param args [String] variable number of string arguments # @return [String] nicely concatenated string or empty string def a_to_s(*args) - # FIXME: this should be deprecated in favor of shell_out_compact/shell_out_compact! + # can't quite deprecate this yet + #Chef.deprecated(:package_misc, "a_to_s is deprecated use shell_out_compact or shell_out_compact_timeout instead") args.flatten.reject { |i| i.nil? || i == "" }.map(&:to_s).join(" ") end diff --git a/lib/chef/provider/package.rb b/lib/chef/provider/package.rb index ef607f15a6..8f504939fc 100644 --- a/lib/chef/provider/package.rb +++ b/lib/chef/provider/package.rb @@ -52,6 +52,17 @@ class Chef @candidate_version = nil end + def options + if new_resource.options.is_a?(String) + # XXX: needs to handle double quotes, single quotes, nested quotes, etc and probably act + # more like a space-separated "C"SV file -- although users can fix this just by passing in + # a correctly pre-split Array. + new_resource.options.split(" ") + else + new_resource.options + end + end + def whyrun_supported? true end @@ -64,16 +75,15 @@ class Chef end end - def load_current_resource - end + def load_current_resource; end def define_resource_requirements # XXX: upgrade with a specific version doesn't make a whole lot of sense, but why don't we throw this anyway if it happens? # if not, shouldn't we raise to tell the user to use install instead of upgrade if they want to pin a version? requirements.assert(:install) do |a| a.assertion { candidates_exist_for_all_forced_changes? } - a.failure_message(Chef::Exceptions::Package, "No version specified, and no candidate version available for #{forced_packages_missing_candidates.join(", ")}") - a.whyrun("Assuming a repository that offers #{forced_packages_missing_candidates.join(", ")} would have been configured") + a.failure_message(Chef::Exceptions::Package, "No version specified, and no candidate version available for #{forced_packages_missing_candidates.join(', ')}") + a.whyrun("Assuming a repository that offers #{forced_packages_missing_candidates.join(', ')} would have been configured") end # XXX: Does it make sense to pass in a source with :upgrade? Probably @@ -81,19 +91,19 @@ class Chef # so we'll just leave things as-is for now. requirements.assert(:upgrade, :install) do |a| a.assertion { candidates_exist_for_all_uninstalled? || new_resource.source } - a.failure_message(Chef::Exceptions::Package, "No candidate version available for #{packages_missing_candidates.join(", ")}") - a.whyrun("Assuming a repository that offers #{packages_missing_candidates.join(", ")} would have been configured") + a.failure_message(Chef::Exceptions::Package, "No candidate version available for #{packages_missing_candidates.join(', ')}") + a.whyrun("Assuming a repository that offers #{packages_missing_candidates.join(', ')} would have been configured") end end action :install do unless target_version_array.any? - Chef::Log.debug("#{@new_resource} is already installed - nothing to do") + Chef::Log.debug("#{new_resource} is already installed - nothing to do") return end # @todo: move the preseed code out of the base class (and complete the fix for Array of preseeds? ugh...) - if @new_resource.response_file + if new_resource.response_file if preseed_file = get_preseed_file(package_names_for_targets, versions_for_targets) converge_by("preseed package #{package_names_for_targets}") do preseed_package(preseed_file) @@ -105,7 +115,7 @@ class Chef multipackage_api_adapter(package_names_for_targets, versions_for_targets) do |name, version| install_package(name, version) end - Chef::Log.info("#{@new_resource} installed #{package_names_for_targets} at #{versions_for_targets}") + Chef::Log.info("#{new_resource} installed #{package_names_for_targets} at #{versions_for_targets}") end end @@ -122,8 +132,8 @@ class Chef private :install_description action :upgrade do - if !target_version_array.any? - Chef::Log.debug("#{@new_resource} no versions to upgrade - nothing to do") + unless target_version_array.any? + Chef::Log.debug("#{new_resource} no versions to upgrade - nothing to do") return end @@ -132,7 +142,7 @@ class Chef upgrade_package(name, version) end log_allow_downgrade = allow_downgrade ? "(allow_downgrade)" : "" - Chef::Log.info("#{@new_resource} upgraded#{log_allow_downgrade} #{package_names_for_targets} to #{versions_for_targets}") + Chef::Log.info("#{new_resource} upgraded#{log_allow_downgrade} #{package_names_for_targets} to #{versions_for_targets}") end end @@ -153,15 +163,15 @@ class Chef action :remove do if removing_package? - description = @new_resource.version ? "version #{@new_resource.version} of " : "" - converge_by("remove #{description}package #{@current_resource.package_name}") do - multipackage_api_adapter(@current_resource.package_name, @new_resource.version) do |name, version| + description = new_resource.version ? "version #{new_resource.version} of " : "" + converge_by("remove #{description}package #{current_resource.package_name}") do + multipackage_api_adapter(current_resource.package_name, new_resource.version) do |name, version| remove_package(name, version) end - Chef::Log.info("#{@new_resource} removed") + Chef::Log.info("#{new_resource} removed") end else - Chef::Log.debug("#{@new_resource} package does not exist - nothing to do") + Chef::Log.debug("#{new_resource} package does not exist - nothing to do") end end @@ -188,48 +198,48 @@ class Chef action :purge do if removing_package? - description = @new_resource.version ? "version #{@new_resource.version} of" : "" - converge_by("purge #{description} package #{@current_resource.package_name}") do - multipackage_api_adapter(@current_resource.package_name, @new_resource.version) do |name, version| + description = new_resource.version ? "version #{new_resource.version} of" : "" + converge_by("purge #{description} package #{current_resource.package_name}") do + multipackage_api_adapter(current_resource.package_name, new_resource.version) do |name, version| purge_package(name, version) end - Chef::Log.info("#{@new_resource} purged") + Chef::Log.info("#{new_resource} purged") end end end action :reconfig do - if @current_resource.version.nil? - Chef::Log.debug("#{@new_resource} is NOT installed - nothing to do") + if current_resource.version.nil? + Chef::Log.debug("#{new_resource} is NOT installed - nothing to do") return end - unless @new_resource.response_file - Chef::Log.debug("#{@new_resource} no response_file provided - nothing to do") + unless new_resource.response_file + Chef::Log.debug("#{new_resource} no response_file provided - nothing to do") return end - if preseed_file = get_preseed_file(@new_resource.package_name, @current_resource.version) - converge_by("reconfigure package #{@new_resource.package_name}") do + if preseed_file = get_preseed_file(new_resource.package_name, current_resource.version) + converge_by("reconfigure package #{new_resource.package_name}") do preseed_package(preseed_file) - multipackage_api_adapter(@new_resource.package_name, @current_resource.version) do |name, version| + multipackage_api_adapter(new_resource.package_name, current_resource.version) do |name, version| reconfig_package(name, version) end - Chef::Log.info("#{@new_resource} reconfigured") + Chef::Log.info("#{new_resource} reconfigured") end else - Chef::Log.debug("#{@new_resource} preseeding has not changed - nothing to do") + Chef::Log.debug("#{new_resource} preseeding has not changed - nothing to do") end end def action_lock - if package_locked(@new_resource.name, @new_resource.version) == false - description = @new_resource.version ? "version #{@new_resource.version} of " : "" - converge_by("lock #{description}package #{@current_resource.package_name}") do - multipackage_api_adapter(@current_resource.package_name, @new_resource.version) do |name, version| + if package_locked(new_resource.name, new_resource.version) == false + description = new_resource.version ? "version #{new_resource.version} of " : "" + converge_by("lock #{description}package #{current_resource.package_name}") do + multipackage_api_adapter(current_resource.package_name, new_resource.version) do |name, version| lock_package(name, version) - Chef::Log.info("#{@new_resource} locked") + Chef::Log.info("#{new_resource} locked") end end else @@ -238,12 +248,12 @@ class Chef end def action_unlock - if package_locked(@new_resource.name, @new_resource.version) == true - description = @new_resource.version ? "version #{@new_resource.version} of " : "" - converge_by("unlock #{description}package #{@current_resource.package_name}") do - multipackage_api_adapter(@current_resource.package_name, @new_resource.version) do |name, version| + if package_locked(new_resource.name, new_resource.version) == true + description = new_resource.version ? "version #{new_resource.version} of " : "" + converge_by("unlock #{description}package #{current_resource.package_name}") do + multipackage_api_adapter(current_resource.package_name, new_resource.version) do |name, version| unlock_package(name, version) - Chef::Log.info("#{@new_resource} unlocked") + Chef::Log.info("#{new_resource} unlocked") end end else @@ -299,6 +309,8 @@ class Chef # used by subclasses. deprecated. use #a_to_s instead. def expand_options(options) + # its deprecated but still work to do to deprecate it fully + #Chef.deprecated(:package_misc, "expand_options is deprecated, use shell_out_compact or shell_out_compact_timeout instead") options ? " #{options}" : "" end @@ -343,7 +355,7 @@ class Chef def get_preseed_file(name, version) resource = preseed_resource(name, version) resource.run_action(:create) - Chef::Log.debug("#{@new_resource} fetched preseed file to #{resource.path}") + Chef::Log.debug("#{new_resource} fetched preseed file to #{resource.path}") if resource.updated_by_last_action? resource.path @@ -355,26 +367,26 @@ class Chef # @todo: extract apt/dpkg specific preseeding to a helper class def preseed_resource(name, version) # A directory in our cache to store this cookbook's preseed files in - file_cache_dir = Chef::FileCache.create_cache_path("preseed/#{@new_resource.cookbook_name}") + file_cache_dir = Chef::FileCache.create_cache_path("preseed/#{new_resource.cookbook_name}") # The full path where the preseed file will be stored cache_seed_to = "#{file_cache_dir}/#{name}-#{version}.seed" - Chef::Log.debug("#{@new_resource} fetching preseed file to #{cache_seed_to}") + Chef::Log.debug("#{new_resource} fetching preseed file to #{cache_seed_to}") - if template_available?(@new_resource.response_file) - Chef::Log.debug("#{@new_resource} fetching preseed file via Template") + if template_available?(new_resource.response_file) + Chef::Log.debug("#{new_resource} fetching preseed file via Template") remote_file = Chef::Resource::Template.new(cache_seed_to, run_context) - remote_file.variables(@new_resource.response_file_variables) - elsif cookbook_file_available?(@new_resource.response_file) - Chef::Log.debug("#{@new_resource} fetching preseed file via cookbook_file") + remote_file.variables(new_resource.response_file_variables) + elsif cookbook_file_available?(new_resource.response_file) + Chef::Log.debug("#{new_resource} fetching preseed file via cookbook_file") remote_file = Chef::Resource::CookbookFile.new(cache_seed_to, run_context) else - message = "No template or cookbook file found for response file #{@new_resource.response_file}" + message = "No template or cookbook file found for response file #{new_resource.response_file}" raise Chef::Exceptions::FileNotFound, message end - remote_file.cookbook_name = @new_resource.cookbook_name - remote_file.source(@new_resource.response_file) + remote_file.cookbook_name = new_resource.cookbook_name + remote_file.source(new_resource.response_file) remote_file.backup(false) remote_file end @@ -612,8 +624,8 @@ class Chef end def allow_downgrade - if @new_resource.respond_to?("allow_downgrade") - @new_resource.allow_downgrade + if new_resource.respond_to?("allow_downgrade") + new_resource.allow_downgrade else false end @@ -628,14 +640,16 @@ class Chef end def add_timeout_option(command_args) + # this is deprecated but its not quite done yet + #Chef.deprecated(:package_misc, "shell_out_with_timeout and add_timeout_option are deprecated methods, use shell_out_compact_timeout instead") args = command_args.dup if args.last.is_a?(Hash) options = args.pop.dup options[:timeout] = new_resource.timeout if new_resource.timeout - options[:timeout] = 900 unless options.has_key?(:timeout) + options[:timeout] = 900 unless options.key?(:timeout) args << options else - args << { :timeout => new_resource.timeout ? new_resource.timeout : 900 } + args << { timeout: new_resource.timeout ? new_resource.timeout : 900 } end args end diff --git a/lib/chef/provider/package/aix.rb b/lib/chef/provider/package/aix.rb index 12bf11ad0f..5af5f5afad 100644 --- a/lib/chef/provider/package/aix.rb +++ b/lib/chef/provider/package/aix.rb @@ -34,45 +34,45 @@ class Chef def define_resource_requirements super requirements.assert(:install) do |a| - a.assertion { @new_resource.source } - a.failure_message Chef::Exceptions::Package, "Source for package #{@new_resource.name} required for action install" + a.assertion { new_resource.source } + a.failure_message Chef::Exceptions::Package, "Source for package #{new_resource.name} required for action install" end requirements.assert(:all_actions) do |a| - a.assertion { !@new_resource.source || package_source_found? } - a.failure_message Chef::Exceptions::Package, "Package #{@new_resource.name} not found: #{@new_resource.source}" - a.whyrun "would assume #{@new_resource.source} would be have previously been made available" + a.assertion { !new_resource.source || package_source_found? } + a.failure_message Chef::Exceptions::Package, "Package #{new_resource.name} not found: #{new_resource.source}" + a.whyrun "would assume #{new_resource.source} would be have previously been made available" end end def load_current_resource - @current_resource = Chef::Resource::Package.new(@new_resource.name) - @current_resource.package_name(@new_resource.package_name) + @current_resource = Chef::Resource::Package.new(new_resource.name) + current_resource.package_name(new_resource.package_name) if package_source_found? - Chef::Log.debug("#{@new_resource} checking pkg status") - ret = shell_out_with_timeout("installp -L -d #{@new_resource.source}") + Chef::Log.debug("#{new_resource} checking pkg status") + ret = shell_out_compact_timeout("installp", "-L", "-d", new_resource.source) ret.stdout.each_line do |line| case line - when /:#{@new_resource.package_name}:/ + when /:#{new_resource.package_name}:/ fields = line.split(":") - @new_resource.version(fields[2]) - when /^#{@new_resource.package_name}:/ + new_resource.version(fields[2]) + when /^#{new_resource.package_name}:/ Chef::Log.warn("You are installing a bff package by product name. For idempotent installs, please install individual filesets") fields = line.split(":") - @new_resource.version(fields[2]) + new_resource.version(fields[2]) end end - raise Chef::Exceptions::Package, "package source #{@new_resource.source} does not provide package #{@new_resource.package_name}" unless @new_resource.version + raise Chef::Exceptions::Package, "package source #{new_resource.source} does not provide package #{new_resource.package_name}" unless new_resource.version end - Chef::Log.debug("#{@new_resource} checking install state") - ret = shell_out_with_timeout("lslpp -lcq #{@current_resource.package_name}") + Chef::Log.debug("#{new_resource} checking install state") + ret = shell_out_compact_timeout("lslpp", "-lcq", current_resource.package_name) ret.stdout.each_line do |line| case line - when /#{@current_resource.package_name}/ + when /#{current_resource.package_name}/ fields = line.split(":") - Chef::Log.debug("#{@new_resource} version #{fields[2]} is already installed") - @current_resource.version(fields[2]) + Chef::Log.debug("#{new_resource} version #{fields[2]} is already installed") + current_resource.version(fields[2]) end end @@ -80,24 +80,24 @@ class Chef raise Chef::Exceptions::Package, "lslpp failed - #{ret.format_for_exception}!" end - @current_resource + current_resource end def candidate_version return @candidate_version if @candidate_version if package_source_found? - ret = shell_out_with_timeout("installp -L -d #{@new_resource.source}") + ret = shell_out_compact_timeout("installp", "-L", "-d", new_resource.source) ret.stdout.each_line do |line| case line - when /\w:#{Regexp.escape(@new_resource.package_name)}:(.*)/ + when /\w:#{Regexp.escape(new_resource.package_name)}:(.*)/ fields = line.split(":") @candidate_version = fields[2] - @new_resource.version(fields[2]) - Chef::Log.debug("#{@new_resource} setting install candidate version to #{@candidate_version}") + new_resource.version(fields[2]) + Chef::Log.debug("#{new_resource} setting install candidate version to #{@candidate_version}") end end unless ret.exitstatus == 0 - raise Chef::Exceptions::Package, "installp -L -d #{@new_resource.source} - #{ret.format_for_exception}!" + raise Chef::Exceptions::Package, "installp -L -d #{new_resource.source} - #{ret.format_for_exception}!" end end @candidate_version @@ -111,30 +111,30 @@ class Chef # So far, the code has been tested only with standalone packages. # def install_package(name, version) - Chef::Log.debug("#{@new_resource} package install options: #{@new_resource.options}") - if @new_resource.options.nil? - shell_out_with_timeout!( "installp -aYF -d #{@new_resource.source} #{@new_resource.package_name}" ) - Chef::Log.debug("#{@new_resource} installed version #{@new_resource.version} from: #{@new_resource.source}") + Chef::Log.debug("#{new_resource} package install options: #{options}") + if options.nil? + shell_out_compact_timeout!("installp", "-aYF", "-d", new_resource.source, new_resource.package_name) + Chef::Log.debug("#{new_resource} installed version #{new_resource.version} from: #{new_resource.source}") else - shell_out_with_timeout!( "installp -aYF #{expand_options(@new_resource.options)} -d #{@new_resource.source} #{@new_resource.package_name}" ) - Chef::Log.debug("#{@new_resource} installed version #{@new_resource.version} from: #{@new_resource.source}") + shell_out_compact_timeout!("installp", "-aYF", options, "-d", new_resource.source, new_resource.package_name) + Chef::Log.debug("#{new_resource} installed version #{new_resource.version} from: #{new_resource.source}") end end - alias_method :upgrade_package, :install_package + alias upgrade_package install_package def remove_package(name, version) - if @new_resource.options.nil? - shell_out_with_timeout!( "installp -u #{name}" ) - Chef::Log.debug("#{@new_resource} removed version #{@new_resource.version}") + if options.nil? + shell_out_compact_timeout!("installp", "-u", name) + Chef::Log.debug("#{new_resource} removed version #{new_resource.version}") else - shell_out_with_timeout!( "installp -u #{expand_options(@new_resource.options)} #{name}" ) - Chef::Log.debug("#{@new_resource} removed version #{@new_resource.version}") + shell_out_compact_timeout!("installp", "-u", options, name) + Chef::Log.debug("#{new_resource} removed version #{new_resource.version}") end end def package_source_found? - @package_source_found ||= @new_resource.source && ::File.exists?(@new_resource.source) + @package_source_found ||= new_resource.source && ::File.exist?(new_resource.source) end end diff --git a/lib/chef/provider/package/apt.rb b/lib/chef/provider/package/apt.rb index 1c8ed8bc94..3f8c34f50c 100644 --- a/lib/chef/provider/package/apt.rb +++ b/lib/chef/provider/package/apt.rb @@ -1,6 +1,6 @@ # # Author:: Adam Jacob (<adam@chef.io>) -# Copyright:: Copyright 2008-2016, Chef Software Inc. +# Copyright:: Copyright 2008-2017, Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -72,21 +72,21 @@ class Chef def package_locked(name, version) islocked = false - locked = shell_out_with_timeout!("apt-mark showhold") + locked = shell_out_compact_timeout!("apt-mark", "showhold") locked.stdout.each_line do |line| line_package = line.strip if line_package == name islocked = true end end - return islocked + islocked end def install_package(name, version) package_name = name.zip(version).map do |n, v| package_data[n][:virtual] ? n : "#{n}=#{v}" end - run_noninteractive("apt-get -q -y", default_release_options, new_resource.options, "install", package_name) + run_noninteractive("apt-get", "-q", "-y", default_release_options, options, "install", package_name) end def upgrade_package(name, version) @@ -97,14 +97,14 @@ class Chef package_name = name.map do |n| package_data[n][:virtual] ? resolve_virtual_package_name(n) : n end - run_noninteractive("apt-get -q -y", new_resource.options, "remove", package_name) + run_noninteractive("apt-get", "-q", "-y", options, "remove", package_name) end def purge_package(name, version) package_name = name.map do |n| package_data[n][:virtual] ? resolve_virtual_package_name(n) : n end - run_noninteractive("apt-get -q -y", new_resource.options, "purge", package_name) + run_noninteractive("apt-get", "-q", "-y", options, "purge", package_name) end def preseed_package(preseed_file) @@ -118,11 +118,11 @@ class Chef end def lock_package(name, version) - run_noninteractive("apt-mark", new_resource.options, "hold", name) + run_noninteractive("apt-mark", options, "hold", name) end def unlock_package(name, version) - run_noninteractive("apt-mark", new_resource.options, "unhold", name) + run_noninteractive("apt-mark", options, "unhold", name) end private @@ -131,12 +131,14 @@ class Chef # interactive prompts. Command is run with default localization rather # than forcing locale to "C", so command output may not be stable. def run_noninteractive(*args) - shell_out_with_timeout!(a_to_s(*args), :env => { "DEBIAN_FRONTEND" => "noninteractive" }) + shell_out_compact_timeout!(*args, env: { "DEBIAN_FRONTEND" => "noninteractive" }) end def default_release_options # Use apt::Default-Release option only if provider supports it - "-o APT::Default-Release=#{new_resource.default_release}" if new_resource.respond_to?(:default_release) && new_resource.default_release + if new_resource.respond_to?(:default_release) && new_resource.default_release + [ "-o", "APT::Default-Release=#{new_resource.default_release}" ] + end end def resolve_package_versions(pkg) @@ -156,7 +158,7 @@ class Chef end def resolve_virtual_package_name(pkg) - showpkg = run_noninteractive("apt-cache showpkg", pkg).stdout + showpkg = run_noninteractive("apt-cache", "showpkg", pkg).stdout partitions = showpkg.rpartition(/Reverse Provides: ?#{$/}/) return nil if partitions[0] == "" && partitions[1] == "" # not found in output set = partitions[2].lines.each_with_object(Set.new) do |line, acc| @@ -166,7 +168,7 @@ class Chef if set.size > 1 raise Chef::Exceptions::Package, "#{new_resource.package_name} is a virtual package provided by multiple packages, you must explicitly select one" end - return set.to_a.first + set.to_a.first end def package_data_for(pkg) @@ -186,7 +188,7 @@ class Chef end end - return { + { current_version: current_version, candidate_version: candidate_version, virtual: virtual, diff --git a/lib/chef/provider/package/cab.rb b/lib/chef/provider/package/cab.rb index a281100f8b..d6e989eb72 100644 --- a/lib/chef/provider/package/cab.rb +++ b/lib/chef/provider/package/cab.rb @@ -75,7 +75,7 @@ class Chef end def dism_command(command) - shellout = Mixlib::ShellOut.new("dism.exe /Online /English #{command} /NoRestart", { :timeout => @new_resource.timeout }) + shellout = Mixlib::ShellOut.new("dism.exe /Online /English #{command} /NoRestart", timeout: new_resource.timeout) with_os_architecture(nil) do shellout.run_command end @@ -87,12 +87,12 @@ class Chef # e.g. Package_for_KB2975719~31bf3856ad364e35~amd64~~6.3.1.8 package = split_package_identity(package_info["package_information"]["package_identity"]) # Search for just the package name to catch a different version being installed - Chef::Log.debug("#{@new_resource} searching for installed package #{package['name']}") + Chef::Log.debug("#{new_resource} searching for installed package #{package['name']}") found_packages = installed_packages.select { |p| p["package_identity"] =~ /^#{package['name']}~/ } - if found_packages.length == 0 + if found_packages.empty? nil elsif found_packages.length == 1 - stdout = dism_command("/Get-PackageInfo /PackageName:\"#{found_packages.first["package_identity"]}\"").stdout + stdout = dism_command("/Get-PackageInfo /PackageName:\"#{found_packages.first['package_identity']}\"").stdout find_version(stdout) else # Presuming this won't happen, otherwise we need to handle it @@ -101,7 +101,7 @@ class Chef end def package_version - Chef::Log.debug("#{@new_resource} getting product version for package at #{cab_file_source}") + Chef::Log.debug("#{new_resource} getting product version for package at #{cab_file_source}") stdout = dism_command("/Get-PackageInfo /PackagePath:\"#{cab_file_source}\"").stdout find_version(stdout) end @@ -115,22 +115,21 @@ class Chef # returns a hash of package state information given the output of dism /get-packages # expected keys: package_identity def parse_dism_get_packages(text) - packages = Array.new + packages = [] text.each_line do |line| key, value = line.split(":") if line.start_with?("Package Identity") - unless key.nil? || value.nil? - package = Hash.new - package[key.downcase.strip.tr(" ", "_")] = value.strip.chomp - packages << package - end + next if key.nil? || value.nil? + package = {} + package[key.downcase.strip.tr(" ", "_")] = value.strip.chomp + packages << package end packages end # returns a hash of package information given the output of dism /get-packageinfo def parse_dism_get_package_info(text) - package_data = Hash.new - errors = Array.new + package_data = {} + errors = [] in_section = false section_headers = [ "Package information", "Custom Properties", "Features" ] text.each_line do |line| @@ -142,7 +141,7 @@ class Chef v = $2 # has to be first or the gsub below replaces this variable k = $1.downcase.strip.tr(" ", "_") if in_section - package_data[in_section] = Hash.new unless package_data[in_section] + package_data[in_section] = {} unless package_data[in_section] package_data[in_section][k] = v else package_data[k] = v @@ -162,7 +161,7 @@ class Chef end def split_package_identity(identity) - data = Hash.new + data = {} data["name"], data["publisher"], data["arch"], data["resource_id"], data["version"] = identity.split("~") data end diff --git a/lib/chef/provider/package/chocolatey.rb b/lib/chef/provider/package/chocolatey.rb index 02a196fa8c..29b9f0d322 100644 --- a/lib/chef/provider/package/chocolatey.rb +++ b/lib/chef/provider/package/chocolatey.rb @@ -30,8 +30,8 @@ class Chef # Declare that our arguments should be arrays use_multipackage_api - PATHFINDING_POWERSHELL_COMMAND = "[System.Environment]::GetEnvironmentVariable('ChocolateyInstall', 'MACHINE')" - CHOCO_MISSING_MSG = <<-EOS + PATHFINDING_POWERSHELL_COMMAND = "[System.Environment]::GetEnvironmentVariable('ChocolateyInstall', 'MACHINE')".freeze + CHOCO_MISSING_MSG = <<-EOS.freeze Could not locate your Chocolatey install. To install chocolatey, we recommend the 'chocolatey' cookbook (https://github.com/chocolatey/chocolatey-cookbook). If Chocolatey is installed, ensure that the 'ChocolateyInstall' environment @@ -59,8 +59,8 @@ EOS # so we want to assert candidates exist for the alternate source requirements.assert(:upgrade, :install) do |a| a.assertion { candidates_exist_for_all_uninstalled? } - a.failure_message(Chef::Exceptions::Package, "No candidate version available for #{packages_missing_candidates.join(", ")}") - a.whyrun("Assuming a repository that offers #{packages_missing_candidates.join(", ")} would have been configured") + a.failure_message(Chef::Exceptions::Package, "No candidate version available for #{packages_missing_candidates.join(', ')}") + a.whyrun("Assuming a repository that offers #{packages_missing_candidates.join(', ')} would have been configured") end end @@ -133,12 +133,11 @@ EOS end # Choco does not have dpkg's distinction between purge and remove - alias_method :purge_package, :remove_package + alias purge_package remove_package # Override the superclass check. The semantics for our new_resource.source is not files to # install from, but like the rubygem provider's sources which are more like repos. - def check_resource_semantics! - end + def check_resource_semantics!; end private @@ -160,7 +159,7 @@ EOS def choco_install_path @choco_install_path ||= powershell_out!( PATHFINDING_POWERSHELL_COMMAND - ).stdout.chomp + ).stdout.chomp end # Helper to dispatch a choco command through shell_out using the timeout @@ -169,7 +168,7 @@ EOS # @param args [String] variable number of string arguments # @return [Mixlib::ShellOut] object returned from shell_out! def choco_command(*args) - shell_out_with_timeout!(args_to_string(choco_exe, *args), { :returns => new_resource.returns }) + shell_out_with_timeout!(args_to_string(choco_exe, *args), returns: new_resource.returns) end # Use the available_packages Hash helper to create an array suitable for @@ -268,7 +267,7 @@ EOS # @param names [Array] original mixed case names # @return [Array] same names in lower case def lowercase_names(names) - names.map { |name| name.downcase } + names.map(&:downcase) end end end diff --git a/lib/chef/provider/package/dnf.rb b/lib/chef/provider/package/dnf.rb index 6eb495df30..c551ae7cb0 100644 --- a/lib/chef/provider/package/dnf.rb +++ b/lib/chef/provider/package/dnf.rb @@ -88,24 +88,24 @@ class Chef def install_package(names, versions) if new_resource.source - dnf(new_resource.options, "-y install", new_resource.source) + dnf(options, "-y install", new_resource.source) else resolved_names = names.each_with_index.map { |name, i| available_version(i).to_s unless name.nil? } - dnf(new_resource.options, "-y install", resolved_names) + dnf(options, "-y install", resolved_names) end flushcache end # dnf upgrade does not work on uninstalled packaged, while install will upgrade - alias_method :upgrade_package, :install_package + alias upgrade_package install_package def remove_package(names, versions) resolved_names = names.each_with_index.map { |name, i| installed_version(i).to_s unless name.nil? } - dnf(new_resource.options, "-y remove", resolved_names) + dnf(options, "-y remove", resolved_names) flushcache end - alias_method :purge_package, :remove_package + alias purge_package remove_package action :flush_cache do flushcache @@ -119,7 +119,7 @@ class Chef # does not match what the dnf library accepts. case line when /^(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)$/ - return Version.new($1, "#{$2 == "(none)" ? "0" : $2}:#{$3}-#{$4}", $5) + return Version.new($1, "#{$2 == '(none)' ? '0' : $2}:#{$3}-#{$4}", $5) end end end @@ -128,11 +128,11 @@ class Chef def available_version(index) @available_version ||= [] - if new_resource.source - @available_version[index] ||= resolve_source_to_version_obj - else - @available_version[index] ||= python_helper.query(:whatavailable, package_name_array[index], safe_version_array[index], safe_arch_array[index]) - end + @available_version[index] ||= if new_resource.source + resolve_source_to_version_obj + else + python_helper.query(:whatavailable, package_name_array[index], safe_version_array[index], safe_arch_array[index]) + end @available_version[index] end @@ -140,11 +140,11 @@ class Chef # @returns Array<Version> def installed_version(index) @installed_version ||= [] - if new_resource.source - @installed_version[index] ||= python_helper.query(:whatinstalled, available_version(index).name, safe_version_array[index], safe_arch_array[index]) - else - @installed_version[index] ||= python_helper.query(:whatinstalled, package_name_array[index], safe_version_array[index], safe_arch_array[index]) - end + @installed_version[index] ||= if new_resource.source + python_helper.query(:whatinstalled, available_version(index).name, safe_version_array[index], safe_arch_array[index]) + else + python_helper.query(:whatinstalled, package_name_array[index], safe_version_array[index], safe_arch_array[index]) + end @installed_version[index] end diff --git a/lib/chef/provider/package/dnf/python_helper.rb b/lib/chef/provider/package/dnf/python_helper.rb index d6e278a9fb..04f0298861 100644 --- a/lib/chef/provider/package/dnf/python_helper.rb +++ b/lib/chef/provider/package/dnf/python_helper.rb @@ -89,10 +89,12 @@ class Chef def add_version(hash, version) epoch = nil if version =~ /(\S+):(\S+)/ - epoch, version = $1, $2 + epoch = $1 + version = $2 end if version =~ /(\S+)-(\S+)/ - version, release = $1, $2 + version = $1 + release = $2 end hash["epoch"] = epoch unless epoch.nil? hash["release"] = release unless release.nil? diff --git a/lib/chef/provider/package/dnf/version.rb b/lib/chef/provider/package/dnf/version.rb index b326913c3a..3cff5b0437 100644 --- a/lib/chef/provider/package/dnf/version.rb +++ b/lib/chef/provider/package/dnf/version.rb @@ -48,7 +48,7 @@ class Chef name == other.name && version == other.version && arch == other.arch end - alias_method :eql?, :== + alias eql? == end end end diff --git a/lib/chef/provider/package/dpkg.rb b/lib/chef/provider/package/dpkg.rb index e57f58e052..89a57affac 100644 --- a/lib/chef/provider/package/dpkg.rb +++ b/lib/chef/provider/package/dpkg.rb @@ -74,17 +74,17 @@ class Chef def install_package(name, version) sources = name.map { |n| name_sources[n] } Chef::Log.info("#{new_resource} installing package(s): #{name.join(' ')}") - run_noninteractive("dpkg -i", new_resource.options, *sources) + run_noninteractive("dpkg", "-i", *options, *sources) end def remove_package(name, version) Chef::Log.info("#{new_resource} removing package(s): #{name.join(' ')}") - run_noninteractive("dpkg -r", new_resource.options, *name) + run_noninteractive("dpkg", "-r", *options, *name) end def purge_package(name, version) Chef::Log.info("#{new_resource} purging packages(s): #{name.join(' ')}") - run_noninteractive("dpkg -P", new_resource.options, *name) + run_noninteractive("dpkg", "-P", *options, *name) end def upgrade_package(name, version) @@ -102,14 +102,13 @@ class Chef end # Override the superclass check. Multiple sources are required here. - def check_resource_semantics! - end + def check_resource_semantics!; end private def read_current_version_of_package(package_name) Chef::Log.debug("#{new_resource} checking install state of #{package_name}") - status = shell_out_with_timeout!("dpkg -s #{package_name}", returns: [0, 1]) + status = shell_out_compact_timeout!("dpkg", "-s", package_name, returns: [0, 1]) package_installed = false status.stdout.each_line do |line| case line @@ -125,7 +124,7 @@ class Chef end end end - return nil + nil end def get_current_version_from(array) @@ -137,7 +136,7 @@ class Chef # Runs command via shell_out_with_timeout with magic environment to disable # interactive prompts. def run_noninteractive(*command) - shell_out_with_timeout!(a_to_s(*command), :env => { "DEBIAN_FRONTEND" => "noninteractive" }) + shell_out_compact_timeout!(*command, env: { "DEBIAN_FRONTEND" => "noninteractive" }) end # Returns true if all sources exist. Returns false if any do not, or if no @@ -177,7 +176,7 @@ class Chef begin pkginfos = resolved_source_array.map do |src| Chef::Log.debug("#{new_resource} checking #{src} dpkg status") - status = shell_out_with_timeout!("dpkg-deb -W #{src}") + status = shell_out_compact_timeout!("dpkg-deb", "-W", src) status.stdout end Hash[*package_name_array.zip(pkginfos).flatten] diff --git a/lib/chef/provider/package/easy_install.rb b/lib/chef/provider/package/easy_install.rb index a9c6e2a792..cc915e606c 100644 --- a/lib/chef/provider/package/easy_install.rb +++ b/lib/chef/provider/package/easy_install.rb @@ -32,11 +32,11 @@ class Chef begin # first check to see if we can import it - output = shell_out_with_timeout!("#{python_binary_path} -c \"import #{name}\"", :returns => [0, 1]).stderr + output = shell_out_compact_timeout!(python_binary_path, "-c", "import #{name}", returns: [0, 1]).stderr if output.include? "ImportError" # then check to see if its on the path - output = shell_out_with_timeout!("#{python_binary_path} -c \"import sys; print sys.path\"", :returns => [0, 1]).stdout - if output.downcase.include? "#{name.downcase}" + output = shell_out_compact_timeout!(python_binary_path, "-c", "import sys; print sys.path", returns: [0, 1]).stdout + if output.downcase.include? name.downcase.to_s check = true end else @@ -50,38 +50,38 @@ class Chef end def easy_install_binary_path - path = @new_resource.easy_install_binary + path = new_resource.easy_install_binary path ? path : "easy_install" end def python_binary_path - path = @new_resource.python_binary + path = new_resource.python_binary path ? path : "python" end def module_name - m = @new_resource.module_name - m ? m : @new_resource.name + m = new_resource.module_name + m ? m : new_resource.name end def load_current_resource - @current_resource = Chef::Resource::Package.new(@new_resource.name) - @current_resource.package_name(@new_resource.package_name) + @current_resource = Chef::Resource::Package.new(new_resource.name) + current_resource.package_name(new_resource.package_name) # get the currently installed version if installed package_version = nil if install_check(module_name) begin - output = shell_out_with_timeout!("#{python_binary_path} -c \"import #{module_name}; print #{module_name}.__version__\"").stdout + output = shell_out_compact_timeout!("#{python_binary_path} -c \"import #{module_name}; print #{module_name}.__version__\"").stdout package_version = output.strip rescue - output = shell_out_with_timeout!("#{python_binary_path} -c \"import sys; print sys.path\"", :returns => [0, 1]).stdout + output = shell_out_compact_timeout!("#{python_binary_path} -c \"import sys; print sys.path\"", returns: [0, 1]).stdout output_array = output.gsub(/[\[\]]/, "").split(/\s*,\s*/) package_path = "" output_array.each do |entry| - if entry.downcase.include?(@new_resource.package_name) + if entry.downcase.include?(new_resource.package_name) package_path = entry end end @@ -91,29 +91,29 @@ class Chef end end - if package_version == @new_resource.version - Chef::Log.debug("#{@new_resource} at version #{@new_resource.version}") - @current_resource.version(@new_resource.version) + if package_version == new_resource.version + Chef::Log.debug("#{new_resource} at version #{new_resource.version}") + current_resource.version(new_resource.version) else - Chef::Log.debug("#{@new_resource} at version #{package_version}") - @current_resource.version(package_version) + Chef::Log.debug("#{new_resource} at version #{package_version}") + current_resource.version(package_version) end - @current_resource + current_resource end def candidate_version return @candidate_version if @candidate_version - # do a dry run to get the latest version - result = shell_out_with_timeout!("#{easy_install_binary_path} -n #{@new_resource.package_name}", :returns => [0, 1]) + # do a dry run to get the latest version + result = shell_out_compact_timeout!("#{easy_install_binary_path} -n #{new_resource.package_name}", returns: [0, 1]) @candidate_version = result.stdout[/(.*)Best match: (.*) (.*)$/, 3] @candidate_version end def install_package(name, version) Chef.deprecated(:easy_install, "The easy_install package provider is deprecated and will be removed in Chef 13.") - run_command(:command => "#{easy_install_binary_path}#{expand_options(@new_resource.options)} \"#{name}==#{version}\"") + shell_out_compact_timeout!(easy_install_binary_path, options, "#{name}==#{version}") end def upgrade_package(name, version) @@ -122,7 +122,7 @@ class Chef def remove_package(name, version) Chef.deprecated(:easy_install, "The easy_install package provider is deprecated and will be removed in Chef 13.") - run_command(:command => "#{easy_install_binary_path}#{expand_options(@new_resource.options)} -m #{name}") + shell_out_compact_timeout!(easy_install_binary_path, options, "-m", name) end def purge_package(name, version) diff --git a/lib/chef/provider/package/freebsd/base.rb b/lib/chef/provider/package/freebsd/base.rb index 0996a38c75..64efe61bfb 100644 --- a/lib/chef/provider/package/freebsd/base.rb +++ b/lib/chef/provider/package/freebsd/base.rb @@ -47,7 +47,7 @@ class Chef # Otherwise look up the path to the ports directory using 'whereis' else - whereis = shell_out_with_timeout!("whereis -s #{port}", :env => nil) + whereis = shell_out_compact_timeout!("whereis", "-s", port, env: nil) unless path = whereis.stdout[/^#{Regexp.escape(port)}:\s+(.+)$/, 1] raise Chef::Exceptions::Package, "Could not find port with the name #{port}" end @@ -56,9 +56,9 @@ class Chef end def makefile_variable_value(variable, dir = nil) - options = dir ? { :cwd => dir } : {} - make_v = shell_out_with_timeout!("make -V #{variable}", options.merge!(:env => nil, :returns => [0, 1])) - make_v.exitstatus == 0 ? make_v.stdout.strip.split($\).first : nil # $\ is the line separator, i.e. newline. + options = dir ? { cwd: dir } : {} + make_v = shell_out_compact_timeout!("make", "-V", variable, options.merge!(env: nil, returns: [0, 1])) + make_v.exitstatus == 0 ? make_v.stdout.strip.split($OUTPUT_RECORD_SEPARATOR).first : nil # $\ is the line separator, i.e. newline. end end @@ -67,19 +67,19 @@ class Chef def initialize(*args) super - @current_resource = Chef::Resource::Package.new(@new_resource.name) + @current_resource = Chef::Resource::Package.new(new_resource.name) end def load_current_resource - @current_resource.package_name(@new_resource.package_name) + current_resource.package_name(new_resource.package_name) - @current_resource.version(current_installed_version) - Chef::Log.debug("#{@new_resource} current version is #{@current_resource.version}") if @current_resource.version + current_resource.version(current_installed_version) + Chef::Log.debug("#{new_resource} current version is #{current_resource.version}") if current_resource.version @candidate_version = candidate_version - Chef::Log.debug("#{@new_resource} candidate version is #{@candidate_version}") if @candidate_version + Chef::Log.debug("#{new_resource} candidate version is #{@candidate_version}") if @candidate_version - @current_resource + current_resource end end diff --git a/lib/chef/provider/package/freebsd/pkg.rb b/lib/chef/provider/package/freebsd/pkg.rb index 78d9449454..1d66d29be6 100644 --- a/lib/chef/provider/package/freebsd/pkg.rb +++ b/lib/chef/provider/package/freebsd/pkg.rb @@ -30,28 +30,28 @@ class Chef include PortsHelper def install_package(name, version) - unless @current_resource.version - case @new_resource.source + unless current_resource.version + case new_resource.source when /^http/, /^ftp/ - if @new_resource.source =~ /\/$/ - shell_out_with_timeout!("pkg_add -r #{package_name}", :env => { "PACKAGESITE" => @new_resource.source, "LC_ALL" => nil }).status + if new_resource.source =~ /\/$/ + shell_out_compact_timeout!("pkg_add", "-r", package_name, env: { "PACKAGESITE" => new_resource.source, "LC_ALL" => nil }).status else - shell_out_with_timeout!("pkg_add -r #{package_name}", :env => { "PACKAGEROOT" => @new_resource.source, "LC_ALL" => nil }).status + shell_out_compact_timeout!("pkg_add", "-r", package_name, env: { "PACKAGEROOT" => new_resource.source, "LC_ALL" => nil }).status end - Chef::Log.debug("#{@new_resource} installed from: #{@new_resource.source}") + Chef::Log.debug("#{new_resource} installed from: #{new_resource.source}") when /^\// - shell_out_with_timeout!("pkg_add #{file_candidate_version_path}", :env => { "PKG_PATH" => @new_resource.source , "LC_ALL" => nil }).status - Chef::Log.debug("#{@new_resource} installed from: #{@new_resource.source}") + shell_out_compact_timeout!("pkg_add", file_candidate_version_path, env: { "PKG_PATH" => new_resource.source, "LC_ALL" => nil }).status + Chef::Log.debug("#{new_resource} installed from: #{new_resource.source}") else - shell_out_with_timeout!("pkg_add -r #{latest_link_name}", :env => nil).status + shell_out_compact_timeout!("pkg_add", "-r", latest_link_name, env: nil).status end end end def remove_package(name, version) - shell_out_with_timeout!("pkg_delete #{package_name}-#{version || @current_resource.version}", :env => nil).status + shell_out_compact_timeout!("pkg_delete", "#{package_name}-#{version || current_resource.version}", env: nil).status end # The name of the package (without the version number) as understood by pkg_add and pkg_info. @@ -63,7 +63,7 @@ class Chef raise Chef::Exceptions::Package, "Unexpected form for PKGNAME variable in #{port_path}/Makefile" end else - @new_resource.package_name + new_resource.package_name end end @@ -72,12 +72,12 @@ class Chef end def current_installed_version - pkg_info = shell_out_with_timeout!("pkg_info -E \"#{package_name}*\"", :env => nil, :returns => [0, 1]) + pkg_info = shell_out_compact_timeout!("pkg_info", "-E", "#{package_name}*", env: nil, returns: [0, 1]) pkg_info.stdout[/^#{Regexp.escape(package_name)}-(.+)/, 1] end def candidate_version - case @new_resource.source + case new_resource.source when /^http/, /^ftp/ repo_candidate_version when /^\// @@ -88,7 +88,7 @@ class Chef end def file_candidate_version_path - Dir[Chef::Util::PathHelper.escape_glob_dir("#{@new_resource.source}/#{@current_resource.package_name}") + "*"][-1].to_s + Dir[Chef::Util::PathHelper.escape_glob_dir("#{new_resource.source}/#{current_resource.package_name}") + "*"][-1].to_s end def file_candidate_version @@ -104,7 +104,7 @@ class Chef end def port_path - port_dir @new_resource.package_name + port_dir new_resource.package_name end end diff --git a/lib/chef/provider/package/freebsd/pkgng.rb b/lib/chef/provider/package/freebsd/pkgng.rb index 56e87f6be9..9a5f0e9472 100644 --- a/lib/chef/provider/package/freebsd/pkgng.rb +++ b/lib/chef/provider/package/freebsd/pkgng.rb @@ -25,45 +25,43 @@ class Chef class Pkgng < Base def install_package(name, version) - unless @current_resource.version - case @new_resource.source + unless current_resource.version + case new_resource.source when /^(http|ftp|\/)/ - shell_out_with_timeout!("pkg add#{expand_options(@new_resource.options)} #{@new_resource.source}", :env => { "LC_ALL" => nil }).status - Chef::Log.debug("#{@new_resource} installed from: #{@new_resource.source}") - + shell_out_compact_timeout!("pkg", "add", options, new_resource.source, env: { "LC_ALL" => nil }).status + Chef::Log.debug("#{new_resource} installed from: #{new_resource.source}") else - shell_out_with_timeout!("pkg install -y#{expand_options(@new_resource.options)} #{name}", :env => { "LC_ALL" => nil }).status + shell_out_compact_timeout!("pkg", "install", "-y", options, name, env: { "LC_ALL" => nil }).status end end end def remove_package(name, version) - options = @new_resource.options && @new_resource.options.sub(repo_regex, "") - options && !options.empty? || options = nil - shell_out_with_timeout!("pkg delete -y#{expand_options(options)} #{name}#{version ? '-' + version : ''}", :env => nil).status + options_dup = options && options.map { |str| str.sub(repo_regex, "") }.reject!(&:empty?) + shell_out_compact_timeout!("pkg", "delete", "-y", options_dup, "#{name}#{version ? '-' + version : ''}", env: nil).status end def current_installed_version - pkg_info = shell_out_with_timeout!("pkg info \"#{@new_resource.package_name}\"", :env => nil, :returns => [0, 70]) + pkg_info = shell_out_compact_timeout!("pkg", "info", new_resource.package_name, env: nil, returns: [0, 70]) pkg_info.stdout[/^Version +: (.+)$/, 1] end def candidate_version - @new_resource.source ? file_candidate_version : repo_candidate_version + new_resource.source ? file_candidate_version : repo_candidate_version end private def file_candidate_version - @new_resource.source[/#{Regexp.escape(@new_resource.package_name)}-(.+)\.txz/, 1] + new_resource.source[/#{Regexp.escape(new_resource.package_name)}-(.+)\.txz/, 1] end def repo_candidate_version - if @new_resource.options && @new_resource.options.match(repo_regex) - options = $1 + if options && options.join(" ").match(repo_regex) + options = $1.split(" ") end - pkg_query = shell_out_with_timeout!("pkg rquery#{expand_options(options)} '%v' #{@new_resource.package_name}", :env => nil) + pkg_query = shell_out_compact_timeout!("pkg", "rquery", options, "%v", new_resource.package_name, env: nil) pkg_query.exitstatus == 0 ? pkg_query.stdout.strip.split(/\n/).last : nil end diff --git a/lib/chef/provider/package/freebsd/port.rb b/lib/chef/provider/package/freebsd/port.rb index 3eb3c5ab01..e87be4d304 100644 --- a/lib/chef/provider/package/freebsd/port.rb +++ b/lib/chef/provider/package/freebsd/port.rb @@ -26,20 +26,20 @@ class Chef include PortsHelper def install_package(name, version) - shell_out_with_timeout!("make -DBATCH install clean", :timeout => 1800, :env => nil, :cwd => port_dir).status + shell_out_compact_timeout!("make", "-DBATCH", "install", "clean", timeout: 1800, env: nil, cwd: port_dir).status end def remove_package(name, version) - shell_out_with_timeout!("make deinstall", :timeout => 300, :env => nil, :cwd => port_dir).status + shell_out_compact_timeout!("make", "deinstall", timeout: 300, env: nil, cwd: port_dir).status end def current_installed_version - pkg_info = if @new_resource.supports_pkgng? - shell_out_with_timeout!("pkg info \"#{@new_resource.package_name}\"", :env => nil, :returns => [0, 70]) + pkg_info = if new_resource.supports_pkgng? + shell_out_compact_timeout!("pkg", "info", new_resource.package_name, env: nil, returns: [0, 70]) else - shell_out_with_timeout!("pkg_info -E \"#{@new_resource.package_name}*\"", :env => nil, :returns => [0, 1]) + shell_out_compact_timeout!("pkg_info", "-E", "#{new_resource.package_name}*", env: nil, returns: [0, 1]) end - pkg_info.stdout[/^#{Regexp.escape(@new_resource.package_name)}-(.+)/, 1] + pkg_info.stdout[/^#{Regexp.escape(new_resource.package_name)}-(.+)/, 1] end def candidate_version @@ -51,7 +51,7 @@ class Chef end def port_dir - super(@new_resource.package_name) + super(new_resource.package_name) end end end diff --git a/lib/chef/provider/package/homebrew.rb b/lib/chef/provider/package/homebrew.rb index a105f6d7d0..f4e19bc857 100644 --- a/lib/chef/provider/package/homebrew.rb +++ b/lib/chef/provider/package/homebrew.rb @@ -32,7 +32,7 @@ class Chef include Chef::Mixin::HomebrewUser def load_current_resource - self.current_resource = Chef::Resource::Package.new(new_resource.name) + self.current_resource = Chef::Resource::HomebrewPackage.new(new_resource.name) current_resource.package_name(new_resource.package_name) current_resource.version(current_installed_version) Chef::Log.debug("#{new_resource} current version is #{current_resource.version}") if current_resource.version @@ -46,7 +46,7 @@ class Chef def install_package(name, version) unless current_resource.version == version - brew("install", new_resource.options, name) + brew("install", options, name) end end @@ -56,24 +56,25 @@ class Chef if current_version.nil? || current_version.empty? install_package(name, version) elsif current_version != version - brew("upgrade", new_resource.options, name) + brew("upgrade", options, name) end end def remove_package(name, version) if current_resource.version - brew("uninstall", new_resource.options, name) + brew("uninstall", options, name) end end # Homebrew doesn't really have a notion of purging, do a "force remove" def purge_package(name, version) - new_resource.options((new_resource.options || "") << " --force").strip - remove_package(name, version) + if current_resource.version + brew("uninstall", "--force", options, name) + end end def brew(*args) - get_response_from_command("brew #{args.join(' ')}") + get_response_from_command("brew", *args) end # We implement a querying method that returns the JSON-as-Hash @@ -121,13 +122,13 @@ class Chef private - def get_response_from_command(command) + def get_response_from_command(*command) homebrew_uid = find_homebrew_uid(new_resource.respond_to?(:homebrew_user) && new_resource.homebrew_user) homebrew_user = Etc.getpwuid(homebrew_uid) - Chef::Log.debug "Executing '#{command}' as user '#{homebrew_user.name}'" + Chef::Log.debug "Executing '#{command.join(' ')}' as user '#{homebrew_user.name}'" # FIXME: this 1800 second default timeout should be deprecated - output = shell_out_with_timeout!(command, :timeout => 1800, :user => homebrew_uid, :environment => { "HOME" => homebrew_user.dir, "RUBYOPT" => nil, "TMPDIR" => nil }) + output = shell_out_compact_timeout!(*command, timeout: 1800, user: homebrew_uid, environment: { "HOME" => homebrew_user.dir, "RUBYOPT" => nil, "TMPDIR" => nil }) output.stdout.chomp end diff --git a/lib/chef/provider/package/ips.rb b/lib/chef/provider/package/ips.rb index bc5b9fff77..9666013cc3 100644 --- a/lib/chef/provider/package/ips.rb +++ b/lib/chef/provider/package/ips.rb @@ -1,7 +1,7 @@ # # Author:: Jason J. W. Williams (<williamsjj@digitar.com>) # Author:: Stephen Nelson-Smith (<sns@chef.io>) -# Copyright:: Copyright 2011-2016, Chef Software Inc. +# Copyright:: Copyright 2011-2017, Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -36,45 +36,40 @@ class Chef super requirements.assert(:all_actions) do |a| - a.assertion { ! @candidate_version.nil? } - a.failure_message Chef::Exceptions::Package, "Package #{@new_resource.package_name} not found" - a.whyrun "Assuming package #{@new_resource.package_name} would have been made available." + a.assertion { !@candidate_version.nil? } + a.failure_message Chef::Exceptions::Package, "Package #{new_resource.package_name} not found" + a.whyrun "Assuming package #{new_resource.package_name} would have been made available." end end def get_current_version - shell_out_with_timeout("pkg info #{@new_resource.package_name}").stdout.each_line do |line| + shell_out_compact_timeout("pkg", "info", new_resource.package_name).stdout.each_line do |line| return $1.split[0] if line =~ /^\s+Version: (.*)/ end - return nil + nil end def get_candidate_version - shell_out_with_timeout!("pkg info -r #{new_resource.package_name}").stdout.each_line do |line| + shell_out_compact_timeout!("pkg", "info", "-r", new_resource.package_name).stdout.each_line do |line| return $1.split[0] if line =~ /Version: (.*)/ end - return nil + nil end def load_current_resource - @current_resource = Chef::Resource::Package.new(@new_resource.name) - @current_resource.package_name(@new_resource.package_name) - Chef::Log.debug("Checking package status for #{@new_resource.name}") - @current_resource.version(get_current_version) + @current_resource = Chef::Resource::IpsPackage.new(new_resource.name) + current_resource.package_name(new_resource.package_name) + Chef::Log.debug("Checking package status for #{new_resource.name}") + current_resource.version(get_current_version) @candidate_version = get_candidate_version - @current_resource + current_resource end def install_package(name, version) - package_name = "#{name}@#{version}" - normal_command = "pkg#{expand_options(@new_resource.options)} install -q #{package_name}" - command = - if @new_resource.respond_to?(:accept_license) && @new_resource.accept_license - normal_command.gsub("-q", "-q --accept") - else - normal_command - end - shell_out_with_timeout!(command) + command = [ "pkg", options, "install", "-q" ] + command << "--accept" if new_resource.accept_license + command << "#{name}@#{version}" + shell_out_compact_timeout!(command) end def upgrade_package(name, version) @@ -83,7 +78,7 @@ class Chef def remove_package(name, version) package_name = "#{name}@#{version}" - shell_out_with_timeout!( "pkg#{expand_options(@new_resource.options)} uninstall -q #{package_name}" ) + shell_out_compact_timeout!( "pkg", options, "uninstall", "-q", package_name ) end end end diff --git a/lib/chef/provider/package/macports.rb b/lib/chef/provider/package/macports.rb index 7bbc68aba8..ad4be00477 100644 --- a/lib/chef/provider/package/macports.rb +++ b/lib/chef/provider/package/macports.rb @@ -7,25 +7,25 @@ class Chef provides :macports_package def load_current_resource - @current_resource = Chef::Resource::Package.new(@new_resource.name) - @current_resource.package_name(@new_resource.package_name) + @current_resource = Chef::Resource::Package.new(new_resource.name) + current_resource.package_name(new_resource.package_name) - @current_resource.version(current_installed_version) - Chef::Log.debug("#{@new_resource} current version is #{@current_resource.version}") if @current_resource.version + current_resource.version(current_installed_version) + Chef::Log.debug("#{new_resource} current version is #{current_resource.version}") if current_resource.version @candidate_version = macports_candidate_version - if !@new_resource.version && !@candidate_version - raise Chef::Exceptions::Package, "Could not get a candidate version for this package -- #{@new_resource.name} does not seem to be a valid package!" + if !new_resource.version && !@candidate_version + raise Chef::Exceptions::Package, "Could not get a candidate version for this package -- #{new_resource.name} does not seem to be a valid package!" end - Chef::Log.debug("#{@new_resource} candidate version is #{@candidate_version}") if @candidate_version + Chef::Log.debug("#{new_resource} candidate version is #{@candidate_version}") if @candidate_version - @current_resource + current_resource end def current_installed_version - command = "port installed #{@new_resource.package_name}" + command = [ "port", "installed", new_resource.package_name ] output = get_response_from_command(command) response = nil @@ -37,7 +37,7 @@ class Chef end def macports_candidate_version - command = "port info --version #{@new_resource.package_name}" + command = [ "port", "info", "--version", new_resource.package_name ] output = get_response_from_command(command) match = output.match(/^version: (.+)$/) @@ -46,37 +46,37 @@ class Chef end def install_package(name, version) - unless @current_resource.version == version - command = "port#{expand_options(@new_resource.options)} install #{name}" - command << " @#{version}" if version && !version.empty? - shell_out_with_timeout!(command) + unless current_resource.version == version + command = [ "port", options, "install", name ] + command << "@#{version}" if version && !version.empty? + shell_out_compact_timeout!(command) end end def purge_package(name, version) - command = "port#{expand_options(@new_resource.options)} uninstall #{name}" - command << " @#{version}" if version && !version.empty? - shell_out_with_timeout!(command) + command = [ "port", options, "uninstall", name ] + command << "@#{version}" if version && !version.empty? + shell_out_compact_timeout!(command) end def remove_package(name, version) - command = "port#{expand_options(@new_resource.options)} deactivate #{name}" - command << " @#{version}" if version && !version.empty? + command = [ "port", options, "deactivate", name ] + command << "@#{version}" if version && !version.empty? - shell_out_with_timeout!(command) + shell_out_compact_timeout!(command) end def upgrade_package(name, version) # Saving this to a variable -- weird rSpec behavior # happens otherwise... - current_version = @current_resource.version + current_version = current_resource.version if current_version.nil? || current_version.empty? # Macports doesn't like when you upgrade a package # that hasn't been installed. install_package(name, version) elsif current_version != version - shell_out_with_timeout!( "port#{expand_options(@new_resource.options)} upgrade #{name} @#{version}" ) + shell_out_compact_timeout!( "port", options, "upgrade", name, "@#{version}" ) end end @@ -84,7 +84,7 @@ class Chef def get_response_from_command(command) output = nil - status = shell_out_with_timeout(command) + status = shell_out_compact_timeout(command) begin output = status.stdout rescue Exception diff --git a/lib/chef/provider/package/msu.rb b/lib/chef/provider/package/msu.rb index 3146ecb04d..fe4a11461f 100644 --- a/lib/chef/provider/package/msu.rb +++ b/lib/chef/provider/package/msu.rb @@ -43,17 +43,17 @@ class Chef @current_resource = Chef::Resource::MsuPackage.new(new_resource.name) # download file if source is a url - msu_file = uri_scheme?(new_resource.source) ? download_source_file : @new_resource.source + msu_file = uri_scheme?(new_resource.source) ? download_source_file : new_resource.source # temp directory where the contents of msu file get extracted @temp_directory = Dir.mktmpdir("chef") extract_msu_contents(msu_file, @temp_directory) @cab_files = read_cab_files_from_xml(@temp_directory) - unless @cab_files.empty? - current_resource.version(get_current_versions) - else + if @cab_files.empty? raise Chef::Exceptions::Package, "Corrupt MSU package: MSU package XML does not contain any cab file" + else + current_resource.version(get_current_versions) end current_resource end @@ -77,7 +77,7 @@ class Chef end def get_cab_package(cab_file) - cab_resource = @new_resource + cab_resource = new_resource cab_resource.source = cab_file cab_pkg = Chef::Provider::Package::Cab.new(cab_resource, nil) end @@ -105,9 +105,9 @@ class Chef end def install_package(name, version) - #use cab_package resource to install the extracted cab packages + # use cab_package resource to install the extracted cab packages @cab_files.each do |cab_file| - declare_resource(:cab_package, @new_resource.name) do + declare_resource(:cab_package, new_resource.name) do source cab_file action :install end @@ -115,9 +115,9 @@ class Chef end def remove_package(name, version) - #use cab_package provider to remove the extracted cab packages + # use cab_package provider to remove the extracted cab packages @cab_files.each do |cab_file| - declare_resource(:cab_package, @new_resource.name) do + declare_resource(:cab_package, new_resource.name) do source cab_file action :remove end @@ -141,7 +141,7 @@ class Chef raise Chef::Exceptions::Package, "Corrupt MSU package: MSU package doesn't contain any xml file" else # msu package contains only single xml file. So using xml_files.first is sufficient - doc = ::File.open("#{xml_files.first}") { |f| REXML::Document.new f } + doc = ::File.open(xml_files.first.to_s) { |f| REXML::Document.new f } locations = doc.elements.each("unattend/servicing/package/source") { |element| puts element.attributes["location"] } locations.each do |loc| cab_files << msu_dir + "/" + loc.attribute("location").value.split("\\")[1] @@ -154,7 +154,7 @@ class Chef def cleanup_after_converge # delete the temp directory where the contents of msu file are extracted - FileUtils.rm_rf(@temp_directory) if Dir.exists?(@temp_directory) + FileUtils.rm_rf(@temp_directory) if Dir.exist?(@temp_directory) end end end diff --git a/lib/chef/provider/package/openbsd.rb b/lib/chef/provider/package/openbsd.rb index 8043c01693..2614683fba 100644 --- a/lib/chef/provider/package/openbsd.rb +++ b/lib/chef/provider/package/openbsd.rb @@ -42,9 +42,9 @@ class Chef end def load_current_resource - @current_resource.package_name(new_resource.package_name) - @current_resource.version(installed_version) - @current_resource + current_resource.package_name(new_resource.package_name) + current_resource.version(installed_version) + current_resource end def define_resource_requirements @@ -68,11 +68,11 @@ class Chef end def install_package(name, version) - unless @current_resource.version + unless current_resource.version if parts = name.match(/^(.+?)--(.+)/) # use double-dash for stems with flavors, see man page for pkg_add name = parts[1] end - shell_out_with_timeout!("pkg_add -r #{name}#{version_string(version)}", :env => { "PKG_PATH" => pkg_path }).status + shell_out_compact_timeout!("pkg_add", "-r", package_string(name, version), env: { "PKG_PATH" => pkg_path }).status Chef::Log.debug("#{new_resource.package_name} installed") end end @@ -81,18 +81,18 @@ class Chef if parts = name.match(/^(.+?)--(.+)/) name = parts[1] end - shell_out_with_timeout!("pkg_delete #{name}#{version_string(version)}", :env => nil).status + shell_out_compact_timeout!("pkg_delete", package_string(name, version), env: nil).status end private def installed_version - if parts = new_resource.package_name.match(/^(.+?)--(.+)/) - name = parts[1] - else - name = new_resource.package_name - end - pkg_info = shell_out_with_timeout!("pkg_info -e \"#{name}->0\"", :env => nil, :returns => [0, 1]) + name = if parts = new_resource.package_name.match(/^(.+?)--(.+)/) + parts[1] + else + new_resource.package_name + end + pkg_info = shell_out_compact_timeout!("pkg_info", "-e", "#{name}->0", env: nil, returns: [0, 1]) result = pkg_info.stdout[/^inst:#{Regexp.escape(name)}-(.+?)\s/, 1] Chef::Log.debug("installed_version of '#{new_resource.package_name}' is '#{result}'") result @@ -101,12 +101,12 @@ class Chef def candidate_version @candidate_version ||= begin results = [] - shell_out_with_timeout!("pkg_info -I \"#{new_resource.package_name}#{version_string(new_resource.version)}\"", :env => nil, :returns => [0, 1]).stdout.each_line do |line| - if parts = new_resource.package_name.match(/^(.+?)--(.+)/) - results << line[/^#{Regexp.escape(parts[1])}-(.+?)\s/, 1] - else - results << line[/^#{Regexp.escape(new_resource.package_name)}-(.+?)\s/, 1] - end + shell_out_compact_timeout!("pkg_info", "-I", package_string(new_resource.package_name, new_resource.version), env: nil, returns: [0, 1]).stdout.each_line do |line| + results << if parts = new_resource.package_name.match(/^(.+?)--(.+)/) + line[/^#{Regexp.escape(parts[1])}-(.+?)\s/, 1] + else + line[/^#{Regexp.escape(new_resource.package_name)}-(.+?)\s/, 1] + end end results = results.reject(&:nil?) Chef::Log.debug("Candidate versions of '#{new_resource.package_name}' are '#{results}'") @@ -121,13 +121,16 @@ class Chef end end - def version_string(version) - ver = "" - ver += "-#{version}" if version + def package_string(name, version) + if version + "#{name}-#{version}" + else + name + end end def pkg_path - ENV["PKG_PATH"] || "http://ftp.OpenBSD.org/pub/#{node["kernel"]["name"]}/#{node["kernel"]["release"]}/packages/#{node["kernel"]["machine"]}/" + ENV["PKG_PATH"] || "http://ftp.OpenBSD.org/pub/#{node['kernel']['name']}/#{node['kernel']['release']}/packages/#{node['kernel']['machine']}/" end end diff --git a/lib/chef/provider/package/pacman.rb b/lib/chef/provider/package/pacman.rb index bd8028d881..25683687b2 100644 --- a/lib/chef/provider/package/pacman.rb +++ b/lib/chef/provider/package/pacman.rb @@ -29,16 +29,16 @@ class Chef provides :pacman_package, os: "linux" def load_current_resource - @current_resource = Chef::Resource::Package.new(@new_resource.name) - @current_resource.package_name(@new_resource.package_name) + @current_resource = Chef::Resource::Package.new(new_resource.name) + current_resource.package_name(new_resource.package_name) - Chef::Log.debug("#{@new_resource} checking pacman for #{@new_resource.package_name}") - status = shell_out_with_timeout("pacman -Qi #{@new_resource.package_name}") + Chef::Log.debug("#{new_resource} checking pacman for #{new_resource.package_name}") + status = shell_out_compact_timeout("pacman", "-Qi", new_resource.package_name) status.stdout.each_line do |line| case line when /^Version(\s?)*: (.+)$/ - Chef::Log.debug("#{@new_resource} current version is #{$2}") - @current_resource.version($2) + Chef::Log.debug("#{new_resource} current version is #{$2}") + current_resource.version($2) end end @@ -46,7 +46,7 @@ class Chef raise Chef::Exceptions::Package, "pacman failed - #{status.inspect}!" end - @current_resource + current_resource end def candidate_version @@ -54,20 +54,20 @@ class Chef repos = %w{extra core community} - if ::File.exists?("/etc/pacman.conf") + if ::File.exist?("/etc/pacman.conf") pacman = ::File.read("/etc/pacman.conf") repos = pacman.scan(/\[(.+)\]/).flatten end package_repos = repos.map { |r| Regexp.escape(r) }.join("|") - status = shell_out_with_timeout("pacman -Sl") + status = shell_out_compact_timeout("pacman", "-Sl") status.stdout.each_line do |line| case line - when /^(#{package_repos}) #{Regexp.escape(@new_resource.package_name)} (.+)$/ - # $2 contains a string like "4.4.0-1" or "3.10-4 [installed]" - # simply split by space and use first token - @candidate_version = $2.split(" ").first + when /^(#{package_repos}) #{Regexp.escape(new_resource.package_name)} (.+)$/ + # $2 contains a string like "4.4.0-1" or "3.10-4 [installed]" + # simply split by space and use first token + @candidate_version = $2.split(" ").first end end @@ -76,14 +76,14 @@ class Chef end unless @candidate_version - raise Chef::Exceptions::Package, "pacman does not have a version of package #{@new_resource.package_name}" + raise Chef::Exceptions::Package, "pacman does not have a version of package #{new_resource.package_name}" end @candidate_version end def install_package(name, version) - shell_out_with_timeout!( "pacman --sync --noconfirm --noprogressbar#{expand_options(@new_resource.options)} #{name}" ) + shell_out_compact_timeout!( "pacman", "--sync", "--noconfirm", "--noprogressbar", options, name) end def upgrade_package(name, version) @@ -91,7 +91,7 @@ class Chef end def remove_package(name, version) - shell_out_with_timeout!( "pacman --remove --noconfirm --noprogressbar#{expand_options(@new_resource.options)} #{name}" ) + shell_out_compact_timeout!( "pacman", "--remove", "--noconfirm", "--noprogressbar", options, name ) end def purge_package(name, version) diff --git a/lib/chef/provider/package/paludis.rb b/lib/chef/provider/package/paludis.rb index 557e7ebc22..0b57d05adf 100644 --- a/lib/chef/provider/package/paludis.rb +++ b/lib/chef/provider/package/paludis.rb @@ -28,38 +28,37 @@ class Chef provides :paludis_package, os: "linux" def load_current_resource - @current_resource = Chef::Resource::Package.new(@new_resource.package_name) - @current_resource.package_name(@new_resource.package_name) + @current_resource = Chef::Resource::Package.new(new_resource.package_name) + current_resource.package_name(new_resource.package_name) - Chef::Log.debug("Checking package status for #{@new_resource.package_name}") + Chef::Log.debug("Checking package status for #{new_resource.package_name}") installed = false re = Regexp.new("(.*)[[:blank:]](.*)[[:blank:]](.*)$") - shell_out!("cave -L warning print-ids -M none -m \"#{@new_resource.package_name}\" -f \"%c/%p %v %r\n\"").stdout.each_line do |line| + shell_out_compact!("cave", "-L", "warning", "print-ids", "-M", "none", "-m", new_resource.package_name, "-f", "%c/%p %v %r\n").stdout.each_line do |line| res = re.match(line) - unless res.nil? - case res[3] - when "accounts", "installed-accounts" - next - when "installed" - installed = true - @current_resource.version(res[2]) - else - @candidate_version = res[2] - end + next if res.nil? + case res[3] + when "accounts", "installed-accounts" + next + when "installed" + installed = true + current_resource.version(res[2]) + else + @candidate_version = res[2] end end - @current_resource + current_resource end def install_package(name, version) - if version - pkg = "=#{name}-#{version}" - else - pkg = "#{@new_resource.package_name}" - end - shell_out!("cave -L warning resolve -x#{expand_options(@new_resource.options)} \"#{pkg}\"", :timeout => @new_resource.timeout) + pkg = if version + "=#{name}-#{version}" + else + new_resource.package_name.to_s + end + shell_out_compact_timeout!("cave", "-L", "warning", "resolve", "-x", options, pkg) end def upgrade_package(name, version) @@ -67,13 +66,13 @@ class Chef end def remove_package(name, version) - if version - pkg = "=#{@new_resource.package_name}-#{version}" - else - pkg = "#{@new_resource.package_name}" - end + pkg = if version + "=#{new_resource.package_name}-#{version}" + else + new_resource.package_name.to_s + end - shell_out!("cave -L warning uninstall -x#{expand_options(@new_resource.options)} \"#{pkg}\"") + shell_out_compact!("cave", "-L", "warning", "uninstall", "-x", options, pkg) end def purge_package(name, version) diff --git a/lib/chef/provider/package/portage.rb b/lib/chef/provider/package/portage.rb index 52b46b04b4..fd96dfa47f 100644 --- a/lib/chef/provider/package/portage.rb +++ b/lib/chef/provider/package/portage.rb @@ -32,14 +32,14 @@ class Chef PACKAGE_NAME_PATTERN = %r{(?:([^/]+)/)?([^/]+)} def load_current_resource - @current_resource = Chef::Resource::Package.new(@new_resource.name) - @current_resource.package_name(@new_resource.package_name) + @current_resource = Chef::Resource::Package.new(new_resource.name) + current_resource.package_name(new_resource.package_name) - category, pkg = %r{^#{PACKAGE_NAME_PATTERN}$}.match(@new_resource.package_name)[1, 2] + category, pkg = /^#{PACKAGE_NAME_PATTERN}$/.match(new_resource.package_name)[1, 2] globsafe_category = category ? Chef::Util::PathHelper.escape_glob_dir(category) : nil globsafe_pkg = Chef::Util::PathHelper.escape_glob_dir(pkg) - possibilities = Dir["/var/db/pkg/#{globsafe_category || "*"}/#{globsafe_pkg}-*"].map { |d| d.sub(%r{/var/db/pkg/}, "") } + possibilities = Dir["/var/db/pkg/#{globsafe_category || '*'}/#{globsafe_pkg}-*"].map { |d| d.sub(%r{/var/db/pkg/}, "") } versions = possibilities.map do |entry| if entry =~ %r{[^/]+/#{Regexp.escape(pkg)}\-(\d[\.\d]*[a-z]?((_(alpha|beta|pre|rc|p)\d*)*)?(-r\d+)?)} [$&, $1] @@ -47,17 +47,17 @@ class Chef end.compact if versions.size > 1 - atoms = versions.map { |v| v.first }.sort + atoms = versions.map(&:first).sort categories = atoms.map { |v| v.split("/")[0] }.uniq if !category && categories.size > 1 - raise Chef::Exceptions::Package, "Multiple packages found for #{@new_resource.package_name}: #{atoms.join(" ")}. Specify a category." + raise Chef::Exceptions::Package, "Multiple packages found for #{new_resource.package_name}: #{atoms.join(' ')}. Specify a category." end elsif versions.size == 1 - @current_resource.version(versions.first.last) - Chef::Log.debug("#{@new_resource} current version #{$1}") + current_resource.version(versions.first.last) + Chef::Log.debug("#{new_resource} current version #{$1}") end - @current_resource + current_resource end def parse_emerge(package, txt) @@ -67,25 +67,25 @@ class Chef txt.each_line do |line| if line =~ /\*\s+#{PACKAGE_NAME_PATTERN}/ found_package_name = $&.delete("*").strip - if package =~ /\// #the category is specified + if package =~ /\// # the category is specified if found_package_name == package availables[found_package_name] = nil end - else #the category is not specified + else # the category is not specified if found_package_name.split("/").last == package availables[found_package_name] = nil end end end - if line =~ /Latest version available: (.*)/ && availables.has_key?(found_package_name) + if line =~ /Latest version available: (.*)/ && availables.key?(found_package_name) availables[found_package_name] = $1.strip end end if availables.size > 1 # shouldn't happen if a category is specified so just use `package` - raise Chef::Exceptions::Package, "Multiple emerge results found for #{package}: #{availables.keys.join(" ")}. Specify a category." + raise Chef::Exceptions::Package, "Multiple emerge results found for #{package}: #{availables.keys.join(' ')}. Specify a category." end availables.values.first @@ -94,8 +94,8 @@ class Chef def candidate_version return @candidate_version if @candidate_version - status = shell_out("emerge --color n --nospinner --search #{@new_resource.package_name.split('/').last}") - available, installed = parse_emerge(@new_resource.package_name, status.stdout) + status = shell_out_compact("emerge", "--color", "n", "--nospinner", "--search", new_resource.package_name.split("/").last) + available, installed = parse_emerge(new_resource.package_name, status.stdout) @candidate_version = available unless status.exitstatus == 0 @@ -113,7 +113,7 @@ class Chef pkg = "~#{name}-#{$1}" end - shell_out!( "emerge -g --color n --nospinner --quiet#{expand_options(@new_resource.options)} #{pkg}" ) + shell_out_compact!( "emerge", "-g", "--color", "n", "--nospinner", "--quiet", options, pkg ) end def upgrade_package(name, version) @@ -121,13 +121,13 @@ class Chef end def remove_package(name, version) - if version - pkg = "=#{@new_resource.package_name}-#{version}" - else - pkg = "#{@new_resource.package_name}" - end + pkg = if version + "=#{new_resource.package_name}-#{version}" + else + new_resource.package_name.to_s + end - shell_out!( "emerge --unmerge --color n --nospinner --quiet#{expand_options(@new_resource.options)} #{pkg}" ) + shell_out_compact!( "emerge", "--unmerge", "--color", "n", "--nospinner", "--quiet", options, pkg ) end def purge_package(name, version) diff --git a/lib/chef/provider/package/powershell.rb b/lib/chef/provider/package/powershell.rb index caeda6d412..3912dd23af 100644 --- a/lib/chef/provider/package/powershell.rb +++ b/lib/chef/provider/package/powershell.rb @@ -36,13 +36,13 @@ class Chef def define_resource_requirements super - if powershell_out("$PSVersionTable.PSVersion.Major").stdout.strip().to_i < 5 + if powershell_out("$PSVersionTable.PSVersion.Major").stdout.strip.to_i < 5 raise "Minimum installed Powershell Version required is 5" end requirements.assert(:install) do |a| a.assertion { candidates_exist_for_all_uninstalled? } - a.failure_message(Chef::Exceptions::Package, "No candidate version available for #{packages_missing_candidates.join(", ")}") - a.whyrun("Assuming a repository that offers #{packages_missing_candidates.join(", ")} would have been configured") + a.failure_message(Chef::Exceptions::Package, "No candidate version available for #{packages_missing_candidates.join(', ')}") + a.whyrun("Assuming a repository that offers #{packages_missing_candidates.join(', ')} would have been configured") end end @@ -53,7 +53,7 @@ class Chef # Installs the package specified with the version passed else latest version will be installed def install_package(names, versions) names.each_with_index do |name, index| - powershell_out("Install-Package '#{name}' -Force -ForceBootstrap -RequiredVersion #{versions[index]}", { :timeout => @new_resource.timeout }) + powershell_out("Install-Package '#{name}' -Force -ForceBootstrap -RequiredVersion #{versions[index]}", timeout: new_resource.timeout) end end @@ -61,12 +61,12 @@ class Chef def remove_package(names, versions) names.each_with_index do |name, index| if versions && !versions[index].nil? - powershell_out( "Uninstall-Package '#{name}' -Force -ForceBootstrap -RequiredVersion #{versions[index]}", { :timeout => @new_resource.timeout }) + powershell_out( "Uninstall-Package '#{name}' -Force -ForceBootstrap -RequiredVersion #{versions[index]}", timeout: new_resource.timeout) else version = "0" until version.empty? - version = powershell_out( "(Uninstall-Package '#{name}' -Force -ForceBootstrap | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => @new_resource.timeout }).stdout.strip() - if !version.empty? + version = powershell_out( "(Uninstall-Package '#{name}' -Force -ForceBootstrap | select version | Format-Table -HideTableHeaders | Out-String).Trim()", timeout: new_resource.timeout).stdout.strip + unless version.empty? Chef::Log.info("Removed package '#{name}' with version #{version}") end end @@ -78,11 +78,11 @@ class Chef def build_candidate_versions versions = [] new_resource.package_name.each_with_index do |name, index| - if new_resource.version && !new_resource.version[index].nil? - version = powershell_out("(Find-Package '#{name}' -RequiredVersion #{new_resource.version[index]} -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => @new_resource.timeout }).stdout.strip() - else - version = powershell_out("(Find-Package '#{name}' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => @new_resource.timeout }).stdout.strip() - end + version = if new_resource.version && !new_resource.version[index].nil? + powershell_out("(Find-Package '#{name}' -RequiredVersion #{new_resource.version[index]} -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", timeout: new_resource.timeout).stdout.strip + else + powershell_out("(Find-Package '#{name}' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", timeout: new_resource.timeout).stdout.strip + end if version.empty? version = nil end @@ -95,11 +95,11 @@ class Chef def build_current_versions version_list = [] new_resource.package_name.each_with_index do |name, index| - if new_resource.version && !new_resource.version[index].nil? - version = powershell_out("(Get-Package -Name '#{name}' -RequiredVersion #{new_resource.version[index]} -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => @new_resource.timeout }).stdout.strip() - else - version = powershell_out("(Get-Package -Name '#{name}' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => @new_resource.timeout }).stdout.strip() - end + version = if new_resource.version && !new_resource.version[index].nil? + powershell_out("(Get-Package -Name '#{name}' -RequiredVersion #{new_resource.version[index]} -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", timeout: new_resource.timeout).stdout.strip + else + powershell_out("(Get-Package -Name '#{name}' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", timeout: new_resource.timeout).stdout.strip + end if version.empty? version = nil end diff --git a/lib/chef/provider/package/rpm.rb b/lib/chef/provider/package/rpm.rb index 777cc6d209..1701886191 100644 --- a/lib/chef/provider/package/rpm.rb +++ b/lib/chef/provider/package/rpm.rb @@ -34,13 +34,13 @@ class Chef requirements.assert(:all_actions) do |a| a.assertion { @package_source_exists } - a.failure_message Chef::Exceptions::Package, "Package #{@new_resource.name} not found: #{@new_resource.source}" - a.whyrun "Assuming package #{@new_resource.name} would have been made available." + a.failure_message Chef::Exceptions::Package, "Package #{new_resource.name} not found: #{new_resource.source}" + a.whyrun "Assuming package #{new_resource.name} would have been made available." end requirements.assert(:all_actions) do |a| a.assertion { !@rpm_status.nil? && (@rpm_status.exitstatus == 0 || @rpm_status.exitstatus == 1) } a.failure_message Chef::Exceptions::Package, "Unable to determine current version due to RPM failure. Detail: #{@rpm_status.inspect}" - a.whyrun "Assuming current version would have been determined for package#{@new_resource.name}." + a.whyrun "Assuming current version would have been determined for package#{new_resource.name}." end end @@ -48,63 +48,63 @@ class Chef @package_source_provided = true @package_source_exists = true - @current_resource = Chef::Resource::Package.new(@new_resource.name) - @current_resource.package_name(@new_resource.package_name) + @current_resource = Chef::Resource::Package.new(new_resource.name) + current_resource.package_name(new_resource.package_name) - if @new_resource.source - unless uri_scheme?(@new_resource.source) || ::File.exists?(@new_resource.source) + if new_resource.source + unless uri_scheme?(new_resource.source) || ::File.exist?(new_resource.source) @package_source_exists = false return end - Chef::Log.debug("#{@new_resource} checking rpm status") - shell_out_with_timeout!("rpm -qp --queryformat '%{NAME} %{VERSION}-%{RELEASE}\n' #{@new_resource.source}").stdout.each_line do |line| + Chef::Log.debug("#{new_resource} checking rpm status") + shell_out_compact_timeout!("rpm", "-qp", "--queryformat", "%{NAME} %{VERSION}-%{RELEASE}\n", new_resource.source).stdout.each_line do |line| case line when /^(\S+)\s(\S+)$/ - @current_resource.package_name($1) - @new_resource.version($2) + current_resource.package_name($1) + new_resource.version($2) @candidate_version = $2 end end else - if Array(@new_resource.action).include?(:install) + if Array(new_resource.action).include?(:install) @package_source_exists = false return end end - Chef::Log.debug("#{@new_resource} checking install state") - @rpm_status = shell_out_with_timeout("rpm -q --queryformat '%{NAME} %{VERSION}-%{RELEASE}\n' #{@current_resource.package_name}") + Chef::Log.debug("#{new_resource} checking install state") + @rpm_status = shell_out_compact_timeout("rpm", "-q", "--queryformat", "%{NAME} %{VERSION}-%{RELEASE}\n", current_resource.package_name) @rpm_status.stdout.each_line do |line| case line when /^(\S+)\s(\S+)$/ - Chef::Log.debug("#{@new_resource} current version is #{$2}") - @current_resource.version($2) + Chef::Log.debug("#{new_resource} current version is #{$2}") + current_resource.version($2) end end - @current_resource + current_resource end def install_package(name, version) - unless @current_resource.version - shell_out_with_timeout!( "rpm #{@new_resource.options} -i #{@new_resource.source}" ) - else + if current_resource.version if allow_downgrade - shell_out_with_timeout!( "rpm #{@new_resource.options} -U --oldpackage #{@new_resource.source}" ) + shell_out_compact_timeout!("rpm", options, "-U", "--oldpackage", new_resource.source) else - shell_out_with_timeout!( "rpm #{@new_resource.options} -U #{@new_resource.source}" ) + shell_out_compact_timeout!("rpm", options, "-U", new_resource.source) end + else + shell_out_compact_timeout!("rpm", options, "-i", new_resource.source) end end - alias_method :upgrade_package, :install_package + alias upgrade_package install_package def remove_package(name, version) if version - shell_out_with_timeout!( "rpm #{@new_resource.options} -e #{name}-#{version}" ) + shell_out_compact_timeout!("rpm", options, "-e", "#{name}-#{version}") else - shell_out_with_timeout!( "rpm #{@new_resource.options} -e #{name}" ) + shell_out_compact_timeout!("rpm", options, "-e", name) end end diff --git a/lib/chef/provider/package/rubygems.rb b/lib/chef/provider/package/rubygems.rb index 7b9ae909c0..1019b8d3fa 100644 --- a/lib/chef/provider/package/rubygems.rb +++ b/lib/chef/provider/package/rubygems.rb @@ -1,7 +1,7 @@ # # Author:: Adam Jacob (<adam@chef.io>) # Author:: Daniel DeLeo (<dan@chef.io>) -# Copyright:: Copyright 2008-2016, 2010-2016 Chef Software, Inc. +# Copyright:: Copyright 2008-2016, 2010-2017, Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -47,7 +47,7 @@ class Chef # alternate value and overwrite it with the defaults. Gem.configuration - DEFAULT_UNINSTALLER_OPTS = { :ignore => true, :executables => true } + DEFAULT_UNINSTALLER_OPTS = { ignore: true, executables: true }.freeze ## # The paths where rubygems should search for installed gems. @@ -133,11 +133,11 @@ class Chef def candidate_version_from_file(gem_dependency, source) spec = spec_from_file(source) if spec.satisfies_requirement?(gem_dependency) - logger.debug { "#{@new_resource} found candidate gem version #{spec.version} from local gem package #{source}" } + logger.debug { "found candidate gem version #{spec.version} from local gem package #{source}" } spec.version else # This is probably going to end badly... - logger.warn { "#{@new_resource} gem package #{source} does not satisfy the requirements #{gem_dependency}" } + logger.warn { "gem package #{source} does not satisfy the requirements #{gem_dependency}" } nil end end @@ -178,11 +178,11 @@ class Chef version = spec && spec.version if version - logger.debug { "#{@new_resource} found gem #{spec.name} version #{version} for platform #{spec.platform} from #{source}" } + logger.debug { "found gem #{spec.name} version #{version} for platform #{spec.platform} from #{source}" } version else source_list = sources.compact.empty? ? "[#{Gem.sources.to_a.join(', ')}]" : "[#{sources.join(', ')}]" - logger.warn { "#{@new_resource} failed to find gem #{gem_dependency} from #{source_list}" } + logger.warn { "failed to find gem #{gem_dependency} from #{source_list}" } nil end end @@ -285,7 +285,7 @@ class Chef # shellout! is a fork/exec which won't work on windows shell_style_paths = shell_out!("#{@gem_binary_location} env gempath").stdout # on windows, the path separator is (usually? always?) semicolon - paths = shell_style_paths.split(::File::PATH_SEPARATOR).map { |path| path.strip } + paths = shell_style_paths.split(::File::PATH_SEPARATOR).map(&:strip) self.class.gempath_cache[@gem_binary_location] = paths end end @@ -322,11 +322,11 @@ class Chef self.class.platform_cache[@gem_binary_location] else gem_environment = shell_out!("#{@gem_binary_location} env").stdout - if jruby = gem_environment[JRUBY_PLATFORM] - self.class.platform_cache[@gem_binary_location] = ["ruby", Gem::Platform.new(jruby)] - else - self.class.platform_cache[@gem_binary_location] = Gem.platforms - end + self.class.platform_cache[@gem_binary_location] = if jruby = gem_environment[JRUBY_PLATFORM] + ["ruby", Gem::Platform.new(jruby)] + else + Gem.platforms + end end end @@ -365,17 +365,17 @@ class Chef super @cleanup_gem_env = true if new_resource.gem_binary - if new_resource.options && new_resource.options.kind_of?(Hash) + if new_resource.options && new_resource.options.is_a?(Hash) msg = "options cannot be given as a hash when using an explicit gem_binary\n" msg << "in #{new_resource} from #{new_resource.source_line}" raise ArgumentError, msg end @gem_env = AlternateGemEnvironment.new(new_resource.gem_binary) - Chef::Log.debug("#{@new_resource} using gem '#{new_resource.gem_binary}'") - elsif is_omnibus? && (!@new_resource.instance_of? Chef::Resource::ChefGem) + Chef::Log.debug("#{new_resource} using gem '#{new_resource.gem_binary}'") + elsif is_omnibus? && (!new_resource.instance_of? Chef::Resource::ChefGem) # Opscode Omnibus - The ruby that ships inside omnibus is only used for Chef # Default to installing somewhere more functional - if new_resource.options && new_resource.options.kind_of?(Hash) + if new_resource.options && new_resource.options.is_a?(Hash) msg = [ "Gem options must be passed to gem_package as a string instead of a hash when", "using this installation of Chef because it runs with its own packaged Ruby. A hash", @@ -386,23 +386,23 @@ class Chef raise ArgumentError, msg end gem_location = find_gem_by_path - @new_resource.gem_binary gem_location + new_resource.gem_binary gem_location @gem_env = AlternateGemEnvironment.new(gem_location) - Chef::Log.debug("#{@new_resource} using gem '#{gem_location}'") + Chef::Log.debug("#{new_resource} using gem '#{gem_location}'") else @gem_env = CurrentGemEnvironment.new @cleanup_gem_env = false - Chef::Log.debug("#{@new_resource} using gem from running ruby environment") + Chef::Log.debug("#{new_resource} using gem from running ruby environment") end end def is_omnibus? if RbConfig::CONFIG["bindir"] =~ %r{/(opscode|chef|chefdk)/embedded/bin} - Chef::Log.debug("#{@new_resource} detected omnibus installation in #{RbConfig::CONFIG['bindir']}") + Chef::Log.debug("#{new_resource} detected omnibus installation in #{RbConfig::CONFIG['bindir']}") # Omnibus installs to a static path because of linking on unix, find it. true elsif RbConfig::CONFIG["bindir"].sub(/^[\w]:/, "") == "/opscode/chef/embedded/bin" - Chef::Log.debug("#{@new_resource} detected omnibus installation in #{RbConfig::CONFIG['bindir']}") + Chef::Log.debug("#{new_resource} detected omnibus installation in #{RbConfig::CONFIG['bindir']}") # windows, with the drive letter removed true else @@ -411,25 +411,25 @@ class Chef end def find_gem_by_path - Chef::Log.debug("#{@new_resource} searching for 'gem' binary in path: #{ENV['PATH']}") + Chef::Log.debug("#{new_resource} searching for 'gem' binary in path: #{ENV['PATH']}") separator = ::File::ALT_SEPARATOR ? ::File::ALT_SEPARATOR : ::File::SEPARATOR - path_to_first_gem = ENV["PATH"].split(::File::PATH_SEPARATOR).find { |path| ::File.exists?(path + separator + "gem") } + path_to_first_gem = ENV["PATH"].split(::File::PATH_SEPARATOR).find { |path| ::File.exist?(path + separator + "gem") } raise Chef::Exceptions::FileNotFound, "Unable to find 'gem' binary in path: #{ENV['PATH']}" if path_to_first_gem.nil? path_to_first_gem + separator + "gem" end def gem_dependency - Gem::Dependency.new(@new_resource.package_name, @new_resource.version) + Gem::Dependency.new(new_resource.package_name, new_resource.version) end def source_is_remote? - return true if @new_resource.source.nil? - scheme = URI.parse(@new_resource.source).scheme + return true if new_resource.source.nil? + scheme = URI.parse(new_resource.source).scheme # URI.parse gets confused by MS Windows paths with forward slashes. scheme = nil if scheme =~ /^[a-z]$/ %w{http https}.include?(scheme) rescue URI::InvalidURIError - Chef::Log.debug("#{@new_resource} failed to parse source '#{@new_resource.source}' as a URI, assuming a local path") + Chef::Log.debug("#{new_resource} failed to parse source '#{new_resource.source}' as a URI, assuming a local path") false end @@ -445,16 +445,16 @@ class Chef # is the current version if !matching_installed_versions.empty? gemspec = matching_installed_versions.send(pos) - logger.debug { "#{@new_resource} found installed gem #{gemspec.name} version #{gemspec.version} matching #{gem_dependency}" } + logger.debug { "#{new_resource} found installed gem #{gemspec.name} version #{gemspec.version} matching #{gem_dependency}" } gemspec # If no version matching the requirements exists, the latest installed # version is the current version. elsif !all_installed_versions.empty? gemspec = all_installed_versions.send(pos) - logger.debug { "#{@new_resource} newest installed version of gem #{gemspec.name} is #{gemspec.version}" } + logger.debug { "#{new_resource} newest installed version of gem #{gemspec.name} is #{gemspec.version}" } gemspec else - logger.debug { "#{@new_resource} no installed version found for #{gem_dependency}" } + logger.debug { "#{new_resource} no installed version found for #{gem_dependency}" } nil end end @@ -470,21 +470,21 @@ class Chef end def gem_sources - @new_resource.source ? Array(@new_resource.source) : nil + new_resource.source ? Array(new_resource.source) : nil end def load_current_resource - @current_resource = Chef::Resource::Package::GemPackage.new(@new_resource.name) - @current_resource.package_name(@new_resource.package_name) + @current_resource = Chef::Resource::Package::GemPackage.new(new_resource.name) + current_resource.package_name(new_resource.package_name) if current_spec = current_version - @current_resource.version(current_spec.version.to_s) + current_resource.version(current_spec.version.to_s) end - @current_resource + current_resource end def cleanup_after_converge if @cleanup_gem_env - logger.debug { "#{@new_resource} resetting gem environment to default" } + logger.debug { "#{new_resource} resetting gem environment to default" } Gem.clear_paths end end @@ -494,7 +494,7 @@ class Chef if source_is_remote? @gem_env.candidate_version_from_remote(gem_dependency, *gem_sources).to_s else - @gem_env.candidate_version_from_file(gem_dependency, @new_resource.source).to_s + @gem_env.candidate_version_from_file(gem_dependency, new_resource.source).to_s end end end @@ -511,18 +511,18 @@ class Chef # 2. shell out to `gem install` when a String of options is given # 3. use gems API with options if a hash of options is given def install_package(name, version) - if source_is_remote? && @new_resource.gem_binary.nil? - if @new_resource.options.nil? - @gem_env.install(gem_dependency, :sources => gem_sources) - elsif @new_resource.options.kind_of?(Hash) - options = @new_resource.options + if source_is_remote? && new_resource.gem_binary.nil? + if new_resource.options.nil? + @gem_env.install(gem_dependency, sources: gem_sources) + elsif new_resource.options.is_a?(Hash) + options = new_resource.options options[:sources] = gem_sources @gem_env.install(gem_dependency, options) else install_via_gem_command(name, version) end - elsif @new_resource.gem_binary.nil? - @gem_env.install(@new_resource.source) + elsif new_resource.gem_binary.nil? + @gem_env.install(new_resource.source) else install_via_gem_command(name, version) end @@ -530,22 +530,22 @@ class Chef end def gem_binary_path - @new_resource.gem_binary || "gem" + new_resource.gem_binary || "gem" end def install_via_gem_command(name, version) - if @new_resource.source =~ /\.gem$/i - name = @new_resource.source - elsif @new_resource.clear_sources + if new_resource.source =~ /\.gem$/i + name = new_resource.source + elsif new_resource.clear_sources src = " --clear-sources" - src << (@new_resource.source && " --source=#{@new_resource.source}" || "") + src << (new_resource.source && " --source=#{new_resource.source}" || "") else - src = @new_resource.source && " --source=#{@new_resource.source} --source=#{Chef::Config[:rubygems_url]}" + src = new_resource.source && " --source=#{new_resource.source} --source=#{Chef::Config[:rubygems_url]}" end - if !version.nil? && version.length > 0 - shell_out_with_timeout!("#{gem_binary_path} install #{name} -q --no-rdoc --no-ri -v \"#{version}\"#{src}#{opts}", :env => nil) + if !version.nil? && !version.empty? + shell_out_with_timeout!("#{gem_binary_path} install #{name} -q --no-rdoc --no-ri -v \"#{version}\"#{src}#{opts}", env: nil) else - shell_out_with_timeout!("#{gem_binary_path} install \"#{name}\" -q --no-rdoc --no-ri #{src}#{opts}", :env => nil) + shell_out_with_timeout!("#{gem_binary_path} install \"#{name}\" -q --no-rdoc --no-ri #{src}#{opts}", env: nil) end end @@ -554,11 +554,11 @@ class Chef end def remove_package(name, version) - if @new_resource.gem_binary.nil? - if @new_resource.options.nil? + if new_resource.gem_binary.nil? + if new_resource.options.nil? @gem_env.uninstall(name, version) - elsif @new_resource.options.kind_of?(Hash) - @gem_env.uninstall(name, version, @new_resource.options) + elsif new_resource.options.is_a?(Hash) + @gem_env.uninstall(name, version, new_resource.options) else uninstall_via_gem_command(name, version) end @@ -569,9 +569,9 @@ class Chef def uninstall_via_gem_command(name, version) if version - shell_out_with_timeout!("#{gem_binary_path} uninstall #{name} -q -x -I -v \"#{version}\"#{opts}", :env => nil) + shell_out_with_timeout!("#{gem_binary_path} uninstall #{name} -q -x -I -v \"#{version}\"#{opts}", env: nil) else - shell_out_with_timeout!("#{gem_binary_path} uninstall #{name} -q -x -I -a#{opts}", :env => nil) + shell_out_with_timeout!("#{gem_binary_path} uninstall #{name} -q -x -I -a#{opts}", env: nil) end end @@ -582,7 +582,7 @@ class Chef private def opts - expand_options(@new_resource.options) + expand_options(new_resource.options) end end diff --git a/lib/chef/provider/package/smartos.rb b/lib/chef/provider/package/smartos.rb index 3f09bef212..8e4368f7c1 100644 --- a/lib/chef/provider/package/smartos.rb +++ b/lib/chef/provider/package/smartos.rb @@ -33,24 +33,24 @@ class Chef provides :smartos_package, os: "solaris2", platform_family: "smartos" def load_current_resource - Chef::Log.debug("#{@new_resource} loading current resource") - @current_resource = Chef::Resource::Package.new(@new_resource.name) - @current_resource.package_name(@new_resource.package_name) - check_package_state(@new_resource.package_name) - @current_resource # modified by check_package_state + Chef::Log.debug("#{new_resource} loading current resource") + @current_resource = Chef::Resource::Package.new(new_resource.name) + current_resource.package_name(new_resource.package_name) + check_package_state(new_resource.package_name) + current_resource # modified by check_package_state end def check_package_state(name) - Chef::Log.debug("#{@new_resource} checking package #{name}") + Chef::Log.debug("#{new_resource} checking package #{name}") version = nil - info = shell_out_with_timeout!("/opt/local/sbin/pkg_info", "-E", "#{name}*", :env => nil, :returns => [0, 1]) + info = shell_out_compact_timeout!("/opt/local/sbin/pkg_info", "-E", "#{name}*", env: nil, returns: [0, 1]) if info.stdout - version = info.stdout[/^#{@new_resource.package_name}-(.+)/, 1] + version = info.stdout[/^#{new_resource.package_name}-(.+)/, 1] end if version - @current_resource.version(version) + current_resource.version(version) end end @@ -58,7 +58,7 @@ class Chef return @candidate_version if @candidate_version name = nil version = nil - pkg = shell_out_with_timeout!("/opt/local/bin/pkgin", "se", new_resource.package_name, :env => nil, :returns => [0, 1]) + pkg = shell_out_compact_timeout!("/opt/local/bin/pkgin", "se", new_resource.package_name, env: nil, returns: [0, 1]) pkg.stdout.each_line do |line| case line when /^#{new_resource.package_name}/ @@ -70,20 +70,20 @@ class Chef end def install_package(name, version) - Chef::Log.debug("#{@new_resource} installing package #{name} version #{version}") + Chef::Log.debug("#{new_resource} installing package #{name} version #{version}") package = "#{name}-#{version}" - out = shell_out_with_timeout!("/opt/local/bin/pkgin", "-y", "install", package, :env => nil) + out = shell_out_compact_timeout!("/opt/local/bin/pkgin", "-y", "install", package, env: nil) end def upgrade_package(name, version) - Chef::Log.debug("#{@new_resource} upgrading package #{name} version #{version}") + Chef::Log.debug("#{new_resource} upgrading package #{name} version #{version}") install_package(name, version) end def remove_package(name, version) - Chef::Log.debug("#{@new_resource} removing package #{name} version #{version}") - package = "#{name}" - out = shell_out_with_timeout!("/opt/local/bin/pkgin", "-y", "remove", package, :env => nil) + Chef::Log.debug("#{new_resource} removing package #{name} version #{version}") + package = name.to_s + out = shell_out_compact_timeout!("/opt/local/bin/pkgin", "-y", "remove", package, env: nil) end end diff --git a/lib/chef/provider/package/solaris.rb b/lib/chef/provider/package/solaris.rb index 1c393e6a20..5537127310 100644 --- a/lib/chef/provider/package/solaris.rb +++ b/lib/chef/provider/package/solaris.rb @@ -33,45 +33,45 @@ class Chef # def initialize(*args) # super - # @current_resource = Chef::Resource::Package.new(@new_resource.name) + # @current_resource = Chef::Resource::Package.new(new_resource.name) # end def define_resource_requirements super requirements.assert(:install) do |a| - a.assertion { @new_resource.source } - a.failure_message Chef::Exceptions::Package, "Source for package #{@new_resource.name} required for action install" + a.assertion { new_resource.source } + a.failure_message Chef::Exceptions::Package, "Source for package #{new_resource.name} required for action install" end requirements.assert(:all_actions) do |a| - a.assertion { !@new_resource.source || @package_source_found } - a.failure_message Chef::Exceptions::Package, "Package #{@new_resource.name} not found: #{@new_resource.source}" - a.whyrun "would assume #{@new_resource.source} would be have previously been made available" + a.assertion { !new_resource.source || @package_source_found } + a.failure_message Chef::Exceptions::Package, "Package #{new_resource.name} not found: #{new_resource.source}" + a.whyrun "would assume #{new_resource.source} would be have previously been made available" end end def load_current_resource - @current_resource = Chef::Resource::Package.new(@new_resource.name) - @current_resource.package_name(@new_resource.package_name) + @current_resource = Chef::Resource::Package.new(new_resource.name) + current_resource.package_name(new_resource.package_name) - if @new_resource.source - @package_source_found = ::File.exists?(@new_resource.source) + if new_resource.source + @package_source_found = ::File.exist?(new_resource.source) if @package_source_found - Chef::Log.debug("#{@new_resource} checking pkg status") - shell_out_with_timeout("pkginfo -l -d #{@new_resource.source} #{@new_resource.package_name}").stdout.each_line do |line| + Chef::Log.debug("#{new_resource} checking pkg status") + shell_out_compact_timeout("pkginfo", "-l", "-d", new_resource.source, new_resource.package_name).stdout.each_line do |line| case line when /VERSION:\s+(.+)/ - @new_resource.version($1) + new_resource.version($1) end end end end - Chef::Log.debug("#{@new_resource} checking install state") - status = shell_out_with_timeout("pkginfo -l #{@current_resource.package_name}") + Chef::Log.debug("#{new_resource} checking install state") + status = shell_out_compact_timeout("pkginfo", "-l", current_resource.package_name) status.stdout.each_line do |line| case line when /VERSION:\s+(.+)/ - Chef::Log.debug("#{@new_resource} version #{$1} is already installed") - @current_resource.version($1) + Chef::Log.debug("#{new_resource} version #{$1} is already installed") + current_resource.version($1) end end @@ -79,56 +79,56 @@ class Chef raise Chef::Exceptions::Package, "pkginfo failed - #{status.inspect}!" end - @current_resource + current_resource end def candidate_version return @candidate_version if @candidate_version - status = shell_out_with_timeout("pkginfo -l -d #{@new_resource.source} #{new_resource.package_name}") + status = shell_out_compact_timeout("pkginfo", "-l", "-d", new_resource.source, new_resource.package_name) status.stdout.each_line do |line| case line when /VERSION:\s+(.+)/ @candidate_version = $1 - @new_resource.version($1) - Chef::Log.debug("#{@new_resource} setting install candidate version to #{@candidate_version}") + new_resource.version($1) + Chef::Log.debug("#{new_resource} setting install candidate version to #{@candidate_version}") end end unless status.exitstatus == 0 - raise Chef::Exceptions::Package, "pkginfo -l -d #{@new_resource.source} - #{status.inspect}!" + raise Chef::Exceptions::Package, "pkginfo -l -d #{new_resource.source} - #{status.inspect}!" end @candidate_version end def install_package(name, version) - Chef::Log.debug("#{@new_resource} package install options: #{@new_resource.options}") - if @new_resource.options.nil? - if ::File.directory?(@new_resource.source) # CHEF-4469 - command = "pkgadd -n -d #{@new_resource.source} #{@new_resource.package_name}" - else - command = "pkgadd -n -d #{@new_resource.source} all" - end - shell_out_with_timeout!(command) - Chef::Log.debug("#{@new_resource} installed version #{@new_resource.version} from: #{@new_resource.source}") + Chef::Log.debug("#{new_resource} package install options: #{options}") + if options.nil? + command = if ::File.directory?(new_resource.source) # CHEF-4469 + [ "pkgadd", "-n", "-d", new_resource.source, new_resource.package_name ] + else + [ "pkgadd", "-n", "-d", new_resource.source, "all" ] + end + shell_out_compact_timeout!(command) + Chef::Log.debug("#{new_resource} installed version #{new_resource.version} from: #{new_resource.source}") else - if ::File.directory?(@new_resource.source) # CHEF-4469 - command = "pkgadd -n#{expand_options(@new_resource.options)} -d #{@new_resource.source} #{@new_resource.package_name}" - else - command = "pkgadd -n#{expand_options(@new_resource.options)} -d #{@new_resource.source} all" - end - shell_out_with_timeout!(command) - Chef::Log.debug("#{@new_resource} installed version #{@new_resource.version} from: #{@new_resource.source}") + command = if ::File.directory?(new_resource.source) # CHEF-4469 + [ "pkgadd", "-n", options, "-d", new_resource.source, new_resource.package_name ] + else + [ "pkgadd", "-n", options, "-d", new_resource.source, "all" ] + end + shell_out_compact_timeout!(*command) + Chef::Log.debug("#{new_resource} installed version #{new_resource.version} from: #{new_resource.source}") end end - alias_method :upgrade_package, :install_package + alias upgrade_package install_package def remove_package(name, version) - if @new_resource.options.nil? - shell_out_with_timeout!( "pkgrm -n #{name}" ) - Chef::Log.debug("#{@new_resource} removed version #{@new_resource.version}") + if options.nil? + shell_out_compact_timeout!( "pkgrm", "-n", name ) + Chef::Log.debug("#{new_resource} removed version #{new_resource.version}") else - shell_out_with_timeout!( "pkgrm -n#{expand_options(@new_resource.options)} #{name}" ) - Chef::Log.debug("#{@new_resource} removed version #{@new_resource.version}") + shell_out_compact_timeout!( "pkgrm", "-n", options, name ) + Chef::Log.debug("#{new_resource} removed version #{new_resource.version}") end end diff --git a/lib/chef/provider/package/windows.rb b/lib/chef/provider/package/windows.rb index 504d5d394a..ca9d1e813a 100644 --- a/lib/chef/provider/package/windows.rb +++ b/lib/chef/provider/package/windows.rb @@ -104,8 +104,8 @@ class Chef return :nsis end - if io.tell() < filesize - io.seek(io.tell() - overlap) + if io.tell < filesize + io.seek(io.tell - overlap) end end @@ -195,7 +195,7 @@ class Chef end def downloadable_file_missing? - !new_resource.source.nil? && uri_scheme?(new_resource.source) && !::File.exists?(source_location) + !new_resource.source.nil? && uri_scheme?(new_resource.source) && !::File.exist?(source_location) end def resource_for_provider diff --git a/lib/chef/provider/package/windows/exe.rb b/lib/chef/provider/package/windows/exe.rb index 60065d9019..0baea6bccd 100644 --- a/lib/chef/provider/package/windows/exe.rb +++ b/lib/chef/provider/package/windows/exe.rb @@ -69,10 +69,10 @@ class Chef def remove_package uninstall_version = new_resource.version || current_installed_version uninstall_entries.select { |entry| [uninstall_version].flatten.include?(entry.display_version) } - .map { |version| version.uninstall_string }.uniq.each do |uninstall_string| - Chef::Log.debug("Registry provided uninstall string for #{new_resource} is '#{uninstall_string}'") - shell_out!(uninstall_command(uninstall_string), { :timeout => new_resource.timeout, :returns => new_resource.returns }) - end + .map(&:uninstall_string).uniq.each do |uninstall_string| + Chef::Log.debug("Registry provided uninstall string for #{new_resource} is '#{uninstall_string}'") + shell_out!(uninstall_command(uninstall_string), timeout: new_resource.timeout, returns: new_resource.returns) + end end private @@ -85,13 +85,13 @@ class Chef " ", unattended_flags, ].join - %Q{start "" /wait #{uninstall_string} & exit %%%%ERRORLEVEL%%%%} + %{start "" /wait #{uninstall_string} & exit %%%%ERRORLEVEL%%%%} end def current_installed_version @current_installed_version ||= if uninstall_entries.count != 0 - uninstall_entries.map { |entry| entry.display_version }.uniq + uninstall_entries.map(&:display_version).uniq end end diff --git a/lib/chef/provider/package/windows/msi.rb b/lib/chef/provider/package/windows/msi.rb index ee3b2f7e8e..7e6048ce49 100644 --- a/lib/chef/provider/package/windows/msi.rb +++ b/lib/chef/provider/package/windows/msi.rb @@ -16,7 +16,7 @@ # limitations under the License. # -# TODO: Allow @new_resource.source to be a Product Code as a GUID for uninstall / network install +# TODO: Allow new_resource.source to be a Product Code as a GUID for uninstall / network install require "chef/win32/api/installer" if (RUBY_PLATFORM =~ /mswin|mingw32|windows/) && Chef::Platform.supports_msi? require "chef/mixin/shell_out" @@ -51,7 +51,7 @@ class Chef get_installed_version(product_code) else if uninstall_entries.count != 0 - uninstall_entries.map { |entry| entry.display_version }.uniq + uninstall_entries.map(&:display_version).uniq end end end @@ -67,23 +67,23 @@ class Chef def install_package # We could use MsiConfigureProduct here, but we'll start off with msiexec Chef::Log.debug("#{new_resource} installing MSI package '#{new_resource.source}'") - shell_out!("msiexec /qn /i \"#{new_resource.source}\" #{expand_options(new_resource.options)}", { :timeout => new_resource.timeout, :returns => new_resource.returns }) + shell_out!("msiexec /qn /i \"#{new_resource.source}\" #{expand_options(new_resource.options)}", timeout: new_resource.timeout, returns: new_resource.returns) end def remove_package # We could use MsiConfigureProduct here, but we'll start off with msiexec if !new_resource.source.nil? && ::File.exist?(new_resource.source) Chef::Log.debug("#{new_resource} removing MSI package '#{new_resource.source}'") - shell_out!("msiexec /qn /x \"#{new_resource.source}\" #{expand_options(new_resource.options)}", { :timeout => new_resource.timeout, :returns => new_resource.returns }) + shell_out!("msiexec /qn /x \"#{new_resource.source}\" #{expand_options(new_resource.options)}", timeout: new_resource.timeout, returns: new_resource.returns) else uninstall_version = new_resource.version || installed_version uninstall_entries.select { |entry| [uninstall_version].flatten.include?(entry.display_version) } - .map { |version| version.uninstall_string }.uniq.each do |uninstall_string| + .map(&:uninstall_string).uniq.each do |uninstall_string| uninstall_string = "msiexec /x #{uninstall_string.match(/{.*}/)}" uninstall_string += expand_options(new_resource.options) uninstall_string += " /q" unless uninstall_string.downcase =~ / \/q/ Chef::Log.debug("#{new_resource} removing MSI package version using '#{uninstall_string}'") - shell_out!(uninstall_string, { :timeout => new_resource.timeout, :returns => new_resource.returns }) + shell_out!(uninstall_string, timeout: new_resource.timeout, returns: new_resource.returns) end end end diff --git a/lib/chef/provider/package/yum.rb b/lib/chef/provider/package/yum.rb index 22ba5cb50a..d37aa1fb73 100644 --- a/lib/chef/provider/package/yum.rb +++ b/lib/chef/provider/package/yum.rb @@ -108,7 +108,7 @@ class Chef islocked = true end end - return islocked + islocked end # @@ -195,10 +195,10 @@ class Chef if new_resource.options repo_control = [] new_resource.options.split.each do |opt| - repo_control << opt if opt =~ %r{--(enable|disable)repo=.+} + repo_control << opt if opt =~ /--(enable|disable)repo=.+/ end - if repo_control.size > 0 + if !repo_control.empty? @yum.enable_extra_repo_control(repo_control.join(" ")) else @yum.disable_extra_repo_control @@ -225,7 +225,7 @@ class Chef installed_versions << iv = @yum.installed_version(pkg_name, pkg_arch) candidate_versions << cv = @yum.candidate_version(pkg_name, pkg_arch) - Chef::Log.debug("Found Yum package: #{pkg_name} installed version: #{iv || "(none)"} candidate version: #{cv || "(none)"}") + Chef::Log.debug("Found Yum package: #{pkg_name} installed version: #{iv || '(none)'} candidate version: #{cv || '(none)'}") end @installed_version = installed_versions.length > 1 ? installed_versions : installed_versions[0] @@ -235,10 +235,12 @@ class Chef # Query the provided source file for the package name and version def query_source_file Chef::Log.debug("#{new_resource} checking rpm status") - shell_out_with_timeout!("rpm -qp --queryformat '%{NAME} %{VERSION}-%{RELEASE} %{ARCH}\n' #{new_resource.source}", :timeout => Chef::Config[:yum_timeout]).stdout.each_line do |line| + shell_out_with_timeout!("rpm -qp --queryformat '%{NAME} %{VERSION}-%{RELEASE} %{ARCH}\n' #{new_resource.source}", timeout: Chef::Config[:yum_timeout]).stdout.each_line do |line| case line when /^(\S+)\s(\S+)\s(\S+)$/ - n, v, a = $1, $2, $3 + n = $1 + v = $2 + a = $3 unless new_resource.package_name == n Chef::Log.debug("#{new_resource} updating package_name from #{new_resource.package_name} to #{n} (per #{new_resource.source})") @@ -264,7 +266,7 @@ class Chef def yum_command(command) command = "#{yum_binary} #{command}" Chef::Log.debug("#{new_resource}: yum command: \"#{command}\"") - status = shell_out_with_timeout(command, { :timeout => Chef::Config[:yum_timeout] }) + status = shell_out_with_timeout(command, timeout: Chef::Config[:yum_timeout]) # This is fun: rpm can encounter errors in the %post/%postun scripts which aren't # considered fatal - meaning the rpm is still successfully installed. These issue @@ -278,12 +280,11 @@ class Chef if status.exitstatus == 1 status.stdout.each_line do |l| # rpm-4.4.2.3 lib/psm.c line 2182 - if l =~ %r{^error: %(post|postun)\(.*\) scriptlet failed, exit status \d+$} - Chef::Log.warn("#{new_resource} caught non-fatal scriptlet issue: \"#{l}\". Can't trust yum exit status " + - "so running install again to verify.") - status = shell_out_with_timeout(command, { :timeout => Chef::Config[:yum_timeout] }) - break - end + next unless l =~ /^error: %(post|postun)\(.*\) scriptlet failed, exit status \d+$/ + Chef::Log.warn("#{new_resource} caught non-fatal scriptlet issue: \"#{l}\". Can't trust yum exit status " \ + "so running install again to verify.") + status = shell_out_with_timeout(command, timeout: Chef::Config[:yum_timeout]) + break end end @@ -323,7 +324,7 @@ class Chef log_method = "downgrading" else # we bail like yum when the package is older - raise Chef::Exceptions::Package, "Installed package #{yum_syntax(n, cv, a)} is newer " + + raise Chef::Exceptions::Package, "Installed package #{yum_syntax(n, cv, a)} is newer " \ "than candidate package #{yum_syntax(n, v, a)}" end end @@ -343,25 +344,24 @@ class Chef pkg_string_bits = [] as_array(name).zip(current_version_array, as_array(version), safe_arch_array).each do |n, cv, v, a| next if n.nil? - unless v == cv - s = yum_syntax(n, v, a) - repo = @yum.package_repository(n, v, a) - repos << "#{s} from #{repo} repository" - pkg_string_bits << s - end + next if v == cv + s = yum_syntax(n, v, a) + repo = @yum.package_repository(n, v, a) + repos << "#{s} from #{repo} repository" + pkg_string_bits << s end pkg_string = pkg_string_bits.join(" ") Chef::Log.info("#{new_resource} #{log_method} #{repos.join(' ')}") yum_command("-d0 -e0 -y#{expand_options(new_resource.options)} #{method} #{pkg_string}") else - raise Chef::Exceptions::Package, "Version #{version} of #{name} not found. Did you specify both version " + + raise Chef::Exceptions::Package, "Version #{version} of #{name} not found. Did you specify both version " \ "and release? (version-release, e.g. 1.84-10.fc6)" end end # Allow for foo.x86_64 style package_name like yum uses in it's output def parse_arch(package_name) - if package_name =~ %r{^(.*)\.(.*)$} + if package_name =~ /^(.*)\.(.*)$/ new_package_name = $1 new_arch = $2 # foo.i386 and foo.beta1 are both valid package names or expressions of an arch. @@ -377,7 +377,7 @@ class Chef return new_package_name, new_arch end end - return package_name, nil + [package_name, nil] end # @@ -389,17 +389,16 @@ class Chef # the list of packages and versions to incorporate those values. def convert_dependency_strings_into_packages package_name_array.each_with_index do |n, index| - unless @yum.package_available?(n) - # If they aren't in the installed packages they could be a dependency. - dep = parse_dependency(n, new_version_array[index]) - if dep - if new_resource.package_name.is_a?(Array) - new_resource.package_name(package_name_array - [n] + [dep.first]) - new_resource.version(new_version_array - [new_version_array[index]] + [dep.last]) if dep.last - else - new_resource.package_name(dep.first) - new_resource.version(dep.last) if dep.last - end + next if @yum.package_available?(n) + # If they aren't in the installed packages they could be a dependency. + dep = parse_dependency(n, new_version_array[index]) + if dep + if new_resource.package_name.is_a?(Array) + new_resource.package_name(package_name_array - [n] + [dep.first]) + new_resource.version(new_version_array - [new_version_array[index]] + [dep.last]) if dep.last + else + new_resource.package_name(dep.first) + new_resource.version(dep.last) if dep.last end end end @@ -421,14 +420,14 @@ class Chef # Transform the package_name into a requirement # If we are passed a version or a version constraint we have to assume it's a requirement first. If it can't be - # parsed only yum_require.name will be set and @new_resource.version will be left intact - if version - require_string = "#{name} #{version}" - else - # Transform the package_name into a requirement, might contain a version, could just be - # a match for virtual provides - require_string = name - end + # parsed only yum_require.name will be set and new_resource.version will be left intact + require_string = if version + "#{name} #{version}" + else + # Transform the package_name into a requirement, might contain a version, could just be + # a match for virtual provides + name + end yum_require = RPMRequire.parse(require_string) # and gather all the packages that have a Provides feature satisfying the requirement. # It could be multiple be we can only manage one @@ -438,7 +437,7 @@ class Chef # Don't bother if we are just ensuring a package is removed - we don't need Provides data actions = Array(new_resource.action) unless actions.size == 1 && (actions[0] == :remove || actions[0] == :purge) - Chef::Log.debug("#{new_resource} couldn't match #{new_resource.package_name} in " + + Chef::Log.debug("#{new_resource} couldn't match #{new_resource.package_name} in " \ "installed Provides, loading available Provides - this may take a moment") @yum.reload_provides packages = @yum.packages_from_require(yum_require) @@ -461,8 +460,8 @@ class Chef unique_names.uniq! if unique_names.size > 1 - Chef::Log.warn("#{new_resource} matched multiple Provides for #{new_resource.package_name} " + - "but we can only use the first match: #{new_package_name}. Please use a more " + + Chef::Log.warn("#{new_resource} matched multiple Provides for #{new_resource.package_name} " \ + "but we can only use the first match: #{new_package_name}. Please use a more " \ "specific version.") end @@ -528,7 +527,7 @@ class Chef if new_resource.respond_to?("flush_cache") new_resource.flush_cache else - { :before => false, :after => false } + { before: false, after: false } end end end diff --git a/lib/chef/provider/package/yum/rpm_utils.rb b/lib/chef/provider/package/yum/rpm_utils.rb index 032597d047..0709118184 100644 --- a/lib/chef/provider/package/yum/rpm_utils.rb +++ b/lib/chef/provider/package/yum/rpm_utils.rb @@ -37,7 +37,7 @@ class Chef lead = 0 tail = evr.size - if %r{^([\d]+):}.match(evr) # rubocop:disable Performance/RedundantMatch + if /^([\d]+):/.match(evr) # rubocop:disable Performance/RedundantMatch epoch = $1.to_i lead = $1.length + 1 elsif evr[0].ord == ":".ord @@ -45,7 +45,7 @@ class Chef lead = 1 end - if %r{:?.*-(.*)$}.match(evr) # rubocop:disable Performance/RedundantMatch + if /:?.*-(.*)$/.match(evr) # rubocop:disable Performance/RedundantMatch release = $1 tail = evr.length - release.length - lead - 1 @@ -230,17 +230,17 @@ class Chef @v = args[1] @r = args[2] else - raise ArgumentError, "Expecting either 'epoch-version-release' or 'epoch, " + + raise ArgumentError, "Expecting either 'epoch-version-release' or 'epoch, " \ "version, release'" end end attr_reader :e, :v, :r - alias :epoch :e - alias :version :v - alias :release :r + alias epoch e + alias version v + alias release r def self.parse(*args) - self.new(*args) + new(*args) end def <=>(other) @@ -317,7 +317,7 @@ class Chef return cmp end - return 0 + 0 end end @@ -339,7 +339,7 @@ class Chef @a = args[4] @provides = args[5] else - raise ArgumentError, "Expecting either 'name, epoch-version-release, arch, provides' " + + raise ArgumentError, "Expecting either 'name, epoch-version-release, arch, provides' " \ "or 'name, epoch, version, release, arch, provides'" end @@ -349,8 +349,8 @@ class Chef end end attr_reader :n, :a, :version, :provides - alias :name :n - alias :arch :a + alias name n + alias arch a def <=>(other) compare(other) @@ -395,7 +395,7 @@ class Chef end end - return 0 + 0 end def to_s @@ -423,7 +423,7 @@ class Chef @version = RPMVersion.new(e, v, r) @flag = args[4] || :== else - raise ArgumentError, "Expecting either 'name, epoch-version-release, flag' or " + + raise ArgumentError, "Expecting either 'name, epoch-version-release, flag' or " \ "'name, epoch, version, release, flag'" end end @@ -434,25 +434,25 @@ class Chef # "mtr >= 2:0.71-3.0" # "mta" def self.parse(string) - if %r{^(\S+)\s+(>|>=|=|==|<=|<)\s+(\S+)$}.match(string) # rubocop:disable Performance/RedundantMatch + if /^(\S+)\s+(>|>=|=|==|<=|<)\s+(\S+)$/.match(string) # rubocop:disable Performance/RedundantMatch name = $1 - if $2 == "=" - flag = :== - else - flag = :"#{$2}" - end + flag = if $2 == "=" + :== + else + :"#{$2}" + end version = $3 - return self.new(name, version, flag) + new(name, version, flag) else name = string - return self.new(name, nil, nil) + new(name, nil, nil) end end # Test if another RPMDependency satisfies our requirements def satisfy?(y) - unless y.kind_of?(RPMDependency) + unless y.is_a?(RPMDependency) raise ArgumentError, "Expecting an RPMDependency object" end @@ -481,7 +481,7 @@ class Chef return true end - return false + false end end @@ -504,11 +504,11 @@ class Chef class RPMDb def initialize # package name => [ RPMPackage, RPMPackage ] of different versions - @rpms = Hash.new + @rpms = {} # package nevra => RPMPackage for lookups - @index = Hash.new + @index = {} # provide name (aka feature) => [RPMPackage, RPMPackage] each providing this feature - @provides = Hash.new + @provides = {} # RPMPackages listed as available @available = Set.new # RPMPackages listed as installed @@ -516,7 +516,7 @@ class Chef end def [](package_name) - self.lookup(package_name) + lookup(package_name) end # Lookup package_name and return a descending array of package objects @@ -537,11 +537,11 @@ class Chef # The available/installed state can be overwritten for existing packages. def push(*args) args.flatten.each do |new_rpm| - unless new_rpm.kind_of?(RPMDbPackage) + unless new_rpm.is_a?(RPMDbPackage) raise ArgumentError, "Expecting an RPMDbPackage object" end - @rpms[new_rpm.n] ||= Array.new + @rpms[new_rpm.n] ||= [] # we may already have this one, like when the installed list is refreshed idx = @index[new_rpm.nevra] @@ -552,7 +552,7 @@ class Chef @rpms[new_rpm.n] << new_rpm new_rpm.provides.each do |provide| - @provides[provide.name] ||= Array.new + @provides[provide.name] ||= [] @provides[provide.name] << new_rpm end @@ -574,7 +574,7 @@ class Chef end def <<(*args) - self.push(args) + push(args) end def clear @@ -596,7 +596,7 @@ class Chef def size @rpms.size end - alias :length :size + alias length size def available_size @available.size @@ -615,7 +615,7 @@ class Chef end def whatprovides(rpmdep) - unless rpmdep.kind_of?(RPMDependency) + unless rpmdep.is_a?(RPMDependency) raise ArgumentError, "Expecting an RPMDependency object" end @@ -632,7 +632,7 @@ class Chef end end - return what + what end end diff --git a/lib/chef/provider/package/yum/yum_cache.rb b/lib/chef/provider/package/yum/yum_cache.rb index 7462529113..9fd95af138 100644 --- a/lib/chef/provider/package/yum/yum_cache.rb +++ b/lib/chef/provider/package/yum/yum_cache.rb @@ -101,12 +101,12 @@ class Chef status = nil begin - status = shell_out!("#{python_bin} #{yum_dump_path}#{opts}", :timeout => Chef::Config[:yum_timeout]) + status = shell_out!("#{python_bin} #{yum_dump_path}#{opts}", timeout: Chef::Config[:yum_timeout]) status.stdout.each_line do |line| one_line = true line.chomp! - if line =~ %r{\[option (.*)\] (.*)} + if line =~ /\[option (.*)\] (.*)/ if $1 == "installonlypkgs" @allow_multi_install = $2.split else @@ -115,7 +115,7 @@ class Chef next end - if line =~ %r{^(\S+) ([0-9]+) (\S+) (\S+) (\S+) \[(.*)\] ([i,a,r]) (\S+)$} + if line =~ /^(\S+) ([0-9]+) (\S+) (\S+) (\S+) \[(.*)\] ([i,a,r]) (\S+)$/ name = $1 epoch = $2 version = $3 @@ -125,7 +125,7 @@ class Chef type = $7 repoid = $8 else - Chef::Log.warn("Problem parsing line '#{line}' from yum-dump.py! " + + Chef::Log.warn("Problem parsing line '#{line}' from yum-dump.py! " \ "Please check your yum configuration.") next end @@ -158,7 +158,7 @@ class Chef raise Chef::Exceptions::Package, "Yum failed - #{status.inspect} - returns: #{error}" else unless one_line - Chef::Log.warn("Odd, no output from yum-dump.py. Please check " + + Chef::Log.warn("Odd, no output from yum-dump.py. Please check " \ "your yum configuration.") end end @@ -233,7 +233,7 @@ class Chef if @rpmdb.lookup(package_name) return true else - if package_name =~ %r{^(.*)\.(.*)$} + if package_name =~ /^(.*)\.(.*)$/ pkg_name = $1 pkg_arch = $2 @@ -245,7 +245,7 @@ class Chef end end - return false + false end # Returns a array of packages satisfying an RPMDependency @@ -260,7 +260,7 @@ class Chef return true if desired_version == v end - return false + false end # Return the source repository for a package-version.arch @@ -269,14 +269,14 @@ class Chef return pkg.repoid if desired_version == pkg.version.to_s end - return nil + nil end # Return the latest available version for a package.arch def available_version(package_name, arch = nil) version(package_name, arch, true, false) end - alias :candidate_version :available_version + alias candidate_version available_version # Return the currently installed version for a package.arch def installed_version(package_name, arch = nil) @@ -361,12 +361,12 @@ class Chef # ['atk = 1.12.2-1.fc6', 'libatk-1.0.so.0'] string.split(", ").each do |seg| # 'atk = 1.12.2-1.fc6' - if seg =~ %r{^'(.*)'$} + if seg =~ /^'(.*)'$/ ret << RPMProvide.parse($1) end end - return ret + ret end end # YumCache diff --git a/lib/chef/provider/package/zypper.rb b/lib/chef/provider/package/zypper.rb index 6965052723..45c6c91f60 100644 --- a/lib/chef/provider/package/zypper.rb +++ b/lib/chef/provider/package/zypper.rb @@ -35,7 +35,7 @@ class Chef candidate_version = current_version = nil is_installed = false Chef::Log.debug("#{new_resource} checking zypper") - status = shell_out_with_timeout!("zypper --non-interactive info #{package_name}") + status = shell_out_compact_timeout!("zypper", "--non-interactive", "info", package_name) status.stdout.each_line do |line| case line when /^Version *: (.+) *$/ @@ -77,14 +77,14 @@ class Chef def package_locked(name, version) islocked = false - locked = shell_out_with_timeout!("zypper locks") + locked = shell_out_compact_timeout!("zypper", "locks") locked.stdout.each_line do |line| line_package = line.split("|").shift(2).last.strip if line_package == name islocked = true end end - return islocked + islocked end def load_current_resource @@ -103,7 +103,7 @@ class Chef end def install_package(name, version) - zypper_package("install --auto-agree-with-licenses", name, version) + zypper_package("install", "--auto-agree-with-licenses", name, version) end def upgrade_package(name, version) @@ -116,7 +116,7 @@ class Chef end def purge_package(name, version) - zypper_package("remove --clean-deps", name, version) + zypper_package("remove", "--clean-deps", name, version) end def lock_package(name, version) @@ -135,24 +135,24 @@ class Chef end end - def zypper_package(command, names, versions) + def zypper_package(command, *options, names, versions) zipped_names = zip(names, versions) if zypper_version < 1.0 - shell_out_with_timeout!(a_to_s("zypper", gpg_checks, command, "-y", names)) + shell_out_compact_timeout!("zypper", gpg_checks, command, *options, "-y", names) else - shell_out_with_timeout!(a_to_s("zypper --non-interactive", gpg_checks, command, zipped_names)) + shell_out_compact_timeout!("zypper", "--non-interactive", gpg_checks, command, *options, zipped_names) end end def gpg_checks case Chef::Config[:zypper_check_gpg] when true - "" + nil when false "--no-gpg-checks" when nil - Chef::Log.warn("Chef::Config[:zypper_check_gpg] was not set. " + - "All packages will be installed without gpg signature checks. " + + Chef::Log.warn("Chef::Config[:zypper_check_gpg] was not set. " \ + "All packages will be installed without gpg signature checks. " \ "This is a security hazard.") "--no-gpg-checks" end diff --git a/lib/chef/resource/freebsd_package.rb b/lib/chef/resource/freebsd_package.rb index a94dd0a928..ecaff95244 100644 --- a/lib/chef/resource/freebsd_package.rb +++ b/lib/chef/resource/freebsd_package.rb @@ -37,7 +37,7 @@ class Chef end def supports_pkgng? - ships_with_pkgng? || !!shell_out!("make -V WITH_PKGNG", :env => nil).stdout.match(/yes/i) + ships_with_pkgng? || !!shell_out_compact!("make", "-V", "WITH_PKGNG", :env => nil).stdout.match(/yes/i) end private diff --git a/lib/chef/resource/gem_package.rb b/lib/chef/resource/gem_package.rb index e095115356..5511d3c580 100644 --- a/lib/chef/resource/gem_package.rb +++ b/lib/chef/resource/gem_package.rb @@ -34,7 +34,7 @@ class Chef # gem will be installed via the gems API. When a String is given, the gem # will be installed by shelling out to the gem command. Using a Hash of # options with an explicit gem_binary will result in undefined behavior. - property :options, [ String, Hash, nil ], desired_state: false + property :options, [ String, Hash, Array, nil ], desired_state: false end end diff --git a/lib/chef/resource/package.rb b/lib/chef/resource/package.rb index 0738107339..baaa5be2c8 100644 --- a/lib/chef/resource/package.rb +++ b/lib/chef/resource/package.rb @@ -36,7 +36,7 @@ class Chef property :package_name, [ String, Array ], identity: true property :version, [ String, Array ] - property :options, String + property :options, [ String, Array ] property :response_file, String, desired_state: false property :response_file_variables, Hash, default: lazy { {} }, desired_state: false property :source, String, desired_state: false |