diff options
Diffstat (limited to 'lib')
408 files changed, 2043 insertions, 1740 deletions
diff --git a/lib/chef/action_collection.rb b/lib/chef/action_collection.rb index af28bf8542..7b1997cfaf 100644 --- a/lib/chef/action_collection.rb +++ b/lib/chef/action_collection.rb @@ -145,6 +145,7 @@ class Chef # def converge_failed(exception) return if consumers.empty? + detect_unprocessed_resources end @@ -156,6 +157,7 @@ class Chef # def resource_action_start(new_resource, action, notification_type = nil, notifier = nil) return if consumers.empty? + pending_updates << ActionRecord.new(new_resource, action, pending_updates.length) end @@ -166,6 +168,7 @@ class Chef # def resource_current_state_loaded(new_resource, action, current_resource) return if consumers.empty? + current_record.current_resource = current_resource end @@ -175,6 +178,7 @@ class Chef # def resource_up_to_date(new_resource, action) return if consumers.empty? + current_record.status = :up_to_date end @@ -184,6 +188,7 @@ class Chef # def resource_skipped(resource, action, conditional) return if consumers.empty? + current_record.status = :skipped current_record.conditional = conditional end @@ -194,6 +199,7 @@ class Chef # def resource_updated(new_resource, action) return if consumers.empty? + current_record.status = :updated end @@ -203,6 +209,7 @@ class Chef # def resource_failed(new_resource, action, exception) return if consumers.empty? + current_record.status = :failed current_record.exception = exception end @@ -213,6 +220,7 @@ class Chef # def resource_completed(new_resource) return if consumers.empty? + current_record.elapsed_time = new_resource.elapsed_time # Verify if the resource has sensitive data and create a new blank resource with only diff --git a/lib/chef/api_client.rb b/lib/chef/api_client.rb index 5c78da41ec..0b82cfa972 100644 --- a/lib/chef/api_client.rb +++ b/lib/chef/api_client.rb @@ -157,7 +157,7 @@ class Chef def self.list(inflate = false) if inflate - response = Hash.new + response = {} Chef::Search::Query.new.search(:client) do |n| n = json_create(n) if n.instance_of?(Hash) response[n.name] = n @@ -171,7 +171,7 @@ class Chef # Load a client by name via the API def self.load(name) response = http_api.get("clients/#{name}") - if response.kind_of?(Chef::ApiClient) + if response.is_a?(Chef::ApiClient) response else from_hash(response) diff --git a/lib/chef/api_client/registration.rb b/lib/chef/api_client/registration.rb index dc4bb4e57a..fea4b001bc 100644 --- a/lib/chef/api_client/registration.rb +++ b/lib/chef/api_client/registration.rb @@ -60,6 +60,7 @@ class Chef rescue Net::HTTPFatalError => e # HTTPFatalError implies 5xx. raise if retries <= 0 + retries -= 1 Chef::Log.warn("Failed to register new client, #{retries} tries remaining") Chef::Log.warn("Response: HTTP #{e.response.code} - #{e}") @@ -71,7 +72,7 @@ class Chef def assert_destination_writable! abs_path = File.expand_path(destination) - if !File.exists?(File.dirname(abs_path)) + unless File.exists?(File.dirname(abs_path)) begin FileUtils.mkdir_p(File.dirname(abs_path)) rescue Errno::EACCES @@ -97,6 +98,7 @@ class Chef # If create fails because the client exists, attempt to update. This # requires admin privileges. raise unless e.response.code == "409" + update end @@ -160,8 +162,7 @@ class Chef api_version: "0", client_name: Chef::Config[:validation_client_name], signing_key_filename: Chef::Config[:validation_key], - } - ) + }) end # Whether or not to generate keys locally and post the public key to the diff --git a/lib/chef/api_client_v1.rb b/lib/chef/api_client_v1.rb index 513d546e64..f3f83cad4e 100644 --- a/lib/chef/api_client_v1.rb +++ b/lib/chef/api_client_v1.rb @@ -190,7 +190,7 @@ class Chef def self.list(inflate = false) if inflate - response = Hash.new + response = {} Chef::Search::Query.new.search(:client) do |n| n = from_hash(n) if n.instance_of?(Hash) response[n.name] = n @@ -270,6 +270,7 @@ class Chef # rescue API V0 if 406 and the server supports V0 supported_versions = server_client_api_version_intersection(e, SUPPORTED_API_VERSIONS) raise e unless supported_versions && supported_versions.include?(0) + new_client = chef_rest_v0.put("clients/#{name}", payload) end diff --git a/lib/chef/application.rb b/lib/chef/application.rb index 0b4ae139d7..a632a97319 100644 --- a/lib/chef/application.rb +++ b/lib/chef/application.rb @@ -353,6 +353,7 @@ class Chef def handle_child_exit(pid_and_status) status = pid_and_status[1] return true if status.success? + message = if status.signaled? "Chef run process terminated by signal #{status.termsig} (#{Signal.list.invert[status.termsig]})" else diff --git a/lib/chef/application/apply.rb b/lib/chef/application/apply.rb index 1a9b115632..a5fe2260db 100644 --- a/lib/chef/application/apply.rb +++ b/lib/chef/application/apply.rb @@ -184,7 +184,7 @@ class Chef::Application::Apply < Chef::Application @recipe_text = STDIN.read temp_recipe_file else - if !ARGV[0] + unless ARGV[0] puts opt_parser Chef::Application.exit! "No recipe file provided", Chef::Exceptions::RecipeNotFound.new end diff --git a/lib/chef/application/client.rb b/lib/chef/application/client.rb index d3e9a77646..1e1b76de15 100644 --- a/lib/chef/application/client.rb +++ b/lib/chef/application/client.rb @@ -469,7 +469,7 @@ class Chef::Application::Client < Chef::Application loop do sleep_then_run_chef_client(time_to_sleep) - Chef::Application.exit!("Exiting", 0) if !Chef::Config[:interval] + Chef::Application.exit!("Exiting", 0) unless Chef::Config[:interval] end end diff --git a/lib/chef/application/solo.rb b/lib/chef/application/solo.rb index 29ee56a7e4..29ba1971e1 100644 --- a/lib/chef/application/solo.rb +++ b/lib/chef/application/solo.rb @@ -272,7 +272,7 @@ class Chef::Application::Solo < Chef::Application Chef::Application.fatal!(unforked_interval_error_message) if !Chef::Config[:client_fork] && Chef::Config[:interval] if Chef::Config[:recipe_url] - cookbooks_path = Array(Chef::Config[:cookbook_path]).detect { |e| Pathname.new(e).cleanpath.to_s =~ /\/cookbooks\/*$/ } + cookbooks_path = Array(Chef::Config[:cookbook_path]).detect { |e| Pathname.new(e).cleanpath.to_s =~ %r{/cookbooks/*$} } recipes_path = File.expand_path(File.join(cookbooks_path, "..")) if Chef::Config[:delete_entire_chef_repo] @@ -342,7 +342,7 @@ class Chef::Application::Solo < Chef::Application end run_chef_client - if !Chef::Config[:interval] + unless Chef::Config[:interval] Chef::Application.exit! "Exiting", 0 end rescue SystemExit => e diff --git a/lib/chef/application/windows_service.rb b/lib/chef/application/windows_service.rb index e0df23371c..04a8812efc 100644 --- a/lib/chef/application/windows_service.rb +++ b/lib/chef/application/windows_service.rb @@ -40,7 +40,7 @@ class Chef option :config_file, short: "-c CONFIG", long: "--config CONFIG", - default: "#{ENV['SYSTEMDRIVE']}/chef/client.rb", + default: "#{ENV["SYSTEMDRIVE"]}/chef/client.rb", description: "The configuration file to use for #{Chef::Dist::PRODUCT} runs." option :log_location, @@ -60,7 +60,7 @@ class Chef description: "Set the number of seconds to wait between #{Chef::Dist::PRODUCT} runs.", proc: lambda { |s| s.to_i } - DEFAULT_LOG_LOCATION ||= "#{ENV['SYSTEMDRIVE']}/chef/client.log".freeze + DEFAULT_LOG_LOCATION ||= "#{ENV["SYSTEMDRIVE"]}/chef/client.log".freeze def service_init @service_action_mutex = Mutex.new @@ -307,7 +307,7 @@ class Chef begin case config[:config_file] - when /^(http|https):\/\// + when %r{^(http|https)://} Chef::HTTP.new("").streaming_request(config[:config_file]) { |f| apply_config(f.path) } else ::File.open(config[:config_file]) { |f| apply_config(f.path) } diff --git a/lib/chef/application/windows_service_manager.rb b/lib/chef/application/windows_service_manager.rb index 2921c3d964..a43c29d072 100644 --- a/lib/chef/application/windows_service_manager.rb +++ b/lib/chef/application/windows_service_manager.rb @@ -46,7 +46,7 @@ class Chef option :config_file, short: "-c CONFIG", long: "--config CONFIG", - default: "#{ENV['SYSTEMDRIVE']}/chef/client.rb", + default: "#{ENV["SYSTEMDRIVE"]}/chef/client.rb", description: "The configuration file to use for #{Chef::Dist::PRODUCT} runs." option :log_location, @@ -78,10 +78,10 @@ class Chef raise ArgumentError, "Service definition is not provided" if service_options.nil? - required_options = [:service_name, :service_display_name, :service_description, :service_file_path] + required_options = %i{service_name service_display_name service_description service_file_path} required_options.each do |req_option| - if !service_options.key?(req_option) + unless service_options.key?(req_option) raise ArgumentError, "Service definition doesn't contain required option #{req_option}" end end diff --git a/lib/chef/blacklist.rb b/lib/chef/blacklist.rb index b304934a98..abf2139044 100644 --- a/lib/chef/blacklist.rb +++ b/lib/chef/blacklist.rb @@ -68,7 +68,7 @@ class Chef # assumed to contain exact keys (that is, Array elements will not be split # by "/"). def self.to_array(item) - return item if item.kind_of? Array + return item if item.is_a? Array parts = item.split("/") parts.shift if !parts.empty? && parts[0].empty? diff --git a/lib/chef/chef_fs/chef_fs_data_store.rb b/lib/chef/chef_fs/chef_fs_data_store.rb index 50badef794..807d5e0155 100644 --- a/lib/chef/chef_fs/chef_fs_data_store.rb +++ b/lib/chef/chef_fs/chef_fs_data_store.rb @@ -246,7 +246,7 @@ class Chef end else - if !data.is_a?(String) + unless data.is_a?(String) raise "set only works with strings" end @@ -279,6 +279,7 @@ class Chef if !policy_group["policies"] || !policy_group["policies"][path[3]] raise ChefZero::DataStore::DataNotFoundError.new(path, entry) end + # The policy group looks like: # { # "policies": { @@ -361,7 +362,7 @@ class Chef if use_memory_store?(path) @memory_store.set(path, data, *options) else - if !data.is_a?(String) + unless data.is_a?(String) raise "set only works with strings: #{path} = #{data.inspect}" end @@ -401,6 +402,7 @@ class Chef unless group["policies"] && group["policies"].key?(path[3]) raise ChefZero::DataStore::DataNotFoundError.new(path) end + group["policies"].delete(path[3]) group end @@ -413,6 +415,7 @@ class Chef if result.size == members.size raise ChefZero::DataStore::DataNotFoundError.new(path) end + result end @@ -424,6 +427,7 @@ class Chef if result.size == invitations.size raise ChefZero::DataStore::DataNotFoundError.new(path) end + result end @@ -457,11 +461,12 @@ class Chef policies.children.each do |policy| # We want to delete just the ones that == POLICY next unless policy.name.rpartition("-")[0] == path[1] + policy.delete(false) FileSystemCache.instance.delete!(policy.file_path) found_policy = true end - raise ChefZero::DataStore::DataNotFoundError.new(path) if !found_policy + raise ChefZero::DataStore::DataNotFoundError.new(path) unless found_policy end else @@ -502,6 +507,7 @@ class Chef revisions << revision if name == path[1] end raise ChefZero::DataStore::DataNotFoundError.new(path) if revisions.empty? + revisions end @@ -525,7 +531,7 @@ class Chef # /cookbooks/name-version -> /cookbooks/name entry.children.map { |child| split_name_version(child.name)[0] }.uniq else - entry.children.map { |child| child.name } + entry.children.map(&:name) end rescue Chef::ChefFS::FileSystem::NotFoundError # If the cookbooks dir doesn't exist, we have no cookbooks (not 404) @@ -538,12 +544,13 @@ class Chef result = with_entry([ path[0] ]) do |entry| # list /cookbooks/name = filter /cookbooks/name-version down to name entry.children.map { |child| split_name_version(child.name) } - .select { |name, version| name == path[1] } - .map { |name, version| version } + .select { |name, version| name == path[1] } + .map { |name, version| version } end if result.empty? raise ChefZero::DataStore::DataNotFoundError.new(path) end + result else # list /cookbooks/name = <single version> @@ -638,7 +645,7 @@ class Chef # Create the .uploaded-cookbook-version.json cookbooks = chef_fs.child(cookbook_type) - if !cookbooks.exists? + unless cookbooks.exists? cookbooks = chef_fs.create_child(cookbook_type) end # We are calling a cookbooks-specific API, so get multiplexed_dirs out of the way if it is there @@ -846,6 +853,7 @@ class Chef def ensure_dir(entry) return entry if entry.exists? + parent = entry.parent if parent ensure_dir(parent) diff --git a/lib/chef/chef_fs/command_line.rb b/lib/chef/chef_fs/command_line.rb index 56c0c574e8..265b95e22d 100644 --- a/lib/chef/chef_fs/command_line.rb +++ b/lib/chef/chef_fs/command_line.rb @@ -44,6 +44,7 @@ class Chef when :directory_to_file next if diff_filter && diff_filter !~ /T/ + if output_mode == :name_only yield "#{new_path}\n" elsif output_mode == :name_status @@ -54,6 +55,7 @@ class Chef when :file_to_directory next if diff_filter && diff_filter !~ /T/ + if output_mode == :name_only yield "#{new_path}\n" elsif output_mode == :name_status @@ -71,6 +73,7 @@ class Chef new_path += File.extname(old_path) end next if diff_filter && diff_filter !~ /D/ + if output_mode == :name_only yield "#{new_path}\n" elsif output_mode == :name_status @@ -86,6 +89,7 @@ class Chef when :added next if diff_filter && diff_filter !~ /A/ + if output_mode == :name_only yield "#{new_path}\n" elsif output_mode == :name_status @@ -101,6 +105,7 @@ class Chef when :modified next if diff_filter && diff_filter !~ /M/ + if output_mode == :name_only yield "#{new_path}\n" elsif output_mode == :name_status @@ -127,7 +132,7 @@ class Chef end end end - if !found_match + unless found_match ui.error "#{pattern}: No such file or directory on remote or local" if ui error = true end diff --git a/lib/chef/chef_fs/config.rb b/lib/chef/chef_fs/config.rb index c6f6878c00..83e82bfa0c 100644 --- a/lib/chef/chef_fs/config.rb +++ b/lib/chef/chef_fs/config.rb @@ -150,7 +150,7 @@ class Chef hosted_everything or allow repo_mode to default} end # Default to getting *everything* from the server. - if !@chef_config[:repo_mode] + unless @chef_config[:repo_mode] if is_hosted? @chef_config[:repo_mode] = "hosted_everything" else @@ -164,7 +164,7 @@ class Chef attr_reader :cookbook_version def is_hosted? - @chef_config[:chef_server_url] =~ /\/+organizations\/.+/ + @chef_config[:chef_server_url] =~ %r{/+organizations/.+} end def chef_fs @@ -272,6 +272,7 @@ class Chef # cookbooks -> cookbook_path singular_name = INFLECTIONS[object_name] raise "Unknown object name #{object_name}" unless singular_name + variable_name = "#{singular_name}_path" paths = Array(@chef_config[variable_name]).flatten result[object_name] = paths.map { |path| File.expand_path(path) } diff --git a/lib/chef/chef_fs/data_handler/container_data_handler.rb b/lib/chef/chef_fs/data_handler/container_data_handler.rb index 63663ea4ae..25bdf73b04 100644 --- a/lib/chef/chef_fs/data_handler/container_data_handler.rb +++ b/lib/chef/chef_fs/data_handler/container_data_handler.rb @@ -24,7 +24,7 @@ class Chef def verify_integrity(object, entry) base_name = remove_dot_json(entry.name) if object["containername"] != base_name - yield("Name in #{entry.path_for_printing} must be '#{base_name}' (is '#{object['containername']}')") + yield("Name in #{entry.path_for_printing} must be '#{base_name}' (is '#{object["containername"]}')") end end diff --git a/lib/chef/chef_fs/data_handler/data_bag_item_data_handler.rb b/lib/chef/chef_fs/data_handler/data_bag_item_data_handler.rb index 855bb06dd7..bb42b89cfd 100644 --- a/lib/chef/chef_fs/data_handler/data_bag_item_data_handler.rb +++ b/lib/chef/chef_fs/data_handler/data_bag_item_data_handler.rb @@ -54,7 +54,7 @@ class Chef def verify_integrity(object, entry) base_name = remove_dot_json(entry.name) if object["raw_data"]["id"] != base_name - yield("ID in #{entry.path_for_printing} must be '#{base_name}' (is '#{object['raw_data']['id']}')") + yield("ID in #{entry.path_for_printing} must be '#{base_name}' (is '#{object["raw_data"]["id"]}')") elsif entry.parent.name =~ RESERVED_NAMES yield("Data bag name ('#{entry.parent.name}') must not match #{RESERVED_NAMES.inspect}") end diff --git a/lib/chef/chef_fs/data_handler/data_handler_base.rb b/lib/chef/chef_fs/data_handler/data_handler_base.rb index febf0daf4b..d51e54e8ab 100644 --- a/lib/chef/chef_fs/data_handler/data_handler_base.rb +++ b/lib/chef/chef_fs/data_handler/data_handler_base.rb @@ -197,7 +197,7 @@ class Chef def verify_integrity(object, entry) base_name = remove_file_extension(entry.name) if object["name"] != base_name - yield("Name must be '#{base_name}' (is '#{object['name']}')") + yield("Name must be '#{base_name}' (is '#{object["name"]}')") end end diff --git a/lib/chef/chef_fs/data_handler/organization_data_handler.rb b/lib/chef/chef_fs/data_handler/organization_data_handler.rb index ebac7051f7..f107e8920b 100644 --- a/lib/chef/chef_fs/data_handler/organization_data_handler.rb +++ b/lib/chef/chef_fs/data_handler/organization_data_handler.rb @@ -27,7 +27,7 @@ class Chef # @yieldparam [s<string>] error message def verify_integrity(object, entry) if entry.org != object["name"] - yield("Name must be '#{entry.org}' (is '#{object['name']}')") + yield("Name must be '#{entry.org}' (is '#{object["name"]}')") end end end diff --git a/lib/chef/chef_fs/data_handler/policy_data_handler.rb b/lib/chef/chef_fs/data_handler/policy_data_handler.rb index 082dc9ec09..8ae749af73 100644 --- a/lib/chef/chef_fs/data_handler/policy_data_handler.rb +++ b/lib/chef/chef_fs/data_handler/policy_data_handler.rb @@ -35,11 +35,11 @@ class Chef def verify_integrity(object_data, entry) name, revision = name_and_revision(entry.name) if object_data["name"] != name - yield("Object name '#{object_data['name']}' doesn't match entry '#{name}'.") + yield("Object name '#{object_data["name"]}' doesn't match entry '#{name}'.") end if object_data["revision_id"] != revision - yield("Object revision ID '#{object_data['revision_id']}' doesn't match entry '#{revision}'.") + yield("Object revision ID '#{object_data["revision_id"]}' doesn't match entry '#{revision}'.") end end end diff --git a/lib/chef/chef_fs/file_pattern.rb b/lib/chef/chef_fs/file_pattern.rb index 88604e2b8f..f4889fbd86 100644 --- a/lib/chef/chef_fs/file_pattern.rb +++ b/lib/chef/chef_fs/file_pattern.rb @@ -74,6 +74,7 @@ class Chef argument_is_absolute = Chef::ChefFS::PathUtils.is_absolute?(path) return false if is_absolute != argument_is_absolute + path = path[1, path.length - 1] if argument_is_absolute path_parts = Chef::ChefFS::PathUtils.split(path) @@ -81,6 +82,7 @@ class Chef return false if regexp_parts.length <= path_parts.length && !has_double_star # If the path doesn't match up to this point, children won't match either. return false if path_parts.zip(regexp_parts).any? { |part, regexp| !regexp.nil? && !regexp.match(part) } + # Otherwise, it's possible we could match: the path matches to this point, and the pattern is longer than the path. # TODO There is one edge case where the double star comes after some characters like abc**def--we could check whether the next # bit of path starts with abc in that case. @@ -114,6 +116,7 @@ class Chef path = path[1, path.length - 1] if Chef::ChefFS::PathUtils.is_absolute?(path) dirs_in_path = Chef::ChefFS::PathUtils.split(path).length return nil if exact_parts.length <= dirs_in_path + exact_parts[dirs_in_path] end @@ -123,7 +126,8 @@ class Chef # abc/*def.exact_path == 'abc/def' # abc/x\\yz.exact_path == 'abc/xyz' def exact_path - return nil if has_double_star || exact_parts.any? { |part| part.nil? } + return nil if has_double_star || exact_parts.any?(&:nil?) + result = Chef::ChefFS::PathUtils.join(*exact_parts) is_absolute ? Chef::ChefFS::PathUtils.join("", result) : result end @@ -151,6 +155,7 @@ class Chef def match?(path) argument_is_absolute = Chef::ChefFS::PathUtils.is_absolute?(path) return false if is_absolute != argument_is_absolute + path = path[1, path.length - 1] if argument_is_absolute !!regexp.match(path) end @@ -183,7 +188,7 @@ class Chef end def calculate - if !@regexp + unless @regexp @is_absolute = Chef::ChefFS::PathUtils.is_absolute?(@pattern) full_regexp_parts = [] @@ -213,9 +218,10 @@ class Chef if has_double_star_prev raise ArgumentError, ".. overlapping a ** is unsupported" end + full_regexp_parts.pop normalized_parts.pop - if !@has_double_star + unless @has_double_star @regexp_parts.pop @exact_parts.pop end @@ -226,7 +232,7 @@ class Chef # Build up the regexp full_regexp_parts << regexp normalized_parts << part - if !@has_double_star + unless @has_double_star @regexp_parts << Regexp.new("^#{regexp}$") @exact_parts << exact end @@ -259,7 +265,7 @@ class Chef pattern.split(pattern_special_characters).each_with_index do |part, index| # Odd indexes from the split are symbols. Even are normal bits. if index.even? - exact << part if !exact.nil? + exact << part unless exact.nil? regexp << part else case part @@ -277,7 +283,7 @@ class Chef else if part[0, 1] == '\\' && part.length == 2 # backslash escapes are only supported on Unix, and are handled here by leaving the escape on (it means the same thing in a regex) - exact << part[1, 1] if !exact.nil? + exact << part[1, 1] unless exact.nil? if regexp_escape_characters.include?(part[1, 1]) regexp << part else @@ -288,7 +294,7 @@ class Chef exact = nil regexp << part else - exact += part if !exact.nil? + exact += part unless exact.nil? regexp << "\\#{part}" end end diff --git a/lib/chef/chef_fs/file_system.rb b/lib/chef/chef_fs/file_system.rb index ff85a4a1b1..f1e7531de5 100644 --- a/lib/chef/chef_fs/file_system.rb +++ b/lib/chef/chef_fs/file_system.rb @@ -94,6 +94,7 @@ class Chef def self.resolve_path(entry, path) return entry if path.length == 0 return resolve_path(entry.root, path) if path[0, 1] == "/" && entry.root != entry + if path[0, 1] == "/" path = path[1, path.length - 1] end @@ -194,7 +195,7 @@ class Chef # Check the outer regex pattern to see if it matches anything on the # filesystem that isn't on the server Chef::ChefFS::FileSystem.list(b_root, pattern).each do |b| - if !found_paths.include?(b.display_path) + unless found_paths.include?(b.display_path) a = Chef::ChefFS::FileSystem.resolve_path(a_root, b.display_path) yield [ a, b ] end @@ -228,7 +229,7 @@ class Chef # Check b for children that aren't in a b.children.each do |b_child| - if !a_children_names.include?(b_child.bare_name) + unless a_children_names.include?(b_child.bare_name) result << [ a.child(b_child.bare_name), b_child ] end end diff --git a/lib/chef/chef_fs/file_system/base_fs_object.rb b/lib/chef/chef_fs/file_system/base_fs_object.rb index f7516232ac..3d9eb5ae4d 100644 --- a/lib/chef/chef_fs/file_system/base_fs_object.rb +++ b/lib/chef/chef_fs/file_system/base_fs_object.rb @@ -32,6 +32,7 @@ class Chef if name != "" raise ArgumentError, "Name of root object must be empty string: was '#{name}' instead" end + @path = "/" end end @@ -107,13 +108,15 @@ class Chef # Override children to report your *actual* list of children as an array. def children - raise NotFoundError.new(self) if !exists? + raise NotFoundError.new(self) unless exists? + [] end # Expand this entry into a chef object (Chef::Role, ::Node, etc.) def chef_object - raise NotFoundError.new(self) if !exists? + raise NotFoundError.new(self) unless exists? + nil end @@ -124,14 +127,16 @@ class Chef # your entry class, and will be called without actually reading the # file_contents. This is used for knife upload /cookbooks/cookbookname. def create_child(name, file_contents) - raise NotFoundError.new(self) if !exists? + raise NotFoundError.new(self) unless exists? + raise OperationNotAllowedError.new(:create_child, self) end # Delete this item, possibly recursively. Entries MUST NOT delete a # directory unless recurse is true. def delete(recurse) - raise NotFoundError.new(self) if !exists? + raise NotFoundError.new(self) unless exists? + raise OperationNotAllowedError.new(:delete, self) end @@ -166,13 +171,15 @@ class Chef # Read the contents of this file entry. def read - raise NotFoundError.new(self) if !exists? + raise NotFoundError.new(self) unless exists? + raise OperationNotAllowedError.new(:read, self) end # Write the contents of this file entry. def write(file_contents) - raise NotFoundError.new(self) if !exists? + raise NotFoundError.new(self) unless exists? + raise OperationNotAllowedError.new(:write, self) end diff --git a/lib/chef/chef_fs/file_system/chef_server/chef_server_root_dir.rb b/lib/chef/chef_fs/file_system/chef_server/chef_server_root_dir.rb index d1d92f508e..20a6895116 100644 --- a/lib/chef/chef_fs/file_system/chef_server/chef_server_root_dir.rb +++ b/lib/chef/chef_fs/file_system/chef_server/chef_server_root_dir.rb @@ -186,7 +186,7 @@ class Chef RestListDir.new("users", self, nil, Chef::ChefFS::DataHandler::UserDataHandler.new), ] end - result.sort_by { |child| child.name } + result.sort_by(&:name) end end end diff --git a/lib/chef/chef_fs/file_system/chef_server/cookbook_artifacts_dir.rb b/lib/chef/chef_fs/file_system/chef_server/cookbook_artifacts_dir.rb index 6c1610876c..273b45a646 100644 --- a/lib/chef/chef_fs/file_system/chef_server/cookbook_artifacts_dir.rb +++ b/lib/chef/chef_fs/file_system/chef_server/cookbook_artifacts_dir.rb @@ -44,7 +44,7 @@ class Chef result = [] root.get_json("#{api_path}/?num_versions=all").each_pair do |cookbook_name, cookbooks| cookbooks["versions"].each do |cookbook_version| - result << CookbookArtifactDir.new("#{cookbook_name}-#{cookbook_version['identifier']}", self) + result << CookbookArtifactDir.new("#{cookbook_name}-#{cookbook_version["identifier"]}", self) end end result.sort_by(&:name) diff --git a/lib/chef/chef_fs/file_system/chef_server/cookbook_dir.rb b/lib/chef/chef_fs/file_system/chef_server/cookbook_dir.rb index b8e1b7b43c..15729b7206 100644 --- a/lib/chef/chef_fs/file_system/chef_server/cookbook_dir.rb +++ b/lib/chef/chef_fs/file_system/chef_server/cookbook_dir.rb @@ -69,6 +69,7 @@ class Chef def can_have_child?(name, is_dir) return name != "root_files" if is_dir + true end @@ -84,7 +85,7 @@ class Chef parts[0, parts.length - 1].each do |part| old_container = container container = old_container.children.find { |child| part == child.name } - if !container + unless container container = CookbookSubdir.new(part, old_container, false, true) old_container.add_child(container) end @@ -93,7 +94,7 @@ class Chef container.add_child(CookbookFile.new(parts[parts.length - 1], container, file)) end end - @children = @children.sort_by { |c| c.name } + @children = @children.sort_by(&:name) end @children end @@ -116,7 +117,8 @@ class Chef end end else - raise NotFoundError.new(self) if !exists? + raise NotFoundError.new(self) unless exists? + raise MustDeleteRecursivelyError.new(self, "#{path_for_printing} must be deleted recursively") end end @@ -131,12 +133,13 @@ class Chef end def compare_to(other) - if !other.dir? + unless other.dir? return [ !exists?, nil, nil ] end + are_same = true Chef::ChefFS::CommandLine.diff_entries(self, other, nil, :name_only).each do |type, old_entry, new_entry| - if [ :directory_to_file, :file_to_directory, :deleted, :added, :modified ].include?(type) + if %i{directory_to_file file_to_directory deleted added modified}.include?(type) are_same = false end end diff --git a/lib/chef/chef_fs/file_system/chef_server/cookbook_file.rb b/lib/chef/chef_fs/file_system/chef_server/cookbook_file.rb index 8bdaf75a30..2dae242223 100644 --- a/lib/chef/chef_fs/file_system/chef_server/cookbook_file.rb +++ b/lib/chef/chef_fs/file_system/chef_server/cookbook_file.rb @@ -38,7 +38,7 @@ class Chef def read tmpfile = rest.streaming_request(file[:url]) - File.open(tmpfile, "rb") { |f| f.read } + File.open(tmpfile, "rb", &:read) rescue Timeout::Error => e raise Chef::ChefFS::FileSystem::OperationFailedError.new(:read, self, e, "Timeout reading #{file[:url]}: #{e}") rescue Net::HTTPClientException => e diff --git a/lib/chef/chef_fs/file_system/chef_server/cookbook_subdir.rb b/lib/chef/chef_fs/file_system/chef_server/cookbook_subdir.rb index d1b415baf1..b21e13b256 100644 --- a/lib/chef/chef_fs/file_system/chef_server/cookbook_subdir.rb +++ b/lib/chef/chef_fs/file_system/chef_server/cookbook_subdir.rb @@ -39,7 +39,7 @@ class Chef def can_have_child?(name, is_dir) if is_dir - return false if !@recursive + return false unless @recursive else return false if @ruby_only && name !~ /\.rb$/ end diff --git a/lib/chef/chef_fs/file_system/chef_server/cookbooks_dir.rb b/lib/chef/chef_fs/file_system/chef_server/cookbooks_dir.rb index dfacc7f5ec..21b7cdaff8 100644 --- a/lib/chef/chef_fs/file_system/chef_server/cookbooks_dir.rb +++ b/lib/chef/chef_fs/file_system/chef_server/cookbooks_dir.rb @@ -88,7 +88,7 @@ class Chef # Work around the fact that CookbookUploader doesn't understand chef_repo_path (yet) def with_actual_cookbooks_dir(actual_cookbook_path) old_cookbook_path = Chef::Config.cookbook_path - Chef::Config.cookbook_path = actual_cookbook_path if !Chef::Config.cookbook_path + Chef::Config.cookbook_path = actual_cookbook_path unless Chef::Config.cookbook_path yield ensure diff --git a/lib/chef/chef_fs/file_system/chef_server/data_bag_dir.rb b/lib/chef/chef_fs/file_system/chef_server/data_bag_dir.rb index fb8a537596..8970ad9b3e 100644 --- a/lib/chef/chef_fs/file_system/chef_server/data_bag_dir.rb +++ b/lib/chef/chef_fs/file_system/chef_server/data_bag_dir.rb @@ -48,8 +48,9 @@ class Chef end def delete(recurse) - if !recurse - raise NotFoundError.new(self) if !exists? + unless recurse + raise NotFoundError.new(self) unless exists? + raise MustDeleteRecursivelyError.new(self, "#{path_for_printing} must be deleted recursively") end begin diff --git a/lib/chef/chef_fs/file_system/chef_server/environments_dir.rb b/lib/chef/chef_fs/file_system/chef_server/environments_dir.rb index 09ab30c799..5425f8a2a5 100644 --- a/lib/chef/chef_fs/file_system/chef_server/environments_dir.rb +++ b/lib/chef/chef_fs/file_system/chef_server/environments_dir.rb @@ -40,12 +40,14 @@ class Chef end def delete(recurse) - raise NotFoundError.new(self) if !exists? + raise NotFoundError.new(self) unless exists? + raise DefaultEnvironmentCannotBeModifiedError.new(:delete, self) end def write(file_contents) - raise NotFoundError.new(self) if !exists? + raise NotFoundError.new(self) unless exists? + raise DefaultEnvironmentCannotBeModifiedError.new(:write, self) end end diff --git a/lib/chef/chef_fs/file_system/chef_server/policies_dir.rb b/lib/chef/chef_fs/file_system/chef_server/policies_dir.rb index d0674075c6..073bea7a95 100644 --- a/lib/chef/chef_fs/file_system/chef_server/policies_dir.rb +++ b/lib/chef/chef_fs/file_system/chef_server/policies_dir.rb @@ -95,6 +95,7 @@ class Chef if e.response.code == "404" raise Chef::ChefFS::FileSystem::NotFoundError.new(self, $!) end + raise Chef::ChefFS::FileSystem::OperationFailedError.new(:children, self, e, "HTTP error retrieving children: #{e}") end # Anything else is unexpected (OperationFailedError) diff --git a/lib/chef/chef_fs/file_system/chef_server/rest_list_dir.rb b/lib/chef/chef_fs/file_system/chef_server/rest_list_dir.rb index 7c5e01bf7e..d2c5bdc9b7 100644 --- a/lib/chef/chef_fs/file_system/chef_server/rest_list_dir.rb +++ b/lib/chef/chef_fs/file_system/chef_server/rest_list_dir.rb @@ -94,6 +94,7 @@ class Chef if e.response.code == "404" raise Chef::ChefFS::FileSystem::NotFoundError.new(self, $!) end + raise Chef::ChefFS::FileSystem::OperationFailedError.new(:children, self, e, "HTTP error retrieving children: #{e}") end else diff --git a/lib/chef/chef_fs/file_system/chef_server/versioned_cookbooks_dir.rb b/lib/chef/chef_fs/file_system/chef_server/versioned_cookbooks_dir.rb index 5973e01e41..0fd1e4acdf 100644 --- a/lib/chef/chef_fs/file_system/chef_server/versioned_cookbooks_dir.rb +++ b/lib/chef/chef_fs/file_system/chef_server/versioned_cookbooks_dir.rb @@ -50,7 +50,7 @@ class Chef result = [] root.get_json("#{api_path}/?num_versions=all").each_pair do |cookbook_name, cookbooks| cookbooks["versions"].each do |cookbook_version| - result << VersionedCookbookDir.new("#{cookbook_name}-#{cookbook_version['version']}", self) + result << VersionedCookbookDir.new("#{cookbook_name}-#{cookbook_version["version"]}", self) end end result.sort_by(&:name) diff --git a/lib/chef/chef_fs/file_system/memory/memory_dir.rb b/lib/chef/chef_fs/file_system/memory/memory_dir.rb index fdef10ff56..e52a4b7c0f 100644 --- a/lib/chef/chef_fs/file_system/memory/memory_dir.rb +++ b/lib/chef/chef_fs/file_system/memory/memory_dir.rb @@ -38,7 +38,7 @@ class Chef dir = self path_parts.each do |path_part| subdir = dir.child(path_part) - if !subdir.exists? + unless subdir.exists? subdir = MemoryDir.new(path_part, dir) dir.add_child(subdir) end diff --git a/lib/chef/chef_fs/file_system/repository/acl.rb b/lib/chef/chef_fs/file_system/repository/acl.rb index 389c1fd38b..c5d763170b 100644 --- a/lib/chef/chef_fs/file_system/repository/acl.rb +++ b/lib/chef/chef_fs/file_system/repository/acl.rb @@ -32,7 +32,7 @@ class Chef end def bare_name - if name == "organization" && parent.kind_of?(AclDir) + if name == "organization" && parent.is_a?(AclDir) "organization.json" else name diff --git a/lib/chef/chef_fs/file_system/repository/base_file.rb b/lib/chef/chef_fs/file_system/repository/base_file.rb index ade5fc2039..daefc3a8b1 100644 --- a/lib/chef/chef_fs/file_system/repository/base_file.rb +++ b/lib/chef/chef_fs/file_system/repository/base_file.rb @@ -122,7 +122,7 @@ class Chef if is_ruby_file? data_handler.from_ruby(file_path).to_json else - File.open(file_path, "rb") { |f| f.read } + File.open(file_path, "rb", &:read) end rescue Errno::ENOENT raise Chef::ChefFS::FileSystem::NotFoundError.new(self, $!) @@ -132,6 +132,7 @@ class Chef if is_ruby_file? raise Chef::ChefFS::FileSystem::RubyFileError.new(:write, self) end + if content && write_pretty_json && is_json_file? content = minimize(content, self) end diff --git a/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_cookbook_dir.rb b/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_cookbook_dir.rb index 5098d55727..74170cc7a9 100644 --- a/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_cookbook_dir.rb +++ b/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_cookbook_dir.rb @@ -34,6 +34,7 @@ class Chef def fs_entry_valid? return false unless File.directory?(file_path) && name_valid? + if can_upload? true else @@ -54,6 +55,7 @@ class Chef if exists? raise Chef::ChefFS::FileSystem::AlreadyExistsError.new(:create_child, self) end + begin Dir.mkdir(file_path) rescue Errno::EEXIST @@ -68,7 +70,7 @@ class Chef # Write out .uploaded-cookbook-version.json # cookbook_file_path = File.join(file_path, cookbook_name) <- this should be the same as self.file_path - if !File.exists?(file_path) + unless File.exists?(file_path) FileUtils.mkdir_p(file_path) end uploaded_cookbook_version_path = File.join(file_path, Chef::Cookbook::CookbookVersionLoader::UPLOADED_COOKBOOK_VERSION_FILE) @@ -81,7 +83,7 @@ class Chef def chef_object cb = cookbook_version - if !cb + unless cb Chef::Log.error("Cookbook #{file_path} empty.") raise "Cookbook #{file_path} empty." end @@ -103,6 +105,7 @@ class Chef elsif name == Chef::Cookbook::CookbookVersionLoader::UPLOADED_COOKBOOK_VERSION_FILE return false end + super(name, is_dir) end @@ -110,6 +113,7 @@ class Chef def self.canonical_cookbook_name(entry_name) name_match = Chef::ChefFS::FileSystem::ChefServer::VersionedCookbookDir::VALID_VERSIONED_COOKBOOK_NAME.match(entry_name) return nil if name_match.nil? + name_match[1] end diff --git a/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_cookbook_entry.rb b/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_cookbook_entry.rb index a6cae64c6d..1708428372 100644 --- a/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_cookbook_entry.rb +++ b/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_cookbook_entry.rb @@ -53,8 +53,8 @@ class Chef def children entries = Dir.entries(file_path).sort - .map { |child_name| make_child_entry(child_name) } - .select { |child| child && can_have_child?(child.name, child.dir?) } + .map { |child_name| make_child_entry(child_name) } + .select { |child| child && can_have_child?(child.name, child.dir?) } entries.select { |entry| !(entry.dir? && entry.children.size == 0 ) } rescue Errno::ENOENT raise Chef::ChefFS::FileSystem::NotFoundError.new(self, $!) @@ -101,6 +101,7 @@ class Chef if child.exists? raise Chef::ChefFS::FileSystem::AlreadyExistsError.new(:create_child, child) end + if file_contents child.write(file_contents) else @@ -121,9 +122,10 @@ class Chef FileSystemCache.instance.delete!(file_path) begin if dir? - if !recurse + unless recurse raise MustDeleteRecursivelyError.new(self, $!) end + FileUtils.rm_r(file_path) else File.delete(file_path) @@ -138,7 +140,7 @@ class Chef end def read - File.open(file_path, "rb") { |f| f.read } + File.open(file_path, "rb", &:read) rescue Errno::ENOENT raise Chef::ChefFS::FileSystem::NotFoundError.new(self, $!) end diff --git a/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_root_dir.rb b/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_root_dir.rb index 30ccf8c736..de1f071fb3 100644 --- a/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_root_dir.rb +++ b/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_root_dir.rb @@ -90,7 +90,7 @@ class Chef @children ||= begin result = child_paths.keys.sort.map { |name| make_child_entry(name) } result += CHILDREN.map { |name| make_child_entry(name) } - result.select { |c| c && c.exists? }.sort_by { |c| c.name } + result.select { |c| c && c.exists? }.sort_by(&:name) end end @@ -140,7 +140,7 @@ class Chef # Used to print out a human-readable file system description def fs_description repo_paths = root_paths || [ File.dirname(child_paths["cookbooks"][0]) ] - result = "repository at #{repo_paths.join(', ')}\n" + result = "repository at #{repo_paths.join(", ")}\n" if versioned_cookbooks result << " Multiple versions per cookbook\n" else @@ -148,7 +148,7 @@ class Chef end child_paths.each_pair do |name, paths| if paths.any? { |path| !repo_paths.include?(File.dirname(path)) } - result << " #{name} at #{paths.join(', ')}\n" + result << " #{name} at #{paths.join(", ")}\n" end end result @@ -179,7 +179,8 @@ class Chef # def make_child_entry(name) if CHILDREN.include?(name) - return nil if !root_dir + return nil unless root_dir + return root_dir.child(name) end @@ -187,6 +188,7 @@ class Chef if paths.size == 0 return NonexistentFSObject.new(name, self) end + case name when "acls" dirs = paths.map { |path| AclsDir.new(name, self, path) } diff --git a/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_versioned_cookbook_dir.rb b/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_versioned_cookbook_dir.rb index 4fb214cff8..442fa879ad 100644 --- a/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_versioned_cookbook_dir.rb +++ b/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_versioned_cookbook_dir.rb @@ -30,6 +30,7 @@ class Chef # want to spend a lot of time adding code to the main Chef libraries canonical_name = canonical_cookbook_name(File.basename(file_path)) raise "When versioned_cookbooks mode is on, cookbook #{file_path} must match format <cookbook_name>-x.y.z" unless canonical_name + # KLUDGE: We shouldn't have to use instance_variable_set loader.instance_variable_set(:@cookbook_name, canonical_name) loader.load_cookbooks diff --git a/lib/chef/chef_fs/file_system/repository/directory.rb b/lib/chef/chef_fs/file_system/repository/directory.rb index f428e939d3..37a7081173 100644 --- a/lib/chef/chef_fs/file_system/repository/directory.rb +++ b/lib/chef/chef_fs/file_system/repository/directory.rb @@ -71,6 +71,7 @@ class Chef def children return FileSystemCache.instance.children(file_path) if FileSystemCache.instance.exist?(file_path) + children = dir_ls.sort .map { |child_name| make_child_entry(child_name) } .select { |new_child| new_child.fs_entry_valid? && can_have_child?(new_child.name, new_child.dir?) } @@ -84,6 +85,7 @@ class Chef if child.exists? raise Chef::ChefFS::FileSystem::AlreadyExistsError.new(:create_child, child) end + FileSystemCache.instance.delete!(child.file_path) if file_contents child.write(file_contents) @@ -122,6 +124,7 @@ class Chef if exists? raise Chef::ChefFS::FileSystem::AlreadyExistsError.new(:create_child, self) end + begin FileSystemCache.instance.delete!(file_path) Dir.mkdir(file_path) @@ -136,9 +139,10 @@ class Chef def delete(recurse) if exists? - if !recurse + unless recurse raise MustDeleteRecursivelyError.new(self, $!) end + FileUtils.rm_r(file_path) FileSystemCache.instance.delete!(file_path) else diff --git a/lib/chef/chef_fs/file_system/repository/file_system_entry.rb b/lib/chef/chef_fs/file_system/repository/file_system_entry.rb index 33b4de8014..7c2d3e1522 100644 --- a/lib/chef/chef_fs/file_system/repository/file_system_entry.rb +++ b/lib/chef/chef_fs/file_system/repository/file_system_entry.rb @@ -92,6 +92,7 @@ class Chef if child.exists? raise Chef::ChefFS::FileSystem::AlreadyExistsError.new(:create_child, child) end + if file_contents child.write(file_contents) else @@ -108,9 +109,10 @@ class Chef def delete(recurse) if dir? - if !recurse + unless recurse raise MustDeleteRecursivelyError.new(self, $!) end + FileUtils.rm_r(file_path) else File.delete(file_path) @@ -124,7 +126,7 @@ class Chef end def read - File.open(file_path, "rb") { |f| f.read } + File.open(file_path, "rb", &:read) rescue Errno::ENOENT raise Chef::ChefFS::FileSystem::NotFoundError.new(self, $!) end diff --git a/lib/chef/chef_fs/file_system_cache.rb b/lib/chef/chef_fs/file_system_cache.rb index e36dbbce7c..0024a49098 100644 --- a/lib/chef/chef_fs/file_system_cache.rb +++ b/lib/chef/chef_fs/file_system_cache.rb @@ -73,6 +73,7 @@ class Chef def _get_parent(path) parts = ChefFS::PathUtils.split(path) return nil if parts.nil? || parts.length < 2 + ChefFS::PathUtils.join(*parts[0..-2]) end end diff --git a/lib/chef/chef_fs/parallelizer/parallel_enumerable.rb b/lib/chef/chef_fs/parallelizer/parallel_enumerable.rb index 2291220ef8..1780b56239 100644 --- a/lib/chef/chef_fs/parallelizer/parallel_enumerable.rb +++ b/lib/chef/chef_fs/parallelizer/parallel_enumerable.rb @@ -147,6 +147,7 @@ class Chef if @each_running raise "each() called on parallel enumerable twice simultaneously! Bad mojo" end + @each_running = true begin # Grab all the inputs, yielding any responses during enumeration @@ -197,7 +198,7 @@ class Chef # If we exited early, perhaps due to any? finding a result, we want # to make sure and throw away any extra results (gracefully) so that # the next enumerator can start over. - if !finished? + unless finished? stop end raise diff --git a/lib/chef/chef_fs/path_utils.rb b/lib/chef/chef_fs/path_utils.rb index fe6428a5b1..c490f50c17 100644 --- a/lib/chef/chef_fs/path_utils.rb +++ b/lib/chef/chef_fs/path_utils.rb @@ -42,6 +42,7 @@ class Chef def self.join(*parts) return "" if parts.length == 0 + # Determine if it started with a slash absolute = parts[0].length == 0 || parts[0].length > 0 && parts[0] =~ /^#{regexp_path_separator}/ # Remove leading and trailing slashes from each part so that the join will work (and the slash at the end will go away) @@ -87,6 +88,7 @@ class Chef # This can occur if a path such as "C:" is given. Ruby gives the parent as "C:." # for reasons only it knows. raise ArgumentError "Invalid path segment #{path}" if parent_path.length > path.length + begin path = File.realpath(path) break @@ -113,6 +115,7 @@ class Chef def self.descendant_path(path, ancestor) candidate_fragment = path[0, ancestor.length] return nil unless PathUtils.os_path_eq?(candidate_fragment, ancestor) + if ancestor.length == path.length "" elsif path[ancestor.length, 1] =~ /#{PathUtils.regexp_path_separator}/ diff --git a/lib/chef/client.rb b/lib/chef/client.rb index 51a93440e9..06370f5d07 100644 --- a/lib/chef/client.rb +++ b/lib/chef/client.rb @@ -881,12 +881,14 @@ class Chef def start_profiling return unless Chef::Config[:profile_ruby] + profiling_prereqs! RubyProf.start end def end_profiling return unless Chef::Config[:profile_ruby] + profiling_prereqs! path = Chef::FileCache.create_cache_path("graph_profile.out", false) File.open(path, "w+") do |file| @@ -900,7 +902,7 @@ class Chef end def is_last_element?(index, object) - object.kind_of?(Array) ? index == object.size - 1 : true + object.is_a?(Array) ? index == object.size - 1 : true end def assert_cookbook_path_not_empty(run_context) @@ -909,7 +911,7 @@ class Chef # Chef::Config[:cookbook_path] can be a string or an array # if it's an array, go through it and check each one, raise error at the last one if no files are found cookbook_paths = Array(Chef::Config[:cookbook_path]) - logger.trace "Loading from cookbook_path: #{cookbook_paths.map { |path| File.expand_path(path) }.join(', ')}" + logger.trace "Loading from cookbook_path: #{cookbook_paths.map { |path| File.expand_path(path) }.join(", ")}" if cookbook_paths.all? { |path| empty_directory?(path) } msg = "None of the cookbook paths set in Chef::Config[:cookbook_path], #{cookbook_paths.inspect}, contain any cookbooks" logger.fatal(msg) diff --git a/lib/chef/config.rb b/lib/chef/config.rb index 759818261e..135ae622f7 100644 --- a/lib/chef/config.rb +++ b/lib/chef/config.rb @@ -74,7 +74,7 @@ class Chef # by redefining the config_attr_writer to not warn for these options. # # REMOVEME once the warnings for these configurables are removed from Ohai. - [ :log_level, :log_location ].each do |option| + %i{log_level log_location}.each do |option| config_attr_writer option do |value| value end diff --git a/lib/chef/cookbook/cookbook_version_loader.rb b/lib/chef/cookbook/cookbook_version_loader.rb index ad7ee3b1c2..767196ea0e 100644 --- a/lib/chef/cookbook/cookbook_version_loader.rb +++ b/lib/chef/cookbook/cookbook_version_loader.rb @@ -52,7 +52,7 @@ class Chef @inferred_cookbook_name = File.basename( path ) @chefignore = chefignore @metadata = nil - @relative_path = /#{Regexp.escape(cookbook_path)}\/(.+)$/ + @relative_path = %r{#{Regexp.escape(cookbook_path)}/(.+)$} @metadata_loaded = false @cookbook_settings = { all_files: {}, @@ -70,6 +70,7 @@ class Chef if empty? raise Exceptions::CookbookNotFoundInRepo, "The directory #{cookbook_path} does not contain a cookbook" end + file_paths_map end @@ -152,6 +153,7 @@ class Chef def metadata_filenames return @metadata_filenames unless @metadata_filenames.empty? + if File.exists?(File.join(cookbook_path, UPLOADED_COOKBOOK_VERSION_FILE)) @uploaded_cookbook_version_file = File.join(cookbook_path, UPLOADED_COOKBOOK_VERSION_FILE) end @@ -171,18 +173,19 @@ class Chef def raise_metadata_error! raise metadata_error unless metadata_error.nil? + # Metadata won't be valid if the cookbook is empty. If the cookbook is # actually empty, a metadata error here would be misleading, so don't # raise it (if called by #load!, a different error is raised). if !empty? && !metadata.valid? - message = "Cookbook loaded at path [#{cookbook_path}] has invalid metadata: #{metadata.errors.join('; ')}" + message = "Cookbook loaded at path [#{cookbook_path}] has invalid metadata: #{metadata.errors.join("; ")}" raise Exceptions::MetadataNotValid, message end false end def empty? - cookbook_settings.values.all? { |files_hash| files_hash.empty? } && metadata_filenames.size == 0 + cookbook_settings.values.all?(&:empty?) && metadata_filenames.size == 0 end def chefignore diff --git a/lib/chef/cookbook/file_system_file_vendor.rb b/lib/chef/cookbook/file_system_file_vendor.rb index 2faeb31815..b89d10cd48 100644 --- a/lib/chef/cookbook/file_system_file_vendor.rb +++ b/lib/chef/cookbook/file_system_file_vendor.rb @@ -49,6 +49,7 @@ class Chef def get_filename(filename) location = File.join(cookbooks[cookbook_name].root_dir, filename) if cookbooks.key?(cookbook_name) raise "File #{filename} does not exist for cookbook #{cookbook_name}" unless location && File.exist?(location) + location end diff --git a/lib/chef/cookbook/file_vendor.rb b/lib/chef/cookbook/file_vendor.rb index 60948cc3a5..82eb4e03f6 100644 --- a/lib/chef/cookbook/file_vendor.rb +++ b/lib/chef/cookbook/file_vendor.rb @@ -54,6 +54,7 @@ class Chef if @vendor_class.nil? raise "Must configure FileVendor to use a specific implementation before creating an instance" end + @vendor_class.new(manifest, @initialization_options) end diff --git a/lib/chef/cookbook/gem_installer.rb b/lib/chef/cookbook/gem_installer.rb index bd1d0fb93a..eab4b47241 100644 --- a/lib/chef/cookbook/gem_installer.rb +++ b/lib/chef/cookbook/gem_installer.rb @@ -43,6 +43,7 @@ class Chef args << {} unless args.last.is_a?(Hash) args.last.merge!(cookbook_gems[args.first].pop) do |key, v1, v2| raise Chef::Exceptions::GemRequirementConflict.new(args.first, key, v1, v2) if v1 != v2 + v2 end end diff --git a/lib/chef/cookbook/manifest_v0.rb b/lib/chef/cookbook/manifest_v0.rb index e285b29fd2..a4c60e5827 100644 --- a/lib/chef/cookbook/manifest_v0.rb +++ b/lib/chef/cookbook/manifest_v0.rb @@ -32,6 +32,7 @@ class Chef response = Mash.new(hash) response[:all_files] = COOKBOOK_SEGMENTS.inject([]) do |memo, segment| next memo if hash[segment].nil? || hash[segment].empty? + hash[segment].each do |file| file["name"] = "#{segment}/#{file["name"]}" memo << file diff --git a/lib/chef/cookbook/metadata.rb b/lib/chef/cookbook/metadata.rb index 6d82ae4e30..d5821a799e 100644 --- a/lib/chef/cookbook/metadata.rb +++ b/lib/chef/cookbook/metadata.rb @@ -53,10 +53,10 @@ class Chef OHAI_VERSIONS = "ohai_versions".freeze GEMS = "gems".freeze - COMPARISON_FIELDS = [ :name, :description, :long_description, :maintainer, - :maintainer_email, :license, :platforms, :dependencies, - :providing, :recipes, :version, :source_url, :issues_url, - :privacy, :chef_versions, :ohai_versions, :gems ].freeze + COMPARISON_FIELDS = %i{name description long_description maintainer + maintainer_email license platforms dependencies + providing recipes version source_url issues_url + privacy chef_versions ohai_versions gems}.freeze VERSION_CONSTRAINTS = { depends: DEPENDENCIES, provides: PROVIDING, @@ -286,6 +286,7 @@ class Chef constraint = validate_version_constraint(:depends, cookbook, version) @dependencies[cookbook] = constraint.to_s end + @dependencies[cookbook] end @@ -444,7 +445,7 @@ class Chef end def self.from_hash(o) - cm = new() + cm = new cm.from_hash(o) cm end @@ -477,7 +478,7 @@ class Chef def self.validate_json(json_str) o = Chef::JSONCompat.from_json(json_str) - metadata = new() + metadata = new VERSION_CONSTRAINTS.each do |dependency_type, hash_key| if dependency_group = o[hash_key] dependency_group.each do |cb_name, constraints| @@ -583,6 +584,7 @@ class Chef def gem_dep_matches?(what, version, *deps) # always match if we have no chef_version at all return true unless deps.length > 0 + # match if we match any of the chef_version lines deps.any? { |dep| dep.match?(what, version) } end @@ -604,7 +606,7 @@ class Chef specify more than one version constraint for a particular cookbook. Consult https://docs.chef.io/config_rb_metadata.html for the updated syntax. - Called by: #{caller_name} '#{dep_name}', #{version_constraints.map { |vc| vc.inspect }.join(", ")} + Called by: #{caller_name} '#{dep_name}', #{version_constraints.map(&:inspect).join(", ")} Called from: #{caller[0...5].map { |line| " " + line }.join("\n")} OBSOLETED @@ -637,7 +639,7 @@ class Chef # === Parameters # arry<Array>:: An array to be validated def validate_string_array(arry) - if arry.kind_of?(Array) + if arry.is_a?(Array) arry.each do |choice| validate( { choice: choice }, { choice: { kind_of: String } } ) end @@ -650,7 +652,7 @@ class Chef # === Parameters # opts<Hash>:: The options hash def validate_choice_array(opts) - if opts[:choice].kind_of?(Array) + if opts[:choice].is_a?(Array) case opts[:type] when "string" validator = [ String ] diff --git a/lib/chef/cookbook/remote_file_vendor.rb b/lib/chef/cookbook/remote_file_vendor.rb index 9ccb2ff46c..dc308b4bf5 100644 --- a/lib/chef/cookbook/remote_file_vendor.rb +++ b/lib/chef/cookbook/remote_file_vendor.rb @@ -37,13 +37,14 @@ class Chef # Chef::Config.cookbook_path file hierarchy for the requested # file. def get_filename(filename) - if filename =~ /([^\/]+)\/(.+)$/ + if filename =~ %r{([^/]+)/(.+)$} segment = $1 else raise "get_filename: Cannot determine segment/filename for incoming filename #{filename}" end raise "No such segment #{segment} in cookbook #{@cookbook_name}" unless @manifest.files_for(segment) + found_manifest_record = @manifest.files_for(segment).find { |manifest_record| manifest_record[:path] == filename } raise "No such file #{filename} in #{@cookbook_name}" unless found_manifest_record @@ -68,7 +69,7 @@ class Chef Chef::FileCache.move_to(raw_file.path, cache_filename) else Chef::Log.trace("Not fetching #{cache_filename}, as the cache is up to date.") - Chef::Log.trace("Current checksum: #{current_checksum}; manifest checksum: #{found_manifest_record['checksum']})") + Chef::Log.trace("Current checksum: #{current_checksum}; manifest checksum: #{found_manifest_record["checksum"]})") end full_path_cache_filename = Chef::FileCache.load(cache_filename, false) diff --git a/lib/chef/cookbook/synchronizer.rb b/lib/chef/cookbook/synchronizer.rb index 8c87ababb6..b6bcd2c150 100644 --- a/lib/chef/cookbook/synchronizer.rb +++ b/lib/chef/cookbook/synchronizer.rb @@ -138,7 +138,7 @@ class Chef end def files_by_cookbook - files.group_by { |file| file.cookbook } + files.group_by(&:cookbook) end def files_remaining_by_cookbook @@ -163,7 +163,7 @@ class Chef # === Returns # true:: Always returns true def sync_cookbooks - Chef::Log.info("Loading cookbooks [#{cookbooks.map { |ckbk| ckbk.name + '@' + ckbk.version }.join(', ')}]") + Chef::Log.info("Loading cookbooks [#{cookbooks.map { |ckbk| ckbk.name + "@" + ckbk.version }.join(", ")}]") Chef::Log.trace("Cookbooks detail: #{cookbooks.inspect}") clear_obsoleted_cookbooks @@ -209,7 +209,7 @@ class Chef # (if we have an override run_list we may not want to do this) def remove_old_cookbooks cache.find(File.join(%w{cookbooks ** {*,.*}})).each do |cache_file| - cache_file =~ /^cookbooks\/([^\/]+)\// + cache_file =~ %r{^cookbooks/([^/]+)/} unless have_cookbook?($1) Chef::Log.info("Removing #{cache_file} from the cache; its cookbook is no longer needed on this client.") cache.delete(cache_file) @@ -221,8 +221,9 @@ class Chef # remove deleted files in cookbooks that are being used on the node def remove_deleted_files cache.find(File.join(%w{cookbooks ** {*,.*}})).each do |cache_file| - md = cache_file.match(/^cookbooks\/([^\/]+)\/([^\/]+)\/(.*)/) + md = cache_file.match(%r{^cookbooks/([^/]+)/([^/]+)/(.*)}) next unless md + ( cookbook_name, segment, file ) = md[1..3] if have_cookbook?(cookbook_name) manifest_segment = cookbook_segment(cookbook_name, segment) @@ -297,6 +298,7 @@ class Chef def cached_copy_up_to_date?(local_path, expected_checksum) return true if Chef::Config[:skip_cookbook_sync] + if cache.key?(local_path) current_checksum = CookbookVersion.checksum_cookbook_file(cache.load(local_path, false)) expected_checksum == current_checksum diff --git a/lib/chef/cookbook/syntax_check.rb b/lib/chef/cookbook/syntax_check.rb index 89061d4f5f..6c1f710f6d 100644 --- a/lib/chef/cookbook/syntax_check.rb +++ b/lib/chef/cookbook/syntax_check.rb @@ -62,6 +62,7 @@ class Chef def ensure_cache_path_created return true if @cache_path_created + FileUtils.mkdir_p(cache_path) @cache_path_created = true end @@ -86,6 +87,7 @@ class Chef unless cookbook_path raise ArgumentError, "Cannot find cookbook #{cookbook_name} unless Chef::Config.cookbook_path is set or an explicit cookbook path is given" end + new(File.join(cookbook_path, cookbook_name.to_s)) end @@ -157,6 +159,7 @@ class Chef def validate_ruby_files untested_ruby_files.each do |ruby_file| return false unless validate_ruby_file(ruby_file) + validated(ruby_file) end end @@ -164,6 +167,7 @@ class Chef def validate_templates untested_template_files.each do |template| return false unless validate_template(template) + validated(template) end end diff --git a/lib/chef/cookbook_loader.rb b/lib/chef/cookbook_loader.rb index ada19baed7..b27d751d64 100644 --- a/lib/chef/cookbook_loader.rb +++ b/lib/chef/cookbook_loader.rb @@ -176,6 +176,7 @@ class Chef if mash.key?(cookbook_name) raise Chef::Exceptions::CookbookMergingError, "Cookbook merging is no longer supported, the cookbook named #{cookbook_name} can only appear once in the cookbook_path" end + mash[cookbook_name] = loader end mash diff --git a/lib/chef/cookbook_manifest.rb b/lib/chef/cookbook_manifest.rb index e061d9ef32..b16eeccbca 100644 --- a/lib/chef/cookbook_manifest.rb +++ b/lib/chef/cookbook_manifest.rb @@ -172,6 +172,7 @@ class Chef def files_for(part) return root_files if part.to_s == "root_files" + manifest[:all_files].select do |file| seg = file[:name].split("/")[0] part.to_s == seg @@ -179,11 +180,12 @@ class Chef end def each_file(excluded_parts: [], &block) - excluded_parts = Array(excluded_parts).map { |p| p.to_s } + excluded_parts = Array(excluded_parts).map(&:to_s) manifest[:all_files].each do |file| seg = file[:name].split("/")[0] next if excluded_parts.include?(seg) + yield file if block_given? end end @@ -221,7 +223,7 @@ class Chef # See #preferred_manifest_record for a description an individual manifest record. def generate_manifest manifest = Mash.new({ - all_files: Array.new, + all_files: [], }) @checksums = {} diff --git a/lib/chef/cookbook_site_streaming_uploader.rb b/lib/chef/cookbook_site_streaming_uploader.rb index cd66a5048b..dd9cf8fa39 100644 --- a/lib/chef/cookbook_site_streaming_uploader.rb +++ b/lib/chef/cookbook_site_streaming_uploader.rb @@ -79,7 +79,7 @@ class Chef unless params.nil? || params.empty? params.each do |key, value| - if value.kind_of?(File) + if value.is_a?(File) content_file = value filepath = value.path filename = File.basename(filepath) diff --git a/lib/chef/cookbook_uploader.rb b/lib/chef/cookbook_uploader.rb index 9aeecf7716..31fec8cfd1 100644 --- a/lib/chef/cookbook_uploader.rb +++ b/lib/chef/cookbook_uploader.rb @@ -68,7 +68,7 @@ class Chef new_sandbox["checksums"].each do |checksum, info| if info["needs_upload"] == true checksums_to_upload << checksum - Chef::Log.info("Uploading #{checksum_files[checksum]} (checksum hex = #{checksum}) to #{info['url']}") + Chef::Log.info("Uploading #{checksum_files[checksum]} (checksum hex = #{checksum}) to #{info["url"]}") queue << uploader_function_for(checksum_files[checksum], checksum, info["url"], checksums_to_upload) else Chef::Log.trace("#{checksum_files[checksum]} has not changed") @@ -120,7 +120,7 @@ class Chef # but we need the base64 encoding for the content-md5 # header checksum64 = Base64.encode64([checksum].pack("H*")).strip - file_contents = File.open(file, "rb") { |f| f.read } + file_contents = File.open(file, "rb", &:read) # Custom headers. 'content-type' disables JSON serialization of the request body. headers = { "content-type" => "application/x-binary", "content-md5" => checksum64, "accept" => "application/json" } diff --git a/lib/chef/cookbook_version.rb b/lib/chef/cookbook_version.rb index e69b2404b7..d546724fa0 100644 --- a/lib/chef/cookbook_version.rb +++ b/lib/chef/cookbook_version.rb @@ -42,7 +42,7 @@ class Chef def_delegator :@cookbook_manifest, :files_for def_delegator :@cookbook_manifest, :each_file - COOKBOOK_SEGMENTS = [ :resources, :providers, :recipes, :definitions, :libraries, :attributes, :files, :templates, :root_files ].freeze + COOKBOOK_SEGMENTS = %i{resources providers recipes definitions libraries attributes files templates root_files}.freeze attr_reader :all_files @@ -96,7 +96,7 @@ class Chef @root_paths = root_paths @frozen = false - @all_files = Array.new + @all_files = [] @file_vendor = nil @cookbook_manifest = Chef::CookbookManifest.new(self) @@ -279,8 +279,8 @@ class Chef def relative_filenames_in_preferred_directory(node, segment, dirname) preferences = preferences_for_path(node, segment, dirname) - filenames_by_pref = Hash.new - preferences.each { |pref| filenames_by_pref[pref] = Array.new } + filenames_by_pref = {} + preferences.each { |pref| filenames_by_pref[pref] = [] } files_for(segment).each do |manifest_record| manifest_record_path = manifest_record[:path] @@ -296,9 +296,9 @@ class Chef # we're just going to make cookbook_files out of these and make the # cookbook find them by filespecificity again. but it's the shortest # path to "success" for now. - if manifest_record_path =~ /(#{Regexp.escape(segment.to_s)}\/[^\/]*\/?#{Regexp.escape(dirname)})\/.+$/ + if manifest_record_path =~ %r{(#{Regexp.escape(segment.to_s)}/[^/]*/?#{Regexp.escape(dirname)})/.+$} specificity_dirname = $1 - non_specific_path = manifest_record_path[/#{Regexp.escape(segment.to_s)}\/[^\/]*\/?#{Regexp.escape(dirname)}\/(.+)$/, 1] + non_specific_path = manifest_record_path[%r{#{Regexp.escape(segment.to_s)}/[^/]*/?#{Regexp.escape(dirname)}/(.+)$}, 1] # Record the specificity_dirname only if it's in the list of # valid preferences if filenames_by_pref[specificity_dirname] @@ -319,14 +319,14 @@ class Chef # description of entries of the returned Array. def preferred_manifest_records_for_directory(node, segment, dirname) preferences = preferences_for_path(node, segment, dirname) - records_by_pref = Hash.new - preferences.each { |pref| records_by_pref[pref] = Array.new } + records_by_pref = {} + preferences.each { |pref| records_by_pref[pref] = [] } files_for(segment).each do |manifest_record| manifest_record_path = manifest_record[:path] # extract the preference part from the path. - if manifest_record_path =~ /(#{Regexp.escape(segment.to_s)}\/[^\/]+\/#{Regexp.escape(dirname)})\/.+$/ + if manifest_record_path =~ %r{(#{Regexp.escape(segment.to_s)}/[^/]+/#{Regexp.escape(dirname)})/.+$} # Note the specificy_dirname includes the segment and # dirname argument as above, which is what # preferences_for_path returns. It could be @@ -502,6 +502,7 @@ class Chef def <=>(other) raise Chef::Exceptions::CookbookVersionNameMismatch if name != other.name + # FIXME: can we change the interface to the Metadata class such # that metadata.version returns a Chef::Version instance instead # of a string? diff --git a/lib/chef/data_bag.rb b/lib/chef/data_bag.rb index d7e2de7397..67180559da 100644 --- a/lib/chef/data_bag.rb +++ b/lib/chef/data_bag.rb @@ -98,7 +98,8 @@ class Chef end names += Dir.glob(File.join( - Chef::Util::PathHelper.escape_glob_dir(path), "*")).map { |f| File.basename(f) }.sort + Chef::Util::PathHelper.escape_glob_dir(path), "*" + )).map { |f| File.basename(f) }.sort end names.inject({}) { |h, n| h[n] = n; h } else diff --git a/lib/chef/data_bag_item.rb b/lib/chef/data_bag_item.rb index 7ac76d9ebb..789afd44a2 100644 --- a/lib/chef/data_bag_item.rb +++ b/lib/chef/data_bag_item.rb @@ -73,6 +73,7 @@ class Chef unless new_data.respond_to?(:[]) && new_data.respond_to?(:keys) raise Exceptions::ValidationFailed, "Data Bag Items must contain a Hash or Mash!" end + validate_id!(new_data["id"]) @raw_data = new_data end @@ -141,12 +142,13 @@ class Chef if Chef::Config[:solo_legacy_mode] bag = Chef::DataBag.load(data_bag) raise Exceptions::InvalidDataBagItemID, "Item #{name} not found in data bag #{data_bag}. Other items found: #{bag.keys.join(", ")}" unless bag.include?(name) + item = bag[name] else item = Chef::ServerAPI.new(Chef::Config[:chef_server_url]).get("data/#{data_bag}/#{name}") end - if item.kind_of?(DataBagItem) + if item.is_a?(DataBagItem) item else item = from_hash(item) @@ -155,7 +157,7 @@ class Chef end end - def destroy(data_bag = self.data_bag(), databag_item = name) + def destroy(data_bag = self.data_bag, databag_item = name) chef_server_rest.delete("data/#{data_bag}/#{databag_item}") end @@ -170,6 +172,7 @@ class Chef end rescue Net::HTTPClientException => e raise e unless e.response.code == "404" + r.post("data/#{data_bag}", self) end self @@ -194,7 +197,7 @@ class Chef end def inspect - "data_bag_item[#{data_bag.inspect}, #{raw_data['id'].inspect}, #{raw_data.inspect}]" + "data_bag_item[#{data_bag.inspect}, #{raw_data["id"].inspect}, #{raw_data.inspect}]" end def pretty_print(pretty_printer) diff --git a/lib/chef/data_collector.rb b/lib/chef/data_collector.rb index b976f9d058..aac864f485 100644 --- a/lib/chef/data_collector.rb +++ b/lib/chef/data_collector.rb @@ -174,6 +174,7 @@ class Chef # def send_to_data_collector(message) return unless Chef::Config[:data_collector][:server_url] + @http ||= setup_http_client(Chef::Config[:data_collector][:server_url]) @http.post(nil, message, headers) rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, diff --git a/lib/chef/data_collector/run_end_message.rb b/lib/chef/data_collector/run_end_message.rb index 70a0b59650..341df5694f 100644 --- a/lib/chef/data_collector/run_end_message.rb +++ b/lib/chef/data_collector/run_end_message.rb @@ -85,12 +85,14 @@ class Chef # @return [Integer] the number of resources successfully updated in the chef-client run def updated_resource_count(action_collection) return 0 if action_collection.nil? + action_collection.filtered_collection(up_to_date: false, skipped: false, unprocessed: false, failed: false).count end # @return [Array<Chef::ActionCollection::ActionRecord>] list of all action_records for all resources def action_records(action_collection) return [] if action_collection.nil? + action_collection.action_records end diff --git a/lib/chef/decorator.rb b/lib/chef/decorator.rb index ac0f8fdfbb..17015bab94 100644 --- a/lib/chef/decorator.rb +++ b/lib/chef/decorator.rb @@ -38,7 +38,7 @@ class Chef # if we wrap a Hash then decorator.kind_of?(Hash) should be true def kind_of?(klass) - __getobj__.kind_of?(klass) || super + __getobj__.is_a?(klass) || super end # reset our methods on the instance if the object changes under us (this also diff --git a/lib/chef/deprecated.rb b/lib/chef/deprecated.rb index da29285223..cda8e197d3 100644 --- a/lib/chef/deprecated.rb +++ b/lib/chef/deprecated.rb @@ -84,6 +84,7 @@ class Chef relevant_line = location_file.readline relevant_line.match?(/#.*chef:silence_deprecation($|[^:]|:#{self.class.deprecation_key})/) end + false end diff --git a/lib/chef/dsl/data_query.rb b/lib/chef/dsl/data_query.rb index 88562df190..ad60852087 100644 --- a/lib/chef/dsl/data_query.rb +++ b/lib/chef/dsl/data_query.rb @@ -38,7 +38,7 @@ class Chef if Kernel.block_given? || args.length >= 4 Chef::Search::Query.new.search(*args, &block) else - results = Array.new + results = [] Chef::Search::Query.new.search(*args) do |o| results << o end diff --git a/lib/chef/dsl/declare_resource.rb b/lib/chef/dsl/declare_resource.rb index f23ef466fb..7ae1551c04 100644 --- a/lib/chef/dsl/declare_resource.rb +++ b/lib/chef/dsl/declare_resource.rb @@ -41,6 +41,7 @@ class Chef # def with_run_context(rc) raise ArgumentError, "with_run_context is useless without a block" unless block_given? + old_run_context = @run_context @run_context = case rc @@ -202,6 +203,7 @@ class Chef # def find_resource!(type, name, run_context: self.run_context) raise ArgumentError, "find_resource! does not take a block" if block_given? + run_context.resource_collection.find(type => name) end diff --git a/lib/chef/dsl/platform_introspection.rb b/lib/chef/dsl/platform_introspection.rb index e7f0c60f0d..3f79782798 100644 --- a/lib/chef/dsl/platform_introspection.rb +++ b/lib/chef/dsl/platform_introspection.rb @@ -70,6 +70,7 @@ class Chef def match_versions(node) platform, version = node[:platform].to_s, node[:platform_version].to_s return nil unless @values.key?(platform) + node_version = Chef::Version::Platform.new(version) key_matches = [] keys = @values[platform].keys @@ -84,6 +85,7 @@ class Chef end end return @values[platform][version] if key_matches.include?(version) + case key_matches.length when 0 return nil @@ -124,7 +126,7 @@ class Chef end def assert_valid_platform_values!(platforms, value) - unless value.kind_of?(Hash) + unless value.is_a?(Hash) msg = "platform dependent values must be specified in the format :platform => {:version => value} " msg << "you gave a value #{value.inspect} for platform(s) #{platforms}" raise ArgumentError, msg diff --git a/lib/chef/encrypted_data_bag_item.rb b/lib/chef/encrypted_data_bag_item.rb index d23712dd6f..667bec0b8f 100644 --- a/lib/chef/encrypted_data_bag_item.rb +++ b/lib/chef/encrypted_data_bag_item.rb @@ -130,11 +130,12 @@ class Chef::EncryptedDataBagItem def self.load_secret(path = nil) path ||= Chef::Config[:encrypted_data_bag_secret] - if !path - raise ArgumentError, "No secret specified and no secret found at #{Chef::Config.platform_specific_path(Chef::Dist::CONF_DIR + '/encrypted_data_bag_secret')}" + unless path + raise ArgumentError, "No secret specified and no secret found at #{Chef::Config.platform_specific_path(Chef::Dist::CONF_DIR + "/encrypted_data_bag_secret")}" end + secret = case path - when /^\w+:\/\// + when %r{^\w+://} # We have a remote key begin Kernel.open(path).read.strip @@ -144,14 +145,16 @@ class Chef::EncryptedDataBagItem raise ArgumentError, "Remote key not found at '#{path}'" end else - if !File.exist?(path) + unless File.exist?(path) raise Errno::ENOENT, "file not found '#{path}'" end + IO.read(path).strip end if secret.size < 1 raise ArgumentError, "invalid zero length secret in '#{path}'" end + secret end diff --git a/lib/chef/encrypted_data_bag_item/assertions.rb b/lib/chef/encrypted_data_bag_item/assertions.rb index bdd522e039..02baad2a2d 100644 --- a/lib/chef/encrypted_data_bag_item/assertions.rb +++ b/lib/chef/encrypted_data_bag_item/assertions.rb @@ -27,7 +27,7 @@ class Chef::EncryptedDataBagItem module Assertions def assert_format_version_acceptable!(format_version) - unless format_version.kind_of?(Integer) && format_version >= Chef::Config[:data_bag_decrypt_minimum_version] + unless format_version.is_a?(Integer) && format_version >= Chef::Config[:data_bag_decrypt_minimum_version] raise UnacceptableEncryptedDataBagItemFormat, "The encrypted data bag item has format version `#{format_version}', " + "but the config setting 'data_bag_decrypt_minimum_version' requires version `#{Chef::Config[:data_bag_decrypt_minimum_version]}'" diff --git a/lib/chef/encrypted_data_bag_item/check_encrypted.rb b/lib/chef/encrypted_data_bag_item/check_encrypted.rb index 9292ce6650..ab720fa64a 100644 --- a/lib/chef/encrypted_data_bag_item/check_encrypted.rb +++ b/lib/chef/encrypted_data_bag_item/check_encrypted.rb @@ -40,6 +40,7 @@ class Chef::EncryptedDataBagItem # keys and the hash's keys. def looks_like_encrypted?(data) return false unless data.is_a?(Hash) && data.key?("version") + case data["version"] when 1 Chef::EncryptedDataBagItem::Encryptor::Version1Encryptor.encryptor_keys.sort == data.keys.sort diff --git a/lib/chef/encrypted_data_bag_item/decryptor.rb b/lib/chef/encrypted_data_bag_item/decryptor.rb index ce7cdc4036..1ddc99391d 100644 --- a/lib/chef/encrypted_data_bag_item/decryptor.rb +++ b/lib/chef/encrypted_data_bag_item/decryptor.rb @@ -94,7 +94,7 @@ class Chef::EncryptedDataBagItem plaintext << openssl_decryptor.final rescue OpenSSL::Cipher::CipherError => e # if the key length is less than 255 characters, and it contains slashes, we think it may be a path. - raise DecryptionFailure, "Error decrypting data bag value: '#{e.message}'. Most likely the provided key is incorrect. #{(@key.length < 255 && @key.include?('/')) ? 'You may need to use --secret-file rather than --secret.' : ''}" + raise DecryptionFailure, "Error decrypting data bag value: '#{e.message}'. Most likely the provided key is incorrect. #{(@key.length < 255 && @key.include?("/")) ? "You may need to use --secret-file rather than --secret." : ""}" end end @@ -147,7 +147,7 @@ class Chef::EncryptedDataBagItem plaintext << openssl_decryptor.final rescue OpenSSL::Cipher::CipherError => e # if the key length is less than 255 characters, and it contains slashes, we think it may be a path. - raise DecryptionFailure, "Error decrypting data bag value: '#{e.message}'. Most likely the provided key is incorrect. #{( @key.length < 255 && @key.include?('/')) ? 'You may need to use --secret-file rather than --secret.' : ''}" + raise DecryptionFailure, "Error decrypting data bag value: '#{e.message}'. Most likely the provided key is incorrect. #{( @key.length < 255 && @key.include?("/")) ? "You may need to use --secret-file rather than --secret." : ""}" end end @@ -188,6 +188,7 @@ class Chef::EncryptedDataBagItem def candidate_hmac_matches?(expected_hmac) return false unless @encrypted_data["hmac"] + expected_bytes = expected_hmac.bytes.to_a candidate_hmac_bytes = Base64.decode64(@encrypted_data["hmac"]).bytes.to_a valid = expected_bytes.size ^ candidate_hmac_bytes.size @@ -213,6 +214,7 @@ class Chef::EncryptedDataBagItem if auth_tag_b64.nil? raise DecryptionFailure, "Error decrypting data bag value: invalid authentication tag. Most likely the data is corrupted" end + Base64.decode64(auth_tag_b64) end diff --git a/lib/chef/encrypted_data_bag_item/encryptor.rb b/lib/chef/encrypted_data_bag_item/encryptor.rb index 514633b526..1bd79016d3 100644 --- a/lib/chef/encrypted_data_bag_item/encryptor.rb +++ b/lib/chef/encrypted_data_bag_item/encryptor.rb @@ -193,6 +193,7 @@ class Chef::EncryptedDataBagItem if @auth_tag.nil? raise EncryptionFailure, "Internal Error: GCM authentication tag read before encryption" end + @auth_tag end diff --git a/lib/chef/environment.rb b/lib/chef/environment.rb index 0e0f6776ec..87716410db 100644 --- a/lib/chef/environment.rb +++ b/lib/chef/environment.rb @@ -42,7 +42,7 @@ class Chef @description = "" @default_attributes = Mash.new @override_attributes = Mash.new - @cookbook_versions = Hash.new + @cookbook_versions = {} @chef_server_rest = chef_server_rest end @@ -158,7 +158,7 @@ class Chef # reset because everything we need will be in the params, this is necessary because certain constraints # may have been removed in the params and need to be removed from cookbook_versions as well. bkup_cb_versions = cookbook_versions - cookbook_versions(Hash.new) + cookbook_versions({}) valid = true begin @@ -229,7 +229,7 @@ class Chef def self.list(inflate = false) if inflate - response = Hash.new + response = {} Chef::Search::Query.new.search(:environment) do |e| response[e.name] = e unless e.nil? end @@ -278,6 +278,7 @@ class Chef chef_server_rest.put("environments/#{@name}", self) rescue Net::HTTPClientException => e raise e unless e.response.code == "404" + chef_server_rest.post("environments", self) end self @@ -297,7 +298,8 @@ class Chef end def self.validate_cookbook_versions(cv) - return false unless cv.kind_of?(Hash) + return false unless cv.is_a?(Hash) + cv.each_value do |version| return false unless Chef::Environment.validate_cookbook_version(version) end diff --git a/lib/chef/event_dispatch/base.rb b/lib/chef/event_dispatch/base.rb index be51cf362f..cb1cc80017 100644 --- a/lib/chef/event_dispatch/base.rb +++ b/lib/chef/event_dispatch/base.rb @@ -29,268 +29,206 @@ class Chef class Base # Called at the very start of a Chef Run - def run_start(version, run_status) - end + def run_start(version, run_status); end - def run_started(run_status) - end + def run_started(run_status); end # Called at the end a successful Chef run. - def run_completed(node, run_status) - end + def run_completed(node, run_status); end # Called at the end of a failed Chef run. - def run_failed(exception, run_status) - end + def run_failed(exception, run_status); end # Called right after ohai runs. # NOTE: the node object here is always nil because of when it is called - def ohai_completed(node) - end + def ohai_completed(node); end # Announce that we're not going to register the client. Generally because # we already have the private key, or because we're deliberately not using # a key. - def skipping_registration(node_name, config) - end + def skipping_registration(node_name, config); end # About to attempt to create a private key registered to the server with # client +node_name+. - def registration_start(node_name, config) - end + def registration_start(node_name, config); end # Successfully created the private key and registered this client with the # server. - def registration_completed - end + def registration_completed; end # Failed to register this client with the server. - def registration_failed(node_name, exception, config) - end + def registration_failed(node_name, exception, config); end # Called before Chef client loads the node data from the server - def node_load_start(node_name, config) - end + def node_load_start(node_name, config); end # TODO: def node_run_list_overridden(*args) # Called once the node is loaded by the policy builder - def node_load_success(node) - end + def node_load_success(node); end # Failed to load node data from the server - def node_load_failed(node_name, exception, config) - end + def node_load_failed(node_name, exception, config); end # Error expanding the run list - def run_list_expand_failed(node, exception) - end + def run_list_expand_failed(node, exception); end # Called after Chef client has loaded the node data. # Default and override attrs from roles have been computed, but not yet applied. # Normal attrs from JSON have been added to the node. - def node_load_completed(node, expanded_run_list, config) - end + def node_load_completed(node, expanded_run_list, config); end # Called after the Policyfile was loaded. This event only occurs when # chef is in policyfile mode. - def policyfile_loaded(policy) - end + def policyfile_loaded(policy); end # Called before the cookbook collection is fetched from the server. - def cookbook_resolution_start(expanded_run_list) - end + def cookbook_resolution_start(expanded_run_list); end # Called when there is an error getting the cookbook collection from the # server. - def cookbook_resolution_failed(expanded_run_list, exception) - end + def cookbook_resolution_failed(expanded_run_list, exception); end # Called when the cookbook collection is returned from the server. - def cookbook_resolution_complete(cookbook_collection) - end + def cookbook_resolution_complete(cookbook_collection); end # Called before unneeded cookbooks are removed - def cookbook_clean_start - end + def cookbook_clean_start; end # Called after the file at +path+ is removed. It may be removed if the # cookbook containing it was removed from the run list, or if the file was # removed from the cookbook. - def removed_cookbook_file(path) - end + def removed_cookbook_file(path); end # Called when cookbook cleaning is finished. - def cookbook_clean_complete - end + def cookbook_clean_complete; end # Called before cookbook sync starts - def cookbook_sync_start(cookbook_count) - end + def cookbook_sync_start(cookbook_count); end # Called when cookbook +cookbook+ has been sync'd - def synchronized_cookbook(cookbook_name, cookbook) - end + def synchronized_cookbook(cookbook_name, cookbook); end # Called when an individual file in a cookbook has been updated - def updated_cookbook_file(cookbook_name, path) - end + def updated_cookbook_file(cookbook_name, path); end # Called when an error occurs during cookbook sync - def cookbook_sync_failed(cookbooks, exception) - end + def cookbook_sync_failed(cookbooks, exception); end # Called after all cookbooks have been sync'd. - def cookbook_sync_complete - end + def cookbook_sync_complete; end # Called when starting to collect gems from the cookbooks - def cookbook_gem_start(gems) - end + def cookbook_gem_start(gems); end # Called when the result of installing the bundle is to install the gem - def cookbook_gem_installing(gem, version) - end + def cookbook_gem_installing(gem, version); end # Called when the result of installing the bundle is to use the gem - def cookbook_gem_using(gem, version) - end + def cookbook_gem_using(gem, version); end # Called when finished installing cookbook gems - def cookbook_gem_finished - end + def cookbook_gem_finished; end # Called when cookbook gem installation fails - def cookbook_gem_failed(exception) - end + def cookbook_gem_failed(exception); end ## TODO: add cookbook name to the API for file load callbacks ## TODO: add callbacks for overall cookbook eval start and complete. # Called immediately after creating the run_context and before any cookbook compilation happens - def cookbook_compilation_start(run_context) - end + def cookbook_compilation_start(run_context); end # Called when library file loading starts - def library_load_start(file_count) - end + def library_load_start(file_count); end # Called when library file has been loaded - def library_file_loaded(path) - end + def library_file_loaded(path); end # Called when a library file has an error on load. - def library_file_load_failed(path, exception) - end + def library_file_load_failed(path, exception); end # Called when library file loading has finished - def library_load_complete - end + def library_load_complete; end # Called when LWRP loading starts - def lwrp_load_start(lwrp_file_count) - end + def lwrp_load_start(lwrp_file_count); end # Called after a LWR or LWP has been loaded - def lwrp_file_loaded(path) - end + def lwrp_file_loaded(path); end # Called after a LWR or LWP file errors on load - def lwrp_file_load_failed(path, exception) - end + def lwrp_file_load_failed(path, exception); end # Called when LWRPs are finished loading - def lwrp_load_complete - end + def lwrp_load_complete; end # Called when an ohai plugin file loading starts - def ohai_plugin_load_start(file_count) - end + def ohai_plugin_load_start(file_count); end # Called when an ohai plugin file has been loaded - def ohai_plugin_file_loaded(path) - end + def ohai_plugin_file_loaded(path); end # Called when an ohai plugin file has an error on load. - def ohai_plugin_file_load_failed(path, exception) - end + def ohai_plugin_file_load_failed(path, exception); end # Called when an ohai plugin file loading has finished - def ohai_plugin_load_complete - end + def ohai_plugin_load_complete; end # Called before attribute files are loaded - def attribute_load_start(attribute_file_count) - end + def attribute_load_start(attribute_file_count); end # Called after the attribute file is loaded - def attribute_file_loaded(path) - end + def attribute_file_loaded(path); end # Called when an attribute file fails to load. - def attribute_file_load_failed(path, exception) - end + def attribute_file_load_failed(path, exception); end # Called when attribute file loading is finished - def attribute_load_complete - end + def attribute_load_complete; end # Called before resource definitions are loaded - def definition_load_start(definition_file_count) - end + def definition_load_start(definition_file_count); end # Called when a resource definition has been loaded - def definition_file_loaded(path) - end + def definition_file_loaded(path); end # Called when a resource definition file fails to load - def definition_file_load_failed(path, exception) - end + def definition_file_load_failed(path, exception); end # Called when resource definitions are done loading - def definition_load_complete - end + def definition_load_complete; end # Called before recipes are loaded - def recipe_load_start(recipe_count) - end + def recipe_load_start(recipe_count); end # Called after the recipe has been loaded - def recipe_file_loaded(path, recipe) - end + def recipe_file_loaded(path, recipe); end # Called after a recipe file fails to load - def recipe_file_load_failed(path, exception, recipe) - end + def recipe_file_load_failed(path, exception, recipe); end # Called when a recipe cannot be resolved - def recipe_not_found(exception) - end + def recipe_not_found(exception); end # Called when recipes have been loaded. - def recipe_load_complete - end + def recipe_load_complete; end # This is called after all cookbook compilation phases are completed. - def cookbook_compilation_complete(run_context) - end + def cookbook_compilation_complete(run_context); end # Called before convergence starts - def converge_start(run_context) - end + def converge_start(run_context); end # Callback hook for handlers to register their interest in the action_collection - def action_collection_registration(action_collection) - end + def action_collection_registration(action_collection); end # Called when the converge phase is finished. - def converge_complete - end + def converge_complete; end # Called if the converge phase fails - def converge_failed(exception) - end + def converge_failed(exception); end # TODO: need events for notification resolve? # def notifications_resolved @@ -320,112 +258,88 @@ class Chef # # Called before action is executed on a resource. - def resource_action_start(resource, action, notification_type = nil, notifier = nil) - end + def resource_action_start(resource, action, notification_type = nil, notifier = nil); end # Called when a resource action has been skipped b/c of a conditional - def resource_skipped(resource, action, conditional) - end + def resource_skipped(resource, action, conditional); end # Called after #load_current_resource has run. - def resource_current_state_loaded(resource, action, current_resource) - end + def resource_current_state_loaded(resource, action, current_resource); end # Called when resource current state load is skipped due to the provider # not supporting whyrun mode. - def resource_current_state_load_bypassed(resource, action, current_resource) - end + def resource_current_state_load_bypassed(resource, action, current_resource); end # Called when evaluating a resource that does not support whyrun in whyrun mode - def resource_bypassed(resource, action, current_resource) - end + def resource_bypassed(resource, action, current_resource); end # Called when a change has been made to a resource. May be called multiple # times per resource, e.g., a file may have its content updated, and then # its permissions updated. - def resource_update_applied(resource, action, update) - end + def resource_update_applied(resource, action, update); end # Called when a progress notification should be sent to the user to # indicate the overall progress of a long running operation, such as # a large file download. - def resource_update_progress(resource, current, total, interval) - end + def resource_update_progress(resource, current, total, interval); end # Called when a resource fails, but will retry. - def resource_failed_retriable(resource, action, retry_count, exception) - end + def resource_failed_retriable(resource, action, retry_count, exception); end # Called when a resource fails and will not be retried. - def resource_failed(resource, action, exception) - end + def resource_failed(resource, action, exception); end # Called after a resource has been completely converged, but only if # modifications were made. - def resource_updated(resource, action) - end + def resource_updated(resource, action); end # Called when a resource has no converge actions, e.g., it was already correct. - def resource_up_to_date(resource, action) - end + def resource_up_to_date(resource, action); end # Called when a resource action has been completed - def resource_completed(resource) - end + def resource_completed(resource); end # A stream has opened. - def stream_opened(stream, options = {}) - end + def stream_opened(stream, options = {}); end # A stream has closed. - def stream_closed(stream, options = {}) - end + def stream_closed(stream, options = {}); end # A chunk of data from a stream. The stream is managed by "stream," which # can be any tag whatsoever. Data in different "streams" may not be placed # on the same line or even sent to the same console. - def stream_output(stream, output, options = {}) - end + def stream_output(stream, output, options = {}); end # Called before handlers run - def handlers_start(handler_count) - end + def handlers_start(handler_count); end # Called after an individual handler has run - def handler_executed(handler) - end + def handler_executed(handler); end # Called after all handlers have executed - def handlers_completed - end + def handlers_completed; end # Called when an assertion declared by a provider fails - def provider_requirement_failed(action, resource, exception, message) - end + def provider_requirement_failed(action, resource, exception, message); end # Called when a provider makes an assumption after a failed assertion # in whyrun mode, in order to allow execution to continue - def whyrun_assumption(action, resource, message) - end + def whyrun_assumption(action, resource, message); end # Emit a message about something being deprecated. - def deprecation(message, location = caller(2..2)[0]) - end + def deprecation(message, location = caller(2..2)[0]); end - def run_list_expanded(run_list_expansion) - end + def run_list_expanded(run_list_expansion); end # An uncategorized message. This supports the case that a user needs to # pass output that doesn't fit into one of the callbacks above. Note that # there's no semantic information about the content or importance of the # message. That means that if you're using this too often, you should add a # callback for it. - def msg(message) - end + def msg(message); end # Called when an attribute is changed by simple assignment - def attribute_changed(precedence, keys, value) - end + def attribute_changed(precedence, keys, value); end end end end diff --git a/lib/chef/event_dispatch/dispatcher.rb b/lib/chef/event_dispatch/dispatcher.rb index 84f1d05129..2fee4bcd0b 100644 --- a/lib/chef/event_dispatch/dispatcher.rb +++ b/lib/chef/event_dispatch/dispatcher.rb @@ -60,7 +60,8 @@ class Chef @in_call = true subscribers.each do |s| # Skip new/unsupported event names - next if !s.respond_to?(method_name) + next unless s.respond_to?(method_name) + mth = s.method(method_name) # Trim arguments to match what the subscriber expects to allow # adding new arguments without breaking compat. diff --git a/lib/chef/event_loggers/base.rb b/lib/chef/event_loggers/base.rb index 2fcc0d2458..b1a2f84988 100644 --- a/lib/chef/event_loggers/base.rb +++ b/lib/chef/event_loggers/base.rb @@ -43,8 +43,9 @@ class Chef def self.new(name) event_logger_class = by_name(name.to_s) - raise UnknownEventLogger, "No event logger found for #{name} (available: #{available_event_loggers.join(', ')})" unless event_logger_class + raise UnknownEventLogger, "No event logger found for #{name} (available: #{available_event_loggers.join(", ")})" unless event_logger_class raise UnavailableEventLogger unless available_event_loggers.include? name.to_s + event_logger_class.new end diff --git a/lib/chef/exceptions.rb b/lib/chef/exceptions.rb index 65ba0ae340..2d7ac374cb 100644 --- a/lib/chef/exceptions.rb +++ b/lib/chef/exceptions.rb @@ -493,9 +493,9 @@ class Chef @resources_found = resources_found matches_info = @resources_found.each do |r| if r["Module"].nil? - "Resource #{r['Name']} was found in #{r['Module']['Name']}" + "Resource #{r["Name"]} was found in #{r["Module"]["Name"]}" else - "Resource #{r['Name']} is a binary resource" + "Resource #{r["Name"]} is a binary resource" end end super "Found multiple resources matching #{matches_info[0]["Module"]["Name"]}:\n#{(matches_info.map { |f| f["Module"]["Version"] }).uniq.join("\n")}" diff --git a/lib/chef/file_access_control/unix.rb b/lib/chef/file_access_control/unix.rb index 8774ad9498..4d3ac84eb0 100644 --- a/lib/chef/file_access_control/unix.rb +++ b/lib/chef/file_access_control/unix.rb @@ -118,9 +118,10 @@ class Chef def gid_from_resource(resource) return nil if resource.nil? || resource.group.nil? - if resource.group.kind_of?(String) + + if resource.group.is_a?(String) diminished_radix_complement( Etc.getgrnam(resource.group).gid ) - elsif resource.group.kind_of?(Integer) + elsif resource.group.is_a?(Integer) resource.group else Chef::Log.error("The `group` parameter of the #{@resource} resource is set to an invalid value (#{resource.owner.inspect})") @@ -169,6 +170,7 @@ class Chef def mode_from_resource(res) return nil if res.nil? || res.mode.nil? + (res.mode.respond_to?(:oct) ? res.mode.oct : res.mode.to_i) & 007777 end @@ -265,9 +267,10 @@ class Chef def uid_from_resource(resource) return nil if resource.nil? || resource.owner.nil? - if resource.owner.kind_of?(String) + + if resource.owner.is_a?(String) diminished_radix_complement( Etc.getpwnam(resource.owner).uid ) - elsif resource.owner.kind_of?(Integer) + elsif resource.owner.is_a?(Integer) resource.owner else Chef::Log.error("The `owner` parameter of the #{@resource} resource is set to an invalid value (#{resource.owner.inspect})") diff --git a/lib/chef/file_access_control/windows.rb b/lib/chef/file_access_control/windows.rb index 3a5bcf9278..de08a31876 100644 --- a/lib/chef/file_access_control/windows.rb +++ b/lib/chef/file_access_control/windows.rb @@ -34,7 +34,8 @@ class Chef # We want to mix these in as class methods def writable?(path) ::File.exists?(path) && Chef::ReservedNames::Win32::File.file_access_check( - path, Chef::ReservedNames::Win32::API::Security::FILE_GENERIC_WRITE) + path, Chef::ReservedNames::Win32::API::Security::FILE_GENERIC_WRITE + ) end end @@ -110,9 +111,9 @@ class Chef end def get_sid(value) - if value.kind_of?(String) + if value.is_a?(String) SID.from_account(value) - elsif value.kind_of?(SID) + elsif value.is_a?(SID) value else raise "Must specify username, group or SID: #{value}" @@ -121,16 +122,18 @@ class Chef def securable_object @securable_object ||= begin - if file.kind_of?(String) + if file.is_a?(String) so = Chef::ReservedNames::Win32::Security::SecurableObject.new(file.dup) end - raise ArgumentError, "'file' must be a valid path or object of type 'Chef::ReservedNames::Win32::Security::SecurableObject'" unless so.kind_of? Chef::ReservedNames::Win32::Security::SecurableObject + raise ArgumentError, "'file' must be a valid path or object of type 'Chef::ReservedNames::Win32::Security::SecurableObject'" unless so.is_a? Chef::ReservedNames::Win32::Security::SecurableObject + so end end def should_update_dacl? return true unless ::File.exists?(file) || ::File.symlink?(file) + dacl = target_dacl existing_dacl = existing_descriptor.dacl inherits = target_inherits @@ -164,6 +167,7 @@ class Chef def should_update_group? return true unless ::File.exists?(file) || ::File.symlink?(file) + (group = target_group) && (group != existing_descriptor.group) end @@ -183,6 +187,7 @@ class Chef def should_update_owner? return true unless ::File.exists?(file) || ::File.symlink?(file) + (owner = target_owner) && (owner != existing_descriptor.owner) end @@ -206,6 +211,7 @@ class Chef mask |= (GENERIC_WRITE | DELETE) if mode & 2 != 0 mask |= GENERIC_EXECUTE if mode & 1 != 0 return [] if mask == 0 + [ ACE.access_allowed(sid, mask) ] end @@ -266,9 +272,10 @@ class Chef def target_dacl return nil if resource.rights.nil? && resource.deny_rights.nil? && resource.mode.nil? + acls = nil - if !resource.deny_rights.nil? + unless resource.deny_rights.nil? acls = [] if acls.nil? resource.deny_rights.each do |rights| @@ -281,7 +288,7 @@ class Chef end end - if !resource.rights.nil? + unless resource.rights.nil? acls = [] if acls.nil? resource.rights.each do |rights| @@ -294,7 +301,7 @@ class Chef end end - if !resource.mode.nil? + unless resource.mode.nil? acls = [] if acls.nil? mode = (resource.mode.respond_to?(:oct) ? resource.mode.oct : resource.mode.to_i) & 0777 @@ -321,6 +328,7 @@ class Chef def target_group return nil if resource.group.nil? + get_sid(resource.group) end @@ -330,6 +338,7 @@ class Chef def target_owner return nil if resource.owner.nil? + get_sid(resource.owner) end end diff --git a/lib/chef/file_cache.rb b/lib/chef/file_cache.rb index ad271a9192..2d4a56a91b 100644 --- a/lib/chef/file_cache.rb +++ b/lib/chef/file_cache.rb @@ -113,6 +113,7 @@ class Chef ) cache_path = create_cache_path(path, false) raise Chef::Exceptions::FileNotFound, "Cannot find #{cache_path} for #{path}!" unless File.exists?(cache_path) + if read File.read(cache_path) else @@ -157,7 +158,7 @@ class Chef # === Returns # [String] - An array of file cache keys matching the glob def find(glob_pattern) - keys = Array.new + keys = [] Dir[File.join(Chef::Util::PathHelper.escape_glob_dir(file_cache_path), glob_pattern)].each do |f| if File.file?(f) keys << f[/^#{Regexp.escape(Dir[Chef::Util::PathHelper.escape_glob_dir(file_cache_path)].first) + File::Separator}(.+)/, 1] diff --git a/lib/chef/file_content_management/deploy.rb b/lib/chef/file_content_management/deploy.rb index 2ad3aa19d5..1f158059e6 100644 --- a/lib/chef/file_content_management/deploy.rb +++ b/lib/chef/file_content_management/deploy.rb @@ -27,9 +27,9 @@ class Chef class Deploy def self.strategy(atomic_update) if atomic_update - Chef::Platform.windows? ? MvWindows.new() : MvUnix.new() + Chef::Platform.windows? ? MvWindows.new : MvUnix.new else - Cp.new() + Cp.new end end end diff --git a/lib/chef/formatters/base.rb b/lib/chef/formatters/base.rb index a295e1390d..3cf04f952e 100644 --- a/lib/chef/formatters/base.rb +++ b/lib/chef/formatters/base.rb @@ -52,7 +52,7 @@ class Chef # TODO: is it too clever to be defining new() on a module like this? def self.new(name, out, err) formatter_class = by_name(name.to_s) - raise UnknownFormatter, "No output formatter found for #{name} (available: #{available_formatters.join(', ')})" unless formatter_class + raise UnknownFormatter, "No output formatter found for #{name} (available: #{available_formatters.join(", ")})" unless formatter_class formatter_class.new(out, err) end @@ -146,8 +146,7 @@ class Chef # Formatters::Base can implement #file_loaded to do the same thing for # every kind of file that Chef loads from a recipe instead of # implementing all the per-filetype callbacks. - def file_loaded(path) - end + def file_loaded(path); end # Generic callback for any attribute/library/lwrp/recipe file throwing an # exception when loaded. Default behavior is to use CompileErrorInspector @@ -222,7 +221,7 @@ class Chef end def is_structured_deprecation?(deprecation) - deprecation.kind_of?(Chef::Deprecated::Base) + deprecation.is_a?(Chef::Deprecated::Base) end def is_formatter? diff --git a/lib/chef/formatters/doc.rb b/lib/chef/formatters/doc.rb index 77deff5b66..5ed75c00eb 100644 --- a/lib/chef/formatters/doc.rb +++ b/lib/chef/formatters/doc.rb @@ -53,7 +53,7 @@ class Chef def run_completed(node) @end_time = Time.now # Print out deprecations. - if !deprecations.empty? + unless deprecations.empty? puts_line "" puts_line "Deprecated features used!" deprecations.each do |message, details| @@ -93,23 +93,19 @@ class Chef end # Called right after ohai runs. - def ohai_completed(node) - end + def ohai_completed(node); end # Already have a client key, assuming this node has registered. - def skipping_registration(node_name, config) - end + def skipping_registration(node_name, config); end # About to attempt to register as +node_name+ def registration_start(node_name, config) puts_line "Creating a new client identity for #{node_name} using the validator key." end - def registration_completed - end + def registration_completed; end - def node_load_start(node_name, config) - end + def node_load_start(node_name, config); end # Failed to load node data from the server def node_load_failed(node_name, exception, config) @@ -118,8 +114,7 @@ class Chef # Default and override attrs from roles have been computed, but not yet applied. # Normal attrs from JSON have been added to the node. - def node_load_completed(node, expanded_run_list, config) - end + def node_load_completed(node, expanded_run_list, config); end def policyfile_loaded(policy) puts_line "Using policy '#{policy["name"]}' at revision '#{policy["revision_id"]}'" @@ -137,22 +132,18 @@ class Chef end # Called when the cookbook collection is returned from the server. - def cookbook_resolution_complete(cookbook_collection) - end + def cookbook_resolution_complete(cookbook_collection); end # Called before unneeded cookbooks are removed - def cookbook_clean_start - end + def cookbook_clean_start; end # Called after the file at +path+ is removed. It may be removed if the # cookbook containing it was removed from the run list, or if the file was # removed from the cookbook. - def removed_cookbook_file(path) - end + def removed_cookbook_file(path); end # Called when cookbook cleaning is finished. - def cookbook_clean_complete - end + def cookbook_clean_complete; end # Called before cookbook sync starts def cookbook_sync_start(cookbook_count) @@ -166,8 +157,7 @@ class Chef end # Called when an individual file in a cookbook has been updated - def updated_cookbook_file(cookbook_name, path) - end + def updated_cookbook_file(cookbook_name, path); end # Called after all cookbooks have been sync'd. def cookbook_sync_complete @@ -206,12 +196,10 @@ class Chef end # Called after a file in a cookbook is loaded. - def file_loaded(path) - end + def file_loaded(path); end # Called when recipes have been loaded. - def recipe_load_complete - end + def recipe_load_complete; end # Called before convergence starts def converge_start(run_context) @@ -263,8 +251,7 @@ class Chef end # Called when a resource fails, but will retry. - def resource_failed_retriable(resource, action, retry_count, exception) - end + def resource_failed_retriable(resource, action, retry_count, exception); end # Called when a resource fails and will not be retried. def resource_failed(resource, action, exception) @@ -281,8 +268,7 @@ class Chef end # Called after #load_current_resource has run. - def resource_current_state_loaded(resource, action, current_resource) - end + def resource_current_state_loaded(resource, action, current_resource); end # Called when a resource has no converge actions, e.g., it was already correct. def resource_up_to_date(resource, action) @@ -296,8 +282,7 @@ class Chef unindent end - def output_record(line) - end + def output_record(line); end # Called when a change has been made to a resource. May be called multiple # times per resource, e.g., a file may have its content updated, and then @@ -306,10 +291,11 @@ class Chef prefix = Chef::Config[:why_run] ? "Would " : "" Array(update).each do |line| next if line.nil? + output_record line - if line.kind_of? String + if line.is_a? String start_line "- #{prefix}#{line}", :green - elsif line.kind_of? Array + elsif line.is_a? Array # Expanded output - delta # @todo should we have a resource_update_delta callback? line.each do |detail| @@ -358,6 +344,7 @@ class Chef # in whyrun mode, in order to allow execution to continue def whyrun_assumption(action, resource, message) return unless message + [ message ].flatten.each do |line| start_line("* #{line}", :yellow) end @@ -366,6 +353,7 @@ class Chef # Called when an assertion declared by a provider fails def provider_requirement_failed(action, resource, exception, message) return unless message + color = Chef::Config[:why_run] ? :yellow : :red [ message ].flatten.each do |line| start_line("* #{line}", color) diff --git a/lib/chef/formatters/error_inspectors/cookbook_resolve_error_inspector.rb b/lib/chef/formatters/error_inspectors/cookbook_resolve_error_inspector.rb index 89d4ba7bce..4a6fa49fe7 100644 --- a/lib/chef/formatters/error_inspectors/cookbook_resolve_error_inspector.rb +++ b/lib/chef/formatters/error_inspectors/cookbook_resolve_error_inspector.rb @@ -143,14 +143,15 @@ class Chef # "{\"error\":[\"{\\\"non_existent_cookbooks\\\":[\\\"nope\\\"],\\\"cookbooks_with_no_versions\\\":[],\\\"message\\\":\\\"Run list contains invalid items: no such cookbook nope.\\\"}\"]}" wrapped_error_message = attempt_json_parse(exception.response.body) - unless wrapped_error_message.kind_of?(Hash) && wrapped_error_message.key?("error") + unless wrapped_error_message.is_a?(Hash) && wrapped_error_message.key?("error") return wrapped_error_message.to_s end error_description = Array(wrapped_error_message["error"]).first - if error_description.kind_of?(Hash) + if error_description.is_a?(Hash) return error_description end + attempt_json_parse(error_description) end diff --git a/lib/chef/formatters/error_inspectors/resource_failure_inspector.rb b/lib/chef/formatters/error_inspectors/resource_failure_inspector.rb index 3fd6094ae0..5141ed89fe 100644 --- a/lib/chef/formatters/error_inspectors/resource_failure_inspector.rb +++ b/lib/chef/formatters/error_inspectors/resource_failure_inspector.rb @@ -55,7 +55,7 @@ class Chef if Chef::Platform.windows? require_relative "../../win32/security" - if !Chef::ReservedNames::Win32::Security.has_admin_privileges? + unless Chef::ReservedNames::Win32::Security.has_admin_privileges? error_description.section("Missing Windows Admin Privileges", "#{Chef::Dist::CLIENT} doesn't have administrator privileges. This can be a possible reason for the resource failure.") end end @@ -63,9 +63,11 @@ class Chef def recipe_snippet return nil if dynamic_resource? + @snippet ||= begin if (file = parse_source) && (line = parse_line(file)) return nil unless ::File.exists?(file) + lines = IO.readlines(file) relevant_lines = ["# In #{file}\n\n"] diff --git a/lib/chef/formatters/indentable_output_stream.rb b/lib/chef/formatters/indentable_output_stream.rb index 0481cb6217..5d58df6f11 100644 --- a/lib/chef/formatters/indentable_output_stream.rb +++ b/lib/chef/formatters/indentable_output_stream.rb @@ -112,7 +112,7 @@ class Chef end def from_args(colors, merge_options = {}) - if colors.size == 1 && colors[0].kind_of?(Hash) + if colors.size == 1 && colors[0].is_a?(Hash) merge_options.merge(colors[0]) else merge_options.merge({ colors: colors }) @@ -154,14 +154,14 @@ class Chef end def indent_line(options) - if !@line_started + unless @line_started # Print indents. If there is a stream name, either print it (if we're # switching streams) or print enough blanks to match # the indents. if options[:name] if @current_stream != options[:stream] - @out.print "#{(' ' * indent)}[#{options[:name]}] " + @out.print "#{(" " * indent)}[#{options[:name]}] " else @out.print " " * (indent + 3 + options[:name].size) end diff --git a/lib/chef/formatters/minimal.rb b/lib/chef/formatters/minimal.rb index 272a89bad0..a35a7e8057 100644 --- a/lib/chef/formatters/minimal.rb +++ b/lib/chef/formatters/minimal.rb @@ -44,36 +44,29 @@ class Chef end # Called right after ohai runs. - def ohai_completed(node) - end + def ohai_completed(node); end # Already have a client key, assuming this node has registered. - def skipping_registration(node_name, config) - end + def skipping_registration(node_name, config); end # About to attempt to register as +node_name+ - def registration_start(node_name, config) - end + def registration_start(node_name, config); end - def registration_completed - end + def registration_completed; end # Failed to register this client with the server. def registration_failed(node_name, exception, config) super end - def node_load_start(node_name, config) - end + def node_load_start(node_name, config); end # Failed to load node data from the server - def node_load_failed(node_name, exception, config) - end + def node_load_failed(node_name, exception, config); end # Default and override attrs from roles have been computed, but not yet applied. # Normal attrs from JSON have been added to the node. - def node_load_completed(node, expanded_run_list, config) - end + def node_load_completed(node, expanded_run_list, config); end # Called before the cookbook collection is fetched from the server. def cookbook_resolution_start(expanded_run_list) @@ -82,28 +75,23 @@ class Chef # Called when there is an error getting the cookbook collection from the # server. - def cookbook_resolution_failed(expanded_run_list, exception) - end + def cookbook_resolution_failed(expanded_run_list, exception); end # Called when the cookbook collection is returned from the server. - def cookbook_resolution_complete(cookbook_collection) - end + def cookbook_resolution_complete(cookbook_collection); end # Called before unneeded cookbooks are removed #-- # TODO: Should be called in CookbookVersion.sync_cookbooks - def cookbook_clean_start - end + def cookbook_clean_start; end # Called after the file at +path+ is removed. It may be removed if the # cookbook containing it was removed from the run list, or if the file was # removed from the cookbook. - def removed_cookbook_file(path) - end + def removed_cookbook_file(path); end # Called when cookbook cleaning is finished. - def cookbook_clean_complete - end + def cookbook_clean_complete; end # Called before cookbook sync starts def cookbook_sync_start(cookbook_count) @@ -116,8 +104,7 @@ class Chef end # Called when an individual file in a cookbook has been updated - def updated_cookbook_file(cookbook_name, path) - end + def updated_cookbook_file(cookbook_name, path); end # Called after all cookbooks have been sync'd. def cookbook_sync_complete @@ -168,16 +155,13 @@ class Chef end # Called before action is executed on a resource. - def resource_action_start(resource, action, notification_type = nil, notifier = nil) - end + def resource_action_start(resource, action, notification_type = nil, notifier = nil); end # Called when a resource fails, but will retry. - def resource_failed_retriable(resource, action, retry_count, exception) - end + def resource_failed_retriable(resource, action, retry_count, exception); end # Called when a resource fails and will not be retried. - def resource_failed(resource, action, exception) - end + def resource_failed(resource, action, exception); end # Called when a resource action has been skipped b/c of a conditional def resource_skipped(resource, action, conditional) @@ -185,8 +169,7 @@ class Chef end # Called after #load_current_resource has run. - def resource_current_state_loaded(resource, action, current_resource) - end + def resource_current_state_loaded(resource, action, current_resource); end # Called when a resource has no converge actions, e.g., it was already correct. def resource_up_to_date(resource, action) @@ -211,24 +194,20 @@ class Chef end # Called before handlers run - def handlers_start(handler_count) - end + def handlers_start(handler_count); end # Called after an individual handler has run - def handler_executed(handler) - end + def handler_executed(handler); end # Called after all handlers have executed - def handlers_completed - end + def handlers_completed; end # An uncategorized message. This supports the case that a user needs to # pass output that doesn't fit into one of the callbacks above. Note that # there's no semantic information about the content or importance of the # message. That means that if you're using this too often, you should add a # callback for it. - def msg(message) - end + def msg(message); end end end diff --git a/lib/chef/guard_interpreter/resource_guard_interpreter.rb b/lib/chef/guard_interpreter/resource_guard_interpreter.rb index 9b7c1517db..adab16f5bf 100644 --- a/lib/chef/guard_interpreter/resource_guard_interpreter.rb +++ b/lib/chef/guard_interpreter/resource_guard_interpreter.rb @@ -91,7 +91,7 @@ class Chef raise ArgumentError, "Specified guard_interpreter resource #{parent_resource.guard_interpreter} unknown for this platform" end - if ! resource_class.ancestors.include?(Chef::Resource::Execute) + unless resource_class.ancestors.include?(Chef::Resource::Execute) raise ArgumentError, "Specified guard interpreter class #{resource_class} must be a kind of Chef::Resource::Execute resource" end diff --git a/lib/chef/handler.rb b/lib/chef/handler.rb index 6fabe98d1f..115110ce91 100644 --- a/lib/chef/handler.rb +++ b/lib/chef/handler.rb @@ -234,8 +234,7 @@ class Chef # The main entry point for report handling. Subclasses should override this # method with their own report handling logic. - def report - end + def report; end # Runs the report handler, rescuing and logging any errors it may cause. # This ensures that all handlers get a chance to run even if one fails. diff --git a/lib/chef/http.rb b/lib/chef/http.rb index f5ad71c694..5546156031 100644 --- a/lib/chef/http.rb +++ b/lib/chef/http.rb @@ -155,7 +155,7 @@ class Chef rescue Net::HTTPClientException => e http_attempts += 1 response = e.response - if response.kind_of?(Net::HTTPNotAcceptable) && version_retries - http_attempts > 0 + if response.is_a?(Net::HTTPNotAcceptable) && version_retries - http_attempts > 0 Chef::Log.trace("Negotiating protocol version with #{url}, retry #{http_attempts}/#{version_retries}") retry else @@ -180,20 +180,21 @@ class Chef method, url, processed_headers, data = apply_request_middleware(method, url, headers, data) response, rest_request, return_value = send_http_request(method, url, processed_headers, data) do |http_response| - if http_response.kind_of?(Net::HTTPSuccess) + if http_response.is_a?(Net::HTTPSuccess) tempfile = stream_to_tempfile(url, http_response, tempfile, &progress_block) end apply_stream_complete_middleware(http_response, rest_request, return_value) end - return nil if response.kind_of?(Net::HTTPRedirection) - unless response.kind_of?(Net::HTTPSuccess) + return nil if response.is_a?(Net::HTTPRedirection) + + unless response.is_a?(Net::HTTPSuccess) response.error! end tempfile rescue Net::HTTPClientException => e http_attempts += 1 response = e.response - if response.kind_of?(Net::HTTPNotAcceptable) && version_retries - http_attempts > 0 + if response.is_a?(Net::HTTPNotAcceptable) && version_retries - http_attempts > 0 Chef::Log.trace("Negotiating protocol version with #{url}, retry #{http_attempts}/#{version_retries}") retry else @@ -226,14 +227,15 @@ class Chef method, url, processed_headers, data = apply_request_middleware(method, url, headers, data) response, rest_request, return_value = send_http_request(method, url, processed_headers, data) do |http_response| - if http_response.kind_of?(Net::HTTPSuccess) + if http_response.is_a?(Net::HTTPSuccess) tempfile = stream_to_tempfile(url, http_response, tempfile) end apply_stream_complete_middleware(http_response, rest_request, return_value) end - return nil if response.kind_of?(Net::HTTPRedirection) - unless response.kind_of?(Net::HTTPSuccess) + return nil if response.is_a?(Net::HTTPRedirection) + + unless response.is_a?(Net::HTTPSuccess) response.error! end @@ -248,7 +250,7 @@ class Chef rescue Net::HTTPClientException => e http_attempts += 1 response = e.response - if response.kind_of?(Net::HTTPNotAcceptable) && version_retries - http_attempts > 0 + if response.is_a?(Net::HTTPNotAcceptable) && version_retries - http_attempts > 0 Chef::Log.trace("Negotiating protocol version with #{url}, retry #{http_attempts}/#{version_retries}") retry else @@ -309,7 +311,8 @@ class Chef # @api private def create_url(path) return path if path.is_a?(URI) - if path =~ /^(http|https|chefzero):\/\//i + + if path =~ %r{^(http|https|chefzero)://}i URI.parse(path) elsif path.nil? || path.empty? URI.parse(@url) @@ -355,7 +358,7 @@ class Chef # @api private def success_response?(response) - response.kind_of?(Net::HTTPSuccess) || response.kind_of?(Net::HTTPRedirection) + response.is_a?(Net::HTTPSuccess) || response.is_a?(Net::HTTPRedirection) end # Runs a synchronous HTTP request, with no middleware applied (use #request @@ -369,17 +372,17 @@ class Chef if block_given? request, response = client.request(method, url, body, headers, &response_handler) else - request, response = client.request(method, url, body, headers) { |r| r.read_body } + request, response = client.request(method, url, body, headers, &:read_body) return_value = response.read_body end @last_response = response - if response.kind_of?(Net::HTTPSuccess) + if response.is_a?(Net::HTTPSuccess) [response, request, return_value] - elsif response.kind_of?(Net::HTTPNotModified) # Must be tested before Net::HTTPRedirection because it's subclass. + elsif response.is_a?(Net::HTTPNotModified) # Must be tested before Net::HTTPRedirection because it's subclass. [response, request, false] elsif redirect_location = redirected_to(response) - if [:GET, :HEAD].include?(method) + if %i{GET HEAD}.include?(method) follow_redirect do redirected_url = url + redirect_location if http_disable_auth_on_redirect @@ -410,7 +413,7 @@ class Chef http_attempts += 1 response, request, return_value = yield # handle HTTP 50X Error - if response.kind_of?(Net::HTTPServerError) && !Chef::Config.local_mode + if response.is_a?(Net::HTTPServerError) && !Chef::Config.local_mode if http_retry_count - http_attempts + 1 > 0 sleep_time = 1 + (2**http_attempts) + rand(2**http_attempts) Chef::Log.error("Server returned error #{response.code} for #{url}, retrying #{http_attempts}/#{http_retry_count} in #{sleep_time}s") @@ -479,6 +482,7 @@ class Chef # @api private def follow_redirect raise Chef::Exceptions::RedirectLimitExceeded if @redirects_followed >= redirect_limit + @redirects_followed += 1 Chef::Log.trace("Following redirect #{@redirects_followed}/#{redirect_limit}") @@ -495,9 +499,10 @@ class Chef # @api private def redirected_to(response) - return nil unless response.kind_of?(Net::HTTPRedirection) + return nil unless response.is_a?(Net::HTTPRedirection) # Net::HTTPNotModified is undesired subclass of Net::HTTPRedirection so test for this - return nil if response.kind_of?(Net::HTTPNotModified) + return nil if response.is_a?(Net::HTTPNotModified) + response["location"] end diff --git a/lib/chef/http/api_versions.rb b/lib/chef/http/api_versions.rb index e1eae4b468..a0486c934f 100644 --- a/lib/chef/http/api_versions.rb +++ b/lib/chef/http/api_versions.rb @@ -24,8 +24,7 @@ class Chef # and maximum supported API versions. class APIVersions - def initialize(options = {}) - end + def initialize(options = {}); end def handle_request(method, url, headers = {}, data = false) [method, url, headers, data] diff --git a/lib/chef/http/auth_credentials.rb b/lib/chef/http/auth_credentials.rb index e761c97e9b..a1542d1f93 100644 --- a/lib/chef/http/auth_credentials.rb +++ b/lib/chef/http/auth_credentials.rb @@ -40,6 +40,7 @@ class Chef def signature_headers(request_params = {}) raise ArgumentError, "Cannot sign the request without a client name, check that :node_name is assigned" if client_name.nil? + Chef::Log.trace("Signing the request as #{client_name}") # params_in = {:http_method => :GET, :path => "/clients", :body => "", :host => "localhost"} diff --git a/lib/chef/http/decompressor.rb b/lib/chef/http/decompressor.rb index f43f054366..3c3960e02f 100644 --- a/lib/chef/http/decompressor.rb +++ b/lib/chef/http/decompressor.rb @@ -64,6 +64,7 @@ class Chef # temporary hack, skip processing if return_value is false # needed to keep conditional get stuff working correctly. return [http_response, rest_request, return_value] if return_value == false + response_body = decompress_body(http_response) http_response.body.replace(response_body) if http_response.body.respond_to?(:replace) [http_response, rest_request, return_value] diff --git a/lib/chef/http/json_output.rb b/lib/chef/http/json_output.rb index 5fe2622f94..62fa379096 100644 --- a/lib/chef/http/json_output.rb +++ b/lib/chef/http/json_output.rb @@ -46,6 +46,7 @@ class Chef # temporary hack, skip processing if return_value is false # needed to keep conditional get stuff working correctly. return [http_response, rest_request, return_value] if return_value == false + if http_response["content-type"] =~ /json/ if http_response.body.nil? return_value = nil @@ -60,7 +61,7 @@ class Chef end [http_response, rest_request, return_value] else - Chef::Log.trace("Expected JSON response, but got content-type '#{http_response['content-type']}'") + Chef::Log.trace("Expected JSON response, but got content-type '#{http_response["content-type"]}'") if http_response.body Chef::Log.trace("Response body contains:\n#{http_response.body.length < 256 ? http_response.body : http_response.body[0..256] + " [...truncated...]"}") end diff --git a/lib/chef/http/json_to_model_output.rb b/lib/chef/http/json_to_model_output.rb index c908d0d23d..a1986bfce5 100644 --- a/lib/chef/http/json_to_model_output.rb +++ b/lib/chef/http/json_to_model_output.rb @@ -26,7 +26,7 @@ class Chef # a `json_class` key. class JSONToModelOutput < JSONOutput def initialize(opts = {}) - opts[:inflate_json_class] = true if !opts.key?(:inflate_json_class) + opts[:inflate_json_class] = true unless opts.key?(:inflate_json_class) super end end diff --git a/lib/chef/http/remote_request_id.rb b/lib/chef/http/remote_request_id.rb index d4fb8eb115..95ce68a2d4 100644 --- a/lib/chef/http/remote_request_id.rb +++ b/lib/chef/http/remote_request_id.rb @@ -21,8 +21,7 @@ class Chef class HTTP class RemoteRequestID - def initialize(opts = {}) - end + def initialize(opts = {}); end def handle_request(method, url, headers = {}, data = false) headers["X-REMOTE-REQUEST-ID"] = Chef::RequestID.instance.request_id diff --git a/lib/chef/http/socketless_chef_zero_client.rb b/lib/chef/http/socketless_chef_zero_client.rb index 61673c28a6..b83fdbd41b 100644 --- a/lib/chef/http/socketless_chef_zero_client.rb +++ b/lib/chef/http/socketless_chef_zero_client.rb @@ -134,7 +134,7 @@ class Chef 511 => "Network Authentication Required", }.freeze - STATUS_MESSAGE.each_value { |v| v.freeze } + STATUS_MESSAGE.each_value(&:freeze) STATUS_MESSAGE.freeze def initialize(base_url) @@ -181,6 +181,7 @@ class Chef body = chunked_body.join("") msg = STATUS_MESSAGE[code] raise "Cannot determine HTTP status message for code #{code}" unless msg + response = Net::HTTPResponse.send(:response_class, code.to_s).new("1.0", code.to_s, msg) response.instance_variable_set(:@body, body) headers.each do |name, value| @@ -200,7 +201,7 @@ class Chef def headers_extracted_from_options options.reject { |name, _| KNOWN_OPTIONS.include?(name) }.map do |name, value| - [name.to_s.split("_").map { |segment| segment.capitalize }.join("-"), value] + [name.to_s.split("_").map(&:capitalize).join("-"), value] end end diff --git a/lib/chef/http/ssl_policies.rb b/lib/chef/http/ssl_policies.rb index 3f7dd34404..a299a8d7ca 100644 --- a/lib/chef/http/ssl_policies.rb +++ b/lib/chef/http/ssl_policies.rb @@ -62,11 +62,13 @@ class Chef unless ::File.exist?(config[:ssl_ca_path]) raise Chef::Exceptions::ConfigurationError, "The configured ssl_ca_path #{config[:ssl_ca_path]} does not exist" end + http_client.ca_path = config[:ssl_ca_path] elsif config[:ssl_ca_file] unless ::File.exist?(config[:ssl_ca_file]) raise Chef::Exceptions::ConfigurationError, "The configured ssl_ca_file #{config[:ssl_ca_file]} does not exist" end + http_client.ca_file = config[:ssl_ca_file] end end @@ -96,6 +98,7 @@ class Chef unless ::File.exists?(config[:ssl_client_key]) raise Chef::Exceptions::ConfigurationError, "The configured ssl_client_key #{config[:ssl_client_key]} does not exist" end + http_client.cert = OpenSSL::X509::Certificate.new(::File.read(config[:ssl_client_cert])) http_client.key = OpenSSL::PKey::RSA.new(::File.read(config[:ssl_client_key])) end diff --git a/lib/chef/http/validate_content_length.rb b/lib/chef/http/validate_content_length.rb index 1b1a8a398a..d1585f7991 100644 --- a/lib/chef/http/validate_content_length.rb +++ b/lib/chef/http/validate_content_length.rb @@ -41,8 +41,7 @@ class Chef end end - def initialize(opts = {}) - end + def initialize(opts = {}); end def handle_request(method, url, headers = {}, data = false) [method, url, headers, data] @@ -74,6 +73,7 @@ class Chef def response_content_length(response) return nil if response["content-length"].nil? + if response["content-length"].is_a?(Array) response["content-length"].first.to_i else diff --git a/lib/chef/json_compat.rb b/lib/chef/json_compat.rb index 13a2c43dbb..cc750e16ee 100644 --- a/lib/chef/json_compat.rb +++ b/lib/chef/json_compat.rb @@ -42,7 +42,7 @@ class Chef # JSON gem requires top level object to be a Hash or Array (otherwise # you get the "must contain two octets" error). Yajl doesn't impose the # same limitation. For compatibility, we re-impose this condition. - unless obj.kind_of?(Hash) || obj.kind_of?(Array) + unless obj.is_a?(Hash) || obj.is_a?(Array) raise Chef::Exceptions::JSON::ParseError, "Top level JSON object must be a Hash or Array. (actual: #{obj.class})" end diff --git a/lib/chef/key.rb b/lib/chef/key.rb index 7f4591c2c7..632820efa4 100644 --- a/lib/chef/key.rb +++ b/lib/chef/key.rb @@ -87,6 +87,7 @@ class Chef def public_key(arg = nil) raise Chef::Exceptions::InvalidKeyAttribute, "you cannot set the public_key if create_key is true" if !arg.nil? && @create_key + set_or_return(:public_key, arg, kind_of: String) end @@ -106,6 +107,7 @@ class Chef def create_key(arg = nil) raise Chef::Exceptions::InvalidKeyAttribute, "you cannot set create_key to true if the public_key field exists" if arg == true && !@public_key.nil? + set_or_return(:create_key, arg, kind_of: [TrueClass, FalseClass]) end diff --git a/lib/chef/knife.rb b/lib/chef/knife.rb index 48226bb344..28634d9e44 100644 --- a/lib/chef/knife.rb +++ b/lib/chef/knife.rb @@ -231,9 +231,7 @@ class Chef end def self.load_deps - dependency_loaders.each do |dep_loader| - dep_loader.call - end + dependency_loaders.each(&:call) end OFFICIAL_PLUGINS = %w{ec2 rackspace windows openstack azure google linode push vcenter lpar}.freeze @@ -244,6 +242,7 @@ class Chef msg "Available #{category_desc}subcommands: (for details, knife SUB-COMMAND --help)\n\n" subcommand_loader.list_commands(preferred_category).sort.each do |category, commands| next if category =~ /deprecated/i + msg "** #{category.upcase} COMMANDS **" commands.sort.each do |command| subcommand_loader.load_command(command) @@ -264,7 +263,7 @@ class Chef # user could not be resolved to a subcommand. # @api private def subcommand_not_found!(args) - ui.fatal("Cannot find subcommand for: '#{args.join(' ')}'") + ui.fatal("Cannot find subcommand for: '#{args.join(" ")}'") # Mention rehash when the subcommands cache(plugin_manifest.json) is used if subcommand_loader.is_a?(Chef::Knife::SubcommandLoader::HashedCommandLoader) @@ -386,6 +385,7 @@ class Chef return :cli if @original_config.include? key return :config if config_file_settings.key? key return :cli_default if default_config.include? key + nil end @@ -476,6 +476,7 @@ class Chef end rescue Exception => e raise if raise_exception || ( Chef::Config[:verbosity] && Chef::Config[:verbosity] >= 2 ) + humanize_exception(e) exit 100 end @@ -640,7 +641,7 @@ class Chef end def maybe_setup_fips - if !config[:fips].nil? + unless config[:fips].nil? Chef::Config[:fips] = config[:fips] end Chef::Config.init_openssl diff --git a/lib/chef/knife/bootstrap.rb b/lib/chef/knife/bootstrap.rb index 13f8731c77..e892f1f2c9 100644 --- a/lib/chef/knife/bootstrap.rb +++ b/lib/chef/knife/bootstrap.rb @@ -195,6 +195,7 @@ class Chef unless valid_values.include?(v) raise "Invalid value '#{v}' for --node-ssl-verify-mode. Valid values are: #{valid_values.join(", ")}" end + v } @@ -282,9 +283,9 @@ class Chef long: "--hint HINT_NAME[=HINT_FILE]", description: "Specify an Ohai hint to be set on the bootstrap target. Use multiple --hint options to specify multiple hints.", proc: Proc.new { |h| - Chef::Config[:knife][:hints] ||= Hash.new + Chef::Config[:knife][:hints] ||= {} name, path = h.split("=") - Chef::Config[:knife][:hints][name] = path ? Chef::JSONCompat.parse(::File.read(path)) : Hash.new + Chef::Config[:knife][:hints][name] = path ? Chef::JSONCompat.parse(::File.read(path)) : {} } # bootstrap override: url of a an installer shell script touse in place of omnitruck @@ -647,6 +648,7 @@ class Chef q.echo = false end end + opts.merge! force_ssh_password_opts(password) do_connect(opts) else @@ -654,14 +656,14 @@ class Chef end end - def handle_ssh_error(e) - end + def handle_ssh_error(e); end # url values override CLI flags, if you provide both # we'll use the one that you gave in the URL. def connection_protocol return @connection_protocol if @connection_protocol - from_url = host_descriptor =~ /^(.*):\/\// ? $1 : nil + + from_url = host_descriptor =~ %r{^(.*)://} ? $1 : nil from_cli = config[:connection_protocol] from_knife = Chef::Config[:knife][:connection_protocol] @connection_protocol = from_url || from_cli || from_knife || "ssh" @@ -678,6 +680,7 @@ class Chef if @config[:first_boot_attributes] && @config[:first_boot_attributes_from_file] raise Chef::Exceptions::BootstrapCommandInputError end + true end @@ -783,16 +786,14 @@ class Chef # Plugins that subclass bootstrap, e.g. knife-ec2, can use this method to create connection objects # # @return [TrueClass] If instance successfully created, or exits - def plugin_setup! - end + def plugin_setup!; end # Perform any teardown or cleanup necessary by the plugin # # Plugins that subclass bootstrap, e.g. knife-ec2, can use this method to display a message or perform any cleanup # # @return [void] - def plugin_finalize - end + def plugin_finalize; end # If session_timeout is too short, it is likely # a holdover from "--winrm-session-timeout" which used @@ -842,6 +843,7 @@ class Chef # host via train def connection_opts(reset: false) return @connection_opts unless @connection_opts.nil? || reset == true + @connection_opts = {} @connection_opts.merge! base_opts @connection_opts.merge! host_verify_opts @@ -892,6 +894,7 @@ class Chef def ssh_opts opts = {} return opts if winrm? + opts[:pty] = true # ensure we can talk to systems with requiretty set true in sshd config opts[:non_interactive] = true # Prevent password prompts from underlying net/ssh opts[:forward_agent] = (config_value(:ssh_forward_agent) === true) @@ -902,6 +905,7 @@ class Chef def ssh_identity_opts opts = {} return opts if winrm? + identity_file = config_value(:ssh_identity_file) if identity_file opts[:key_files] = [identity_file] @@ -962,6 +966,7 @@ class Chef # should we change that for consistency? def sudo_opts return {} if winrm? + opts = { sudo: false } if config[:use_sudo] opts[:sudo] = true @@ -977,6 +982,7 @@ class Chef def winrm_opts return {} unless winrm? + auth_method = config_value(:winrm_auth_method, :winrm_auth_method, "negotiate") opts = { winrm_transport: auth_method, # winrm gem and train calls auth method 'transport' @@ -1006,7 +1012,7 @@ class Chef non_interactive: false, keys_only: false, key_files: [], - auth_methods: [:password, :keyboard_interactive], + auth_methods: %i{password keyboard_interactive}, } end @@ -1085,6 +1091,7 @@ class Chef def session_timeout timeout = config_value(:session_timeout) return options[:session_timeout][:default] if timeout.nil? + timeout.to_i end end diff --git a/lib/chef/knife/bootstrap/chef_vault_handler.rb b/lib/chef/knife/bootstrap/chef_vault_handler.rb index 605a9d359b..b6a292fda0 100644 --- a/lib/chef/knife/bootstrap/chef_vault_handler.rb +++ b/lib/chef/knife/bootstrap/chef_vault_handler.rb @@ -145,6 +145,7 @@ class Chef if Gem::Version.new(ChefVault::VERSION) < Gem::Version.new("2.6.0") raise error_message end + true rescue LoadError raise error_message diff --git a/lib/chef/knife/bootstrap/client_builder.rb b/lib/chef/knife/bootstrap/client_builder.rb index 87dd03d6ed..3dee318414 100644 --- a/lib/chef/knife/bootstrap/client_builder.rb +++ b/lib/chef/knife/bootstrap/client_builder.rb @@ -188,6 +188,7 @@ class Chef true rescue Net::HTTPClientException => e raise unless e.response.code == "404" + false end diff --git a/lib/chef/knife/bootstrap/train_connector.rb b/lib/chef/knife/bootstrap/train_connector.rb index da5db65de0..8487116f08 100644 --- a/lib/chef/knife/bootstrap/train_connector.rb +++ b/lib/chef/knife/bootstrap/train_connector.rb @@ -23,7 +23,7 @@ class Chef class Knife class Bootstrap < Knife class TrainConnector - SSH_CONFIG_OVERRIDE_KEYS ||= [:user, :port, :proxy].freeze + SSH_CONFIG_OVERRIDE_KEYS ||= %i{user port proxy}.freeze MKTEMP_WIN_COMMAND ||= <<~EOM.freeze $parent = [System.IO.Path]::GetTempPath(); @@ -213,6 +213,7 @@ class Chef if result.exit_status != 0 raise RemoteExecutionFailed.new(hostname, command, result) end + result end @@ -247,6 +248,7 @@ class Chef # Return a hash of winrm options based on configuration already built. def opts_inferred_from_winrm(config, opts_in) return {} unless config[:backend] == "winrm" + opts_out = {} if opts_in[:ssl] @@ -296,6 +298,7 @@ class Chef # itself - causing SSH config data to be ignored def missing_opts_from_ssh_config(config, opts_in) return {} unless config[:backend] == "ssh" + host_cfg = ssh_config_for_host(config[:host]) opts_out = {} opts_in.each do |key, _value| diff --git a/lib/chef/knife/client_bulk_delete.rb b/lib/chef/knife/client_bulk_delete.rb index 703ccb7747..6997110612 100644 --- a/lib/chef/knife/client_bulk_delete.rb +++ b/lib/chef/knife/client_bulk_delete.rb @@ -45,6 +45,7 @@ class Chef validators_to_delete = {} all_clients.each do |name, client| next unless name =~ matcher + if client.validator validators_to_delete[client.name] = client else diff --git a/lib/chef/knife/cookbook_delete.rb b/lib/chef/knife/cookbook_delete.rb index 381df56d71..98e54f486d 100644 --- a/lib/chef/knife/cookbook_delete.rb +++ b/lib/chef/knife/cookbook_delete.rb @@ -106,7 +106,7 @@ class Chef end valid_responses[(available_versions.size + 1).to_s] = :all question << "#{available_versions.size + 1}. All versions\n\n" - responses = ask_question(question).split(",").map { |response| response.strip } + responses = ask_question(question).split(",").map(&:strip) if responses.empty? ui.error("No versions specified, exiting") diff --git a/lib/chef/knife/cookbook_download.rb b/lib/chef/knife/cookbook_download.rb index 2da5e138a3..aa6458a5d0 100644 --- a/lib/chef/knife/cookbook_download.rb +++ b/lib/chef/knife/cookbook_download.rb @@ -87,7 +87,7 @@ class Chef ui.info("Downloading #{segment}") files.each do |segment_file| dest = File.join(basedir, segment_file["path"].gsub("/", File::SEPARATOR)) - Chef::Log.trace("Downloading #{segment_file['path']} to #{dest}") + Chef::Log.trace("Downloading #{segment_file["path"]} to #{dest}") FileUtils.mkdir_p(File.dirname(dest)) tempfile = rest.streaming_request(segment_file["url"]) FileUtils.mv(tempfile.path, dest) diff --git a/lib/chef/knife/cookbook_show.rb b/lib/chef/knife/cookbook_show.rb index d1e7220650..97e771a183 100644 --- a/lib/chef/knife/cookbook_show.rb +++ b/lib/chef/knife/cookbook_show.rb @@ -57,7 +57,7 @@ class Chef case @name_args.length when 4 # We are showing a specific file - node = Hash.new + node = {} node[:fqdn] = config[:fqdn] if config.key?(:fqdn) node[:platform] = config[:platform] if config.key?(:platform) node[:platform_version] = config[:platform_version] if config.key?(:platform_version) diff --git a/lib/chef/knife/cookbook_upload.rb b/lib/chef/knife/cookbook_upload.rb index 11736e6084..d73fa9ae68 100644 --- a/lib/chef/knife/cookbook_upload.rb +++ b/lib/chef/knife/cookbook_upload.rb @@ -92,7 +92,7 @@ class Chef # Get a list of cookbooks and their versions from the server # to check for the existence of a cookbook's dependencies. @server_side_cookbooks = Chef::CookbookVersion.list_all_versions - justify_width = @server_side_cookbooks.map { |name| name.size }.max.to_i + 2 + justify_width = @server_side_cookbooks.map(&:size).max.to_i + 2 if config[:all] cookbook_repo.load_cookbooks cookbooks_for_upload = [] @@ -154,7 +154,7 @@ class Chef upload_set = {} @name_args.each do |cookbook_name| begin - if ! upload_set.key?(cookbook_name) + unless upload_set.key?(cookbook_name) upload_set[cookbook_name] = cookbook_repo[cookbook_name] if config[:depends] upload_set[cookbook_name].metadata.dependencies.each_key { |dep| @name_args << dep } @@ -224,7 +224,7 @@ class Chef broken_filenames = Array(broken_files).map { |path, info| path } ui.error "The cookbook #{cookbook.name} has one or more broken files" ui.error "This is probably caused by broken symlinks in the cookbook directory" - ui.error "The broken file(s) are: #{broken_filenames.join(' ')}" + ui.error "The broken file(s) are: #{broken_filenames.join(" ")}" exit 1 end end @@ -240,7 +240,7 @@ class Chef missing_cookbook_names = missing_dependencies.map { |cookbook_name, version| "'#{cookbook_name}' version '#{version}'" } ui.error "Cookbook #{cookbook.name} depends on cookbooks which are not currently" ui.error "being uploaded and cannot be found on the server." - ui.error "The missing cookbook(s) are: #{missing_cookbook_names.join(', ')}" + ui.error "The missing cookbook(s) are: #{missing_cookbook_names.join(", ")}" exit 1 end end @@ -253,7 +253,7 @@ class Chef Log.debug "Versions of cookbook '#{cookbook_name}' returned by the server: #{versions.join(", ")}" @server_side_cookbooks[cookbook_name]["versions"].each do |versions_hash| if Chef::VersionConstraint.new(version).include?(versions_hash["version"]) - Log.debug "Matched cookbook '#{cookbook_name}' with constraint '#{version}' to cookbook version '#{versions_hash['version']}' on the server" + Log.debug "Matched cookbook '#{cookbook_name}' with constraint '#{version}' to cookbook version '#{versions_hash["version"]}' on the server" return true end end diff --git a/lib/chef/knife/core/bootstrap_context.rb b/lib/chef/knife/core/bootstrap_context.rb index fbe56031cb..49f0069ba6 100644 --- a/lib/chef/knife/core/bootstrap_context.rb +++ b/lib/chef/knife/core/bootstrap_context.rb @@ -96,7 +96,7 @@ class Chef client_rb << "chef_license \"#{@chef_config[:chef_license]}\"\n" end - if !(@chef_config[:config_log_level].nil? || @chef_config[:config_log_level].empty?) + unless @chef_config[:config_log_level].nil? || @chef_config[:config_log_level].empty? client_rb << %Q{log_level :#{@chef_config[:config_log_level]}\n} end diff --git a/lib/chef/knife/core/cookbook_scm_repo.rb b/lib/chef/knife/core/cookbook_scm_repo.rb index f97923d96b..62d4ef30c5 100644 --- a/lib/chef/knife/core/cookbook_scm_repo.rb +++ b/lib/chef/knife/core/cookbook_scm_repo.rb @@ -50,7 +50,7 @@ class Chef exit 1 end if use_current_branch - @default_branch = get_current_branch() + @default_branch = get_current_branch end unless branch_exists?(default_branch) ui.error "The default branch '#{default_branch}' does not exist" diff --git a/lib/chef/knife/core/gem_glob_loader.rb b/lib/chef/knife/core/gem_glob_loader.rb index 15707dee2e..8fe228b848 100644 --- a/lib/chef/knife/core/gem_glob_loader.rb +++ b/lib/chef/knife/core/gem_glob_loader.rb @@ -111,14 +111,14 @@ class Chef def check_spec_for_glob(spec, glob) dirs = if spec.require_paths.size > 1 - "{#{spec.require_paths.join(',')}}" + "{#{spec.require_paths.join(",")}}" else spec.require_paths.first end glob = File.join(Chef::Util::PathHelper.escape_glob_dir(spec.full_gem_path, dirs), glob) - Dir[glob].map { |f| f.untaint } + Dir[glob].map(&:untaint) end def from_different_chef_version?(path) diff --git a/lib/chef/knife/core/generic_presenter.rb b/lib/chef/knife/core/generic_presenter.rb index 96a4c766a5..90f529a3d9 100644 --- a/lib/chef/knife/core/generic_presenter.rb +++ b/lib/chef/knife/core/generic_presenter.rb @@ -201,13 +201,13 @@ class Chef end end # necessary (?) for coercing objects (the run_list object?) to hashes - ( !data.kind_of?(Array) && data.respond_to?(:to_hash) ) ? data.to_hash : data + ( !data.is_a?(Array) && data.respond_to?(:to_hash) ) ? data.to_hash : data end def format_cookbook_list_for_display(item) if config[:with_uri] item.inject({}) do |collected, (cookbook, versions)| - collected[cookbook] = Hash.new + collected[cookbook] = {} versions["versions"].each do |ver| collected[cookbook][ver["version"]] = ver["url"] end @@ -218,9 +218,9 @@ class Chef collected[cookbook] = versions["versions"].map { |v| v["version"] } collected end - key_length = versions_by_cookbook.empty? ? 0 : versions_by_cookbook.keys.map { |name| name.size }.max + 2 + key_length = versions_by_cookbook.empty? ? 0 : versions_by_cookbook.keys.map(&:size).max + 2 versions_by_cookbook.sort.map do |cookbook, versions| - "#{cookbook.ljust(key_length)} #{versions.join(' ')}" + "#{cookbook.ljust(key_length)} #{versions.join(" ")}" end end end diff --git a/lib/chef/knife/core/node_presenter.rb b/lib/chef/knife/core/node_presenter.rb index a77e9d7a65..258a4822fd 100644 --- a/lib/chef/knife/core/node_presenter.rb +++ b/lib/chef/knife/core/node_presenter.rb @@ -61,7 +61,7 @@ class Chef end def summarize_json(data) - if data.kind_of?(Chef::Node) + if data.is_a?(Chef::Node) node = data result = {} @@ -92,53 +92,53 @@ class Chef # the volume of output is adjusted accordingly. Uses colors if enabled # in the ui object. def summarize(data) - if data.kind_of?(Chef::Node) + if data.is_a?(Chef::Node) node = data # special case ec2 with their split horizon whatsis. ip = (node[:ec2] && node[:ec2][:public_ipv4]) || node[:ipaddress] summarized = <<~SUMMARY - #{ui.color('Node Name:', :bold)} #{ui.color(node.name, :bold)} + #{ui.color("Node Name:", :bold)} #{ui.color(node.name, :bold)} SUMMARY show_policy = !(node.policy_name.nil? && node.policy_group.nil?) if show_policy summarized << <<~POLICY - #{key('Policy Name:')} #{node.policy_name} - #{key('Policy Group:')} #{node.policy_group} + #{key("Policy Name:")} #{node.policy_name} + #{key("Policy Group:")} #{node.policy_group} POLICY else summarized << <<~ENV - #{key('Environment:')} #{node.chef_environment} + #{key("Environment:")} #{node.chef_environment} ENV end summarized << <<~SUMMARY - #{key('FQDN:')} #{node[:fqdn]} - #{key('IP:')} #{ip} - #{key('Run List:')} #{node.run_list} + #{key("FQDN:")} #{node[:fqdn]} + #{key("IP:")} #{ip} + #{key("Run List:")} #{node.run_list} SUMMARY unless show_policy summarized << <<~ROLES - #{key('Roles:')} #{Array(node[:roles]).join(', ')} + #{key("Roles:")} #{Array(node[:roles]).join(", ")} ROLES end summarized << <<~SUMMARY - #{key('Recipes:')} #{Array(node[:recipes]).join(', ')} - #{key('Platform:')} #{node[:platform]} #{node[:platform_version]} - #{key('Tags:')} #{node.tags.join(', ')} + #{key("Recipes:")} #{Array(node[:recipes]).join(", ")} + #{key("Platform:")} #{node[:platform]} #{node[:platform_version]} + #{key("Tags:")} #{node.tags.join(", ")} SUMMARY if config[:medium_output] || config[:long_output] summarized += <<~MORE - #{key('Attributes:')} + #{key("Attributes:")} #{text_format(node.normal_attrs)} MORE end if config[:long_output] summarized += <<~MOST - #{key('Default Attributes:')} + #{key("Default Attributes:")} #{text_format(node.default_attrs)} - #{key('Override Attributes:')} + #{key("Override Attributes:")} #{text_format(node.override_attrs)} - #{key('Automatic Attributes (Ohai Data):')} + #{key("Automatic Attributes (Ohai Data):")} #{text_format(node.automatic_attrs)} MOST end diff --git a/lib/chef/knife/core/object_loader.rb b/lib/chef/knife/core/object_loader.rb index 94b956be04..087213fadf 100644 --- a/lib/chef/knife/core/object_loader.rb +++ b/lib/chef/knife/core/object_loader.rb @@ -40,7 +40,7 @@ class Chef def load_from(repo_location, *components) unless object_file = find_file(repo_location, *components) - ui.error "Could not find or open file '#{components.last}' in current directory or in '#{repo_location}/#{components.join('/')}'" + ui.error "Could not find or open file '#{components.last}' in current directory or in '#{repo_location}/#{components.join("/")}'" exit 1 end object_from_file(object_file) diff --git a/lib/chef/knife/core/status_presenter.rb b/lib/chef/knife/core/status_presenter.rb index 820c572f1f..562bd7b0e9 100644 --- a/lib/chef/knife/core/status_presenter.rb +++ b/lib/chef/knife/core/status_presenter.rb @@ -108,13 +108,13 @@ class Chef end end - line_parts = Array.new + line_parts = [] if node["ohai_time"] hours, minutes, seconds = time_difference_in_hms(node["ohai_time"]) - hours_text = "#{hours} hour#{hours == 1 ? ' ' : 's'}" - minutes_text = "#{minutes} minute#{minutes == 1 ? ' ' : 's'}" - seconds_text = "#{seconds} second#{seconds == 1 ? ' ' : 's'}" + hours_text = "#{hours} hour#{hours == 1 ? " " : "s"}" + minutes_text = "#{minutes} minute#{minutes == 1 ? " " : "s"}" + seconds_text = "#{seconds} second#{seconds == 1 ? " " : "s"}" if hours > 24 color = :red text = hours_text @@ -140,7 +140,7 @@ class Chef if node["platform"] platform = node["platform"].dup if node["platform_version"] - platform << " #{node['platform_version']}" + platform << " #{node["platform_version"]}" end line_parts << platform end diff --git a/lib/chef/knife/core/subcommand_loader.rb b/lib/chef/knife/core/subcommand_loader.rb index f2dc06ce36..5b9474515a 100644 --- a/lib/chef/knife/core/subcommand_loader.rb +++ b/lib/chef/knife/core/subcommand_loader.rb @@ -82,6 +82,7 @@ class Chef # Load all the sub-commands def load_commands return true if @loaded + subcommand_files.each { |subcommand| Kernel.load subcommand } @loaded = true end diff --git a/lib/chef/knife/core/text_formatter.rb b/lib/chef/knife/core/text_formatter.rb index 8775e2e76f..e0df395545 100644 --- a/lib/chef/knife/core/text_formatter.rb +++ b/lib/chef/knife/core/text_formatter.rb @@ -28,7 +28,7 @@ class Chef @ui = ui @data = if data.respond_to?(:display_hash) data.display_hash - elsif data.kind_of?(Array) + elsif data.is_a?(Array) data elsif data.respond_to?(:to_hash) data.to_hash @@ -48,7 +48,7 @@ class Chef justify_width = data.keys.map { |k| k.to_s.size }.max.to_i + 1 data.sort.each do |key, value| # key: ['value'] should be printed as key: value - if value.kind_of?(Array) && value.size == 1 && is_singleton(value[0]) + if value.is_a?(Array) && value.size == 1 && is_singleton(value[0]) value = value[0] end if is_singleton(value) @@ -62,7 +62,7 @@ class Chef lines.each { |line| buffer << " #{line}\n" } end end - elsif data.kind_of?(Array) + elsif data.is_a?(Array) data.each_index do |index| item = data[index] buffer << text_format(data[index]) @@ -77,7 +77,7 @@ class Chef end def is_singleton(value) - !(value.kind_of?(Array) || value.respond_to?(:keys)) + !(value.is_a?(Array) || value.respond_to?(:keys)) end end end diff --git a/lib/chef/knife/core/ui.rb b/lib/chef/knife/core/ui.rb index 7961e1b523..41fb37c220 100644 --- a/lib/chef/knife/core/ui.rb +++ b/lib/chef/knife/core/ui.rb @@ -69,6 +69,7 @@ class Chef stdout.puts message rescue Errno::EPIPE => e raise e if @config[:verbosity] >= 2 + exit 0 end @@ -85,6 +86,7 @@ class Chef unless lines.empty? prefix, = first_line.split(":", 2) return if prefix.nil? + prefix_len = prefix.length prefix_len -= 9 if color? # prefix includes 9 bytes of color escape sequences prefix_len += 2 # include room to align to the ": " following PREFIX @@ -95,6 +97,7 @@ class Chef end rescue Errno::EPIPE => e raise e if @config[:verbosity] >= 2 + exit 0 end @@ -105,28 +108,28 @@ class Chef # # @param message [String] the text string def debug(message) - log("#{color('DEBUG:', :blue, :bold)} #{message}") + log("#{color("DEBUG:", :blue, :bold)} #{message}") end # Print a warning message # # @param message [String] the text string def warn(message) - log("#{color('WARNING:', :yellow, :bold)} #{message}") + log("#{color("WARNING:", :yellow, :bold)} #{message}") end # Print an error message # # @param message [String] the text string def error(message) - log("#{color('ERROR:', :red, :bold)} #{message}") + log("#{color("ERROR:", :red, :bold)} #{message}") end # Print a message describing a fatal error. # # @param message [String] the text string def fatal(message) - log("#{color('FATAL:', :red, :bold)} #{message}") + log("#{color("FATAL:", :red, :bold)} #{message}") end def color(string, *colors) @@ -186,6 +189,7 @@ class Chef stdout.puts data rescue Errno::EPIPE => e raise e if @config[:verbosity] >= 2 + exit 0 end @@ -199,7 +203,7 @@ class Chef def edit_data(data, parse_output = true, object_class: nil) output = Chef::JSONCompat.to_json_pretty(data) - if !config[:disable_editing] + unless config[:disable_editing] Tempfile.open([ "knife-edit-", ".json" ]) do |tf| tf.sync = true tf.puts output diff --git a/lib/chef/knife/data_bag_create.rb b/lib/chef/knife/data_bag_create.rb index 92ea981a2b..c520bba570 100644 --- a/lib/chef/knife/data_bag_create.rb +++ b/lib/chef/knife/data_bag_create.rb @@ -55,6 +55,7 @@ class Chef ui.info("Data bag #{@data_bag_name} already exists") rescue Net::HTTPClientException => e raise unless e.to_s =~ /^404/ + # if it doesn't exists, try to create it rest.post("data", { "name" => @data_bag_name }) ui.info("Created data_bag[#{@data_bag_name}]") diff --git a/lib/chef/knife/data_bag_from_file.rb b/lib/chef/knife/data_bag_from_file.rb index 050c9b404f..78cf2df3a5 100644 --- a/lib/chef/knife/data_bag_from_file.rb +++ b/lib/chef/knife/data_bag_from_file.rb @@ -98,7 +98,7 @@ class Chef end def normalize_item_paths(args) - paths = Array.new + paths = [] args.each do |path| if File.directory?(path) paths.concat(Dir.glob(File.join(Chef::Util::PathHelper.escape_glob_dir(path), "*.json"))) diff --git a/lib/chef/knife/deps.rb b/lib/chef/knife/deps.rb index bc4b853879..f620b53bfa 100644 --- a/lib/chef/knife/deps.rb +++ b/lib/chef/knife/deps.rb @@ -67,7 +67,7 @@ class Chef end def print_flattened_dependencies(entry, dependencies) - if !dependencies[entry.path] + unless dependencies[entry.path] dependencies[entry.path] = get_dependencies(entry) dependencies[entry.path].each do |child| child_entry = Chef::ChefFS::FileSystem.resolve_path(@root, child) @@ -78,8 +78,8 @@ class Chef end def print_dependencies_tree(entry, dependencies, printed = {}, depth = 0) - dependencies[entry.path] = get_dependencies(entry) if !dependencies[entry.path] - output "#{' ' * depth}#{format_path(entry)}" + dependencies[entry.path] = get_dependencies(entry) unless dependencies[entry.path] + output "#{" " * depth}#{format_path(entry)}" if !printed[entry.path] && (config[:recurse] || depth == 0) printed[entry.path] = true dependencies[entry.path].each do |child| @@ -97,7 +97,7 @@ class Chef node = Chef::JSONCompat.parse(entry.read) result = [] if node["chef_environment"] && node["chef_environment"] != "_default" - result << "/environments/#{node['chef_environment']}.json" + result << "/environments/#{node["chef_environment"]}.json" end if node["run_list"] result += dependencies_from_runlist(node["run_list"]) @@ -109,13 +109,13 @@ class Chef result = [] if role["run_list"] dependencies_from_runlist(role["run_list"]).each do |dependency| - result << dependency if !result.include?(dependency) + result << dependency unless result.include?(dependency) end end if role["env_run_lists"] role["env_run_lists"].each_pair do |env, run_list| dependencies_from_runlist(run_list).each do |dependency| - result << dependency if !result.include?(dependency) + result << dependency unless result.include?(dependency) end end end diff --git a/lib/chef/knife/edit.rb b/lib/chef/knife/edit.rb index 406782ef85..e1e9ee1b0d 100644 --- a/lib/chef/knife/edit.rb +++ b/lib/chef/knife/edit.rb @@ -66,14 +66,14 @@ class Chef end def edit_text(text, extension) - if !config[:disable_editing] + unless config[:disable_editing] Tempfile.open([ "knife-edit-", extension ]) do |file| # Write the text to a temporary file file.write(text) file.close # Let the user edit the temporary file - if !system("#{config[:editor]} #{file.path}") + unless system("#{config[:editor]} #{file.path}") raise "Please set EDITOR environment variable. See https://docs.chef.io/knife_setup.html for details." end diff --git a/lib/chef/knife/environment_compare.rb b/lib/chef/knife/environment_compare.rb index b00fc4fc3b..38e259a856 100644 --- a/lib/chef/knife/environment_compare.rb +++ b/lib/chef/knife/environment_compare.rb @@ -109,6 +109,7 @@ class Chef environments.each { |n| total << constraints[n][c] } if total.uniq.count == 1 next if config[:mismatch] + color = :white else color = :yellow diff --git a/lib/chef/knife/key_list.rb b/lib/chef/knife/key_list.rb index 5295238f6f..2ffafc63ed 100644 --- a/lib/chef/knife/key_list.rb +++ b/lib/chef/knife/key_list.rb @@ -70,7 +70,8 @@ class Chef keys.each do |key| next if !key["expired"] && @config[:only_expired] next if key["expired"] && @config[:only_non_expired] - display = "#{colorize(key['name'].ljust(max_length))} #{key['uri']}" + + display = "#{colorize(key["name"].ljust(max_length))} #{key["uri"]}" display = "#{display} (expired)" if key["expired"] display_info(display) end @@ -78,6 +79,7 @@ class Chef keys.each do |key| next if !key["expired"] && @config[:only_expired] next if key["expired"] && @config[:only_non_expired] + display_info(key["name"]) end end diff --git a/lib/chef/knife/list.rb b/lib/chef/knife/list.rb index 08bb73e489..e5e196ecea 100644 --- a/lib/chef/knife/list.rb +++ b/lib/chef/knife/list.rb @@ -77,7 +77,7 @@ class Chef # Process directories if !config[:bare_directories] - dir_results = parallelize(all_results.select { |result| result.dir? }) do |result| + dir_results = parallelize(all_results.select(&:dir?)) do |result| add_dir_result(result) end.flatten(1) @@ -97,7 +97,7 @@ class Chef end # Sort by path for happy output - results = results.sort_by { |result| result.path } + results = results.sort_by(&:path) dir_results = dir_results.sort_by { |result| result[0].path } # Print! @@ -123,7 +123,7 @@ class Chef def add_dir_result(result) begin - children = result.children.sort_by { |child| child.name } + children = result.children.sort_by(&:name) rescue Chef::ChefFS::FileSystem::NotFoundError => e ui.error "#{format_path(e.entry)}: No such file or directory" return [] @@ -131,7 +131,7 @@ class Chef result = [ [ result, children ] ] if config[:recursive] - child_dirs = children.select { |child| child.dir? } + child_dirs = children.select(&:dir?) result += parallelize(child_dirs) { |child| add_dir_result(child) }.flatten(1).to_a end result @@ -144,7 +144,7 @@ class Chef def print_results(results, indent) return if results.length == 0 - print_space = results.map { |result| result.length }.max + 2 + print_space = results.map(&:length).max + 2 if config[:one_column] || !stdout.isatty columns = 0 else diff --git a/lib/chef/knife/node_bulk_delete.rb b/lib/chef/knife/node_bulk_delete.rb index 04d19648d2..030260b944 100644 --- a/lib/chef/knife/node_bulk_delete.rb +++ b/lib/chef/knife/node_bulk_delete.rb @@ -40,6 +40,7 @@ class Chef all_nodes.each do |name, node| next unless name =~ matcher + nodes_to_delete[name] = node end diff --git a/lib/chef/knife/node_edit.rb b/lib/chef/knife/node_edit.rb index d0b9239e28..ca3b54c2a5 100644 --- a/lib/chef/knife/node_edit.rb +++ b/lib/chef/knife/node_edit.rb @@ -46,7 +46,7 @@ class Chef updated_node = node_editor.edit_node if updated_values = node_editor.updated? - ui.info "Saving updated #{updated_values.join(', ')} on node #{node.name}" + ui.info "Saving updated #{updated_values.join(", ")} on node #{node.name}" updated_node.save else ui.info "Node not updated, skipping node save" diff --git a/lib/chef/knife/node_run_list_add.rb b/lib/chef/knife/node_run_list_add.rb index b8d7dc0b99..9b50e2483a 100644 --- a/lib/chef/knife/node_run_list_add.rb +++ b/lib/chef/knife/node_run_list_add.rb @@ -44,11 +44,11 @@ class Chef if @name_args.size > 2 # Check for nested lists and create a single plain one entries = @name_args[1..-1].map do |entry| - entry.split(",").map { |e| e.strip } + entry.split(",").map(&:strip) end.flatten else # Convert to array and remove the extra spaces - entries = @name_args[1].split(",").map { |e| e.strip } + entries = @name_args[1].split(",").map(&:strip) end if config[:after] && config[:before] diff --git a/lib/chef/knife/node_run_list_remove.rb b/lib/chef/knife/node_run_list_remove.rb index 2c8aa78929..36c98a724b 100644 --- a/lib/chef/knife/node_run_list_remove.rb +++ b/lib/chef/knife/node_run_list_remove.rb @@ -35,11 +35,11 @@ class Chef if @name_args.size > 2 # Check for nested lists and create a single plain one entries = @name_args[1..-1].map do |entry| - entry.split(",").map { |e| e.strip } + entry.split(",").map(&:strip) end.flatten else # Convert to array and remove the extra spaces - entries = @name_args[1].split(",").map { |e| e.strip } + entries = @name_args[1].split(",").map(&:strip) end # iterate over the list of things to remove, diff --git a/lib/chef/knife/node_run_list_set.rb b/lib/chef/knife/node_run_list_set.rb index c2dd987864..eae05003ff 100644 --- a/lib/chef/knife/node_run_list_set.rb +++ b/lib/chef/knife/node_run_list_set.rb @@ -37,11 +37,11 @@ class Chef elsif @name_args.size > 2 # Check for nested lists and create a single plain one entries = @name_args[1..-1].map do |entry| - entry.split(",").map { |e| e.strip } + entry.split(",").map(&:strip) end.flatten else # Convert to array and remove the extra spaces - entries = @name_args[1].split(",").map { |e| e.strip } + entries = @name_args[1].split(",").map(&:strip) end node = Chef::Node.load(@name_args[0]) diff --git a/lib/chef/knife/null.rb b/lib/chef/knife/null.rb index d3abbea4e9..7221eee9f5 100644 --- a/lib/chef/knife/null.rb +++ b/lib/chef/knife/null.rb @@ -6,8 +6,7 @@ class Chef # setting the category to deprecated keeps it out of help category "deprecated" - def run - end + def run; end end end end diff --git a/lib/chef/knife/role_bulk_delete.rb b/lib/chef/knife/role_bulk_delete.rb index 7e5fafb26b..1277c966be 100644 --- a/lib/chef/knife/role_bulk_delete.rb +++ b/lib/chef/knife/role_bulk_delete.rb @@ -41,6 +41,7 @@ class Chef roles_to_delete = {} all_roles.each do |name, role| next unless name =~ matcher + roles_to_delete[role.name] = role end diff --git a/lib/chef/knife/role_env_run_list_add.rb b/lib/chef/knife/role_env_run_list_add.rb index 997fccff42..8f6a5cadba 100644 --- a/lib/chef/knife/role_env_run_list_add.rb +++ b/lib/chef/knife/role_env_run_list_add.rb @@ -69,11 +69,11 @@ class Chef if @name_args.size > 2 # Check for nested lists and create a single plain one entries = @name_args[2..-1].map do |entry| - entry.split(",").map { |e| e.strip } + entry.split(",").map(&:strip) end.flatten else # Convert to array and remove the extra spaces - entries = @name_args[2].split(",").map { |e| e.strip } + entries = @name_args[2].split(",").map(&:strip) end add_to_env_run_list(role, environment, entries, config[:after]) diff --git a/lib/chef/knife/role_env_run_list_set.rb b/lib/chef/knife/role_env_run_list_set.rb index 4f79d50cc2..084bc02aff 100644 --- a/lib/chef/knife/role_env_run_list_set.rb +++ b/lib/chef/knife/role_env_run_list_set.rb @@ -52,11 +52,11 @@ class Chef elsif @name_args.size > 2 # Check for nested lists and create a single plain one entries = @name_args[2..-1].map do |entry| - entry.split(",").map { |e| e.strip } + entry.split(",").map(&:strip) end.flatten else # Convert to array and remove the extra spaces - entries = @name_args[2].split(",").map { |e| e.strip } + entries = @name_args[2].split(",").map(&:strip) end set_env_run_list(role, environment, entries ) diff --git a/lib/chef/knife/role_run_list_add.rb b/lib/chef/knife/role_run_list_add.rb index ff0addbcfe..3c4961cbe1 100644 --- a/lib/chef/knife/role_run_list_add.rb +++ b/lib/chef/knife/role_run_list_add.rb @@ -69,11 +69,11 @@ class Chef if @name_args.size > 1 # Check for nested lists and create a single plain one entries = @name_args[1..-1].map do |entry| - entry.split(",").map { |e| e.strip } + entry.split(",").map(&:strip) end.flatten else # Convert to array and remove the extra spaces - entries = @name_args[1].split(",").map { |e| e.strip } + entries = @name_args[1].split(",").map(&:strip) end add_to_env_run_list(role, environment, entries, config[:after]) diff --git a/lib/chef/knife/role_run_list_set.rb b/lib/chef/knife/role_run_list_set.rb index 447ce145b8..7302797c33 100644 --- a/lib/chef/knife/role_run_list_set.rb +++ b/lib/chef/knife/role_run_list_set.rb @@ -51,11 +51,11 @@ class Chef elsif @name_args.size > 1 # Check for nested lists and create a single plain one entries = @name_args[1..-1].map do |entry| - entry.split(",").map { |e| e.strip } + entry.split(",").map(&:strip) end.flatten else # Convert to array and remove the extra spaces - entries = @name_args[1].split(",").map { |e| e.strip } + entries = @name_args[1].split(",").map(&:strip) end set_env_run_list(role, environment, entries ) diff --git a/lib/chef/knife/search.rb b/lib/chef/knife/search.rb index b2aa7b5dc9..a089ee8f1b 100644 --- a/lib/chef/knife/search.rb +++ b/lib/chef/knife/search.rb @@ -83,7 +83,7 @@ class Chef result_items = [] result_count = 0 - search_args = Hash.new + search_args = {} search_args[:fuzz] = true search_args[:start] = config[:start] if config[:start] search_args[:rows] = config[:rows] if config[:rows] @@ -97,7 +97,7 @@ class Chef begin q.search(@type, @query, search_args) do |item| - formatted_item = Hash.new + formatted_item = {} if config[:id_only] formatted_item = format_for_display({ "id" => item["__display_name"] }) elsif item.is_a?(Hash) @@ -169,7 +169,7 @@ class Chef # and the path is an array with the path elements as strings (in order) # See lib/chef/search/query.rb for more examples of this. def create_result_filter(filter_string) - final_filter = Hash.new + final_filter = {} filter_string.delete!(" ") filters = filter_string.split(",") filters.each do |f| @@ -180,7 +180,7 @@ class Chef end def create_result_filter_from_attributes(filter_array) - final_filter = Hash.new + final_filter = {} filter_array.each do |f| final_filter[f] = f.split(".") end diff --git a/lib/chef/knife/ssh.rb b/lib/chef/knife/ssh.rb index e979002c75..2a4334570e 100644 --- a/lib/chef/knife/ssh.rb +++ b/lib/chef/knife/ssh.rb @@ -185,8 +185,8 @@ class Chef if fqdns.count != fqdns.uniq.count duplicated_fqdns = fqdns.uniq ui.send(config[:duplicated_fqdns], - "SSH #{duplicated_fqdns.count > 1 ? 'nodes are' : 'node is'} " + - "duplicated: #{duplicated_fqdns.join(',')}") + "SSH #{duplicated_fqdns.count > 1 ? "nodes are" : "node is"} " + + "duplicated: #{duplicated_fqdns.join(",")}") exit 10 if config[:duplicated_fqdns] == :fatal end end @@ -225,7 +225,7 @@ class Chef end def search_nodes - list = Array.new + list = [] query = Chef::Search::Query.new required_attributes = { fqdn: ["fqdn"], cloud: ["cloud"] } @@ -245,10 +245,12 @@ class Chef # we should skip the loop to next iteration if the item # returned by the search is nil next if item.nil? + # next if we couldn't find the specified attribute in the # returned node object host = get_ssh_attribute(item) next if host.nil? + prefix = get_prefix_attribute(item) ssh_port = item.dig("cloud", "public_ssh_port") srv = [host, ssh_port, prefix] @@ -288,7 +290,7 @@ class Chef port ||= ssh_config[:port] opts[:port] = port unless port.nil? opts[:logger] = Chef::Log.with_child(subsystem: "net/ssh") if Chef::Log.level == :trace - if !config[:host_key_verify] + unless config[:host_key_verify] opts[:verify_host_key] = false opts[:user_known_hosts_file] = "/dev/null" end @@ -358,11 +360,12 @@ class Chef command.force_encoding("binary") if command.respond_to?(:force_encoding) subsession.open_channel do |chan| if config[:on_error] && exit_status != 0 - chan.close() + chan.close else chan.request_pty chan.exec command do |ch, success| raise ArgumentError, "Cannot execute #{command}" unless success + ch.on_data do |ichannel, data| print_data(ichannel.connection[:prefix], data) if data =~ /^knife sudo password: / @@ -394,7 +397,7 @@ class Chef # line is input. def read_line loop do - command = reader.readline("#{ui.color('knife-ssh>', :bold)} ", true) + command = reader.readline("#{ui.color("knife-ssh>", :bold)} ", true) if command.nil? command = "exit" @@ -430,7 +433,7 @@ class Chef break when /^on (.+?); (.+)$/ raw_list = $1.split(" ") - server_list = Array.new + server_list = [] session.servers.each do |session_server| server_list << session_server if raw_list.include?(session_server.host) end @@ -483,7 +486,7 @@ class Chef end.join(" \\; ") end - tmux_name = "'knife ssh #{@name_args[0].tr(':.', '=-')}'" + tmux_name = "'knife ssh #{@name_args[0].tr(":.", "=-")}'" begin server = session.servers_for.first cmd = ["tmux new-session -d -s #{tmux_name}", @@ -545,6 +548,7 @@ class Chef def get_stripped_unfrozen_value(value) return nil if value.nil? + value.strip end @@ -594,7 +598,7 @@ class Chef @password = config[:ssh_password] if config[:ssh_password] # If a password was not given, check for SSH identity file. - if !@password + unless @password configure_ssh_identity_file configure_ssh_gateway_identity end diff --git a/lib/chef/knife/supermarket_download.rb b/lib/chef/knife/supermarket_download.rb index b48126151f..8bd7b90add 100644 --- a/lib/chef/knife/supermarket_download.rb +++ b/lib/chef/knife/supermarket_download.rb @@ -115,7 +115,7 @@ class Chef end def specific_cookbook_version_url - "#{cookbooks_api_url}/#{@name_args[0]}/versions/#{@name_args[1].tr('.', '_')}" + "#{cookbooks_api_url}/#{@name_args[0]}/versions/#{@name_args[1].tr(".", "_")}" end end end diff --git a/lib/chef/knife/supermarket_list.rb b/lib/chef/knife/supermarket_list.rb index ee0ed0b54c..700d928af8 100644 --- a/lib/chef/knife/supermarket_list.rb +++ b/lib/chef/knife/supermarket_list.rb @@ -39,7 +39,7 @@ class Chef def run if config[:with_uri] - cookbooks = Hash.new + cookbooks = {} get_cookbook_list.each { |k, v| cookbooks[k] = v["cookbook"] } ui.output(format_for_display(cookbooks)) else diff --git a/lib/chef/knife/supermarket_share.rb b/lib/chef/knife/supermarket_share.rb index f0c0970f9d..f178b4ab35 100644 --- a/lib/chef/knife/supermarket_share.rb +++ b/lib/chef/knife/supermarket_share.rb @@ -113,7 +113,8 @@ class Chef data = noauth_rest.get("#{config[:supermarket_site]}/api/v1/cookbooks/#{@name_args[0]}") data["category"] rescue => e - return "Other" if e.kind_of?(Net::HTTPClientException) && e.response.code == "404" + return "Other" if e.is_a?(Net::HTTPClientException) && e.response.code == "404" + ui.fatal("Unable to reach Supermarket: #{e.message}. Increase log verbosity (-VV) for more information.") Chef::Log.trace("\n#{e.backtrace.join("\n")}") exit(1) @@ -149,7 +150,7 @@ class Chef end def tar_cmd - if !@tar_cmd + unless @tar_cmd @tar_cmd = "tar" begin # Unix and Mac only - prefer gnutar diff --git a/lib/chef/knife/supermarket_show.rb b/lib/chef/knife/supermarket_show.rb index c3f0628029..8ef00fca2b 100644 --- a/lib/chef/knife/supermarket_show.rb +++ b/lib/chef/knife/supermarket_show.rb @@ -45,7 +45,7 @@ class Chef when 1 noauth_rest.get("#{supermarket_uri}/cookbooks/#{@name_args[0]}") when 2 - noauth_rest.get("#{supermarket_uri}/cookbooks/#{@name_args[0]}/versions/#{name_args[1].tr('.', '_')}") + noauth_rest.get("#{supermarket_uri}/cookbooks/#{@name_args[0]}/versions/#{name_args[1].tr(".", "_")}") end end diff --git a/lib/chef/knife/supermarket_unshare.rb b/lib/chef/knife/supermarket_unshare.rb index acdcf53f85..352d34fdb1 100644 --- a/lib/chef/knife/supermarket_unshare.rb +++ b/lib/chef/knife/supermarket_unshare.rb @@ -50,6 +50,7 @@ class Chef rest.delete "#{config[:supermarket_site]}/api/v1/cookbooks/#{@name_args[0]}" rescue Net::HTTPClientException => e raise e unless e.message =~ /Forbidden/ + ui.error "Forbidden: You must be the maintainer of #{@cookbook_name} to unshare it." exit 1 end diff --git a/lib/chef/knife/tag_delete.rb b/lib/chef/knife/tag_delete.rb index e7e6e21a38..1c9f2185d7 100644 --- a/lib/chef/knife/tag_delete.rb +++ b/lib/chef/knife/tag_delete.rb @@ -41,7 +41,7 @@ class Chef end node = Chef::Node.load name - deleted_tags = Array.new + deleted_tags = [] tags.each do |tag| unless node.tags.delete(tag).nil? deleted_tags << tag diff --git a/lib/chef/knife/xargs.rb b/lib/chef/knife/xargs.rb index a8ec99920b..13135ba47c 100644 --- a/lib/chef/knife/xargs.rb +++ b/lib/chef/knife/xargs.rb @@ -183,7 +183,7 @@ class Chef end # Create the command - paths = tempfiles.keys.map { |tempfile| tempfile.path }.join(" ") + paths = tempfiles.keys.map(&:path).join(" ") if config[:replace_all] final_command = command.gsub(config[:replace_all], paths) elsif config[:replace_first] @@ -197,7 +197,7 @@ class Chef def destroy_tempfiles(tempfiles) # Unlink the files now that we're done with them - tempfiles.each_key { |tempfile| tempfile.close! } + tempfiles.each_key(&:close!) end def xargs_files(command, tempfiles) diff --git a/lib/chef/log/syslog.rb b/lib/chef/log/syslog.rb index 7e63bbb553..80efb8ab93 100644 --- a/lib/chef/log/syslog.rb +++ b/lib/chef/log/syslog.rb @@ -36,11 +36,11 @@ class Chef def initialize(program_name = "#{Chef::Dist::CLIENT}", facility = ::Syslog::LOG_DAEMON, logopts = nil) super return if defined? ::Logger::Syslog::SYSLOG + ::Logger::Syslog.const_set :SYSLOG, SYSLOG end - def close - end + def close; end end end end diff --git a/lib/chef/log/winevt.rb b/lib/chef/log/winevt.rb index 4affef78a3..dcc13a77e4 100644 --- a/lib/chef/log/winevt.rb +++ b/lib/chef/log/winevt.rb @@ -47,8 +47,7 @@ class Chef @eventlog = eventlog || ::Win32::EventLog.open("Application") end - def close - end + def close; end def info(msg) @eventlog.report_event( diff --git a/lib/chef/mash.rb b/lib/chef/mash.rb index 8b9e115dd1..404d6d622f 100644 --- a/lib/chef/mash.rb +++ b/lib/chef/mash.rb @@ -72,7 +72,7 @@ class Mash < Hash super # Handle nested values each do |k, v| - if v.kind_of?(Mash) || v.is_a?(Array) + if v.is_a?(Mash) || v.is_a?(Array) self[k] = v.dup end end @@ -210,7 +210,7 @@ class Mash < Hash # # @api private def convert_key(key) - key.kind_of?(Symbol) ? key.to_s : key + key.is_a?(Symbol) ? key.to_s : key end # @param value<Object> The value to convert. diff --git a/lib/chef/mixin/api_version_request_handling.rb b/lib/chef/mixin/api_version_request_handling.rb index a4e657ac9e..c2f7a3203f 100644 --- a/lib/chef/mixin/api_version_request_handling.rb +++ b/lib/chef/mixin/api_version_request_handling.rb @@ -35,7 +35,7 @@ class Chef return nil if exception.response.code != "406" || exception.response["x-ops-server-api-version"].nil? # intersection of versions the server and client support, will be of length zero if no intersection - server_supported_client_versions = Array.new + server_supported_client_versions = [] header = Chef::JSONCompat.from_json(exception.response["x-ops-server-api-version"]) min_server_version = Integer(header["min_version"]) diff --git a/lib/chef/mixin/checksum.rb b/lib/chef/mixin/checksum.rb index 5394c5ea48..6b9dfa4b5f 100644 --- a/lib/chef/mixin/checksum.rb +++ b/lib/chef/mixin/checksum.rb @@ -29,6 +29,7 @@ class Chef def short_cksum(checksum) return "none" if checksum.nil? + checksum.slice(0, 6) end diff --git a/lib/chef/mixin/convert_to_class_name.rb b/lib/chef/mixin/convert_to_class_name.rb index d6bd8a4ea7..c5944c3985 100644 --- a/lib/chef/mixin/convert_to_class_name.rb +++ b/lib/chef/mixin/convert_to_class_name.rb @@ -25,7 +25,7 @@ class Chef def convert_to_class_name(str) str = normalize_snake_case_name(str) rname = nil - regexp = %r{^(.+?)(_(.+))?$} + regexp = /^(.+?)(_(.+))?$/ mn = str.match(regexp) if mn @@ -112,6 +112,7 @@ class Chef constant = constant.ancestors.inject do |const, ancestor| break const if ancestor == Object break ancestor if ancestor.const_defined?(name, false) + const end diff --git a/lib/chef/mixin/create_path.rb b/lib/chef/mixin/create_path.rb index 455110b1a2..78cf71af0b 100644 --- a/lib/chef/mixin/create_path.rb +++ b/lib/chef/mixin/create_path.rb @@ -29,11 +29,11 @@ class Chef # === Returns # The created file_path. def create_path(file_path) - unless file_path.kind_of?(String) || file_path.kind_of?(Array) + unless file_path.is_a?(String) || file_path.is_a?(Array) raise ArgumentError, "file_path must be a string or an array!" end - if file_path.kind_of?(String) + if file_path.is_a?(String) file_path = File.expand_path(file_path).split(File::SEPARATOR) file_path.shift if file_path[0] == "" # Check if path starts with a separator or drive letter (Windows) diff --git a/lib/chef/mixin/deep_merge.rb b/lib/chef/mixin/deep_merge.rb index 1ecd00eb2d..4f400b7595 100644 --- a/lib/chef/mixin/deep_merge.rb +++ b/lib/chef/mixin/deep_merge.rb @@ -30,8 +30,8 @@ class Chef extend self def merge(first, second) - first = Mash.new(first) unless first.kind_of?(Mash) - second = Mash.new(second) unless second.kind_of?(Mash) + first = Mash.new(first) unless first.is_a?(Mash) + second = Mash.new(second) unless second.is_a?(Mash) DeepMerge.deep_merge(second, first) end @@ -62,7 +62,7 @@ class Chef when nil dest when Hash - if dest.kind_of?(Hash) + if dest.is_a?(Hash) source.each do |src_key, src_value| if dest.key?(src_key) dest[src_key] = deep_merge!(src_value, dest[src_key]) @@ -74,7 +74,7 @@ class Chef dest = source end when Array - if dest.kind_of?(Array) + if dest.is_a?(Array) dest |= source else dest = source @@ -103,7 +103,7 @@ class Chef # values when there is a conflict. def hash_only_merge!(merge_onto, merge_with) # If there are two Hashes, recursively merge. - if merge_onto.kind_of?(Hash) && merge_with.kind_of?(Hash) + if merge_onto.is_a?(Hash) && merge_with.is_a?(Hash) merge_with.each do |key, merge_with_value| value = if merge_onto.key?(key) diff --git a/lib/chef/mixin/get_source_from_package.rb b/lib/chef/mixin/get_source_from_package.rb index 832f96064d..9aafcc6ae4 100644 --- a/lib/chef/mixin/get_source_from_package.rb +++ b/lib/chef/mixin/get_source_from_package.rb @@ -35,6 +35,7 @@ class Chef def initialize(new_resource, run_context) super 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.exist?(new_resource.package_name) diff --git a/lib/chef/mixin/homebrew_user.rb b/lib/chef/mixin/homebrew_user.rb index 82dbb36f6c..bf608b539b 100644 --- a/lib/chef/mixin/homebrew_user.rb +++ b/lib/chef/mixin/homebrew_user.rb @@ -40,6 +40,7 @@ class Chef # They could provide us a user name or a UID if provided_user return provided_user if provided_user.is_a? Integer + return Etc.getpwnam(provided_user).uid end diff --git a/lib/chef/mixin/openssl_helper.rb b/lib/chef/mixin/openssl_helper.rb index 2312d606ad..5a4bd6077a 100644 --- a/lib/chef/mixin/openssl_helper.rb +++ b/lib/chef/mixin/openssl_helper.rb @@ -46,6 +46,7 @@ class Chef # Check if the dhparam.pem file exists # Verify the dhparam.pem file contains a key return false unless ::File.exist?(dhparam_pem_path) + dhparam = ::OpenSSL::PKey::DH.new File.read(dhparam_pem_path) dhparam.params_ok? end @@ -158,6 +159,7 @@ class Chef def gen_ec_priv_key(curve) raise TypeError, "curve must be a string" unless curve.is_a?(String) raise ArgumentError, "Specified curve is not available on this system" unless curve == "prime256v1" || curve == "secp384r1" || curve == "secp521r1" + ::OpenSSL::PKey::EC.new(curve).generate_key end @@ -262,7 +264,7 @@ class Chef cert = ::OpenSSL::X509::Certificate.new ef = ::OpenSSL::X509::ExtensionFactory.new - cert.serial = gen_serial() + cert.serial = gen_serial cert.version = 2 cert.subject = request.subject cert.public_key = request.public_key @@ -275,6 +277,7 @@ class Chef extension << ef.create_extension("basicConstraints", "CA:TRUE", true) else raise TypeError, "info['issuer'] must be a Ruby OpenSSL::X509::Certificate object" unless info["issuer"].is_a?(::OpenSSL::X509::Certificate) + cert.issuer = info["issuer"].subject ef.issuer_certificate = info["issuer"] end @@ -325,6 +328,7 @@ class Chef # @return [Integer] def get_next_crl_number(crl) raise TypeError, "crl must be a Ruby OpenSSL::X509::CRL object" unless crl.is_a?(::OpenSSL::X509::CRL) + crlnum = 1 crl.extensions.each do |e| crlnum = e.value if e.oid == "crlNumber" diff --git a/lib/chef/mixin/params_validate.rb b/lib/chef/mixin/params_validate.rb index 0f18eb4f54..0bf3543fbf 100644 --- a/lib/chef/mixin/params_validate.rb +++ b/lib/chef/mixin/params_validate.rb @@ -90,13 +90,13 @@ class Chef # looking for _pv_:symbol as methods. Assuming it find them, it calls the right # one. #++ - raise ArgumentError, "Options must be a hash" unless opts.kind_of?(Hash) - raise ArgumentError, "Validation Map must be a hash" unless map.kind_of?(Hash) + raise ArgumentError, "Options must be a hash" unless opts.is_a?(Hash) + raise ArgumentError, "Validation Map must be a hash" unless map.is_a?(Hash) @validation_message ||= {} map.each do |key, validation| - unless key.kind_of?(Symbol) || key.kind_of?(String) + unless key.is_a?(Symbol) || key.is_a?(String) raise ArgumentError, "Validation map keys must be symbols or strings!" end @@ -151,6 +151,7 @@ class Chef if is_required return true if opts.key?(key.to_s) && (explicitly_allows_nil || !opts[key.to_s].nil?) return true if opts.key?(key.to_sym) && (explicitly_allows_nil || !opts[key.to_sym].nil?) + raise Exceptions::ValidationFailed, _validation_message(key, "Required argument #{key.inspect} is missing!") end true @@ -176,7 +177,7 @@ class Chef end # Ruby will print :something as something, which confuses users so make sure to print them as symbols # by inspecting the value instead of just printing it - raise Exceptions::ValidationFailed, _validation_message(key, "Option #{key} must be equal to one of: #{to_be.map { |v| v.inspect }.join(", ")}! You passed #{value.inspect}.") + raise Exceptions::ValidationFailed, _validation_message(key, "Option #{key} must be equal to one of: #{to_be.map(&:inspect).join(", ")}! You passed #{value.inspect}.") end end @@ -193,7 +194,7 @@ class Chef unless value.nil? to_be = Array(to_be) to_be.each do |tb| - return true if value.kind_of?(tb) + return true if value.is_a?(tb) end raise Exceptions::ValidationFailed, _validation_message(key, "Option #{key} must be a kind of #{to_be}! You passed #{value.inspect}.") end @@ -236,7 +237,7 @@ class Chef # def _pv_cannot_be(opts, key, predicate_method_base_name) value = _pv_opts_lookup(opts, key) - if !value.nil? + unless value.nil? Array(predicate_method_base_name).each do |method_name| predicate_method = :"#{method_name}?" @@ -278,7 +279,7 @@ class Chef def _pv_default(opts, key, default_value) value = _pv_opts_lookup(opts, key) if value.nil? - default_value = default_value.freeze if !default_value.is_a?(DelayedEvaluator) + default_value = default_value.freeze unless default_value.is_a?(DelayedEvaluator) opts[key] = default_value end end @@ -298,7 +299,7 @@ class Chef # def _pv_regex(opts, key, regex) value = _pv_opts_lookup(opts, key) - if !value.nil? + unless value.nil? Array(regex).flatten.each do |r| return true if r.match(value.to_s) end @@ -319,9 +320,10 @@ class Chef # ``` # def _pv_callbacks(opts, key, callbacks) - raise ArgumentError, "Callback list must be a hash!" unless callbacks.kind_of?(Hash) + raise ArgumentError, "Callback list must be a hash!" unless callbacks.is_a?(Hash) + value = _pv_opts_lookup(opts, key) - if !value.nil? + unless value.nil? callbacks.each do |message, zeproc| unless zeproc.call(value) raise Exceptions::ValidationFailed, _validation_message(key, "Option #{key}'s value #{value} #{message}!") @@ -342,6 +344,7 @@ class Chef if is_name_property if opts[key].nil? raise Exceptions::CannotValidateStaticallyError, "name_property cannot be evaluated without a resource." if self == Chef::Mixin::ParamsValidate + opts[key] = instance_variable_get(:"@name") end end @@ -407,6 +410,7 @@ class Chef # def _pv_is(opts, key, to_be) return true if !opts.key?(key.to_s) && !opts.key?(key.to_sym) + value = _pv_opts_lookup(opts, key) to_be = [ to_be ].flatten(1) errors = [] @@ -414,6 +418,7 @@ class Chef case tb when Proc raise Exceptions::CannotValidateStaticallyError, "is: proc { } must be evaluated once for each resource" if self == Chef::Mixin::ParamsValidate + instance_exec(value, &tb) when Property begin @@ -422,6 +427,7 @@ class Chef rescue Exceptions::ValidationFailed # re-raise immediately if there is only one "is" so we get a better stack raise if to_be.size == 1 + errors << $! false end @@ -432,7 +438,7 @@ class Chef if passed true else - message = "Property #{key} must be one of: #{to_be.map { |v| v.inspect }.join(", ")}! You passed #{value.inspect}." + message = "Property #{key} must be one of: #{to_be.map(&:inspect).join(", ")}! You passed #{value.inspect}." unless errors.empty? message << " Errors:\n#{errors.map { |m| "- #{m}" }.join("\n")}" end @@ -458,9 +464,11 @@ class Chef def _pv_coerce(opts, key, coercer) if opts.key?(key.to_s) raise Exceptions::CannotValidateStaticallyError, "coerce must be evaluated for each resource." if self == Chef::Mixin::ParamsValidate + opts[key.to_s] = instance_exec(opts[key], &coercer) elsif opts.key?(key.to_sym) raise Exceptions::CannotValidateStaticallyError, "coerce must be evaluated for each resource." if self == Chef::Mixin::ParamsValidate + opts[key.to_sym] = instance_exec(opts[key], &coercer) end end @@ -478,7 +486,7 @@ class Chef def get(resource, nil_set: false) value = super # All values are sticky, frozen or not - if !is_set?(resource) + unless is_set?(resource) set_value(resource, value) end value diff --git a/lib/chef/mixin/powershell_out.rb b/lib/chef/mixin/powershell_out.rb index 3ef4cd84cc..1baece5527 100644 --- a/lib/chef/mixin/powershell_out.rb +++ b/lib/chef/mixin/powershell_out.rb @@ -91,7 +91,7 @@ class Chef "-InputFormat None", ] - "powershell.exe #{flags.join(' ')} -Command \"#{script.gsub('"', '\"')}\"" + "powershell.exe #{flags.join(" ")} -Command \"#{script.gsub('"', '\"')}\"" end end end diff --git a/lib/chef/mixin/powershell_type_coercions.rb b/lib/chef/mixin/powershell_type_coercions.rb index 792ec18842..a75022c771 100644 --- a/lib/chef/mixin/powershell_type_coercions.rb +++ b/lib/chef/mixin/powershell_type_coercions.rb @@ -52,14 +52,14 @@ class Chef translated = x.inject([]) do |memo, (k, v)| memo << "#{k}=#{translate_type(v)}" end - "@{#{translated.join(';')}}" + "@{#{translated.join(";")}}" end def translate_array(x) translated = x.map do |v| translate_type(v) end - "@(#{translated.join(',')})" + "@(#{translated.join(",")})" end def unsafe?(s) diff --git a/lib/chef/mixin/properties.rb b/lib/chef/mixin/properties.rb index 03ee1d66cc..ecb589e015 100644 --- a/lib/chef/mixin/properties.rb +++ b/lib/chef/mixin/properties.rb @@ -102,7 +102,7 @@ class Chef options = options.inject({}) { |memo, (key, value)| memo[key.to_sym] = value; memo } - options[:instance_variable_name] = :"@#{name}" if !options.key?(:instance_variable_name) + options[:instance_variable_name] = :"@#{name}" unless options.key?(:instance_variable_name) options[:name] = name options[:declared_in] = self @@ -191,8 +191,8 @@ class Chef # @return [Array<Property>] All properties in desired state. # def state_properties(*names) - if !names.empty? - names = names.map { |name| name.to_sym }.uniq + unless names.empty? + names = names.map(&:to_sym).uniq local_properties = properties(false) # Add new properties to the list. @@ -214,7 +214,7 @@ class Chef end end - properties.values.select { |property| property.desired_state? } + properties.values.select(&:desired_state?) end # @@ -240,8 +240,8 @@ class Chef # @return [Array<Property>] All identity properties. # def identity_properties(*names) - if !names.empty? - names = names.map { |name| name.to_sym } + unless names.empty? + names = names.map(&:to_sym) # Add or change properties that are not part of the identity. names.each do |name| @@ -263,7 +263,7 @@ class Chef end end - result = properties.values.select { |property| property.identity? } + result = properties.values.select(&:identity?) result = [ properties[:name] ] if result.empty? result end @@ -288,7 +288,8 @@ class Chef # def property_is_set?(name) property = self.class.properties[name.to_sym] - raise ArgumentError, "Property #{name} is not defined in class #{self}" if !property + raise ArgumentError, "Property #{name} is not defined in class #{self}" unless property + property.is_set?(self) end @@ -301,7 +302,8 @@ class Chef # def reset_property(name) property = self.class.properties[name.to_sym] - raise ArgumentError, "Property #{name} is not defined in class #{self}" if !property + raise ArgumentError, "Property #{name} is not defined in class #{self}" unless property + property.reset(self) end @@ -312,7 +314,8 @@ class Chef # @return [String] The description of the property. def property_description(name) property = self.class.properties[name.to_sym] - raise ArgumentError, "Property #{name} is not defined in class #{self}" if !property + raise ArgumentError, "Property #{name} is not defined in class #{self}" unless property + property.description end diff --git a/lib/chef/mixin/securable.rb b/lib/chef/mixin/securable.rb index eb59f184d1..d90b906f91 100644 --- a/lib/chef/mixin/securable.rb +++ b/lib/chef/mixin/securable.rb @@ -44,7 +44,7 @@ class Chef arg, callbacks: { "not in valid numeric range" => lambda do |m| - if m.kind_of?(String) + if m.is_a?(String) m =~ /^0/ || m = "0#{m}" end @@ -128,13 +128,13 @@ class Chef if permission < 0 || permission > 1 << 32 raise ArgumentError, "permissions flags must be positive and <= 32 bits (#{permission})" end - elsif !([:full_control, :modify, :read_execute, :read, :write].include?(permission.to_sym)) + elsif !(%i{full_control modify read_execute read write}.include?(permission.to_sym)) raise ArgumentError, "permissions parameter must be :full_control, :modify, :read_execute, :read, :write or an integer representing Windows permission flags" end end [ principals ].flatten.each do |principal| - if !principal.is_a?(String) + unless principal.is_a?(String) raise ArgumentError, "principals parameter must be a string or array of strings representing usernames" end end diff --git a/lib/chef/mixin/shell_out.rb b/lib/chef/mixin/shell_out.rb index 9f7b18eace..5fc7c249b9 100644 --- a/lib/chef/mixin/shell_out.rb +++ b/lib/chef/mixin/shell_out.rb @@ -75,6 +75,7 @@ class Chef # historically resources have not properly declared defaults on their timeouts, so a default default of 900s was enforced here default_val = 900 return options if options.key?(:timeout) + # FIXME: need to nuke descendents tracker out of Chef::Provider so we can just define that class here without requiring the # world, and then just use symbol lookup if obj.class.ancestors.map(&:name).include?("Chef::Provider") && obj.respond_to?(:new_resource) && obj.new_resource.respond_to?(:timeout) && !options.key?(:timeout) diff --git a/lib/chef/mixin/template.rb b/lib/chef/mixin/template.rb index f32b560e0e..488a80acdb 100644 --- a/lib/chef/mixin/template.rb +++ b/lib/chef/mixin/template.rb @@ -102,6 +102,7 @@ class Chef # by the bare `node` everywhere. def node return @node if @node + raise "Could not find a value for node. If you are explicitly setting variables in a template, " + "include a node variable if you plan to use it." end @@ -183,7 +184,7 @@ class Chef def _extend_modules(module_names) module_names.each do |mod| - context_methods = [:node, :render, :render_template, :render_template_from_string] + context_methods = %i{node render render_template render_template_from_string} context_methods.each do |core_method| if mod.method_defined?(core_method) || mod.private_method_defined?(core_method) Chef::Log.warn("Core template method `#{core_method}' overridden by extension module #{mod}") diff --git a/lib/chef/mixin/user_context.rb b/lib/chef/mixin/user_context.rb index c49bdc7880..bd73e818b0 100644 --- a/lib/chef/mixin/user_context.rb +++ b/lib/chef/mixin/user_context.rb @@ -30,7 +30,7 @@ class Chef raise Exceptions::UnsupportedPlatform, "User context impersonation is supported only on the Windows platform" end - if ! block_given? + unless block_given? raise ArgumentError, "You must supply a block to `with_user_context`" end diff --git a/lib/chef/mixin/which.rb b/lib/chef/mixin/which.rb index 974cb50fa3..a51963b6c2 100644 --- a/lib/chef/mixin/which.rb +++ b/lib/chef/mixin/which.rb @@ -56,6 +56,7 @@ class Chef File.executable?(filename) && !File.directory?(filename) end return false unless is_executable + block ? yield(filename) : true end end diff --git a/lib/chef/mixin/windows_architecture_helper.rb b/lib/chef/mixin/windows_architecture_helper.rb index 96e1b8d34e..cf05a682b5 100644 --- a/lib/chef/mixin/windows_architecture_helper.rb +++ b/lib/chef/mixin/windows_architecture_helper.rb @@ -49,8 +49,8 @@ class Chef node ||= begin os_arch = ENV["PROCESSOR_ARCHITEW6432"] || ENV["PROCESSOR_ARCHITECTURE"] - Hash.new.tap do |n| - n[:kernel] = Hash.new + {}.tap do |n| + n[:kernel] = {} n[:kernel][:machine] = os_arch == "AMD64" ? :x86_64 : :i386 end end @@ -82,7 +82,7 @@ class Chef end def assert_valid_windows_architecture!(architecture) - if !valid_windows_architecture?(architecture) + unless valid_windows_architecture?(architecture) raise Chef::Exceptions::Win32ArchitectureIncorrect, "The specified architecture was not valid. It must be one of :i386 or :x86_64" end diff --git a/lib/chef/mixin/windows_env_helper.rb b/lib/chef/mixin/windows_env_helper.rb index 6a5240c005..8036fa2bbe 100644 --- a/lib/chef/mixin/windows_env_helper.rb +++ b/lib/chef/mixin/windows_env_helper.rb @@ -46,8 +46,8 @@ class Chef if SendMessageTimeoutA(HWND_BROADCAST, WM_SETTINGCHANGE, 0, FFI::MemoryPointer.from_string("Environment").address, flags, 5000, nil) == 0 Chef::ReservedNames::Win32::Error.raise! end - if SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0, FFI::MemoryPointer.from_string( - utf8_to_wide("Environment") + if SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0, FFI::MemoryPointer.from_string( + utf8_to_wide("Environment") ).address, flags, 5000, nil) == 0 Chef::ReservedNames::Win32::Error.raise! end diff --git a/lib/chef/monkey_patches/net_http.rb b/lib/chef/monkey_patches/net_http.rb index e1a65a369c..a50b7fd74c 100644 --- a/lib/chef/monkey_patches/net_http.rb +++ b/lib/chef/monkey_patches/net_http.rb @@ -25,7 +25,7 @@ module Net end end -if Net::HTTP.instance_methods.map { |m| m.to_s }.include?("proxy_uri") +if Net::HTTP.instance_methods.map(&:to_s).include?("proxy_uri") begin # Ruby 2.0 changes the way proxy support is implemented in Net::HTTP. # The implementation does not work correctly with IPv6 literals because it diff --git a/lib/chef/monkey_patches/webrick-utils.rb b/lib/chef/monkey_patches/webrick-utils.rb index c90c9fe251..fa52a753c4 100644 --- a/lib/chef/monkey_patches/webrick-utils.rb +++ b/lib/chef/monkey_patches/webrick-utils.rb @@ -24,6 +24,7 @@ module WEBrick unless port raise ArgumentError, "must specify port" end + res = Socket.getaddrinfo(address, port, Socket::AF_UNSPEC, # address family Socket::SOCK_STREAM, # socket type @@ -44,6 +45,7 @@ module WEBrick end end raise last_error if sockets.empty? + sockets end module_function :create_listeners diff --git a/lib/chef/node.rb b/lib/chef/node.rb index a6a7c06dc4..dfd2c685e1 100644 --- a/lib/chef/node.rb +++ b/lib/chef/node.rb @@ -90,6 +90,7 @@ class Chef # and setup the node[:cookbooks] attribute so that it is published in the node object def set_cookbook_attribute return unless run_context.cookbook_collection + run_context.cookbook_collection.each do |cookbook_name, cookbook| automatic_attrs[:cookbooks][cookbook_name][:version] = cookbook.version end @@ -120,7 +121,8 @@ class Chef { name: { kind_of: String, cannot_be: :blank, regex: /^[\-[:alnum:]_:.]+$/ }, - }) + } + ) @name = arg else @name @@ -152,6 +154,7 @@ class Chef # @return [String] the current policy_name, or the one you just set def policy_name(arg = NULL_ARG) return @policy_name if arg.equal?(NULL_ARG) + validate({ policy_name: arg }, { policy_name: { kind_of: [ String, NilClass ], regex: /^[\-:.[:alnum:]_]+$/ } }) @policy_name = arg end @@ -174,6 +177,7 @@ class Chef # @return [String] the current policy_group, or the one you just set def policy_group(arg = NULL_ARG) return @policy_group if arg.equal?(NULL_ARG) + validate({ policy_group: arg }, { policy_group: { kind_of: [ String, NilClass ], regex: /^[\-:.[:alnum:]_]+$/ } }) @policy_group = arg end @@ -316,6 +320,7 @@ class Chef # @return [Chef::RunList] the override run list def override_runlist(*args) return @override_runlist if args.length == 0 + @override_runlist_set = true @override_runlist.reset!(args) end @@ -403,6 +408,7 @@ class Chef if attrs.key?("recipes") || attrs.key?("run_list") raise Chef::Exceptions::AmbiguousRunlistSpecification, "please set the node's run list using the 'run_list' attribute only." end + logger.info("Setting the run_list to #{new_run_list} from CLI options") run_list(new_run_list) end @@ -518,7 +524,7 @@ class Chef "default" => attributes.combined_default.to_hash, "override" => attributes.combined_override.to_hash, # Render correctly for run_list items so malformed json does not result - "run_list" => @primary_runlist.run_list.map { |item| item.to_s }, + "run_list" => @primary_runlist.run_list.map(&:to_s), } # Chef Server rejects node JSON with extra keys; prior to 12.3, # "policy_name" and "policy_group" are unknown; after 12.3 they are @@ -542,7 +548,8 @@ class Chef end def self.from_hash(o) - return o if o.kind_of? Chef::Node + return o if o.is_a? Chef::Node + node = new node.name(o["name"]) @@ -574,7 +581,7 @@ class Chef def self.list_by_environment(environment, inflate = false) if inflate - response = Hash.new + response = {} Chef::Search::Query.new.search(:node, "chef_environment:#{environment}") { |n| response[n.name] = n unless n.nil? } response else @@ -584,7 +591,7 @@ class Chef def self.list(inflate = false) if inflate - response = Hash.new + response = {} Chef::Search::Query.new.search(:node) do |n| n = Chef::Node.from_hash(n) response[n.name] = n unless n.nil? @@ -599,6 +606,7 @@ class Chef load(node_name) rescue Net::HTTPClientException => e raise unless e.response.code == "404" + node = build(node_name) node.create end @@ -660,7 +668,7 @@ class Chef end def ==(other) - if other.kind_of?(self.class) + if other.is_a?(self.class) name == other.name else false @@ -679,6 +687,7 @@ class Chef chef_server_rest.put("nodes/#{name}", trimmed_data) rescue Net::HTTPClientException => e raise e unless e.response.code == "404" + chef_server_rest.post("nodes", trimmed_data) end diff --git a/lib/chef/node/attribute.rb b/lib/chef/node/attribute.rb index eac867899c..bc4983384b 100644 --- a/lib/chef/node/attribute.rb +++ b/lib/chef/node/attribute.rb @@ -51,109 +51,109 @@ class Chef # List of the component attribute hashes, in order of precedence, low to # high. - COMPONENTS = [ - :@default, - :@env_default, - :@role_default, - :@force_default, - :@normal, - :@override, - :@role_override, - :@env_override, - :@force_override, - :@automatic, - ].freeze - - DEFAULT_COMPONENTS = [ - :@default, - :@env_default, - :@role_default, - :@force_default, - ].freeze - - OVERRIDE_COMPONENTS = [ - :@override, - :@role_override, - :@env_override, - :@force_override, - ].freeze - - ENUM_METHODS = [ - :all?, - :any?, - :assoc, - :chunk, - :collect, - :collect_concat, - :compare_by_identity, - :compare_by_identity?, - :count, - :cycle, - :detect, - :drop, - :drop_while, - :each, - :each_cons, - :each_entry, - :each_key, - :each_pair, - :each_slice, - :each_value, - :each_with_index, - :each_with_object, - :empty?, - :entries, - :except, - :fetch, - :find, - :find_all, - :find_index, - :first, - :flat_map, - :flatten, - :grep, - :group_by, - :has_value?, - :include?, - :index, - :inject, - :invert, - :key, - :keys, - :length, - :map, - :max, - :max_by, - :merge, - :min, - :min_by, - :minmax, - :minmax_by, - :none?, - :one?, - :partition, - :rassoc, - :reduce, - :reject, - :reverse_each, - :select, - :size, - :slice_before, - :sort, - :sort_by, - :store, - :symbolize_keys, - :take, - :take_while, - :to_a, - :to_h, - :to_hash, - :to_set, - :value?, - :values, - :values_at, - :zip, - ].freeze + COMPONENTS = %i{ + @default + @env_default + @role_default + @force_default + @normal + @override + @role_override + @env_override + @force_override + @automatic + }.freeze + + DEFAULT_COMPONENTS = %i{ + @default + @env_default + @role_default + @force_default + }.freeze + + OVERRIDE_COMPONENTS = %i{ + @override + @role_override + @env_override + @force_override + }.freeze + + ENUM_METHODS = %i{ + all? + any? + assoc + chunk + collect + collect_concat + compare_by_identity + compare_by_identity? + count + cycle + detect + drop + drop_while + each + each_cons + each_entry + each_key + each_pair + each_slice + each_value + each_with_index + each_with_object + empty? + entries + except + fetch + find + find_all + find_index + first + flat_map + flatten + grep + group_by + has_value? + include? + index + inject + invert + key + keys + length + map + max + max_by + merge + min + min_by + minmax + minmax_by + none? + one? + partition + rassoc + reduce + reject + reverse_each + select + size + slice_before + sort + sort_by + store + symbolize_keys + take + take_while + to_a + to_h + to_hash + to_set + value? + values + values_at + zip + }.freeze ENUM_METHODS.each do |delegated_method| define_method(delegated_method) do |*args, &block| @@ -341,6 +341,7 @@ class Chef def with_deep_merged_return_value(obj, *path, last) hash = obj.read(*path) return nil unless hash.is_a?(Hash) + ret = hash[last] yield ret @@ -357,6 +358,7 @@ class Chef # - this API autovivifies (and cannot trainwreck) def default!(*args) return Decorator::Unchain.new(self, :default!) unless args.length > 0 + write(:default, *args) end @@ -365,6 +367,7 @@ class Chef # - this API autovivifies (and cannot trainwreck) def normal!(*args) return Decorator::Unchain.new(self, :normal!) unless args.length > 0 + write(:normal, *args) end @@ -373,6 +376,7 @@ class Chef # - this API autovivifies (and cannot trainwreck) def override!(*args) return Decorator::Unchain.new(self, :override!) unless args.length > 0 + write(:override, *args) end @@ -381,6 +385,7 @@ class Chef # - this API autovivifies (and cannot trainwreck) def force_default!(*args) return Decorator::Unchain.new(self, :force_default!) unless args.length > 0 + value = args.pop rm_default(*args) write(:force_default, *args, value) @@ -389,6 +394,7 @@ class Chef # clears from all override precedence levels and then sets force_override def force_override!(*args) return Decorator::Unchain.new(self, :force_override!) unless args.length > 0 + value = args.pop rm_override(*args) write(:force_override, *args, value) @@ -417,16 +423,19 @@ class Chef def normal_unless(*args) return Decorator::Unchain.new(self, :normal_unless) unless args.length > 0 + write(:normal, *args) if normal.read(*args[0...-1]).nil? end def default_unless(*args) return Decorator::Unchain.new(self, :default_unless) unless args.length > 0 + write(:default, *args) if default.read(*args[0...-1]).nil? end def override_unless(*args) return Decorator::Unchain.new(self, :override_unless) unless args.length > 0 + write(:override, *args) if override.read(*args[0...-1]).nil? end @@ -478,7 +487,7 @@ class Chef end def inspect - "#<#{self.class} " << (COMPONENTS + [:@merged_attributes, :@properties]).map do |iv| + "#<#{self.class} " << (COMPONENTS + %i{@merged_attributes @properties}).map do |iv| "#{iv}=#{instance_variable_get(iv).inspect}" end.join(", ") << ">" end @@ -573,7 +582,7 @@ class Chef # needed for __path__ def convert_key(key) - key.kind_of?(Symbol) ? key.to_s : key + key.is_a?(Symbol) ? key.to_s : key end NIL = Object.new @@ -581,7 +590,7 @@ class Chef # @api private def deep_merge!(merge_onto, merge_with) # If there are two Hashes, recursively merge. - if merge_onto.kind_of?(Hash) && merge_with.kind_of?(Hash) + if merge_onto.is_a?(Hash) && merge_with.is_a?(Hash) merge_with.each do |key, merge_with_value| value = if merge_onto.key?(key) @@ -595,7 +604,7 @@ class Chef end merge_onto - elsif merge_onto.kind_of?(Array) && merge_with.kind_of?(Array) + elsif merge_onto.is_a?(Array) && merge_with.is_a?(Array) merge_onto |= merge_with # If merge_with is NIL, don't replace merge_onto @@ -604,9 +613,9 @@ class Chef # In all other cases, replace merge_onto with merge_with else - if merge_with.kind_of?(Hash) + if merge_with.is_a?(Hash) Chef::Node::ImmutableMash.new(merge_with) - elsif merge_with.kind_of?(Array) + elsif merge_with.is_a?(Array) Chef::Node::ImmutableArray.new(merge_with) else merge_with @@ -617,7 +626,7 @@ class Chef # @api private def hash_only_merge!(merge_onto, merge_with) # If there are two Hashes, recursively merge. - if merge_onto.kind_of?(Hash) && merge_with.kind_of?(Hash) + if merge_onto.is_a?(Hash) && merge_with.is_a?(Hash) merge_with.each do |key, merge_with_value| value = if merge_onto.key?(key) @@ -637,9 +646,9 @@ class Chef # In all other cases, replace merge_onto with merge_with else - if merge_with.kind_of?(Hash) + if merge_with.is_a?(Hash) Chef::Node::ImmutableMash.new(merge_with) - elsif merge_with.kind_of?(Array) + elsif merge_with.is_a?(Array) Chef::Node::ImmutableArray.new(merge_with) else merge_with diff --git a/lib/chef/node/attribute_collections.rb b/lib/chef/node/attribute_collections.rb index 3f19321afa..dadc209ae9 100644 --- a/lib/chef/node/attribute_collections.rb +++ b/lib/chef/node/attribute_collections.rb @@ -106,7 +106,7 @@ class Chef # Methods that mutate a VividMash. Each of them is overridden so that it # also invalidates the cached merged_attributes on the root Attribute # object. - MUTATOR_METHODS = Chef::Node::Mixin::ImmutablizeHash::DISALLOWED_MUTATOR_METHODS - [ :write, :write!, :unlink, :unlink! ] + MUTATOR_METHODS = Chef::Node::Mixin::ImmutablizeHash::DISALLOWED_MUTATOR_METHODS - %i{write write! unlink unlink!} # For all of the mutating methods on Mash, override them so that they # also invalidate the cached `merged_attributes` on the root Attribute diff --git a/lib/chef/node/common_api.rb b/lib/chef/node/common_api.rb index a703c1ef54..1ea1067113 100644 --- a/lib/chef/node/common_api.rb +++ b/lib/chef/node/common_api.rb @@ -36,7 +36,7 @@ class Chef last = args.pop prev_memo = prev_key = nil chain = args.inject(self) do |memo, key| - if !valid_container?(memo, key) + unless valid_container?(memo, key) prev_memo[prev_key] = {} memo = prev_memo[prev_key] end @@ -44,7 +44,7 @@ class Chef prev_key = key memo[key] end - if !valid_container?(chain, last) + unless valid_container?(chain, last) prev_memo[prev_key] = {} chain = prev_memo[prev_key] end @@ -59,9 +59,11 @@ class Chef last = args.pop obj = args.inject(self) do |memo, key| raise Chef::Exceptions::AttributeTypeMismatch unless valid_container?(memo, key) + memo[key] end raise Chef::Exceptions::AttributeTypeMismatch unless valid_container?(obj, last) + obj[last] = value end @@ -71,6 +73,7 @@ class Chef def exist?(*path) path.inject(self) do |memo, key| return false unless valid_container?(memo, key) + if memo.is_a?(Hash) if memo.key?(key) memo[key] @@ -98,6 +101,7 @@ class Chef # non-autovivifying reader that throws an exception if the attribute does not exist def read!(*path) raise Chef::Exceptions::NoSuchAttribute unless exist?(*path) + path.inject(self) do |memo, key| memo[key] end @@ -108,11 +112,13 @@ class Chef def unlink(*path, last) hash = path.empty? ? self : read(*path) return nil unless hash.is_a?(Hash) || hash.is_a?(Array) + hash.delete(last) end def unlink!(*path) raise Chef::Exceptions::NoSuchAttribute unless exist?(*path) + unlink(*path) end diff --git a/lib/chef/node/immutable_collections.rb b/lib/chef/node/immutable_collections.rb index 994d5c37e4..b4a7a39ba0 100644 --- a/lib/chef/node/immutable_collections.rb +++ b/lib/chef/node/immutable_collections.rb @@ -151,7 +151,7 @@ class Chef end def to_h - h = Hash.new + h = {} each_pair do |k, v| h[k] = case v diff --git a/lib/chef/node/mixin/immutablize_array.rb b/lib/chef/node/mixin/immutablize_array.rb index a2b8649268..e9cbb2142a 100644 --- a/lib/chef/node/mixin/immutablize_array.rb +++ b/lib/chef/node/mixin/immutablize_array.rb @@ -1,5 +1,5 @@ #-- -# Copyright:: Copyright 2016-2018, Chef Software Inc. +# Copyright:: Copyright 2016-2019, Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -21,150 +21,150 @@ class Chef module ImmutablizeArray # Allowed methods that MUST NOT mutate the object # (if any of these methods mutate the underlying object that is a bug that needs to be fixed) - ALLOWED_METHODS = [ - :&, - :*, - :+, - :-, - :[], - :abbrev, - :all?, - :any?, - :assoc, - :at, - :bsearch, - :bsearch_index, - :chain, - :chunk, - :chunk_while, - :collect, - :collect_concat, - :combination, - :compact, - :count, - :cycle, - :detect, - :difference, - :dig, - :drop, - :drop_while, - :each, - :each_cons, - :each_entry, - :each_index, - :each_slice, - :each_with_index, - :each_with_object, - :empty?, - :entries, - :fetch, - :filter, - :find, - :find_all, - :find_index, - :first, - :flat_map, - :flatten, - :grep, - :grep_v, - :group_by, - :include?, - :index, - :inject, - :join, - :last, - :lazy, - :length, - :map, - :max, - :max_by, - :member?, - :min, - :min_by, - :minmax, - :minmax_by, - :none?, - :one?, - :pack, - :partition, - :permutation, - :product, - :rassoc, - :reduce, - :reject, - :repeated_combination, - :repeated_permutation, - :reverse, - :reverse_each, - :rindex, - :rotate, - :sample, - :save_plist, - :select, - :shelljoin, - :shuffle, - :size, - :slice, - :slice_after, - :slice_before, - :slice_when, - :sort, - :sort_by, - :sum, - :take, - :take_while, - :to_a, - :to_ary, - :to_csv, - :to_h, - :to_plist, - :to_set, - :transpose, - :union, - :uniq, - :values_at, - :zip, - :|, - ].freeze + ALLOWED_METHODS = %i{ + & + * + + + - + [] + abbrev + all? + any? + assoc + at + bsearch + bsearch_index + chain + chunk + chunk_while + collect + collect_concat + combination + compact + count + cycle + detect + difference + dig + drop + drop_while + each + each_cons + each_entry + each_index + each_slice + each_with_index + each_with_object + empty? + entries + fetch + filter + find + find_all + find_index + first + flat_map + flatten + grep + grep_v + group_by + include? + index + inject + join + last + lazy + length + map + max + max_by + member? + min + min_by + minmax + minmax_by + none? + one? + pack + partition + permutation + product + rassoc + reduce + reject + repeated_combination + repeated_permutation + reverse + reverse_each + rindex + rotate + sample + save_plist + select + shelljoin + shuffle + size + slice + slice_after + slice_before + slice_when + sort + sort_by + sum + take + take_while + to_a + to_ary + to_csv + to_h + to_plist + to_set + transpose + union + uniq + values_at + zip + | + }.freeze # A list of methods that mutate Array. Each of these is overridden to # raise an error, making this instances of this class more or less # immutable. - DISALLOWED_MUTATOR_METHODS = [ - :<<, - :[]=, - :append, - :clear, - :collect!, - :compact!, - :concat, - :default=, - :default_proc=, - :delete, - :delete_at, - :delete_if, - :fill, - :filter!, - :flatten!, - :insert, - :keep_if, - :map!, - :merge!, - :pop, - :prepend, - :push, - :reject!, - :replace, - :reverse!, - :rotate!, - :select!, - :shift, - :shuffle!, - :slice!, - :sort!, - :sort_by!, - :uniq!, - :unshift, - ].freeze + DISALLOWED_MUTATOR_METHODS = %i{ + << + []= + append + clear + collect! + compact! + concat + default= + default_proc= + delete + delete_at + delete_if + fill + filter! + flatten! + insert + keep_if + map! + merge! + pop + prepend + push + reject! + replace + reverse! + rotate! + select! + shift + shuffle! + slice! + sort! + sort_by! + uniq! + unshift + }.freeze # Redefine all of the methods that mutate a Hash to raise an error when called. # This is the magic that makes this object "Immutable" diff --git a/lib/chef/node/mixin/immutablize_hash.rb b/lib/chef/node/mixin/immutablize_hash.rb index 109390ed74..8c0d1c9509 100644 --- a/lib/chef/node/mixin/immutablize_hash.rb +++ b/lib/chef/node/mixin/immutablize_hash.rb @@ -1,5 +1,5 @@ #-- -# Copyright:: Copyright 2016-2018, Chef Software Inc. +# Copyright:: Copyright 2016-2019, Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -21,136 +21,136 @@ class Chef module ImmutablizeHash # allowed methods that MUST NOT mutate the object # (if any of these methods mutate the underlying object that is a bug that needs to be fixed) - ALLOWED_METHODS = [ - :<, - :<=, - :>, - :>=, - :[], - :all?, - :any?, - :assoc, - :chain, - :chunk, - :chunk_while, - :collect, - :collect_concat, - :compact, - :compare_by_identity, - :compare_by_identity?, - :count, - :cycle, - :default, - :default_proc, - :detect, - :dig, - :drop, - :drop_while, - :each, - :each_cons, - :each_entry, - :each_key, - :each_pair, - :each_slice, - :each_value, - :each_with_index, - :each_with_object, - :empty?, - :entries, - :fetch, - :fetch_values, - :filter, - :find, - :find_all, - :find_index, - :first, - :flat_map, - :flatten, - :grep, - :grep_v, - :group_by, - :has_key?, - :has_value?, - :include?, - :index, - :inject, - :invert, - :key, - :key?, - :keys, - :lazy, - :length, - :map, - :max, - :max_by, - :member?, - :merge, - :min, - :min_by, - :minmax, - :minmax_by, - :none?, - :normalize_param, - :one?, - :partition, - :rassoc, - :reduce, - :reject, - :reverse_each, - :save_plist, - :select, - :size, - :slice, - :slice_after, - :slice_before, - :slice_when, - :sort, - :sort_by, - :sum, - :take, - :take_while, - :to_a, - :to_h, - :to_hash, - :to_plist, - :to_proc, - :to_set, - :to_xml_attributes, - :transform_keys, - :transform_values, - :uniq, - :value?, - :values, - :values_at, - :zip, - ].freeze - DISALLOWED_MUTATOR_METHODS = [ - :[]=, - :clear, - :collect!, - :compact!, - :default=, - :default_proc=, - :delete, - :delete_if, - :filter!, - :keep_if, - :map!, - :merge!, - :rehash, - :reject!, - :replace, - :select!, - :shift, - :store, - :transform_keys!, - :transform_values!, - :unlink!, - :unlink, - :update, - :write!, - :write, - ].freeze + ALLOWED_METHODS = %i{ + < + <= + > + >= + [] + all? + any? + assoc + chain + chunk + chunk_while + collect + collect_concat + compact + compare_by_identity + compare_by_identity? + count + cycle + default + default_proc + detect + dig + drop + drop_while + each + each_cons + each_entry + each_key + each_pair + each_slice + each_value + each_with_index + each_with_object + empty? + entries + fetch + fetch_values + filter + find + find_all + find_index + first + flat_map + flatten + grep + grep_v + group_by + has_key? + has_value? + include? + index + inject + invert + key + key? + keys + lazy + length + map + max + max_by + member? + merge + min + min_by + minmax + minmax_by + none? + normalize_param + one? + partition + rassoc + reduce + reject + reverse_each + save_plist + select + size + slice + slice_after + slice_before + slice_when + sort + sort_by + sum + take + take_while + to_a + to_h + to_hash + to_plist + to_proc + to_set + to_xml_attributes + transform_keys + transform_values + uniq + value? + values + values_at + zip + }.freeze + DISALLOWED_MUTATOR_METHODS = %i{ + []= + clear + collect! + compact! + default= + default_proc= + delete + delete_if + filter! + keep_if + map! + merge! + rehash + reject! + replace + select! + shift + store + transform_keys! + transform_values! + unlink! + unlink + update + write! + write + }.freeze # Redefine all of the methods that mutate a Hash to raise an error when called. # This is the magic that makes this object "Immutable" diff --git a/lib/chef/node_map.rb b/lib/chef/node_map.rb index f54b3dc6bb..dd118c26cf 100644 --- a/lib/chef/node_map.rb +++ b/lib/chef/node_map.rb @@ -120,6 +120,7 @@ class Chef # def get(node, key, canonical: nil) return nil unless map.key?(key) + map[key].map do |matcher| return matcher[:klass] if node_matches?(node, matcher) && canonical_matches?(canonical, matcher) end @@ -140,6 +141,7 @@ class Chef # def list(node, key, canonical: nil) return [] unless map.key?(key) + map[key].select do |matcher| node_matches?(node, matcher) && canonical_matches?(canonical, matcher) end.map { |matcher| matcher[:klass] } @@ -155,6 +157,7 @@ class Chef # @return [Hash] deleted entries in the same format as the @map def delete_class(klass) raise "please use a Class type for the klass argument" unless klass.is_a?(Class) + deleted = {} map.each do |key, matchers| deleted_matchers = [] @@ -224,7 +227,8 @@ class Chef def matches_black_white_list?(node, filters, attribute) # It's super common for the filter to be nil. Catch that so we don't # spend any time here. - return true if !filters[attribute] + return true unless filters[attribute] + filter_values = Array(filters[attribute]) value = node[attribute] @@ -241,7 +245,8 @@ class Chef def matches_version_list?(node, filters, attribute) # It's super common for the filter to be nil. Catch that so we don't # spend any time here. - return true if !filters[attribute] + return true unless filters[attribute] + filter_values = Array(filters[attribute]) value = node[attribute] @@ -257,6 +262,7 @@ class Chef # def matches_target_mode?(filters) return true unless Chef::Config.target_mode? + !!filters[:target_mode] end @@ -270,16 +276,19 @@ class Chef def block_matches?(node, block) return true if block.nil? + block.call node end def node_matches?(node, matcher) - return true if !node + return true unless node + filters_match?(node, matcher) && block_matches?(node, matcher[:block]) end def canonical_matches?(canonical, matcher) return true if canonical.nil? + !!canonical == !!matcher[:canonical] end @@ -289,16 +298,22 @@ class Chef def compare_matchers(key, new_matcher, matcher) cmp = compare_matcher_properties(new_matcher[:block], matcher[:block]) return cmp if cmp != 0 + cmp = compare_matcher_properties(new_matcher[:platform_version], matcher[:platform_version]) return cmp if cmp != 0 + cmp = compare_matcher_properties(new_matcher[:platform], matcher[:platform]) return cmp if cmp != 0 + cmp = compare_matcher_properties(new_matcher[:platform_family], matcher[:platform_family]) return cmp if cmp != 0 + cmp = compare_matcher_properties(new_matcher[:os], matcher[:os]) return cmp if cmp != 0 + cmp = compare_matcher_properties(new_matcher[:override], matcher[:override]) return cmp if cmp != 0 + # If all things are identical, return 0 0 end diff --git a/lib/chef/null_logger.rb b/lib/chef/null_logger.rb index 5781d8e055..16ff33ba80 100644 --- a/lib/chef/null_logger.rb +++ b/lib/chef/null_logger.rb @@ -27,29 +27,21 @@ class Chef # probably expected a real logger and not this "fake" one. class NullLogger - def fatal(message, &block) - end + def fatal(message, &block); end - def error(message, &block) - end + def error(message, &block); end - def warn(message, &block) - end + def warn(message, &block); end - def info(message, &block) - end + def info(message, &block); end - def debug(message, &block) - end + def debug(message, &block); end - def trace(message, &block) - end + def trace(message, &block); end - def add(severity, message = nil, progname = nil) - end + def add(severity, message = nil, progname = nil); end - def <<(message) - end + def <<(message); end def fatal? false diff --git a/lib/chef/platform/query_helpers.rb b/lib/chef/platform/query_helpers.rb index 6e56eba120..ffcd7e0bd9 100644 --- a/lib/chef/platform/query_helpers.rb +++ b/lib/chef/platform/query_helpers.rb @@ -26,6 +26,7 @@ class Chef def windows_nano_server? return false unless windows? + require "win32/registry" unless defined?(Win32::Registry) # This method may be called before ohai runs (e.g., it may be used to @@ -48,6 +49,7 @@ class Chef def supports_msi? return false unless windows? + require "win32/registry" unless defined?(Win32::Registry) key = "System\\CurrentControlSet\\Services\\msiserver" @@ -90,6 +92,7 @@ class Chef def supported_powershell_version?(node, version_string) return false unless node[:languages] && node[:languages][:powershell] + require "rubygems" unless defined?(Gem) Gem::Version.new(node[:languages][:powershell][:version]) >= Gem::Version.new(version_string) diff --git a/lib/chef/platform/rebooter.rb b/lib/chef/platform/rebooter.rb index 386970186d..ad17ffad8c 100644 --- a/lib/chef/platform/rebooter.rb +++ b/lib/chef/platform/rebooter.rb @@ -38,7 +38,7 @@ class Chef when Chef::Platform.windows? # should this do /f as well? do we then need a minimum delay to let apps quit? # Use explicit path to shutdown.exe, to protect against https://github.com/chef/chef/issues/5594 - windows_shutdown_path = "#{ENV['SYSTEMROOT']}/System32/shutdown.exe" + windows_shutdown_path = "#{ENV["SYSTEMROOT"]}/System32/shutdown.exe" "#{windows_shutdown_path} /r /t #{reboot_info[:delay_mins] * 60} /c \"#{reboot_info[:reason]}\"" when node["os"] == "solaris2" # SysV-flavored shutdown diff --git a/lib/chef/platform/service_helpers.rb b/lib/chef/platform/service_helpers.rb index 2faec6fc8a..851c3ebffc 100644 --- a/lib/chef/platform/service_helpers.rb +++ b/lib/chef/platform/service_helpers.rb @@ -72,7 +72,7 @@ class Chef configs = [] if file_exist?(Chef.path_to("/etc/init.d/#{service_name}")) - configs += [ :initd, :systemd ] + configs += %i{initd systemd} end if file_exist?(Chef.path_to("/etc/init/#{service_name}.conf")) @@ -108,7 +108,7 @@ class Chef def has_systemd_service_unit?(svc_name) %w{ /etc /usr/lib /lib /run }.any? do |load_path| file_exist?( - Chef.path_to("#{load_path}/systemd/system/#{svc_name.gsub(/@.*$/, '@')}.service") + Chef.path_to("#{load_path}/systemd/system/#{svc_name.gsub(/@.*$/, "@")}.service") ) end end diff --git a/lib/chef/policy_builder/expand_node_object.rb b/lib/chef/policy_builder/expand_node_object.rb index fceec9d873..4afb4d7d60 100644 --- a/lib/chef/policy_builder/expand_node_object.rb +++ b/lib/chef/policy_builder/expand_node_object.rb @@ -139,7 +139,7 @@ class Chef expand_run_list Chef::Log.info("Run List is [#{node.run_list}]") - Chef::Log.info("Run List expands to [#{@expanded_run_list_with_versions.join(', ')}]") + Chef::Log.info("Run List expands to [#{@expanded_run_list_with_versions.join(", ")}]") events.node_load_completed(node, @expanded_run_list_with_versions, Chef::Config) events.run_list_expanded(@run_list_expansion) @@ -235,7 +235,7 @@ class Chef def runlist_override_sanity_check! # Convert to array and remove whitespace if override_runlist.is_a?(String) - @override_runlist = override_runlist.split(",").map { |e| e.strip } + @override_runlist = override_runlist.split(",").map(&:strip) end @override_runlist = [override_runlist].flatten.compact override_runlist.map! do |item| diff --git a/lib/chef/policy_builder/policyfile.rb b/lib/chef/policy_builder/policyfile.rb index 3e1a2e81c6..70a2e44635 100644 --- a/lib/chef/policy_builder/policyfile.rb +++ b/lib/chef/policy_builder/policyfile.rb @@ -156,7 +156,7 @@ class Chef apply_policyfile_attributes Chef::Log.info("Run List is [#{run_list}]") - Chef::Log.info("Run List expands to [#{run_list_with_versions_for_display.join(', ')}]") + Chef::Log.info("Run List expands to [#{run_list_with_versions_for_display.join(", ")}]") events.node_load_completed(node, run_list_with_versions_for_display, Chef::Config) events.run_list_expanded(run_list_expansion_ish) @@ -304,7 +304,7 @@ class Chef if named_run_list_requested? named_run_list || raise(ConfigurationError, "Policy '#{retrieved_policy_name}' revision '#{revision_id}' does not have named_run_list '#{named_run_list_name}'" + - "(available named_run_lists: [#{available_named_run_lists.join(', ')}])") + "(available named_run_lists: [#{available_named_run_lists.join(", ")}])") else policy["run_list"] end @@ -340,7 +340,7 @@ class Chef unless policy.key?("cookbook_locks") errors << "Policyfile is missing cookbook_locks element" end - if run_list.kind_of?(Array) + if run_list.is_a?(Array) run_list_errors = run_list.select do |maybe_recipe_spec| validate_recipe_spec(maybe_recipe_spec) end diff --git a/lib/chef/powershell.rb b/lib/chef/powershell.rb index 3fe58b254b..2de0bfe40b 100644 --- a/lib/chef/powershell.rb +++ b/lib/chef/powershell.rb @@ -35,11 +35,13 @@ class Chef # @return [Object] output def initialize(script) raise "Chef::PowerShell can only be used on the Windows platform." unless RUBY_PLATFORM =~ /mswin|mingw32|windows/ + exec(script) end def error? return true if errors.count > 0 + false end diff --git a/lib/chef/property.rb b/lib/chef/property.rb index c26146a96b..6aa76a5236 100644 --- a/lib/chef/property.rb +++ b/lib/chef/property.rb @@ -130,6 +130,7 @@ class Chef if options.key?(:name_property) raise ArgumentError, "name_attribute and name_property are functionally identical and both cannot be specified on a property at once. Use just one on property #{self}" end + # replace name_property with name_attribute in place options = Hash[options.map { |k, v| k == :name_attribute ? [ :name_property, v ] : [ k, v ] }] @options = options @@ -230,6 +231,7 @@ class Chef def default return options[:default] if options.key?(:default) return Chef::DelayedEvaluator.new { name } if name_property? + nil end @@ -259,7 +261,8 @@ class Chef # @return [Boolean] # def desired_state? - return true if !options.key?(:desired_state) + return true unless options.key?(:desired_state) + options[:desired_state] end @@ -319,7 +322,7 @@ class Chef # def validation_options @validation_options ||= options.reject do |k, v| - [:declared_in, :name, :instance_variable_name, :desired_state, :identity, :default, :name_property, :coerce, :required, :nillable, :sensitive, :description, :introduced, :deprecated, :default_description, :skip_docs].include?(k) + %i{declared_in name instance_variable_name desired_state identity default name_property coerce required nillable sensitive description introduced deprecated default_description skip_docs}.include?(k) end end @@ -551,7 +554,7 @@ class Chef def emit_dsl # We don't create the getter/setter if it's a custom property; we will # be using the existing getter/setter to manipulate it instead. - return if !instance_variable_name + return unless instance_variable_name # Properties may override existing properties up the inheritance heirarchy, but # properties must not override inherited methods like Object#hash. When the Resource is diff --git a/lib/chef/provider.rb b/lib/chef/provider.rb index a95056d70c..6d1985bbbb 100644 --- a/lib/chef/provider.rb +++ b/lib/chef/provider.rb @@ -135,8 +135,7 @@ class Chef new_resource.cookbook_name end - def check_resource_semantics! - end + def check_resource_semantics!; end # a simple placeholder method that will be called / raise if a resource tries to # use current_resource without defining a load_current_resource method. @@ -144,11 +143,9 @@ class Chef raise Chef::Exceptions::Override, "You must override load_current_resource in #{self}" end - def define_resource_requirements - end + def define_resource_requirements; end - def cleanup_after_converge - end + def cleanup_after_converge; end # the :nothing action which is available on all resources by default def action_nothing @@ -245,7 +242,7 @@ class Chef Chef::Runner.new(run_context).converge return_value ensure - if run_context.resource_collection.any? { |r| r.updated? } + if run_context.resource_collection.any?(&:updated?) new_resource.updated_by_last_action(true) end @run_context = old_run_context @@ -269,12 +266,12 @@ class Chef # @return [Boolean] whether the block was executed. # def converge_if_changed(*properties, &converge_block) - if !converge_block + unless converge_block raise ArgumentError, "converge_if_changed must be passed a block!" end - properties = new_resource.class.state_properties.map { |p| p.name } if properties.empty? - properties = properties.map { |p| p.to_sym } + properties = new_resource.class.state_properties.map(&:name) if properties.empty? + properties = properties.map(&:to_sym) if current_resource # Collect the list of modified properties specified_properties = properties.select { |property| new_resource.property_is_set?(property) } @@ -296,7 +293,7 @@ class Chef end # Print the pretty green text and run the block - property_size = modified.map { |p| p.size }.max + property_size = modified.map(&:size).max modified.map! do |p| properties_str = if new_resource.sensitive || new_resource.class.properties[p].sensitive? "(suppressed sensitive property)" @@ -310,7 +307,7 @@ class Chef else # The resource doesn't exist. Mark that we are *creating* this, and # write down any properties we are setting. - property_size = properties.map { |p| p.size }.max + property_size = properties.map(&:size).max created = properties.map do |property| default = " (default value)" unless new_resource.property_is_set?(property) properties_str = if new_resource.sensitive || new_resource.class.properties[property].sensitive? diff --git a/lib/chef/provider/apt_preference.rb b/lib/chef/provider/apt_preference.rb index 7a5f3fbf79..0e655cf0c0 100644 --- a/lib/chef/provider/apt_preference.rb +++ b/lib/chef/provider/apt_preference.rb @@ -28,8 +28,7 @@ class Chef APT_PREFERENCE_DIR = "/etc/apt/preferences.d".freeze - def load_current_resource - end + def load_current_resource; end action :add do preference = build_pref( diff --git a/lib/chef/provider/apt_repository.rb b/lib/chef/provider/apt_repository.rb index 9065a7d9dc..85fac1d2da 100644 --- a/lib/chef/provider/apt_repository.rb +++ b/lib/chef/provider/apt_repository.rb @@ -32,8 +32,7 @@ class Chef LIST_APT_KEY_FINGERPRINTS = %w{apt-key adv --list-public-keys --with-fingerprint --with-colons}.freeze - def load_current_resource - end + def load_current_resource; end action :add do if new_resource.key.nil? diff --git a/lib/chef/provider/apt_update.rb b/lib/chef/provider/apt_update.rb index d20cf12d0d..8914d5412b 100644 --- a/lib/chef/provider/apt_update.rb +++ b/lib/chef/provider/apt_update.rb @@ -28,11 +28,10 @@ class Chef APT_CONF_DIR = "/etc/apt/apt.conf.d".freeze STAMP_DIR = "/var/lib/apt/periodic".freeze - def load_current_resource - end + def load_current_resource; end action :periodic do - if !apt_up_to_date? + unless apt_up_to_date? converge_by "update new lists of packages" do do_update end diff --git a/lib/chef/provider/cookbook_file.rb b/lib/chef/provider/cookbook_file.rb index b8ec86cd92..3d09d291a3 100644 --- a/lib/chef/provider/cookbook_file.rb +++ b/lib/chef/provider/cookbook_file.rb @@ -39,6 +39,7 @@ class Chef def managing_content? return true if new_resource.checksum return true if !new_resource.source.nil? && @action != :create_if_missing + false end diff --git a/lib/chef/provider/cron.rb b/lib/chef/provider/cron.rb index 577876ccf2..aad59d1eba 100644 --- a/lib/chef/provider/cron.rb +++ b/lib/chef/provider/cron.rb @@ -25,11 +25,11 @@ class Chef provides :cron, os: ["!aix", "!solaris2"] - SPECIAL_TIME_VALUES = [:reboot, :yearly, :annually, :monthly, :weekly, :daily, :midnight, :hourly].freeze - CRON_ATTRIBUTES = [:minute, :hour, :day, :month, :weekday, :time, :command, :mailto, :path, :shell, :home, :environment].freeze - WEEKDAY_SYMBOLS = [:sunday, :monday, :tuesday, :wednesday, :thursday, :friday, :saturday].freeze + SPECIAL_TIME_VALUES = %i{reboot yearly annually monthly weekly daily midnight hourly}.freeze + CRON_ATTRIBUTES = %i{minute hour day month weekday time command mailto path shell home environment}.freeze + WEEKDAY_SYMBOLS = %i{sunday monday tuesday wednesday thursday friday saturday}.freeze - CRON_PATTERN = /\A([-0-9*,\/]+)\s([-0-9*,\/]+)\s([-0-9*,\/]+)\s([-0-9*,\/]+|[a-zA-Z]{3})\s([-0-9*,\/]+|[a-zA-Z]{3})\s(.*)/.freeze + CRON_PATTERN = %r{\A([-0-9*,/]+)\s([-0-9*,/]+)\s([-0-9*,/]+)\s([-0-9*,/]+|[a-zA-Z]{3})\s([-0-9*,/]+|[a-zA-Z]{3})\s(.*)}.freeze SPECIAL_PATTERN = /\A(@(#{SPECIAL_TIME_VALUES.join('|')}))\s(.*)/.freeze ENV_PATTERN = /\A(\S+)=(\S*)/.freeze ENVIRONMENT_PROPERTIES = %w{MAILTO PATH SHELL HOME}.freeze @@ -203,6 +203,7 @@ class Chef def read_crontab so = shell_out!("crontab -l -u #{new_resource.user}", returns: [0, 1]) return nil if so.exitstatus == 1 + so.stdout rescue => e raise Chef::Exceptions::Cron, "Error determining state of #{new_resource.name}, error: #{e}" @@ -218,7 +219,7 @@ class Chef def get_crontab_entry newcron = "" newcron << "# Chef Name: #{new_resource.name}\n" - [ :mailto, :path, :shell, :home ].each do |v| + %i{mailto path shell home}.each do |v| newcron << "#{v.to_s.upcase}=\"#{new_resource.send(v)}\"\n" if new_resource.send(v) end new_resource.environment.each do |name, value| diff --git a/lib/chef/provider/cron/unix.rb b/lib/chef/provider/cron/unix.rb index c89491cf45..f807ede3bb 100644 --- a/lib/chef/provider/cron/unix.rb +++ b/lib/chef/provider/cron/unix.rb @@ -42,6 +42,7 @@ class Chef raise Chef::Exceptions::Cron, "Error determining state of #{@new_resource.name}, exit: #{status}" end return nil if status > 0 + crontab.stdout.chomp << "\n" end diff --git a/lib/chef/provider/dsc_resource.rb b/lib/chef/provider/dsc_resource.rb index b7785a6660..da8b17ed04 100644 --- a/lib/chef/provider/dsc_resource.rb +++ b/lib/chef/provider/dsc_resource.rb @@ -34,7 +34,7 @@ class Chef end def action_run - if ! test_resource + unless test_resource converge_by(generate_description) do result = set_resource reboot_if_required @@ -42,8 +42,7 @@ class Chef end end - def load_current_resource - end + def load_current_resource; end def define_resource_requirements requirements.assert(:run) do |a| diff --git a/lib/chef/provider/dsc_script.rb b/lib/chef/provider/dsc_script.rb index d7ac9689ef..999ea9f33e 100644 --- a/lib/chef/provider/dsc_script.rb +++ b/lib/chef/provider/dsc_script.rb @@ -41,7 +41,7 @@ class Chef end def action_run - if ! @resource_converged + unless @resource_converged converge_by(generate_description) do run_configuration(:set) logger.info("DSC resource configuration completed successfully") @@ -162,7 +162,7 @@ class Chef # We ignore the last log message because it only contains the time it took, which looks weird cleaned_messages = resource.change_log[0..-2].map { |c| c.sub(/^#{Regexp.escape(resource.name)}/, "").strip } unless cleaned_messages.empty? - "converge DSC resource #{resource.name} by #{cleaned_messages.find_all { |c| c != '' }.join("\n")}" + "converge DSC resource #{resource.name} by #{cleaned_messages.find_all { |c| c != "" }.join("\n")}" else "converge DSC resource #{resource.name}" end diff --git a/lib/chef/provider/execute.rb b/lib/chef/provider/execute.rb index c4312b58b4..61107a84ba 100644 --- a/lib/chef/provider/execute.rb +++ b/lib/chef/provider/execute.rb @@ -121,7 +121,7 @@ class Chef def sentinel_file Pathname.new(Chef::Util::PathHelper.cleanpath( - ( cwd && creates_relative? ) ? ::File.join(cwd, creates) : creates + ( cwd && creates_relative? ) ? ::File.join(cwd, creates) : creates )) end diff --git a/lib/chef/provider/file.rb b/lib/chef/provider/file.rb index bf38a36a6a..054b9718c3 100644 --- a/lib/chef/provider/file.rb +++ b/lib/chef/provider/file.rb @@ -90,7 +90,7 @@ class Chef @current_resource ||= Chef::Resource::File.new(new_resource.name) current_resource.path(new_resource.path) - if !needs_creating? + unless needs_creating? # we are updating an existing file if managing_content? logger.trace("#{new_resource} checksumming file at #{new_resource.path}.") @@ -190,6 +190,7 @@ class Chef def managing_content? return true if new_resource.checksum return true if !new_resource.content.nil? && @action != :create_if_missing + false end @@ -339,8 +340,8 @@ class Chef if tempfile new_resource.verify.each do |v| - if ! v.verify(tempfile.path) - raise Chef::Exceptions::ValidationFailed.new "Proposed content for #{new_resource.path} failed verification #{new_resource.sensitive ? '[sensitive]' : v}" + unless v.verify(tempfile.path) + raise Chef::Exceptions::ValidationFailed.new "Proposed content for #{new_resource.path} failed verification #{new_resource.sensitive ? "[sensitive]" : v}" end end end @@ -459,6 +460,7 @@ class Chef # reporting won't work for Windows. return end + acl_scanner = ScanAccessControl.new(new_resource, resource) acl_scanner.set_all! end diff --git a/lib/chef/provider/git.rb b/lib/chef/provider/git.rb index 4d39485a62..b7ca81b3f8 100644 --- a/lib/chef/provider/git.rb +++ b/lib/chef/provider/git.rb @@ -51,12 +51,12 @@ class Chef end requirements.assert(:all_actions) do |a| - a.assertion { !(new_resource.revision =~ /^origin\//) } + a.assertion { !(new_resource.revision =~ %r{^origin/}) } a.failure_message Chef::Exceptions::InvalidRemoteGitReference, "Deploying remote branches is not supported. " + "Specify the remote branch as a local branch for " + "the git repository you're deploying from " + - "(ie: '#{new_resource.revision.gsub('origin/', '')}' rather than '#{new_resource.revision}')." + "(ie: '#{new_resource.revision.gsub("origin/", "")}' rather than '#{new_resource.revision}')." end requirements.assert(:all_actions) do |a| @@ -111,6 +111,7 @@ class Chef def git_gem_version return @git_gem_version if defined?(@git_gem_version) + output = git("--version").stdout match = GIT_VERSION_PATTERN.match(output) if match diff --git a/lib/chef/provider/group.rb b/lib/chef/provider/group.rb index ba84ea9468..1c8a18c037 100644 --- a/lib/chef/provider/group.rb +++ b/lib/chef/provider/group.rb @@ -66,7 +66,7 @@ class Chef if !new_resource.members.nil? && !new_resource.excluded_members.nil? common_members = new_resource.members & new_resource.excluded_members a.assertion { common_members.empty? } - a.failure_message(Chef::Exceptions::ConflictingMembersInGroup, "Attempting to both add and remove users from a group: '#{common_members.join(', ')}'") + a.failure_message(Chef::Exceptions::ConflictingMembersInGroup, "Attempting to both add and remove users from a group: '#{common_members.join(", ")}'") # No why-run alternative end end @@ -88,11 +88,12 @@ class Chef missing_members = [] new_resource.members.each do |member| next if has_current_group_member?(member) + validate_member!(member) missing_members << member end unless missing_members.empty? - @change_desc << "add missing member(s): #{missing_members.join(', ')}" + @change_desc << "add missing member(s): #{missing_members.join(", ")}" end members_to_be_removed = [] @@ -102,7 +103,7 @@ class Chef end end unless members_to_be_removed.empty? - @change_desc << "remove existing member(s): #{members_to_be_removed.join(', ')}" + @change_desc << "remove existing member(s): #{members_to_be_removed.join(", ")}" end elsif new_resource.members != current_resource.members @change_desc << "replace group members with new list of members" @@ -140,6 +141,7 @@ class Chef def action_remove return unless @group_exists + converge_by("remove group #{new_resource.group_name}") do remove_group logger.info("#{new_resource} removed") @@ -148,6 +150,7 @@ class Chef def action_manage return unless @group_exists && compare_group + converge_by(["manage group #{new_resource.group_name}"] + change_desc) do manage_group logger.info("#{new_resource} managed") @@ -156,6 +159,7 @@ class Chef def action_modify return unless compare_group + converge_by(["modify group #{new_resource.group_name}"] + change_desc) do manage_group logger.info("#{new_resource} modified") diff --git a/lib/chef/provider/group/aix.rb b/lib/chef/provider/group/aix.rb index 72bfc76d97..aa4d8ba4c4 100644 --- a/lib/chef/provider/group/aix.rb +++ b/lib/chef/provider/group/aix.rb @@ -54,6 +54,7 @@ class Chef def set_members(members) return if members.empty? + shell_out!("chgrpmem", "-m", "=", members.join(","), new_resource.group_name) end @@ -65,6 +66,7 @@ class Chef opts = [] { gid: "id" }.sort_by { |a| a[0] }.each do |field, option| next unless current_resource.send(field) != new_resource.send(field) + if new_resource.send(field) logger.trace("#{new_resource} setting #{field} to #{new_resource.send(field)}") opts << "#{option}=#{new_resource.send(field)}" diff --git a/lib/chef/provider/group/dscl.rb b/lib/chef/provider/group/dscl.rb index a5c4d27ddb..decad69e40 100644 --- a/lib/chef/provider/group/dscl.rb +++ b/lib/chef/provider/group/dscl.rb @@ -40,6 +40,7 @@ class Chef return "" if ( args.first =~ /^delete/ ) && ( result[1].exitstatus != 0 ) raise(Chef::Exceptions::Group, "dscl error: #{result.inspect}") unless result[1].exitstatus == 0 raise(Chef::Exceptions::Group, "dscl error: #{result.inspect}") if result[2] =~ /No such key: / + result[2] end @@ -88,6 +89,7 @@ class Chef def gid_used?(gid) return false unless gid + search_gids = safe_dscl("search", "/Groups", "PrimaryGroupID", gid.to_s) # dscl -search should not return anything if the gid doesn't exist, @@ -99,13 +101,14 @@ class Chef def set_gid new_resource.gid(get_free_gid) if [nil, ""].include? new_resource.gid raise(Chef::Exceptions::Group, "gid is already in use") if gid_used?(new_resource.gid) + safe_dscl("create", "/Groups/#{new_resource.group_name}", "PrimaryGroupID", new_resource.gid) end def set_members # First reset the memberships if the append is not set unless new_resource.append - logger.trace("#{new_resource} removing group members #{current_resource.members.join(' ')}") unless current_resource.members.empty? + logger.trace("#{new_resource} removing group members #{current_resource.members.join(" ")}") unless current_resource.members.empty? safe_dscl("create", "/Groups/#{new_resource.group_name}", "GroupMembers", "") # clear guid list safe_dscl("create", "/Groups/#{new_resource.group_name}", "GroupMembership", "") # clear user list current_resource.members([ ]) @@ -118,7 +121,7 @@ class Chef members_to_be_added << member unless current_resource.members.include?(member) end unless members_to_be_added.empty? - logger.trace("#{new_resource} setting group members #{members_to_be_added.join(', ')}") + logger.trace("#{new_resource} setting group members #{members_to_be_added.join(", ")}") safe_dscl("append", "/Groups/#{new_resource.group_name}", "GroupMembership", *members_to_be_added) end end @@ -130,7 +133,7 @@ class Chef members_to_be_removed << member if current_resource.members.include?(member) end unless members_to_be_removed.empty? - logger.trace("#{new_resource} removing group members #{members_to_be_removed.join(', ')}") + logger.trace("#{new_resource} removing group members #{members_to_be_removed.join(", ")}") safe_dscl("delete", "/Groups/#{new_resource.group_name}", "GroupMembership", *members_to_be_removed) end end diff --git a/lib/chef/provider/group/groupadd.rb b/lib/chef/provider/group/groupadd.rb index dd99a1c49a..eca104b565 100644 --- a/lib/chef/provider/group/groupadd.rb +++ b/lib/chef/provider/group/groupadd.rb @@ -111,6 +111,7 @@ class Chef { gid: "-g" }.sort_by { |a| a[0] }.each do |field, option| next unless current_resource.send(field) != new_resource.send(field) next unless new_resource.send(field) + opts << option opts << new_resource.send(field) logger.trace("#{new_resource} set #{field} to #{new_resource.send(field)}") diff --git a/lib/chef/provider/group/groupmod.rb b/lib/chef/provider/group/groupmod.rb index ac033e607d..c560e55f99 100644 --- a/lib/chef/provider/group/groupmod.rb +++ b/lib/chef/provider/group/groupmod.rb @@ -84,7 +84,7 @@ class Chef # Adds a list of usernames to the group using `user mod` def add_group_members(members) - logger.trace("#{new_resource} adding members #{members.join(', ')}") unless members.empty? + logger.trace("#{new_resource} adding members #{members.join(", ")}") unless members.empty? members.each do |user| shell_out!("user", "mod", "-G", new_resource.group_name, user) end diff --git a/lib/chef/provider/group/pw.rb b/lib/chef/provider/group/pw.rb index 2a1f294bde..c018de8d4d 100644 --- a/lib/chef/provider/group/pw.rb +++ b/lib/chef/provider/group/pw.rb @@ -44,7 +44,7 @@ class Chef # new or existing group. Because pw groupadd does not support the -m # and -d options used by manage_group, we treat group creation as a # special case and use -M. - logger.trace("#{new_resource} setting group members: #{new_resource.members.join(',')}") + logger.trace("#{new_resource} setting group members: #{new_resource.members.join(",")}") command += [ "-M", new_resource.members.join(",") ] end @@ -119,12 +119,12 @@ class Chef end unless members_to_be_added.empty? - logger.trace("#{new_resource} adding group members: #{members_to_be_added.join(',')}") + logger.trace("#{new_resource} adding group members: #{members_to_be_added.join(",")}") opts << [ "-m", members_to_be_added.join(",") ] end unless members_to_be_removed.empty? - logger.trace("#{new_resource} removing group members: #{members_to_be_removed.join(',')}") + logger.trace("#{new_resource} removing group members: #{members_to_be_removed.join(",")}") opts << [ "-d", members_to_be_removed.join(",") ] end diff --git a/lib/chef/provider/group/suse.rb b/lib/chef/provider/group/suse.rb index f17c1fc005..7bd9700a15 100644 --- a/lib/chef/provider/group/suse.rb +++ b/lib/chef/provider/group/suse.rb @@ -45,8 +45,8 @@ class Chef false end end - a.failure_message Chef::Exceptions::Group, "Could not add users #{to_add(new_resource.members).join(', ')} to #{new_resource.group_name}: one of these users does not exist" - a.whyrun "Could not find one of these users: #{to_add(new_resource.members).join(', ')}. Assuming it will be created by a prior step" + a.failure_message Chef::Exceptions::Group, "Could not add users #{to_add(new_resource.members).join(", ")} to #{new_resource.group_name}: one of these users does not exist" + a.whyrun "Could not find one of these users: #{to_add(new_resource.members).join(", ")}. Assuming it will be created by a prior step" end end diff --git a/lib/chef/provider/group/usermod.rb b/lib/chef/provider/group/usermod.rb index 79a774a4c3..b4e93580ff 100644 --- a/lib/chef/provider/group/usermod.rb +++ b/lib/chef/provider/group/usermod.rb @@ -59,6 +59,7 @@ class Chef unless new_resource.action.include?(:create) raise Chef::Exceptions::UnsupportedAction, "Setting members directly is not supported by #{self}" end + members.each do |member| add_member(member) end diff --git a/lib/chef/provider/group/windows.rb b/lib/chef/provider/group/windows.rb index fc4d7df96b..6dda6a7cc2 100644 --- a/lib/chef/provider/group/windows.rb +++ b/lib/chef/provider/group/windows.rb @@ -90,7 +90,7 @@ class Chef end def locally_qualified_name(account_name) - account_name.include?("\\") ? account_name : "#{ENV['COMPUTERNAME']}\\#{account_name}" + account_name.include?("\\") ? account_name : "#{ENV["COMPUTERNAME"]}\\#{account_name}" end def validate_member!(member) diff --git a/lib/chef/provider/http_request.rb b/lib/chef/provider/http_request.rb index 6859385f7b..3f475f005f 100644 --- a/lib/chef/provider/http_request.rb +++ b/lib/chef/provider/http_request.rb @@ -120,7 +120,7 @@ class Chef private def check_message(message) - if message.kind_of?(Proc) + if message.is_a?(Proc) message.call else message diff --git a/lib/chef/provider/ifconfig.rb b/lib/chef/provider/ifconfig.rb index 0ca419da0f..93db827e97 100644 --- a/lib/chef/provider/ifconfig.rb +++ b/lib/chef/provider/ifconfig.rb @@ -87,6 +87,7 @@ class Chef end next unless @interfaces.key?(new_resource.device) + @interface = @interfaces.fetch(new_resource.device) current_resource.target(new_resource.target) @@ -116,11 +117,11 @@ class Chef @int_name = "nil" elsif line.match(addr_regex)[2] == "" @int_name = line.match(addr_regex)[1] - @interfaces[@int_name] = Hash.new + @interfaces[@int_name] = {} @interfaces[@int_name]["mtu"] = (line =~ /mtu (\S+)/ ? Regexp.last_match(1) : "nil") if line =~ /mtu/ && @interfaces[@int_name]["mtu"].nil? else @int_name = "#{line.match(addr_regex)[1]}:#{line.match(addr_regex)[2]}" - @interfaces[@int_name] = Hash.new + @interfaces[@int_name] = {} @interfaces[@int_name]["mtu"] = (line =~ /mtu (\S+)/ ? Regexp.last_match(1) : "nil") if line =~ /mtu/ && @interfaces[@int_name]["mtu"].nil? end else @@ -132,6 +133,7 @@ class Chef end next unless @interfaces.key?(new_resource.device) + @interface = @interfaces.fetch(new_resource.device) current_resource.target(new_resource.target) @@ -144,6 +146,7 @@ class Chef current_resource.metric(@interface["metric"]) end end + current_resource end @@ -162,7 +165,7 @@ class Chef unless current_resource.inet_addr unless new_resource.device == loopback_device command = add_command - converge_by("run #{command.join(' ')} to add #{new_resource}") do + converge_by("run #{command.join(" ")} to add #{new_resource}") do shell_out!(command) logger.info("#{new_resource} added") end @@ -177,8 +180,9 @@ class Chef # enables, but does not manage config files return if current_resource.inet_addr return if new_resource.device == loopback_device + command = enable_command - converge_by("run #{command.join(' ')} to enable #{new_resource}") do + converge_by("run #{command.join(" ")} to enable #{new_resource}") do shell_out!(command) logger.info("#{new_resource} enabled") end @@ -188,7 +192,7 @@ class Chef # check to see if load_current_resource found the interface if current_resource.device command = delete_command - converge_by("run #{command.join(' ')} to delete #{new_resource}") do + converge_by("run #{command.join(" ")} to delete #{new_resource}") do shell_out!(command) logger.info("#{new_resource} deleted") end @@ -203,7 +207,7 @@ class Chef # disables, but leaves config files in place. if current_resource.device command = disable_command - converge_by("run #{command.join(' ')} to disable #{new_resource}") do + converge_by("run #{command.join(" ")} to disable #{new_resource}") do shell_out!(command) logger.info("#{new_resource} disabled") end @@ -222,6 +226,7 @@ class Chef def generate_config return unless can_generate_config? + b = binding template = ::ERB.new(@config_template) config = resource_for_config(@config_path) @@ -232,6 +237,7 @@ class Chef def delete_config return unless can_generate_config? + config = resource_for_config(@config_path) config.run_action(:delete) new_resource.updated_by_last_action(true) if config.updated? diff --git a/lib/chef/provider/ifconfig/aix.rb b/lib/chef/provider/ifconfig/aix.rb index 1b52060ad2..2f83336f8d 100644 --- a/lib/chef/provider/ifconfig/aix.rb +++ b/lib/chef/provider/ifconfig/aix.rb @@ -66,6 +66,7 @@ class Chef def add_command # ifconfig changes are temporary, chdev persist across reboots. raise Chef::Exceptions::Ifconfig, "interface metric property cannot be set for :add action" if new_resource.metric + command = [ "chdev", "-l", new_resource.device, "-a", "netaddr=#{new_resource.name}" ] command += [ "-a", "netmask=#{new_resource.mask}" ] if new_resource.mask command += [ "-a", "mtu=#{new_resource.mtu}" ] if new_resource.mtu diff --git a/lib/chef/provider/ifconfig/debian.rb b/lib/chef/provider/ifconfig/debian.rb index 614cd7baf9..17d5fdd243 100644 --- a/lib/chef/provider/ifconfig/debian.rb +++ b/lib/chef/provider/ifconfig/debian.rb @@ -65,6 +65,7 @@ iface <%= new_resource.device %> <%= new_resource.family %> static def enforce_interfaces_dot_d_sanity # on ubuntu 18.04 there's no interfaces file and it uses interfaces.d by default return if ::File.directory?(INTERFACES_DOT_D_DIR) && !::File.exist?(INTERFACES_FILE) + # create /etc/network/interfaces.d via dir resource (to get reporting, etc) dir = Chef::Resource::Directory.new(INTERFACES_DOT_D_DIR, run_context) dir.run_action(:create) diff --git a/lib/chef/provider/launchd.rb b/lib/chef/provider/launchd.rb index 880c5d9aa7..4f20a417a6 100644 --- a/lib/chef/provider/launchd.rb +++ b/lib/chef/provider/launchd.rb @@ -29,18 +29,18 @@ class Chef extend Forwardable provides :launchd, os: "darwin" - def_delegators :new_resource, *[ - :backup, - :cookbook, - :group, - :label, - :mode, - :owner, - :path, - :source, - :session_type, - :type, - ] + def_delegators :new_resource, *%i{ + backup + cookbook + group + label + mode + owner + path + source + session_type + type + } def load_current_resource current_resource = Chef::Resource::Launchd.new(new_resource.name) @@ -90,6 +90,7 @@ class Chef def manage_plist(action) return unless manage_agent?(action) + if source res = cookbook_file_resource else @@ -102,6 +103,7 @@ class Chef def manage_service(action) return unless manage_agent?(action) + res = service_resource res.run_action(action) new_resource.updated_by_last_action(true) if res.updated? @@ -112,7 +114,7 @@ class Chef console_user = Etc.getpwuid(::File.stat("/dev/console").uid).name root = console_user == "root" agent = type == "agent" - invalid_action = [:delete, :disable, :enable, :restart].include?(action) + invalid_action = %i{delete disable enable restart}.include?(action) lltstype = "" if new_resource.limit_load_to_session_type lltstype = new_resource.limit_load_to_session_type @@ -179,6 +181,7 @@ class Chef def gen_hash return nil unless new_resource.program || new_resource.program_arguments + { "label" => "Label", "program" => "Program", diff --git a/lib/chef/provider/lwrp_base.rb b/lib/chef/provider/lwrp_base.rb index 80cb4a34a8..37ea5d9647 100644 --- a/lib/chef/provider/lwrp_base.rb +++ b/lib/chef/provider/lwrp_base.rb @@ -42,8 +42,7 @@ class Chef # no-op `load_current_resource`. Allows simple LWRP providers to work # without defining this method explicitly (silences # Chef::Exceptions::Override exception) - def load_current_resource - end + def load_current_resource; end # class methods class <<self diff --git a/lib/chef/provider/mount.rb b/lib/chef/provider/mount.rb index e8e2b4dc7b..f7843319f0 100644 --- a/lib/chef/provider/mount.rb +++ b/lib/chef/provider/mount.rb @@ -167,6 +167,7 @@ class Chef if (tries -= 1) < 0 raise Chef::Exceptions::Mount, "Retries exceeded waiting for filesystem to unmount" end + sleep 0.1 end end diff --git a/lib/chef/provider/mount/aix.rb b/lib/chef/provider/mount/aix.rb index 68a4552bab..29e31f166e 100644 --- a/lib/chef/provider/mount/aix.rb +++ b/lib/chef/provider/mount/aix.rb @@ -110,7 +110,7 @@ class Chef when /#{search_device}\s+#{Regexp.escape(@new_resource.mount_point)}/ mounted = true logger.trace("Special device #{device_logstring} mounted as #{@new_resource.mount_point}") - when /^[\/\w]+\s+#{Regexp.escape(@new_resource.mount_point)}\s+/ + when %r{^[/\w]+\s+#{Regexp.escape(@new_resource.mount_point)}\s+} mounted = false logger.trace("Found conflicting mount point #{@new_resource.mount_point} in /etc/fstab") end @@ -123,7 +123,7 @@ class Chef mountable? command = [ "mount", "-v", @new_resource.fstype ] - if !(@new_resource.options.nil? || @new_resource.options.empty?) + unless @new_resource.options.nil? || @new_resource.options.empty? command << "-o" command << @new_resource.options.join(",") end @@ -146,7 +146,7 @@ class Chef def remount_command if !(@new_resource.options.nil? || @new_resource.options.empty?) - [ "mount", "-o", "remount,#{@new_resource.options.join(',')}", @new_resource.device, @new_resource.mount_point ] + [ "mount", "-o", "remount,#{@new_resource.options.join(",")}", @new_resource.device, @new_resource.mount_point ] else [ "mount", "-o", "remount", @new_resource.device, @new_resource.mount_point ] end @@ -174,7 +174,7 @@ class Chef end fstab.puts("\tvfs\t\t= #{@new_resource.fstype}") fstab.puts("\tmount\t\t= false") - fstab.puts "\toptions\t\t= #{@new_resource.options.join(',')}" unless @new_resource.options.nil? || @new_resource.options.empty? + fstab.puts "\toptions\t\t= #{@new_resource.options.join(",")}" unless @new_resource.options.nil? || @new_resource.options.empty? logger.trace("#{@new_resource} is enabled at #{@new_resource.mount_point}") end end @@ -196,14 +196,14 @@ class Chef found_device = false ::File.open("/etc/filesystems", "r").each_line do |line| case line - when /^\/.+:\s*$/ + when %r{^/.+:\s*$} if line =~ /#{Regexp.escape(@new_resource.mount_point)}+:/ found_device = true else found_device = false end end - if !found_device + unless found_device contents << line end end diff --git a/lib/chef/provider/mount/mount.rb b/lib/chef/provider/mount/mount.rb index 304d922966..17b357ec70 100644 --- a/lib/chef/provider/mount/mount.rb +++ b/lib/chef/provider/mount/mount.rb @@ -47,6 +47,7 @@ class Chef elsif @new_resource.mount_point != "none" && !::File.exists?(@new_resource.mount_point) raise Chef::Exceptions::Mount, "Mount point #{@new_resource.mount_point} does not exist" end + true end @@ -70,7 +71,7 @@ class Chef @current_resource.pass($5.to_i) logger.trace("Found mount #{device_fstab} to #{@new_resource.mount_point} in /etc/fstab") next - when /^[\/\w]+\s+#{Regexp.escape(@new_resource.mount_point)}\s+/ + when %r{^[/\w]+\s+#{Regexp.escape(@new_resource.mount_point)}\s+} enabled = false logger.trace("Found conflicting mount point #{@new_resource.mount_point} in /etc/fstab") end @@ -95,7 +96,7 @@ class Chef when /^#{device_mount_regex}\s+on\s+#{Regexp.escape(real_mount_point)}\s/ mounted = true logger.trace("Special device #{device_logstring} mounted as #{real_mount_point}") - when /^([\/\w])+\son\s#{Regexp.escape(real_mount_point)}\s+/ + when %r{^([/\w])+\son\s#{Regexp.escape(real_mount_point)}\s+} mounted = false logger.trace("Special device #{$~[1]} mounted as #{real_mount_point}") end @@ -137,7 +138,7 @@ class Chef end def remount_command - [ "mount", "-o", "remount,#{@new_resource.options.join(',')}", @new_resource.mount_point ] + [ "mount", "-o", "remount,#{@new_resource.options.join(",")}", @new_resource.mount_point ] end def remount_fs @@ -200,7 +201,7 @@ class Chef end def network_device? - @new_resource.device =~ /:/ || @new_resource.device =~ /\/\// + @new_resource.device =~ /:/ || @new_resource.device =~ %r{//} end def device_should_exist? diff --git a/lib/chef/provider/mount/solaris.rb b/lib/chef/provider/mount/solaris.rb index 69659d4918..24f3a1f7ec 100644 --- a/lib/chef/provider/mount/solaris.rb +++ b/lib/chef/provider/mount/solaris.rb @@ -93,7 +93,7 @@ class Chef # FIXME: Should remount always do the remount or only if the options change? actual_options = native_options(options) actual_options.delete("-") - mount_options = actual_options.empty? ? "" : ",#{actual_options.join(',')}" + mount_options = actual_options.empty? ? "" : ",#{actual_options.join(",")}" shell_out!("mount", "-o", "remount#{mount_options}", mount_point) end @@ -158,7 +158,7 @@ class Chef when /^#{device_regex}\s+on\s+#{Regexp.escape(mount_point)}\s+/ logger.trace("Special device #{device} is mounted as #{mount_point}") mounted = true - when /^([\/\w]+)\son\s#{Regexp.escape(mount_point)}\s+/ + when %r{^([/\w]+)\son\s#{Regexp.escape(mount_point)}\s+} logger.trace("Special device #{Regexp.last_match[1]} is mounted as #{mount_point}") mounted = false end @@ -180,7 +180,7 @@ class Chef # solaris /etc/vfstab format: # device device mount FS fsck mount mount # to mount to fsck point type pass at boot options - when /^#{device_regex}\s+[-\/\w]+\s+#{Regexp.escape(mount_point)}\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ + when %r{^#{device_regex}\s+[-/\w]+\s+#{Regexp.escape(mount_point)}\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)} enabled = true fstype = Regexp.last_match[1] options = Regexp.last_match[4] @@ -196,7 +196,7 @@ class Chef pass = (Regexp.last_match[2] == "-") ? 0 : Regexp.last_match[2].to_i logger.trace("Found mount #{device} to #{mount_point} in #{VFSTAB}") next - when /^[-\/\w]+\s+[-\/\w]+\s+#{Regexp.escape(mount_point)}\s+/ + when %r{^[-/\w]+\s+[-/\w]+\s+#{Regexp.escape(mount_point)}\s+} # if we find a mountpoint on top of our mountpoint, then we are not enabled enabled = false logger.trace("Found conflicting mount point #{mount_point} in #{VFSTAB}") diff --git a/lib/chef/provider/package.rb b/lib/chef/provider/package.rb index 2c984b780e..5ccb264adf 100644 --- a/lib/chef/provider/package.rb +++ b/lib/chef/provider/package.rb @@ -68,8 +68,8 @@ class Chef # 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 @@ -77,8 +77,8 @@ 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 @@ -102,6 +102,7 @@ class Chef description = [] target_version_array.each_with_index do |target_version, i| next if target_version.nil? + package_name = package_name_array[i] description << "install version #{target_version} of package #{package_name}" end @@ -130,6 +131,7 @@ class Chef description = [] target_version_array.each_with_index do |target_version, i| next if target_version.nil? + package_name = package_name_array[i] candidate_version = candidate_version_array[i] current_version = current_version_array[i] || "uninstalled" @@ -231,8 +233,7 @@ class Chef end # Subclasses will override this to a method and provide a preseed file path - def prepare_for_installation - end + def prepare_for_installation; end # @todo use composition rather than inheritance @@ -322,6 +323,7 @@ class Chef # def version_equals?(v1, v2) return false unless v1 && v2 + v1 == v2 end @@ -507,6 +509,7 @@ class Chef missing = [] each_package do |package_name, new_version, current_version, candidate_version| next if new_version.nil? || current_version.nil? + if !version_requirement_satisfied?(current_version, new_version) && candidate_version.nil? missing.push(package_name) end diff --git a/lib/chef/provider/package/apt.rb b/lib/chef/provider/package/apt.rb index cd28746411..744e5b2e83 100644 --- a/lib/chef/provider/package/apt.rb +++ b/lib/chef/provider/package/apt.rb @@ -84,9 +84,7 @@ class Chef @locked_packages ||= begin locked = shell_out!("apt-mark", "showhold") - locked.stdout.each_line.map do |line| - line.strip - end + locked.stdout.each_line.map(&:strip) end end @@ -134,6 +132,7 @@ class Chef # @return [Boolean] if apt-get supports --allow-downgrades def supports_allow_downgrade? return @supports_allow_downgrade unless @supports_allow_downgrade.nil? + @supports_allow_downgrade = ( version_compare(apt_version, "1.1.0") >= 0 ) end @@ -194,6 +193,7 @@ class Chef 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| # there may be multiple reverse provides for a single package acc.add(line.split[0]) @@ -201,6 +201,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 + set.to_a.first end diff --git a/lib/chef/provider/package/bff.rb b/lib/chef/provider/package/bff.rb index b0a89454b5..0b358dcb46 100644 --- a/lib/chef/provider/package/bff.rb +++ b/lib/chef/provider/package/bff.rb @@ -84,6 +84,7 @@ class Chef def candidate_version return @candidate_version if @candidate_version + if package_source_found? ret = shell_out("installp", "-L", "-d", new_resource.source) ret.stdout.each_line do |line| diff --git a/lib/chef/provider/package/cab.rb b/lib/chef/provider/package/cab.rb index 9b2aaa048f..fd099811e0 100644 --- a/lib/chef/provider/package/cab.rb +++ b/lib/chef/provider/package/cab.rb @@ -78,6 +78,7 @@ class Chef result = shell_out("dism.exe /Online /English #{command} /NoRestart", { timeout: new_resource.timeout }) if result.exitstatus == -2146498530 raise Chef::Exceptions::Package, "The specified package is not applicable to this image." if result.stdout.include?("0x800f081e") + result.error! end result @@ -88,7 +89,7 @@ class Chef # e.g. Package_for_KB2975719~31bf3856ad364e35~amd64~~6.3.1.8 package = new_cab_identity # Search for just the package name to catch a different version being installed - logger.trace("#{new_resource} searching for installed package #{package['name']}") + logger.trace("#{new_resource} searching for installed package #{package["name"]}") existing_package_identities = installed_packages.map do |p| split_package_identity(p["package_identity"]) end @@ -101,7 +102,7 @@ class Chef found_packages.first["version"] else # Presuming this won't happen, otherwise we need to handle it - raise Chef::Exceptions::Package, "Found multiple packages installed matching name #{package['name']}, found: #{found_packages.length} matches" + raise Chef::Exceptions::Package, "Found multiple packages installed matching name #{package["name"]}, found: #{found_packages.length} matches" end end @@ -127,6 +128,7 @@ class Chef text.each_line do |line| key, value = line.split(":") if line.start_with?("Package Identity") next if key.nil? || value.nil? + package = {} package[key.downcase.strip.tr(" ", "_")] = value.strip.chomp packages << package diff --git a/lib/chef/provider/package/chocolatey.rb b/lib/chef/provider/package/chocolatey.rb index a7e6096cd6..a09bbf55de 100644 --- a/lib/chef/provider/package/chocolatey.rb +++ b/lib/chef/provider/package/chocolatey.rb @@ -59,8 +59,8 @@ class Chef # 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 @@ -154,6 +154,7 @@ class Chef # run before choco.exe gets called from #load_current_resource. exe_path = ::File.join(choco_install_path.to_s, "bin", "choco.exe") raise Chef::Exceptions::MissingLibrary, CHOCO_MISSING_MSG unless ::File.exist?(exe_path) + exe_path end end @@ -230,6 +231,7 @@ class Chef # @return [Hash] name-to-version mapping of available packages def available_packages return @available_packages if @available_packages + @available_packages = {} package_name_array.each do |pkg| available_versions = @@ -266,6 +268,7 @@ class Chef hash = {} choco_command(*args).stdout.each_line do |line| next if line.start_with?("Chocolatey v") + name, version = line.split("|") hash[name.downcase] = version&.chomp end diff --git a/lib/chef/provider/package/dnf.rb b/lib/chef/provider/package/dnf.rb index 5cfc82ad1c..d7b61e0789 100644 --- a/lib/chef/provider/package/dnf.rb +++ b/lib/chef/provider/package/dnf.rb @@ -126,7 +126,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 diff --git a/lib/chef/provider/package/dnf/python_helper.rb b/lib/chef/provider/package/dnf/python_helper.rb index 881c852392..c5edbfbc3a 100644 --- a/lib/chef/provider/package/dnf/python_helper.rb +++ b/lib/chef/provider/package/dnf/python_helper.rb @@ -161,6 +161,7 @@ class Chef retry else raise e if output.empty? + raise "dnf-helper.py had stderr output:\n\n#{output}" end end diff --git a/lib/chef/provider/package/dpkg.rb b/lib/chef/provider/package/dpkg.rb index eaeb5c8fce..e6012edee8 100644 --- a/lib/chef/provider/package/dpkg.rb +++ b/lib/chef/provider/package/dpkg.rb @@ -75,17 +75,17 @@ class Chef def install_package(name, version) sources = name.map { |n| name_sources[n] } - logger.info("#{new_resource} installing package(s): #{name.join(' ')}") + logger.info("#{new_resource} installing package(s): #{name.join(" ")}") run_noninteractive("dpkg", "-i", *options, *sources) end def remove_package(name, version) - logger.info("#{new_resource} removing package(s): #{name.join(' ')}") + logger.info("#{new_resource} removing package(s): #{name.join(" ")}") run_noninteractive("dpkg", "-r", *options, *name) end def purge_package(name, version) - logger.info("#{new_resource} purging packages(s): #{name.join(' ')}") + logger.info("#{new_resource} purging packages(s): #{name.join(" ")}") run_noninteractive("dpkg", "-P", *options, *name) end @@ -218,7 +218,7 @@ class Chef # # @return [Boolean] true if we're doing :install or :upgrade def installing? - [:install, :upgrade].include?(action) + %i{install upgrade}.include?(action) end end diff --git a/lib/chef/provider/package/freebsd/base.rb b/lib/chef/provider/package/freebsd/base.rb index 7c1b244283..70ca3f4a98 100644 --- a/lib/chef/provider/package/freebsd/base.rb +++ b/lib/chef/provider/package/freebsd/base.rb @@ -37,12 +37,12 @@ class Chef case port # When the package name starts with a '/' treat it as the full path to the ports directory. - when /^\// + when %r{^/} port # Otherwise if the package name contains a '/' not at the start (like 'www/wordpress') treat # as a relative path from /usr/ports. - when /\// + when %r{/} "/usr/ports/#{port}" # Otherwise look up the path to the ports directory using 'whereis' @@ -51,6 +51,7 @@ class Chef unless path = whereis.stdout[/^#{Regexp.escape(port)}:\s+(.+)$/, 1] raise Chef::Exceptions::Package, "Could not find port with the name #{port}" end + path end end diff --git a/lib/chef/provider/package/freebsd/pkgng.rb b/lib/chef/provider/package/freebsd/pkgng.rb index a3d70ad9cd..48fc7a0dd5 100644 --- a/lib/chef/provider/package/freebsd/pkgng.rb +++ b/lib/chef/provider/package/freebsd/pkgng.rb @@ -27,7 +27,7 @@ class Chef def install_package(name, version) unless current_resource.version case new_resource.source - when /^(http|ftp|\/)/ + when %r{^(http|ftp|/)} shell_out!("pkg", "add", options, new_resource.source, env: { "LC_ALL" => nil }).status logger.trace("#{new_resource} installed from: #{new_resource.source}") else @@ -38,7 +38,7 @@ class Chef def remove_package(name, version) options_dup = options && options.map { |str| str.sub(repo_regex, "") }.reject!(&:empty?) - shell_out!("pkg", "delete", "-y", options_dup, "#{name}#{version ? '-' + version : ''}", env: nil).status + shell_out!("pkg", "delete", "-y", options_dup, "#{name}#{version ? "-" + version : ""}", env: nil).status end def current_installed_version diff --git a/lib/chef/provider/package/homebrew.rb b/lib/chef/provider/package/homebrew.rb index f71aaf1882..3d60ee4380 100644 --- a/lib/chef/provider/package/homebrew.rb +++ b/lib/chef/provider/package/homebrew.rb @@ -126,7 +126,7 @@ class Chef homebrew_uid = find_homebrew_uid(new_resource.respond_to?(:homebrew_user) && new_resource.homebrew_user) homebrew_user = Etc.getpwuid(homebrew_uid) - logger.trace "Executing '#{command.join(' ')}' as user '#{homebrew_user.name}'" + logger.trace "Executing '#{command.join(" ")}' as user '#{homebrew_user.name}'" # FIXME: this 1800 second default timeout should be deprecated output = shell_out!(*command, timeout: 1800, user: homebrew_uid, environment: { "HOME" => homebrew_user.dir, "RUBYOPT" => nil, "TMPDIR" => nil }) output.stdout.chomp diff --git a/lib/chef/provider/package/macports.rb b/lib/chef/provider/package/macports.rb index 384435778d..1d0bfa9984 100644 --- a/lib/chef/provider/package/macports.rb +++ b/lib/chef/provider/package/macports.rb @@ -93,6 +93,7 @@ class Chef unless status.exitstatus == 0 || status.exitstatus == 1 raise Chef::Exceptions::Package, "#{command} failed - #{status.inspect}!" end + output end end diff --git a/lib/chef/provider/package/msu.rb b/lib/chef/provider/package/msu.rb index 073d3f6454..a00b3f3471 100644 --- a/lib/chef/provider/package/msu.rb +++ b/lib/chef/provider/package/msu.rb @@ -54,6 +54,7 @@ class Chef else current_resource.version(get_current_versions) end + current_resource end @@ -125,7 +126,7 @@ class Chef def extract_msu_contents(msu_file, destination) with_os_architecture(nil) do - shell_out!("#{ENV['SYSTEMROOT']}\\system32\\expand.exe -f:* #{msu_file} #{destination}") + shell_out!("#{ENV["SYSTEMROOT"]}\\system32\\expand.exe -f:* #{msu_file} #{destination}") end end @@ -148,6 +149,7 @@ class Chef cab_files end + cab_files end diff --git a/lib/chef/provider/package/openbsd.rb b/lib/chef/provider/package/openbsd.rb index b7f8260e7b..38ff84f105 100644 --- a/lib/chef/provider/package/openbsd.rb +++ b/lib/chef/provider/package/openbsd.rb @@ -130,7 +130,7 @@ class Chef 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/paludis.rb b/lib/chef/provider/package/paludis.rb index 27854f31be..3fd526abe4 100644 --- a/lib/chef/provider/package/paludis.rb +++ b/lib/chef/provider/package/paludis.rb @@ -38,6 +38,7 @@ class Chef 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| res = re.match(line) next if res.nil? + case res[3] when "accounts", "installed-accounts" next diff --git a/lib/chef/provider/package/portage.rb b/lib/chef/provider/package/portage.rb index aa8b9852b0..889d262d1e 100644 --- a/lib/chef/provider/package/portage.rb +++ b/lib/chef/provider/package/portage.rb @@ -38,7 +38,7 @@ class Chef 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] @@ -49,7 +49,7 @@ class Chef 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) diff --git a/lib/chef/provider/package/powershell.rb b/lib/chef/provider/package/powershell.rb index 7901569532..a27f7fa6c8 100644 --- a/lib/chef/provider/package/powershell.rb +++ b/lib/chef/provider/package/powershell.rb @@ -39,10 +39,11 @@ class Chef 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 diff --git a/lib/chef/provider/package/rpm.rb b/lib/chef/provider/package/rpm.rb index 45dbf91061..75b41a26e4 100644 --- a/lib/chef/provider/package/rpm.rb +++ b/lib/chef/provider/package/rpm.rb @@ -116,6 +116,7 @@ class Chef def uri_scheme?(str) scheme = URI.split(str).first return false unless scheme + %w{http https ftp file}.include?(scheme.downcase) rescue URI::InvalidURIError false diff --git a/lib/chef/provider/package/rubygems.rb b/lib/chef/provider/package/rubygems.rb index 8179deceed..876a90392c 100644 --- a/lib/chef/provider/package/rubygems.rb +++ b/lib/chef/provider/package/rubygems.rb @@ -199,7 +199,7 @@ class Chef logger.trace { "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(', ')}]" + source_list = sources.compact.empty? ? "[#{Gem.sources.to_a.join(", ")}]" : "[#{sources.join(", ")}]" logger.warn { "failed to find gem #{gem_dependency} from #{source_list}" } nil end @@ -421,11 +421,11 @@ class Chef def is_omnibus? if RbConfig::CONFIG["bindir"] =~ %r{/(opscode|chef|chefdk)/embedded/bin} - logger.trace("#{new_resource} detected omnibus installation in #{RbConfig::CONFIG['bindir']}") + logger.trace("#{new_resource} detected omnibus installation in #{RbConfig::CONFIG["bindir"]}") # Omnibus installs to a static path because of linking on unix, find it. true elsif RbConfig::CONFIG["bindir"].sub(/^[\w]:/, "") == "/opscode/chef/embedded/bin" - logger.trace("#{new_resource} detected omnibus installation in #{RbConfig::CONFIG['bindir']}") + logger.trace("#{new_resource} detected omnibus installation in #{RbConfig::CONFIG["bindir"]}") # windows, with the drive letter removed true else @@ -444,6 +444,7 @@ class Chef def source_is_remote? return true if new_resource.source.nil? return true if new_resource.source.is_a?(Array) + scheme = URI.parse(new_resource.source).scheme # URI.parse gets confused by MS Windows paths with forward slashes. scheme = nil if scheme =~ /^[a-z]$/ @@ -516,6 +517,7 @@ class Chef def version_requirement_satisfied?(current_version, new_version) return false unless current_version && new_version + Gem::Requirement.new(new_version).satisfied_by?(Gem::Version.new(current_version)) end diff --git a/lib/chef/provider/package/smartos.rb b/lib/chef/provider/package/smartos.rb index be1e6f81a3..a44280ec75 100644 --- a/lib/chef/provider/package/smartos.rb +++ b/lib/chef/provider/package/smartos.rb @@ -56,6 +56,7 @@ class Chef def candidate_version return @candidate_version if @candidate_version + name = nil version = nil pkg = shell_out!("/opt/local/bin/pkgin", "se", new_resource.package_name, env: nil, returns: [0, 1]) diff --git a/lib/chef/provider/package/snap.rb b/lib/chef/provider/package/snap.rb index 8096f54659..cb639ff77f 100644 --- a/lib/chef/provider/package/snap.rb +++ b/lib/chef/provider/package/snap.rb @@ -154,6 +154,7 @@ class Chef if response["type"] == "error" raise "status: #{response["status"]}, kind: #{response["result"]["kind"]}, message: #{response["result"]["message"]}" end + response["change"] end @@ -177,6 +178,7 @@ class Chef end n += 1 raise "Snap operating timed out after #{n} seconds." if n == 300 + sleep(1) end end @@ -188,7 +190,7 @@ class Chef def get_snap_version_from_source(path) body = { "context-id" => "get_snap_version_from_source_#{path}", - "args" => ["info", path,], + "args" => ["info", path], }.to_json # json = call_snap_api('POST', '/v2/snapctl', body) @@ -319,6 +321,7 @@ class Chef unless [200, 404].include? json["status-code"] raise Chef::Exceptions::Package, json["result"], caller end + json["result"] end @@ -338,6 +341,7 @@ class Chef unless [200, 404].include? json["status-code"] raise Chef::Exceptions::Package, json["result"], caller end + json["result"] end diff --git a/lib/chef/provider/package/solaris.rb b/lib/chef/provider/package/solaris.rb index d30e783a1e..fb0e88ecdb 100644 --- a/lib/chef/provider/package/solaris.rb +++ b/lib/chef/provider/package/solaris.rb @@ -83,6 +83,7 @@ class Chef def candidate_version return @candidate_version if @candidate_version + status = shell_out("pkginfo", "-l", "-d", new_resource.source, new_resource.package_name) status.stdout.each_line do |line| case line @@ -95,6 +96,7 @@ class Chef unless status.exitstatus == 0 raise Chef::Exceptions::Package, "pkginfo -l -d #{new_resource.source} - #{status.inspect}!" end + @candidate_version end diff --git a/lib/chef/provider/package/windows/exe.rb b/lib/chef/provider/package/windows/exe.rb index 7663bf0ad4..947f66e238 100644 --- a/lib/chef/provider/package/windows/exe.rb +++ b/lib/chef/provider/package/windows/exe.rb @@ -1,7 +1,7 @@ # # Author:: Seth Chisamore (<schisamo@chef.io>) # Author:: Matt Wrock <matt@mattwrock.com> -# Copyright:: Copyright 2011-2016, Chef Software, Inc. +# Copyright:: Copyright 2011-2019, Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -71,10 +71,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(&:uninstall_string).uniq.each do |uninstall_string| - logger.trace("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| + logger.trace("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 diff --git a/lib/chef/provider/package/windows/msi.rb b/lib/chef/provider/package/windows/msi.rb index 870aff6865..91b3d7a2b2 100644 --- a/lib/chef/provider/package/windows/msi.rb +++ b/lib/chef/provider/package/windows/msi.rb @@ -60,6 +60,7 @@ class Chef def package_version return new_resource.version if new_resource.version + if !new_resource.source.nil? && ::File.exist?(new_resource.source) logger.trace("#{new_resource} getting product version for package at #{new_resource.source}") get_product_property(new_resource.source, "ProductVersion") @@ -80,13 +81,13 @@ class Chef else uninstall_version = new_resource.version || installed_version uninstall_entries.select { |entry| [uninstall_version].flatten.include?(entry.display_version) } - .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/ - logger.trace("#{new_resource} removing MSI package version using '#{uninstall_string}'") - shell_out!(uninstall_string, timeout: new_resource.timeout, returns: new_resource.returns) - end + .map(&:uninstall_string).uniq.each do |uninstall_string| + uninstall_string = "msiexec /x #{uninstall_string.match(/{.*}/)}" + uninstall_string += expand_options(new_resource.options) + uninstall_string += " /q" unless uninstall_string.downcase =~ %r{ /q} + logger.trace("#{new_resource} removing MSI package version using '#{uninstall_string}'") + shell_out!(uninstall_string, timeout: new_resource.timeout, returns: new_resource.returns) + end end end end diff --git a/lib/chef/provider/package/windows/registry_uninstall_entry.rb b/lib/chef/provider/package/windows/registry_uninstall_entry.rb index d57f700799..6f8f359894 100644 --- a/lib/chef/provider/package/windows/registry_uninstall_entry.rb +++ b/lib/chef/provider/package/windows/registry_uninstall_entry.rb @@ -58,6 +58,7 @@ class Chef def self.quiet_uninstall_string_key?(quiet_uninstall_string, hkey, key, entry) return RegistryUninstallEntry.new(hkey, key, entry) if quiet_uninstall_string.nil? + RegistryUninstallEntry.new(hkey, key, entry, "QuietUninstallString") end diff --git a/lib/chef/provider/package/yum.rb b/lib/chef/provider/package/yum.rb index 74343fa10d..e32457cc0c 100644 --- a/lib/chef/provider/package/yum.rb +++ b/lib/chef/provider/package/yum.rb @@ -156,7 +156,7 @@ class Chef # this will resolve things like `/usr/bin/perl` or virtual packages like `mysql` -- it will not work (well? at all?) with globs that match multiple packages def resolved_package_lock_names(names) names.each_with_index.map do |name, i| - if !name.nil? + unless name.nil? if installed_version(i).version.nil? available_version(i).name else @@ -186,16 +186,19 @@ class Chef def version_gt?(v1, v2) return false if v1.nil? || v2.nil? + python_helper.compare_versions(v1, v2) == 1 end def version_equals?(v1, v2) return false if v1.nil? || v2.nil? + python_helper.compare_versions(v1, v2) == 0 end def version_compare(v1, v2) return false if v1.nil? || v2.nil? + python_helper.compare_versions(v1, v2) end @@ -213,7 +216,7 @@ class Chef # does not match what the yum 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 diff --git a/lib/chef/provider/package/yum/python_helper.rb b/lib/chef/provider/package/yum/python_helper.rb index ee7f64d1ea..f99b17bcce 100644 --- a/lib/chef/provider/package/yum/python_helper.rb +++ b/lib/chef/provider/package/yum/python_helper.rb @@ -165,7 +165,7 @@ class Chef end # Special handling for certain action / param combos - if [:whatinstalled, :whatavailable].include?(action) + if %i{whatinstalled whatavailable}.include?(action) add_version(hash, parameters["version"]) unless parameters["version"].nil? end @@ -212,6 +212,7 @@ class Chef retry else raise e if output.empty? + raise "yum-helper.py had stderr/stdout output:\n\n#{output}" end end diff --git a/lib/chef/provider/reboot.rb b/lib/chef/provider/reboot.rb index 407d847313..7fd3c32d53 100644 --- a/lib/chef/provider/reboot.rb +++ b/lib/chef/provider/reboot.rb @@ -49,7 +49,7 @@ class Chef reason: new_resource.reason, timestamp: Time.now, requested_by: new_resource.name - ) + ) end def action_request_reboot diff --git a/lib/chef/provider/registry_key.rb b/lib/chef/provider/registry_key.rb index 11d9f3f9b3..5dcb9f1959 100644 --- a/lib/chef/provider/registry_key.rb +++ b/lib/chef/provider/registry_key.rb @@ -76,7 +76,7 @@ class Chef def define_resource_requirements requirements.assert(:create, :create_if_missing, :delete, :delete_key) do |a| a.assertion { registry.hive_exists?(new_resource.key) } - a.failure_message(Chef::Exceptions::Win32RegHiveMissing, "Hive #{new_resource.key.split("\\").shift} does not exist") + a.failure_message(Chef::Exceptions::Win32RegHiveMissing, "Hive #{new_resource.key.split('\\').shift} does not exist") end requirements.assert(:create) do |a| @@ -122,7 +122,7 @@ class Chef new_resource.unscrubbed_values.each do |value| if @name_hash.key?(value[:name].downcase) current_value = @name_hash[value[:name].downcase] - if [:dword, :dword_big_endian, :qword].include? value[:type] + if %i{dword dword_big_endian qword}.include? value[:type] value[:data] = value[:data].to_i end unless current_value[:type] == value[:type] && current_value[:data] == value[:data] diff --git a/lib/chef/provider/remote_directory.rb b/lib/chef/provider/remote_directory.rb index 933ebe119d..e7d470916b 100644 --- a/lib/chef/provider/remote_directory.rb +++ b/lib/chef/provider/remote_directory.rb @@ -102,7 +102,7 @@ class Chef if purge Dir.glob(::File.join(Chef::Util::PathHelper.escape_glob_dir(path), "**", "*"), ::File::FNM_DOTMATCH).sort!.reverse!.each do |file| # skip '.' and '..' - next if [".", ".."].include?(Pathname.new(file).basename().to_s) + next if [".", ".."].include?(Pathname.new(file).basename.to_s) # Clean the path. This is required because of the ::File.join file = Chef::Util::PathHelper.cleanpath(file) diff --git a/lib/chef/provider/remote_file.rb b/lib/chef/provider/remote_file.rb index ba384ea3ba..a2506d6a15 100644 --- a/lib/chef/provider/remote_file.rb +++ b/lib/chef/provider/remote_file.rb @@ -32,18 +32,18 @@ class Chef def define_resource_requirements [ new_resource.remote_user, new_resource.remote_domain, new_resource.remote_password ].each do |prop| - requirements.assert(:all_actions) do |a| - a.assertion do - if prop - node[:platform_family] == "windows" - else - true + requirements.assert(:all_actions) do |a| + a.assertion do + if prop + node[:platform_family] == "windows" + else + true + end end + a.failure_message Chef::Exceptions::UnsupportedPlatform, "'remote_user', 'remote_domain' and 'remote_password' properties are supported only for Windows platform" + a.whyrun("Assuming that the platform is Windows while passing 'remote_user', 'remote_domain' and 'remote_password' properties") end - a.failure_message Chef::Exceptions::UnsupportedPlatform, "'remote_user', 'remote_domain' and 'remote_password' properties are supported only for Windows platform" - a.whyrun("Assuming that the platform is Windows while passing 'remote_user', 'remote_domain' and 'remote_password' properties") end - end super end @@ -58,6 +58,7 @@ class Chef def managing_content? return true if new_resource.checksum return true if !new_resource.source.nil? && @action != :create_if_missing + false end diff --git a/lib/chef/provider/remote_file/fetcher.rb b/lib/chef/provider/remote_file/fetcher.rb index 3011dd80a0..f007fe40db 100644 --- a/lib/chef/provider/remote_file/fetcher.rb +++ b/lib/chef/provider/remote_file/fetcher.rb @@ -24,9 +24,10 @@ class Chef def self.for_resource(uri, new_resource, current_resource) if network_share?(uri) - if !Chef::Platform.windows? + unless Chef::Platform.windows? raise Exceptions::UnsupportedPlatform, "Fetching the file on a network share is supported only on the Windows platform. Please change your source: #{uri}" end + Chef::Provider::RemoteFile::NetworkFile.new(uri, new_resource, current_resource) else case uri.scheme @@ -48,7 +49,7 @@ class Chef def self.network_share?(source) case source when String - !!(%r{\A\\\\[A-Za-z0-9+\-\.]+} =~ source) + !!(/\A\\\\[A-Za-z0-9+\-\.]+/ =~ source) else false end diff --git a/lib/chef/provider/remote_file/local_file.rb b/lib/chef/provider/remote_file/local_file.rb index 14877806ce..d4b71e24fa 100644 --- a/lib/chef/provider/remote_file/local_file.rb +++ b/lib/chef/provider/remote_file/local_file.rb @@ -35,7 +35,7 @@ class Chef # CHEF-4472: Remove the leading slash from windows paths that we receive from a file:// URI def fix_windows_path(path) - path.gsub(/^\/([a-zA-Z]:)/, '\1') + path.gsub(%r{^/([a-zA-Z]:)}, '\1') end def source_path diff --git a/lib/chef/provider/route.rb b/lib/chef/provider/route.rb index 1f78db07ad..009c57e546 100644 --- a/lib/chef/provider/route.rb +++ b/lib/chef/provider/route.rb @@ -111,6 +111,7 @@ class Chef # Skip formatting lines (header, etc) next unless destination && gateway && mask + logger.trace("#{new_resource} system has route: dest=#{destination} mask=#{mask} gw=#{gateway}") # check if what were trying to configure is already there @@ -132,7 +133,7 @@ class Chef logger.trace("#{new_resource} route already active - nothing to do") else command = generate_command(:add) - converge_by("run #{command.join(' ')} to add route") do + converge_by("run #{command.join(" ")} to add route") do shell_out!(*command) logger.info("#{new_resource} added") end @@ -145,7 +146,7 @@ class Chef def action_delete if is_running command = generate_command(:delete) - converge_by("run #{command.join(' ')} to delete route ") do + converge_by("run #{command.join(" ")} to delete route ") do shell_out!(*command) logger.info("#{new_resource} removed") end @@ -164,6 +165,7 @@ class Chef # walk the collection run_context.resource_collection.each do |resource| next unless resource.is_a? Chef::Resource::Route + # default to eth0 dev = if resource.device resource.device diff --git a/lib/chef/provider/service/aixinit.rb b/lib/chef/provider/service/aixinit.rb index 6469b6389c..05cdc2befe 100644 --- a/lib/chef/provider/service/aixinit.rb +++ b/lib/chef/provider/service/aixinit.rb @@ -22,7 +22,7 @@ class Chef class Provider class Service class AixInit < Chef::Provider::Service::Init - RC_D_SCRIPT_NAME = /\/etc\/rc.d\/rc2.d\/([SK])(\d\d|)/i.freeze + RC_D_SCRIPT_NAME = %r{/etc/rc.d/rc2.d/([SK])(\d\d|)}i.freeze def initialize(new_resource, run_context) super diff --git a/lib/chef/provider/service/arch.rb b/lib/chef/provider/service/arch.rb index fd1b54a302..bb209e22ae 100644 --- a/lib/chef/provider/service/arch.rb +++ b/lib/chef/provider/service/arch.rb @@ -34,6 +34,7 @@ class Chef::Provider::Service::Arch < Chef::Provider::Service::Init def load_current_resource raise Chef::Exceptions::Service, "Could not find /etc/rc.conf" unless ::File.exists?("/etc/rc.conf") raise Chef::Exceptions::Service, "No DAEMONS found in /etc/rc.conf" unless ::File.read("/etc/rc.conf") =~ /DAEMONS=\((.*)\)/m + super @current_resource.enabled(daemons.include?(@current_resource.service_name)) @@ -60,7 +61,7 @@ class Chef::Provider::Service::Arch < Chef::Provider::Service::Init # FIXME: Multiple entries of DAEMONS will cause very bad results :) def update_daemons(entries) - content = ::File.read("/etc/rc.conf").gsub(/DAEMONS=\((.*)\)/m, "DAEMONS=(#{entries.join(' ')})") + content = ::File.read("/etc/rc.conf").gsub(/DAEMONS=\((.*)\)/m, "DAEMONS=(#{entries.join(" ")})") ::File.open("/etc/rc.conf", "w") do |f| f.write(content) end diff --git a/lib/chef/provider/service/debian.rb b/lib/chef/provider/service/debian.rb index 059b9777d9..9f48504d5e 100644 --- a/lib/chef/provider/service/debian.rb +++ b/lib/chef/provider/service/debian.rb @@ -26,8 +26,8 @@ class Chef Chef::Platform::ServiceHelpers.service_resource_providers.include?(:debian) end - UPDATE_RC_D_ENABLED_MATCHES = /\/rc[\dS].d\/S|not installed/i.freeze - UPDATE_RC_D_PRIORITIES = /\/rc([\dS]).d\/([SK])(\d\d)/i.freeze + UPDATE_RC_D_ENABLED_MATCHES = %r{/rc[\dS].d/S|not installed}i.freeze + UPDATE_RC_D_PRIORITIES = %r{/rc([\dS]).d/([SK])(\d\d)}i.freeze def self.supports?(resource, action) Chef::Platform::ServiceHelpers.config_for_service(resource.service_name).include?(:initd) @@ -58,21 +58,22 @@ class Chef a.whyrun ["Unable to determine priority of service, assuming service would have been correctly installed earlier in the run.", "Assigning temporary priorities to continue.", "If this service is not properly installed prior to this point, this will fail."] do - temp_priorities = { "6" => [:stop, "20"], - "0" => [:stop, "20"], - "1" => [:stop, "20"], - "2" => [:start, "20"], - "3" => [:start, "20"], - "4" => [:start, "20"], - "5" => [:start, "20"] } - current_resource.priority(temp_priorities) - end + temp_priorities = { "6" => [:stop, "20"], + "0" => [:stop, "20"], + "1" => [:stop, "20"], + "2" => [:start, "20"], + "3" => [:start, "20"], + "4" => [:start, "20"], + "5" => [:start, "20"] } + current_resource.priority(temp_priorities) + end end end # returns a list of levels that the service should be stopped or started on def parse_init_file(path) return [] unless ::File.exist?(path) + in_info = false ::File.readlines(path).each_with_object([]) do |line, acc| if line =~ /^### BEGIN INIT INFO/ diff --git a/lib/chef/provider/service/freebsd.rb b/lib/chef/provider/service/freebsd.rb index ee0cad53f3..7733831945 100644 --- a/lib/chef/provider/service/freebsd.rb +++ b/lib/chef/provider/service/freebsd.rb @@ -118,7 +118,7 @@ class Chef private def read_rc_conf - ::File.open("/etc/rc.conf", "r") { |file| file.readlines } + ::File.open("/etc/rc.conf", "r", &:readlines) end def write_rc_conf(lines) diff --git a/lib/chef/provider/service/openbsd.rb b/lib/chef/provider/service/openbsd.rb index 3f28e69ce3..c368815418 100644 --- a/lib/chef/provider/service/openbsd.rb +++ b/lib/chef/provider/service/openbsd.rb @@ -78,7 +78,7 @@ class Chef end def enable_service - if !is_enabled? + unless is_enabled? if is_builtin? if is_enabled_by_default? update_rcl rc_conf_local.sub(/^#{Regexp.escape(builtin_service_enable_variable_name)}=.*/, "") @@ -92,9 +92,9 @@ class Chef old_services_list = old_services_list ? old_services_list[1].split(" ") : [] new_services_list = old_services_list + [new_resource.service_name] if rc_conf_local =~ /^pkg_scripts="(.*)"/ - new_rcl = rc_conf_local.sub(/^pkg_scripts="(.*)"/, "pkg_scripts=\"#{new_services_list.join(' ')}\"") + new_rcl = rc_conf_local.sub(/^pkg_scripts="(.*)"/, "pkg_scripts=\"#{new_services_list.join(" ")}\"") else - new_rcl = rc_conf_local + "\n" + "pkg_scripts=\"#{new_services_list.join(' ')}\"\n" + new_rcl = rc_conf_local + "\n" + "pkg_scripts=\"#{new_services_list.join(" ")}\"\n" end update_rcl new_rcl end @@ -132,7 +132,7 @@ class Chef end def update_rcl(value) - FileUtils.touch RC_CONF_LOCAL_PATH if !::File.exists? RC_CONF_LOCAL_PATH + FileUtils.touch RC_CONF_LOCAL_PATH unless ::File.exists? RC_CONF_LOCAL_PATH ::File.write(RC_CONF_LOCAL_PATH, value) @rc_conf_local = value end @@ -170,7 +170,7 @@ class Chef var_name = builtin_service_enable_variable_name if var_name if m = rc_conf.match(/^#{Regexp.escape(var_name)}=(.*)/) - if !(m[1] =~ /"?[Nn][Oo]"?/) + unless m[1] =~ /"?[Nn][Oo]"?/ result = true end end @@ -186,12 +186,12 @@ class Chef if var_name if m = rc_conf_local.match(/^#{Regexp.escape(var_name)}=(.*)/) @enabled_state_found = true - if !(m[1] =~ /"?[Nn][Oo]"?/) # e.g. looking for httpd_flags=NO + unless m[1] =~ /"?[Nn][Oo]"?/ # e.g. looking for httpd_flags=NO result = true end end end - if !@enabled_state_found + unless @enabled_state_found result = is_enabled_by_default? end else diff --git a/lib/chef/provider/service/redhat.rb b/lib/chef/provider/service/redhat.rb index f3c081534c..8751090d44 100644 --- a/lib/chef/provider/service/redhat.rb +++ b/lib/chef/provider/service/redhat.rb @@ -106,13 +106,13 @@ class Chef # @api private def levels - (run_levels.nil? || run_levels.empty?) ? "" : "--level #{run_levels.join('')} " + (run_levels.nil? || run_levels.empty?) ? "" : "--level #{run_levels.join("")} " end def enable_service unless run_levels.nil? || run_levels.empty? disable_levels = current_run_levels - run_levels - shell_out! "/sbin/chkconfig --level #{disable_levels.join('')} #{new_resource.service_name} off" unless disable_levels.empty? + shell_out! "/sbin/chkconfig --level #{disable_levels.join("")} #{new_resource.service_name} off" unless disable_levels.empty? end shell_out! "/sbin/chkconfig #{levels}#{new_resource.service_name} on" end diff --git a/lib/chef/provider/service/simple.rb b/lib/chef/provider/service/simple.rb index 302a2e75f4..754437b4a0 100644 --- a/lib/chef/provider/service/simple.rb +++ b/lib/chef/provider/service/simple.rb @@ -73,7 +73,8 @@ class Chef requirements.assert(:all_actions) do |a| a.assertion do @new_resource.status_command || supports[:status] || - (!ps_cmd.nil? && !ps_cmd.empty?) end + (!ps_cmd.nil? && !ps_cmd.empty?) + end a.failure_message Chef::Exceptions::Service, "#{@new_resource} could not determine how to inspect the process table, please set this node's 'command.ps' attribute" end requirements.assert(:all_actions) do |a| diff --git a/lib/chef/provider/service/systemd.rb b/lib/chef/provider/service/systemd.rb index 46541bac73..565668c081 100644 --- a/lib/chef/provider/service/systemd.rb +++ b/lib/chef/provider/service/systemd.rb @@ -62,8 +62,7 @@ class Chef::Provider::Service::Systemd < Chef::Provider::Service::Simple end # systemd supports user services just fine - def user_services_requirements - end + def user_services_requirements; end def define_resource_requirements shared_resource_requirements @@ -78,6 +77,7 @@ class Chef::Provider::Service::Systemd < Chef::Provider::Service::Simple def get_systemctl_options_args if new_resource.user raise NotImplementedError, "#{new_resource} does not support the user property on a target_mode host (yet)" if Chef::Config.target_mode? + uid = Etc.getpwnam(new_resource.user).uid options = { environment: { diff --git a/lib/chef/provider/service/upstart.rb b/lib/chef/provider/service/upstart.rb index f4ca45f8ea..8b2db84f35 100644 --- a/lib/chef/provider/service/upstart.rb +++ b/lib/chef/provider/service/upstart.rb @@ -32,7 +32,7 @@ class Chef Chef::Platform::ServiceHelpers.service_resource_providers.include?(:upstart) end - UPSTART_STATE_FORMAT = /\S+ \(?(start|stop)?\)? ?[\/ ](\w+)/.freeze + UPSTART_STATE_FORMAT = %r{\S+ \(?(start|stop)?\)? ?[/ ](\w+)}.freeze # Returns true if the configs for the service name has upstart variable def self.supports?(resource, action) @@ -51,6 +51,7 @@ class Chef def initialize(new_resource, run_context) # TODO: re-evaluate if this is needed after integrating cookbook fix raise ArgumentError, "run_context cannot be nil" unless run_context + super run_context.node @@ -82,7 +83,7 @@ class Chef # Do not call super, only call shared requirements shared_resource_requirements requirements.assert(:all_actions) do |a| - if !@command_success + unless @command_success whyrun_msg = if @new_resource.status_command "Provided status command #{@new_resource.status_command} failed." else diff --git a/lib/chef/provider/service/windows.rb b/lib/chef/provider/service/windows.rb index adb214711a..79ac2b1e29 100644 --- a/lib/chef/provider/service/windows.rb +++ b/lib/chef/provider/service/windows.rb @@ -211,8 +211,8 @@ class Chef::Provider::Service::Windows < Chef::Provider::Service converge_if_changed :service_type, :startup_type, :error_control, :binary_path_name, :load_order_group, :dependencies, :run_as_user, :display_name, :description do - Win32::Service.configure(windows_service_config(:configure)) - end + Win32::Service.configure(windows_service_config(:configure)) + end converge_delayed_start end @@ -307,7 +307,7 @@ class Chef::Provider::Service::Windows < Chef::Provider::Service # remove characters that make for broken or wonky filenames. def clean_username_for_path(username) - username.gsub(/[\/\\. ]+/, "_") + username.gsub(%r{[/\\. ]+}, "_") end def canonicalize_username(username) @@ -330,6 +330,7 @@ class Chef::Provider::Service::Windows < Chef::Provider::Service loop do break if current_state == desired_state raise Timeout::Error if ( retries += 1 ) > resource_timeout + sleep 1 end end diff --git a/lib/chef/provider/subversion.rb b/lib/chef/provider/subversion.rb index 580c879c97..dd3ece4786 100644 --- a/lib/chef/provider/subversion.rb +++ b/lib/chef/provider/subversion.rb @@ -36,7 +36,7 @@ class Chef def load_current_resource @current_resource = Chef::Resource::Subversion.new(new_resource.name) - unless [:export, :force_export].include?(Array(new_resource.action).first) + unless %i{export force_export}.include?(Array(new_resource.action).first) if current_revision = find_current_revision current_resource.revision current_revision end @@ -137,6 +137,7 @@ class Chef def find_current_revision return nil unless ::File.exist?(::File.join(new_resource.destination, ".svn")) + command = scm(:info) svn_info = shell_out!(command, run_options(cwd: cwd, returns: [0, 1])).stdout @@ -175,6 +176,7 @@ class Chef rev = (repo_attrs["Last Changed Rev"] || repo_attrs["Revision"]) rev.strip! if rev raise "Could not parse `svn info` data: #{svn_info}" if repo_attrs.empty? + logger.trace "#{new_resource} resolved revision #{new_resource.revision} to #{rev}" rev end @@ -185,6 +187,7 @@ class Chef # and will respond appropriately. def authentication return "" unless new_resource.svn_username + result = "--username #{new_resource.svn_username} " result << "--password #{new_resource.svn_password} " result diff --git a/lib/chef/provider/template.rb b/lib/chef/provider/template.rb index 4aab1697f2..f506462268 100644 --- a/lib/chef/provider/template.rb +++ b/lib/chef/provider/template.rb @@ -51,6 +51,7 @@ class Chef def managing_content? return true if new_resource.checksum return true if !new_resource.source.nil? && @action != :create_if_missing + false end diff --git a/lib/chef/provider/user.rb b/lib/chef/provider/user.rb index f4046a8bbf..38fe233d76 100644 --- a/lib/chef/provider/user.rb +++ b/lib/chef/provider/user.rb @@ -109,7 +109,7 @@ class Chef def compare_user return true if !new_resource.home.nil? && Pathname.new(new_resource.home).cleanpath != Pathname.new(current_resource.home).cleanpath - [ :comment, :shell, :password, :uid, :gid ].each do |user_attrib| + %i{comment shell password uid gid}.each do |user_attrib| return true if !new_resource.send(user_attrib).nil? && new_resource.send(user_attrib).to_s != current_resource.send(user_attrib).to_s end @@ -132,6 +132,7 @@ class Chef def action_remove return unless @user_exists + converge_by("remove user #{new_resource.username}") do remove_user logger.info("#{new_resource} removed") @@ -140,6 +141,7 @@ class Chef def action_manage return unless @user_exists && compare_user + converge_by("manage user #{new_resource.username}") do manage_user logger.info("#{new_resource} managed") @@ -148,6 +150,7 @@ class Chef def action_modify return unless compare_user + converge_by("modify user #{new_resource.username}") do manage_user logger.info("#{new_resource} modified") @@ -213,6 +216,7 @@ class Chef def updating_home? return false if new_resource.home.nil? return true if current_resource.home.nil? + # Pathname#cleanpath matches more edge conditions than File.expand_path() new_resource.home && Pathname.new(current_resource.home).cleanpath != Pathname.new(new_resource.home).cleanpath end diff --git a/lib/chef/provider/user/aix.rb b/lib/chef/provider/user/aix.rb index 230bc6183e..8a170d276a 100644 --- a/lib/chef/provider/user/aix.rb +++ b/lib/chef/provider/user/aix.rb @@ -32,6 +32,7 @@ class Chef add_password manage_home return if universal_options.empty? && usermod_options.empty? + shell_out!("usermod", universal_options, usermod_options, new_resource.username) end @@ -107,6 +108,7 @@ class Chef def add_password return unless current_resource.password != new_resource.password && new_resource.password + logger.trace("#{new_resource.username} setting password to #{new_resource.password}") command = "echo '#{new_resource.username}:#{new_resource.password}' | chpasswd -e" shell_out!(command) @@ -115,6 +117,7 @@ class Chef # Aix specific handling to update users home directory. def manage_home return unless updating_home? && new_resource.manage_home + # -m option does not work on aix, so move dir. if ::File.directory?(current_resource.home) logger.trace("Changing users home directory from #{current_resource.home} to #{new_resource.home}") diff --git a/lib/chef/provider/user/dscl.rb b/lib/chef/provider/user/dscl.rb index 1ec80af039..b8f85618da 100644 --- a/lib/chef/provider/user/dscl.rb +++ b/lib/chef/provider/user/dscl.rb @@ -128,7 +128,7 @@ in 'password', with the associated 'salt' and 'iterations'.") # Convert the salt from Base64 encoding to hex before consuming them current_resource.salt(shadow_hash["SALTED-SHA512-PBKDF2"]["salt"].string.unpack("H*").first) else - raise(Chef::Exceptions::User, "Unknown shadow_hash format: #{shadow_hash.keys.join(' ')}") + raise(Chef::Exceptions::User, "Unknown shadow_hash format: #{shadow_hash.keys.join(" ")}") end end @@ -230,6 +230,7 @@ in 'password', with the associated 'salt' and 'iterations'.") # def uid_used?(uid) return false unless uid + users_uids = run_dscl("list", "/Users", "uid").split("\n") uid_map = users_uids.each_with_object({}) do |tuid, tmap| x = tuid.split @@ -290,7 +291,7 @@ in 'password', with the associated 'salt' and 'iterations'.") end def validate_home_dir_specification! - unless new_resource.home =~ /^\// + unless new_resource.home =~ %r{^/} raise(Chef::Exceptions::InvalidHomeDirectory, "invalid path spec for User: '#{new_resource.username}', home directory: '#{new_resource.home}'") end end @@ -562,6 +563,7 @@ in 'password', with the associated 'salt' and 'iterations'.") # def dscl_set(user_hash, key, value) raise "Unknown dscl key #{key}" unless DSCL_PROPERTY_MAP.keys.include?(key) + user_hash[DSCL_PROPERTY_MAP[key]] = [ value ] user_hash end @@ -571,6 +573,7 @@ in 'password', with the associated 'salt' and 'iterations'.") # def dscl_get(user_hash, key) raise "Unknown dscl key #{key}" unless DSCL_PROPERTY_MAP.keys.include?(key) + # DSCL values are set as arrays value = user_hash[DSCL_PROPERTY_MAP[key]] value.nil? ? value : value.first @@ -585,12 +588,14 @@ in 'password', with the associated 'salt' and 'iterations'.") return "" if ( args.first =~ /^delete/ ) && ( result.exitstatus != 0 ) raise(Chef::Exceptions::DsclCommandFailed, "dscl error: #{result.inspect}") unless result.exitstatus == 0 raise(Chef::Exceptions::DsclCommandFailed, "dscl error: #{result.inspect}") if result.stdout =~ /No such key: / + result.stdout end def run_plutil(*args) result = shell_out("plutil", "-#{args[0]}", args[1..-1]) raise(Chef::Exceptions::PlistUtilCommandFailed, "plutil error: #{result.inspect}") unless result.exitstatus == 0 + if result.stdout.encoding == Encoding::ASCII_8BIT result.stdout.encode("utf-8", "binary", undef: :replace, invalid: :replace, replace: "?") else diff --git a/lib/chef/provider/user/linux.rb b/lib/chef/provider/user/linux.rb index a9a3e23cd9..d27dbcabd4 100644 --- a/lib/chef/provider/user/linux.rb +++ b/lib/chef/provider/user/linux.rb @@ -93,6 +93,7 @@ class Chef # checking "does not exist" has to come before exit code handling since centos and ubuntu differ in exit codes if passwd_s.stderr =~ /does not exist/ return false if whyrun_mode? + raise Chef::Exceptions::User, "User #{new_resource.username} does not exist when checking lock status for #{new_resource}" end diff --git a/lib/chef/provider/user/pw.rb b/lib/chef/provider/user/pw.rb index d03b7647ec..bc2991249b 100644 --- a/lib/chef/provider/user/pw.rb +++ b/lib/chef/provider/user/pw.rb @@ -77,6 +77,7 @@ class Chef field_list.sort_by { |a| a[0] }.each do |field, option| field_symbol = field.to_sym next unless current_resource.send(field_symbol) != new_resource.send(field_symbol) + if new_resource.send(field_symbol) logger.trace("#{new_resource} setting #{field} to #{new_resource.send(field_symbol)}") opts << option diff --git a/lib/chef/provider/user/solaris.rb b/lib/chef/provider/user/solaris.rb index 796d3b87cc..57893d23d5 100644 --- a/lib/chef/provider/user/solaris.rb +++ b/lib/chef/provider/user/solaris.rb @@ -37,6 +37,7 @@ class Chef def manage_user manage_password return if universal_options.empty? && usermod_options.empty? + shell_out!("usermod", universal_options, usermod_options, new_resource.username) end @@ -112,6 +113,7 @@ class Chef def manage_password return unless current_resource.password != new_resource.password && new_resource.password + logger.trace("#{new_resource} setting password to #{new_resource.password}") write_shadow_file end diff --git a/lib/chef/provider/user/windows.rb b/lib/chef/provider/user/windows.rb index 8a070f0d47..6d50e2c8ee 100644 --- a/lib/chef/provider/user/windows.rb +++ b/lib/chef/provider/user/windows.rb @@ -65,7 +65,7 @@ class Chef logger.trace("#{new_resource} password has changed") return true end - [ :uid, :comment, :home, :shell, :full_name ].any? do |user_attrib| + %i{uid comment home shell full_name}.any? do |user_attrib| !new_resource.send(user_attrib).nil? && new_resource.send(user_attrib) != current_resource.send(user_attrib) end end @@ -110,6 +110,7 @@ class Chef field_symbol = field.to_sym next unless current_resource.send(field_symbol) != new_resource.send(field_symbol) next unless new_resource.send(field_symbol) + unless field_symbol == :password logger.trace("#{new_resource} setting #{field} to #{new_resource.send(field_symbol)}") end diff --git a/lib/chef/provider/windows_env.rb b/lib/chef/provider/windows_env.rb index 6b76b23928..3fd4b18cfa 100644 --- a/lib/chef/provider/windows_env.rb +++ b/lib/chef/provider/windows_env.rb @@ -67,6 +67,7 @@ class Chef new_values.inject(0) do |index, val| next_index = current_values.find_index val return true if next_index.nil? || next_index < index + next_index end false @@ -99,6 +100,7 @@ class Chef # after we removed the element. def delete_element return false unless new_resource.delim # no delim: delete the key + needs_delete = new_values.any? { |v| current_values.include?(v) } if !needs_delete logger.trace("#{new_resource} element '#{new_resource.value}' does not exist") @@ -191,6 +193,7 @@ class Chef def env_obj(key_name) return @env_obj if @env_obj + wmi = WmiLite::Wmi.new # Note that by design this query is case insensitive with regard to key_name environment_variables = wmi.query("select * from Win32_Environment where name = '#{key_name}'") diff --git a/lib/chef/provider/windows_script.rb b/lib/chef/provider/windows_script.rb index 56651a23a6..172b07d712 100644 --- a/lib/chef/provider/windows_script.rb +++ b/lib/chef/provider/windows_script.rb @@ -58,7 +58,7 @@ class Chef rescue raise ensure - if ! wow64_redirection_state.nil? + unless wow64_redirection_state.nil? restore_wow64_file_redirection(@run_context.node, wow64_redirection_state) end end diff --git a/lib/chef/provider/windows_task.rb b/lib/chef/provider/windows_task.rb index 49f67d680d..b94b6b875c 100644 --- a/lib/chef/provider/windows_task.rb +++ b/lib/chef/provider/windows_task.rb @@ -603,7 +603,8 @@ class Chef validate << "Command" if new_resource.command.nil? || new_resource.command.empty? validate << "Task Name" if new_resource.task_name.nil? || new_resource.task_name.empty? return true if validate.empty? - raise Chef::Exceptions::ValidationFailed.new "Value for '#{validate.join(', ')}' option cannot be empty" + + raise Chef::Exceptions::ValidationFailed.new "Value for '#{validate.join(", ")}' option cannot be empty" end # rubocop:disable Style/StringLiteralsInInterpolation diff --git a/lib/chef/provider/yum_repository.rb b/lib/chef/provider/yum_repository.rb index f70ec2bbd9..9ae3bad29c 100644 --- a/lib/chef/provider/yum_repository.rb +++ b/lib/chef/provider/yum_repository.rb @@ -30,8 +30,7 @@ class Chef which "yum" end - def load_current_resource - end + def load_current_resource; end action :create do declare_resource(:template, "/etc/yum.repos.d/#{new_resource.repositoryid}.repo") do diff --git a/lib/chef/provider/zypper_repository.rb b/lib/chef/provider/zypper_repository.rb index 46d81430dd..764979cb3a 100644 --- a/lib/chef/provider/zypper_repository.rb +++ b/lib/chef/provider/zypper_repository.rb @@ -28,8 +28,7 @@ class Chef class ZypperRepository < Chef::Provider provides :zypper_repository, platform_family: "suse" - def load_current_resource - end + def load_current_resource; end action :create do if new_resource.gpgautoimportkeys @@ -135,7 +134,7 @@ class Chef def key_fingerprint(key_path) so = shell_out!("gpg --with-fingerprint #{key_path}") # expected output and match: http://rubular.com/r/BpfMjxySQM - fingerprint = /pub\s*\S*\/(\S*)/.match(so.stdout)[1].downcase + fingerprint = %r{pub\s*\S*/(\S*)}.match(so.stdout)[1].downcase logger.trace("GPG fingerprint of key at #{key_path} is #{fingerprint}") fingerprint end diff --git a/lib/chef/recipe.rb b/lib/chef/recipe.rb index 6bfc74d900..154072827e 100644 --- a/lib/chef/recipe.rb +++ b/lib/chef/recipe.rb @@ -47,6 +47,7 @@ class Chef [ $1.to_sym, $2 ] when /^::(.+)/ raise "current_cookbook is nil, cannot resolve #{recipe_name}" if current_cookbook.nil? + [ current_cookbook.to_sym, $1 ] else [ recipe_name.to_sym, "default" ] @@ -58,7 +59,7 @@ class Chef @recipe_name = recipe_name @run_context = run_context # TODO: 5/19/2010 cw/tim: determine whether this can be removed - @params = Hash.new + @params = {} end # Used in DSL mixins diff --git a/lib/chef/resource.rb b/lib/chef/resource.rb index 40dcbd1ed2..7f0895d6c9 100644 --- a/lib/chef/resource.rb +++ b/lib/chef/resource.rb @@ -121,7 +121,7 @@ class Chef end @before = nil - @params = Hash.new + @params = {} @provider = nil @allowed_actions = self.class.allowed_actions.to_a @action = self.class.default_action @@ -516,6 +516,7 @@ class Chef result[property.name] = send(property.name) end return result.values.first if identity_properties.size == 1 + result end @@ -581,6 +582,7 @@ class Chef begin return if should_skip?(action) + provider_for_action(action).run_action rescue StandardError => e if ignore_failure @@ -629,6 +631,7 @@ class Chef def to_text return "suppressed sensitive resource output" if sensitive + text = "# Declared in #{@source_line}\n\n" text << "#{resource_name}(\"#{name}\") do\n" @@ -641,7 +644,7 @@ class Chef end end - ivars = instance_variables.map { |ivar| ivar.to_sym } - HIDDEN_IVARS + ivars = instance_variables.map(&:to_sym) - HIDDEN_IVARS ivars.each do |ivar| iv = ivar.to_s.sub(/^@/, "") if all_props.keys.include?(iv) @@ -662,7 +665,7 @@ class Chef end def inspect - ivars = instance_variables.map { |ivar| ivar.to_sym } - FORBIDDEN_IVARS + ivars = instance_variables.map(&:to_sym) - FORBIDDEN_IVARS ivars.inject("<#{self}") do |str, ivar| str << " #{ivar}: #{instance_variable_get(ivar).inspect}" end << ">" @@ -672,8 +675,8 @@ class Chef # is loaded. activesupport will call as_json and skip over to_json. This ensure # json is encoded as expected def as_json(*a) - safe_ivars = instance_variables.map { |ivar| ivar.to_sym } - FORBIDDEN_IVARS - instance_vars = Hash.new + safe_ivars = instance_variables.map(&:to_sym) - FORBIDDEN_IVARS + instance_vars = {} safe_ivars.each do |iv| instance_vars[iv.to_s.sub(/^@/, "")] = instance_variable_get(iv) end @@ -695,10 +698,11 @@ class Chef self.class.state_properties.each do |p| result[p.name] = p.get(self) end - safe_ivars = instance_variables.map { |ivar| ivar.to_sym } - FORBIDDEN_IVARS + safe_ivars = instance_variables.map(&:to_sym) - FORBIDDEN_IVARS safe_ivars.each do |iv| key = iv.to_s.sub(/^@/, "").to_sym next if result.key?(key) + result[key] = instance_variable_get(iv) end result @@ -746,7 +750,7 @@ class Chef # @see Chef::Resource.action_class # def provider(arg = nil) - klass = if arg.kind_of?(String) || arg.kind_of?(Symbol) + klass = if arg.is_a?(String) || arg.is_a?(Symbol) lookup_provider_constant(arg) else arg @@ -779,7 +783,7 @@ class Chef # @return [Array<Symbol>] All property names with desired state. # def self.state_attrs(*names) - state_properties(*names).map { |property| property.name } + state_properties(*names).map(&:name) end # @@ -809,8 +813,9 @@ class Chef def self.identity_property(name = nil) result = identity_properties(*Array(name)) if result.size > 1 - raise Chef::Exceptions::MultipleIdentityError, "identity_property cannot be called on an object with more than one identity property (#{result.map { |r| r.name }.join(", ")})." + raise Chef::Exceptions::MultipleIdentityError, "identity_property cannot be called on an object with more than one identity property (#{result.map(&:name).join(", ")})." end + result.first end @@ -830,7 +835,8 @@ class Chef # def self.identity_attr(name = nil) property = identity_property(name) - return nil if !property + return nil unless property + property.name end @@ -951,7 +957,7 @@ class Chef if name name = name.to_sym # If our class is not already providing this name, provide it. - if !Chef::ResourceResolver.includes_handler?(name, self) + unless Chef::ResourceResolver.includes_handler?(name, self) provides name, canonical: true end @resource_name = name @@ -1104,6 +1110,7 @@ class Chef if provider.whyrun_mode? && !provider.whyrun_supported? raise "Cannot retrieve #{self.class.current_resource} in why-run mode: #{provider} does not support why-run" end + provider.load_current_resource provider.current_resource end @@ -1190,9 +1197,9 @@ class Chef # # FORBIDDEN_IVARS do not show up when the resource is converted to JSON (ie. hidden from data_collector and sending to the chef server via #to_json/to_h/as_json/inspect) - FORBIDDEN_IVARS = [:@run_context, :@logger, :@not_if, :@only_if, :@enclosing_provider, :@description, :@introduced, :@examples, :@validation_message, :@deprecated, :@default_description, :@skip_docs, :@executed_by_runner].freeze + FORBIDDEN_IVARS = %i{@run_context @logger @not_if @only_if @enclosing_provider @description @introduced @examples @validation_message @deprecated @default_description @skip_docs @executed_by_runner}.freeze # HIDDEN_IVARS do not show up when the resource is displayed to the user as text (ie. in the error inspector output via #to_text) - HIDDEN_IVARS = [:@allowed_actions, :@resource_name, :@source_line, :@run_context, :@logger, :@name, :@not_if, :@only_if, :@elapsed_time, :@enclosing_provider, :@description, :@introduced, :@examples, :@validation_message, :@deprecated, :@default_description, :@skip_docs, :@executed_by_runner].freeze + HIDDEN_IVARS = %i{@allowed_actions @resource_name @source_line @run_context @logger @name @not_if @only_if @elapsed_time @enclosing_provider @description @introduced @examples @validation_message @deprecated @default_description @skip_docs @executed_by_runner}.freeze include Chef::Mixin::ConvertToClassName extend Chef::Mixin::ConvertToClassName @@ -1289,7 +1296,7 @@ class Chef # life as well. @@sorted_descendants = nil def self.sorted_descendants - @@sorted_descendants ||= descendants.sort_by { |x| x.to_s } + @@sorted_descendants ||= descendants.sort_by(&:to_s) end def self.inherited(child) @@ -1376,6 +1383,7 @@ class Chef # the declared key we want to fall back on the old to_s key. def declared_key return to_s if declared_type.nil? + "#{declared_type}[#{@name}]" end @@ -1542,6 +1550,7 @@ class Chef def self.resource_for_node(short_name, node) klass = Chef::ResourceResolver.resolve(short_name, node: node) raise Chef::Exceptions::NoSuchResourceType.new(short_name, node) if klass.nil? + klass end @@ -1580,7 +1589,7 @@ class Chef def self.remove_canonical_dsl if @resource_name remaining = Chef.resource_handler_map.delete_canonical(@resource_name, self) - if !remaining + unless remaining Chef::DSL::Resources.remove_resource_dsl(@resource_name) end end diff --git a/lib/chef/resource/apt_package.rb b/lib/chef/resource/apt_package.rb index b94c480a29..020905d86a 100644 --- a/lib/chef/resource/apt_package.rb +++ b/lib/chef/resource/apt_package.rb @@ -42,7 +42,7 @@ class Chef property :response_file_variables, Hash, description: "A Hash of response file variables in the form of {'VARIABLE' => 'VALUE'}.", - default: lazy { Hash.new }, desired_state: false + default: lazy { {} }, desired_state: false end end diff --git a/lib/chef/resource/apt_repository.rb b/lib/chef/resource/apt_repository.rb index c70631253b..c73408807d 100644 --- a/lib/chef/resource/apt_repository.rb +++ b/lib/chef/resource/apt_repository.rb @@ -33,7 +33,7 @@ class Chef # defaults, but since we allowed users to pass nil here we need to continue # to allow that so don't refactor this however tempting it is property :repo_name, String, - regex: [/^[^\/]+$/], + regex: [%r{^[^/]+$}], description: "An optional property to set the repository name if it differs from the resource block's name. The value of this setting must not contain spaces.", validation_message: "repo_name property cannot contain a forward slash '/'", introduced: "14.1", name_property: true diff --git a/lib/chef/resource/build_essential.rb b/lib/chef/resource/build_essential.rb index e37b929fa5..b38ec6b24a 100644 --- a/lib/chef/resource/build_essential.rb +++ b/lib/chef/resource/build_essential.rb @@ -79,7 +79,7 @@ class Chef # Per OmniOS documentation, the gcc bin dir isn't in the default # $PATH, so add it to the running process environment # http://omnios.omniti.com/wiki.php/DevEnv - ENV["PATH"] = "#{ENV['PATH']}:/opt/gcc-4.7.2/bin" + ENV["PATH"] = "#{ENV["PATH"]}:/opt/gcc-4.7.2/bin" when "solaris2" package "autoconf" package "automake" @@ -110,7 +110,7 @@ class Chef package %w{ gcc48 gcc48-c++ } if node["platform_version"].to_i < 12 else Chef::Log.warn <<-EOH - The build_essential resource does not currently support the '#{node['platform_family']}' + The build_essential resource does not currently support the '#{node["platform_family"]}' platform family. Skipping... EOH end @@ -134,6 +134,7 @@ class Chef # @return [void] def after_created return unless compile_time + Array(action).each do |action| run_action(action) end diff --git a/lib/chef/resource/cab_package.rb b/lib/chef/resource/cab_package.rb index 04d6f97976..376a384bd7 100644 --- a/lib/chef/resource/cab_package.rb +++ b/lib/chef/resource/cab_package.rb @@ -1,6 +1,6 @@ # # Author:: Vasundhara Jagdale (<vasundhara.jagdale@msystechnologies.com>) -# Copyright:: Copyright 2008-2016, Chef Software, Inc. +# Copyright:: Copyright 2008-2019, Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -39,7 +39,7 @@ class Chef uri_scheme?(s) ? s : Chef::Util::PathHelper.canonical_path(s, false) end end), - default: lazy { |r| r.package_name }, default_description: "The package name." + default: lazy { package_name }, default_description: "The package name." end end end diff --git a/lib/chef/resource/chef_gem.rb b/lib/chef/resource/chef_gem.rb index 755040f26b..04492e2a26 100644 --- a/lib/chef/resource/chef_gem.rb +++ b/lib/chef/resource/chef_gem.rb @@ -37,10 +37,10 @@ class Chef class ChefGem < Chef::Resource::Package::GemPackage resource_name :chef_gem - property :gem_binary, default: "#{RbConfig::CONFIG['bindir']}/gem", default_description: "Chef's built-in gem binary.", + property :gem_binary, default: "#{RbConfig::CONFIG["bindir"]}/gem", default_description: "Chef's built-in gem binary.", description: "The path of a gem binary to use for the installation. By default, the same version of Ruby that is used by the #{Chef::Dist::CLIENT} will be installed.", callbacks: { - "The chef_gem resource is restricted to the current gem environment, use gem_package to install to other environments." => proc { |v| v == "#{RbConfig::CONFIG['bindir']}/gem" }, + "The chef_gem resource is restricted to the current gem environment, use gem_package to install to other environments." => proc { |v| v == "#{RbConfig::CONFIG["bindir"]}/gem" }, } property :compile_time, [TrueClass, FalseClass], description: "Controls the phase during which a gem is installed on a node. Set to 'true' to install a gem while the resource collection is being built (the 'compile phase'). Set to 'false' to install a gem while the #{Chef::Dist::CLIENT} is configuring the node (the 'converge phase').", diff --git a/lib/chef/resource/chef_handler.rb b/lib/chef/resource/chef_handler.rb index d5f4525744..80ee765ade 100644 --- a/lib/chef/resource/chef_handler.rb +++ b/lib/chef/resource/chef_handler.rb @@ -67,6 +67,7 @@ class Chef new_resource.type.each do |type, enable| next unless enable + register_handler(type, handler) end end diff --git a/lib/chef/resource/chocolatey_config.rb b/lib/chef/resource/chocolatey_config.rb index 3a3814db3a..2be4b7be0a 100644 --- a/lib/chef/resource/chocolatey_config.rb +++ b/lib/chef/resource/chocolatey_config.rb @@ -40,7 +40,7 @@ class Chef # @return [String] the element's value field def fetch_config_element(id) require "rexml/document" unless defined?(REXML::Document) - config_file = "#{ENV['ALLUSERSPROFILE']}\\chocolatey\\config\\chocolatey.config" + config_file = "#{ENV["ALLUSERSPROFILE"]}\\chocolatey\\config\\chocolatey.config" raise "Could not find the Chocolatey config at #{config_file}!" unless ::File.exist?(config_file) contents = REXML::Document.new(::File.read(config_file)) @@ -72,7 +72,7 @@ class Chef # @param [String] action the name of the action to perform # @return [String] the choco config command string def choco_cmd(action) - cmd = "#{ENV['ALLUSERSPROFILE']}\\chocolatey\\bin\\choco config #{action} --name #{new_resource.config_key}" + cmd = "#{ENV["ALLUSERSPROFILE"]}\\chocolatey\\bin\\choco config #{action} --name #{new_resource.config_key}" cmd << " --value #{new_resource.value}" if action == "set" cmd end diff --git a/lib/chef/resource/chocolatey_feature.rb b/lib/chef/resource/chocolatey_feature.rb index 1c190905f3..eef28cbe0a 100644 --- a/lib/chef/resource/chocolatey_feature.rb +++ b/lib/chef/resource/chocolatey_feature.rb @@ -39,7 +39,7 @@ class Chef # @return [String] the element's value field def fetch_feature_element(name) require "rexml/document" unless defined?(REXML::Document) - config_file = "#{ENV['ALLUSERSPROFILE']}\\chocolatey\\config\\chocolatey.config" + config_file = "#{ENV["ALLUSERSPROFILE"]}\\chocolatey\\config\\chocolatey.config" raise "Could not find the Chocolatey config at #{config_file}!" unless ::File.exist?(config_file) contents = REXML::Document.new(::File.read(config_file)) @@ -71,7 +71,7 @@ class Chef # @param [String] action the name of the action to perform # @return [String] the choco feature command string def choco_cmd(action) - cmd = "#{ENV['ALLUSERSPROFILE']}\\chocolatey\\bin\\choco feature #{action} --name #{new_resource.feature_name}" + cmd = "#{ENV["ALLUSERSPROFILE"]}\\chocolatey\\bin\\choco feature #{action} --name #{new_resource.feature_name}" cmd end end diff --git a/lib/chef/resource/chocolatey_source.rb b/lib/chef/resource/chocolatey_source.rb index 22ca387679..9f57e0dbdc 100644 --- a/lib/chef/resource/chocolatey_source.rb +++ b/lib/chef/resource/chocolatey_source.rb @@ -62,7 +62,7 @@ class Chef def fetch_source_element(id) require "rexml/document" unless defined?(REXML::Document) - config_file = "#{ENV['ALLUSERSPROFILE']}\\chocolatey\\config\\chocolatey.config" + config_file = "#{ENV["ALLUSERSPROFILE"]}\\chocolatey\\config\\chocolatey.config" raise "Could not find the Chocolatey config at #{config_file}!" unless ::File.exist?(config_file) config_contents = REXML::Document.new(::File.read(config_file)) @@ -114,7 +114,7 @@ class Chef # @param [String] action the name of the action to perform # @return [String] the choco source command string def choco_cmd(action) - cmd = "#{ENV['ALLUSERSPROFILE']}\\chocolatey\\bin\\choco source #{action} -n \"#{new_resource.source_name}\"" + cmd = "#{ENV["ALLUSERSPROFILE"]}\\chocolatey\\bin\\choco source #{action} -n \"#{new_resource.source_name}\"" if action == "add" cmd << " -s #{new_resource.source} --priority=#{new_resource.priority}" cmd << " --bypassproxy" if new_resource.bypass_proxy diff --git a/lib/chef/resource/cron.rb b/lib/chef/resource/cron.rb index ad8e228152..dbc6a998cc 100644 --- a/lib/chef/resource/cron.rb +++ b/lib/chef/resource/cron.rb @@ -160,7 +160,7 @@ class Chef property :environment, Hash, description: "A Hash of environment variables in the form of ({'ENV_VARIABLE' => 'VALUE'}).", - default: lazy { Hash.new } + default: lazy { {} } private diff --git a/lib/chef/resource/cron_d.rb b/lib/chef/resource/cron_d.rb index 6fcca2a231..3ebf415c50 100644 --- a/lib/chef/resource/cron_d.rb +++ b/lib/chef/resource/cron_d.rb @@ -35,9 +35,11 @@ class Chef # @return [Boolean] valid or not? def self.validate_numeric(spec, min, max) return true if spec == "*" + # binding.pry if spec.respond_to? :to_int return false unless spec >= min && spec <= max + return true end @@ -45,6 +47,7 @@ class Chef spec.split(%r{\/|-|,}).each do |x| next if x == "*" return false unless x =~ /^\d+$/ + x = x.to_i return false unless x >= min && x <= max end @@ -56,12 +59,14 @@ class Chef # @return [Boolean] valid or not? def self.validate_month(spec) return true if spec == "*" + if spec.respond_to? :to_int validate_numeric(spec, 1, 12) elsif spec.respond_to? :to_str return true if spec == "*" # Named abbreviations are permitted but not as part of a range or with stepping return true if %w{jan feb mar apr may jun jul aug sep oct nov dec}.include? spec.downcase + # 1-12 are legal for months validate_numeric(spec, 1, 12) else @@ -74,12 +79,14 @@ class Chef # @return [Boolean] valid or not? def self.validate_dow(spec) return true if spec == "*" + if spec.respond_to? :to_int validate_numeric(spec, 0, 7) elsif spec.respond_to? :to_str return true if spec == "*" # Named abbreviations are permitted but not as part of a range or with stepping return true if %w{sun mon tue wed thu fri sat}.include? spec.downcase + # 0-7 are legal for days of week validate_numeric(spec, 0, 7) else @@ -152,7 +159,7 @@ class Chef property :environment, Hash, description: "A Hash containing additional arbitrary environment variables under which the cron job will be run in the form of ``({'ENV_VARIABLE' => 'VALUE'})``.", - default: lazy { Hash.new } + default: lazy { {} } property :mode, [String, Integer], description: "The octal mode of the generated crontab file.", diff --git a/lib/chef/resource/dmg_package.rb b/lib/chef/resource/dmg_package.rb index dfe6eb45c6..403716cad7 100644 --- a/lib/chef/resource/dmg_package.rb +++ b/lib/chef/resource/dmg_package.rb @@ -1,6 +1,6 @@ # # Author:: Joshua Timberman (<jtimberman@chef.io>) -# Copyright:: 2011-2018, Chef Software, Inc. +# Copyright:: 2011-2019, Chef Software Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -48,12 +48,12 @@ class Chef property :volumes_dir, String, description: "The directory under /Volumes where the dmg is mounted if it differs from the name of the .dmg file.", - default: lazy { |r| r.app }, default_description: "The value passed for the application name." + default: lazy { app }, default_description: "The value passed for the application name." property :dmg_name, String, description: "The name of the .dmg file if it differs from that of the app, or if the name has spaces.", desired_state: false, - default: lazy { |r| r.app }, default_description: "The value passed for the application name." + default: lazy { app }, default_description: "The value passed for the application name." property :type, String, description: "The type of package.", diff --git a/lib/chef/resource/dnf_package.rb b/lib/chef/resource/dnf_package.rb index a89f6bfcff..c90e135335 100644 --- a/lib/chef/resource/dnf_package.rb +++ b/lib/chef/resource/dnf_package.rb @@ -56,21 +56,21 @@ class Chef description: "Flush the in-memory cache before or after a DNF operation that installs, upgrades, or removes a package. DNF automatically synchronizes remote metadata to a local cache. The #{Chef::Dist::CLIENT} creates a copy of the local cache, and then stores it in-memory during the #{Chef::Dist::CLIENT} run. The in-memory cache allows packages to be installed during the #{Chef::Dist::CLIENT} run without the need to continue synchronizing the remote metadata to the local cache while the #{Chef::Dist::CLIENT} run is in-progress.", default: { before: false, after: false }, coerce: proc { |v| - if v.is_a?(Hash) - v - elsif v.is_a?(Array) - v.each_with_object({}) { |arg, obj| obj[arg] = true } - elsif v.is_a?(TrueClass) || v.is_a?(FalseClass) - { before: v, after: v } - elsif v == :before - { before: true, after: false } - elsif v == :after - { after: true, before: false } - end - } + if v.is_a?(Hash) + v + elsif v.is_a?(Array) + v.each_with_object({}) { |arg, obj| obj[arg] = true } + elsif v.is_a?(TrueClass) || v.is_a?(FalseClass) + { before: v, after: v } + elsif v == :before + { before: true, after: false } + elsif v == :after + { after: true, before: false } + end + } def allow_downgrade(arg = nil) - if !arg.nil? + unless arg.nil? Chef.deprecated(:dnf_package_allow_downgrade, "the allow_downgrade property on the dnf_package provider is not used, DNF supports downgrades by default.") end false diff --git a/lib/chef/resource/dpkg_package.rb b/lib/chef/resource/dpkg_package.rb index 9e49dded46..116e17d6a6 100644 --- a/lib/chef/resource/dpkg_package.rb +++ b/lib/chef/resource/dpkg_package.rb @@ -35,7 +35,7 @@ class Chef property :response_file_variables, Hash, description: "A Hash of response file variables in the form of {'VARIABLE' => 'VALUE'}.", - default: lazy { Hash.new }, desired_state: false + default: lazy { {} }, desired_state: false end end end diff --git a/lib/chef/resource/dsc_resource.rb b/lib/chef/resource/dsc_resource.rb index 8d03231367..fe47d7fd1a 100644 --- a/lib/chef/resource/dsc_resource.rb +++ b/lib/chef/resource/dsc_resource.rb @@ -42,7 +42,7 @@ class Chef end "#{property}=>#{obj_text}" end - "{#{descriptions.join(', ')}}" + "{#{descriptions.join(", ")}}" end end @@ -77,7 +77,7 @@ class Chef description: "The version number of the module to use. PowerShell 5.0.10018.0 (or higher) supports having multiple versions of a module installed. This should be specified along with the module_name." def property(property_name, value = nil) - if not property_name.is_a?(Symbol) + unless property_name.is_a?(Symbol) raise TypeError, "A property name of type Symbol must be specified, '#{property_name}' of type #{property_name.class} was given" end @@ -99,7 +99,7 @@ class Chef # If the set method of the DSC resource indicate that a reboot # is necessary, reboot_action provides the mechanism for a reboot to # be requested. - property :reboot_action, Symbol, default: :nothing, equal_to: [:nothing, :reboot_now, :request_reboot], + property :reboot_action, Symbol, default: :nothing, equal_to: %i{nothing reboot_now request_reboot}, introduced: "12.6", description: "Use to request an immediate reboot or to queue a reboot using the :reboot_now (immediate reboot) or :request_reboot (queued reboot) actions built into the reboot resource." diff --git a/lib/chef/resource/dsc_script.rb b/lib/chef/resource/dsc_script.rb index 83f355c9c4..2ebb224b5b 100644 --- a/lib/chef/resource/dsc_script.rb +++ b/lib/chef/resource/dsc_script.rb @@ -45,6 +45,7 @@ class Chef if arg && configuration_name raise ArgumentError, "The 'code' and 'command' properties may not be used together" end + set_or_return( :code, arg, @@ -56,6 +57,7 @@ class Chef if arg && code raise ArgumentError, "Property `configuration_name` may not be set if `code` is set" end + set_or_return( :configuration_name, arg, @@ -67,6 +69,7 @@ class Chef if arg && code raise ArgumentError, "The 'code' and 'command' properties may not be used together" end + set_or_return( :command, arg, @@ -78,6 +81,7 @@ class Chef if arg && configuration_data_script raise ArgumentError, "The 'configuration_data' and 'configuration_data_script' properties may not be used together" end + set_or_return( :configuration_data, arg, @@ -89,6 +93,7 @@ class Chef if arg && configuration_data raise ArgumentError, "The 'configuration_data' and 'configuration_data_script' properties may not be used together" end + set_or_return( :configuration_data_script, arg, diff --git a/lib/chef/resource/execute.rb b/lib/chef/resource/execute.rb index 50fa0f13b2..add15e3085 100644 --- a/lib/chef/resource/execute.rb +++ b/lib/chef/resource/execute.rb @@ -1,7 +1,7 @@ # # Author:: Adam Jacob (<adam@chef.io>) # Author:: Tyler Cloke (<tyler@chef.io>) -# Copyright:: Copyright 2008-2018, Chef Software Inc. +# Copyright:: Copyright 2008-2019, Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -94,7 +94,7 @@ class Chef # lazy used to set default value of sensitive to true if password is set property :sensitive, [ TrueClass, FalseClass ], description: "Ensure that sensitive resource data is not logged by the #{Chef::Dist::CLIENT}.", - default: lazy { |r| r.password ? true : false }, default_description: "True if the password property is set. False otherwise." + default: lazy { password ? true : false }, default_description: "True if the password property is set. False otherwise." property :elevated, [ TrueClass, FalseClass ], default: false, description: "Determines whether the script will run with elevated permissions to circumvent User Access Control (UAC) interactively blocking the process.\nThis will cause the process to be run under a batch login instead of an interactive login. The user running #{Chef::Dist::CLIENT} needs the “Replace a process level token” and “Adjust Memory Quotas for a process” permissions. The user that is running the command needs the “Log on as a batch job” permission.\nBecause this requires a login, the user and password properties are required.", diff --git a/lib/chef/resource/file.rb b/lib/chef/resource/file.rb index 47fd9cada7..c737780e2d 100644 --- a/lib/chef/resource/file.rb +++ b/lib/chef/resource/file.rb @@ -1,7 +1,7 @@ # # Author:: Adam Jacob (<adam@chef.io>) # Author:: Seth Chisamore (<schisamo@chef.io>) -# Copyright:: Copyright 2008-2018, Chef Software Inc. +# Copyright:: Copyright 2008-2019, Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -55,7 +55,7 @@ class Chef property :path, String, name_property: true, identity: true, description: "The full path to the file, including the file name and its extension. For example: /files/file.txt. Default value: the name of the resource block. Microsoft Windows: A path that begins with a forward slash (/) will point to the root of the current working directory of the #{Chef::Dist::CLIENT} process. This path can vary from system to system. Therefore, using a path that begins with a forward slash (/) is not recommended." - property :atomic_update, [ TrueClass, FalseClass ], desired_state: false, default: lazy { |r| r.docker? && r.special_docker_files?(r.path) ? false : Chef::Config[:file_atomic_update] }, + property :atomic_update, [ TrueClass, FalseClass ], desired_state: false, default: lazy { docker? && special_docker_files?(path) ? false : Chef::Config[:file_atomic_update] }, description: "Perform atomic file updates on a per-resource basis. Set to true for atomic file updates. Set to false for non-atomic file updates. This setting overrides file_atomic_update, which is a global setting found in the client.rb file." property :backup, [ Integer, FalseClass ], desired_state: false, default: 5, @@ -78,7 +78,7 @@ class Chef property :verifications, Array, default: lazy { [] } def verify(command = nil, opts = {}, &block) - if ! (command.nil? || [String, Symbol].include?(command.class)) + unless command.nil? || [String, Symbol].include?(command.class) raise ArgumentError, "verify requires either a string, symbol, or a block" end diff --git a/lib/chef/resource/file/verification.rb b/lib/chef/resource/file/verification.rb index c0739a6d44..7cd3144509 100644 --- a/lib/chef/resource/file/verification.rb +++ b/lib/chef/resource/file/verification.rb @@ -77,6 +77,7 @@ class Chef if c.nil? raise Chef::Exceptions::VerificationNotFound.new "No file verification for #{name} found." end + c end @@ -113,6 +114,7 @@ class Chef if @command.include?("%{file}") raise ArgumentError, "The %{file} expansion for verify commands has been removed. Please use %{path} instead." end + command = @command % { path: path } interpreter = Chef::GuardInterpreter.for_resource(@parent_resource, command, @command_opts) interpreter.evaluate diff --git a/lib/chef/resource/file/verification/systemd_unit.rb b/lib/chef/resource/file/verification/systemd_unit.rb index 7e4090b5ac..63e8ded89b 100644 --- a/lib/chef/resource/file/verification/systemd_unit.rb +++ b/lib/chef/resource/file/verification/systemd_unit.rb @@ -46,6 +46,7 @@ class Chef def verify(path, opts = {}) return true unless systemd_analyze_path + Dir.mktmpdir("chef-systemd-unit") do |dir| temp = "#{dir}/#{::File.basename(@parent_resource.path)}" ::FileUtils.cp(path, temp) diff --git a/lib/chef/resource/git.rb b/lib/chef/resource/git.rb index dfb2921f97..4d5f4ac091 100644 --- a/lib/chef/resource/git.rb +++ b/lib/chef/resource/git.rb @@ -25,7 +25,7 @@ class Chef property :additional_remotes, Hash, description: "A Hash of additional remotes that are added to the git repository configuration.", - default: lazy { Hash.new } + default: lazy { {} } alias :branch :revision alias :reference :revision diff --git a/lib/chef/resource/homebrew_tap.rb b/lib/chef/resource/homebrew_tap.rb index 8f415a3ff1..23738d6e51 100644 --- a/lib/chef/resource/homebrew_tap.rb +++ b/lib/chef/resource/homebrew_tap.rb @@ -57,7 +57,7 @@ class Chef unless tapped?(new_resource.tap_name) converge_by("tap #{new_resource.tap_name}") do - shell_out!("#{new_resource.homebrew_path} tap #{new_resource.full ? '--full' : ''} #{new_resource.tap_name} #{new_resource.url || ''}", + shell_out!("#{new_resource.homebrew_path} tap #{new_resource.full ? "--full" : ""} #{new_resource.tap_name} #{new_resource.url || ""}", user: new_resource.owner, env: { "HOME" => ::Dir.home(new_resource.owner), "USER" => new_resource.owner }, cwd: ::Dir.home(new_resource.owner)) diff --git a/lib/chef/resource/hostname.rb b/lib/chef/resource/hostname.rb index 71160e983e..dab599c272 100644 --- a/lib/chef/resource/hostname.rb +++ b/lib/chef/resource/hostname.rb @@ -203,7 +203,7 @@ class Chef declare_resource(:execute, "svccfg -s system/identity:node setprop config/nodename=\'#{new_resource.hostname}\'") do notifies :run, "execute[svcadm refresh]", :immediately notifies :run, "execute[svcadm restart]", :immediately - not_if { shell_out!("svccfg -s system/identity:node listprop config/nodename").stdout.chomp =~ /config\/nodename\s+astring\s+#{new_resource.hostname}/ } + not_if { shell_out!("svccfg -s system/identity:node listprop config/nodename").stdout.chomp =~ %r{config/nodename\s+astring\s+#{new_resource.hostname}} } end declare_resource(:execute, "svcadm refresh") do command "svcadm refresh system/identity:node" diff --git a/lib/chef/resource/http_request.rb b/lib/chef/resource/http_request.rb index efcb807ed4..efcb379640 100644 --- a/lib/chef/resource/http_request.rb +++ b/lib/chef/resource/http_request.rb @@ -33,7 +33,7 @@ class Chef property :url, String, identity: true, description: "The URL to which an HTTP request is sent." - property :headers, Hash, default: lazy { Hash.new }, + property :headers, Hash, default: lazy { {} }, description: "A Hash of custom headers." def initialize(name, run_context = nil) diff --git a/lib/chef/resource/launchd.rb b/lib/chef/resource/launchd.rb index 6cc697eee8..39d95bbf69 100644 --- a/lib/chef/resource/launchd.rb +++ b/lib/chef/resource/launchd.rb @@ -77,54 +77,54 @@ class Chef description: "A Hash (similar to crontab) that defines the calendar frequency at which a job is started or an Array.", coerce: proc { |type| # Coerce into an array of hashes to make validation easier - array = if type.is_a?(Array) - type - else - [type] - end + array = if type.is_a?(Array) + type + else + [type] + end # Check to make sure that our array only has hashes - unless array.all? { |obj| obj.is_a?(Hash) } - error_msg = "start_calendar_interval must be a single hash or an array of hashes!" - raise Chef::Exceptions::ValidationFailed, error_msg - end + unless array.all? { |obj| obj.is_a?(Hash) } + error_msg = "start_calendar_interval must be a single hash or an array of hashes!" + raise Chef::Exceptions::ValidationFailed, error_msg + end # Make sure the hashes don't have any incorrect keys/values - array.each do |entry| - allowed_keys = %w{Minute Hour Day Weekday Month} - unless entry.keys.all? { |key| allowed_keys.include?(key) } - failed_keys = entry.keys.reject { |k| allowed_keys.include?(k) }.join(", ") - error_msg = "The following key(s): #{failed_keys} are invalid for start_calendar_interval, must be one of: #{allowed_keys.join(", ")}" - raise Chef::Exceptions::ValidationFailed, error_msg - end - - unless entry.values.all? { |val| val.is_a?(Integer) } - failed_values = entry.values.reject { |val| val.is_a?(Integer) }.join(", ") - error_msg = "Invalid value(s) (#{failed_values}) for start_calendar_interval item. Values must be integers!" - raise Chef::Exceptions::ValidationFailed, error_msg - end - end + array.each do |entry| + allowed_keys = %w{Minute Hour Day Weekday Month} + unless entry.keys.all? { |key| allowed_keys.include?(key) } + failed_keys = entry.keys.reject { |k| allowed_keys.include?(k) }.join(", ") + error_msg = "The following key(s): #{failed_keys} are invalid for start_calendar_interval, must be one of: #{allowed_keys.join(", ")}" + raise Chef::Exceptions::ValidationFailed, error_msg + end + + unless entry.values.all? { |val| val.is_a?(Integer) } + failed_values = entry.values.reject { |val| val.is_a?(Integer) }.join(", ") + error_msg = "Invalid value(s) (#{failed_values}) for start_calendar_interval item. Values must be integers!" + raise Chef::Exceptions::ValidationFailed, error_msg + end + end # Don't return array if we only have one entry - if array.size == 1 - array.first - else - array - end - } + if array.size == 1 + array.first + else + array + end + } property :type, String, description: "The type of resource. Possible values: daemon (default), agent.", default: "daemon", coerce: proc { |type| - type = type ? type.downcase : "daemon" - types = %w{daemon agent} - - unless types.include?(type) - error_msg = "type must be daemon or agent" - raise Chef::Exceptions::ValidationFailed, error_msg - end - type - } + type = type ? type.downcase : "daemon" + types = %w{daemon agent} + + unless types.include?(type) + error_msg = "type must be daemon or agent" + raise Chef::Exceptions::ValidationFailed, error_msg + end + type + } # Apple LaunchD Keys property :abandon_process_group, [ TrueClass, FalseClass ], diff --git a/lib/chef/resource/link.rb b/lib/chef/resource/link.rb index 66388a6463..81ca2f5600 100644 --- a/lib/chef/resource/link.rb +++ b/lib/chef/resource/link.rb @@ -56,8 +56,8 @@ class Chef property :link_type, [String, Symbol], description: "The type of link: :symbolic or :hard.", - coerce: proc { |arg| arg.kind_of?(String) ? arg.to_sym : arg }, - equal_to: [ :symbolic, :hard ], default: :symbolic + coerce: proc { |arg| arg.is_a?(String) ? arg.to_sym : arg }, + equal_to: %i{symbolic hard}, default: :symbolic property :group, [String, Integer], description: "A group name or ID number that identifies the group associated with a symbolic link.", diff --git a/lib/chef/resource/locale.rb b/lib/chef/resource/locale.rb index f833a4e7d3..8edb278e48 100644 --- a/lib/chef/resource/locale.rb +++ b/lib/chef/resource/locale.rb @@ -40,19 +40,19 @@ class Chef description: "A Hash of LC_* env variables in the form of ({ 'LC_ENV_VARIABLE' => 'VALUE' }).", default: lazy { {} }, coerce: proc { |h| - if h.respond_to?(:keys) - invalid_keys = h.keys - LC_VARIABLES - unless invalid_keys.empty? - error_msg = "Key of option lc_env must be equal to one of: \"#{LC_VARIABLES.join('", "')}\"! You passed \"#{invalid_keys.join(', ')}\"." - raise Chef::Exceptions::ValidationFailed, error_msg - end - end - unless h.values.all? { |x| x =~ LOCALE_REGEX } - error_msg = "Values of option lc_env should be non-empty string without any leading whitespaces." - raise Chef::Exceptions::ValidationFailed, error_msg - end - h - } + if h.respond_to?(:keys) + invalid_keys = h.keys - LC_VARIABLES + unless invalid_keys.empty? + error_msg = "Key of option lc_env must be equal to one of: \"#{LC_VARIABLES.join('", "')}\"! You passed \"#{invalid_keys.join(", ")}\"." + raise Chef::Exceptions::ValidationFailed, error_msg + end + end + unless h.values.all? { |x| x =~ LOCALE_REGEX } + error_msg = "Values of option lc_env should be non-empty string without any leading whitespaces." + raise Chef::Exceptions::ValidationFailed, error_msg + end + h + } # @deprecated Use {#lc_env} instead of this property. # {#lc_env} uses Hash with specific LC var as key. @@ -97,7 +97,7 @@ class Chef # @raise [Mixlib::ShellOut::ShellCommandFailed] not a supported language or locale # def generate_locales - shell_out!("locale-gen #{unavailable_locales.join(' ')}") + shell_out!("locale-gen #{unavailable_locales.join(" ")}") end # Updates system locale by appropriately writing them in /etc/locale.conf diff --git a/lib/chef/resource/log.rb b/lib/chef/resource/log.rb index 4f76ea12de..98cf0fb204 100644 --- a/lib/chef/resource/log.rb +++ b/lib/chef/resource/log.rb @@ -43,7 +43,7 @@ class Chef description: "The message to be added to a log file. If not specified we'll use the resource's name instead." property :level, Symbol, - equal_to: [ :debug, :info, :warn, :error, :fatal ], default: :info, + equal_to: %i{debug info warn error fatal}, default: :info, description: "The logging level to display this message at." allowed_actions :write diff --git a/lib/chef/resource/lwrp_base.rb b/lib/chef/resource/lwrp_base.rb index 54936725b1..0e19e59d6f 100644 --- a/lib/chef/resource/lwrp_base.rb +++ b/lib/chef/resource/lwrp_base.rb @@ -115,6 +115,7 @@ class Chef # +default_action+ and other DSL-y methods when extending LWRP::Base. def from_superclass(m, default = nil) return default if superclass == Chef::Resource::LWRPBase + superclass.respond_to?(m) ? superclass.send(m) : default end end diff --git a/lib/chef/resource/macos_userdefaults.rb b/lib/chef/resource/macos_userdefaults.rb index 75704400d5..02d65baee4 100644 --- a/lib/chef/resource/macos_userdefaults.rb +++ b/lib/chef/resource/macos_userdefaults.rb @@ -67,6 +67,7 @@ class Chef def coerce_booleans(val) return 1 if [true, "TRUE", "1", "true", "YES", "yes"].include?(val) return 0 if [false, "FALSE", "0", "false", "NO", "no"].include?(val) + val end diff --git a/lib/chef/resource/mount.rb b/lib/chef/resource/mount.rb index b800387975..a9e6b3374b 100644 --- a/lib/chef/resource/mount.rb +++ b/lib/chef/resource/mount.rb @@ -45,7 +45,7 @@ class Chef property :device_type, [String, Symbol], description: "The type of device: :device, :label, or :uuid", - coerce: proc { |arg| arg.kind_of?(String) ? arg.to_sym : arg }, + coerce: proc { |arg| arg.is_a?(String) ? arg.to_sym : arg }, default: :device, equal_to: RUBY_PLATFORM =~ /solaris/i ? %i{ device } : %i{ device label uuid } @@ -62,7 +62,7 @@ class Chef property :options, [Array, String, nil], description: "An array or comma separated list of options for the mount.", - coerce: proc { |arg| arg.kind_of?(String) ? arg.split(",") : arg }, + coerce: proc { |arg| arg.is_a?(String) ? arg.split(",") : arg }, default: %w{defaults} property :dump, [Integer, FalseClass], diff --git a/lib/chef/resource/msu_package.rb b/lib/chef/resource/msu_package.rb index 75515b4f78..a69f72001f 100644 --- a/lib/chef/resource/msu_package.rb +++ b/lib/chef/resource/msu_package.rb @@ -1,6 +1,6 @@ # # Author:: Nimisha Sharad (<nimisha.sharad@msystechnologies.com>) -# Copyright:: Copyright 2008-2016, Chef Software, Inc. +# Copyright:: Copyright 2008-2019, Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -40,7 +40,7 @@ class Chef uri_scheme?(s) ? s : Chef::Util::PathHelper.canonical_path(s, false) end end), - default: lazy { |r| r.package_name } + default: lazy { package_name } property :checksum, String, desired_state: false, description: "SHA-256 digest used to verify the checksum of the downloaded MSU package." diff --git a/lib/chef/resource/ohai_hint.rb b/lib/chef/resource/ohai_hint.rb index c11ef78950..30d7a3bd0c 100644 --- a/lib/chef/resource/ohai_hint.rb +++ b/lib/chef/resource/ohai_hint.rb @@ -79,6 +79,7 @@ class Chef # @return [JSON] json representation of the content of an empty string if content was nil def format_content(content) return "" if content.nil? || content.empty? + JSON.pretty_generate(content) end end @@ -88,6 +89,7 @@ class Chef # @return [void] def after_created return unless compile_time + Array(action).each do |action| run_action(action) end diff --git a/lib/chef/resource/openssl_x509_certificate.rb b/lib/chef/resource/openssl_x509_certificate.rb index 8353f5ad09..20cf998239 100644 --- a/lib/chef/resource/openssl_x509_certificate.rb +++ b/lib/chef/resource/openssl_x509_certificate.rb @@ -70,7 +70,7 @@ class Chef property :extensions, Hash, description: "Hash of X509 Extensions entries, in format { 'keyUsage' => { 'values' => %w( keyEncipherment digitalSignature), 'critical' => true } }.", - default: lazy { Hash.new } + default: lazy { {} } property :subject_alt_name, Array, description: "Array of Subject Alternative Name entries, in format DNS:example.com or IP:1.2.3.4.", @@ -168,7 +168,7 @@ class Chef end def subject - subject = OpenSSL::X509::Name.new() + subject = OpenSSL::X509::Name.new subject.add_entry("C", new_resource.country) unless new_resource.country.nil? subject.add_entry("ST", new_resource.state) unless new_resource.state.nil? subject.add_entry("L", new_resource.city) unless new_resource.city.nil? diff --git a/lib/chef/resource/openssl_x509_request.rb b/lib/chef/resource/openssl_x509_request.rb index 6fa3d6db9e..982f29dd75 100644 --- a/lib/chef/resource/openssl_x509_request.rb +++ b/lib/chef/resource/openssl_x509_request.rb @@ -130,7 +130,7 @@ class Chef end def subject - csr_subject = OpenSSL::X509::Name.new() + csr_subject = OpenSSL::X509::Name.new csr_subject.add_entry("C", new_resource.country) unless new_resource.country.nil? csr_subject.add_entry("ST", new_resource.state) unless new_resource.state.nil? csr_subject.add_entry("L", new_resource.city) unless new_resource.city.nil? diff --git a/lib/chef/resource/registry_key.rb b/lib/chef/resource/registry_key.rb index 1bf73f1cdb..a5c99313bf 100644 --- a/lib/chef/resource/registry_key.rb +++ b/lib/chef/resource/registry_key.rb @@ -86,10 +86,12 @@ class Chef @values.each do |v| raise ArgumentError, "Missing name key in RegistryKey values hash" unless v.key?(:name) + v.each_key do |key| - raise ArgumentError, "Bad key #{key} in RegistryKey values hash" unless [:name, :type, :data].include?(key) + raise ArgumentError, "Bad key #{key} in RegistryKey values hash" unless %i{name type data}.include?(key) end raise ArgumentError, "Type of name => #{v[:name]} should be string" unless v[:name].is_a?(String) + if v[:type] raise ArgumentError, "Type of type => #{v[:type]} should be symbol" unless v[:type].is_a?(Symbol) end @@ -101,7 +103,7 @@ class Chef end property :recursive, [TrueClass, FalseClass], default: false - property :architecture, Symbol, default: :machine, equal_to: [:machine, :x86_64, :i386] + property :architecture, Symbol, default: :machine, equal_to: %i{machine x86_64 i386} private @@ -121,7 +123,7 @@ class Chef # Some data types may raise errors when sent as json. Returns true if this # value's data may need to be converted to a checksum. def needs_checksum?(value) - unsafe_types = [:binary, :dword, :dword_big_endian, :qword] + unsafe_types = %i{binary dword dword_big_endian qword} unsafe_types.include?(value[:type]) end diff --git a/lib/chef/resource/remote_file.rb b/lib/chef/resource/remote_file.rb index fae3e10695..cba3908b0c 100644 --- a/lib/chef/resource/remote_file.rb +++ b/lib/chef/resource/remote_file.rb @@ -88,7 +88,7 @@ class Chef property :ftp_active_mode, [ TrueClass, FalseClass ], default: false - property :headers, Hash, default: lazy { Hash.new } + property :headers, Hash, default: lazy { {} } property :show_progress, [ TrueClass, FalseClass ], default: false @@ -98,7 +98,7 @@ class Chef property :remote_password, String, sensitive: true - property :authentication, equal_to: [:remote, :local], default: :remote + property :authentication, equal_to: %i{remote local}, default: :remote def after_created validate_identity_platform(remote_user, remote_password, remote_domain) @@ -161,6 +161,7 @@ class Chef def validate_source(source) source = Array(source).flatten raise ArgumentError, "#{resource_name} has an empty source" if source.empty? + source.each do |src| unless absolute_uri?(src) raise Exceptions::InvalidRemoteFileURI, @@ -171,7 +172,7 @@ class Chef end def absolute_uri?(source) - Chef::Provider::RemoteFile::Fetcher.network_share?(source) || (source.kind_of?(String) && as_uri(source).absolute?) + Chef::Provider::RemoteFile::Fetcher.network_share?(source) || (source.is_a?(String) && as_uri(source).absolute?) rescue URI::InvalidURIError false end diff --git a/lib/chef/resource/resource_notification.rb b/lib/chef/resource/resource_notification.rb index 1b3e01696a..7e93fff433 100644 --- a/lib/chef/resource/resource_notification.rb +++ b/lib/chef/resource/resource_notification.rb @@ -53,13 +53,13 @@ class Chef # # @return [void] def resolve_resource_reference(resource_collection) - return resource if resource.kind_of?(Chef::Resource) && notifying_resource.kind_of?(Chef::Resource) + return resource if resource.is_a?(Chef::Resource) && notifying_resource.is_a?(Chef::Resource) - if not(resource.kind_of?(Chef::Resource)) + unless resource.is_a?(Chef::Resource) fix_resource_reference(resource_collection) end - if not(notifying_resource.kind_of?(Chef::Resource)) + unless notifying_resource.is_a?(Chef::Resource) fix_notifier_reference(resource_collection) end end @@ -131,6 +131,7 @@ class Chef def ==(other) return false unless other.is_a?(self.class) + other.resource == resource && other.action == action && other.notifying_resource == notifying_resource end diff --git a/lib/chef/resource/route.rb b/lib/chef/resource/route.rb index 42302afe6a..ecd63966cf 100644 --- a/lib/chef/resource/route.rb +++ b/lib/chef/resource/route.rb @@ -50,7 +50,7 @@ class Chef property :route_type, [Symbol, String], description: "", - equal_to: [:host, :net], default: :host, desired_state: false + equal_to: %i{host net}, default: :host, desired_state: false end end end diff --git a/lib/chef/resource/sudo.rb b/lib/chef/resource/sudo.rb index 7dbae2623c..eb89687411 100644 --- a/lib/chef/resource/sudo.rb +++ b/lib/chef/resource/sudo.rb @@ -222,6 +222,7 @@ class Chef def visudo_present? return true if ::File.exist?(new_resource.visudo_binary) + Chef::Log.warn("The visudo binary cannot be found at '#{new_resource.visudo_binary}'. Skipping sudoer file validation. If visudo is on this system you can specify the path using the 'visudo_binary' property.") end end diff --git a/lib/chef/resource/swap_file.rb b/lib/chef/resource/swap_file.rb index 4a5629d824..2efe040c47 100644 --- a/lib/chef/resource/swap_file.rb +++ b/lib/chef/resource/swap_file.rb @@ -51,7 +51,7 @@ class Chef Chef::Log.debug("#{new_resource} already created - nothing to do") else begin - Chef::Log.info "starting first create: #{node['virtualization']['system']}" + Chef::Log.info "starting first create: #{node["virtualization"]["system"]}" do_create(swap_creation_command) rescue Mixlib::ShellOut::ShellCommandFailed => e Chef::Log.warn("#{new_resource} Rescuing failed swapfile creation for #{new_resource.path}") diff --git a/lib/chef/resource/sysctl.rb b/lib/chef/resource/sysctl.rb index 2986c4e914..a6c316c5bc 100644 --- a/lib/chef/resource/sysctl.rb +++ b/lib/chef/resource/sysctl.rb @@ -80,12 +80,12 @@ class Chef directory new_resource.conf_dir - file "#{new_resource.conf_dir}/99-chef-#{new_resource.key.tr('/', '.')}.conf" do + file "#{new_resource.conf_dir}/99-chef-#{new_resource.key.tr("/", ".")}.conf" do content "#{new_resource.key} = #{new_resource.value}" end execute "Load sysctl values" do - command "sysctl #{'-e ' if new_resource.ignore_error}-p" + command "sysctl #{"-e " if new_resource.ignore_error}-p" default_env true action :run end @@ -96,9 +96,9 @@ class Chef description "Remove a sysctl value." # only converge the resource if the file actually exists to delete - if ::File.exist?("#{new_resource.conf_dir}/99-chef-#{new_resource.key.tr('/', '.')}.conf") - converge_by "removing sysctl config at #{new_resource.conf_dir}/99-chef-#{new_resource.key.tr('/', '.')}.conf" do - file "#{new_resource.conf_dir}/99-chef-#{new_resource.key.tr('/', '.')}.conf" do + if ::File.exist?("#{new_resource.conf_dir}/99-chef-#{new_resource.key.tr("/", ".")}.conf") + converge_by "removing sysctl config at #{new_resource.conf_dir}/99-chef-#{new_resource.key.tr("/", ".")}.conf" do + file "#{new_resource.conf_dir}/99-chef-#{new_resource.key.tr("/", ".")}.conf" do action :delete end @@ -113,7 +113,7 @@ class Chef action_class do def set_sysctl_param(key, value) - shell_out!("sysctl #{'-e ' if new_resource.ignore_error}-w \"#{key}=#{value}\"") + shell_out!("sysctl #{"-e " if new_resource.ignore_error}-w \"#{key}=#{value}\"") end end @@ -133,6 +133,7 @@ class Chef def get_sysctl_value(key) val = shell_out!("sysctl -n -e #{key}").stdout.tr("\t", " ").strip raise unless val == get_sysctld_value(key) + val end @@ -140,10 +141,12 @@ class Chef # return the value. Raise in case this conf file needs to be created # or updated def get_sysctld_value(key) - raise unless ::File.exist?("/etc/sysctl.d/99-chef-#{key.tr('/', '.')}.conf") - k, v = ::File.read("/etc/sysctl.d/99-chef-#{key.tr('/', '.')}.conf").match(/(.*) = (.*)/).captures + raise unless ::File.exist?("/etc/sysctl.d/99-chef-#{key.tr("/", ".")}.conf") + + k, v = ::File.read("/etc/sysctl.d/99-chef-#{key.tr("/", ".")}.conf").match(/(.*) = (.*)/).captures raise "Unknown sysctl key!" if k.nil? raise "Unknown sysctl value!" if v.nil? + v end end diff --git a/lib/chef/resource/template.rb b/lib/chef/resource/template.rb index 27002c4a03..3ff568b1a1 100644 --- a/lib/chef/resource/template.rb +++ b/lib/chef/resource/template.rb @@ -60,7 +60,7 @@ class Chef property :variables, Hash, description: "The variables property of the template resource can be used to reference a partial template file by using a Hash.", - default: lazy { Hash.new } + default: lazy { {} } property :cookbook, String, description: "The cookbook in which a file is located (if it is not located in the current cookbook). The default value is the current cookbook.", @@ -109,7 +109,7 @@ class Chef "`helper(:method)` requires a block argument (e.g., `helper(:method) { code }`)" end - unless method_name.kind_of?(Symbol) + unless method_name.is_a?(Symbol) raise Exceptions::ValidationFailed, "method_name argument to `helper(method_name)` must be a symbol (e.g., `helper(:method) { code }`)" end @@ -163,7 +163,7 @@ class Chef "Passing both a module and block to #helpers is not supported. Call #helpers multiple times instead" elsif block_given? @inline_helper_modules << block - elsif module_name.kind_of?(::Module) + elsif module_name.is_a?(::Module) @helper_modules << module_name elsif module_name.nil? raise Exceptions::ValidationFailed, diff --git a/lib/chef/resource/timezone.rb b/lib/chef/resource/timezone.rb index 0f5cf7cb0c..16a7f1031e 100644 --- a/lib/chef/resource/timezone.rb +++ b/lib/chef/resource/timezone.rb @@ -126,6 +126,7 @@ class Chef def current_windows_tz tz_shellout = shell_out("tzutil /g") raise "There was an error running the tzutil command" if tz_shellout.exitstatus == 1 + tz_shellout.stdout.strip end end diff --git a/lib/chef/resource/windows_ad_join.rb b/lib/chef/resource/windows_ad_join.rb index fd08f9149a..23faa60ee5 100644 --- a/lib/chef/resource/windows_ad_join.rb +++ b/lib/chef/resource/windows_ad_join.rb @@ -48,7 +48,7 @@ class Chef description: "The path to the Organizational Unit where the host will be placed." property :reboot, Symbol, - equal_to: [:immediate, :delayed, :never, :request_reboot, :reboot_now], + equal_to: %i{immediate delayed never request_reboot reboot_now}, validation_message: "The reboot property accepts :immediate (reboot as soon as the resource completes), :delayed (reboot once the #{Chef::Dist::PRODUCT} run completes), and :never (Don't reboot)", description: "Controls the system reboot behavior post domain joining. Reboot immediately, after the #{Chef::Dist::PRODUCT} run completes, or never. Note that a reboot is necessary for changes to take effect.", default: :immediate @@ -96,6 +96,7 @@ class Chef def on_domain? node_domain = powershell_out!("(Get-WmiObject Win32_ComputerSystem).Domain") raise "Failed to check if the system is joined to the domain #{new_resource.domain_name}: #{node_domain.stderr}}" if node_domain.error? + node_domain.stdout.downcase.strip == new_resource.domain_name.downcase end diff --git a/lib/chef/resource/windows_certificate.rb b/lib/chef/resource/windows_certificate.rb index fa76d7273d..cdd7ed1ef1 100644 --- a/lib/chef/resource/windows_certificate.rb +++ b/lib/chef/resource/windows_certificate.rb @@ -2,7 +2,7 @@ # Author:: Richard Lavey (richard.lavey@calastone.com) # # Copyright:: 2015-2017, Calastone Ltd. -# Copyright:: 2018, Chef Software, Inc. +# Copyright:: 2018-2019, Chef Software Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -55,7 +55,7 @@ class Chef # lazy used to set default value of sensitive to true if password is set property :sensitive, [TrueClass, FalseClass], description: "Ensure that sensitive resource data is not logged by the #{Chef::Dist::CLIENT}.", - default: lazy { |r| r.pfx_password ? true : false }, skip_docs: true + default: lazy { pfx_password ? true : false }, skip_docs: true action :create do description "Creates or updates a certificate." @@ -77,7 +77,7 @@ class Chef guard_script = cert_script(false) else # make sure we have no spaces in the hash string - hash = "\"#{new_resource.source.gsub(/\s/, '')}\"" + hash = "\"#{new_resource.source.gsub(/\s/, "")}\"" code_script = "" guard_script = "" end diff --git a/lib/chef/resource/windows_dfs_folder.rb b/lib/chef/resource/windows_dfs_folder.rb index 763163eb90..8078f965fb 100644 --- a/lib/chef/resource/windows_dfs_folder.rb +++ b/lib/chef/resource/windows_dfs_folder.rb @@ -46,17 +46,18 @@ class Chef raise "target_path is required for install" unless property_is_set?(:target_path) raise "description is required for install" unless property_is_set?(:description) + powershell_script "Create or Update DFS Folder" do code <<-EOH - $needs_creating = (Get-DfsnFolder -Path '\\\\#{ENV['COMPUTERNAME']}\\#{new_resource.namespace_name}\\#{new_resource.folder_path}' -ErrorAction SilentlyContinue) -eq $null + $needs_creating = (Get-DfsnFolder -Path '\\\\#{ENV["COMPUTERNAME"]}\\#{new_resource.namespace_name}\\#{new_resource.folder_path}' -ErrorAction SilentlyContinue) -eq $null if (!($needs_creating)) { - Remove-DfsnFolder -Path '\\\\#{ENV['COMPUTERNAME']}\\#{new_resource.namespace_name}\\#{new_resource.folder_path}' -Force + Remove-DfsnFolder -Path '\\\\#{ENV["COMPUTERNAME"]}\\#{new_resource.namespace_name}\\#{new_resource.folder_path}' -Force } - New-DfsnFolder -Path '\\\\#{ENV['COMPUTERNAME']}\\#{new_resource.namespace_name}\\#{new_resource.folder_path}' -TargetPath '#{new_resource.target_path}' -Description '#{new_resource.description}' + New-DfsnFolder -Path '\\\\#{ENV["COMPUTERNAME"]}\\#{new_resource.namespace_name}\\#{new_resource.folder_path}' -TargetPath '#{new_resource.target_path}' -Description '#{new_resource.description}' EOH - not_if "return ((Get-DfsnFolder -Path '\\\\#{ENV['COMPUTERNAME']}\\#{new_resource.namespace_name}\\#{new_resource.folder_path}' -ErrorAction SilentlyContinue).Description -eq '#{new_resource.description}' -and (Get-DfsnFolderTarget -Path '\\\\#{ENV['COMPUTERNAME']}\\#{new_resource.namespace_name}\\#{new_resource.folder_path}').TargetPath -eq '#{new_resource.target_path}' )" + not_if "return ((Get-DfsnFolder -Path '\\\\#{ENV["COMPUTERNAME"]}\\#{new_resource.namespace_name}\\#{new_resource.folder_path}' -ErrorAction SilentlyContinue).Description -eq '#{new_resource.description}' -and (Get-DfsnFolderTarget -Path '\\\\#{ENV["COMPUTERNAME"]}\\#{new_resource.namespace_name}\\#{new_resource.folder_path}').TargetPath -eq '#{new_resource.target_path}' )" end end @@ -65,9 +66,9 @@ class Chef powershell_script "Delete DFS Namespace" do code <<-EOH - Remove-DfsnFolder -Path '\\\\#{ENV['COMPUTERNAME']}\\#{new_resource.namespace_name}\\#{new_resource.folder_path}' -Force + Remove-DfsnFolder -Path '\\\\#{ENV["COMPUTERNAME"]}\\#{new_resource.namespace_name}\\#{new_resource.folder_path}' -Force EOH - only_if "return ((Get-DfsnFolder -Path '\\\\#{ENV['COMPUTERNAME']}\\#{new_resource.namespace_name}\\#{new_resource.folder_path}' ) -ne $null)" + only_if "return ((Get-DfsnFolder -Path '\\\\#{ENV["COMPUTERNAME"]}\\#{new_resource.namespace_name}\\#{new_resource.folder_path}' ) -ne $null)" end end end diff --git a/lib/chef/resource/windows_dfs_namespace.rb b/lib/chef/resource/windows_dfs_namespace.rb index 34ac58ff2e..3b201d1028 100644 --- a/lib/chef/resource/windows_dfs_namespace.rb +++ b/lib/chef/resource/windows_dfs_namespace.rb @@ -69,17 +69,17 @@ class Chef powershell_script "Create DFS Namespace" do code <<-EOH - $needs_creating = (Get-DfsnRoot -Path '\\\\#{ENV['COMPUTERNAME']}\\#{new_resource.namespace_name}' -ErrorAction SilentlyContinue) -eq $null + $needs_creating = (Get-DfsnRoot -Path '\\\\#{ENV["COMPUTERNAME"]}\\#{new_resource.namespace_name}' -ErrorAction SilentlyContinue) -eq $null if ($needs_creating) { - New-DfsnRoot -Path '\\\\#{ENV['COMPUTERNAME']}\\#{new_resource.namespace_name}' -TargetPath '\\\\#{ENV['COMPUTERNAME']}\\#{new_resource.namespace_name}' -Type Standalone -Description '#{new_resource.description}' + New-DfsnRoot -Path '\\\\#{ENV["COMPUTERNAME"]}\\#{new_resource.namespace_name}' -TargetPath '\\\\#{ENV["COMPUTERNAME"]}\\#{new_resource.namespace_name}' -Type Standalone -Description '#{new_resource.description}' } else { - Set-DfsnRoot -Path '\\\\#{ENV['COMPUTERNAME']}\\#{new_resource.namespace_name}' -Description '#{new_resource.description}' + Set-DfsnRoot -Path '\\\\#{ENV["COMPUTERNAME"]}\\#{new_resource.namespace_name}' -Description '#{new_resource.description}' } EOH - not_if "return (Get-DfsnRoot -Path '\\\\#{ENV['COMPUTERNAME']}\\#{new_resource.namespace_name}' -ErrorAction SilentlyContinue).description -eq '#{new_resource.description}'" + not_if "return (Get-DfsnRoot -Path '\\\\#{ENV["COMPUTERNAME"]}\\#{new_resource.namespace_name}' -ErrorAction SilentlyContinue).description -eq '#{new_resource.description}'" end end @@ -88,9 +88,9 @@ class Chef powershell_script "Delete DFS Namespace" do code <<-EOH - Remove-DfsnRoot -Path '\\\\#{ENV['COMPUTERNAME']}\\#{new_resource.namespace_name}' -Force + Remove-DfsnRoot -Path '\\\\#{ENV["COMPUTERNAME"]}\\#{new_resource.namespace_name}' -Force EOH - only_if "return ((Get-DfsnRoot -Path '\\\\#{ENV['COMPUTERNAME']}\\#{new_resource.namespace_name}') -ne $null)" + only_if "return ((Get-DfsnRoot -Path '\\\\#{ENV["COMPUTERNAME"]}\\#{new_resource.namespace_name}') -ne $null)" end windows_share new_resource.namespace_name do diff --git a/lib/chef/resource/windows_dfs_server.rb b/lib/chef/resource/windows_dfs_server.rb index cfcf20ec59..89376a0877 100644 --- a/lib/chef/resource/windows_dfs_server.rb +++ b/lib/chef/resource/windows_dfs_server.rb @@ -48,7 +48,7 @@ class Chef default: 3600 load_current_value do - ps_results = powershell_out("Get-DfsnServerConfiguration -ComputerName '#{ENV['COMPUTERNAME']}' | Select LdapTimeoutSec, PreferLogonDC, EnableSiteCostedReferrals, SyncIntervalSec, UseFqdn | ConvertTo-Json") + ps_results = powershell_out("Get-DfsnServerConfiguration -ComputerName '#{ENV["COMPUTERNAME"]}' | Select LdapTimeoutSec, PreferLogonDC, EnableSiteCostedReferrals, SyncIntervalSec, UseFqdn | ConvertTo-Json") if ps_results.error? raise "The dfs_server resource failed to fetch the current state via the Get-DfsnServerConfiguration PowerShell cmlet. Is the DFS Windows feature installed?" @@ -68,7 +68,7 @@ class Chef description "Configure DFS settings." converge_if_changed do - powershell_out("Set-DfsnServerConfiguration -ComputerName '#{ENV['COMPUTERNAME']}' EnableSiteCostedReferrals $#{new_resource.enable_site_costed_referrals} -UseFqdn $#{new_resource.use_fqdn} -LdapTimeoutSec #{new_resource.ldap_timeout_secs} -PreferLogonDC $#{new_resource.prefer_login_dc} -SyncIntervalSec #{new_resource.sync_interval_secs}") + powershell_out("Set-DfsnServerConfiguration -ComputerName '#{ENV["COMPUTERNAME"]}' EnableSiteCostedReferrals $#{new_resource.enable_site_costed_referrals} -UseFqdn $#{new_resource.use_fqdn} -LdapTimeoutSec #{new_resource.ldap_timeout_secs} -PreferLogonDC $#{new_resource.prefer_login_dc} -SyncIntervalSec #{new_resource.sync_interval_secs}") end end end diff --git a/lib/chef/resource/windows_feature.rb b/lib/chef/resource/windows_feature.rb index e937c6f990..cc80284019 100644 --- a/lib/chef/resource/windows_feature.rb +++ b/lib/chef/resource/windows_feature.rb @@ -44,7 +44,7 @@ class Chef property :install_method, Symbol, description: "The underlying installation method to use for feature installation. Specify ':windows_feature_dism' for DISM or ':windows_feature_powershell' for PowerShell.", - equal_to: [:windows_feature_dism, :windows_feature_powershell, :windows_feature_servermanagercmd], + equal_to: %i{windows_feature_dism windows_feature_powershell windows_feature_servermanagercmd}, default: :windows_feature_dism property :timeout, Integer, diff --git a/lib/chef/resource/windows_feature_dism.rb b/lib/chef/resource/windows_feature_dism.rb index 4bbfff9823..faeb0b0762 100644 --- a/lib/chef/resource/windows_feature_dism.rb +++ b/lib/chef/resource/windows_feature_dism.rb @@ -58,17 +58,18 @@ class Chef reload_cached_dism_data unless node["dism_features_cache"] fail_if_unavailable # fail if the features don't exist - logger.trace("Windows features needing installation: #{features_to_install.empty? ? 'none' : features_to_install.join(',')}") + logger.trace("Windows features needing installation: #{features_to_install.empty? ? "none" : features_to_install.join(",")}") unless features_to_install.empty? - message = "install Windows feature#{'s' if features_to_install.count > 1} #{features_to_install.join(',')}" + message = "install Windows feature#{"s" if features_to_install.count > 1} #{features_to_install.join(",")}" converge_by(message) do - install_command = "dism.exe /online /enable-feature #{features_to_install.map { |f| "/featurename:#{f}" }.join(' ')} /norestart" + install_command = "dism.exe /online /enable-feature #{features_to_install.map { |f| "/featurename:#{f}" }.join(" ")} /norestart" install_command << " /LimitAccess /Source:\"#{new_resource.source}\"" if new_resource.source install_command << " /All" if new_resource.all begin shell_out!(install_command, returns: [0, 42, 127, 3010], timeout: new_resource.timeout) rescue Mixlib::ShellOut::ShellCommandFailed => e raise "Error 50 returned by DISM related to parent features, try setting the 'all' property to 'true' on the 'windows_feature_dism' resource." if required_parent_feature?(e.inspect) + raise e.message end @@ -82,12 +83,12 @@ class Chef reload_cached_dism_data unless node["dism_features_cache"] - logger.trace("Windows features needing removal: #{features_to_remove.empty? ? 'none' : features_to_remove.join(',')}") + logger.trace("Windows features needing removal: #{features_to_remove.empty? ? "none" : features_to_remove.join(",")}") unless features_to_remove.empty? - message = "remove Windows feature#{'s' if features_to_remove.count > 1} #{features_to_remove.join(',')}" + message = "remove Windows feature#{"s" if features_to_remove.count > 1} #{features_to_remove.join(",")}" converge_by(message) do - shell_out!("dism.exe /online /disable-feature #{features_to_remove.map { |f| "/featurename:#{f}" }.join(' ')} /norestart", returns: [0, 42, 127, 3010], timeout: new_resource.timeout) + shell_out!("dism.exe /online /disable-feature #{features_to_remove.map { |f| "/featurename:#{f}" }.join(" ")} /norestart", returns: [0, 42, 127, 3010], timeout: new_resource.timeout) reload_cached_dism_data # Reload cached dism feature state end @@ -103,11 +104,11 @@ class Chef fail_if_unavailable # fail if the features don't exist - logger.trace("Windows features needing deletion: #{features_to_delete.empty? ? 'none' : features_to_delete.join(',')}") + logger.trace("Windows features needing deletion: #{features_to_delete.empty? ? "none" : features_to_delete.join(",")}") unless features_to_delete.empty? - message = "delete Windows feature#{'s' if features_to_delete.count > 1} #{features_to_delete.join(',')} from the image" + message = "delete Windows feature#{"s" if features_to_delete.count > 1} #{features_to_delete.join(",")} from the image" converge_by(message) do - shell_out!("dism.exe /online /disable-feature #{features_to_delete.map { |f| "/featurename:#{f}" }.join(' ')} /Remove /norestart", returns: [0, 42, 127, 3010], timeout: new_resource.timeout) + shell_out!("dism.exe /online /disable-feature #{features_to_delete.map { |f| "/featurename:#{f}" }.join(" ")} /Remove /norestart", returns: [0, 42, 127, 3010], timeout: new_resource.timeout) reload_cached_dism_data # Reload cached dism feature state end @@ -158,7 +159,7 @@ class Chef # the difference of desired features to install to all features is what's not available unavailable = (new_resource.feature_name - all_available) - raise "The Windows feature#{'s' if unavailable.count > 1} #{unavailable.join(',')} #{unavailable.count > 1 ? 'are' : 'is'} not available on this version of Windows. Run 'dism /online /Get-Features' to see the list of available feature names." unless unavailable.empty? + raise "The Windows feature#{"s" if unavailable.count > 1} #{unavailable.join(",")} #{unavailable.count > 1 ? "are" : "is"} not available on this version of Windows. Run 'dism /online /Get-Features' to see the list of available feature names." unless unavailable.empty? end # run dism.exe to get a list of all available features and their state @@ -189,7 +190,7 @@ class Chef add_to_feature_mash("disabled", feature_details_raw) end end - logger.trace("The cache contains\n#{node['dism_features_cache']}") + logger.trace("The cache contains\n#{node["dism_features_cache"]}") end # parse the feature string and add the values to the appropriate array diff --git a/lib/chef/resource/windows_feature_powershell.rb b/lib/chef/resource/windows_feature_powershell.rb index 6806c92fb9..5cdbe1f74c 100644 --- a/lib/chef/resource/windows_feature_powershell.rb +++ b/lib/chef/resource/windows_feature_powershell.rb @@ -68,10 +68,10 @@ class Chef fail_if_unavailable # fail if the features don't exist fail_if_removed # fail if the features are in removed state - Chef::Log.debug("Windows features needing installation: #{features_to_install.empty? ? 'none' : features_to_install.join(',')}") + Chef::Log.debug("Windows features needing installation: #{features_to_install.empty? ? "none" : features_to_install.join(",")}") unless features_to_install.empty? - converge_by("install Windows feature#{'s' if features_to_install.count > 1} #{features_to_install.join(',')}") do - install_command = "#{install_feature_cmdlet} #{features_to_install.join(',')}" + converge_by("install Windows feature#{"s" if features_to_install.count > 1} #{features_to_install.join(",")}") do + install_command = "#{install_feature_cmdlet} #{features_to_install.join(",")}" install_command << " -IncludeAllSubFeature" if new_resource.all if older_than_win_2012_or_8? && (new_resource.source || new_resource.management_tools) Chef::Log.warn("The 'source' and 'management_tools' properties are only available on Windows 8/2012 or greater. Skipping these properties!") @@ -93,11 +93,11 @@ class Chef reload_cached_powershell_data unless node["powershell_features_cache"] - Chef::Log.debug("Windows features needing removal: #{features_to_remove.empty? ? 'none' : features_to_remove.join(',')}") + Chef::Log.debug("Windows features needing removal: #{features_to_remove.empty? ? "none" : features_to_remove.join(",")}") unless features_to_remove.empty? - converge_by("remove Windows feature#{'s' if features_to_remove.count > 1} #{features_to_remove.join(',')}") do - cmd = powershell_out!("#{remove_feature_cmdlet} #{features_to_remove.join(',')}", timeout: new_resource.timeout) + converge_by("remove Windows feature#{"s" if features_to_remove.count > 1} #{features_to_remove.join(",")}") do + cmd = powershell_out!("#{remove_feature_cmdlet} #{features_to_remove.join(",")}", timeout: new_resource.timeout) Chef::Log.info(cmd.stdout) reload_cached_powershell_data # Reload cached powershell feature state @@ -113,11 +113,11 @@ class Chef fail_if_unavailable # fail if the features don't exist - Chef::Log.debug("Windows features needing deletion: #{features_to_delete.empty? ? 'none' : features_to_delete.join(',')}") + Chef::Log.debug("Windows features needing deletion: #{features_to_delete.empty? ? "none" : features_to_delete.join(",")}") unless features_to_delete.empty? - converge_by("delete Windows feature#{'s' if features_to_delete.count > 1} #{features_to_delete.join(',')} from the image") do - cmd = powershell_out!("Uninstall-WindowsFeature #{features_to_delete.join(',')} -Remove", timeout: new_resource.timeout) + converge_by("delete Windows feature#{"s" if features_to_delete.count > 1} #{features_to_delete.join(",")} from the image") do + cmd = powershell_out!("Uninstall-WindowsFeature #{features_to_delete.join(",")} -Remove", timeout: new_resource.timeout) Chef::Log.info(cmd.stdout) reload_cached_powershell_data # Reload cached powershell feature state @@ -132,6 +132,7 @@ class Chef def powershell_version cmd = powershell_out("$PSVersionTable.psversion.major") return 1 if cmd.stdout.empty? # PowerShell 1.0 doesn't have a $PSVersionTable + Regexp.last_match(1).to_i if cmd.stdout =~ /^(\d+)/ rescue Errno::ENOENT 0 # zero as in nothing is installed @@ -195,7 +196,7 @@ class Chef # the difference of desired features to install to all features is what's not available unavailable = (new_resource.feature_name - all_available) - raise "The Windows feature#{'s' if unavailable.count > 1} #{unavailable.join(',')} #{unavailable.count > 1 ? 'are' : 'is'} not available on this version of Windows. Run 'Get-WindowsFeature' to see the list of available feature names." unless unavailable.empty? + raise "The Windows feature#{"s" if unavailable.count > 1} #{unavailable.join(",")} #{unavailable.count > 1 ? "are" : "is"} not available on this version of Windows. Run 'Get-WindowsFeature' to see the list of available feature names." unless unavailable.empty? end # run Get-WindowsFeature to get a list of all available features and their state @@ -218,7 +219,7 @@ class Chef add_to_feature_mash("disabled", feature_details_raw["Name"]) end end - Chef::Log.debug("The powershell cache contains\n#{node['powershell_features_cache']}") + Chef::Log.debug("The powershell cache contains\n#{node["powershell_features_cache"]}") end # fetch the list of available feature names and state in JSON and parse the JSON @@ -245,11 +246,12 @@ class Chef # @return [void] def fail_if_removed return if new_resource.source # if someone provides a source then all is well + if node["platform_version"].to_f > 6.2 # 2012R2 or later return if registry_key_exists?('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Servicing') && registry_value_exists?('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Servicing', name: "LocalSourcePath") # if source is defined in the registry, still fine end removed = new_resource.feature_name & node["powershell_features_cache"]["removed"] - raise "The Windows feature#{'s' if removed.count > 1} #{removed.join(',')} #{removed.count > 1 ? 'are' : 'is'} removed from the host and cannot be installed." unless removed.empty? + raise "The Windows feature#{"s" if removed.count > 1} #{removed.join(",")} #{removed.count > 1 ? "are" : "is"} removed from the host and cannot be installed." unless removed.empty? end # Fail unless we're on windows 8+ / 2012+ where deleting a feature is supported diff --git a/lib/chef/resource/windows_firewall_rule.rb b/lib/chef/resource/windows_firewall_rule.rb index f933ba9139..424d8d0fde 100644 --- a/lib/chef/resource/windows_firewall_rule.rb +++ b/lib/chef/resource/windows_firewall_rule.rb @@ -42,7 +42,7 @@ class Chef property :local_port, [String, Integer, Array], # split various formats of comma separated lists and provide a sorted array of strings to match PS output - coerce: proc { |d| d.is_a?(String) ? d.split(/\s*,\s*/).sort : Array(d).sort.map { |x| x.to_s } }, + coerce: proc { |d| d.is_a?(String) ? d.split(/\s*,\s*/).sort : Array(d).sort.map(&:to_s) }, description: "The local port the firewall rule applies to." property :remote_address, String, @@ -50,11 +50,11 @@ class Chef property :remote_port, [String, Integer, Array], # split various formats of comma separated lists and provide a sorted array of strings to match PS output - coerce: proc { |d| d.is_a?(String) ? d.split(/\s*,\s*/).sort : Array(d).sort.map { |x| x.to_s } }, + coerce: proc { |d| d.is_a?(String) ? d.split(/\s*,\s*/).sort : Array(d).sort.map(&:to_s) }, description: "The remote port the firewall rule applies to." property :direction, [Symbol, String], - default: :inbound, equal_to: [:inbound, :outbound], + default: :inbound, equal_to: %i{inbound outbound}, description: "The direction of the firewall rule. Direction means either inbound or outbound traffic.", coerce: proc { |d| d.is_a?(String) ? d.downcase.to_sym : d } @@ -63,12 +63,12 @@ class Chef description: "The protocol the firewall rule applies to." property :firewall_action, [Symbol, String], - default: :allow, equal_to: [:allow, :block, :notconfigured], + default: :allow, equal_to: %i{allow block notconfigured}, description: "The action of the firewall rule.", coerce: proc { |f| f.is_a?(String) ? f.downcase.to_sym : f } property :profile, [Symbol, String], - default: :any, equal_to: [:public, :private, :domain, :any, :notapplicable], + default: :any, equal_to: %i{public private domain any notapplicable}, description: "The profile the firewall rule applies to.", coerce: proc { |p| p.is_a?(String) ? p.downcase.to_sym : p } @@ -79,7 +79,7 @@ class Chef description: "The service the firewall rule applies to." property :interface_type, [Symbol, String], - default: :any, equal_to: [:any, :wireless, :wired, :remoteaccess], + default: :any, equal_to: %i{any wireless wired remoteaccess}, description: "The interface type the firewall rule applies to.", coerce: proc { |i| i.is_a?(String) ? i.downcase.to_sym : i } @@ -121,9 +121,9 @@ class Chef if current_resource converge_if_changed :rule_name, :local_address, :local_port, :remote_address, :remote_port, :direction, :protocol, :firewall_action, :profile, :program, :service, :interface_type, :enabled do - cmd = firewall_command("Set") - powershell_out!(cmd) - end + cmd = firewall_command("Set") + powershell_out!(cmd) + end else converge_by("create firewall rule #{new_resource.rule_name}") do cmd = firewall_command("New") @@ -152,9 +152,9 @@ class Chef cmd << " -DisplayName '#{new_resource.rule_name}'" if cmdlet_type == "New" cmd << " -Description '#{new_resource.description}'" if new_resource.description cmd << " -LocalAddress '#{new_resource.local_address}'" if new_resource.local_address - cmd << " -LocalPort #{new_resource.local_port.join(',')}" if new_resource.local_port + cmd << " -LocalPort #{new_resource.local_port.join(",")}" if new_resource.local_port cmd << " -RemoteAddress '#{new_resource.remote_address}'" if new_resource.remote_address - cmd << " -RemotePort #{new_resource.remote_port.join(',')}" if new_resource.remote_port + cmd << " -RemotePort #{new_resource.remote_port.join(",")}" if new_resource.remote_port cmd << " -Direction '#{new_resource.direction}'" if new_resource.direction cmd << " -Protocol '#{new_resource.protocol}'" if new_resource.protocol cmd << " -Action '#{new_resource.firewall_action}'" if new_resource.firewall_action diff --git a/lib/chef/resource/windows_pagefile.rb b/lib/chef/resource/windows_pagefile.rb index 8249436144..03a7511f47 100644 --- a/lib/chef/resource/windows_pagefile.rb +++ b/lib/chef/resource/windows_pagefile.rb @@ -87,6 +87,7 @@ class Chef # is set then this validation is not necessary / doesn't make sense at all def validate_name return if /^.:.*.sys/ =~ new_resource.path + raise "#{new_resource.path} does not match the format DRIVE:\\path\\file.sys for pagefiles. Example: C:\\pagefile.sys" end diff --git a/lib/chef/resource/windows_script.rb b/lib/chef/resource/windows_script.rb index 3177a32090..c542fbd81b 100644 --- a/lib/chef/resource/windows_script.rb +++ b/lib/chef/resource/windows_script.rb @@ -41,7 +41,7 @@ class Chef public def architecture(arg = nil) - assert_architecture_compatible!(arg) if ! arg.nil? + assert_architecture_compatible!(arg) unless arg.nil? result = set_or_return( :architecture, arg, diff --git a/lib/chef/resource/windows_service.rb b/lib/chef/resource/windows_service.rb index 91c3450603..b8ee4edf9c 100644 --- a/lib/chef/resource/windows_service.rb +++ b/lib/chef/resource/windows_service.rb @@ -58,7 +58,7 @@ class Chef # - :manual # - :disabled # Reference: https://github.com/chef/win32-service/blob/ffi/lib/win32/windows/constants.rb#L49-L54 - property :startup_type, [Symbol], equal_to: [:automatic, :manual, :disabled], default: :automatic, coerce: proc { |x| + property :startup_type, [Symbol], equal_to: %i{automatic manual disabled}, default: :automatic, coerce: proc { |x| if x.is_a?(Integer) ALLOWED_START_TYPES.invert.fetch(x) do Chef::Log.warn("Unsupported startup_type #{x}, falling back to :automatic") diff --git a/lib/chef/resource/windows_share.rb b/lib/chef/resource/windows_share.rb index 0dcf49e432..a5924d2996 100644 --- a/lib/chef/resource/windows_share.rb +++ b/lib/chef/resource/windows_share.rb @@ -160,6 +160,7 @@ class Chef json_results.each do |perm| next unless perm["AccessControlType"] == 0 # allow + case perm["AccessRight"] when 0 then f_users << stripped_account(perm["AccountName"]) # 0 full control when 1 then c_users << stripped_account(perm["AccountName"]) # 1 == change @@ -172,7 +173,7 @@ class Chef # local names are returned from Get-SmbShareAccess in the full format MACHINE\\NAME # but users of this resource would simply say NAME so we need to strip the values for comparison def stripped_account(name) - name.slice!("#{node['hostname']}\\") + name.slice!("#{node["hostname"]}\\") name end @@ -218,6 +219,7 @@ class Chef def different_path? return false if current_resource.nil? # going from nil to something isn't different for our concerns return false if current_resource.path == Chef::Util::PathHelper.cleanpath(new_resource.path) + true end @@ -274,6 +276,7 @@ class Chef # set permissions for a brand new share OR # update permissions if the current state and desired state differ next unless permissions_need_update?(perm_type) + grant_command = "Grant-SmbShareAccess -Name '#{new_resource.share_name}' -AccountName \"#{new_resource.send("#{perm_type}_users").join('","')}\" -Force -AccessRight #{perm_type}" Chef::Log.debug("Running '#{grant_command}' to update the share permissions") diff --git a/lib/chef/resource/windows_task.rb b/lib/chef/resource/windows_task.rb index b985231c8a..95de6b37c2 100644 --- a/lib/chef/resource/windows_task.rb +++ b/lib/chef/resource/windows_task.rb @@ -31,7 +31,7 @@ class Chef allowed_actions :create, :delete, :run, :end, :enable, :disable, :change default_action :create - property :task_name, String, regex: [/\A[^\/\:\*\?\<\>\|]+\z/], + property :task_name, String, regex: [%r{\A[^/\:\*\?\<\>\|]+\z}], description: "An optional property to set the task name if it differs from the resource block's name. Example: 'Task Name' or '/Task Name'", name_property: true @@ -49,7 +49,7 @@ class Chef property :password, String, description: "The user’s password. The user property must be set if using this property." - property :run_level, Symbol, equal_to: [:highest, :limited], + property :run_level, Symbol, equal_to: %i{highest limited}, description: "Run with ':limited' or ':highest' privileges.", default: :limited @@ -64,16 +64,16 @@ class Chef property :frequency_modifier, [Integer, String], default: 1 - property :frequency, Symbol, equal_to: [:minute, - :hourly, - :daily, - :weekly, - :monthly, - :once, - :on_logon, - :onstart, - :on_idle, - :none], + property :frequency, Symbol, equal_to: %i{minute + hourly + daily + weekly + monthly + once + on_logon + onstart + on_idle + none}, description: "The frequency with which to run the task." property :start_day, String, @@ -140,6 +140,7 @@ class Chef if execution_time_limit execution_time_limit(259200) if execution_time_limit == "PT72H" raise ArgumentError, "Invalid value passed for `execution_time_limit`. Please pass seconds as an Integer (e.g. 60) or a String with numeric values only (e.g. '60')." unless numeric_value_in_string?(execution_time_limit) + execution_time_limit(sec_to_min(execution_time_limit)) end @@ -174,7 +175,7 @@ class Chef end def validate_frequency(frequency) - if frequency.nil? || !([:minute, :hourly, :daily, :weekly, :monthly, :once, :on_logon, :onstart, :on_idle, :none].include?(frequency)) + if frequency.nil? || !(%i{minute hourly daily weekly monthly once on_logon onstart on_idle none}.include?(frequency)) raise ArgumentError, "Frequency needs to be provided. Valid frequencies are :minute, :hourly, :daily, :weekly, :monthly, :once, :on_logon, :onstart, :on_idle, :none." end end @@ -200,7 +201,7 @@ class Chef end def validate_random_delay(random_delay, frequency) - if [:on_logon, :onstart, :on_idle, :none].include? frequency + if %i{on_logon onstart on_idle none}.include? frequency raise ArgumentError, "`random_delay` property is supported only for frequency :once, :minute, :hourly, :daily, :weekly and :monthly" end @@ -215,7 +216,7 @@ class Chef # make sure the start_day is in MM/DD/YYYY format: http://rubular.com/r/cgjHemtWl5 if start_day - raise ArgumentError, "`start_day` property must be in the MM/DD/YYYY format." unless /^(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.](19|20)\d\d$/ =~ start_day + raise ArgumentError, "`start_day` property must be in the MM/DD/YYYY format." unless %r{^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$} =~ start_day end end @@ -255,7 +256,7 @@ class Chef alias non_system_user? password_required? def validate_create_frequency_modifier(frequency, frequency_modifier) - if ([:on_logon, :onstart, :on_idle, :none].include?(frequency)) && ( frequency_modifier != 1) + if (%i{on_logon onstart on_idle none}.include?(frequency)) && ( frequency_modifier != 1) raise ArgumentError, "frequency_modifier property not supported with frequency :#{frequency}" end @@ -287,7 +288,7 @@ class Chef end def validate_create_day(day, frequency, frequency_modifier) - raise ArgumentError, "day property is only valid for tasks that run monthly or weekly" unless [:weekly, :monthly].include?(frequency) + raise ArgumentError, "day property is only valid for tasks that run monthly or weekly" unless %i{weekly monthly}.include?(frequency) # This has been verified with schtask.exe https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/schtasks#d-dayday-- # verified with earlier code if day "*" is given with frequency it raised exception Invalid value for /D option @@ -301,7 +302,7 @@ class Chef else days.map! { |day| day.to_s.strip.downcase } unless (days - VALID_WEEK_DAYS).empty? - raise ArgumentError, "day property invalid. Only valid values are: #{VALID_WEEK_DAYS.map(&:upcase).join(', ')}. Multiple values must be separated by a comma." + raise ArgumentError, "day property invalid. Only valid values are: #{VALID_WEEK_DAYS.map(&:upcase).join(", ")}. Multiple values must be separated by a comma." end end end @@ -309,11 +310,12 @@ class Chef def validate_create_months(months, frequency) raise ArgumentError, "months property is only valid for tasks that run monthly" if frequency != :monthly + if months.is_a?(String) months = months.split(",") months.map! { |month| month.strip.upcase } unless (months - VALID_MONTHS).empty? - raise ArgumentError, "months property invalid. Only valid values are: #{VALID_MONTHS.join(', ')}. Multiple values must be separated by a comma." + raise ArgumentError, "months property invalid. Only valid values are: #{VALID_MONTHS.join(", ")}. Multiple values must be separated by a comma." end end end diff --git a/lib/chef/resource/windows_uac.rb b/lib/chef/resource/windows_uac.rb index f53767f4b8..c4d5b53c14 100644 --- a/lib/chef/resource/windows_uac.rb +++ b/lib/chef/resource/windows_uac.rb @@ -44,12 +44,12 @@ class Chef property :consent_behavior_admins, Symbol, description: 'Behavior of the elevation prompt for administrators in Admin Approval Mode. Sets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA\ConsentPromptBehaviorAdmin.', - equal_to: [:no_prompt, :secure_prompt_for_creds, :secure_prompt_for_consent, :prompt_for_creds, :prompt_for_consent, :prompt_for_consent_non_windows_binaries], + equal_to: %i{no_prompt secure_prompt_for_creds secure_prompt_for_consent prompt_for_creds prompt_for_consent prompt_for_consent_non_windows_binaries}, default: :prompt_for_consent_non_windows_binaries property :consent_behavior_users, Symbol, description: 'Behavior of the elevation prompt for standard users. Sets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA\ConsentPromptBehaviorUser.', - equal_to: [:auto_deny, :secure_prompt_for_creds, :prompt_for_creds], + equal_to: %i{auto_deny secure_prompt_for_creds prompt_for_creds}, default: :prompt_for_creds action :configure do @@ -79,14 +79,14 @@ class Chef # # @return [Integer] def consent_behavior_admins_symbol_to_reg(sym) - [:no_prompt, :secure_prompt_for_creds, :secure_prompt_for_consent, :prompt_for_creds, :prompt_for_consent, :prompt_for_consent_non_windows_binaries].index(sym) + %i{no_prompt secure_prompt_for_creds secure_prompt_for_consent prompt_for_creds prompt_for_consent prompt_for_consent_non_windows_binaries}.index(sym) end # converts the symbols we use in the consent_behavior_users property into numbers 0-2 based on their array index # # @return [Integer] def consent_behavior_users_symbol_to_reg(sym) - [:auto_deny, :secure_prompt_for_creds, :prompt_for_creds].index(sym) + %i{auto_deny secure_prompt_for_creds prompt_for_creds}.index(sym) end end end diff --git a/lib/chef/resource/windows_workgroup.rb b/lib/chef/resource/windows_workgroup.rb index 3a983b6987..b1ae5c2b95 100644 --- a/lib/chef/resource/windows_workgroup.rb +++ b/lib/chef/resource/windows_workgroup.rb @@ -45,7 +45,7 @@ class Chef desired_state: false property :reboot, Symbol, - equal_to: [:never, :request_reboot, :reboot_now], + equal_to: %i{never request_reboot reboot_now}, validation_message: "The reboot property accepts :immediate (reboot as soon as the resource completes), :delayed (reboot once the #{Chef::Dist::PRODUCT} run completes), and :never (Don't reboot)", description: "Controls the system reboot behavior post workgroup joining. Reboot immediately, after the #{Chef::Dist::PRODUCT} run completes, or never. Note that a reboot is necessary for changes to take effect.", coerce: proc { |x| clarify_reboot(x) }, @@ -105,6 +105,7 @@ class Chef def workgroup_member? node_workgroup = powershell_out!("(Get-WmiObject -Class Win32_ComputerSystem).Workgroup") raise "Failed to determine if system already a member of workgroup #{new_resource.workgroup_name}" if node_workgroup.error? + node_workgroup.stdout.downcase.strip == new_resource.workgroup_name.downcase end end diff --git a/lib/chef/resource/yum_repository.rb b/lib/chef/resource/yum_repository.rb index 1883439da1..05639842af 100644 --- a/lib/chef/resource/yum_repository.rb +++ b/lib/chef/resource/yum_repository.rb @@ -142,7 +142,7 @@ class Chef property :report_instanceid, [TrueClass, FalseClass], description: "Determines whether to report the instance ID when using Amazon Linux AMIs and repositories." - property :repositoryid, String, regex: [/^[^\/]+$/], + property :repositoryid, String, regex: [%r{^[^/]+$}], description: "An optional property to set the repository name if it differs from the resource block's name.", validation_message: "repositoryid property cannot contain a forward slash '/'", name_property: true diff --git a/lib/chef/resource/zypper_repository.rb b/lib/chef/resource/zypper_repository.rb index 92ab012c66..447660e9ac 100644 --- a/lib/chef/resource/zypper_repository.rb +++ b/lib/chef/resource/zypper_repository.rb @@ -29,7 +29,7 @@ class Chef introduced "13.3" property :repo_name, String, - regex: [/^[^\/]+$/], + regex: [%r{^[^/]+$}], description: "An optional property to set the repository name if it differs from the resource block's name.", validation_message: "repo_name property cannot contain a forward slash '/'", name_property: true diff --git a/lib/chef/resource_builder.rb b/lib/chef/resource_builder.rb index d4d20e01ed..7d2184c06a 100644 --- a/lib/chef/resource_builder.rb +++ b/lib/chef/resource_builder.rb @@ -47,6 +47,7 @@ class Chef if resource.resource_name.nil? raise Chef::Exceptions::InvalidResourceSpecification, "#{resource}.resource_name is `nil`! Did you forget to put `provides :blah` or `resource_name :blah` in your resource class?" end + resource.source_line = created_at resource.declared_type = type diff --git a/lib/chef/resource_collection.rb b/lib/chef/resource_collection.rb index 0293f380b0..3b6ff4297e 100644 --- a/lib/chef/resource_collection.rb +++ b/lib/chef/resource_collection.rb @@ -1,7 +1,7 @@ # # Author:: Adam Jacob (<adam@chef.io>) # Author:: Christopher Walters (<cw@chef.io>) -# Copyright:: Copyright 2008-2016, Chef Software Inc. +# Copyright:: Copyright 2008-2019, Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -87,9 +87,9 @@ class Chef # Read-only methods are simple to delegate - doing that below resource_list_methods = Enumerable.instance_methods + - [:iterator, :all_resources, :[], :each, :execute_each_resource, :each_index, :empty?] - + %i{iterator all_resources [] each execute_each_resource each_index empty?} - [:find] # find overridden below - resource_set_methods = [:resources, :keys, :validate_lookup_spec!] + resource_set_methods = %i{resources keys validate_lookup_spec!} def_delegators :resource_list, *resource_list_methods def_delegators :resource_set, *resource_set_methods @@ -119,7 +119,7 @@ class Chef end def self.from_hash(o) - collection = new() + collection = new { "@resource_list" => "ResourceList", "@resource_set" => "ResourceSet" }.each_pair do |name, klass| obj = Chef::ResourceCollection.const_get(klass).from_hash(o["instance_vars"].delete(name)) collection.instance_variable_set(name.to_sym, obj) @@ -134,6 +134,7 @@ class Chef rc.resource_collection.resource_set.lookup(key) rescue Chef::Exceptions::ResourceNotFound raise if rc.parent_run_context.nil? + lookup_recursive(rc.parent_run_context, key) end @@ -141,6 +142,7 @@ class Chef rc.resource_collection.resource_set.find(*args) rescue Chef::Exceptions::ResourceNotFound raise if rc.parent_run_context.nil? + find_recursive(rc.parent_run_context, *args) end end diff --git a/lib/chef/resource_collection/resource_collection_serialization.rb b/lib/chef/resource_collection/resource_collection_serialization.rb index 3008625912..57e2e27e6a 100644 --- a/lib/chef/resource_collection/resource_collection_serialization.rb +++ b/lib/chef/resource_collection/resource_collection_serialization.rb @@ -23,7 +23,7 @@ class Chef module ResourceCollectionSerialization # Serialize this object as a hash def to_h - instance_vars = Hash.new + instance_vars = {} instance_variables.each do |iv| instance_vars[iv] = instance_variable_get(iv) end @@ -45,7 +45,7 @@ class Chef module ClassMethods def from_hash(o) - collection = new() + collection = new o["instance_vars"].each do |k, v| collection.instance_variable_set(k.to_sym, v) end @@ -58,9 +58,10 @@ class Chef end def is_chef_resource!(arg) - unless arg.kind_of?(Chef::Resource) + unless arg.is_a?(Chef::Resource) raise ArgumentError, "Cannot insert a #{arg.class} into a resource collection: must be a subclass of Chef::Resource" end + true end end diff --git a/lib/chef/resource_collection/resource_list.rb b/lib/chef/resource_collection/resource_list.rb index 9e2b798e93..2bcbc8de0f 100644 --- a/lib/chef/resource_collection/resource_list.rb +++ b/lib/chef/resource_collection/resource_list.rb @@ -36,11 +36,11 @@ class Chef private :resources # Delegate direct access methods to the @resources array # 4 extra methods here are not included in the Enumerable's instance methods - direct_access_methods = Enumerable.instance_methods + [ :[], :each, :each_index, :empty? ] + direct_access_methods = Enumerable.instance_methods + %i{[] each each_index empty?} def_delegators :resources, *(direct_access_methods) def initialize - @resources = Array.new + @resources = [] @insert_after_idx = nil end @@ -69,11 +69,13 @@ class Chef def delete(key) raise ArgumentError, "Must pass a Chef::Resource or String to delete" unless key.is_a?(String) || key.is_a?(Chef::Resource) + key = key.to_s ret = @resources.reject! { |r| r.to_s == key } if ret.nil? raise Chef::Exceptions::ResourceNotFound, "Cannot find a resource matching #{key} (did you define it first?)" end + ret end @@ -96,7 +98,7 @@ class Chef end def self.from_hash(o) - collection = new() + collection = new resources = o["instance_vars"]["@resources"].map { |r| Chef::Resource.from_hash(r) } collection.instance_variable_set(:@resources, resources) collection diff --git a/lib/chef/resource_collection/resource_set.rb b/lib/chef/resource_collection/resource_set.rb index b1c980dbc1..6b51ace3c1 100644 --- a/lib/chef/resource_collection/resource_set.rb +++ b/lib/chef/resource_collection/resource_set.rb @@ -36,7 +36,7 @@ class Chef NAMELESS_RESOURCE_MATCH = /^([^\[\]\s]+)$/.freeze def initialize - @resources_by_key = Hash.new + @resources_by_key = {} end def keys @@ -53,22 +53,26 @@ class Chef def lookup(key) raise ArgumentError, "Must pass a Chef::Resource or String to lookup" unless key.is_a?(String) || key.is_a?(Chef::Resource) + key = key.to_s res = @resources_by_key[key] unless res raise Chef::Exceptions::ResourceNotFound, "Cannot find a resource matching #{key} (did you define it first?)" end + res end def delete(key) raise ArgumentError, "Must pass a Chef::Resource or String to delete" unless key.is_a?(String) || key.is_a?(Chef::Resource) + key = key.to_s res = @resources_by_key.delete(key) if res == @resources_by_key.default raise Chef::Exceptions::ResourceNotFound, "Cannot find a resource matching #{key} (did you define it first?)" end + res end @@ -85,7 +89,7 @@ class Chef # Raises an ArgumentError if you feed it bad lookup information # Raises a Runtime Error if it can't find the resources you are looking for. def find(*args) - results = Array.new + results = [] args.each do |arg| case arg when Hash @@ -136,7 +140,7 @@ class Chef end def self.from_hash(o) - collection = new() + collection = new rl = o["instance_vars"]["@resources_by_key"] resources = rl.merge(rl) { |k, r| Chef::Resource.from_hash(r) } collection.instance_variable_set(:@resources_by_key, resources) @@ -150,9 +154,9 @@ class Chef end def find_resource_by_hash(arg) - results = Array.new + results = [] arg.each do |resource_type, name_list| - instance_names = name_list.kind_of?(Array) ? name_list : [ name_list ] + instance_names = name_list.is_a?(Array) ? name_list : [ name_list ] instance_names.each do |instance_name| results << lookup(create_key(resource_type, instance_name)) end @@ -170,7 +174,7 @@ class Chef rescue Chef::Exceptions::ResourceNotFound => e if arg =~ MULTIPLE_RESOURCE_MATCH begin - results = Array.new + results = [] resource_type = $1 arg =~ /^.+\[(.+)\]$/ resource_list = $1 diff --git a/lib/chef/resource_collection/stepable_iterator.rb b/lib/chef/resource_collection/stepable_iterator.rb index 958ffa28cb..d010c29be5 100644 --- a/lib/chef/resource_collection/stepable_iterator.rb +++ b/lib/chef/resource_collection/stepable_iterator.rb @@ -82,6 +82,7 @@ class Chef def step return nil if @position == size + call_iterator_block @position += 1 end diff --git a/lib/chef/resource_definition.rb b/lib/chef/resource_definition.rb index 6c0f76c169..40c15a1baa 100644 --- a/lib/chef/resource_definition.rb +++ b/lib/chef/resource_definition.rb @@ -29,20 +29,22 @@ class Chef def initialize(node = nil) @name = nil - @params = Hash.new + @params = {} @recipe = nil @node = node end def define(resource_name, prototype_params = nil, &block) - unless resource_name.kind_of?(Symbol) + unless resource_name.is_a?(Symbol) raise ArgumentError, "You must use a symbol when defining a new resource!" end + @name = resource_name if prototype_params - unless prototype_params.kind_of?(Hash) + unless prototype_params.is_a?(Hash) raise ArgumentError, "You must pass a hash as the prototype parameters for a definition." end + @params = prototype_params end if Kernel.block_given? diff --git a/lib/chef/resource_definition_list.rb b/lib/chef/resource_definition_list.rb index 0dbc115ada..d28a8f4bd5 100644 --- a/lib/chef/resource_definition_list.rb +++ b/lib/chef/resource_definition_list.rb @@ -26,7 +26,7 @@ class Chef attr_accessor :defines def initialize - @defines = Hash.new + @defines = {} end def define(resource_name, prototype_params = nil, &block) diff --git a/lib/chef/resource_inspector.rb b/lib/chef/resource_inspector.rb index 940440de7c..8d92db04b6 100644 --- a/lib/chef/resource_inspector.rb +++ b/lib/chef/resource_inspector.rb @@ -25,7 +25,7 @@ require_relative "json_compat" module ResourceInspector def self.get_default(default) - if default.kind_of?(Chef::DelayedEvaluator) + if default.is_a?(Chef::DelayedEvaluator) # ideally we'd get the block we pass to `lazy`, but the best we can do # is to get the source location, which then results in reparsing the source # code for the resource ourselves and just no diff --git a/lib/chef/role.rb b/lib/chef/role.rb index d0c1bc4327..d32de42756 100644 --- a/lib/chef/role.rb +++ b/lib/chef/role.rb @@ -91,7 +91,7 @@ class Chef # Per environment run lists def env_run_lists(env_run_lists = nil) - if !env_run_lists.nil? + unless env_run_lists.nil? unless env_run_lists.key?("_default") msg = "_default key is required in env_run_lists.\n" msg << "(env_run_lists: #{env_run_lists.inspect})" @@ -106,7 +106,7 @@ class Chef alias :env_run_list :env_run_lists def env_run_lists_add(env_run_lists = nil) - if !env_run_lists.nil? + unless env_run_lists.nil? env_run_lists.each { |k, v| @env_run_lists[k] = Chef::RunList.new(*Array(v)) } end @env_run_lists @@ -143,9 +143,9 @@ class Chef # Render to_json correctly for run_list items (both run_list and evn_run_lists) # so malformed json does not result - "run_list" => run_list.run_list.map { |item| item.to_s }, + "run_list" => run_list.run_list.map(&:to_s), "env_run_lists" => env_run_lists_without_default.inject({}) do |accumulator, (k, v)| - accumulator[k] = v.map { |x| x.to_s } + accumulator[k] = v.map(&:to_s) accumulator end, } @@ -192,7 +192,7 @@ class Chef # Get the list of all roles from the API. def self.list(inflate = false) if inflate - response = Hash.new + response = {} Chef::Search::Query.new.search(:role) do |n| response[n.name] = n unless n.nil? end @@ -226,6 +226,7 @@ class Chef chef_server_rest.put("roles/#{@name}", self) rescue Net::HTTPClientException => e raise e unless e.response.code == "404" + chef_server_rest.post("roles", self) end self @@ -248,11 +249,12 @@ class Chef paths = Array(Chef::Config[:role_path]) paths.each do |path| roles_files = Dir.glob(File.join(Chef::Util::PathHelper.escape_glob_dir(path), "**", "**")) - js_files = roles_files.select { |file| file.match(/\/#{name}\.json$/) } - rb_files = roles_files.select { |file| file.match(/\/#{name}\.rb$/) } + js_files = roles_files.select { |file| file.match(%r{/#{name}\.json$}) } + rb_files = roles_files.select { |file| file.match(%r{/#{name}\.rb$}) } if js_files.count > 1 || rb_files.count > 1 raise Chef::Exceptions::DuplicateRole, "Multiple roles of same type found named #{name}" end + js_path, rb_path = js_files.first, rb_files.first if js_path && File.exists?(js_path) diff --git a/lib/chef/run_context.rb b/lib/chef/run_context.rb index 49b904aeed..eb211dc5a5 100644 --- a/lib/chef/run_context.rb +++ b/lib/chef/run_context.rb @@ -185,7 +185,7 @@ class Chef @logger = logger || Chef::Log.with_child @cookbook_collection = cookbook_collection self.node = node if node - @definitions = Hash.new + @definitions = {} @loaded_recipes_hash = {} @loaded_attributes_hash = {} @reboot_info = {} @@ -313,7 +313,7 @@ class Chef # @see DSL::IncludeRecipe#include_recipe # def include_recipe(*recipe_names, current_cookbook: nil) - result_recipes = Array.new + result_recipes = [] recipe_names.flatten.each do |recipe_name| if result = load_recipe(recipe_name, current_cookbook: current_cookbook) result_recipes << result @@ -373,7 +373,7 @@ class Chef # @raise [Chef::Exceptions::RecipeNotFound] If the file does not exist. # def load_recipe_file(recipe_file) - if !File.exist?(recipe_file) + unless File.exist?(recipe_file) raise Chef::Exceptions::RecipeNotFound, "could not find recipe file #{recipe_file}" end @@ -705,12 +705,12 @@ class Chef resource_collection= runner runner= - }.map { |x| x.to_sym } + }.map(&:to_sym) # Verify that we didn't miss any methods unless @__skip_method_checking # hook specifically for compat_resource missing_methods = superclass.instance_methods(false) - instance_methods(false) - CHILD_STATE - if !missing_methods.empty? + unless missing_methods.empty? raise "ERROR: not all methods of RunContext accounted for in ChildRunContext! All methods must be marked as child methods with CHILD_STATE or delegated to the parent_run_context. Missing #{missing_methods.join(", ")}." end end diff --git a/lib/chef/run_context/cookbook_compiler.rb b/lib/chef/run_context/cookbook_compiler.rb index 0ea66dcf52..116020de19 100644 --- a/lib/chef/run_context/cookbook_compiler.rb +++ b/lib/chef/run_context/cookbook_compiler.rb @@ -207,6 +207,7 @@ class Chef list_of_attr_files.each do |filename| next unless File.extname(filename) == ".rb" + load_attribute_file(cookbook_name.to_s, filename) end end @@ -223,6 +224,7 @@ class Chef def load_libraries_from_cookbook(cookbook_name) files_in_cookbook_by_segment(cookbook_name, :libraries).each do |filename| next unless File.extname(filename) == ".rb" + begin logger.trace("Loading cookbook #{cookbook_name}'s library file: #{filename}") Kernel.require(filename) @@ -237,10 +239,12 @@ class Chef def load_lwrps_from_cookbook(cookbook_name) files_in_cookbook_by_segment(cookbook_name, :providers).each do |filename| next unless File.extname(filename) == ".rb" + load_lwrp_provider(cookbook_name, filename) end files_in_cookbook_by_segment(cookbook_name, :resources).each do |filename| next unless File.extname(filename) == ".rb" + load_lwrp_resource(cookbook_name, filename) end end @@ -327,7 +331,7 @@ class Chef # +cookbook_name+ in lexical sort order. def each_cookbook_dep(cookbook_name, &block) cookbook = cookbook_collection[cookbook_name] - cookbook.metadata.dependencies.keys.sort.map { |x| x.to_sym }.each(&block) + cookbook.metadata.dependencies.keys.sort.map(&:to_sym).each(&block) end # Given a +recipe_name+, finds the file associated with the recipe. diff --git a/lib/chef/run_list.rb b/lib/chef/run_list.rb index 7ec5419ab7..1108b5d2c1 100644 --- a/lib/chef/run_list.rb +++ b/lib/chef/run_list.rb @@ -70,10 +70,11 @@ class Chef alias :add :<< def ==(other) - if other.kind_of?(Chef::RunList) + if other.is_a?(Chef::RunList) other.run_list_items == @run_list_items else return false unless other.respond_to?(:size) && (other.size == @run_list_items.size) + other_run_list_items = other.dup other_run_list_items.map! { |item| coerce_to_run_list_item(item) } @@ -86,7 +87,7 @@ class Chef end def for_json - to_a.map { |item| item.to_s } + to_a.map(&:to_s) end def to_json(*a) @@ -122,7 +123,7 @@ class Chef def reset!(*args) @run_list_items.clear args.flatten.each do |item| - if item.kind_of?(Chef::RunList) + if item.is_a?(Chef::RunList) item.each { |r| self << r } else self << item @@ -152,7 +153,7 @@ class Chef end def coerce_to_run_list_item(item) - item.kind_of?(RunListItem) ? item : parse_entry(item) + item.is_a?(RunListItem) ? item : parse_entry(item) end def expansion_for_data_source(environment, data_source, opts = {}) diff --git a/lib/chef/run_list/run_list_expansion.rb b/lib/chef/run_list/run_list_expansion.rb index 9ddcdf7373..9cd7aa1394 100644 --- a/lib/chef/run_list/run_list_expansion.rb +++ b/lib/chef/run_list/run_list_expansion.rb @@ -64,7 +64,7 @@ class Chef def initialize(environment, run_list_items, source = nil) @environment = environment - @missing_roles_with_including_role = Array.new + @missing_roles_with_including_role = [] @run_list_items = run_list_items.dup @source = source @@ -102,6 +102,7 @@ class Chef # nil if the role does not exist def inflate_role(role_name, included_by) return false if applied_role?(role_name) # Prevent infinite loops + applied_role(role_name) fetch_role(role_name, included_by) end @@ -140,7 +141,7 @@ class Chef end def errors - @missing_roles_with_including_role.map { |item| item.first } + @missing_roles_with_including_role.map(&:first) end def to_json(*a) diff --git a/lib/chef/run_list/run_list_item.rb b/lib/chef/run_list/run_list_item.rb index f5aec6de5e..30b9bbe562 100644 --- a/lib/chef/run_list/run_list_item.rb +++ b/lib/chef/run_list/run_list_item.rb @@ -18,10 +18,10 @@ class Chef class RunList class RunListItem - QUALIFIED_RECIPE = %r{^recipe\[([^\]@]+)(@([0-9]+(\.[0-9]+){1,2}))?\]$}.freeze - QUALIFIED_ROLE = %r{^role\[([^\]]+)\]$}.freeze - VERSIONED_UNQUALIFIED_RECIPE = %r{^([^@]+)(@([0-9]+(\.[0-9]+){1,2}))$}.freeze - FALSE_FRIEND = %r{[\[\]]}.freeze + QUALIFIED_RECIPE = /^recipe\[([^\]@]+)(@([0-9]+(\.[0-9]+){1,2}))?\]$/.freeze + QUALIFIED_ROLE = /^role\[([^\]]+)\]$/.freeze + VERSIONED_UNQUALIFIED_RECIPE = /^([^@]+)(@([0-9]+(\.[0-9]+){1,2}))$/.freeze + FALSE_FRIEND = /[\[\]]/.freeze attr_reader :name, :type, :version @@ -80,7 +80,7 @@ class Chef end def ==(other) - if other.kind_of?(String) + if other.is_a?(String) to_s == other.to_s else other.respond_to?(:type) && other.respond_to?(:name) && other.respond_to?(:version) && other.type == @type && other.name == @name && other.version == @version diff --git a/lib/chef/run_list/versioned_recipe_list.rb b/lib/chef/run_list/versioned_recipe_list.rb index 182c749b46..6083dae953 100644 --- a/lib/chef/run_list/versioned_recipe_list.rb +++ b/lib/chef/run_list/versioned_recipe_list.rb @@ -26,7 +26,7 @@ class Chef def initialize super - @versions = Hash.new + @versions = {} end def add_recipe(name, version = nil) diff --git a/lib/chef/run_status.rb b/lib/chef/run_status.rb index 575d31159b..4d3eae21ae 100644 --- a/lib/chef/run_status.rb +++ b/lib/chef/run_status.rb @@ -75,7 +75,7 @@ class Chef::RunStatus # The list of all resources in the current run context's +resource_collection+ # that are marked as updated def updated_resources - @run_context && @run_context.resource_collection.select { |r| r.updated } + @run_context && @run_context.resource_collection.select(&:updated) end # The backtrace from +exception+, if any diff --git a/lib/chef/runner.rb b/lib/chef/runner.rb index f3f4c9e9d9..a0ae61fe4c 100644 --- a/lib/chef/runner.rb +++ b/lib/chef/runner.rb @@ -89,9 +89,7 @@ class Chef # +run_action+ for each resource in turn. def converge # Resolve all lazy/forward references in notifications - run_context.resource_collection.each do |resource| - resource.resolve_notification_references - end + run_context.resource_collection.each(&:resolve_notification_references) # Execute each resource. run_context.resource_collection.execute_each_resource do |resource| @@ -118,7 +116,7 @@ class Chef collected_failures.client_run_failure(error) unless error.nil? delayed_actions.each do |notification| result = run_delayed_notification(notification) - if result.kind_of?(Exception) + if result.is_a?(Exception) collected_failures.notification_failure(result) end end diff --git a/lib/chef/search/query.rb b/lib/chef/search/query.rb index 46e5c15b8f..5a9c1f6d41 100644 --- a/lib/chef/search/query.rb +++ b/lib/chef/search/query.rb @@ -113,7 +113,7 @@ class Chef end def validate_type(t) - unless t.kind_of?(String) || t.kind_of?(Symbol) + unless t.is_a?(String) || t.is_a?(Symbol) msg = "Invalid search object type #{t.inspect} (#{t.class}), must be a String or Symbol." + "Usage: search(:node, QUERY[, OPTIONAL_ARGS])" + " `knife search environment QUERY (options)`" @@ -122,10 +122,10 @@ class Chef end def hashify_args(*args) - return Hash.new if args.empty? + return {} if args.empty? return args.first if args.first.is_a?(Hash) - args_h = Hash.new + args_h = {} # If we have 4 arguments, the first is the now-removed sort option, so # just ignore it. args.pop(0) if args.length == 4 diff --git a/lib/chef/shell/ext.rb b/lib/chef/shell/ext.rb index 5260832e91..843126b4f2 100644 --- a/lib/chef/shell/ext.rb +++ b/lib/chef/shell/ext.rb @@ -47,8 +47,8 @@ module Shell unless jobs.respond_to?(:session_select) def jobs.select_shell_session(target_context) # rubocop:disable Lint/NestedMethodDefinition - session = if target_context.kind_of?(Class) - select_session_by_context { |main| main.kind_of?(target_context) } + session = if target_context.is_a?(Class) + select_session_by_context { |main| main.is_a?(target_context) } else select_session_by_context { |main| main.equal?(target_context) } end diff --git a/lib/chef/shell/model_wrapper.rb b/lib/chef/shell/model_wrapper.rb index c2c5f2cd09..0ad4329c7f 100644 --- a/lib/chef/shell/model_wrapper.rb +++ b/lib/chef/shell/model_wrapper.rb @@ -33,6 +33,7 @@ module Shell def search(query) return all if query.to_s == "all" + results = [] Chef::Search::Query.new.search(@model_symbol, format_query(query)) do |obj| if block_given? @@ -81,7 +82,7 @@ module Shell # the user wanted instead of the URI=>object stuff def list_objects objects = @model_class.method(:list).arity == 0 ? @model_class.list : @model_class.list(true) - objects.map { |obj| Array(obj).find { |o| o.kind_of?(@model_class) } } + objects.map { |obj| Array(obj).find { |o| o.is_a?(@model_class) } } end def format_query(query) diff --git a/lib/chef/shell/shell_session.rb b/lib/chef/shell/shell_session.rb index d17d212d18..85e5b85ab3 100644 --- a/lib/chef/shell/shell_session.rb +++ b/lib/chef/shell/shell_session.rb @@ -260,7 +260,7 @@ module Shell @run_list_expansion = @node.expand!("server") @expanded_run_list_with_versions = @run_list_expansion.recipes.with_version_constraints_strings Chef::Log.info("Run List is [#{@node.run_list}]") - Chef::Log.info("Run List expands to [#{@expanded_run_list_with_versions.join(', ')}]") + Chef::Log.info("Run List expands to [#{@expanded_run_list_with_versions.join(", ")}]") @node end diff --git a/lib/chef/train_transport.rb b/lib/chef/train_transport.rb index fdb4b5305a..accaa6355b 100644 --- a/lib/chef/train_transport.rb +++ b/lib/chef/train_transport.rb @@ -94,13 +94,13 @@ class Chef def self.build_transport(logger = Chef::Log.with_child(subsystem: "transport")) # TODO: Consider supporting parsing the protocol from a URI passed to `--target` # - train_config = Hash.new + train_config = {} # Load the target_mode config context from Chef::Config, and place any valid settings into the train configuration tm_config = Chef::Config.target_mode protocol = tm_config.protocol train_config = tm_config.to_hash.select { |k| Train.options(protocol).key?(k) } - Chef::Log.trace("Using target mode options from Chef config file: #{train_config.keys.join(', ')}") if train_config + Chef::Log.trace("Using target mode options from Chef config file: #{train_config.keys.join(", ")}") if train_config # Load the credentials file, and place any valid settings into the train configuration credentials = load_credentials(tm_config.host) @@ -108,7 +108,7 @@ class Chef valid_settings = credentials.select { |k| Train.options(protocol).key?(k) } valid_settings[:enable_password] = credentials[:enable_password] if credentials.key?(:enable_password) train_config.merge!(valid_settings) - Chef::Log.trace("Using target mode options from credentials file: #{valid_settings.keys.join(', ')}") if valid_settings + Chef::Log.trace("Using target mode options from credentials file: #{valid_settings.keys.join(", ")}") if valid_settings end train_config[:logger] = logger diff --git a/lib/chef/user.rb b/lib/chef/user.rb index 99ade65150..91749cc158 100644 --- a/lib/chef/user.rb +++ b/lib/chef/user.rb @@ -181,7 +181,7 @@ class Chef # into the form # { "USERNAME" => "URI" } def self.transform_ohc_list_response(response) - new_response = Hash.new + new_response = {} response.each do |u| name = u["user"]["username"] new_response[name] = Chef::Config[:chef_server_url] + "/users/#{name}" diff --git a/lib/chef/user_v1.rb b/lib/chef/user_v1.rb index 015beb371b..786bc3a057 100644 --- a/lib/chef/user_v1.rb +++ b/lib/chef/user_v1.rb @@ -154,6 +154,7 @@ class Chef payload[:create_key] = @create_key unless @create_key.nil? payload[:middle_name] = @middle_name unless @middle_name.nil? raise Chef::Exceptions::InvalidUserAttribute, "You cannot set both public_key and create_key for create." if !@create_key.nil? && !@public_key.nil? + new_user = chef_root_rest_v1.post("users", payload) # get the private_key out of the chef_key hash if it exists @@ -168,6 +169,7 @@ class Chef # rescue API V0 if 406 and the server supports V0 supported_versions = server_client_api_version_intersection(e, SUPPORTED_API_VERSIONS) raise e unless supported_versions && supported_versions.include?(0) + payload = { username: @username, display_name: @display_name, @@ -311,7 +313,7 @@ class Chef # into the form # { "USERNAME" => "URI" } def self.transform_list_response(response) - new_response = Hash.new + new_response = {} response.each do |u| name = u["user"]["username"] new_response[name] = Chef::Config[:chef_server_url] + "/users/#{name}" diff --git a/lib/chef/util/diff.rb b/lib/chef/util/diff.rb index decff35d85..326f67a38e 100644 --- a/lib/chef/util/diff.rb +++ b/lib/chef/util/diff.rb @@ -58,6 +58,7 @@ class Chef def for_reporting # caller needs to ensure that new files aren't posted to resource reporting return nil if @diff.nil? + @diff.join("\\n") end @@ -89,8 +90,8 @@ class Chef diff_str = "" file_length_difference = 0 - old_data = IO.readlines(old_file).map { |e| e.chomp } - new_data = IO.readlines(new_file).map { |e| e.chomp } + old_data = IO.readlines(old_file).map(&:chomp) + new_data = IO.readlines(new_file).map(&:chomp) diff_data = ::Diff::LCS.diff(old_data, new_data) return diff_str if old_data.empty? && new_data.empty? @@ -111,6 +112,7 @@ class Chef file_length_difference = hunk.file_length_difference next unless old_hunk next if hunk.merge(old_hunk) + diff_str << old_hunk.diff(:unified) << "\n" ensure old_hunk = hunk @@ -170,6 +172,7 @@ class Chef return buff !~ /\A[\s[:print:]]*\z/m rescue ArgumentError => e return true if e.message =~ /invalid byte sequence/ + raise end end diff --git a/lib/chef/util/dsc/configuration_generator.rb b/lib/chef/util/dsc/configuration_generator.rb index d7fe17f979..6f3dd908b8 100644 --- a/lib/chef/util/dsc/configuration_generator.rb +++ b/lib/chef/util/dsc/configuration_generator.rb @@ -40,14 +40,15 @@ class Chef::Util::DSC document_generation_cmdlet = Chef::Util::Powershell::Cmdlet.new( @node, - configuration_document_generation_code(script_path, configuration_name)) + configuration_document_generation_code(script_path, configuration_name) + ) merged_configuration_flags = get_merged_configuration_flags!(configuration_flags, configuration_name) document_generation_cmdlet.run!(merged_configuration_flags, shellout_flags) configuration_document_location = find_configuration_document(configuration_name) - if ! configuration_document_location + unless configuration_document_location raise "No DSC configuration for '#{configuration_name}' was generated from supplied DSC script" end @@ -74,6 +75,7 @@ class Chef::Util::DSC if merged_configuration_flags.key?(switch.to_s.downcase.to_sym) raise ArgumentError, "The `flags` attribute for the dsc_script resource contained a command line switch :#{switch} that is disallowed." end + merged_configuration_flags[switch.to_s.downcase.to_sym] = value end end @@ -100,7 +102,7 @@ class Chef::Util::DSC if resources.length == 0 || resources.include?("*") "Import-DscResource -ModuleName #{resource_module}" else - "Import-DscResource -ModuleName #{resource_module} -Name #{resources.join(',')}" + "Import-DscResource -ModuleName #{resource_module} -Name #{resources.join(",")}" end end else @@ -131,9 +133,7 @@ class Chef::Util::DSC end def get_configuration_document(document_path) - ::File.open(document_path, "rb") do |file| - file.read - end + ::File.open(document_path, "rb", &:read) end end end diff --git a/lib/chef/util/dsc/lcm_output_parser.rb b/lib/chef/util/dsc/lcm_output_parser.rb index 63cc16fa39..e6c6147b42 100644 --- a/lib/chef/util/dsc/lcm_output_parser.rb +++ b/lib/chef/util/dsc/lcm_output_parser.rb @@ -80,7 +80,7 @@ class Chef def self.test_dsc_parser(lcm_output) lcm_output ||= "" - current_resource = Hash.new + current_resource = {} resources = [] lcm_output.lines.each do |line| @@ -110,7 +110,7 @@ class Chef def self.what_if_parser(lcm_output) lcm_output ||= "" - current_resource = Hash.new + current_resource = {} resources = [] lcm_output.lines.each do |line| diff --git a/lib/chef/util/dsc/local_configuration_manager.rb b/lib/chef/util/dsc/local_configuration_manager.rb index 79c57c50c2..c0c05faba9 100644 --- a/lib/chef/util/dsc/local_configuration_manager.rb +++ b/lib/chef/util/dsc/local_configuration_manager.rb @@ -93,9 +93,9 @@ class Chef::Util::DSC # LCM returns an error if any of the resources do not support the opptional What-If Chef::Log.warn("Received error while testing configuration due to resource not supporting 'WhatIf'") elsif dsc_module_import_failure?(dsc_exception_output) - Chef::Log.warn("Received error while testing configuration due to a module for an imported resource possibly not being fully installed:\n#{dsc_exception_output.gsub(/\s+/, ' ')}") + Chef::Log.warn("Received error while testing configuration due to a module for an imported resource possibly not being fully installed:\n#{dsc_exception_output.gsub(/\s+/, " ")}") else - Chef::Log.warn("Received error while testing configuration:\n#{dsc_exception_output.gsub(/\s+/, ' ')}") + Chef::Log.warn("Received error while testing configuration:\n#{dsc_exception_output.gsub(/\s+/, " ")}") end end diff --git a/lib/chef/util/file_edit.rb b/lib/chef/util/file_edit.rb index 5ea3c17129..7d6bb88f60 100644 --- a/lib/chef/util/file_edit.rb +++ b/lib/chef/util/file_edit.rb @@ -30,6 +30,7 @@ class Chef def initialize(filepath) raise ArgumentError, "File '#{filepath}' does not exist" unless File.exist?(filepath) + @editor = Editor.new(File.open(filepath, &:readlines)) @original_pathname = filepath @file_edited = false diff --git a/lib/chef/util/powershell/cmdlet.rb b/lib/chef/util/powershell/cmdlet.rb index 72657a6d55..75cf489e9e 100644 --- a/lib/chef/util/powershell/cmdlet.rb +++ b/lib/chef/util/powershell/cmdlet.rb @@ -89,7 +89,7 @@ class Chef def run!(switches = {}, execution_options = {}, *arguments) result = run(switches, execution_options, arguments) - if ! result.succeeded? + unless result.succeeded? raise Chef::Exceptions::PowershellCmdletException, "PowerShell Cmdlet failed: #{result.stderr}" end diff --git a/lib/chef/util/threaded_job_queue.rb b/lib/chef/util/threaded_job_queue.rb index eaffd9ea70..6b13bf99a3 100644 --- a/lib/chef/util/threaded_job_queue.rb +++ b/lib/chef/util/threaded_job_queue.rb @@ -54,7 +54,7 @@ class Chef end end workers.each { |worker| self << Thread.method(:exit) } - workers.each { |worker| worker.join } + workers.each(&:join) end end end diff --git a/lib/chef/util/windows/logon_session.rb b/lib/chef/util/windows/logon_session.rb index 2e1f19b001..b7db9da51c 100644 --- a/lib/chef/util/windows/logon_session.rb +++ b/lib/chef/util/windows/logon_session.rb @@ -51,7 +51,7 @@ class Chef logon_type = (authentication == :local) ? (Chef::ReservedNames::Win32::API::Security::LOGON32_LOGON_NETWORK) : (Chef::ReservedNames::Win32::API::Security::LOGON32_LOGON_NEW_CREDENTIALS) status = Chef::ReservedNames::Win32::API::Security.LogonUserW(username, domain, password, logon_type, Chef::ReservedNames::Win32::API::Security::LOGON32_PROVIDER_DEFAULT, token) - if !status + unless status last_error = FFI::LastError.error raise Chef::Exceptions::Win32APIError, "Logon for user `#{original_username}` failed with Win32 status #{last_error}." end @@ -74,7 +74,7 @@ class Chef def set_user_context validate_session_open! - if ! session_opened + unless session_opened raise "Attempted to set the user context before opening a session." end @@ -84,7 +84,7 @@ class Chef status = Chef::ReservedNames::Win32::API::Security.ImpersonateLoggedOnUser(token.read_ulong) - if !status + unless status last_error = FFI::LastError.error raise Chef::Exceptions::Win32APIError, "Attempt to impersonate user `#{original_username}` failed with Win32 status #{last_error}." end @@ -98,7 +98,7 @@ class Chef if impersonating status = Chef::ReservedNames::Win32::API::Security.RevertToSelf - if !status + unless status last_error = FFI::LastError.error raise Chef::Exceptions::Win32APIError, "Unable to restore user context with Win32 status #{last_error}." end @@ -119,7 +119,7 @@ class Chef attr_reader :impersonating def validate_session_open! - if ! session_opened + unless session_opened raise "Attempted to set the user context before opening a session." end end diff --git a/lib/chef/util/windows/net_use.rb b/lib/chef/util/windows/net_use.rb index 1a2acaed33..9e6735429b 100644 --- a/lib/chef/util/windows/net_use.rb +++ b/lib/chef/util/windows/net_use.rb @@ -38,7 +38,7 @@ class Chef::Util::Windows::NetUse < Chef::Util::Windows def add(args) if args.class == String remote = args - args = Hash.new + args = {} args[:remote] = remote end args[:local] ||= use_name @@ -66,7 +66,7 @@ class Chef::Util::Windows::NetUse < Chef::Util::Windows end def device - get_info()[:remote] + get_info[:remote] end def delete diff --git a/lib/chef/util/windows/net_user.rb b/lib/chef/util/windows/net_user.rb index 615e666b66..5545ff4ca5 100644 --- a/lib/chef/util/windows/net_user.rb +++ b/lib/chef/util/windows/net_user.rb @@ -103,6 +103,7 @@ class Chef::Util::Windows::NetUser < Chef::Util::Windows if e.to_s =~ /System Error Code: 1326/ return false end + # all other exceptions will assume we cannot logon for a different reason Chef::Log.trace("Unable to login with the specified credentials. Assuming the credentials are valid.") true @@ -167,6 +168,6 @@ class Chef::Util::Windows::NetUser < Chef::Util::Windows end def check_enabled - (get_info()[:flags] & NetUser::UF_ACCOUNTDISABLE) != 0 + (get_info[:flags] & NetUser::UF_ACCOUNTDISABLE) != 0 end end diff --git a/lib/chef/version_class.rb b/lib/chef/version_class.rb index f98673b019..68acaf1e44 100644 --- a/lib/chef/version_class.rb +++ b/lib/chef/version_class.rb @@ -33,7 +33,7 @@ class Chef end def <=>(other) - [:major, :minor, :patch].each do |method| + %i{major minor patch}.each do |method| version = send(method) begin ans = (version <=> other.send(method)) diff --git a/lib/chef/version_constraint.rb b/lib/chef/version_constraint.rb index ba0a3669ed..bfaf403f47 100644 --- a/lib/chef/version_constraint.rb +++ b/lib/chef/version_constraint.rb @@ -90,7 +90,7 @@ class Chef parse(constraint_spec.first) else msg = "only one version constraint operation is supported, but you gave #{constraint_spec.size} " - msg << "['#{constraint_spec.join(', ')}']" + msg << "['#{constraint_spec.join(", ")}']" raise Chef::Exceptions::InvalidVersionConstraint, msg end end diff --git a/lib/chef/whitelist.rb b/lib/chef/whitelist.rb index 3f23aff240..8309580e81 100644 --- a/lib/chef/whitelist.rb +++ b/lib/chef/whitelist.rb @@ -73,7 +73,7 @@ class Chef # assumed to contain exact keys (that is, Array elements will not be split # by "/"). def self.to_array(item) - return item if item.kind_of? Array + return item if item.is_a? Array parts = item.split("/") parts.shift if !parts.empty? && parts[0].empty? diff --git a/lib/chef/win32/api/crypto.rb b/lib/chef/win32/api/crypto.rb index 1b73ac65d1..13828dd62a 100644 --- a/lib/chef/win32/api/crypto.rb +++ b/lib/chef/win32/api/crypto.rb @@ -47,15 +47,15 @@ class Chef end - safe_attach_function :CryptProtectData, [ - :PDATA_BLOB, - :LPCWSTR, - :PDATA_BLOB, - :pointer, - :PCRYPTPROTECT_PROMPTSTRUCT, - :DWORD, - :PDATA_BLOB, - ], :BOOL + safe_attach_function :CryptProtectData, %i{ + PDATA_BLOB + LPCWSTR + PDATA_BLOB + pointer + PCRYPTPROTECT_PROMPTSTRUCT + DWORD + PDATA_BLOB + }, :BOOL end end diff --git a/lib/chef/win32/api/error.rb b/lib/chef/win32/api/error.rb index 618ce266f6..79b65c8509 100644 --- a/lib/chef/win32/api/error.rb +++ b/lib/chef/win32/api/error.rb @@ -905,8 +905,8 @@ DWORD WINAPI FormatMessage( __in_opt va_list *Arguments ); =end - safe_attach_function :FormatMessageA, [:DWORD, :HANDLE, :DWORD, :DWORD, :LPTSTR, :DWORD, :varargs], :DWORD - safe_attach_function :FormatMessageW, [:DWORD, :HANDLE, :DWORD, :DWORD, :LPWSTR, :DWORD, :varargs], :DWORD + safe_attach_function :FormatMessageA, %i{DWORD HANDLE DWORD DWORD LPTSTR DWORD varargs}, :DWORD + safe_attach_function :FormatMessageW, %i{DWORD HANDLE DWORD DWORD LPWSTR DWORD varargs}, :DWORD =begin DWORD WINAPI GetLastError(void); @@ -918,7 +918,7 @@ void WINAPI SetLastError( ); =end safe_attach_function :SetLastError, [:DWORD], :void - safe_attach_function :SetLastErrorEx, [:DWORD, :DWORD], :void + safe_attach_function :SetLastErrorEx, %i{DWORD DWORD}, :void =begin UINT WINAPI GetErrorMode(void);s =end @@ -938,7 +938,7 @@ HMODULE WINAPI LoadLibraryEx( _In_ DWORD dwFlags ); =end - safe_attach_function :LoadLibraryExW, [:LPCTSTR, :HANDLE, :DWORD], :HANDLE + safe_attach_function :LoadLibraryExW, %i{LPCTSTR HANDLE DWORD}, :HANDLE =begin https://msdn.microsoft.com/en-us/library/windows/desktop/ms683152(v=vs.85).aspx diff --git a/lib/chef/win32/api/file.rb b/lib/chef/win32/api/file.rb index eea46ce87d..bdc2d6f6e5 100644 --- a/lib/chef/win32/api/file.rb +++ b/lib/chef/win32/api/file.rb @@ -369,7 +369,7 @@ HANDLE WINAPI CreateFile( __in_opt HANDLE hTemplateFile ); =end - safe_attach_function :CreateFileW, [:LPCTSTR, :DWORD, :DWORD, :LPSECURITY_ATTRIBUTES, :DWORD, :DWORD, :pointer], :HANDLE + safe_attach_function :CreateFileW, %i{LPCTSTR DWORD DWORD LPSECURITY_ATTRIBUTES DWORD DWORD pointer}, :HANDLE =begin BOOL WINAPI FindClose( @@ -393,7 +393,7 @@ DWORD WINAPI GetFinalPathNameByHandle( __in DWORD dwFlags ); =end - safe_attach_function :GetFinalPathNameByHandleW, [:HANDLE, :LPTSTR, :DWORD, :DWORD], :DWORD + safe_attach_function :GetFinalPathNameByHandleW, %i{HANDLE LPTSTR DWORD DWORD}, :DWORD =begin BOOL WINAPI GetFileInformationByHandle( @@ -401,7 +401,7 @@ BOOL WINAPI GetFileInformationByHandle( __out LPBY_HANDLE_FILE_INFORMATION lpFileInformation ); =end - safe_attach_function :GetFileInformationByHandle, [:HANDLE, :LPBY_HANDLE_FILE_INFORMATION], :BOOL + safe_attach_function :GetFileInformationByHandle, %i{HANDLE LPBY_HANDLE_FILE_INFORMATION}, :BOOL =begin HANDLE WINAPI FindFirstFile( @@ -409,7 +409,7 @@ HANDLE WINAPI FindFirstFile( __out LPWIN32_FIND_DATA lpFindFileData ); =end - safe_attach_function :FindFirstFileW, [:LPCTSTR, :LPWIN32_FIND_DATA], :HANDLE + safe_attach_function :FindFirstFileW, %i{LPCTSTR LPWIN32_FIND_DATA}, :HANDLE =begin BOOL WINAPI CreateHardLink( @@ -418,7 +418,7 @@ BOOL WINAPI CreateHardLink( __reserved LPSECURITY_ATTRIBUTES lpSecurityAttributes ); =end - safe_attach_function :CreateHardLinkW, [:LPCTSTR, :LPCTSTR, :LPSECURITY_ATTRIBUTES], :BOOLEAN + safe_attach_function :CreateHardLinkW, %i{LPCTSTR LPCTSTR LPSECURITY_ATTRIBUTES}, :BOOLEAN =begin BOOLEAN WINAPI CreateSymbolicLink( @@ -427,7 +427,7 @@ BOOLEAN WINAPI CreateSymbolicLink( __in DWORD dwFlags ); =end - safe_attach_function :CreateSymbolicLinkW, [:LPTSTR, :LPTSTR, :DWORD], :BOOLEAN + safe_attach_function :CreateSymbolicLinkW, %i{LPTSTR LPTSTR DWORD}, :BOOLEAN =begin DWORD WINAPI GetLongPathName( @@ -436,7 +436,7 @@ DWORD WINAPI GetLongPathName( __in DWORD cchBuffer ); =end - safe_attach_function :GetLongPathNameW, [:LPCTSTR, :LPTSTR, :DWORD], :DWORD + safe_attach_function :GetLongPathNameW, %i{LPCTSTR LPTSTR DWORD}, :DWORD =begin DWORD WINAPI GetShortPathName( @@ -445,7 +445,7 @@ DWORD WINAPI GetShortPathName( __in DWORD cchBuffer ); =end - safe_attach_function :GetShortPathNameW, [:LPCTSTR, :LPTSTR, :DWORD], :DWORD + safe_attach_function :GetShortPathNameW, %i{LPCTSTR LPTSTR DWORD}, :DWORD =begin BOOL WINAPI DeviceIoControl( @@ -459,7 +459,7 @@ BOOL WINAPI DeviceIoControl( __inout_opt LPOVERLAPPED lpOverlapped ); =end - safe_attach_function :DeviceIoControl, [:HANDLE, :DWORD, :LPVOID, :DWORD, :LPVOID, :DWORD, :LPDWORD, :pointer], :BOOL + safe_attach_function :DeviceIoControl, %i{HANDLE DWORD LPVOID DWORD LPVOID DWORD LPDWORD pointer}, :BOOL # BOOL WINAPI DeleteVolumeMountPoint( # _In_ LPCTSTR lpszVolumeMountPoint @@ -470,14 +470,14 @@ BOOL WINAPI DeviceIoControl( # _In_ LPCTSTR lpszVolumeMountPoint, # _In_ LPCTSTR lpszVolumeName # ); - safe_attach_function :SetVolumeMountPointW, [:LPCTSTR, :LPCTSTR], :BOOL + safe_attach_function :SetVolumeMountPointW, %i{LPCTSTR LPCTSTR}, :BOOL # BOOL WINAPI GetVolumeNameForVolumeMountPoint( # _In_ LPCTSTR lpszVolumeMountPoint, # _Out_ LPTSTR lpszVolumeName, # _In_ DWORD cchBufferLength # ); - safe_attach_function :GetVolumeNameForVolumeMountPointW, [:LPCTSTR, :LPTSTR, :DWORD], :BOOL + safe_attach_function :GetVolumeNameForVolumeMountPointW, %i{LPCTSTR LPTSTR DWORD}, :BOOL =begin BOOL WINAPI GetFileVersionInfo( @@ -487,7 +487,7 @@ BOOL WINAPI GetFileVersionInfo( _Out_ LPVOID lpData ); =end - safe_attach_function :GetFileVersionInfoW, [:LPCTSTR, :DWORD, :DWORD, :LPVOID], :BOOL + safe_attach_function :GetFileVersionInfoW, %i{LPCTSTR DWORD DWORD LPVOID}, :BOOL =begin DWORD WINAPI GetFileVersionInfoSize( @@ -495,7 +495,7 @@ DWORD WINAPI GetFileVersionInfoSize( _Out_opt_ LPDWORD lpdwHandle ); =end - safe_attach_function :GetFileVersionInfoSizeW, [:LPCTSTR, :LPDWORD], :DWORD + safe_attach_function :GetFileVersionInfoSizeW, %i{LPCTSTR LPDWORD}, :DWORD =begin BOOL WINAPI VerQueryValue( @@ -505,7 +505,7 @@ BOOL WINAPI VerQueryValue( _Out_ PUINT puLen ); =end - safe_attach_function :VerQueryValueW, [:LPCVOID, :LPCTSTR, :LPVOID, :PUINT], :BOOL + safe_attach_function :VerQueryValueW, %i{LPCVOID LPCTSTR LPVOID PUINT}, :BOOL ############################################### # Helpers diff --git a/lib/chef/win32/api/installer.rb b/lib/chef/win32/api/installer.rb index 118afe8c8f..5af1be7eba 100644 --- a/lib/chef/win32/api/installer.rb +++ b/lib/chef/win32/api/installer.rb @@ -44,7 +44,7 @@ UINT MsiOpenPackage( _Out_ MSIHANDLE *hProduct ); =end - safe_attach_function :msi_open_package, :MsiOpenPackageExA, [ :string, :int, :pointer ], :int + safe_attach_function :msi_open_package, :MsiOpenPackageExA, %i{string int pointer}, :int =begin UINT MsiGetProductProperty( @@ -54,7 +54,7 @@ UINT MsiGetProductProperty( _Inout_ DWORD *pcchValueBuf ); =end - safe_attach_function :msi_get_product_property, :MsiGetProductPropertyA, [ :pointer, :pointer, :pointer, :pointer ], :int + safe_attach_function :msi_get_product_property, :MsiGetProductPropertyA, %i{pointer pointer pointer pointer}, :int =begin UINT MsiGetProductInfo( @@ -64,7 +64,7 @@ UINT MsiGetProductInfo( _Inout_ DWORD *pcchValueBuf ); =end - safe_attach_function :msi_get_product_info, :MsiGetProductInfoA, [ :pointer, :pointer, :pointer, :pointer ], :int + safe_attach_function :msi_get_product_info, :MsiGetProductInfoA, %i{pointer pointer pointer pointer}, :int =begin UINT MsiCloseHandle( diff --git a/lib/chef/win32/api/memory.rb b/lib/chef/win32/api/memory.rb index 369ab5e650..cd7d9f0eb0 100644 --- a/lib/chef/win32/api/memory.rb +++ b/lib/chef/win32/api/memory.rb @@ -56,7 +56,7 @@ HLOCAL WINAPI LocalAlloc( __in SIZE_T uBytes ); =end - safe_attach_function :LocalAlloc, [ :UINT, :SIZE_T ], :pointer + safe_attach_function :LocalAlloc, %i{UINT SIZE_T}, :pointer =begin UINT WINAPI LocalFlags( @@ -79,7 +79,7 @@ HLOCAL WINAPI LocalReAlloc( __in UINT uFlags ); =end - safe_attach_function :LocalReAlloc, [ :pointer, :SIZE_T, :UINT ], :pointer + safe_attach_function :LocalReAlloc, %i{pointer SIZE_T UINT}, :pointer =begin UINT WINAPI LocalSize( @@ -95,9 +95,9 @@ UINT WINAPI LocalSize( ffi_lib FFI::Library::LIBC safe_attach_function :malloc, [:size_t], :pointer safe_attach_function :calloc, [:size_t], :pointer - safe_attach_function :realloc, [:pointer, :size_t], :pointer + safe_attach_function :realloc, %i{pointer size_t}, :pointer safe_attach_function :free, [:pointer], :void - safe_attach_function :memcpy, [:pointer, :pointer, :size_t], :pointer + safe_attach_function :memcpy, %i{pointer pointer size_t}, :pointer end end diff --git a/lib/chef/win32/api/net.rb b/lib/chef/win32/api/net.rb index 392a442962..182c31cf66 100644 --- a/lib/chef/win32/api/net.rb +++ b/lib/chef/win32/api/net.rb @@ -169,9 +169,9 @@ class Chef # _In_ LPBYTE buf, # _Out_ LPDWORD parm_err # ); - safe_attach_function :NetLocalGroupAdd, [ - :LPCWSTR, :DWORD, :LPBYTE, :LPDWORD - ], :DWORD + safe_attach_function :NetLocalGroupAdd, %i{ + LPCWSTR DWORD LPBYTE LPDWORD + }, :DWORD # NET_API_STATUS NetLocalGroupSetInfo( # _In_ LPCWSTR servername, @@ -180,15 +180,15 @@ class Chef # _In_ LPBYTE buf, # _Out_ LPDWORD parm_err # ); - safe_attach_function :NetLocalGroupSetInfo, [ - :LPCWSTR, :LPCWSTR, :DWORD, :LPBYTE, :LPDWORD - ], :DWORD + safe_attach_function :NetLocalGroupSetInfo, %i{ + LPCWSTR LPCWSTR DWORD LPBYTE LPDWORD + }, :DWORD # NET_API_STATUS NetLocalGroupDel( # _In_ LPCWSTR servername, # _In_ LPCWSTR groupname # ); - safe_attach_function :NetLocalGroupDel, [:LPCWSTR, :LPCWSTR], :DWORD + safe_attach_function :NetLocalGroupDel, %i{LPCWSTR LPCWSTR}, :DWORD # NET_API_STATUS NetLocalGroupGetMembers( # _In_ LPCWSTR servername, @@ -200,10 +200,10 @@ class Chef # _Out_ LPDWORD totalentries, # _Inout_ PDWORD_PTR resumehandle # ); - safe_attach_function :NetLocalGroupGetMembers, [ - :LPCWSTR, :LPCWSTR, :DWORD, :LPBYTE, :DWORD, - :LPDWORD, :LPDWORD, :PDWORD_PTR - ], :DWORD + safe_attach_function :NetLocalGroupGetMembers, %i{ + LPCWSTR LPCWSTR DWORD LPBYTE DWORD + LPDWORD LPDWORD PDWORD_PTR + }, :DWORD # NET_API_STATUS NetUserEnum( # _In_ LPCWSTR servername, @@ -215,10 +215,10 @@ class Chef # _Out_ LPDWORD totalentries, # _Inout_ LPDWORD resume_handle # ); - safe_attach_function :NetUserEnum, [ - :LPCWSTR, :DWORD, :DWORD, :LPBYTE, - :DWORD, :LPDWORD, :LPDWORD, :LPDWORD - ], :DWORD + safe_attach_function :NetUserEnum, %i{ + LPCWSTR DWORD DWORD LPBYTE + DWORD LPDWORD LPDWORD LPDWORD + }, :DWORD # NET_API_STATUS NetApiBufferFree( # _In_ LPVOID Buffer @@ -231,9 +231,9 @@ class Chef # _In_ LPBYTE buf, # _Out_ LPDWORD parm_err # ); - safe_attach_function :NetUserAdd, [ - :LMSTR, :DWORD, :LPBYTE, :LPDWORD - ], :DWORD + safe_attach_function :NetUserAdd, %i{ + LMSTR DWORD LPBYTE LPDWORD + }, :DWORD # NET_API_STATUS NetLocalGroupAddMembers( # _In_ LPCWSTR servername, @@ -242,9 +242,9 @@ class Chef # _In_ LPBYTE buf, # _In_ DWORD totalentries # ); - safe_attach_function :NetLocalGroupAddMembers, [ - :LPCWSTR, :LPCWSTR, :DWORD, :LPBYTE, :DWORD - ], :DWORD + safe_attach_function :NetLocalGroupAddMembers, %i{ + LPCWSTR LPCWSTR DWORD LPBYTE DWORD + }, :DWORD # NET_API_STATUS NetLocalGroupSetMembers( # _In_ LPCWSTR servername, @@ -253,9 +253,9 @@ class Chef # _In_ LPBYTE buf, # _In_ DWORD totalentries # ); - safe_attach_function :NetLocalGroupSetMembers, [ - :LPCWSTR, :LPCWSTR, :DWORD, :LPBYTE, :DWORD - ], :DWORD + safe_attach_function :NetLocalGroupSetMembers, %i{ + LPCWSTR LPCWSTR DWORD LPBYTE DWORD + }, :DWORD # NET_API_STATUS NetLocalGroupDelMembers( # _In_ LPCWSTR servername, @@ -264,9 +264,9 @@ class Chef # _In_ LPBYTE buf, # _In_ DWORD totalentries # ); - safe_attach_function :NetLocalGroupDelMembers, [ - :LPCWSTR, :LPCWSTR, :DWORD, :LPBYTE, :DWORD - ], :DWORD + safe_attach_function :NetLocalGroupDelMembers, %i{ + LPCWSTR LPCWSTR DWORD LPBYTE DWORD + }, :DWORD # NET_API_STATUS NetUserGetInfo( # _In_ LPCWSTR servername, @@ -274,9 +274,9 @@ class Chef # _In_ DWORD level, # _Out_ LPBYTE *bufptr # ); - safe_attach_function :NetUserGetInfo, [ - :LPCWSTR, :LPCWSTR, :DWORD, :LPBYTE - ], :DWORD + safe_attach_function :NetUserGetInfo, %i{ + LPCWSTR LPCWSTR DWORD LPBYTE + }, :DWORD # NET_API_STATUS NetApiBufferFree( # _In_ LPVOID Buffer @@ -290,22 +290,22 @@ class Chef # _In_ LPBYTE buf, # _Out_ LPDWORD parm_err # ); - safe_attach_function :NetUserSetInfo, [ - :LPCWSTR, :LPCWSTR, :DWORD, :LPBYTE, :LPDWORD - ], :DWORD + safe_attach_function :NetUserSetInfo, %i{ + LPCWSTR LPCWSTR DWORD LPBYTE LPDWORD + }, :DWORD # NET_API_STATUS NetUserDel( # _In_ LPCWSTR servername, # _In_ LPCWSTR username # ); - safe_attach_function :NetUserDel, [:LPCWSTR, :LPCWSTR], :DWORD + safe_attach_function :NetUserDel, %i{LPCWSTR LPCWSTR}, :DWORD # NET_API_STATUS NetUseDel( # _In_ LMSTR UncServerName, # _In_ LMSTR UseName, # _In_ DWORD ForceCond # ); - safe_attach_function :NetUseDel, [:LMSTR, :LMSTR, :DWORD], :DWORD + safe_attach_function :NetUseDel, %i{LMSTR LMSTR DWORD}, :DWORD # NET_API_STATUS NetUseGetInfo( # _In_ LMSTR UncServerName, @@ -313,7 +313,7 @@ class Chef # _In_ DWORD Level, # _Out_ LPBYTE *BufPtr # ); - safe_attach_function :NetUseGetInfo, [:LMSTR, :LMSTR, :DWORD, :pointer], :DWORD + safe_attach_function :NetUseGetInfo, %i{LMSTR LMSTR DWORD pointer}, :DWORD # NET_API_STATUS NetUseAdd( # _In_ LMSTR UncServerName, @@ -321,7 +321,7 @@ class Chef # _In_ LPBYTE Buf, # _Out_ LPDWORD ParmError # ); - safe_attach_function :NetUseAdd, [:LMSTR, :DWORD, :LPBYTE, :LPDWORD], :DWORD + safe_attach_function :NetUseAdd, %i{LMSTR DWORD LPBYTE LPDWORD}, :DWORD end end end diff --git a/lib/chef/win32/api/process.rb b/lib/chef/win32/api/process.rb index 3ac6a5c222..81a411e099 100644 --- a/lib/chef/win32/api/process.rb +++ b/lib/chef/win32/api/process.rb @@ -31,10 +31,10 @@ class Chef ffi_lib "kernel32" safe_attach_function :GetCurrentProcess, [], :HANDLE - safe_attach_function :GetProcessHandleCount, [ :HANDLE, :LPDWORD ], :BOOL + safe_attach_function :GetProcessHandleCount, %i{HANDLE LPDWORD}, :BOOL safe_attach_function :GetProcessId, [ :HANDLE ], :DWORD safe_attach_function :CloseHandle, [ :HANDLE ], :BOOL - safe_attach_function :IsWow64Process, [ :HANDLE, :PBOOL ], :BOOL + safe_attach_function :IsWow64Process, %i{HANDLE PBOOL}, :BOOL end end diff --git a/lib/chef/win32/api/psapi.rb b/lib/chef/win32/api/psapi.rb index 852cb9710b..491fe22c50 100644 --- a/lib/chef/win32/api/psapi.rb +++ b/lib/chef/win32/api/psapi.rb @@ -43,7 +43,7 @@ class Chef ffi_lib "psapi" - safe_attach_function :GetProcessMemoryInfo, [ :HANDLE, :pointer, :DWORD ], :BOOL + safe_attach_function :GetProcessMemoryInfo, %i{HANDLE pointer DWORD}, :BOOL end end diff --git a/lib/chef/win32/api/registry.rb b/lib/chef/win32/api/registry.rb index c368add37a..49f0da0010 100644 --- a/lib/chef/win32/api/registry.rb +++ b/lib/chef/win32/api/registry.rb @@ -36,14 +36,14 @@ class Chef # _In_ REGSAM samDesired, # _Reserved_ DWORD Reserved # ); - safe_attach_function :RegDeleteKeyExW, [ :HKEY, :LPCTSTR, :LONG, :DWORD ], :LONG - safe_attach_function :RegDeleteKeyExA, [ :HKEY, :LPCTSTR, :LONG, :DWORD ], :LONG + safe_attach_function :RegDeleteKeyExW, %i{HKEY LPCTSTR LONG DWORD}, :LONG + safe_attach_function :RegDeleteKeyExA, %i{HKEY LPCTSTR LONG DWORD}, :LONG # LONG WINAPI RegDeleteValue( # _In_ HKEY hKey, # _In_opt_ LPCTSTR lpValueName # ); - safe_attach_function :RegDeleteValueW, [ :HKEY, :LPCTSTR ], :LONG + safe_attach_function :RegDeleteValueW, %i{HKEY LPCTSTR}, :LONG end end diff --git a/lib/chef/win32/api/security.rb b/lib/chef/win32/api/security.rb index a856fbd0a1..b651283758 100644 --- a/lib/chef/win32/api/security.rb +++ b/lib/chef/win32/api/security.rb @@ -216,21 +216,21 @@ class Chef # Win32 API Bindings ############################################### - SE_OBJECT_TYPE = enum :SE_OBJECT_TYPE, [ - :SE_UNKNOWN_OBJECT_TYPE, - :SE_FILE_OBJECT, - :SE_SERVICE, - :SE_PRINTER, - :SE_REGISTRY_KEY, - :SE_LMSHARE, - :SE_KERNEL_OBJECT, - :SE_WINDOW_OBJECT, - :SE_DS_OBJECT, - :SE_DS_OBJECT_ALL, - :SE_PROVIDER_DEFINED_OBJECT, - :SE_WMIGUID_OBJECT, - :SE_REGISTRY_WOW64_32KEY, - ] + SE_OBJECT_TYPE = enum :SE_OBJECT_TYPE, %i{ + SE_UNKNOWN_OBJECT_TYPE + SE_FILE_OBJECT + SE_SERVICE + SE_PRINTER + SE_REGISTRY_KEY + SE_LMSHARE + SE_KERNEL_OBJECT + SE_WINDOW_OBJECT + SE_DS_OBJECT + SE_DS_OBJECT_ALL + SE_PROVIDER_DEFINED_OBJECT + SE_WMIGUID_OBJECT + SE_REGISTRY_WOW64_32KEY + } SID_NAME_USE = enum :SID_NAME_USE, [ :SidTypeUser, 1, @@ -298,12 +298,12 @@ class Chef end # https://msdn.microsoft.com/en-us/library/windows/desktop/aa379572%28v=vs.85%29.aspx - SECURITY_IMPERSONATION_LEVEL = enum :SECURITY_IMPERSONATION_LEVEL, [ - :SecurityAnonymous, - :SecurityIdentification, - :SecurityImpersonation, - :SecurityDelegation, - ] + SECURITY_IMPERSONATION_LEVEL = enum :SECURITY_IMPERSONATION_LEVEL, %i{ + SecurityAnonymous + SecurityIdentification + SecurityImpersonation + SecurityDelegation + } # https://msdn.microsoft.com/en-us/library/windows/desktop/bb530718%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396 ELEVATION_TYPE = enum :ELEVATION_TYPE, [ @@ -415,58 +415,58 @@ class Chef ffi_lib "advapi32" - safe_attach_function :AccessCheck, [:pointer, :HANDLE, :DWORD, :pointer, :pointer, :pointer, :pointer, :pointer], :BOOL - safe_attach_function :AddAce, [ :pointer, :DWORD, :DWORD, :LPVOID, :DWORD ], :BOOL - safe_attach_function :AddAccessAllowedAce, [ :pointer, :DWORD, :DWORD, :pointer ], :BOOL - safe_attach_function :AddAccessAllowedAceEx, [ :pointer, :DWORD, :DWORD, :DWORD, :pointer ], :BOOL - safe_attach_function :AddAccessDeniedAce, [ :pointer, :DWORD, :DWORD, :pointer ], :BOOL - safe_attach_function :AddAccessDeniedAceEx, [ :pointer, :DWORD, :DWORD, :DWORD, :pointer ], :BOOL - safe_attach_function :AdjustTokenPrivileges, [ :HANDLE, :BOOL, :pointer, :DWORD, :pointer, :PDWORD ], :BOOL - safe_attach_function :ConvertSidToStringSidA, [ :pointer, :pointer ], :BOOL - safe_attach_function :ConvertStringSidToSidW, [ :pointer, :pointer ], :BOOL - safe_attach_function :DeleteAce, [ :pointer, :DWORD ], :BOOL - safe_attach_function :DuplicateToken, [:HANDLE, :SECURITY_IMPERSONATION_LEVEL, :PHANDLE], :BOOL - safe_attach_function :EqualSid, [ :pointer, :pointer ], :BOOL + safe_attach_function :AccessCheck, %i{pointer HANDLE DWORD pointer pointer pointer pointer pointer}, :BOOL + safe_attach_function :AddAce, %i{pointer DWORD DWORD LPVOID DWORD}, :BOOL + safe_attach_function :AddAccessAllowedAce, %i{pointer DWORD DWORD pointer}, :BOOL + safe_attach_function :AddAccessAllowedAceEx, %i{pointer DWORD DWORD DWORD pointer}, :BOOL + safe_attach_function :AddAccessDeniedAce, %i{pointer DWORD DWORD pointer}, :BOOL + safe_attach_function :AddAccessDeniedAceEx, %i{pointer DWORD DWORD DWORD pointer}, :BOOL + safe_attach_function :AdjustTokenPrivileges, %i{HANDLE BOOL pointer DWORD pointer PDWORD}, :BOOL + safe_attach_function :ConvertSidToStringSidA, %i{pointer pointer}, :BOOL + safe_attach_function :ConvertStringSidToSidW, %i{pointer pointer}, :BOOL + safe_attach_function :DeleteAce, %i{pointer DWORD}, :BOOL + safe_attach_function :DuplicateToken, %i{HANDLE SECURITY_IMPERSONATION_LEVEL PHANDLE}, :BOOL + safe_attach_function :EqualSid, %i{pointer pointer}, :BOOL safe_attach_function :FreeSid, [ :pointer ], :pointer - safe_attach_function :GetAce, [ :pointer, :DWORD, :pointer ], :BOOL - safe_attach_function :GetFileSecurityW, [:LPCWSTR, :DWORD, :pointer, :DWORD, :pointer], :BOOL + safe_attach_function :GetAce, %i{pointer DWORD pointer}, :BOOL + safe_attach_function :GetFileSecurityW, %i{LPCWSTR DWORD pointer DWORD pointer}, :BOOL safe_attach_function :GetLengthSid, [ :pointer ], :DWORD - safe_attach_function :GetNamedSecurityInfoW, [ :LPWSTR, :SE_OBJECT_TYPE, :DWORD, :pointer, :pointer, :pointer, :pointer, :pointer ], :DWORD - safe_attach_function :GetSecurityDescriptorControl, [ :pointer, :PWORD, :LPDWORD], :BOOL - safe_attach_function :GetSecurityDescriptorDacl, [ :pointer, :LPBOOL, :pointer, :LPBOOL ], :BOOL - safe_attach_function :GetSecurityDescriptorGroup, [ :pointer, :pointer, :LPBOOL], :BOOL - safe_attach_function :GetSecurityDescriptorOwner, [ :pointer, :pointer, :LPBOOL], :BOOL - safe_attach_function :GetSecurityDescriptorSacl, [ :pointer, :LPBOOL, :pointer, :LPBOOL ], :BOOL - safe_attach_function :InitializeAcl, [ :pointer, :DWORD, :DWORD ], :BOOL - safe_attach_function :InitializeSecurityDescriptor, [ :pointer, :DWORD ], :BOOL + safe_attach_function :GetNamedSecurityInfoW, %i{LPWSTR SE_OBJECT_TYPE DWORD pointer pointer pointer pointer pointer}, :DWORD + safe_attach_function :GetSecurityDescriptorControl, %i{pointer PWORD LPDWORD}, :BOOL + safe_attach_function :GetSecurityDescriptorDacl, %i{pointer LPBOOL pointer LPBOOL}, :BOOL + safe_attach_function :GetSecurityDescriptorGroup, %i{pointer pointer LPBOOL}, :BOOL + safe_attach_function :GetSecurityDescriptorOwner, %i{pointer pointer LPBOOL}, :BOOL + safe_attach_function :GetSecurityDescriptorSacl, %i{pointer LPBOOL pointer LPBOOL}, :BOOL + safe_attach_function :InitializeAcl, %i{pointer DWORD DWORD}, :BOOL + safe_attach_function :InitializeSecurityDescriptor, %i{pointer DWORD}, :BOOL safe_attach_function :IsValidAcl, [ :pointer ], :BOOL safe_attach_function :IsValidSecurityDescriptor, [ :pointer ], :BOOL safe_attach_function :IsValidSid, [ :pointer ], :BOOL - safe_attach_function :LookupAccountNameW, [ :LPCWSTR, :LPCWSTR, :pointer, :LPDWORD, :LPWSTR, :LPDWORD, :pointer ], :BOOL - safe_attach_function :LookupAccountSidW, [ :LPCWSTR, :pointer, :LPWSTR, :LPDWORD, :LPWSTR, :LPDWORD, :pointer ], :BOOL - safe_attach_function :LookupPrivilegeNameW, [ :LPCWSTR, :PLUID, :LPWSTR, :LPDWORD ], :BOOL - safe_attach_function :LookupPrivilegeDisplayNameW, [ :LPCWSTR, :LPCWSTR, :LPWSTR, :LPDWORD, :LPDWORD ], :BOOL - safe_attach_function :LookupPrivilegeValueW, [ :LPCWSTR, :LPCWSTR, :PLUID ], :BOOL - safe_attach_function :LsaAddAccountRights, [ :pointer, :pointer, :pointer, :ULONG ], :NTSTATUS - safe_attach_function :LsaRemoveAccountRights, [ :pointer, :pointer, :BOOL, :pointer, :ULONG ], :NTSTATUS + safe_attach_function :LookupAccountNameW, %i{LPCWSTR LPCWSTR pointer LPDWORD LPWSTR LPDWORD pointer}, :BOOL + safe_attach_function :LookupAccountSidW, %i{LPCWSTR pointer LPWSTR LPDWORD LPWSTR LPDWORD pointer}, :BOOL + safe_attach_function :LookupPrivilegeNameW, %i{LPCWSTR PLUID LPWSTR LPDWORD}, :BOOL + safe_attach_function :LookupPrivilegeDisplayNameW, %i{LPCWSTR LPCWSTR LPWSTR LPDWORD LPDWORD}, :BOOL + safe_attach_function :LookupPrivilegeValueW, %i{LPCWSTR LPCWSTR PLUID}, :BOOL + safe_attach_function :LsaAddAccountRights, %i{pointer pointer pointer ULONG}, :NTSTATUS + safe_attach_function :LsaRemoveAccountRights, %i{pointer pointer BOOL pointer ULONG}, :NTSTATUS safe_attach_function :LsaClose, [ :LSA_HANDLE ], :NTSTATUS - safe_attach_function :LsaEnumerateAccountRights, [ :LSA_HANDLE, :PSID, :PLSA_UNICODE_STRING, :PULONG ], :NTSTATUS + safe_attach_function :LsaEnumerateAccountRights, %i{LSA_HANDLE PSID PLSA_UNICODE_STRING PULONG}, :NTSTATUS safe_attach_function :LsaFreeMemory, [ :PVOID ], :NTSTATUS safe_attach_function :LsaNtStatusToWinError, [ :NTSTATUS ], :ULONG - safe_attach_function :LsaOpenPolicy, [ :PLSA_UNICODE_STRING, :PLSA_OBJECT_ATTRIBUTES, :DWORD, :PLSA_HANDLE ], :NTSTATUS - safe_attach_function :MakeAbsoluteSD, [ :pointer, :pointer, :LPDWORD, :pointer, :LPDWORD, :pointer, :LPDWORD, :pointer, :LPDWORD, :pointer, :LPDWORD], :BOOL - safe_attach_function :MapGenericMask, [ :PDWORD, :PGENERICMAPPING ], :void - safe_attach_function :OpenProcessToken, [ :HANDLE, :DWORD, :PHANDLE ], :BOOL - safe_attach_function :QuerySecurityAccessMask, [ :DWORD, :LPDWORD ], :void - safe_attach_function :SetFileSecurityW, [ :LPWSTR, :DWORD, :pointer ], :BOOL - safe_attach_function :SetNamedSecurityInfoW, [ :LPWSTR, :SE_OBJECT_TYPE, :DWORD, :pointer, :pointer, :pointer, :pointer ], :DWORD - safe_attach_function :SetSecurityAccessMask, [ :DWORD, :LPDWORD ], :void - safe_attach_function :SetSecurityDescriptorDacl, [ :pointer, :BOOL, :pointer, :BOOL ], :BOOL - safe_attach_function :SetSecurityDescriptorGroup, [ :pointer, :pointer, :BOOL ], :BOOL - safe_attach_function :SetSecurityDescriptorOwner, [ :pointer, :pointer, :BOOL ], :BOOL - safe_attach_function :SetSecurityDescriptorSacl, [ :pointer, :BOOL, :pointer, :BOOL ], :BOOL - safe_attach_function :GetTokenInformation, [ :HANDLE, :TOKEN_INFORMATION_CLASS, :pointer, :DWORD, :PDWORD ], :BOOL - safe_attach_function :LogonUserW, [:LPTSTR, :LPTSTR, :LPTSTR, :DWORD, :DWORD, :PHANDLE], :BOOL + safe_attach_function :LsaOpenPolicy, %i{PLSA_UNICODE_STRING PLSA_OBJECT_ATTRIBUTES DWORD PLSA_HANDLE}, :NTSTATUS + safe_attach_function :MakeAbsoluteSD, %i{pointer pointer LPDWORD pointer LPDWORD pointer LPDWORD pointer LPDWORD pointer LPDWORD}, :BOOL + safe_attach_function :MapGenericMask, %i{PDWORD PGENERICMAPPING}, :void + safe_attach_function :OpenProcessToken, %i{HANDLE DWORD PHANDLE}, :BOOL + safe_attach_function :QuerySecurityAccessMask, %i{DWORD LPDWORD}, :void + safe_attach_function :SetFileSecurityW, %i{LPWSTR DWORD pointer}, :BOOL + safe_attach_function :SetNamedSecurityInfoW, %i{LPWSTR SE_OBJECT_TYPE DWORD pointer pointer pointer pointer}, :DWORD + safe_attach_function :SetSecurityAccessMask, %i{DWORD LPDWORD}, :void + safe_attach_function :SetSecurityDescriptorDacl, %i{pointer BOOL pointer BOOL}, :BOOL + safe_attach_function :SetSecurityDescriptorGroup, %i{pointer pointer BOOL}, :BOOL + safe_attach_function :SetSecurityDescriptorOwner, %i{pointer pointer BOOL}, :BOOL + safe_attach_function :SetSecurityDescriptorSacl, %i{pointer BOOL pointer BOOL}, :BOOL + safe_attach_function :GetTokenInformation, %i{HANDLE TOKEN_INFORMATION_CLASS pointer DWORD PDWORD}, :BOOL + safe_attach_function :LogonUserW, %i{LPTSTR LPTSTR LPTSTR DWORD DWORD PHANDLE}, :BOOL safe_attach_function :ImpersonateLoggedOnUser, [:HANDLE], :BOOL safe_attach_function :RevertToSelf, [], :BOOL diff --git a/lib/chef/win32/api/synchronization.rb b/lib/chef/win32/api/synchronization.rb index 19ca24bf00..aaedf2dd89 100644 --- a/lib/chef/win32/api/synchronization.rb +++ b/lib/chef/win32/api/synchronization.rb @@ -56,8 +56,8 @@ HANDLE WINAPI CreateMutex( _In_opt_ LPCTSTR lpName ); =end - safe_attach_function :CreateMutexW, [ :LPSECURITY_ATTRIBUTES, :BOOL, :LPCTSTR ], :HANDLE - safe_attach_function :CreateMutexA, [ :LPSECURITY_ATTRIBUTES, :BOOL, :LPCTSTR ], :HANDLE + safe_attach_function :CreateMutexW, %i{LPSECURITY_ATTRIBUTES BOOL LPCTSTR}, :HANDLE + safe_attach_function :CreateMutexA, %i{LPSECURITY_ATTRIBUTES BOOL LPCTSTR}, :HANDLE =begin DWORD WINAPI WaitForSingleObject( @@ -65,7 +65,7 @@ DWORD WINAPI WaitForSingleObject( _In_ DWORD dwMilliseconds ); =end - safe_attach_function :WaitForSingleObject, [ :HANDLE, :DWORD ], :DWORD + safe_attach_function :WaitForSingleObject, %i{HANDLE DWORD}, :DWORD =begin BOOL WINAPI ReleaseMutex( @@ -81,8 +81,8 @@ HANDLE WINAPI OpenMutex( _In_ LPCTSTR lpName ); =end - safe_attach_function :OpenMutexW, [ :DWORD, :BOOL, :LPCTSTR ], :HANDLE - safe_attach_function :OpenMutexA, [ :DWORD, :BOOL, :LPCTSTR ], :HANDLE + safe_attach_function :OpenMutexW, %i{DWORD BOOL LPCTSTR}, :HANDLE + safe_attach_function :OpenMutexA, %i{DWORD BOOL LPCTSTR}, :HANDLE end end end diff --git a/lib/chef/win32/api/system.rb b/lib/chef/win32/api/system.rb index ebe89f357f..48054c0b4f 100644 --- a/lib/chef/win32/api/system.rb +++ b/lib/chef/win32/api/system.rb @@ -177,7 +177,7 @@ BOOL WINAPI GetProductInfo( __out PDWORD pdwReturnedProductType ); =end - safe_attach_function :GetProductInfo, [:DWORD, :DWORD, :DWORD, :DWORD, :PDWORD], :BOOL + safe_attach_function :GetProductInfo, %i{DWORD DWORD DWORD DWORD PDWORD}, :BOOL =begin int WINAPI GetSystemMetrics( @@ -192,8 +192,8 @@ UINT WINAPI GetSystemWow64Directory( _In_ UINT uSize ); =end - safe_attach_function :GetSystemWow64DirectoryW, [:LPTSTR, :UINT], :UINT - safe_attach_function :GetSystemWow64DirectoryA, [:LPTSTR, :UINT], :UINT + safe_attach_function :GetSystemWow64DirectoryW, %i{LPTSTR UINT}, :UINT + safe_attach_function :GetSystemWow64DirectoryA, %i{LPTSTR UINT}, :UINT =begin BOOL WINAPI Wow64DisableWow64FsRedirection( @@ -220,8 +220,8 @@ LRESULT WINAPI SendMessageTimeout( _Out_opt_ PDWORD_PTR lpdwResult ); =end - safe_attach_function :SendMessageTimeoutW, [:HWND, :UINT, :WPARAM, :LPARAM, :UINT, :UINT, :PDWORD_PTR], :LRESULT - safe_attach_function :SendMessageTimeoutA, [:HWND, :UINT, :WPARAM, :LPARAM, :UINT, :UINT, :PDWORD_PTR], :LRESULT + safe_attach_function :SendMessageTimeoutW, %i{HWND UINT WPARAM LPARAM UINT UINT PDWORD_PTR}, :LRESULT + safe_attach_function :SendMessageTimeoutA, %i{HWND UINT WPARAM LPARAM UINT UINT PDWORD_PTR}, :LRESULT =begin DWORD WINAPI ExpandEnvironmentStrings( @@ -230,8 +230,8 @@ DWORD WINAPI ExpandEnvironmentStrings( _In_ DWORD nSize ); =end - safe_attach_function :ExpandEnvironmentStringsW, [:pointer, :pointer, :DWORD], :DWORD - safe_attach_function :ExpandEnvironmentStringsA, [:pointer, :pointer, :DWORD], :DWORD + safe_attach_function :ExpandEnvironmentStringsW, %i{pointer pointer DWORD}, :DWORD + safe_attach_function :ExpandEnvironmentStringsA, %i{pointer pointer DWORD}, :DWORD end end end diff --git a/lib/chef/win32/api/unicode.rb b/lib/chef/win32/api/unicode.rb index 05c098fc62..70aee58df6 100644 --- a/lib/chef/win32/api/unicode.rb +++ b/lib/chef/win32/api/unicode.rb @@ -101,7 +101,7 @@ BOOL IsTextUnicode( __inout LPINT lpiResult ); =end - safe_attach_function :IsTextUnicode, [:pointer, :int, :LPINT], :BOOL + safe_attach_function :IsTextUnicode, %i{pointer int LPINT}, :BOOL =begin int MultiByteToWideChar( @@ -113,7 +113,7 @@ int MultiByteToWideChar( __in int cchWideChar ); =end - safe_attach_function :MultiByteToWideChar, [:UINT, :DWORD, :LPCSTR, :int, :LPWSTR, :int], :int + safe_attach_function :MultiByteToWideChar, %i{UINT DWORD LPCSTR int LPWSTR int}, :int =begin int WideCharToMultiByte( @@ -127,7 +127,7 @@ int WideCharToMultiByte( __out LPBOOL lpUsedDefaultChar ); =end - safe_attach_function :WideCharToMultiByte, [:UINT, :DWORD, :LPCWSTR, :int, :LPSTR, :int, :LPCSTR, :LPBOOL], :int + safe_attach_function :WideCharToMultiByte, %i{UINT DWORD LPCWSTR int LPSTR int LPCSTR LPBOOL}, :int end end diff --git a/lib/chef/win32/eventlog.rb b/lib/chef/win32/eventlog.rb index e8c63bf13a..ca15acf3d8 100644 --- a/lib/chef/win32/eventlog.rb +++ b/lib/chef/win32/eventlog.rb @@ -17,9 +17,9 @@ # if Chef::Platform.windows? - if !defined? Chef::Win32EventLogLoaded + unless defined? Chef::Win32EventLogLoaded if defined? Windows::Constants - [:INFINITE, :WAIT_FAILED, :FORMAT_MESSAGE_IGNORE_INSERTS, :ERROR_INSUFFICIENT_BUFFER].each do |c| + %i{INFINITE WAIT_FAILED FORMAT_MESSAGE_IGNORE_INSERTS ERROR_INSUFFICIENT_BUFFER}.each do |c| # These are redefined in 'win32/eventlog' Windows::Constants.send(:remove_const, c) if Windows::Constants.const_defined? c end diff --git a/lib/chef/win32/file.rb b/lib/chef/win32/file.rb index 274879a32d..4fac3fe797 100644 --- a/lib/chef/win32/file.rb +++ b/lib/chef/win32/file.rb @@ -41,6 +41,7 @@ class Chef # def self.link(old_name, new_name) raise Errno::ENOENT, "(#{old_name}, #{new_name})" unless ::File.exist?(old_name) || ::File.symlink?(old_name) + # TODO do a check for CreateHardLinkW and # raise NotImplemented exception on older Windows old_name = encode_path(old_name) @@ -104,6 +105,7 @@ class Chef # def self.readlink(link_name) raise Errno::ENOENT, link_name unless ::File.exists?(link_name) || ::File.symlink?(link_name) + symlink_file_handle(link_name) do |handle| # Go to DeviceIoControl to get the symlink information # http://msdn.microsoft.com/en-us/library/windows/desktop/aa364571(v=vs.85).aspx @@ -180,7 +182,8 @@ class Chef Chef::ReservedNames::Win32::Security::STANDARD_RIGHTS_READ token = Chef::ReservedNames::Win32::Security.open_process_token( Chef::ReservedNames::Win32::Process.get_current_process, - token_rights) + token_rights + ) duplicate_token = token.duplicate_token(:SecurityImpersonation) mapping = Chef::ReservedNames::Win32::Security::GENERIC_MAPPING.new diff --git a/lib/chef/win32/file/info.rb b/lib/chef/win32/file/info.rb index 9d1b16fbea..234c04cdbb 100644 --- a/lib/chef/win32/file/info.rb +++ b/lib/chef/win32/file/info.rb @@ -34,6 +34,7 @@ class Chef # http://msdn.microsoft.com/en-us/library/windows/desktop/aa363788(v=vs.85).aspx def initialize(file_name) raise Errno::ENOENT, file_name unless ::File.exist?(file_name) + @file_info = retrieve_file_info(file_name) end diff --git a/lib/chef/win32/file/version_info.rb b/lib/chef/win32/file/version_info.rb index 609d72b96a..f74c98b86d 100644 --- a/lib/chef/win32/file/version_info.rb +++ b/lib/chef/win32/file/version_info.rb @@ -28,25 +28,26 @@ class Chef def initialize(file_name) raise Errno::ENOENT, file_name unless ::File.exist?(file_name) + @file_version_info = retrieve_file_version_info(file_name) end # defining method for each predefined version resource string # see https://msdn.microsoft.com/en-us/library/windows/desktop/ms647464(v=vs.85).aspx - [ - :Comments, - :CompanyName, - :FileDescription, - :FileVersion, - :InternalName, - :LegalCopyright, - :LegalTrademarks, - :OriginalFilename, - :ProductName, - :ProductVersion, - :PrivateBuild, - :SpecialBuild, - ].each do |method| + %i{ + Comments + CompanyName + FileDescription + FileVersion + InternalName + LegalCopyright + LegalTrademarks + OriginalFilename + ProductName + ProductVersion + PrivateBuild + SpecialBuild + }.each do |method| define_method method do begin get_version_info_string(method.to_s) diff --git a/lib/chef/win32/memory.rb b/lib/chef/win32/memory.rb index 853551f183..1ea6375e01 100644 --- a/lib/chef/win32/memory.rb +++ b/lib/chef/win32/memory.rb @@ -67,7 +67,7 @@ class Chef # Free memory allocated using local_alloc def self.local_free(pointer) result = LocalFree(pointer) - if !result.null? + unless result.null? Chef::ReservedNames::Win32::Error.raise! end end diff --git a/lib/chef/win32/net.rb b/lib/chef/win32/net.rb index b92b723e27..1c08f2fbeb 100644 --- a/lib/chef/win32/net.rb +++ b/lib/chef/win32/net.rb @@ -224,7 +224,8 @@ class Chef buf = FFI::MemoryPointer.new(LOCALGROUP_MEMBERS_INFO_3, members.size) Array.new(members.size) do |i| member_info = LOCALGROUP_MEMBERS_INFO_3.new( - buf + i * LOCALGROUP_MEMBERS_INFO_3.size) + buf + i * LOCALGROUP_MEMBERS_INFO_3.size + ) member_info[:lgrmi3_domainandname] = FFI::MemoryPointer.from_string(wstring(members[i])) member_info end @@ -236,7 +237,8 @@ class Chef lgrmi3s = members_to_lgrmi3(members) rc = NetLocalGroupAddMembers( - server_name, group_name, 3, lgrmi3s[0], members.size) + server_name, group_name, 3, lgrmi3s[0], members.size + ) if rc != NERR_Success Chef::ReservedNames::Win32::Error.raise!(nil, rc) @@ -249,7 +251,8 @@ class Chef lgrmi3s = members_to_lgrmi3(members) rc = NetLocalGroupSetMembers( - server_name, group_name, 3, lgrmi3s[0], members.size) + server_name, group_name, 3, lgrmi3s[0], members.size + ) if rc != NERR_Success Chef::ReservedNames::Win32::Error.raise!(nil, rc) @@ -262,7 +265,8 @@ class Chef lgrmi3s = members_to_lgrmi3(members) rc = NetLocalGroupDelMembers( - server_name, group_name, 3, lgrmi3s[0], members.size) + server_name, group_name, 3, lgrmi3s[0], members.size + ) if rc != NERR_Success Chef::ReservedNames::Win32::Error.raise!(nil, rc) diff --git a/lib/chef/win32/registry.rb b/lib/chef/win32/registry.rb index c0efa68464..90bc35143a 100644 --- a/lib/chef/win32/registry.rb +++ b/lib/chef/win32/registry.rb @@ -132,6 +132,7 @@ class Chef if has_subkeys?(key_path) && !recursive raise Chef::Exceptions::Win32RegNoRecursive, "Registry key #{key_path} has subkeys, and recursive not specified" end + hive, key_including_parent = get_hive_and_key(key_path) # key_including_parent: Software\\Root\\Branch\\Fruit # key => Fruit @@ -161,6 +162,7 @@ class Chef unless key_exists?(key_path) raise Chef::Exceptions::Win32RegKeyMissing, "Registry key #{key_path} does not exist" end + true end @@ -226,6 +228,7 @@ class Chef unless value_exists?(key_path, value) raise Chef::Exceptions::Win32RegValueMissing, "Registry key #{key_path} has no value named #{value[:name]}" end + true end @@ -233,6 +236,7 @@ class Chef unless data_exists?(key_path, value) raise Chef::Exceptions::Win32RegDataMissing, "Registry key #{key_path} has no value named #{value[:name]}, containing type #{value[:type]} and data #{value[:data]}" end + true end @@ -279,6 +283,7 @@ class Chef if val.is_a? String return val.downcase end + val end @@ -356,7 +361,7 @@ class Chef hive, key = get_hive_and_key(key_path) missing_key_arr.each do |intermediate_key| existing_key_path = existing_key_path << "\\" << intermediate_key - if !key_exists?(existing_key_path) + unless key_exists?(existing_key_path) Chef::Log.trace("Recursively creating registry key #{existing_key_path}") hive.create(get_key(existing_key_path), ::Win32::Registry::KEY_ALL_ACCESS | registry_system_architecture) end diff --git a/lib/chef/win32/security.rb b/lib/chef/win32/security.rb index 9a97fd77d2..5b78b652eb 100644 --- a/lib/chef/win32/security.rb +++ b/lib/chef/win32/security.rb @@ -200,6 +200,7 @@ class Chef result = LsaEnumerateAccountRights(policy_handle.read_pointer, sid, privilege_pointer, privilege_length) win32_error = LsaNtStatusToWinError(result) return [] if win32_error == 2 # FILE_NOT_FOUND - No rights assigned + test_and_raise_lsa_nt_status(result) privilege_length.read_ulong.times do |i| @@ -327,6 +328,7 @@ class Chef elsif FFI::LastError.error != ERROR_INSUFFICIENT_BUFFER Chef::ReservedNames::Win32::Error.raise! end + owner_result_storage = FFI::MemoryPointer.new owner_result_size.read_ulong unless GetTokenInformation(token.handle.handle, :TokenOwner, owner_result_storage, owner_result_size.read_ulong, owner_result_size) Chef::ReservedNames::Win32::Error.raise! @@ -342,6 +344,7 @@ class Chef elsif FFI::LastError.error != ERROR_INSUFFICIENT_BUFFER Chef::ReservedNames::Win32::Error.raise! end + group_result_storage = FFI::MemoryPointer.new group_result_size.read_ulong unless GetTokenInformation(token.handle.handle, :TokenPrimaryGroup, group_result_storage, group_result_size.read_ulong, group_result_size) Chef::ReservedNames::Win32::Error.raise! @@ -357,6 +360,7 @@ class Chef elsif FFI::LastError.error != ERROR_INSUFFICIENT_BUFFER Chef::ReservedNames::Win32::Error.raise! end + info_ptr = FFI::MemoryPointer.new(:pointer) token_info_pointer = TOKEN_ELEVATION_TYPE.new info_ptr token_info_length = 4 @@ -653,6 +657,7 @@ class Chef process_token = open_current_process_token(TOKEN_READ) rescue Exception => run_error return false if run_error.message =~ /Access is denied/ + Chef::ReservedNames::Win32::Error.raise! end diff --git a/lib/chef/win32/security/acl.rb b/lib/chef/win32/security/acl.rb index a2700b36ac..ec963fb522 100644 --- a/lib/chef/win32/security/acl.rb +++ b/lib/chef/win32/security/acl.rb @@ -45,6 +45,7 @@ class Chef def ==(other) return false if length != other.length + 0.upto(length - 1) do |i| return false if self[i] != other[i] end @@ -88,7 +89,7 @@ class Chef end def to_s - "[#{collect { |ace| ace.to_s }.join(", ")}]" + "[#{collect(&:to_s).join(", ")}]" end def self.align_dword(size) diff --git a/lib/chef/win32/security/security_descriptor.rb b/lib/chef/win32/security/security_descriptor.rb index 83f5c466aa..3d109e60bb 100644 --- a/lib/chef/win32/security/security_descriptor.rb +++ b/lib/chef/win32/security/security_descriptor.rb @@ -41,7 +41,8 @@ class Chef end def dacl - raise "DACL not present" if !dacl_present? + raise "DACL not present" unless dacl_present? + present, acl, defaulted = Chef::ReservedNames::Win32::Security.get_security_descriptor_dacl(self) acl end @@ -65,7 +66,8 @@ class Chef end def sacl - raise "SACL not present" if !sacl_present? + raise "SACL not present" unless sacl_present? + Security.with_privileges("SeSecurityPrivilege") do present, acl, defaulted = Chef::ReservedNames::Win32::Security.get_security_descriptor_sacl(self) acl diff --git a/lib/chef/win32/security/sid.rb b/lib/chef/win32/security/sid.rb index 4d34f8b8a7..9643a80c67 100644 --- a/lib/chef/win32/security/sid.rb +++ b/lib/chef/win32/security/sid.rb @@ -231,33 +231,33 @@ class Chef end def self.None - SID.from_account("#{::ENV['COMPUTERNAME']}\\None") + SID.from_account("#{::ENV["COMPUTERNAME"]}\\None") end def self.Administrator - SID.from_account("#{::ENV['COMPUTERNAME']}\\#{SID.admin_account_name}") + SID.from_account("#{::ENV["COMPUTERNAME"]}\\#{SID.admin_account_name}") end def self.Guest - SID.from_account("#{::ENV['COMPUTERNAME']}\\Guest") + SID.from_account("#{::ENV["COMPUTERNAME"]}\\Guest") end def self.current_user - SID.from_account("#{::ENV['USERDOMAIN']}\\#{::ENV['USERNAME']}") + SID.from_account("#{::ENV["USERDOMAIN"]}\\#{::ENV["USERNAME"]}") end SERVICE_ACCOUNT_USERS = [self.LocalSystem, self.NtLocal, self.NtNetwork].flat_map do |user_type| - [user_type.account_simple_name.upcase, - user_type.account_name.upcase] - end.freeze + [user_type.account_simple_name.upcase, + user_type.account_name.upcase] + end.freeze BUILT_IN_GROUPS = [self.BuiltinAdministrators, self.BuiltinUsers, self.Guests].flat_map do |user_type| - [user_type.account_simple_name.upcase, - user_type.account_name.upcase] - end.freeze + [user_type.account_simple_name.upcase, + user_type.account_name.upcase] + end.freeze SYSTEM_USER = SERVICE_ACCOUNT_USERS + BUILT_IN_GROUPS @@ -338,6 +338,7 @@ class Chef end raise "Can not determine the administrator account name." if admin_account_name.nil? + admin_account_name end end diff --git a/lib/chef/win32/security/token.rb b/lib/chef/win32/security/token.rb index dfd1e31241..78c79fbb44 100644 --- a/lib/chef/win32/security/token.rb +++ b/lib/chef/win32/security/token.rb @@ -35,7 +35,8 @@ class Chef def enable_privileges(*privilege_names) # Build the list of privileges we want to set new_privileges = Chef::ReservedNames::Win32::API::Security::TOKEN_PRIVILEGES.new( - FFI::MemoryPointer.new(Chef::ReservedNames::Win32::API::Security::TOKEN_PRIVILEGES.size_with_privileges(privilege_names.length))) + FFI::MemoryPointer.new(Chef::ReservedNames::Win32::API::Security::TOKEN_PRIVILEGES.size_with_privileges(privilege_names.length)) + ) new_privileges[:PrivilegeCount] = 0 privilege_names.each do |privilege_name| luid = Chef::ReservedNames::Win32::API::Security::LUID.new @@ -64,6 +65,7 @@ class Chef unless Chef::ReservedNames::Win32::API::Security.DuplicateToken(handle.handle, security_impersonation_level, duplicate_token_handle) raise Chef::ReservedNames::Win32::Error.raise! end + Token.new(Handle.new(duplicate_token_handle.read_ulong)) end end diff --git a/lib/chef/win32/version.rb b/lib/chef/win32/version.rb index 93e09d3c83..d3ebf46871 100644 --- a/lib/chef/win32/version.rb +++ b/lib/chef/win32/version.rb @@ -43,7 +43,7 @@ class Chef private_class_method :get_system_metrics def self.method_name_from_marketing_name(marketing_name) - "#{marketing_name.gsub(/\s/, '_').tr('.', '_').downcase}?" + "#{marketing_name.gsub(/\s/, "_").tr(".", "_").downcase}?" end private_class_method :method_name_from_marketing_name @@ -80,7 +80,7 @@ class Chef @sku = get_product_info(@major_version, @minor_version, @sp_major_version, @sp_minor_version) end - marketing_names = Array.new + marketing_names = [] # General Windows checks WIN_VERSIONS.each do |k, v| @@ -128,7 +128,7 @@ class Chef # The operating system version is a string in the following form # that can be split into components based on the '.' delimiter: # MajorVersionNumber.MinorVersionNumber.BuildNumber - os_version.split(".").collect { |version_string| version_string.to_i } + os_version.split(".").collect(&:to_i) end def get_version_ex |