diff options
author | Tim Smith <tsmith@chef.io> | 2019-12-29 18:06:37 -0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-12-29 18:06:37 -0800 |
commit | c8bf6efa66ff005ab87ff81c9a857ea0c6c1090e (patch) | |
tree | 3a25409c03ff3ac83f94e6e740145353d3e2c095 /lib | |
parent | 435755ee68c14fd6d6f858e451e7afeee1610e6f (diff) | |
parent | ecad8fee4a946b337e60a4274de2b2c872c9e81b (diff) | |
download | chef-zero-c8bf6efa66ff005ab87ff81c9a857ea0c6c1090e.tar.gz |
Merge pull request #298 from chef/chefstyle
Apply Chefstyle
Diffstat (limited to 'lib')
39 files changed, 128 insertions, 79 deletions
diff --git a/lib/chef_zero/chef_data/cookbook_data.rb b/lib/chef_zero/chef_data/cookbook_data.rb index e4ec9b3..747877a 100644 --- a/lib/chef_zero/chef_data/cookbook_data.rb +++ b/lib/chef_zero/chef_data/cookbook_data.rb @@ -107,7 +107,7 @@ module ChefZero if directory.is_a?(Hash) directory.keys else - directory.children.map { |c| c.name } + directory.children.map(&:name) end end diff --git a/lib/chef_zero/chef_data/data_normalizer.rb b/lib/chef_zero/chef_data/data_normalizer.rb index b69fcaf..b5286dc 100644 --- a/lib/chef_zero/chef_data/data_normalizer.rb +++ b/lib/chef_zero/chef_data/data_normalizer.rb @@ -53,7 +53,7 @@ module ChefZero user["admin"] ||= false user["admin"] = !!user["admin"] user["openid"] ||= nil - if !osc_compat + unless osc_compat if method == "GET" user.delete("admin") user.delete("password") @@ -69,7 +69,7 @@ module ChefZero def self.normalize_data_bag_item(data_bag_item, data_bag_name, id, method) if method == "DELETE" # TODO SERIOUSLY, WHO DOES THIS MANY EXCEPTIONS IN THEIR INTERFACE - if !(data_bag_item["json_class"] == "Chef::DataBagItem" && data_bag_item["raw_data"]) + unless data_bag_item["json_class"] == "Chef::DataBagItem" && data_bag_item["raw_data"] data_bag_item["id"] ||= id data_bag_item = { "raw_data" => data_bag_item } data_bag_item["chef_type"] ||= "data_bag_item" @@ -93,14 +93,15 @@ module ChefZero end def self.normalize_cookbook(endpoint, org_prefix, cookbook, name, version, base_uri, method, - is_cookbook_artifact = false, api_version: 2) + is_cookbook_artifact = false, api_version: 2) # TODO I feel dirty if method == "PUT" && api_version < 2 cookbook["all_files"] = cookbook.delete(["root_files"]) { [] } COOKBOOK_SEGMENTS.each do |segment| next unless cookbook.key? segment + cookbook[segment].each do |file| - file["name"] = "#{segment}/#{file['name']}" + file["name"] = "#{segment}/#{file["name"]}" cookbook["all_files"] << file end cookbook.delete(segment) @@ -131,6 +132,7 @@ module ChefZero file.delete("full_path") next unless COOKBOOK_SEGMENTS.include? segment + file["name"] = name cookbook[segment] << file end diff --git a/lib/chef_zero/chef_data/default_creator.rb b/lib/chef_zero/chef_data/default_creator.rb index 5f6cf8b..90c8200 100644 --- a/lib/chef_zero/chef_data/default_creator.rb +++ b/lib/chef_zero/chef_data/default_creator.rb @@ -140,6 +140,7 @@ module ChefZero def exists?(path) return true if path.size == 0 + parent_list = list(path[0..-2]) parent_list && parent_list.include?(path[-1]) end @@ -184,7 +185,8 @@ module ChefZero value = DEFAULT_ORG_SPINE 2.upto(path.size - 1) do |index| value = nil if @deleted[path[0..index]] - break if !value + break unless value + value = value[path[index]] end @@ -272,7 +274,8 @@ module ChefZero object_path = AclPath.get_object_path(path) # The actual things containers correspond to don't have to exist, as # long as the container does - return nil if !data_exists?(object_path) + return nil unless data_exists?(object_path) + basic_acl = case path[3..-1].join("/") when "root", "containers/containers", "containers/groups" @@ -350,7 +353,7 @@ module ChefZero if path.size == 4 && path[0] == "organizations" && path[2] == "clients" begin client = FFI_Yajl::Parser.parse(data.get(path)) - if !client["validator"] + unless client["validator"] unknown_owners |= [ path[3] ] end rescue @@ -453,7 +456,7 @@ module ChefZero def is_dir?(path) case path.size when 0, 1 - return true + true when 2 path[0] == "organizations" || (path[0] == "acls" && path[1] != "root") when 3 diff --git a/lib/chef_zero/data_store/data_error.rb b/lib/chef_zero/data_store/data_error.rb index b392e58..c528a4a 100644 --- a/lib/chef_zero/data_store/data_error.rb +++ b/lib/chef_zero/data_store/data_error.rb @@ -24,7 +24,7 @@ module ChefZero def initialize(path, cause = nil) @path = path @cause = cause - path_for_msg = path.nil? ? "nil" : "/#{path.join('/')}" + path_for_msg = path.nil? ? "nil" : "/#{path.join("/")}" super "Data path: #{path_for_msg}" end end diff --git a/lib/chef_zero/data_store/default_facade.rb b/lib/chef_zero/data_store/default_facade.rb index 6c94dff..2b93b78 100644 --- a/lib/chef_zero/data_store/default_facade.rb +++ b/lib/chef_zero/data_store/default_facade.rb @@ -100,7 +100,7 @@ module ChefZero begin real_store.delete(path) rescue DataNotFoundError - if !deleted + unless deleted raise end end @@ -111,7 +111,7 @@ module ChefZero begin real_store.delete_dir(path, *options) rescue DataNotFoundError - if !deleted + unless deleted raise end end diff --git a/lib/chef_zero/data_store/memory_store_v2.rb b/lib/chef_zero/data_store/memory_store_v2.rb index 8e041b5..809d221 100644 --- a/lib/chef_zero/data_store/memory_store_v2.rb +++ b/lib/chef_zero/data_store/memory_store_v2.rb @@ -37,7 +37,7 @@ module ChefZero parent = _get(path, options.include?(:recursive)) if parent.key?(name) - if !options.include?(:recursive) + unless options.include?(:recursive) raise DataAlreadyExistsError.new(path + [name]) end else @@ -46,7 +46,7 @@ module ChefZero end def create(path, name, data, *options) - if !data.is_a?(String) + unless data.is_a?(String) raise "set only works with strings (given data: #{data.inspect})" end @@ -55,19 +55,21 @@ module ChefZero if parent.key?(name) raise DataAlreadyExistsError.new(path + [name]) end + parent[name] = data end def get(path, request = nil) value = _get(path) if value.is_a?(Hash) - raise "get() called on directory #{path.join('/')}" + raise "get() called on directory #{path.join("/")}" end + value end def set(path, data, *options) - if !data.is_a?(String) + unless data.is_a?(String) raise "set only works with strings: #{path} = #{data.inspect}" end @@ -77,36 +79,40 @@ module ChefZero if !options.include?(:create) && !parent[path[-1]] raise DataNotFoundError.new(path) end + parent[path[-1]] = data end def delete(path) parent = _get(path[0, path.length - 1]) - if !parent.key?(path[-1]) + unless parent.key?(path[-1]) raise DataNotFoundError.new(path) end - if !parent[path[-1]].is_a?(String) + unless parent[path[-1]].is_a?(String) raise "delete only works with strings: #{path}" end + parent.delete(path[-1]) end def delete_dir(path, *options) parent = _get(path[0, path.length - 1]) - if !parent.key?(path[-1]) + unless parent.key?(path[-1]) raise DataNotFoundError.new(path) end - if !parent[path[-1]].is_a?(Hash) + unless parent[path[-1]].is_a?(Hash) raise "delete_dir only works with directories: #{path}" end + parent.delete(path[-1]) end def list(path) dir = _get(path) - if !dir.is_a? Hash + unless dir.is_a? Hash raise "list only works with directories (#{path} = #{dir.class})" end + dir.keys.sort end @@ -115,6 +121,7 @@ module ChefZero if value.is_a?(Hash) && !options[:allow_dirs] raise "exists? does not work with directories (#{path} = #{value.class})" end + true rescue DataNotFoundError false @@ -122,9 +129,10 @@ module ChefZero def exists_dir?(path) dir = _get(path) - if !dir.is_a? Hash + unless dir.is_a? Hash raise "exists_dir? only works with directories (#{path} = #{dir.class})" end + true rescue DataNotFoundError false @@ -135,7 +143,7 @@ module ChefZero def _get(path, create_dir = false) value = @data path.each_with_index do |path_part, index| - if !value.key?(path_part) + unless value.key?(path_part) if create_dir value[path_part] = {} else diff --git a/lib/chef_zero/data_store/raw_file_store.rb b/lib/chef_zero/data_store/raw_file_store.rb index 31bf08a..d643f03 100644 --- a/lib/chef_zero/data_store/raw_file_store.rb +++ b/lib/chef_zero/data_store/raw_file_store.rb @@ -44,6 +44,7 @@ module ChefZero if destructible Dir.entries(root).each do |entry| next if entry == "." || entry == ".." + FileUtils.rm_rf(Path.join(root, entry)) end end @@ -110,9 +111,10 @@ module ChefZero def delete_dir(path, *options) if options.include?(:recursive) - if !File.exist?(path_to(path)) + unless File.exist?(path_to(path)) raise DataNotFoundError.new(path) end + FileUtils.rm_rf(path_to(path)) else begin diff --git a/lib/chef_zero/data_store/v1_to_v2_adapter.rb b/lib/chef_zero/data_store/v1_to_v2_adapter.rb index 874c05a..1840656 100644 --- a/lib/chef_zero/data_store/v1_to_v2_adapter.rb +++ b/lib/chef_zero/data_store/v1_to_v2_adapter.rb @@ -21,6 +21,7 @@ module ChefZero raise DataNotFoundError.new(path) if skip_organizations?(path) raise "Cannot create #{name} at #{path} with V1ToV2Adapter: only handles a single org named #{single_org}." if skip_organizations?(path, name) raise DataAlreadyExistsError.new(path + [ name ]) if path.size < 2 + fix_exceptions do real_store.create_dir(path[2..-1], name, *options) end @@ -30,6 +31,7 @@ module ChefZero raise DataNotFoundError.new(path) if skip_organizations?(path) raise "Cannot create #{name} at #{path} with V1ToV2Adapter: only handles a single org named #{single_org}." if skip_organizations?(path, name) raise DataAlreadyExistsError.new(path + [ name ]) if path.size < 2 + fix_exceptions do real_store.create(path[2..-1], name, data, *options) end @@ -37,6 +39,7 @@ module ChefZero def get(path, request = nil) raise DataNotFoundError.new(path) if skip_organizations?(path) + fix_exceptions do # Make it so build_uri will include /organizations/ORG inside the V1 data store if request && request.rest_base_prefix.size == 0 @@ -53,6 +56,7 @@ module ChefZero def set(path, data, *options) raise DataNotFoundError.new(path) if skip_organizations?(path) + fix_exceptions do real_store.set(path[2..-1], data, *options) end @@ -60,6 +64,7 @@ module ChefZero def delete(path, *options) raise DataNotFoundError.new(path) if skip_organizations?(path) && !options.include?(:recursive) + fix_exceptions do real_store.delete(path[2..-1]) end @@ -67,6 +72,7 @@ module ChefZero def delete_dir(path, *options) raise DataNotFoundError.new(path) if skip_organizations?(path) && !options.include?(:recursive) + fix_exceptions do real_store.delete_dir(path[2..-1], *options) end @@ -74,6 +80,7 @@ module ChefZero def list(path) raise DataNotFoundError.new(path) if skip_organizations?(path) + if path == [] [ "organizations" ] elsif path == [ "organizations" ] @@ -87,6 +94,7 @@ module ChefZero def exists?(path) return false if skip_organizations?(path) + fix_exceptions do real_store.exists?(path[2..-1]) end @@ -94,12 +102,14 @@ module ChefZero def exists_dir?(path) return false if skip_organizations?(path) + if path == [] true elsif path == [ "organizations" ] || path == [ "users" ] true else return false if skip_organizations?(path) + fix_exceptions do real_store.exists_dir?(path[2..-1]) end diff --git a/lib/chef_zero/endpoints/acl_endpoint.rb b/lib/chef_zero/endpoints/acl_endpoint.rb index e389f2d..d5010f9 100644 --- a/lib/chef_zero/endpoints/acl_endpoint.rb +++ b/lib/chef_zero/endpoints/acl_endpoint.rb @@ -23,6 +23,7 @@ module ChefZero if !acl_path || !%w{read create update delete grant}.include?(perm) raise RestErrorResponse.new(404, "Object not found: #{build_uri(request.base_uri, request.rest_path)}") end + [acl_path, perm] end diff --git a/lib/chef_zero/endpoints/acls_endpoint.rb b/lib/chef_zero/endpoints/acls_endpoint.rb index 64840cd..48759c2 100644 --- a/lib/chef_zero/endpoints/acls_endpoint.rb +++ b/lib/chef_zero/endpoints/acls_endpoint.rb @@ -17,9 +17,10 @@ module ChefZero path = request.rest_path[0..-2] # Strip off _acl path = path[0..1] if path.size == 3 && path[0] == "organizations" && %w{organization organizations}.include?(path[2]) acl_path = ChefData::AclPath.get_acl_data_path(path) - if !acl_path + unless acl_path raise RestErrorResponse.new(404, "Object not found: #{build_uri(request.base_uri, request.rest_path)}") end + acls = FFI_Yajl::Parser.parse(get_data(request, acl_path)) acls = ChefData::DataNormalizer.normalize_acls(acls) if request.query_params["detail"] == "granular" diff --git a/lib/chef_zero/endpoints/actor_default_key_endpoint.rb b/lib/chef_zero/endpoints/actor_default_key_endpoint.rb index 1985dea..a13204b 100644 --- a/lib/chef_zero/endpoints/actor_default_key_endpoint.rb +++ b/lib/chef_zero/endpoints/actor_default_key_endpoint.rb @@ -53,6 +53,7 @@ module ChefZero def actor_path(request) return request.rest_path[0..3] if request.rest_path[2] == "clients" + request.rest_path[0..1] end diff --git a/lib/chef_zero/endpoints/actor_endpoint.rb b/lib/chef_zero/endpoints/actor_endpoint.rb index 4cba31a..8c79f9a 100644 --- a/lib/chef_zero/endpoints/actor_endpoint.rb +++ b/lib/chef_zero/endpoints/actor_endpoint.rb @@ -125,7 +125,7 @@ module ChefZero def rename_keys!(request, new_client_or_user_name) orig_keys_path = keys_path_base(request) new_keys_path = orig_keys_path.dup - .tap { |path| path[-2] = new_client_or_user_name } + .tap { |path| path[-2] = new_client_or_user_name } key_names = list_data_or_else(request, orig_keys_path, nil) return unless key_names # No keys to move diff --git a/lib/chef_zero/endpoints/actor_keys_endpoint.rb b/lib/chef_zero/endpoints/actor_keys_endpoint.rb index b3bab9a..89528b2 100644 --- a/lib/chef_zero/endpoints/actor_keys_endpoint.rb +++ b/lib/chef_zero/endpoints/actor_keys_endpoint.rb @@ -50,7 +50,7 @@ module ChefZero response_body["private_key"] = private_key if generate_keys json_response(201, response_body, - headers: { "Location" => response_body["uri"] }) + headers: { "Location" => response_body["uri"] }) end private @@ -117,6 +117,7 @@ module ChefZero def actor_path(request) return request.rest_path[0..3] if client?(request) + request.rest_path[0..1] end diff --git a/lib/chef_zero/endpoints/authenticate_user_endpoint.rb b/lib/chef_zero/endpoints/authenticate_user_endpoint.rb index e54b8f1..44ed24e 100644 --- a/lib/chef_zero/endpoints/authenticate_user_endpoint.rb +++ b/lib/chef_zero/endpoints/authenticate_user_endpoint.rb @@ -19,6 +19,7 @@ module ChefZero if user["password"] != password raise RestErrorResponse.new(401, "Bad username or password") end + # Include only particular user data in the response user.keep_if { |key, value| %w{first_name last_name display_name email username}.include?(key) } json_response(200, { diff --git a/lib/chef_zero/endpoints/containers_endpoint.rb b/lib/chef_zero/endpoints/containers_endpoint.rb index e8708ed..2260765 100644 --- a/lib/chef_zero/endpoints/containers_endpoint.rb +++ b/lib/chef_zero/endpoints/containers_endpoint.rb @@ -15,7 +15,7 @@ module ChefZero data = parse_json(request.body) # if they don't match, id wins. container_name = data["id"] || data["containername"] - container_path_suffix = data["containerpath"].split("/").reject { |o| o.empty? } + container_path_suffix = data["containerpath"].split("/").reject(&:empty?) create_data(request, request.rest_path, container_name, to_json({}), :create_dir) json_response(201, { uri: build_uri(request.base_uri, request.rest_path + container_path_suffix + [container_name]) }) diff --git a/lib/chef_zero/endpoints/cookbook_artifact_identifier_endpoint.rb b/lib/chef_zero/endpoints/cookbook_artifact_identifier_endpoint.rb index 9f7b973..1c2d6a7 100644 --- a/lib/chef_zero/endpoints/cookbook_artifact_identifier_endpoint.rb +++ b/lib/chef_zero/endpoints/cookbook_artifact_identifier_endpoint.rb @@ -60,8 +60,8 @@ module ChefZero def normalize(request, cookbook_artifact_data) cookbook = parse_json(cookbook_artifact_data) ChefData::DataNormalizer.normalize_cookbook(self, request.rest_path[0..1], - cookbook, request.rest_path[3], request.rest_path[4], - request.base_uri, request.method, true, api_version: request.api_version) + cookbook, request.rest_path[3], request.rest_path[4], + request.base_uri, request.method, true, api_version: request.api_version) end end end diff --git a/lib/chef_zero/endpoints/cookbook_version_endpoint.rb b/lib/chef_zero/endpoints/cookbook_version_endpoint.rb index 0ee5be7..5ec1aa4 100644 --- a/lib/chef_zero/endpoints/cookbook_version_endpoint.rb +++ b/lib/chef_zero/endpoints/cookbook_version_endpoint.rb @@ -27,9 +27,10 @@ module ChefZero if request.query_params["force"] != "true" raise RestErrorResponse.new(409, "The cookbook #{name} at version #{version} is frozen. Use the 'force' option to override.") end + # For some reason, you are forever unable to modify "frozen?" on a frozen cookbook. request_body = FFI_Yajl::Parser.parse(request.body) - if !request_body["frozen?"] + unless request_body["frozen?"] request_body["frozen?"] = true request.body = FFI_Yajl::Encoder.encode(request_body, pretty: true) end @@ -92,6 +93,7 @@ module ChefZero rescue ChefZero::DataStore::DataNotFoundError # Not all chef versions support cookbook_artifacts raise unless cookbook_type == "cookbook_artifacts" + cookbooks = [] end cookbooks.each do |cookbook_name| diff --git a/lib/chef_zero/endpoints/cookbooks_base.rb b/lib/chef_zero/endpoints/cookbooks_base.rb index e515992..331f504 100644 --- a/lib/chef_zero/endpoints/cookbooks_base.rb +++ b/lib/chef_zero/endpoints/cookbooks_base.rb @@ -54,6 +54,7 @@ module ChefZero versions = [] cookbooks_list[name].sort_by { |version| Gem::Version.new(version.dup) }.reverse_each do |version| break if num_versions && versions.size >= num_versions + if constraint.satisfied_by?(Gem::Version.new(version.dup)) versions << version end @@ -66,6 +67,7 @@ module ChefZero cookbook["all_files"].inject([]) do |acc, file| part, name = file["name"].split("/") next acc unless part == "recipes" || File.extname(name) != ".rb" + if name == "default.rb" acc << cookbook_name else diff --git a/lib/chef_zero/endpoints/data_bags_endpoint.rb b/lib/chef_zero/endpoints/data_bags_endpoint.rb index 5b9dd14..f90b7d7 100644 --- a/lib/chef_zero/endpoints/data_bags_endpoint.rb +++ b/lib/chef_zero/endpoints/data_bags_endpoint.rb @@ -10,7 +10,7 @@ module ChefZero json = FFI_Yajl::Parser.parse(contents) name = identity_keys.map { |k| json[k] }.select { |v| v }.first if name.nil? - error(400, "Must specify #{identity_keys.map { |k| k.inspect }.join(' or ')} in JSON") + error(400, "Must specify #{identity_keys.map(&:inspect).join(" or ")} in JSON") elsif exists_data_dir?(request, request.rest_path[0..1] + ["data", name]) error(409, "Object already exists") else diff --git a/lib/chef_zero/endpoints/environment_cookbook_versions_endpoint.rb b/lib/chef_zero/endpoints/environment_cookbook_versions_endpoint.rb index 43ef4ce..8023d69 100644 --- a/lib/chef_zero/endpoints/environment_cookbook_versions_endpoint.rb +++ b/lib/chef_zero/endpoints/environment_cookbook_versions_endpoint.rb @@ -15,12 +15,14 @@ module ChefZero run_list = FFI_Yajl::Parser.parse(request.body)["run_list"] run_list.each do |run_list_entry| if run_list_entry =~ /(.+)::.+\@(.+)/ || run_list_entry =~ /(.+)\@(.+)/ - raise RestErrorResponse.new(412, "No such cookbook: #{$1}") if !cookbook_names.include?($1) - raise RestErrorResponse.new(412, "No such cookbook version for cookbook #{$1}: #{$2}") if !list_data(request, request.rest_path[0..1] + ["cookbooks", $1]).include?($2) + raise RestErrorResponse.new(412, "No such cookbook: #{$1}") unless cookbook_names.include?($1) + raise RestErrorResponse.new(412, "No such cookbook version for cookbook #{$1}: #{$2}") unless list_data(request, request.rest_path[0..1] + ["cookbooks", $1]).include?($2) + desired_versions[$1] = [ $2 ] else desired_cookbook = run_list_entry.split("::")[0] - raise RestErrorResponse.new(412, "No such cookbook: #{desired_cookbook}") if !cookbook_names.include?(desired_cookbook) + raise RestErrorResponse.new(412, "No such cookbook: #{desired_cookbook}") unless cookbook_names.include?(desired_cookbook) + desired_versions[desired_cookbook] = list_data(request, request.rest_path[0..1] + ["cookbooks", desired_cookbook]) end end @@ -35,7 +37,7 @@ module ChefZero # Depsolve! solved = depsolve(request, desired_versions.keys, desired_versions, environment_constraints) - if !solved + unless solved if @last_missing_dep && !cookbook_names.include?(@last_missing_dep) return raise RestErrorResponse.new(412, "No such cookbook: #{@last_missing_dep}") elsif @last_constraint_failure @@ -64,7 +66,7 @@ module ChefZero # If everything is already solve_for = unsolved[0] - return desired_versions if !solve_for + return desired_versions unless solve_for # Go through each desired version of this cookbook, starting with the latest, # until we find one we can solve successfully with @@ -81,10 +83,10 @@ module ChefZero cookbook_dependencies.each_pair do |dep_name, dep_constraint| # If the dep is not already in the list, add it to the list to solve # and bring in all environment-allowed cookbook versions to desired_versions - if !new_desired_versions.key?(dep_name) + unless new_desired_versions.key?(dep_name) new_unsolved += [dep_name] # If the dep is missing, we will try other versions of the cookbook that might not have the bad dep. - if !exists_data_dir?(request, request.rest_path[0..1] + ["cookbooks", dep_name]) + unless exists_data_dir?(request, request.rest_path[0..1] + ["cookbooks", dep_name]) @last_missing_dep = dep_name.to_s dep_not_found = true break @@ -110,7 +112,8 @@ module ChefZero end def filter_by_constraint(versions, cookbook_name, constraint) - return versions if !constraint + return versions unless constraint + constraint = Gem::Requirement.new(constraint) new_versions = versions[cookbook_name] new_versions = new_versions.select { |version| constraint.satisfied_by?(Gem::Version.new(version.dup)) } diff --git a/lib/chef_zero/endpoints/not_found_endpoint.rb b/lib/chef_zero/endpoints/not_found_endpoint.rb index 1c18f8b..160d4a2 100644 --- a/lib/chef_zero/endpoints/not_found_endpoint.rb +++ b/lib/chef_zero/endpoints/not_found_endpoint.rb @@ -4,7 +4,7 @@ module ChefZero module Endpoints class NotFoundEndpoint def call(request) - [404, { "Content-Type" => "application/json" }, FFI_Yajl::Encoder.encode({ "error" => ["Object not found: #{request.env['REQUEST_PATH']}"] }, pretty: true)] + [404, { "Content-Type" => "application/json" }, FFI_Yajl::Encoder.encode({ "error" => ["Object not found: #{request.env["REQUEST_PATH"]}"] }, pretty: true)] end end end diff --git a/lib/chef_zero/endpoints/organization_association_request_endpoint.rb b/lib/chef_zero/endpoints/organization_association_request_endpoint.rb index c73d816..65caf56 100644 --- a/lib/chef_zero/endpoints/organization_association_request_endpoint.rb +++ b/lib/chef_zero/endpoints/organization_association_request_endpoint.rb @@ -11,6 +11,7 @@ module ChefZero if id !~ /(.+)-#{orgname}$/ raise HttpErrorResponse.new(404, "Invalid ID #{id}. Must be of the form username-#{orgname}") end + username = $1 path = request.rest_path[0..-2] + [username] delete_data(request, path) diff --git a/lib/chef_zero/endpoints/organization_endpoint.rb b/lib/chef_zero/endpoints/organization_endpoint.rb index 3c14548..d71d9ad 100644 --- a/lib/chef_zero/endpoints/organization_endpoint.rb +++ b/lib/chef_zero/endpoints/organization_endpoint.rb @@ -19,8 +19,9 @@ module ChefZero save_org = FFI_Yajl::Encoder.encode(org, pretty: true) if new_org["name"] != request.rest_path[-1] # This is a rename - return error(400, "Cannot rename org #{request.rest_path[-1]} to #{new_org['name']}: rename not supported for orgs") + return error(400, "Cannot rename org #{request.rest_path[-1]} to #{new_org["name"]}: rename not supported for orgs") end + set_data(request, request.rest_path + [ "org" ], save_org) json_response(200, { "uri" => (build_uri(request.base_uri, request.rest_path)).to_s, diff --git a/lib/chef_zero/endpoints/policy_group_policy_endpoint.rb b/lib/chef_zero/endpoints/policy_group_policy_endpoint.rb index a34da32..b69cfe3 100644 --- a/lib/chef_zero/endpoints/policy_group_policy_endpoint.rb +++ b/lib/chef_zero/endpoints/policy_group_policy_endpoint.rb @@ -48,7 +48,7 @@ module ChefZero # If the policy revision being submitted does not exist, create it. # Storage: /organizations/ORG/policies/POLICY/revisions/REVISION policyfile_path = request.rest_path[0..1] + ["policies", policy_name, "revisions", revision_id] - if !exists_data?(request, policyfile_path) + unless exists_data?(request, policyfile_path) create_data(request, policyfile_path[0..-2], revision_id, request.body, :create_dir) end diff --git a/lib/chef_zero/endpoints/rest_list_endpoint.rb b/lib/chef_zero/endpoints/rest_list_endpoint.rb index 135f0e9..28af8d4 100644 --- a/lib/chef_zero/endpoints/rest_list_endpoint.rb +++ b/lib/chef_zero/endpoints/rest_list_endpoint.rb @@ -26,7 +26,7 @@ module ChefZero contents = request.body key = get_key(contents) if key.nil? - error(400, "Must specify #{identity_keys.map { |k| k.inspect }.join(' or ')} in JSON") + error(400, "Must specify #{identity_keys.map(&:inspect).join(" or ")} in JSON") else create_data(request, request.rest_path, key, contents) json_response(201, { "uri" => (build_uri(request.base_uri, request.rest_path + [key])).to_s }) diff --git a/lib/chef_zero/endpoints/rest_object_endpoint.rb b/lib/chef_zero/endpoints/rest_object_endpoint.rb index 5d6ae40..4fc2ef1 100644 --- a/lib/chef_zero/endpoints/rest_object_endpoint.rb +++ b/lib/chef_zero/endpoints/rest_object_endpoint.rb @@ -70,6 +70,7 @@ module ChefZero # Does this request change the value of the identity key? def is_rename?(request) return false unless (key = identity_key_value(request)) + key != request.rest_path[-1] end end diff --git a/lib/chef_zero/endpoints/sandbox_endpoint.rb b/lib/chef_zero/endpoints/sandbox_endpoint.rb index d7eb4de..aedb665 100644 --- a/lib/chef_zero/endpoints/sandbox_endpoint.rb +++ b/lib/chef_zero/endpoints/sandbox_endpoint.rb @@ -9,7 +9,7 @@ module ChefZero def put(request) existing_sandbox = FFI_Yajl::Parser.parse(get_data(request)) existing_sandbox["checksums"].each do |checksum| - if !exists_data?(request, request.rest_path[0..1] + ["file_store", "checksums", checksum]) + unless exists_data?(request, request.rest_path[0..1] + ["file_store", "checksums", checksum]) raise RestErrorResponse.new(503, "Checksum not uploaded: #{checksum}") end end diff --git a/lib/chef_zero/endpoints/search_endpoint.rb b/lib/chef_zero/endpoints/search_endpoint.rb index e2f30ce..c341074 100644 --- a/lib/chef_zero/endpoints/search_endpoint.rb +++ b/lib/chef_zero/endpoints/search_endpoint.rb @@ -30,7 +30,7 @@ module ChefZero if path.size > 0 value = search_value path.each do |path_part| - value = value[path_part] if !value.nil? + value = value[path_part] unless value.nil? end data[key] = value else @@ -180,7 +180,7 @@ module ChefZero dest when Hash source.each do |src_key, src_value| - if dest.kind_of?(Hash) + if dest.is_a?(Hash) if dest[src_key] dest[src_key] = deep_merge!(src_value, dest[src_key]) else # dest[src_key] doesn't exist so we take whatever source has @@ -191,7 +191,7 @@ module ChefZero end end when Array - if dest.kind_of?(Array) + if dest.is_a?(Array) dest |= source else dest = source diff --git a/lib/chef_zero/endpoints/system_recovery_endpoint.rb b/lib/chef_zero/endpoints/system_recovery_endpoint.rb index 0ad2293..0f77a8c 100644 --- a/lib/chef_zero/endpoints/system_recovery_endpoint.rb +++ b/lib/chef_zero/endpoints/system_recovery_endpoint.rb @@ -10,13 +10,13 @@ module ChefZero name = request_json["username"] password = request_json["password"] user = get_data(request, request.rest_path[0..-2] + ["users", name], :nil) - if !user + unless user raise RestErrorResponse.new(403, "Nonexistent user") end user = FFI_Yajl::Parser.parse(user) user = ChefData::DataNormalizer.normalize_user(user, name, [ "username" ], server.options[:osc_compat]) - if !user["recovery_authentication_enabled"] + unless user["recovery_authentication_enabled"] raise RestErrorResponse.new(403, "Only users with recovery_authentication_enabled=true may use /system_recovery to log in") end if user["password"] != password diff --git a/lib/chef_zero/endpoints/user_association_request_endpoint.rb b/lib/chef_zero/endpoints/user_association_request_endpoint.rb index 580ba49..70dd189 100644 --- a/lib/chef_zero/endpoints/user_association_request_endpoint.rb +++ b/lib/chef_zero/endpoints/user_association_request_endpoint.rb @@ -11,6 +11,7 @@ module ChefZero if id !~ /^#{username}-(.+)/ raise RestErrorResponse.new(400, "Association request #{id} is invalid. Must be #{username}-orgname.") end + orgname = $1 json = FFI_Yajl::Parser.parse(request.body) diff --git a/lib/chef_zero/rest_base.rb b/lib/chef_zero/rest_base.rb index 4cf73ba..a7a05b9 100644 --- a/lib/chef_zero/rest_base.rb +++ b/lib/chef_zero/rest_base.rb @@ -30,15 +30,13 @@ module ChefZero } return json_response(406, - response, - request_version: version, response_version: -1 - ) + response, + request_version: version, response_version: -1) end rescue ArgumentError json_response(406, - { "username" => request.requestor }, - request_version: -1, response_version: -1 - ) + { "username" => request.requestor }, + request_version: -1, response_version: -1) end def call(request) @@ -46,14 +44,15 @@ module ChefZero return response unless response.nil? method = request.method.downcase.to_sym - if !respond_to?(method) - accept_methods = [:get, :put, :post, :delete].select { |m| respond_to?(m) } + unless respond_to?(method) + accept_methods = %i{get put post delete}.select { |m| respond_to?(m) } accept_methods_str = accept_methods.map { |m| m.to_s.upcase }.join(", ") - return [405, { "Content-Type" => "text/plain", "Allow" => accept_methods_str }, "Bad request method for '#{request.env['REQUEST_PATH']}': #{request.env['REQUEST_METHOD']}"] + return [405, { "Content-Type" => "text/plain", "Allow" => accept_methods_str }, "Bad request method for '#{request.env["REQUEST_PATH"]}': #{request.env["REQUEST_METHOD"]}"] end if json_only && !accepts?(request, "application", "json") return [406, { "Content-Type" => "text/plain" }, "Must accept application/json"] end + # Dispatch to get()/post()/put()/delete() begin send(method, request) @@ -70,7 +69,8 @@ module ChefZero def accepts?(request, category, type) # If HTTP_ACCEPT is not sent at all, assume it accepts anything # This parses as per http://tools.ietf.org/html/rfc7231#section-5.3 - return true if !request.env["HTTP_ACCEPT"] + return true unless request.env["HTTP_ACCEPT"] + accepts = request.env["HTTP_ACCEPT"].split(/,\s*/).map { |x| x.split(";", 2)[0].strip } accepts.include?("#{category}/#{type}") || accepts.include?("#{category}/*") || accepts.include?("*/*") end @@ -284,7 +284,7 @@ module ChefZero end def self.build_uri(base_uri, rest_path) - "#{base_uri}/#{rest_path.map { |v| URI.escape(v) }.join('/')}" + "#{base_uri}/#{rest_path.map { |v| URI.escape(v) }.join("/")}" end def populate_defaults(request, response) diff --git a/lib/chef_zero/rest_request.rb b/lib/chef_zero/rest_request.rb index 864c9b1..379cc20 100644 --- a/lib/chef_zero/rest_request.rb +++ b/lib/chef_zero/rest_request.rb @@ -18,7 +18,7 @@ module ChefZero else scheme = env["rack.url_scheme"] end - @base_uri ||= "#{scheme}://#{env['HTTP_HOST']}#{env['SCRIPT_NAME']}" + @base_uri ||= "#{scheme}://#{env["HTTP_HOST"]}#{env["SCRIPT_NAME"]}" end def base_uri=(value) @@ -68,14 +68,14 @@ module ChefZero end def to_s - result = "#{method} #{rest_path.join('/')}" + result = "#{method} #{rest_path.join("/")}" if query_params.size > 0 - result << "?#{query_params.map { |k, v| "#{k}=#{v}" }.join('&')}" + result << "?#{query_params.map { |k, v| "#{k}=#{v}" }.join("&")}" end if body.chomp != "" result << "\n--- #{method} BODY ---\n" result << body - result << "\n" if !body.end_with?("\n") + result << "\n" unless body.end_with?("\n") result << "--- END #{method} BODY ---" end result diff --git a/lib/chef_zero/rest_router.rb b/lib/chef_zero/rest_router.rb index ce08204..dc24bb3 100644 --- a/lib/chef_zero/rest_router.rb +++ b/lib/chef_zero/rest_router.rb @@ -5,9 +5,9 @@ module ChefZero def initialize(routes) @routes = routes.map do |route, endpoint| if route =~ /\*\*$/ - pattern = Regexp.new("^#{route[0..-3].gsub('*', '[^/]*')}") + pattern = Regexp.new("^#{route[0..-3].gsub("*", "[^/]*")}") else - pattern = Regexp.new("^#{route.gsub('*', '[^/]*')}$") + pattern = Regexp.new("^#{route.gsub("*", "[^/]*")}$") end [ pattern, endpoint ] end diff --git a/lib/chef_zero/rspec.rb b/lib/chef_zero/rspec.rb index 496cea5..8d78560 100644 --- a/lib/chef_zero/rspec.rb +++ b/lib/chef_zero/rspec.rb @@ -69,6 +69,7 @@ module ChefZero if chef_server_options[:server_scope] != self.class.chef_server_options[:server_scope] raise "server_scope: #{chef_server_options[:server_scope]} will not be honored: it can only be set on when_the_chef_server!" end + Log.info("Starting #{ChefZero::Dist::PRODUCT} server with options #{chef_server_options}") ChefZero::RSpec.set_server_options(chef_server_options) diff --git a/lib/chef_zero/server.rb b/lib/chef_zero/server.rb index 0c60f78..2606dfb 100644 --- a/lib/chef_zero/server.rb +++ b/lib/chef_zero/server.rb @@ -176,7 +176,8 @@ module ChefZero end def local_mode_url - raise "Port not yet set, cannot generate URL" unless port.kind_of?(Integer) + raise "Port not yet set, cannot generate URL" unless port.is_a?(Integer) + "chefzero://localhost:#{port}" end @@ -275,7 +276,7 @@ module ChefZero true rescue Errno::EADDRINUSE ChefZero::Log.warn("Port #{port} not available") - @server.listeners.each { |l| l.close } + @server.listeners.each(&:close) @server.listeners.clear false end @@ -305,7 +306,7 @@ module ChefZero break end end - if !@port + unless @port raise Errno::EADDRINUSE, "No port in :port range #{options[:port]} is available" end @@ -501,11 +502,13 @@ module ChefZero else cookbook_data = ChefData::CookbookData.to_hash(cookbook, name_version) end - raise "No version specified" if !cookbook_data[:version] + raise "No version specified" unless cookbook_data[:version] + data_store.create_dir(["organizations", org_name, cookbook_type], cookbook_data[:cookbook_name], :recursive) data_store.set(["organizations", org_name, cookbook_type, cookbook_data[:cookbook_name], cookbook_data[:version]], FFI_Yajl::Encoder.encode(cookbook_data, pretty: true), :create) cookbook_data.values.each do |files| next unless files.is_a? Array + files.each do |file| data_store.set(["organizations", org_name, "file_store", "checksums", file[:checksum]], get_file(cookbook, file[:path]), :create) end @@ -642,6 +645,7 @@ module ChefZero def app return @app if @app + router = RestRouter.new(endpoints) router.not_found = NotFoundEndpoint.new diff --git a/lib/chef_zero/socketless_server_map.rb b/lib/chef_zero/socketless_server_map.rb index 1e7c1e2..f433ed2 100644 --- a/lib/chef_zero/socketless_server_map.rb +++ b/lib/chef_zero/socketless_server_map.rb @@ -85,6 +85,7 @@ module ChefZero def request(port, request_env) server = @servers_by_port[port] raise ServerNotFound, "No socketless #{ChefZero::Dist::PRODUCT} server on given port #{port.inspect}" unless server + server.handle_socketless_request(request_env) end diff --git a/lib/chef_zero/solr/query/phrase.rb b/lib/chef_zero/solr/query/phrase.rb index d345a8e..666b3c2 100644 --- a/lib/chef_zero/solr/query/phrase.rb +++ b/lib/chef_zero/solr/query/phrase.rb @@ -11,7 +11,7 @@ module ChefZero else literal_string = nil end - super(terms.map { |term| term.regexp_string }.join("#{NON_WORD_CHARACTER}+"), literal_string) + super(terms.map(&:regexp_string).join("#{NON_WORD_CHARACTER}+"), literal_string) end def to_s diff --git a/lib/chef_zero/solr/query/range_query.rb b/lib/chef_zero/solr/query/range_query.rb index 67ce1ce..7eed494 100644 --- a/lib/chef_zero/solr/query/range_query.rb +++ b/lib/chef_zero/solr/query/range_query.rb @@ -10,7 +10,7 @@ module ChefZero end def to_s - "#{@from_inclusive ? '[' : '{'}#{@from} TO #{@to}#{@to_inclusive ? ']' : '}'}" + "#{@from_inclusive ? "[" : "{"}#{@from} TO #{@to}#{@to_inclusive ? "]" : "}"}" end def matches_values?(values) @@ -20,7 +20,7 @@ module ChefZero when -1 return false when 0 - return false if !@from_inclusive + return false unless @from_inclusive end end unless @to == "*" @@ -28,7 +28,7 @@ module ChefZero when 1 return false when 0 - return false if !@to_inclusive + return false unless @to_inclusive end end return true diff --git a/lib/chef_zero/solr/solr_parser.rb b/lib/chef_zero/solr/solr_parser.rb index 86c232f..8de63e6 100644 --- a/lib/chef_zero/solr/solr_parser.rb +++ b/lib/chef_zero/solr/solr_parser.rb @@ -50,7 +50,7 @@ module ChefZero if @query_string[@index] == '\\' @index += 1 end - @index += 1 if !eof? + @index += 1 unless eof? break if eof? || !peek_term_token end @query_string[start_index..@index - 1] @@ -66,6 +66,7 @@ module ChefZero def peek_term_token return nil if @query_string[@index] =~ /\s/ + op = peek_operator_token !op || op == "-" end @@ -79,6 +80,7 @@ module ChefZero return result end end + nil end @@ -145,13 +147,13 @@ module ChefZero # If it's the start of a range query, build that elsif token == "{" || token == "[" left = next_token - parse_error(left, "Expected left term in range query") if !left + parse_error(left, "Expected left term in range query") unless left to = next_token parse_error(left, "Expected TO in range query") if to != "TO" right = next_token - parse_error(right, "Expected left term in range query") if !right + parse_error(right, "Expected left term in range query") unless right end_range = next_token - parse_error(right, "Expected end range '#{end_range}") if !["}", "]"].include?(end_range) + parse_error(right, "Expected end range '#{end_range}") unless ["}", "]"].include?(end_range) Query::RangeQuery.new(left, right, token == "[", end_range == "]") elsif token == "(" |