summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLamont Granquist <lamont@chef.io>2019-07-08 16:47:38 -0700
committerGitHub <noreply@github.com>2019-07-08 16:47:38 -0700
commitcfdd8523b66c92d988547269380319ac250b3ee9 (patch)
treed4983e2d9ca8b40f791e68152b7bfd99d4cd0fd7
parent643899fb580385968465c7e15e4f20908fc6c5ac (diff)
parentac56ffafe24e39fffb02cc1fbc0d3f27303390be (diff)
downloadchef-cfdd8523b66c92d988547269380319ac250b3ee9.tar.gz
Merge pull request #8711 from chef/lcg/new-chefstyle2
More Chefstyle updates
-rw-r--r--chef-config/lib/chef-config/config.rb16
-rw-r--r--chef-config/lib/chef-config/logger.rb27
-rw-r--r--chef-config/lib/chef-config/mixin/credentials.rb3
-rw-r--r--chef-config/lib/chef-config/mixin/fuzzy_hostname_matcher.rb2
-rw-r--r--chef-config/lib/chef-config/path_helper.rb2
-rw-r--r--chef-config/lib/chef-config/workstation_config_loader.rb1
-rw-r--r--chef-config/spec/unit/config_spec.rb4
-rw-r--r--chef-config/spec/unit/workstation_config_loader_spec.rb5
-rw-r--r--ext/win32-eventlog/Rakefile2
-rw-r--r--kitchen-tests/cookbooks/end_to_end/recipes/default.rb6
-rw-r--r--lib/chef/action_collection.rb8
-rw-r--r--lib/chef/api_client.rb4
-rw-r--r--lib/chef/api_client/registration.rb7
-rw-r--r--lib/chef/api_client_v1.rb3
-rw-r--r--lib/chef/application.rb1
-rw-r--r--lib/chef/application/apply.rb2
-rw-r--r--lib/chef/application/client.rb2
-rw-r--r--lib/chef/application/solo.rb4
-rw-r--r--lib/chef/application/windows_service.rb6
-rw-r--r--lib/chef/application/windows_service_manager.rb6
-rw-r--r--lib/chef/blacklist.rb2
-rw-r--r--lib/chef/chef_fs/chef_fs_data_store.rb22
-rw-r--r--lib/chef/chef_fs/command_line.rb7
-rw-r--r--lib/chef/chef_fs/config.rb5
-rw-r--r--lib/chef/chef_fs/data_handler/container_data_handler.rb2
-rw-r--r--lib/chef/chef_fs/data_handler/data_bag_item_data_handler.rb2
-rw-r--r--lib/chef/chef_fs/data_handler/data_handler_base.rb2
-rw-r--r--lib/chef/chef_fs/data_handler/organization_data_handler.rb2
-rw-r--r--lib/chef/chef_fs/data_handler/policy_data_handler.rb4
-rw-r--r--lib/chef/chef_fs/file_pattern.rb20
-rw-r--r--lib/chef/chef_fs/file_system.rb5
-rw-r--r--lib/chef/chef_fs/file_system/base_fs_object.rb19
-rw-r--r--lib/chef/chef_fs/file_system/chef_server/chef_server_root_dir.rb2
-rw-r--r--lib/chef/chef_fs/file_system/chef_server/cookbook_artifacts_dir.rb2
-rw-r--r--lib/chef/chef_fs/file_system/chef_server/cookbook_dir.rb13
-rw-r--r--lib/chef/chef_fs/file_system/chef_server/cookbook_file.rb2
-rw-r--r--lib/chef/chef_fs/file_system/chef_server/cookbook_subdir.rb2
-rw-r--r--lib/chef/chef_fs/file_system/chef_server/cookbooks_dir.rb2
-rw-r--r--lib/chef/chef_fs/file_system/chef_server/data_bag_dir.rb5
-rw-r--r--lib/chef/chef_fs/file_system/chef_server/environments_dir.rb6
-rw-r--r--lib/chef/chef_fs/file_system/chef_server/policies_dir.rb1
-rw-r--r--lib/chef/chef_fs/file_system/chef_server/rest_list_dir.rb1
-rw-r--r--lib/chef/chef_fs/file_system/chef_server/versioned_cookbooks_dir.rb2
-rw-r--r--lib/chef/chef_fs/file_system/memory/memory_dir.rb2
-rw-r--r--lib/chef/chef_fs/file_system/repository/acl.rb2
-rw-r--r--lib/chef/chef_fs/file_system/repository/base_file.rb3
-rw-r--r--lib/chef/chef_fs/file_system/repository/chef_repository_file_system_cookbook_dir.rb8
-rw-r--r--lib/chef/chef_fs/file_system/repository/chef_repository_file_system_cookbook_entry.rb10
-rw-r--r--lib/chef/chef_fs/file_system/repository/chef_repository_file_system_root_dir.rb10
-rw-r--r--lib/chef/chef_fs/file_system/repository/chef_repository_file_system_versioned_cookbook_dir.rb1
-rw-r--r--lib/chef/chef_fs/file_system/repository/directory.rb6
-rw-r--r--lib/chef/chef_fs/file_system/repository/file_system_entry.rb6
-rw-r--r--lib/chef/chef_fs/file_system_cache.rb1
-rw-r--r--lib/chef/chef_fs/parallelizer/parallel_enumerable.rb3
-rw-r--r--lib/chef/chef_fs/path_utils.rb3
-rw-r--r--lib/chef/client.rb6
-rw-r--r--lib/chef/config.rb2
-rw-r--r--lib/chef/cookbook/cookbook_version_loader.rb9
-rw-r--r--lib/chef/cookbook/file_system_file_vendor.rb1
-rw-r--r--lib/chef/cookbook/file_vendor.rb1
-rw-r--r--lib/chef/cookbook/gem_installer.rb1
-rw-r--r--lib/chef/cookbook/manifest_v0.rb1
-rw-r--r--lib/chef/cookbook/metadata.rb20
-rw-r--r--lib/chef/cookbook/remote_file_vendor.rb5
-rw-r--r--lib/chef/cookbook/synchronizer.rb10
-rw-r--r--lib/chef/cookbook/syntax_check.rb4
-rw-r--r--lib/chef/cookbook_loader.rb1
-rw-r--r--lib/chef/cookbook_manifest.rb6
-rw-r--r--lib/chef/cookbook_site_streaming_uploader.rb2
-rw-r--r--lib/chef/cookbook_uploader.rb4
-rw-r--r--lib/chef/cookbook_version.rb19
-rw-r--r--lib/chef/data_bag.rb3
-rw-r--r--lib/chef/data_bag_item.rb9
-rw-r--r--lib/chef/data_collector.rb1
-rw-r--r--lib/chef/data_collector/run_end_message.rb2
-rw-r--r--lib/chef/decorator.rb2
-rw-r--r--lib/chef/deprecated.rb1
-rw-r--r--lib/chef/dsl/data_query.rb2
-rw-r--r--lib/chef/dsl/declare_resource.rb2
-rw-r--r--lib/chef/dsl/platform_introspection.rb4
-rw-r--r--lib/chef/encrypted_data_bag_item.rb11
-rw-r--r--lib/chef/encrypted_data_bag_item/assertions.rb2
-rw-r--r--lib/chef/encrypted_data_bag_item/check_encrypted.rb1
-rw-r--r--lib/chef/encrypted_data_bag_item/decryptor.rb6
-rw-r--r--lib/chef/encrypted_data_bag_item/encryptor.rb1
-rw-r--r--lib/chef/environment.rb10
-rw-r--r--lib/chef/event_dispatch/base.rb258
-rw-r--r--lib/chef/event_dispatch/dispatcher.rb3
-rw-r--r--lib/chef/event_loggers/base.rb3
-rw-r--r--lib/chef/exceptions.rb4
-rw-r--r--lib/chef/file_access_control/unix.rb11
-rw-r--r--lib/chef/file_access_control/windows.rb25
-rw-r--r--lib/chef/file_cache.rb3
-rw-r--r--lib/chef/file_content_management/deploy.rb4
-rw-r--r--lib/chef/formatters/base.rb7
-rw-r--r--lib/chef/formatters/doc.rb54
-rw-r--r--lib/chef/formatters/error_inspectors/cookbook_resolve_error_inspector.rb5
-rw-r--r--lib/chef/formatters/error_inspectors/resource_failure_inspector.rb4
-rw-r--r--lib/chef/formatters/indentable_output_stream.rb6
-rw-r--r--lib/chef/formatters/minimal.rb63
-rw-r--r--lib/chef/guard_interpreter/resource_guard_interpreter.rb2
-rw-r--r--lib/chef/handler.rb3
-rw-r--r--lib/chef/http.rb41
-rw-r--r--lib/chef/http/api_versions.rb3
-rw-r--r--lib/chef/http/auth_credentials.rb1
-rw-r--r--lib/chef/http/decompressor.rb1
-rw-r--r--lib/chef/http/json_output.rb3
-rw-r--r--lib/chef/http/json_to_model_output.rb2
-rw-r--r--lib/chef/http/remote_request_id.rb3
-rw-r--r--lib/chef/http/socketless_chef_zero_client.rb5
-rw-r--r--lib/chef/http/ssl_policies.rb3
-rw-r--r--lib/chef/http/validate_content_length.rb4
-rw-r--r--lib/chef/json_compat.rb2
-rw-r--r--lib/chef/key.rb2
-rw-r--r--lib/chef/knife.rb11
-rw-r--r--lib/chef/knife/bootstrap.rb27
-rw-r--r--lib/chef/knife/bootstrap/chef_vault_handler.rb1
-rw-r--r--lib/chef/knife/bootstrap/client_builder.rb1
-rw-r--r--lib/chef/knife/bootstrap/train_connector.rb5
-rw-r--r--lib/chef/knife/client_bulk_delete.rb1
-rw-r--r--lib/chef/knife/cookbook_delete.rb2
-rw-r--r--lib/chef/knife/cookbook_download.rb2
-rw-r--r--lib/chef/knife/cookbook_show.rb2
-rw-r--r--lib/chef/knife/cookbook_upload.rb10
-rw-r--r--lib/chef/knife/core/bootstrap_context.rb2
-rw-r--r--lib/chef/knife/core/cookbook_scm_repo.rb2
-rw-r--r--lib/chef/knife/core/gem_glob_loader.rb4
-rw-r--r--lib/chef/knife/core/generic_presenter.rb8
-rw-r--r--lib/chef/knife/core/node_presenter.rb34
-rw-r--r--lib/chef/knife/core/object_loader.rb2
-rw-r--r--lib/chef/knife/core/status_presenter.rb10
-rw-r--r--lib/chef/knife/core/subcommand_loader.rb1
-rw-r--r--lib/chef/knife/core/text_formatter.rb8
-rw-r--r--lib/chef/knife/core/ui.rb14
-rw-r--r--lib/chef/knife/data_bag_create.rb1
-rw-r--r--lib/chef/knife/data_bag_from_file.rb2
-rw-r--r--lib/chef/knife/deps.rb12
-rw-r--r--lib/chef/knife/edit.rb4
-rw-r--r--lib/chef/knife/environment_compare.rb1
-rw-r--r--lib/chef/knife/key_list.rb4
-rw-r--r--lib/chef/knife/list.rb10
-rw-r--r--lib/chef/knife/node_bulk_delete.rb1
-rw-r--r--lib/chef/knife/node_edit.rb2
-rw-r--r--lib/chef/knife/node_run_list_add.rb4
-rw-r--r--lib/chef/knife/node_run_list_remove.rb4
-rw-r--r--lib/chef/knife/node_run_list_set.rb4
-rw-r--r--lib/chef/knife/null.rb3
-rw-r--r--lib/chef/knife/role_bulk_delete.rb1
-rw-r--r--lib/chef/knife/role_env_run_list_add.rb4
-rw-r--r--lib/chef/knife/role_env_run_list_set.rb4
-rw-r--r--lib/chef/knife/role_run_list_add.rb4
-rw-r--r--lib/chef/knife/role_run_list_set.rb4
-rw-r--r--lib/chef/knife/search.rb8
-rw-r--r--lib/chef/knife/ssh.rb22
-rw-r--r--lib/chef/knife/supermarket_download.rb2
-rw-r--r--lib/chef/knife/supermarket_list.rb2
-rw-r--r--lib/chef/knife/supermarket_share.rb5
-rw-r--r--lib/chef/knife/supermarket_show.rb2
-rw-r--r--lib/chef/knife/supermarket_unshare.rb1
-rw-r--r--lib/chef/knife/tag_delete.rb2
-rw-r--r--lib/chef/knife/xargs.rb4
-rw-r--r--lib/chef/log/syslog.rb4
-rw-r--r--lib/chef/log/winevt.rb3
-rw-r--r--lib/chef/mash.rb4
-rw-r--r--lib/chef/mixin/api_version_request_handling.rb2
-rw-r--r--lib/chef/mixin/checksum.rb1
-rw-r--r--lib/chef/mixin/convert_to_class_name.rb3
-rw-r--r--lib/chef/mixin/create_path.rb4
-rw-r--r--lib/chef/mixin/deep_merge.rb10
-rw-r--r--lib/chef/mixin/get_source_from_package.rb1
-rw-r--r--lib/chef/mixin/homebrew_user.rb1
-rw-r--r--lib/chef/mixin/openssl_helper.rb6
-rw-r--r--lib/chef/mixin/params_validate.rb32
-rw-r--r--lib/chef/mixin/powershell_out.rb2
-rw-r--r--lib/chef/mixin/powershell_type_coercions.rb4
-rw-r--r--lib/chef/mixin/properties.rb23
-rw-r--r--lib/chef/mixin/securable.rb6
-rw-r--r--lib/chef/mixin/shell_out.rb1
-rw-r--r--lib/chef/mixin/template.rb3
-rw-r--r--lib/chef/mixin/user_context.rb2
-rw-r--r--lib/chef/mixin/which.rb1
-rw-r--r--lib/chef/mixin/windows_architecture_helper.rb6
-rw-r--r--lib/chef/mixin/windows_env_helper.rb4
-rw-r--r--lib/chef/monkey_patches/net_http.rb2
-rw-r--r--lib/chef/monkey_patches/webrick-utils.rb2
-rw-r--r--lib/chef/node.rb21
-rw-r--r--lib/chef/node/attribute.rb233
-rw-r--r--lib/chef/node/attribute_collections.rb2
-rw-r--r--lib/chef/node/common_api.rb10
-rw-r--r--lib/chef/node/immutable_collections.rb2
-rw-r--r--lib/chef/node/mixin/immutablize_array.rb284
-rw-r--r--lib/chef/node/mixin/immutablize_hash.rb262
-rw-r--r--lib/chef/node_map.rb21
-rw-r--r--lib/chef/null_logger.rb24
-rw-r--r--lib/chef/platform/query_helpers.rb3
-rw-r--r--lib/chef/platform/rebooter.rb2
-rw-r--r--lib/chef/platform/service_helpers.rb4
-rw-r--r--lib/chef/policy_builder/expand_node_object.rb4
-rw-r--r--lib/chef/policy_builder/policyfile.rb6
-rw-r--r--lib/chef/powershell.rb2
-rw-r--r--lib/chef/property.rb9
-rw-r--r--lib/chef/provider.rb21
-rw-r--r--lib/chef/provider/apt_preference.rb3
-rw-r--r--lib/chef/provider/apt_repository.rb3
-rw-r--r--lib/chef/provider/apt_update.rb5
-rw-r--r--lib/chef/provider/cookbook_file.rb1
-rw-r--r--lib/chef/provider/cron.rb11
-rw-r--r--lib/chef/provider/cron/unix.rb1
-rw-r--r--lib/chef/provider/dsc_resource.rb5
-rw-r--r--lib/chef/provider/dsc_script.rb4
-rw-r--r--lib/chef/provider/execute.rb2
-rw-r--r--lib/chef/provider/file.rb8
-rw-r--r--lib/chef/provider/git.rb5
-rw-r--r--lib/chef/provider/group.rb10
-rw-r--r--lib/chef/provider/group/aix.rb2
-rw-r--r--lib/chef/provider/group/dscl.rb9
-rw-r--r--lib/chef/provider/group/groupadd.rb1
-rw-r--r--lib/chef/provider/group/groupmod.rb2
-rw-r--r--lib/chef/provider/group/pw.rb6
-rw-r--r--lib/chef/provider/group/suse.rb4
-rw-r--r--lib/chef/provider/group/usermod.rb1
-rw-r--r--lib/chef/provider/group/windows.rb2
-rw-r--r--lib/chef/provider/http_request.rb2
-rw-r--r--lib/chef/provider/ifconfig.rb18
-rw-r--r--lib/chef/provider/ifconfig/aix.rb1
-rw-r--r--lib/chef/provider/ifconfig/debian.rb1
-rw-r--r--lib/chef/provider/launchd.rb29
-rw-r--r--lib/chef/provider/lwrp_base.rb3
-rw-r--r--lib/chef/provider/mount.rb1
-rw-r--r--lib/chef/provider/mount/aix.rb12
-rw-r--r--lib/chef/provider/mount/mount.rb9
-rw-r--r--lib/chef/provider/mount/solaris.rb8
-rw-r--r--lib/chef/provider/package.rb15
-rw-r--r--lib/chef/provider/package/apt.rb7
-rw-r--r--lib/chef/provider/package/bff.rb1
-rw-r--r--lib/chef/provider/package/cab.rb6
-rw-r--r--lib/chef/provider/package/chocolatey.rb7
-rw-r--r--lib/chef/provider/package/dnf.rb2
-rw-r--r--lib/chef/provider/package/dnf/python_helper.rb1
-rw-r--r--lib/chef/provider/package/dpkg.rb8
-rw-r--r--lib/chef/provider/package/freebsd/base.rb5
-rw-r--r--lib/chef/provider/package/freebsd/pkgng.rb4
-rw-r--r--lib/chef/provider/package/homebrew.rb2
-rw-r--r--lib/chef/provider/package/macports.rb1
-rw-r--r--lib/chef/provider/package/msu.rb4
-rw-r--r--lib/chef/provider/package/openbsd.rb2
-rw-r--r--lib/chef/provider/package/paludis.rb1
-rw-r--r--lib/chef/provider/package/portage.rb4
-rw-r--r--lib/chef/provider/package/powershell.rb5
-rw-r--r--lib/chef/provider/package/rpm.rb1
-rw-r--r--lib/chef/provider/package/rubygems.rb8
-rw-r--r--lib/chef/provider/package/smartos.rb1
-rw-r--r--lib/chef/provider/package/snap.rb6
-rw-r--r--lib/chef/provider/package/solaris.rb2
-rw-r--r--lib/chef/provider/package/windows/exe.rb10
-rw-r--r--lib/chef/provider/package/windows/msi.rb15
-rw-r--r--lib/chef/provider/package/windows/registry_uninstall_entry.rb1
-rw-r--r--lib/chef/provider/package/yum.rb7
-rw-r--r--lib/chef/provider/package/yum/python_helper.rb3
-rw-r--r--lib/chef/provider/reboot.rb2
-rw-r--r--lib/chef/provider/registry_key.rb4
-rw-r--r--lib/chef/provider/remote_directory.rb2
-rw-r--r--lib/chef/provider/remote_file.rb19
-rw-r--r--lib/chef/provider/remote_file/fetcher.rb5
-rw-r--r--lib/chef/provider/remote_file/local_file.rb2
-rw-r--r--lib/chef/provider/route.rb6
-rw-r--r--lib/chef/provider/service/aixinit.rb2
-rw-r--r--lib/chef/provider/service/arch.rb3
-rw-r--r--lib/chef/provider/service/debian.rb23
-rw-r--r--lib/chef/provider/service/freebsd.rb2
-rw-r--r--lib/chef/provider/service/openbsd.rb14
-rw-r--r--lib/chef/provider/service/redhat.rb4
-rw-r--r--lib/chef/provider/service/simple.rb3
-rw-r--r--lib/chef/provider/service/systemd.rb4
-rw-r--r--lib/chef/provider/service/upstart.rb5
-rw-r--r--lib/chef/provider/service/windows.rb7
-rw-r--r--lib/chef/provider/subversion.rb5
-rw-r--r--lib/chef/provider/template.rb1
-rw-r--r--lib/chef/provider/user.rb6
-rw-r--r--lib/chef/provider/user/aix.rb3
-rw-r--r--lib/chef/provider/user/dscl.rb9
-rw-r--r--lib/chef/provider/user/linux.rb1
-rw-r--r--lib/chef/provider/user/pw.rb1
-rw-r--r--lib/chef/provider/user/solaris.rb2
-rw-r--r--lib/chef/provider/user/windows.rb3
-rw-r--r--lib/chef/provider/windows_env.rb3
-rw-r--r--lib/chef/provider/windows_script.rb2
-rw-r--r--lib/chef/provider/windows_task.rb3
-rw-r--r--lib/chef/provider/yum_repository.rb3
-rw-r--r--lib/chef/provider/zypper_repository.rb5
-rw-r--r--lib/chef/recipe.rb3
-rw-r--r--lib/chef/resource.rb39
-rw-r--r--lib/chef/resource/apt_package.rb2
-rw-r--r--lib/chef/resource/apt_repository.rb2
-rw-r--r--lib/chef/resource/build_essential.rb5
-rw-r--r--lib/chef/resource/cab_package.rb4
-rw-r--r--lib/chef/resource/chef_gem.rb4
-rw-r--r--lib/chef/resource/chef_handler.rb1
-rw-r--r--lib/chef/resource/chocolatey_config.rb4
-rw-r--r--lib/chef/resource/chocolatey_feature.rb4
-rw-r--r--lib/chef/resource/chocolatey_source.rb4
-rw-r--r--lib/chef/resource/cron.rb2
-rw-r--r--lib/chef/resource/cron_d.rb9
-rw-r--r--lib/chef/resource/dmg_package.rb6
-rw-r--r--lib/chef/resource/dnf_package.rb26
-rw-r--r--lib/chef/resource/dpkg_package.rb2
-rw-r--r--lib/chef/resource/dsc_resource.rb6
-rw-r--r--lib/chef/resource/dsc_script.rb5
-rw-r--r--lib/chef/resource/execute.rb4
-rw-r--r--lib/chef/resource/file.rb6
-rw-r--r--lib/chef/resource/file/verification.rb2
-rw-r--r--lib/chef/resource/file/verification/systemd_unit.rb1
-rw-r--r--lib/chef/resource/git.rb2
-rw-r--r--lib/chef/resource/homebrew_tap.rb2
-rw-r--r--lib/chef/resource/hostname.rb2
-rw-r--r--lib/chef/resource/http_request.rb2
-rw-r--r--lib/chef/resource/launchd.rb76
-rw-r--r--lib/chef/resource/link.rb4
-rw-r--r--lib/chef/resource/locale.rb28
-rw-r--r--lib/chef/resource/log.rb2
-rw-r--r--lib/chef/resource/lwrp_base.rb1
-rw-r--r--lib/chef/resource/macos_userdefaults.rb1
-rw-r--r--lib/chef/resource/mount.rb4
-rw-r--r--lib/chef/resource/msu_package.rb4
-rw-r--r--lib/chef/resource/ohai_hint.rb2
-rw-r--r--lib/chef/resource/openssl_x509_certificate.rb4
-rw-r--r--lib/chef/resource/openssl_x509_request.rb2
-rw-r--r--lib/chef/resource/registry_key.rb8
-rw-r--r--lib/chef/resource/remote_file.rb7
-rw-r--r--lib/chef/resource/resource_notification.rb7
-rw-r--r--lib/chef/resource/route.rb2
-rw-r--r--lib/chef/resource/sudo.rb1
-rw-r--r--lib/chef/resource/swap_file.rb2
-rw-r--r--lib/chef/resource/sysctl.rb19
-rw-r--r--lib/chef/resource/template.rb6
-rw-r--r--lib/chef/resource/timezone.rb1
-rw-r--r--lib/chef/resource/windows_ad_join.rb3
-rw-r--r--lib/chef/resource/windows_certificate.rb6
-rw-r--r--lib/chef/resource/windows_dfs_folder.rb13
-rw-r--r--lib/chef/resource/windows_dfs_namespace.rb12
-rw-r--r--lib/chef/resource/windows_dfs_server.rb4
-rw-r--r--lib/chef/resource/windows_feature.rb2
-rw-r--r--lib/chef/resource/windows_feature_dism.rb23
-rw-r--r--lib/chef/resource/windows_feature_powershell.rb26
-rw-r--r--lib/chef/resource/windows_firewall_rule.rb22
-rw-r--r--lib/chef/resource/windows_pagefile.rb1
-rw-r--r--lib/chef/resource/windows_script.rb2
-rw-r--r--lib/chef/resource/windows_service.rb2
-rw-r--r--lib/chef/resource/windows_share.rb5
-rw-r--r--lib/chef/resource/windows_task.rb40
-rw-r--r--lib/chef/resource/windows_uac.rb8
-rw-r--r--lib/chef/resource/windows_workgroup.rb3
-rw-r--r--lib/chef/resource/yum_repository.rb2
-rw-r--r--lib/chef/resource/zypper_repository.rb2
-rw-r--r--lib/chef/resource_builder.rb1
-rw-r--r--lib/chef/resource_collection.rb10
-rw-r--r--lib/chef/resource_collection/resource_collection_serialization.rb7
-rw-r--r--lib/chef/resource_collection/resource_list.rb8
-rw-r--r--lib/chef/resource_collection/resource_set.rb16
-rw-r--r--lib/chef/resource_collection/stepable_iterator.rb1
-rw-r--r--lib/chef/resource_definition.rb8
-rw-r--r--lib/chef/resource_definition_list.rb2
-rw-r--r--lib/chef/resource_inspector.rb2
-rw-r--r--lib/chef/role.rb16
-rw-r--r--lib/chef/run_context.rb10
-rw-r--r--lib/chef/run_context/cookbook_compiler.rb6
-rw-r--r--lib/chef/run_list.rb9
-rw-r--r--lib/chef/run_list/run_list_expansion.rb5
-rw-r--r--lib/chef/run_list/run_list_item.rb10
-rw-r--r--lib/chef/run_list/versioned_recipe_list.rb2
-rw-r--r--lib/chef/run_status.rb2
-rw-r--r--lib/chef/runner.rb6
-rw-r--r--lib/chef/search/query.rb6
-rw-r--r--lib/chef/shell/ext.rb4
-rw-r--r--lib/chef/shell/model_wrapper.rb3
-rw-r--r--lib/chef/shell/shell_session.rb2
-rw-r--r--lib/chef/train_transport.rb6
-rw-r--r--lib/chef/user.rb2
-rw-r--r--lib/chef/user_v1.rb4
-rw-r--r--lib/chef/util/diff.rb7
-rw-r--r--lib/chef/util/dsc/configuration_generator.rb12
-rw-r--r--lib/chef/util/dsc/lcm_output_parser.rb4
-rw-r--r--lib/chef/util/dsc/local_configuration_manager.rb4
-rw-r--r--lib/chef/util/file_edit.rb1
-rw-r--r--lib/chef/util/powershell/cmdlet.rb2
-rw-r--r--lib/chef/util/threaded_job_queue.rb2
-rw-r--r--lib/chef/util/windows/logon_session.rb10
-rw-r--r--lib/chef/util/windows/net_use.rb4
-rw-r--r--lib/chef/util/windows/net_user.rb3
-rw-r--r--lib/chef/version_class.rb2
-rw-r--r--lib/chef/version_constraint.rb2
-rw-r--r--lib/chef/whitelist.rb2
-rw-r--r--lib/chef/win32/api/crypto.rb18
-rw-r--r--lib/chef/win32/api/error.rb8
-rw-r--r--lib/chef/win32/api/file.rb28
-rw-r--r--lib/chef/win32/api/installer.rb6
-rw-r--r--lib/chef/win32/api/memory.rb8
-rw-r--r--lib/chef/win32/api/net.rb74
-rw-r--r--lib/chef/win32/api/process.rb4
-rw-r--r--lib/chef/win32/api/psapi.rb2
-rw-r--r--lib/chef/win32/api/registry.rb6
-rw-r--r--lib/chef/win32/api/security.rb130
-rw-r--r--lib/chef/win32/api/synchronization.rb10
-rw-r--r--lib/chef/win32/api/system.rb14
-rw-r--r--lib/chef/win32/api/unicode.rb6
-rw-r--r--lib/chef/win32/eventlog.rb4
-rw-r--r--lib/chef/win32/file.rb5
-rw-r--r--lib/chef/win32/file/info.rb1
-rw-r--r--lib/chef/win32/file/version_info.rb29
-rw-r--r--lib/chef/win32/memory.rb2
-rw-r--r--lib/chef/win32/net.rb12
-rw-r--r--lib/chef/win32/registry.rb7
-rw-r--r--lib/chef/win32/security.rb5
-rw-r--r--lib/chef/win32/security/acl.rb3
-rw-r--r--lib/chef/win32/security/security_descriptor.rb6
-rw-r--r--lib/chef/win32/security/sid.rb21
-rw-r--r--lib/chef/win32/security/token.rb4
-rw-r--r--lib/chef/win32/version.rb6
-rw-r--r--omnibus_overrides.rb2
-rw-r--r--spec/functional/dsl/reboot_pending_spec.rb2
-rw-r--r--spec/functional/event_loggers/windows_eventlog_spec.rb10
-rw-r--r--spec/functional/file_content_management/deploy_strategies_spec.rb42
-rw-r--r--spec/functional/knife/exec_spec.rb2
-rw-r--r--spec/functional/knife/ssh_spec.rb6
-rw-r--r--spec/functional/mixin/user_context_spec.rb4
-rw-r--r--spec/functional/rebooter_spec.rb2
-rwxr-xr-xspec/functional/resource/aix_service_spec.rb2
-rwxr-xr-xspec/functional/resource/aixinit_service_spec.rb2
-rw-r--r--spec/functional/resource/chocolatey_package_spec.rb2
-rw-r--r--spec/functional/resource/cookbook_file_spec.rb4
-rw-r--r--spec/functional/resource/cron_spec.rb1
-rw-r--r--spec/functional/resource/dsc_resource_spec.rb3
-rw-r--r--spec/functional/resource/dsc_script_spec.rb14
-rw-r--r--spec/functional/resource/group_spec.rb28
-rw-r--r--spec/functional/resource/link_spec.rb4
-rw-r--r--spec/functional/resource/locale_spec.rb8
-rw-r--r--spec/functional/resource/mount_spec.rb2
-rw-r--r--spec/functional/resource/powershell_script_spec.rb17
-rw-r--r--spec/functional/resource/reboot_spec.rb2
-rw-r--r--spec/functional/resource/remote_file_spec.rb4
-rw-r--r--spec/functional/resource/template_spec.rb2
-rw-r--r--spec/functional/resource/user/windows_spec.rb4
-rw-r--r--spec/functional/resource/windows_certificate_spec.rb6
-rw-r--r--spec/functional/resource/windows_service_spec.rb6
-rw-r--r--spec/functional/run_lock_spec.rb5
-rw-r--r--spec/functional/util/powershell/cmdlet_spec.rb2
-rw-r--r--spec/functional/win32/security_spec.rb17
-rw-r--r--spec/functional/win32/service_manager_spec.rb2
-rw-r--r--spec/integration/client/client_spec.rb160
-rw-r--r--spec/integration/client/exit_code_spec.rb4
-rw-r--r--spec/integration/client/ipv6_spec.rb4
-rw-r--r--spec/integration/knife/chef_fs_data_store_spec.rb50
-rw-r--r--spec/integration/knife/chef_repo_path_spec.rb8
-rw-r--r--spec/integration/knife/config_get_spec.rb2
-rw-r--r--spec/integration/knife/config_list_profiles_spec.rb3
-rw-r--r--spec/integration/knife/cookbook_api_ipv6_spec.rb2
-rw-r--r--spec/integration/knife/cookbook_download_spec.rb2
-rw-r--r--spec/integration/knife/diff_spec.rb4
-rw-r--r--spec/integration/knife/download_spec.rb2
-rw-r--r--spec/integration/knife/redirection_spec.rb2
-rw-r--r--spec/integration/knife/upload_spec.rb4
-rw-r--r--spec/integration/recipes/accumulator_spec.rb8
-rw-r--r--spec/integration/recipes/lwrp_inline_resources_spec.rb10
-rw-r--r--spec/integration/recipes/lwrp_spec.rb4
-rw-r--r--spec/integration/recipes/notifies_spec.rb40
-rw-r--r--spec/integration/recipes/notifying_block_spec.rb8
-rw-r--r--spec/integration/recipes/provider_choice.rb3
-rw-r--r--spec/integration/recipes/recipe_dsl_spec.rb18
-rw-r--r--spec/integration/recipes/remote_directory.rb4
-rw-r--r--spec/integration/solo/solo_spec.rb40
-rw-r--r--spec/spec_helper.rb17
-rw-r--r--spec/stress/win32/security_spec.rb2
-rw-r--r--spec/support/lib/chef/resource/zen_follower.rb2
-rw-r--r--spec/support/lib/chef/resource/zen_master.rb2
-rw-r--r--spec/support/mock/platform.rb4
-rw-r--r--spec/support/platform_helpers.rb6
-rw-r--r--spec/support/platforms/win32/spec_service.rb16
-rw-r--r--spec/support/shared/functional/execute_resource.rb8
-rw-r--r--spec/support/shared/functional/file_resource.rb4
-rw-r--r--spec/support/shared/functional/http.rb54
-rw-r--r--spec/support/shared/functional/securable_resource.rb12
-rw-r--r--spec/support/shared/functional/win32_service.rb2
-rw-r--r--spec/support/shared/functional/windows_script.rb3
-rw-r--r--spec/support/shared/integration/app_server_support.rb7
-rw-r--r--spec/support/shared/integration/integration_helper.rb1
-rw-r--r--spec/support/shared/integration/knife_support.rb10
-rw-r--r--spec/support/shared/unit/application_dot_d.rb14
-rw-r--r--spec/support/shared/unit/file_system_support.rb5
-rw-r--r--spec/support/shared/unit/platform_introspector.rb24
-rw-r--r--spec/support/shared/unit/provider/file.rb2
-rw-r--r--spec/support/shared/unit/script_resource.rb2
-rw-r--r--spec/support/shared/unit/windows_script_resource.rb2
-rw-r--r--spec/tiny_server.rb2
-rw-r--r--spec/unit/api_client/registration_spec.rb2
-rw-r--r--spec/unit/api_client_spec.rb10
-rw-r--r--spec/unit/api_client_v1_spec.rb12
-rw-r--r--spec/unit/application/exit_code_spec.rb5
-rw-r--r--spec/unit/application/knife_spec.rb3
-rw-r--r--spec/unit/chef_fs/config_spec.rb6
-rw-r--r--spec/unit/chef_fs/file_system/repository/directory_spec.rb2
-rw-r--r--spec/unit/chef_fs/parallelizer.rb2
-rw-r--r--spec/unit/client_spec.rb2
-rw-r--r--spec/unit/config_fetcher_spec.rb2
-rw-r--r--spec/unit/cookbook/metadata_spec.rb8
-rw-r--r--spec/unit/cookbook_loader_spec.rb20
-rw-r--r--spec/unit/cookbook_site_streaming_uploader_spec.rb3
-rw-r--r--spec/unit/data_bag_item_spec.rb16
-rw-r--r--spec/unit/data_bag_spec.rb2
-rw-r--r--spec/unit/decorator_spec.rb4
-rw-r--r--spec/unit/deprecated_spec.rb4
-rw-r--r--spec/unit/dsl/data_query_spec.rb5
-rw-r--r--spec/unit/dsl/declare_resource_spec.rb2
-rw-r--r--spec/unit/dsl/platform_introspection_spec.rb4
-rw-r--r--spec/unit/encrypted_data_bag_item/check_encrypted_spec.rb3
-rw-r--r--spec/unit/encrypted_data_bag_item_spec.rb3
-rw-r--r--spec/unit/environment_spec.rb16
-rw-r--r--spec/unit/event_dispatch/dsl_spec.rb2
-rw-r--r--spec/unit/formatters/error_inspectors/resource_failure_inspector_spec.rb6
-rw-r--r--spec/unit/guard_interpreter/resource_guard_interpreter_spec.rb2
-rw-r--r--spec/unit/http/authenticator_spec.rb5
-rw-r--r--spec/unit/http/json_input_spec.rb2
-rw-r--r--spec/unit/key_spec.rb2
-rw-r--r--spec/unit/knife/bootstrap_spec.rb34
-rw-r--r--spec/unit/knife/client_bulk_delete_spec.rb8
-rw-r--r--spec/unit/knife/configure_client_spec.rb2
-rw-r--r--spec/unit/knife/configure_spec.rb2
-rw-r--r--spec/unit/knife/cookbook_bulk_delete_spec.rb2
-rw-r--r--spec/unit/knife/cookbook_delete_spec.rb2
-rw-r--r--spec/unit/knife/cookbook_download_spec.rb4
-rw-r--r--spec/unit/knife/cookbook_metadata_spec.rb8
-rw-r--r--spec/unit/knife/cookbook_upload_spec.rb6
-rw-r--r--spec/unit/knife/core/gem_glob_loader_spec.rb8
-rw-r--r--spec/unit/knife/core/hashed_command_loader_spec.rb4
-rw-r--r--spec/unit/knife/core/node_editor_spec.rb16
-rw-r--r--spec/unit/knife/core/windows_bootstrap_context_spec.rb3
-rw-r--r--spec/unit/knife/data_bag_from_file_spec.rb3
-rw-r--r--spec/unit/knife/data_bag_show_spec.rb3
-rw-r--r--spec/unit/knife/key_create_spec.rb2
-rw-r--r--spec/unit/knife/key_edit_spec.rb2
-rw-r--r--spec/unit/knife/key_list_spec.rb2
-rw-r--r--spec/unit/knife/node_bulk_delete_spec.rb6
-rw-r--r--spec/unit/knife/node_delete_spec.rb4
-rw-r--r--spec/unit/knife/node_edit_spec.rb2
-rw-r--r--spec/unit/knife/node_environment_set_spec.rb2
-rw-r--r--spec/unit/knife/node_from_file_spec.rb2
-rw-r--r--spec/unit/knife/node_policy_set_spec.rb2
-rw-r--r--spec/unit/knife/node_run_list_add_spec.rb2
-rw-r--r--spec/unit/knife/node_run_list_remove_spec.rb2
-rw-r--r--spec/unit/knife/node_run_list_set_spec.rb2
-rw-r--r--spec/unit/knife/node_show_spec.rb2
-rw-r--r--spec/unit/knife/role_bulk_delete_spec.rb4
-rw-r--r--spec/unit/knife/role_create_spec.rb2
-rw-r--r--spec/unit/knife/role_delete_spec.rb2
-rw-r--r--spec/unit/knife/role_edit_spec.rb2
-rw-r--r--spec/unit/knife/role_env_run_list_add_spec.rb2
-rw-r--r--spec/unit/knife/role_env_run_list_clear_spec.rb2
-rw-r--r--spec/unit/knife/role_env_run_list_remove_spec.rb2
-rw-r--r--spec/unit/knife/role_env_run_list_replace_spec.rb2
-rw-r--r--spec/unit/knife/role_env_run_list_set_spec.rb2
-rw-r--r--spec/unit/knife/role_from_file_spec.rb2
-rw-r--r--spec/unit/knife/role_run_list_add_spec.rb2
-rw-r--r--spec/unit/knife/role_run_list_clear_spec.rb2
-rw-r--r--spec/unit/knife/role_run_list_remove_spec.rb2
-rw-r--r--spec/unit/knife/role_run_list_replace_spec.rb2
-rw-r--r--spec/unit/knife/role_run_list_set_spec.rb2
-rw-r--r--spec/unit/knife/status_spec.rb3
-rw-r--r--spec/unit/knife/supermarket_install_spec.rb5
-rw-r--r--spec/unit/knife/supermarket_share_spec.rb2
-rw-r--r--spec/unit/knife_spec.rb55
-rw-r--r--spec/unit/lwrp_spec.rb38
-rw-r--r--spec/unit/mixin/homebrew_user_spec.rb2
-rw-r--r--spec/unit/mixin/params_validate_spec.rb20
-rw-r--r--spec/unit/mixin/properties_spec.rb8
-rw-r--r--spec/unit/mixin/shell_out_spec.rb6
-rw-r--r--spec/unit/mixin/template_spec.rb12
-rw-r--r--spec/unit/mixin/unformatter_spec.rb3
-rw-r--r--spec/unit/mixin/user_context_spec.rb3
-rw-r--r--spec/unit/mixin/which.rb2
-rw-r--r--spec/unit/mixin/windows_architecture_helper_spec.rb6
-rw-r--r--spec/unit/node/attribute_spec.rb18
-rw-r--r--spec/unit/node/immutable_collections_spec.rb100
-rw-r--r--spec/unit/node_spec.rb22
-rw-r--r--spec/unit/org_spec.rb6
-rw-r--r--spec/unit/policy_builder/policyfile_spec.rb4
-rw-r--r--spec/unit/property/state_spec.rb47
-rw-r--r--spec/unit/property/validation_spec.rb27
-rw-r--r--spec/unit/property_spec.rb21
-rw-r--r--spec/unit/provider/apt_update_spec.rb12
-rw-r--r--spec/unit/provider/cron_spec.rb2
-rw-r--r--spec/unit/provider/dsc_resource_spec.rb9
-rw-r--r--spec/unit/provider/dsc_script_spec.rb2
-rw-r--r--spec/unit/provider/group/dscl_spec.rb2
-rw-r--r--spec/unit/provider/group/groupadd_spec.rb2
-rw-r--r--spec/unit/provider/group_spec.rb5
-rw-r--r--spec/unit/provider/launchd_spec.rb24
-rw-r--r--spec/unit/provider/link_spec.rb33
-rw-r--r--spec/unit/provider/mount/mount_spec.rb62
-rw-r--r--spec/unit/provider/mount/solaris_spec.rb22
-rw-r--r--spec/unit/provider/osx_profile_spec.rb12
-rw-r--r--spec/unit/provider/package/apt_spec.rb8
-rw-r--r--spec/unit/provider/package/bff_spec.rb2
-rw-r--r--spec/unit/provider/package/cab_spec.rb2
-rw-r--r--spec/unit/provider/package/msu_spec.rb2
-rw-r--r--spec/unit/provider/package/openbsd_spec.rb24
-rw-r--r--spec/unit/provider/package/smartos_spec.rb4
-rw-r--r--spec/unit/provider/package/windows/exe_spec.rb18
-rw-r--r--spec/unit/provider/package/windows/msi_spec.rb14
-rw-r--r--spec/unit/provider/package/windows_spec.rb3
-rw-r--r--spec/unit/provider/package/yum/yum_cache_spec.rb2
-rw-r--r--spec/unit/provider/powershell_script_spec.rb24
-rw-r--r--spec/unit/provider/registry_key_spec.rb2
-rw-r--r--spec/unit/provider/route_spec.rb22
-rw-r--r--spec/unit/provider/service/arch_service_spec.rb22
-rw-r--r--spec/unit/provider/service/debian_service_spec.rb3
-rw-r--r--spec/unit/provider/service/freebsd_service_spec.rb42
-rw-r--r--spec/unit/provider/service/gentoo_service_spec.rb4
-rw-r--r--spec/unit/provider/service/init_service_spec.rb18
-rw-r--r--spec/unit/provider/service/invokercd_service_spec.rb18
-rw-r--r--spec/unit/provider/service/openbsd_service_spec.rb26
-rw-r--r--spec/unit/provider/service/simple_service_spec.rb10
-rw-r--r--spec/unit/provider/service/upstart_service_spec.rb28
-rw-r--r--spec/unit/provider/service/windows_spec.rb88
-rw-r--r--spec/unit/provider/subversion_spec.rb12
-rw-r--r--spec/unit/provider/systemd_unit_spec.rb292
-rw-r--r--spec/unit/provider/windows_task_spec.rb2
-rw-r--r--spec/unit/provider_resolver_spec.rb4
-rw-r--r--spec/unit/provider_spec.rb6
-rw-r--r--spec/unit/recipe_spec.rb6
-rw-r--r--spec/unit/resource/batch_spec.rb2
-rw-r--r--spec/unit/resource/cab_package_spec.rb2
-rw-r--r--spec/unit/resource/chef_gem_spec.rb2
-rw-r--r--spec/unit/resource/directory_spec.rb2
-rw-r--r--spec/unit/resource/dnf_package_spec.rb2
-rw-r--r--spec/unit/resource/dsc_resource_spec.rb2
-rw-r--r--spec/unit/resource/file/verification_spec.rb3
-rw-r--r--spec/unit/resource/file_spec.rb2
-rw-r--r--spec/unit/resource/group_spec.rb2
-rw-r--r--spec/unit/resource/link_spec.rb2
-rw-r--r--spec/unit/resource/locale_spec.rb24
-rw-r--r--spec/unit/resource/osx_profile_spec.rb3
-rw-r--r--spec/unit/resource/powershell_script_spec.rb19
-rw-r--r--spec/unit/resource/registry_key_spec.rb6
-rw-r--r--spec/unit/resource/service_spec.rb2
-rw-r--r--spec/unit/resource/template_spec.rb4
-rw-r--r--spec/unit/resource/windows_env_spec.rb2
-rw-r--r--spec/unit/resource/windows_service_spec.rb14
-rw-r--r--spec/unit/resource/windows_task_spec.rb4
-rw-r--r--spec/unit/resource/windows_uac_spec.rb4
-rw-r--r--spec/unit/resource/yum_package_spec.rb2
-rw-r--r--spec/unit/resource_collection/resource_list_spec.rb2
-rw-r--r--spec/unit/resource_collection/resource_set_spec.rb2
-rw-r--r--spec/unit/resource_collection/stepable_iterator_spec.rb4
-rw-r--r--spec/unit/resource_collection_spec.rb8
-rw-r--r--spec/unit/resource_definition_spec.rb4
-rw-r--r--spec/unit/resource_inspector_spec.rb2
-rw-r--r--spec/unit/resource_spec.rb42
-rw-r--r--spec/unit/role_spec.rb4
-rw-r--r--spec/unit/run_context/cookbook_compiler_spec.rb8
-rw-r--r--spec/unit/run_list/run_list_expansion_spec.rb15
-rw-r--r--spec/unit/run_list_spec.rb2
-rw-r--r--spec/unit/runner_spec.rb6
-rw-r--r--spec/unit/search/query_spec.rb5
-rw-r--r--spec/unit/shell/model_wrapper_spec.rb2
-rw-r--r--spec/unit/shell/shell_session_spec.rb9
-rw-r--r--spec/unit/shell_spec.rb3
-rw-r--r--spec/unit/user_spec.rb8
-rw-r--r--spec/unit/user_v1_spec.rb6
-rw-r--r--spec/unit/util/backup_spec.rb2
-rw-r--r--spec/unit/util/editor_spec.rb2
-rw-r--r--spec/unit/util/powershell/ps_credential_spec.rb5
-rw-r--r--spec/unit/util/threaded_job_queue_spec.rb4
-rw-r--r--spec/unit/version_class_spec.rb6
-rw-r--r--spec/unit/win32/registry_spec.rb10
-rw-r--r--spec/unit/win32/security_spec.rb3
-rwxr-xr-xtasks/docs.rb12
-rw-r--r--tasks/rspec.rb2
676 files changed, 3459 insertions, 3094 deletions
diff --git a/chef-config/lib/chef-config/config.rb b/chef-config/lib/chef-config/config.rb
index 051cdbfb7f..d136a8f79c 100644
--- a/chef-config/lib/chef-config/config.rb
+++ b/chef-config/lib/chef-config/config.rb
@@ -103,6 +103,7 @@ module ChefConfig
if option.empty? || !option.include?("=")
raise UnparsableConfigOption, "Unparsable config option #{option.inspect}"
end
+
# Split including whitespace if someone does truly odd like
# --config-option "foo = bar"
key, value = option.split(/\s*=\s*/, 2)
@@ -133,7 +134,7 @@ module ChefConfig
# @return [Boolean] is the URL valid
def self.is_valid_url?(uri)
url = uri.to_s.strip
- /^http:\/\// =~ url || /^https:\/\// =~ url || /^chefzero:/ =~ url
+ %r{^http://} =~ url || %r{^https://} =~ url || /^chefzero:/ =~ url
end
# Override the config dispatch to set the value of multiple server options simultaneously
@@ -144,6 +145,7 @@ module ChefConfig
unless is_valid_url? uri
raise ConfigurationError, "#{uri} is an invalid chef_server_url. The URL must start with http://, https://, or chefzero://."
end
+
uri.to_s.strip
end
@@ -160,7 +162,7 @@ module ChefConfig
# etc.) work.
default :chef_repo_path do
if configuration[:cookbook_path]
- if configuration[:cookbook_path].kind_of?(String)
+ if configuration[:cookbook_path].is_a?(String)
File.expand_path("..", configuration[:cookbook_path])
else
configuration[:cookbook_path].map do |path|
@@ -192,7 +194,7 @@ module ChefConfig
# @param child_path [String]
def self.derive_path_from_chef_repo_path(child_path)
- if chef_repo_path.kind_of?(String)
+ if chef_repo_path.is_a?(String)
PathHelper.join(chef_repo_path, child_path)
else
chef_repo_path.uniq.map { |path| PathHelper.join(path, child_path) }
@@ -401,7 +403,7 @@ module ChefConfig
default :repo_mode do
if local_mode && !chef_zero.osc_compat
"hosted_everything"
- elsif chef_server_url =~ /\/+organizations\/.+/
+ elsif chef_server_url =~ %r{/+organizations/.+}
"hosted_everything"
else
"everything"
@@ -457,7 +459,7 @@ module ChefConfig
default(:chef_server_root) do
# if the chef_server_url is a path to an organization, aka
# 'some_url.../organizations/*' then remove the '/organization/*' by default
- if configuration[:chef_server_url] =~ /\/organizations\/\S*$/
+ if configuration[:chef_server_url] =~ %r{/organizations/\S*$}
configuration[:chef_server_url].split("/")[0..-3].join("/")
elsif configuration[:chef_server_url] # default to whatever chef_server_url is
configuration[:chef_server_url]
@@ -1071,8 +1073,8 @@ module ChefConfig
# Check if the proxy string contains a scheme. If not, add the url's scheme to the
# proxy before parsing. The regex /^.*:\/\// matches, for example, http://. Reusing proxy
# here since we are really just trying to get the string built correctly.
- proxy = if !proxy_env_var.empty?
- if proxy_env_var =~ /^.*:\/\//
+ proxy = unless proxy_env_var.empty?
+ if proxy_env_var =~ %r{^.*://}
URI.parse(proxy_env_var)
else
URI.parse("#{scheme}://#{proxy_env_var}")
diff --git a/chef-config/lib/chef-config/logger.rb b/chef-config/lib/chef-config/logger.rb
index 69d7889f88..3fc389f54b 100644
--- a/chef-config/lib/chef-config/logger.rb
+++ b/chef-config/lib/chef-config/logger.rb
@@ -21,32 +21,23 @@ module ChefConfig
# logger for `ChefConfig.logger`
class NullLogger
- def <<(_msg)
- end
+ def <<(_msg); end
- def add(_severity, _message = nil, _progname = nil)
- end
+ def add(_severity, _message = nil, _progname = nil); end
- def trace(_progname = nil, &block)
- end
+ def trace(_progname = nil, &block); end
- def debug(_progname = nil, &block)
- end
+ def debug(_progname = nil, &block); end
- def info(_progname = nil, &block)
- end
+ def info(_progname = nil, &block); end
- def warn(_progname = nil, &block)
- end
+ def warn(_progname = nil, &block); end
- def deprecation(_progname = nil, &block)
- end
+ def deprecation(_progname = nil, &block); end
- def error(_progname = nil, &block)
- end
+ def error(_progname = nil, &block); end
- def fatal(_progname = nil, &block)
- end
+ def fatal(_progname = nil, &block); end
end
diff --git a/chef-config/lib/chef-config/mixin/credentials.rb b/chef-config/lib/chef-config/mixin/credentials.rb
index 5b0078d1cc..3882924d1a 100644
--- a/chef-config/lib/chef-config/mixin/credentials.rb
+++ b/chef-config/lib/chef-config/mixin/credentials.rb
@@ -65,6 +65,7 @@ module ChefConfig
def parse_credentials_file
credentials_file = credentials_file_path
return nil unless File.file?(credentials_file)
+
begin
Tomlrb.load_file(credentials_file)
rescue => e
@@ -85,10 +86,12 @@ module ChefConfig
profile = credentials_profile(profile)
config = parse_credentials_file
return if config.nil? # No credentials, nothing to do here.
+
if config[profile].nil?
# Unknown profile name. For "default" just silently ignore, otherwise
# raise an error.
return if profile == "default"
+
raise ChefConfig::ConfigurationError, "Profile #{profile} doesn't exist. Please add it to #{credentials_file}."
end
apply_credentials(config[profile], profile)
diff --git a/chef-config/lib/chef-config/mixin/fuzzy_hostname_matcher.rb b/chef-config/lib/chef-config/mixin/fuzzy_hostname_matcher.rb
index ca1bdb4c0b..b7a8a178ea 100644
--- a/chef-config/lib/chef-config/mixin/fuzzy_hostname_matcher.rb
+++ b/chef-config/lib/chef-config/mixin/fuzzy_hostname_matcher.rb
@@ -32,7 +32,7 @@ module ChefConfig
def fuzzy_hostname_match?(hostname, match)
# Do greedy matching by adding wildcard if it is not specified
- match = "*" + match if !match.start_with?("*")
+ match = "*" + match unless match.start_with?("*")
Fuzzyurl.matches?(Fuzzyurl.mask(hostname: match), hostname)
end
diff --git a/chef-config/lib/chef-config/path_helper.rb b/chef-config/lib/chef-config/path_helper.rb
index 7e0f4361ce..6c60b82b89 100644
--- a/chef-config/lib/chef-config/path_helper.rb
+++ b/chef-config/lib/chef-config/path_helper.rb
@@ -63,7 +63,7 @@ module ChefConfig
trailing_slashes = /[#{path_separator_regex}]+$/
leading_slashes = /^[#{path_separator_regex}]+/
- args.flatten.inject() do |joined_path, component|
+ args.flatten.inject do |joined_path, component|
joined_path = joined_path.sub(trailing_slashes, "")
component = component.sub(leading_slashes, "")
joined_path + "#{path_separator}#{component}"
diff --git a/chef-config/lib/chef-config/workstation_config_loader.rb b/chef-config/lib/chef-config/workstation_config_loader.rb
index a3aa40433a..d38cae3d88 100644
--- a/chef-config/lib/chef-config/workstation_config_loader.rb
+++ b/chef-config/lib/chef-config/workstation_config_loader.rb
@@ -155,6 +155,7 @@ module ChefConfig
if creds.key?("node_name") && creds.key?("client_name")
raise ChefConfig::ConfigurationError, "Do not specify both node_name and client_name. You should prefer client_name."
end
+
# Load credentials data into the Chef configuration.
creds.each do |key, value|
case key.to_s
diff --git a/chef-config/spec/unit/config_spec.rb b/chef-config/spec/unit/config_spec.rb
index 378cc4a4a1..dec5b8755f 100644
--- a/chef-config/spec/unit/config_spec.rb
+++ b/chef-config/spec/unit/config_spec.rb
@@ -195,7 +195,7 @@ RSpec.describe ChefConfig::Config do
[ false, true ].each do |is_windows|
- context "On #{is_windows ? 'Windows' : 'Unix'}" do
+ context "On #{is_windows ? "Windows" : "Unix"}" do
def to_platform(*args)
ChefConfig::Config.platform_specific_path(*args)
end
@@ -618,7 +618,7 @@ RSpec.describe ChefConfig::Config do
# On Windows, we'll detect an omnibus build and set this to the
# cacert.pem included in the package, but it's nil if you're on Windows
# w/o omnibus (e.g., doing development on Windows, custom build, etc.)
- if !is_windows
+ unless is_windows
it "ChefConfig::Config[:ssl_ca_file] defaults to nil" do
expect(ChefConfig::Config[:ssl_ca_file]).to be_nil
end
diff --git a/chef-config/spec/unit/workstation_config_loader_spec.rb b/chef-config/spec/unit/workstation_config_loader_spec.rb
index e1717b6574..e1cab3d4d0 100644
--- a/chef-config/spec/unit/workstation_config_loader_spec.rb
+++ b/chef-config/spec/unit/workstation_config_loader_spec.rb
@@ -375,7 +375,8 @@ RSpec.describe ChefConfig::WorkstationConfigLoader do
before do
ChefConfig::Config[:config_d_dir] = tempdir
allow(config_loader).to receive(:path_exists?).with(
- an_instance_of(String)).and_return(false)
+ an_instance_of(String)
+ ).and_return(false)
end
after do
@@ -516,7 +517,7 @@ RSpec.describe ChefConfig::WorkstationConfigLoader do
-----BEGIN RSA PRIVATE KEY-----
foo
EOH
-)
+ )
end
end
diff --git a/ext/win32-eventlog/Rakefile b/ext/win32-eventlog/Rakefile
index 1b974670e5..a4f032d04e 100644
--- a/ext/win32-eventlog/Rakefile
+++ b/ext/win32-eventlog/Rakefile
@@ -23,7 +23,7 @@ CC = "gcc".freeze
ensure_present [MC, RC, CC]
task build: [EVT_RESOURCE_OBJECT, EVT_SHARED_OBJECT]
-task default: [:build, :register]
+task default: %i{build register}
file EVT_RC_FILE => EVT_MC_FILE do
sh "#{MC} #{EVT_MC_FILE}"
diff --git a/kitchen-tests/cookbooks/end_to_end/recipes/default.rb b/kitchen-tests/cookbooks/end_to_end/recipes/default.rb
index 6d95f4471b..decd6a24af 100644
--- a/kitchen-tests/cookbooks/end_to_end/recipes/default.rb
+++ b/kitchen-tests/cookbooks/end_to_end/recipes/default.rb
@@ -26,11 +26,11 @@ end
yum_repository "epel" do
enabled true
- description "Extra Packages for Enterprise Linux #{node['platform_version'].to_i} - $basearch"
+ description "Extra Packages for Enterprise Linux #{node["platform_version"].to_i} - $basearch"
failovermethod "priority"
- gpgkey "https://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-#{node['platform_version'].to_i}"
+ gpgkey "https://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-#{node["platform_version"].to_i}"
gpgcheck true
- mirrorlist "https://mirrors.fedoraproject.org/metalink?repo=epel-#{node['platform_version'].to_i}&arch=$basearch"
+ mirrorlist "https://mirrors.fedoraproject.org/metalink?repo=epel-#{node["platform_version"].to_i}&arch=$basearch"
only_if { platform_family?("rhel") }
end
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
diff --git a/omnibus_overrides.rb b/omnibus_overrides.rb
index 1ec6417074..7d2a8221c0 100644
--- a/omnibus_overrides.rb
+++ b/omnibus_overrides.rb
@@ -30,4 +30,4 @@ override "openssl", version: "1.0.2r"
# definition. This pin will ensure that ohai and chef-client commands use the
# same (released) version of ohai.
gemfile_lock = File.join(File.expand_path(File.dirname(__FILE__)), "Gemfile.lock")
-override "ohai", version: "#{::File.readlines(gemfile_lock).find { |l| l =~ /^\s+ohai \((\d+\.\d+\.\d+)\)/ }; 'v' + $1}" # rubocop: disable Layout/SpaceInsideStringInterpolation
+override "ohai", version: "#{::File.readlines(gemfile_lock).find { |l| l =~ /^\s+ohai \((\d+\.\d+\.\d+)\)/ }; "v" + $1}" # rubocop: disable Layout/SpaceInsideStringInterpolation
diff --git a/spec/functional/dsl/reboot_pending_spec.rb b/spec/functional/dsl/reboot_pending_spec.rb
index 855a38b9cf..89701802b3 100644
--- a/spec/functional/dsl/reboot_pending_spec.rb
+++ b/spec/functional/dsl/reboot_pending_spec.rb
@@ -36,7 +36,7 @@ describe Chef::DSL::RebootPending, :windows_only do
let(:reg_key) { nil }
let(:original_set) { false }
- before(:all) { @any_flag = Hash.new }
+ before(:all) { @any_flag = {} }
after { @any_flag[reg_key] = original_set }
diff --git a/spec/functional/event_loggers/windows_eventlog_spec.rb b/spec/functional/event_loggers/windows_eventlog_spec.rb
index c1e5150428..ca15d3e38d 100644
--- a/spec/functional/event_loggers/windows_eventlog_spec.rb
+++ b/spec/functional/event_loggers/windows_eventlog_spec.rb
@@ -49,16 +49,18 @@ describe Chef::EventLoggers::WindowsEventLogger, :windows_only do
logger.run_start(version, run_status)
expect(event_log.read(flags, offset).any? do |e|
- e.source == Chef::Dist::PRODUCT && e.event_id == 10000 &&
- e.string_inserts[0].include?(version) end).to be_truthy
+ e.source == Chef::Dist::PRODUCT && e.event_id == 10000 &&
+ e.string_inserts[0].include?(version)
+ end ).to be_truthy
end
it "writes run_started event with event_id 10001 and contains the run_id" do
logger.run_started(run_status)
expect(event_log.read(flags, offset).any? do |e|
- e.source == Chef::Dist::PRODUCT && e.event_id == 10001 &&
- e.string_inserts[0].include?(run_id) end).to be_truthy
+ e.source == Chef::Dist::PRODUCT && e.event_id == 10001 &&
+ e.string_inserts[0].include?(run_id)
+ end ).to be_truthy
end
it "writes run_completed event with event_id 10002 and contains the run_id and elapsed time" do
diff --git a/spec/functional/file_content_management/deploy_strategies_spec.rb b/spec/functional/file_content_management/deploy_strategies_spec.rb
index 9e2131388f..07991aa8bd 100644
--- a/spec/functional/file_content_management/deploy_strategies_spec.rb
+++ b/spec/functional/file_content_management/deploy_strategies_spec.rb
@@ -175,20 +175,20 @@ end
describe Chef::FileContentManagement::Deploy::Cp do
let(:unix_invariants) do
- [
- :uid,
- :gid,
- :mode,
- :ino,
- ]
+ %i{
+ uid
+ gid
+ mode
+ ino
+ }
end
let(:security_descriptor_invariants) do
- [
- :owner,
- :group,
- :dacl,
- ]
+ %i{
+ owner
+ group
+ dacl
+ }
end
it_should_behave_like "a content deploy strategy"
@@ -198,11 +198,11 @@ end
describe Chef::FileContentManagement::Deploy::MvUnix, :unix_only do
let(:unix_invariants) do
- [
- :uid,
- :gid,
- :mode,
- ]
+ %i{
+ uid
+ gid
+ mode
+ }
end
it_should_behave_like "a content deploy strategy"
@@ -216,11 +216,11 @@ describe Chef::FileContentManagement::Deploy::MvWindows, :windows_only do
context "when a file has no sacl" do
let(:security_descriptor_invariants) do
- [
- :owner,
- :group,
- :dacl,
- ]
+ %i{
+ owner
+ group
+ dacl
+ }
end
it_should_behave_like "a content deploy strategy"
diff --git a/spec/functional/knife/exec_spec.rb b/spec/functional/knife/exec_spec.rb
index 7cdf1c93eb..010b89c4f4 100644
--- a/spec/functional/knife/exec_spec.rb
+++ b/spec/functional/knife/exec_spec.rb
@@ -49,7 +49,7 @@ describe Chef::Knife::Exec do
code = "$output.puts nodes.all"
@knife.config[:exec] = code
@knife.run
- expect($output.string).to match(%r{node\[ohai-world\]})
+ expect($output.string).to match(/node\[ohai-world\]/)
end
end
diff --git a/spec/functional/knife/ssh_spec.rb b/spec/functional/knife/ssh_spec.rb
index 95e7b6454c..aade00cbf1 100644
--- a/spec/functional/knife/ssh_spec.rb
+++ b/spec/functional/knife/ssh_spec.rb
@@ -31,7 +31,7 @@ describe Chef::Knife::Ssh do
@server.stop
end
- let(:ssh_config) { Hash.new }
+ let(:ssh_config) { {} }
before do
allow(Net::SSH).to receive(:configuration_for).and_return(ssh_config)
end
@@ -301,7 +301,7 @@ describe Chef::Knife::Ssh do
end
it "uses the ssh_gateway_identity file" do
- expect(@knife.session).to receive(:via).with("ec2.public_hostname", "user", { keys: File.expand_path("#{ENV['HOME']}/.ssh/aws-gateway.rsa").squeeze("/"), keys_only: true })
+ expect(@knife.session).to receive(:via).with("ec2.public_hostname", "user", { keys: File.expand_path("#{ENV["HOME"]}/.ssh/aws-gateway.rsa").squeeze("/"), keys_only: true })
@knife.run
expect(@knife.config[:ssh_gateway_identity]).to eq("~/.ssh/aws-gateway.rsa")
end
@@ -315,7 +315,7 @@ describe Chef::Knife::Ssh do
end
it "uses the ssh_gateway_identity file" do
- expect(@knife.session).to receive(:via).with("ec2.public_hostname", "user", { keys: File.expand_path("#{ENV['HOME']}/.ssh/aws-gateway.rsa").squeeze("/"), keys_only: true })
+ expect(@knife.session).to receive(:via).with("ec2.public_hostname", "user", { keys: File.expand_path("#{ENV["HOME"]}/.ssh/aws-gateway.rsa").squeeze("/"), keys_only: true })
@knife.run
expect(@knife.config[:ssh_gateway_identity]).to eq("~/.ssh/aws-gateway.rsa")
end
diff --git a/spec/functional/mixin/user_context_spec.rb b/spec/functional/mixin/user_context_spec.rb
index 802b1db9f1..b6b8b057d5 100644
--- a/spec/functional/mixin/user_context_spec.rb
+++ b/spec/functional/mixin/user_context_spec.rb
@@ -26,7 +26,7 @@ describe Chef::Mixin::UserContext, windows_only: true do
let(:get_user_name_a) do
FFI.ffi_lib "advapi32.dll"
- FFI.attach_function :GetUserNameA, [ :pointer, :pointer ], :bool
+ FFI.attach_function :GetUserNameA, %i{pointer pointer}, :bool
end
let(:process_username) do
@@ -36,12 +36,14 @@ describe Chef::Mixin::UserContext, windows_only: true do
if succeeded || last_error != Chef::ReservedNames::Win32::API::Error::ERROR_INSUFFICIENT_BUFFER
raise Chef::Exceptions::Win32APIError, "Expected ERROR_INSUFFICIENT_BUFFER from GetUserNameA but it returned the following error: #{last_error}"
end
+
user_name = FFI::MemoryPointer.new :char, (name_size.read_long)
succeeded = get_user_name_a.call(user_name, name_size)
last_error = FFI::LastError.error
if succeeded == 0 || last_error != 0
raise Chef::Exceptions::Win32APIError, "GetUserNameA failed with #{lasterror}"
end
+
user_name.read_string
end
diff --git a/spec/functional/rebooter_spec.rb b/spec/functional/rebooter_spec.rb
index 8e5b23f86b..747978cc96 100644
--- a/spec/functional/rebooter_spec.rb
+++ b/spec/functional/rebooter_spec.rb
@@ -44,7 +44,7 @@ describe Chef::Platform::Rebooter do
let(:expected) do
{
- windows: "#{ENV['SYSTEMROOT']}/System32/shutdown.exe /r /t 300 /c \"rebooter spec test\"",
+ windows: "#{ENV["SYSTEMROOT"]}/System32/shutdown.exe /r /t 300 /c \"rebooter spec test\"",
linux: 'shutdown -r +5 "rebooter spec test" &',
solaris: 'shutdown -i6 -g5 -y "rebooter spec test" &',
}
diff --git a/spec/functional/resource/aix_service_spec.rb b/spec/functional/resource/aix_service_spec.rb
index 5fff3e00d7..9ffe05266d 100755
--- a/spec/functional/resource/aix_service_spec.rb
+++ b/spec/functional/resource/aix_service_spec.rb
@@ -77,7 +77,7 @@ describe Chef::Resource::Service, :requires_root, :aix_only do
include Chef::Mixin::ShellOut
def get_user_id
- shell_out("id -u #{ENV['USER']}").stdout.chomp
+ shell_out("id -u #{ENV["USER"]}").stdout.chomp
end
describe "When service is a subsystem" do
diff --git a/spec/functional/resource/aixinit_service_spec.rb b/spec/functional/resource/aixinit_service_spec.rb
index 68ea5ab8b2..fc8a80eb08 100755
--- a/spec/functional/resource/aixinit_service_spec.rb
+++ b/spec/functional/resource/aixinit_service_spec.rb
@@ -40,7 +40,7 @@ describe Chef::Resource::Service, :requires_root, :aix_only do
directory = []
if priority.is_a? Hash
priority.each do |level, o|
- directory << "/etc/rc.d/rc#{level}.d/#{(o[0] == :start ? 'S' : 'K')}#{o[1]}#{new_resource.service_name}"
+ directory << "/etc/rc.d/rc#{level}.d/#{(o[0] == :start ? "S" : "K")}#{o[1]}#{new_resource.service_name}"
end
directory
else
diff --git a/spec/functional/resource/chocolatey_package_spec.rb b/spec/functional/resource/chocolatey_package_spec.rb
index 3c4b08a1f4..c5590b2d88 100644
--- a/spec/functional/resource/chocolatey_package_spec.rb
+++ b/spec/functional/resource/chocolatey_package_spec.rb
@@ -22,7 +22,7 @@ describe Chef::Resource::ChocolateyPackage, :windows_only, :choco_installed do
include Chef::Mixin::PowershellOut
let(:package_name) { "test-A" }
- let(:package_list) { proc { powershell_out!("choco list -lo -r #{Array(package_name).join(' ')}").stdout.chomp } }
+ let(:package_list) { proc { powershell_out!("choco list -lo -r #{Array(package_name).join(" ")}").stdout.chomp } }
let(:package_source) { File.join(CHEF_SPEC_ASSETS, "chocolatey_feed") }
subject do
diff --git a/spec/functional/resource/cookbook_file_spec.rb b/spec/functional/resource/cookbook_file_spec.rb
index d127413c73..6e964a6499 100644
--- a/spec/functional/resource/cookbook_file_spec.rb
+++ b/spec/functional/resource/cookbook_file_spec.rb
@@ -25,9 +25,7 @@ describe Chef::Resource::CookbookFile do
let(:source) { "java.response" }
let(:cookbook_name) { "java" }
let(:expected_content) do
- content = File.open(File.join(CHEF_SPEC_DATA, "cookbooks", "java", "files", "default", "java.response"), "rb") do |f|
- f.read
- end
+ content = File.open(File.join(CHEF_SPEC_DATA, "cookbooks", "java", "files", "default", "java.response"), "rb", &:read)
content.force_encoding(Encoding::BINARY) if content.respond_to?(:force_encoding)
content
end
diff --git a/spec/functional/resource/cron_spec.rb b/spec/functional/resource/cron_spec.rb
index f616b84ce9..16b0d2645c 100644
--- a/spec/functional/resource/cron_spec.rb
+++ b/spec/functional/resource/cron_spec.rb
@@ -118,6 +118,7 @@ describe Chef::Resource::Cron, :requires_root, :unix_only do
def cron_attribute_should_exists(cron_name, attribute, value)
return if %w{aix solaris}.include?(ohai[:platform])
+
# Test if the attribute exists on newly created cron
cron_should_exists(cron_name, "")
expect(shell_out("crontab -l -u #{new_resource.user} | grep '#{attribute.upcase}=\"#{value}\"'").exitstatus).to eq(0)
diff --git a/spec/functional/resource/dsc_resource_spec.rb b/spec/functional/resource/dsc_resource_spec.rb
index 3491bb6bbe..8f5ba5fd9e 100644
--- a/spec/functional/resource/dsc_resource_spec.rb
+++ b/spec/functional/resource/dsc_resource_spec.rb
@@ -46,7 +46,8 @@ describe Chef::Resource::DscResource, :windows_powershell_dsc_only do
it "raises an exception if the resource is not found" do
new_resource.resource "thisdoesnotexist"
expect { new_resource.run_action(:run) }.to raise_error(
- Chef::Exceptions::ResourceNotFound)
+ Chef::Exceptions::ResourceNotFound
+ )
end
end
diff --git a/spec/functional/resource/dsc_script_spec.rb b/spec/functional/resource/dsc_script_spec.rb
index 0808927000..224141c0f8 100644
--- a/spec/functional/resource/dsc_script_spec.rb
+++ b/spec/functional/resource/dsc_script_spec.rb
@@ -184,8 +184,8 @@ describe Chef::Resource::DscScript, :windows_powershell_dsc_only do
end
let(:dsc_environment_env_var_name) { "dsc_test_cwd" }
- let(:dsc_environment_no_fail_not_etc_directory) { "#{ENV['systemroot']}\\system32" }
- let(:dsc_environment_fail_etc_directory) { "#{ENV['systemroot']}\\system32\\drivers\\etc" }
+ let(:dsc_environment_no_fail_not_etc_directory) { "#{ENV["systemroot"]}\\system32" }
+ let(:dsc_environment_fail_etc_directory) { "#{ENV["systemroot"]}\\system32\\drivers\\etc" }
let(:exception_message_signature) { "LL927-LL928" }
let(:dsc_environment_config) do
<<~EOH
@@ -349,9 +349,7 @@ describe Chef::Resource::DscScript, :windows_powershell_dsc_only do
let(:config_param_section) { config_params }
let(:config_flags) { { "#{dsc_user_prefix_param_name}": (dsc_user_prefix).to_s, "#{dsc_user_suffix_param_name}": (dsc_user_suffix).to_s } }
it "does not directly contain the user name" do
- configuration_script_content = ::File.open(dsc_test_resource.command) do |file|
- file.read
- end
+ configuration_script_content = ::File.open(dsc_test_resource.command, &:read)
expect(configuration_script_content.include?(dsc_user)).to be(false)
end
it_behaves_like "a dsc_script with configuration data"
@@ -361,9 +359,7 @@ describe Chef::Resource::DscScript, :windows_powershell_dsc_only do
let(:dsc_user_code) { dsc_user_env_code }
it "does not directly contain the user name" do
- configuration_script_content = ::File.open(dsc_test_resource.command) do |file|
- file.read
- end
+ configuration_script_content = ::File.open(dsc_test_resource.command, &:read)
expect(configuration_script_content.include?(dsc_user)).to be(false)
end
it_behaves_like "a dsc_script with configuration data"
@@ -464,7 +460,7 @@ describe Chef::Resource::DscScript, :windows_powershell_dsc_only do
User dsctestusercreate
{
UserName = '#{dsc_user}'
- Password = #{r.ps_credential('jf9a8m49jrajf4#')}
+ Password = #{r.ps_credential("jf9a8m49jrajf4#")}
Ensure = "Present"
}
EOF
diff --git a/spec/functional/resource/group_spec.rb b/spec/functional/resource/group_spec.rb
index efa089ca2e..5b34ad92d0 100644
--- a/spec/functional/resource/group_spec.rb
+++ b/spec/functional/resource/group_spec.rb
@@ -1,7 +1,7 @@
#
# Author:: Chirag Jog (<chirag@clogeny.com>)
# Author:: Siddheshwar More (<siddheshwar.more@clogeny.com>)
-# Copyright:: Copyright 2013-2018, Chef Software Inc.
+# Copyright:: Copyright 2013-2019, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -96,7 +96,7 @@ describe Chef::Resource::Group, :requires_root_or_running_windows do
end
def create_user(username, uid = nil)
- if ! windows_domain_user?(username)
+ unless windows_domain_user?(username)
user_to_create = user(username)
user_to_create.uid(uid) if uid
user_to_create.run_action(:create)
@@ -105,7 +105,7 @@ describe Chef::Resource::Group, :requires_root_or_running_windows do
end
def remove_user(username)
- if ! windows_domain_user?(username)
+ unless windows_domain_user?(username)
u = user(username)
u.manage_home false # jekins hosts throw mail spool file not owned by user if we use manage_home true
u.run_action(:remove)
@@ -152,7 +152,7 @@ describe Chef::Resource::Group, :requires_root_or_running_windows do
let(:excluded_members) { [] }
it "should raise an error" do
- expect { group_resource.run_action(tested_action) }.to raise_error()
+ expect { group_resource.run_action(tested_action) }.to raise_error
end
end
@@ -162,7 +162,7 @@ describe Chef::Resource::Group, :requires_root_or_running_windows do
end
it "should raise an error" do
- expect { group_resource.run_action(tested_action) }.to raise_error()
+ expect { group_resource.run_action(tested_action) }.to raise_error
end
end
end
@@ -333,10 +333,11 @@ describe Chef::Resource::Group, :requires_root_or_running_windows do
describe "when group name is length 256", :windows_only do
let!(:group_name) do
- "theoldmanwalkingdownthestreetalwayshadagood\
-smileonhisfacetheoldmanwalkingdownthestreetalwayshadagoodsmileonhisface\
-theoldmanwalkingdownthestreetalwayshadagoodsmileonhisfacetheoldmanwalking\
-downthestreetalwayshadagoodsmileonhisfacetheoldmanwalkingdownthestree" end
+ "theoldmanwalkingdownthestreetalwayshadagood"\
+ "smileonhisfacetheoldmanwalkingdownthestreetalwayshadagoodsmileonhisface"\
+ "theoldmanwalkingdownthestreetalwayshadagoodsmileonhisfacetheoldmanwalking"\
+ "downthestreetalwayshadagoodsmileonhisfacetheoldmanwalkingdownthestree"
+ end
it "should create a group" do
group_resource.run_action(:create)
@@ -359,10 +360,11 @@ downthestreetalwayshadagoodsmileonhisfacetheoldmanwalkingdownthestree" end
# for group name > 256, Windows 2016 returns "The parameter is incorrect"
context "group create action: when group name length is more than 256", :windows_only do
let!(:group_name) do
- "theoldmanwalkingdownthestreetalwayshadagood\
-smileonhisfacetheoldmanwalkingdownthestreetalwayshadagoodsmileonhisface\
-theoldmanwalkingdownthestreetalwayshadagoodsmileonhisfacetheoldmanwalking\
-downthestreetalwayshadagoodsmileonhisfacetheoldmanwalkingdownthestreeQQQQQQ" end
+ "theoldmanwalkingdownthestreetalwayshadagood"\
+ "smileonhisfacetheoldmanwalkingdownthestreetalwayshadagoodsmileonhisface"\
+ "theoldmanwalkingdownthestreetalwayshadagoodsmileonhisfacetheoldmanwalking"\
+ "downthestreetalwayshadagoodsmileonhisfacetheoldmanwalkingdownthestreeQQQQQQ"
+ end
it "should not create a group" do
expect { group_resource.run_action(:create) }.to raise_error(ArgumentError)
diff --git a/spec/functional/resource/link_spec.rb b/spec/functional/resource/link_spec.rb
index d86a904098..4593dc1971 100644
--- a/spec/functional/resource/link_spec.rb
+++ b/spec/functional/resource/link_spec.rb
@@ -133,9 +133,9 @@ describe Chef::Resource::Link do
end
def get_sid(value)
- if value.kind_of?(String)
+ if value.is_a?(String)
Chef::ReservedNames::Win32::Security::SID.from_account(value)
- elsif value.kind_of?(Chef::ReservedNames::Win32::Security::SID)
+ elsif value.is_a?(Chef::ReservedNames::Win32::Security::SID)
value
else
raise "Must specify username or SID: #{value}"
diff --git a/spec/functional/resource/locale_spec.rb b/spec/functional/resource/locale_spec.rb
index 83dfc2d007..0103df305b 100644
--- a/spec/functional/resource/locale_spec.rb
+++ b/spec/functional/resource/locale_spec.rb
@@ -61,18 +61,18 @@ describe Chef::Resource::Locale, :requires_root do
context "Unsets system variable" do
it "when LC var is not given" do
- resource.lc_env()
+ resource.lc_env
resource.run_action(:update)
unsets_system_locale("LC_MESSAGES=en_US")
end
it "when lang is not given" do
- resource.lang()
+ resource.lang
resource.run_action(:update)
unsets_system_locale("LANG=en_US")
end
it "when both lang & LC vars are not given" do
- resource.lang()
- resource.lc_env()
+ resource.lang
+ resource.lc_env
resource.run_action(:update)
unsets_system_locale("LANG=en_US", "LC_TIME=en_IN")
sets_system_locale("")
diff --git a/spec/functional/resource/mount_spec.rb b/spec/functional/resource/mount_spec.rb
index f6c7f91bcd..6dd9f54412 100644
--- a/spec/functional/resource/mount_spec.rb
+++ b/spec/functional/resource/mount_spec.rb
@@ -73,7 +73,7 @@ describe Chef::Resource::Mount, :requires_root, :skip_travis, external: include_
def mount_should_exist(mount_point, device, fstype = nil, options = nil)
validation_cmd = "mount | grep #{mount_point} | grep #{device} "
validation_cmd << " | grep #{fstype} " unless fstype.nil?
- validation_cmd << " | grep #{options.join(',')} " unless options.nil? || options.empty?
+ validation_cmd << " | grep #{options.join(",")} " unless options.nil? || options.empty?
expect(shell_out(validation_cmd).exitstatus).to eq(0)
end
diff --git a/spec/functional/resource/powershell_script_spec.rb b/spec/functional/resource/powershell_script_spec.rb
index 850c273a6c..74ece0d33c 100644
--- a/spec/functional/resource/powershell_script_spec.rb
+++ b/spec/functional/resource/powershell_script_spec.rb
@@ -28,13 +28,13 @@ describe Chef::Resource::WindowsScript::PowershellScript, :windows_only do
it_behaves_like "a Windows script running on Windows"
- let(:successful_executable_script_content) { "#{ENV['SystemRoot']}\\system32\\attrib.exe $env:systemroot" }
- let(:failed_executable_script_content) { "#{ENV['SystemRoot']}\\system32\\attrib.exe /badargument" }
+ let(:successful_executable_script_content) { "#{ENV["SystemRoot"]}\\system32\\attrib.exe $env:systemroot" }
+ let(:failed_executable_script_content) { "#{ENV["SystemRoot"]}\\system32\\attrib.exe /badargument" }
let(:processor_architecture_script_content) { "echo $env:PROCESSOR_ARCHITECTURE" }
let(:native_architecture_script_content) { "echo $env:PROCESSOR_ARCHITECTUREW6432" }
let(:cmdlet_exit_code_not_found_content) { "get-item '.\\thisdoesnotexist'" }
let(:cmdlet_exit_code_success_content) { "get-item ." }
- let(:windows_process_exit_code_success_content) { "#{ENV['SystemRoot']}\\system32\\attrib.exe $env:systemroot" }
+ let(:windows_process_exit_code_success_content) { "#{ENV["SystemRoot"]}\\system32\\attrib.exe $env:systemroot" }
let(:windows_process_exit_code_not_found_content) { "findstr /notavalidswitch" }
let(:arbitrary_nonzero_process_exit_code) { 4193 }
let(:arbitrary_nonzero_process_exit_code_content) { "exit #{arbitrary_nonzero_process_exit_code}" }
@@ -479,26 +479,26 @@ describe Chef::Resource::WindowsScript::PowershellScript, :windows_only do
end
it "evaluates a not_if block using the cwd guard parameter" do
- custom_cwd = "#{ENV['SystemRoot']}\\system32\\drivers\\etc"
+ custom_cwd = "#{ENV["SystemRoot"]}\\system32\\drivers\\etc"
resource.not_if "exit ! [int32]($pwd.path -eq '#{custom_cwd}')", cwd: custom_cwd
expect(resource.should_skip?(:run)).to be_truthy
end
it "evaluates an only_if block using the cwd guard parameter" do
- custom_cwd = "#{ENV['SystemRoot']}\\system32\\drivers\\etc"
+ custom_cwd = "#{ENV["SystemRoot"]}\\system32\\drivers\\etc"
resource.only_if "exit ! [int32]($pwd.path -eq '#{custom_cwd}')", cwd: custom_cwd
expect(resource.should_skip?(:run)).to be_falsey
end
it "inherits cwd from the parent resource for only_if" do
- custom_cwd = "#{ENV['SystemRoot']}\\system32\\drivers\\etc"
+ custom_cwd = "#{ENV["SystemRoot"]}\\system32\\drivers\\etc"
resource.cwd custom_cwd
resource.only_if "exit ! [int32]($pwd.path -eq '#{custom_cwd}')"
expect(resource.should_skip?(:run)).to be_falsey
end
it "inherits cwd from the parent resource for not_if" do
- custom_cwd = "#{ENV['SystemRoot']}\\system32\\drivers\\etc"
+ custom_cwd = "#{ENV["SystemRoot"]}\\system32\\drivers\\etc"
resource.cwd custom_cwd
resource.not_if "exit ! [int32]($pwd.path -eq '#{custom_cwd}')"
expect(resource.should_skip?(:run)).to be_truthy
@@ -590,7 +590,8 @@ describe Chef::Resource::WindowsScript::PowershellScript, :windows_only do
resource.only_if "$true", architecture: :i386
expect { resource.run_action(:run) }.to raise_error(
Chef::Exceptions::Win32ArchitectureIncorrect,
- /cannot execute script with requested architecture 'i386' on Windows Nano Server/)
+ /cannot execute script with requested architecture 'i386' on Windows Nano Server/
+ )
end
end
end
diff --git a/spec/functional/resource/reboot_spec.rb b/spec/functional/resource/reboot_spec.rb
index 3b8e3efe8a..5489dc1c72 100644
--- a/spec/functional/resource/reboot_spec.rb
+++ b/spec/functional/resource/reboot_spec.rb
@@ -45,7 +45,7 @@ describe Chef::Resource::Reboot do
shared_context "testing run context modification" do
def test_reboot_action(resource)
reboot_info = resource.run_context.reboot_info
- expect(reboot_info.keys.sort).to eq([:delay_mins, :reason, :requested_by, :timestamp])
+ expect(reboot_info.keys.sort).to eq(%i{delay_mins reason requested_by timestamp})
expect(reboot_info[:delay_mins]).to eq(expected[:delay_mins])
expect(reboot_info[:reason]).to eq(expected[:reason])
expect(reboot_info[:requested_by]).to eq(expected[:requested_by])
diff --git a/spec/functional/resource/remote_file_spec.rb b/spec/functional/resource/remote_file_spec.rb
index 44a7a46d68..ffa0364d1d 100644
--- a/spec/functional/resource/remote_file_spec.rb
+++ b/spec/functional/resource/remote_file_spec.rb
@@ -134,7 +134,7 @@ describe Chef::Resource::RemoteFile do
let(:smb_file_local_file_name) { "smb_file.txt" }
let(:smb_file_local_path) { File.join( smb_share_root_directory, smb_file_local_file_name ) }
let(:smb_share_name) { "chef_smb_test" }
- let(:smb_remote_path) { File.join("//#{ENV['COMPUTERNAME']}", smb_share_name, smb_file_local_file_name).gsub(/\//, "\\") }
+ let(:smb_remote_path) { File.join("//#{ENV["COMPUTERNAME"]}", smb_share_name, smb_file_local_file_name).gsub(%r{/}, "\\") }
let(:smb_file_content) { "hellofun" }
let(:local_destination_path) { File.join(Dir.tmpdir, make_tmpname("chef_remote_file")) }
let(:windows_current_user) { ENV["USERNAME"] }
@@ -155,7 +155,7 @@ describe Chef::Resource::RemoteFile do
before do
shell_out("net.exe share #{smb_share_name} /delete")
File.write(smb_file_local_path, smb_file_content )
- shell_out!("net.exe share #{smb_share_name}=\"#{smb_share_root_directory.gsub(/\//, '\\')}\" /grant:\"authenticated users\",read")
+ shell_out!("net.exe share #{smb_share_name}=\"#{smb_share_root_directory.gsub(%r{/}, '\\')}\" /grant:\"authenticated users\",read")
end
after do
diff --git a/spec/functional/resource/template_spec.rb b/spec/functional/resource/template_spec.rb
index 679ffe661a..feef97dd27 100644
--- a/spec/functional/resource/template_spec.rb
+++ b/spec/functional/resource/template_spec.rb
@@ -21,7 +21,7 @@ require "spec_helper"
describe Chef::Resource::Template do
def binread(file)
- File.open(file, "rb") { |f| f.read }
+ File.open(file, "rb", &:read)
end
include_context Chef::Resource::File
diff --git a/spec/functional/resource/user/windows_spec.rb b/spec/functional/resource/user/windows_spec.rb
index 3a5535f194..6bab270f56 100644
--- a/spec/functional/resource/user/windows_spec.rb
+++ b/spec/functional/resource/user/windows_spec.rb
@@ -47,13 +47,13 @@ describe Chef::Provider::User::Windows, :windows_only do
end
def backup_secedit_policy
- backup_command = "secedit /export /cfg #{ENV['TEMP']}\\secedit_restore.inf /areas SECURITYPOLICY"
+ backup_command = "secedit /export /cfg #{ENV["TEMP"]}\\secedit_restore.inf /areas SECURITYPOLICY"
shell_out(backup_command)
end
def restore_secedit_policy
security_database = "C:\\windows\\security\\database\\seceditnew.sdb"
- restore_command = "secedit /configure /db #{security_database} /cfg #{ENV['TEMP']}\\secedit_restore.inf /areas SECURITYPOLICY"
+ restore_command = "secedit /configure /db #{security_database} /cfg #{ENV["TEMP"]}\\secedit_restore.inf /areas SECURITYPOLICY"
shell_out(restore_command)
end
diff --git a/spec/functional/resource/windows_certificate_spec.rb b/spec/functional/resource/windows_certificate_spec.rb
index 79b3cd890b..9b79de6a77 100644
--- a/spec/functional/resource/windows_certificate_spec.rb
+++ b/spec/functional/resource/windows_certificate_spec.rb
@@ -81,9 +81,9 @@ describe Chef::Resource::WindowsCertificate, :windows_only, :appveyor_only do
# Byepassing the validation so that we may create a custom store
allow_any_instance_of(Chef::Mixin::ParamsValidate)
- .to receive(:_pv_equal_to)
- .with(opts, key, to_be)
- .and_return(true)
+ .to receive(:_pv_equal_to)
+ .with(opts, key, to_be)
+ .and_return(true)
# Creating a custom store for the testing
create_store(store)
diff --git a/spec/functional/resource/windows_service_spec.rb b/spec/functional/resource/windows_service_spec.rb
index f422ac21d6..999b235df1 100644
--- a/spec/functional/resource/windows_service_spec.rb
+++ b/spec/functional/resource/windows_service_spec.rb
@@ -24,7 +24,7 @@ describe Chef::Resource::WindowsService, :windows_only, :system_windows_service_
include_context "using Win32::Service"
let(:username) { "service_spec_user" }
- let(:qualified_username) { "#{ENV['COMPUTERNAME']}\\#{username}" }
+ let(:qualified_username) { "#{ENV["COMPUTERNAME"]}\\#{username}" }
let(:password) { "1a2b3c4X!&narf" }
let(:user_resource) do
@@ -36,7 +36,7 @@ describe Chef::Resource::WindowsService, :windows_only, :system_windows_service_
end
let(:global_service_file_path) do
- "#{ENV['WINDIR']}\\temp\\#{File.basename(test_service[:service_file_path])}"
+ "#{ENV["WINDIR"]}\\temp\\#{File.basename(test_service[:service_file_path])}"
end
let(:service_params) do
@@ -59,7 +59,7 @@ describe Chef::Resource::WindowsService, :windows_only, :system_windows_service_
let(:service_resource) do
r = Chef::Resource::WindowsService.new(service_params[:service_name], run_context)
- [:run_as_user, :run_as_password].each { |prop| r.send(prop, service_params[prop]) }
+ %i{run_as_user run_as_password}.each { |prop| r.send(prop, service_params[prop]) }
r
end
diff --git a/spec/functional/run_lock_spec.rb b/spec/functional/run_lock_spec.rb
index 49972360ef..d9a8bd2d0e 100644
--- a/spec/functional/run_lock_spec.rb
+++ b/spec/functional/run_lock_spec.rb
@@ -334,6 +334,7 @@ describe Chef::RunLock do
loop do
line = readline_nonblock(read_from_process)
break if line.nil?
+
event, time = line.split("@")
example.log_event("#{name}.last_event got #{event}")
example.log_event("[#{name}] #{event}", time.strip)
@@ -346,7 +347,7 @@ describe Chef::RunLock do
example.log_event("#{name}.run_to(#{to_event.inspect})")
# Start the process if it's not started
- start if !pid
+ start unless pid
# Tell the process what to stop at (also means it can go)
write_to_process.print "#{to_event}\n"
@@ -370,7 +371,7 @@ describe Chef::RunLock do
def run_to_completion
example.log_event("#{name}.run_to_completion")
# Start the process if it's not started
- start if !pid
+ start unless pid
# Tell the process to stop at nothing (no blocking)
@write_to_process.print "nothing\n"
diff --git a/spec/functional/util/powershell/cmdlet_spec.rb b/spec/functional/util/powershell/cmdlet_spec.rb
index 4be021a60b..8ec4fa1366 100644
--- a/spec/functional/util/powershell/cmdlet_spec.rb
+++ b/spec/functional/util/powershell/cmdlet_spec.rb
@@ -29,7 +29,7 @@ describe Chef::Util::Powershell::Cmdlet, :windows_powershell_dsc_only do
let(:invalid_cmdlet) { Chef::Util::Powershell::Cmdlet.new(@node, "get-idontexist", cmd_output_format) }
let(:cmdlet_get_item_requires_switch_or_argument) { Chef::Util::Powershell::Cmdlet.new(@node, "get-item", cmd_output_format, { depth: 2 }) }
let(:cmdlet_alias_requires_switch_or_argument) { Chef::Util::Powershell::Cmdlet.new(@node, "alias", cmd_output_format, { depth: 2 }) }
- let(:etc_directory) { "#{ENV['systemroot']}\\system32\\drivers\\etc" }
+ let(:etc_directory) { "#{ENV["systemroot"]}\\system32\\drivers\\etc" }
let(:architecture_cmdlet) { Chef::Util::Powershell::Cmdlet.new(@node, "$env:PROCESSOR_ARCHITECTURE") }
it "executes a simple process" do
diff --git a/spec/functional/win32/security_spec.rb b/spec/functional/win32/security_spec.rb
index 92ce480d25..a72088a079 100644
--- a/spec/functional/win32/security_spec.rb
+++ b/spec/functional/win32/security_spec.rb
@@ -61,7 +61,8 @@ describe "Chef::Win32::Security", :windows_only do
describe "get_file_security" do
it "should return a security descriptor when called with a path that exists" do
security_descriptor = Chef::ReservedNames::Win32::Security.get_file_security(
- "C:\\Program Files")
+ "C:\\Program Files"
+ )
# Make sure the security descriptor works
expect(security_descriptor.dacl_present?).to be true
end
@@ -70,7 +71,8 @@ describe "Chef::Win32::Security", :windows_only do
describe "access_check" do
let(:security_descriptor) do
Chef::ReservedNames::Win32::Security.get_file_security(
- "C:\\Program Files")
+ "C:\\Program Files"
+ )
end
let(:token_rights) { Chef::ReservedNames::Win32::Security::TOKEN_ALL_ACCESS }
@@ -78,7 +80,8 @@ describe "Chef::Win32::Security", :windows_only do
let(:token) do
Chef::ReservedNames::Win32::Security.open_process_token(
Chef::ReservedNames::Win32::Process.get_current_process,
- token_rights).duplicate_token(:SecurityImpersonation)
+ token_rights
+ ).duplicate_token(:SecurityImpersonation)
end
let(:mapping) do
@@ -102,7 +105,8 @@ describe "Chef::Win32::Security", :windows_only do
let(:token) do
Chef::ReservedNames::Win32::Security.open_process_token(
Chef::ReservedNames::Win32::Process.get_current_process,
- token_rights)
+ token_rights
+ )
end
context "with all rights" do
let(:token_rights) { Chef::ReservedNames::Win32::Security::TOKEN_ALL_ACCESS }
@@ -127,11 +131,12 @@ describe "Chef::Win32::Security", :windows_only do
let(:token) do
Chef::ReservedNames::Win32::Security.open_process_token(
Chef::ReservedNames::Win32::Process.get_current_process,
- token_rights)
+ token_rights
+ )
end
context "when the token is valid" do
- let(:token_elevation_type) { [:TokenElevationTypeDefault, :TokenElevationTypeFull, :TokenElevationTypeLimited] }
+ let(:token_elevation_type) { %i{TokenElevationTypeDefault TokenElevationTypeFull TokenElevationTypeLimited} }
it "returns the token elevation type" do
elevation_type = Chef::ReservedNames::Win32::Security.get_token_information_elevation_type(token)
diff --git a/spec/functional/win32/service_manager_spec.rb b/spec/functional/win32/service_manager_spec.rb
index 8fff73396e..abc8118835 100644
--- a/spec/functional/win32/service_manager_spec.rb
+++ b/spec/functional/win32/service_manager_spec.rb
@@ -43,7 +43,7 @@ describe "Chef::Application::WindowsServiceManager", :windows_only, :system_wind
end
it "throws an error with required missing options" do
- [:service_name, :service_display_name, :service_description, :service_file_path].each do |key|
+ %i{service_name service_display_name service_description service_file_path}.each do |key|
service_def = test_service.dup
service_def.delete(key)
diff --git a/spec/integration/client/client_spec.rb b/spec/integration/client/client_spec.rb
index c2dc740025..68cfd015ab 100644
--- a/spec/integration/client/client_spec.rb
+++ b/spec/integration/client/client_spec.rb
@@ -21,9 +21,7 @@ describe "chef-client" do
# just a normal file
# (expected_content should be uncompressed)
@api.get("/recipes.tgz", 200) do
- File.open(recipes_filename, "rb") do |f|
- f.read
- end
+ File.open(recipes_filename, "rb", &:read)
end
end
@@ -55,19 +53,19 @@ describe "chef-client" do
it "should complete with success" do
file "config/client.rb", <<~EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
EOM
- shell_out!("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", cwd: chef_dir)
+ shell_out!("#{chef_client} -c \"#{path_to("config/client.rb")}\" -o 'x::default'", cwd: chef_dir)
end
it "should complete successfully with --no-listen" do
file "config/client.rb", <<~EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
EOM
- result = shell_out("#{chef_client} --no-listen -c \"#{path_to('config/client.rb')}\" -o 'x::default'", cwd: chef_dir)
+ result = shell_out("#{chef_client} --no-listen -c \"#{path_to("config/client.rb")}\" -o 'x::default'", cwd: chef_dir)
result.error!
end
@@ -108,10 +106,10 @@ describe "chef-client" do
it "should complete with success" do
file "config/client.rb", <<~EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", cwd: chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" -o 'x::default'", cwd: chef_dir)
result.error!
end
@@ -151,34 +149,34 @@ describe "chef-client" do
it "should complete with success even with a client key" do
file "config/client.rb", <<~EOM
local_mode true
- client_key #{path_to('mykey.pem').inspect}
- cookbook_path #{path_to('cookbooks').inspect}
+ client_key #{path_to("mykey.pem").inspect}
+ cookbook_path #{path_to("cookbooks").inspect}
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", cwd: chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" -o 'x::default'", cwd: chef_dir)
result.error!
end
it "should run recipes specified directly on the command line" do
file "config/client.rb", <<~EOM
local_mode true
- client_key #{path_to('mykey.pem').inspect}
- cookbook_path #{path_to('cookbooks').inspect}
+ client_key #{path_to("mykey.pem").inspect}
+ cookbook_path #{path_to("cookbooks").inspect}
EOM
file "arbitrary.rb", <<~EOM
- file #{path_to('tempfile.txt').inspect} do
+ file #{path_to("tempfile.txt").inspect} do
content '1'
end
EOM
file "arbitrary2.rb", <<~EOM
- file #{path_to('tempfile2.txt').inspect} do
+ file #{path_to("tempfile2.txt").inspect} do
content '2'
end
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" #{path_to('arbitrary.rb')} #{path_to('arbitrary2.rb')}", cwd: chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" #{path_to("arbitrary.rb")} #{path_to("arbitrary2.rb")}", cwd: chef_dir)
result.error!
expect(IO.read(path_to("tempfile.txt"))).to eq("1")
@@ -188,17 +186,17 @@ describe "chef-client" do
it "should run recipes specified as relative paths directly on the command line" do
file "config/client.rb", <<~EOM
local_mode true
- client_key #{path_to('mykey.pem').inspect}
- cookbook_path #{path_to('cookbooks').inspect}
+ client_key #{path_to("mykey.pem").inspect}
+ cookbook_path #{path_to("cookbooks").inspect}
EOM
file "arbitrary.rb", <<~EOM
- file #{path_to('tempfile.txt').inspect} do
+ file #{path_to("tempfile.txt").inspect} do
content '1'
end
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" arbitrary.rb", cwd: path_to(""))
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" arbitrary.rb", cwd: path_to(""))
result.error!
expect(IO.read(path_to("tempfile.txt"))).to eq("1")
@@ -207,8 +205,8 @@ describe "chef-client" do
it "should run recipes specified directly on the command line AFTER recipes in the run list" do
file "config/client.rb", <<~EOM
local_mode true
- client_key #{path_to('mykey.pem').inspect}
- cookbook_path #{path_to('cookbooks').inspect}
+ client_key #{path_to("mykey.pem").inspect}
+ cookbook_path #{path_to("cookbooks").inspect}
EOM
file "cookbooks/x/recipes/constant_definition.rb", <<~EOM
@@ -218,12 +216,12 @@ describe "chef-client" do
EOM
file "arbitrary.rb", <<~EOM
- file #{path_to('tempfile.txt').inspect} do
+ file #{path_to("tempfile.txt").inspect} do
content ::Blah::THECONSTANT
end
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o x::constant_definition arbitrary.rb", cwd: path_to(""))
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" -o x::constant_definition arbitrary.rb", cwd: path_to(""))
result.error!
expect(IO.read(path_to("tempfile.txt"))).to eq("1")
@@ -232,8 +230,8 @@ describe "chef-client" do
it "should run recipes specified directly on the command line AFTER recipes in the run list (without an override_runlist this time)" do
file "config/client.rb", <<~EOM
local_mode true
- client_key #{path_to('mykey.pem').inspect}
- cookbook_path #{path_to('cookbooks').inspect}
+ client_key #{path_to("mykey.pem").inspect}
+ cookbook_path #{path_to("cookbooks").inspect}
EOM
file "config/dna.json", <<~EOM
@@ -249,12 +247,12 @@ describe "chef-client" do
EOM
file "arbitrary.rb", <<~EOM
- file #{path_to('tempfile.txt').inspect} do
+ file #{path_to("tempfile.txt").inspect} do
content ::Blah::THECONSTANT
end
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -j \"#{path_to('config/dna.json')}\" arbitrary.rb", cwd: path_to(""))
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" -j \"#{path_to("config/dna.json")}\" arbitrary.rb", cwd: path_to(""))
result.error!
expect(IO.read(path_to("tempfile.txt"))).to eq("1")
@@ -263,8 +261,8 @@ describe "chef-client" do
it "an override_runlist of an empty string should allow a recipe specified directly on the command line to be the only one run" do
file "config/client.rb", <<~EOM
local_mode true
- client_key #{path_to('mykey.pem').inspect}
- cookbook_path #{path_to('cookbooks').inspect}
+ client_key #{path_to("mykey.pem").inspect}
+ cookbook_path #{path_to("cookbooks").inspect}
class ::Blah
THECONSTANT = "1"
end
@@ -284,12 +282,12 @@ describe "chef-client" do
file "arbitrary.rb", <<~EOM
raise "this test failed" unless ::Blah::THECONSTANT == "1"
- file #{path_to('tempfile.txt').inspect} do
+ file #{path_to("tempfile.txt").inspect} do
content ::Blah::THECONSTANT
end
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -j \"#{path_to('config/dna.json')}\" -o \"\" arbitrary.rb", cwd: path_to(""))
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" -j \"#{path_to("config/dna.json")}\" -o \"\" arbitrary.rb", cwd: path_to(""))
result.error!
expect(IO.read(path_to("tempfile.txt"))).to eq("1")
@@ -300,30 +298,30 @@ describe "chef-client" do
it "should complete with success when passed the -z flag" do
file "config/client.rb", <<~EOM
chef_server_url 'http://omg.com/blah'
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' -z", cwd: chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" -o 'x::default' -z", cwd: chef_dir)
result.error!
end
it "should complete with success when passed the --local-mode flag" do
file "config/client.rb", <<~EOM
chef_server_url 'http://omg.com/blah'
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --local-mode", cwd: chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" -o 'x::default' --local-mode", cwd: chef_dir)
result.error!
end
it "should not print SSL warnings when running in local-mode" do
file "config/client.rb", <<~EOM
chef_server_url 'http://omg.com/blah'
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --local-mode", cwd: chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" -o 'x::default' --local-mode", cwd: chef_dir)
expect(result.stdout).not_to include("SSL validation of HTTPS requests is disabled.")
result.error!
end
@@ -331,20 +329,20 @@ describe "chef-client" do
it "should complete with success when passed -z and --chef-zero-port" do
file "config/client.rb", <<~EOM
chef_server_url 'http://omg.com/blah'
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' -z", cwd: chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" -o 'x::default' -z", cwd: chef_dir)
result.error!
end
it "should complete with success when setting the run list with -r" do
file "config/client.rb", <<~EOM
chef_server_url 'http://omg.com/blah'
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -r 'x::default' -z -l info", cwd: chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" -r 'x::default' -z -l info", cwd: chef_dir)
expect(result.stdout).not_to include("Overridden Run List")
expect(result.stdout).to include("Run List is [recipe[x::default]]")
result.error!
@@ -353,9 +351,9 @@ describe "chef-client" do
it "should complete with success when using --profile-ruby and output a profile file", :not_supported_on_aix do
file "config/client.rb", <<~EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
EOM
- result = shell_out!("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' -z --profile-ruby", cwd: chef_dir)
+ result = shell_out!("#{chef_client} -c \"#{path_to("config/client.rb")}\" -o 'x::default' -z --profile-ruby", cwd: chef_dir)
result.error!
expect(File.exist?(path_to("config/local-mode-cache/cache/graph_profile.out"))).to be true
end
@@ -363,9 +361,9 @@ describe "chef-client" do
it "doesn't produce a profile when --profile-ruby is not present" do
file "config/client.rb", <<~EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
EOM
- result = shell_out!("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' -z", cwd: chef_dir)
+ result = shell_out!("#{chef_client} -c \"#{path_to("config/client.rb")}\" -o 'x::default' -z", cwd: chef_dir)
result.error!
expect(File.exist?(path_to("config/local-mode-cache/cache/graph_profile.out"))).to be false
end
@@ -381,11 +379,11 @@ describe "chef-client" do
EOM
file "config/client.rb", <<~EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
EOM
end
it "should fail the chef client run" do
- command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", cwd: chef_dir)
+ command = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" -o 'x::default' --no-fork", cwd: chef_dir)
expect(command.exitstatus).to eql(1)
expect(command.stdout).to match(/Chef::Exceptions::CookbookChefVersionMismatch/)
end
@@ -406,12 +404,12 @@ describe "chef-client" do
EOM
file "config/client.rb", <<-EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
EOM
end
it "the cheffish DSL is loaded lazily" do
- command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", cwd: chef_dir)
+ command = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" -o 'x::default' --no-fork", cwd: chef_dir)
expect(command.exitstatus).to eql(0)
end
end
@@ -437,7 +435,7 @@ describe "chef-client" do
it "should output each deprecation warning only once, at the end of the run" do
file "config/client.rb", <<~EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
# Mimick what happens when you are on the console
formatters << :doc
log_level :warn
@@ -445,7 +443,7 @@ describe "chef-client" do
ENV.delete("CHEF_TREAT_DEPRECATION_WARNINGS_AS_ERRORS")
- result = shell_out!("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", cwd: chef_dir)
+ result = shell_out!("#{chef_client} -c \"#{path_to("config/client.rb")}\" -o 'x::default'", cwd: chef_dir)
expect(result.error?).to be_falsey
# Search to the end of the client run in the output
@@ -460,7 +458,7 @@ describe "chef-client" do
when_the_repository "has a cookbook that deploys a file" do
before do
file "cookbooks/x/recipes/default.rb", <<~RECIPE
- cookbook_file #{path_to('tempfile.txt').inspect} do
+ cookbook_file #{path_to("tempfile.txt").inspect} do
source "my_file"
end
RECIPE
@@ -476,9 +474,9 @@ describe "chef-client" do
file "config/client.rb", <<~EOM
no_lazy_load #{lazy}
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
EOM
- result = shell_out("#{chef_client} -l debug -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", cwd: chef_dir)
+ result = shell_out("#{chef_client} -l debug -c \"#{path_to("config/client.rb")}\" -o 'x::default' --no-fork", cwd: chef_dir)
result.error!
expect(IO.read(path_to("tempfile.txt")).strip).to eq("this is my file")
@@ -490,7 +488,7 @@ describe "chef-client" do
when_the_repository "has a cookbook with an ohai plugin" do
before do
file "cookbooks/x/recipes/default.rb", <<~RECIPE
- file #{path_to('tempfile.txt').inspect} do
+ file #{path_to("tempfile.txt").inspect} do
content node["english"]["version"]
end
RECIPE
@@ -508,12 +506,12 @@ describe "chef-client" do
file "config/client.rb", <<~EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
EOM
end
it "should run the ohai plugin" do
- result = shell_out("#{chef_client} -l debug -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", cwd: chef_dir)
+ result = shell_out("#{chef_client} -l debug -c \"#{path_to("config/client.rb")}\" -o 'x::default' --no-fork", cwd: chef_dir)
result.error!
expect(IO.read(path_to("tempfile.txt"))).to eq("2014")
@@ -536,7 +534,7 @@ describe "chef-client" do
file "config/client.rb", <<~EOM
chef_repo_path "#{tmp_dir}"
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --recipe-url=http://localhost:9000/recipes.tgz -o 'x::default' -z", cwd: tmp_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --recipe-url=http://localhost:9000/recipes.tgz -o 'x::default' -z", cwd: tmp_dir)
result.error!
end
@@ -569,17 +567,17 @@ describe "chef-client" do
file "config/client.rb", <<~EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
EOM
end
it "the chef client run should succeed" do
- command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", cwd: chef_dir)
+ command = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" -o 'x::default' --no-fork", cwd: chef_dir)
command.error!
end
it "a chef-solo run should succeed" do
- command = shell_out("#{chef_solo} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", cwd: chef_dir)
+ command = shell_out("#{chef_solo} -c \"#{path_to("config/client.rb")}\" -o 'x::default' --no-fork", cwd: chef_dir)
command.error!
end
end
@@ -593,30 +591,30 @@ describe "chef-client" do
EOM
file "config/client.rb", <<~EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
EOM
end
it "a chef client run should not log to info by default" do
- command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", cwd: chef_dir)
+ command = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" -o 'x::default' --no-fork", cwd: chef_dir)
command.error!
expect(command.stdout).not_to include("INFO")
end
it "a chef client run to a pipe should not log to info by default" do
- command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork | tee #{path_to('chefrun.out')}", cwd: chef_dir)
+ command = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" -o 'x::default' --no-fork | tee #{path_to("chefrun.out")}", cwd: chef_dir)
command.error!
expect(command.stdout).not_to include("INFO")
end
it "a chef solo run should not log to info by default" do
- command = shell_out("#{chef_solo} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", cwd: chef_dir)
+ command = shell_out("#{chef_solo} -c \"#{path_to("config/client.rb")}\" -o 'x::default' --no-fork", cwd: chef_dir)
command.error!
expect(command.stdout).not_to include("INFO")
end
it "a chef solo run to a pipe should not log to info by default" do
- command = shell_out("#{chef_solo} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork | tee #{path_to('chefrun.out')}", cwd: chef_dir)
+ command = shell_out("#{chef_solo} -c \"#{path_to("config/client.rb")}\" -o 'x::default' --no-fork | tee #{path_to("chefrun.out")}", cwd: chef_dir)
command.error!
expect(command.stdout).not_to include("INFO")
end
@@ -629,42 +627,42 @@ EOM
EOM
file "config/client.rb", <<~EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
EOM
end
it "chef-client runs by default with no supervisor" do
- command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", cwd: chef_dir)
+ command = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" -o 'x::default'", cwd: chef_dir)
command.error!
expect(command.stdout).to include("NOFORK")
end
it "chef-solo runs by default with no supervisor" do
- command = shell_out("#{chef_solo} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", cwd: chef_dir)
+ command = shell_out("#{chef_solo} -c \"#{path_to("config/client.rb")}\" -o 'x::default'", cwd: chef_dir)
command.error!
expect(command.stdout).to include("NOFORK")
end
it "chef-client --no-fork does not fork" do
- command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", cwd: chef_dir)
+ command = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" -o 'x::default' --no-fork", cwd: chef_dir)
command.error!
expect(command.stdout).to include("NOFORK")
end
it "chef-solo --no-fork does not fork" do
- command = shell_out("#{chef_solo} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", cwd: chef_dir)
+ command = shell_out("#{chef_solo} -c \"#{path_to("config/client.rb")}\" -o 'x::default' --no-fork", cwd: chef_dir)
command.error!
expect(command.stdout).to include("NOFORK")
end
it "chef-client with --fork uses a supervisor" do
- command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --fork", cwd: chef_dir)
+ command = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" -o 'x::default' --fork", cwd: chef_dir)
command.error!
expect(command.stdout).to include("WITHFORK")
end
it "chef-solo with --fork uses a supervisor" do
- command = shell_out("#{chef_solo} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --fork", cwd: chef_dir)
+ command = shell_out("#{chef_solo} -c \"#{path_to("config/client.rb")}\" -o 'x::default' --fork", cwd: chef_dir)
command.error!
expect(command.stdout).to include("WITHFORK")
end
@@ -677,19 +675,19 @@ EOM
EOM
file "config/client.rb", <<~EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
client_fork true
EOM
end
it "chef-client uses a supervisor" do
- command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", cwd: chef_dir)
+ command = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" -o 'x::default'", cwd: chef_dir)
command.error!
expect(command.stdout).to include("WITHFORK")
end
it "chef-solo uses a supervisor" do
- command = shell_out("#{chef_solo} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", cwd: chef_dir)
+ command = shell_out("#{chef_solo} -c \"#{path_to("config/client.rb")}\" -o 'x::default'", cwd: chef_dir)
command.error!
expect(command.stdout).to include("WITHFORK")
end
@@ -702,19 +700,19 @@ EOM
EOM
file "config/client.rb", <<~EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
client_fork false
EOM
end
it "chef-client uses a supervisor" do
- command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", cwd: chef_dir)
+ command = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" -o 'x::default'", cwd: chef_dir)
command.error!
expect(command.stdout).to include("NOFORK")
end
it "chef-solo uses a supervisor" do
- command = shell_out("#{chef_solo} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", cwd: chef_dir)
+ command = shell_out("#{chef_solo} -c \"#{path_to("config/client.rb")}\" -o 'x::default'", cwd: chef_dir)
command.error!
expect(command.stdout).to include("NOFORK")
end
diff --git a/spec/integration/client/exit_code_spec.rb b/spec/integration/client/exit_code_spec.rb
index ff48d69527..37999ab431 100644
--- a/spec/integration/client/exit_code_spec.rb
+++ b/spec/integration/client/exit_code_spec.rb
@@ -30,12 +30,12 @@ describe "chef-client" do
def setup_client_rb
file "config/client.rb", <<~EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
EOM
end
def run_chef_client_and_expect_exit_code(exit_code)
- shell_out!("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default'",
+ shell_out!("#{chef_client} -c \"#{path_to("config/client.rb")}\" -o 'x::default'",
cwd: chef_dir,
returns: [exit_code])
end
diff --git a/spec/integration/client/ipv6_spec.rb b/spec/integration/client/ipv6_spec.rb
index b97eb4e8b4..2d16786334 100644
--- a/spec/integration/client/ipv6_spec.rb
+++ b/spec/integration/client/ipv6_spec.rb
@@ -63,7 +63,7 @@ describe "chef-client" do
let(:basic_config_file) do
<<~END_CLIENT_RB
chef_server_url "http://[::1]:8900"
- validation_key '#{path_to('config/validator.pem')}'
+ validation_key '#{path_to("config/validator.pem")}'
cache_path '#{cache_path}'
client_key '#{cache_path}/client.pem'
END_CLIENT_RB
@@ -75,7 +75,7 @@ describe "chef-client" do
let(:chef_dir) { File.join(File.dirname(__FILE__), "..", "..", "..", "bin") }
- let(:chef_client_cmd) { %Q{bundle exec chef-client --minimal-ohai -c "#{path_to('config/client.rb')}" -lwarn} }
+ let(:chef_client_cmd) { %Q{bundle exec chef-client --minimal-ohai -c "#{path_to("config/client.rb")}" -lwarn} }
after do
FileUtils.rm_rf(cache_path)
diff --git a/spec/integration/knife/chef_fs_data_store_spec.rb b/spec/integration/knife/chef_fs_data_store_spec.rb
index abd4f129a1..58ca5121c5 100644
--- a/spec/integration/knife/chef_fs_data_store_spec.rb
+++ b/spec/integration/knife/chef_fs_data_store_spec.rb
@@ -185,12 +185,12 @@ describe "ChefFSDataStore tests", :workstation do
end
it "knife raw -z -i empty.json -m PUT /clients/x" do
- knife("raw -z -i #{path_to('empty.json')} -m PUT /clients/x").should_succeed( /"x"/ )
+ knife("raw -z -i #{path_to("empty.json")} -m PUT /clients/x").should_succeed( /"x"/ )
knife("list --local /clients").should_succeed "/clients/x.json\n"
end
it "knife cookbook upload works" do
- knife("cookbook upload -z --cookbook-path #{path_to('cookbooks_to_upload')} x").should_succeed stderr: <<~EOM
+ knife("cookbook upload -z --cookbook-path #{path_to("cookbooks_to_upload")} x").should_succeed stderr: <<~EOM
Uploading x [1.0.0]
Uploaded 1 cookbook.
EOM
@@ -198,28 +198,28 @@ describe "ChefFSDataStore tests", :workstation do
end
it "knife raw -z -i empty.json -m PUT /data/x/y" do
- knife("raw -z -i #{path_to('empty.json')} -m PUT /data/x/y").should_succeed( /"y"/ )
+ knife("raw -z -i #{path_to("empty.json")} -m PUT /data/x/y").should_succeed( /"y"/ )
knife("list --local -Rfp /data_bags").should_succeed "/data_bags/x/\n/data_bags/x/y.json\n"
end
it "knife raw -z -i empty.json -m PUT /environments/x" do
- knife("raw -z -i #{path_to('empty.json')} -m PUT /environments/x").should_succeed( /"x"/ )
+ knife("raw -z -i #{path_to("empty.json")} -m PUT /environments/x").should_succeed( /"x"/ )
knife("list --local /environments").should_succeed "/environments/x.json\n"
end
it "knife raw -z -i dummynode.json -m PUT /nodes/x" do
- knife("raw -z -i #{path_to('dummynode.json')} -m PUT /nodes/x").should_succeed( /"x"/ )
+ knife("raw -z -i #{path_to("dummynode.json")} -m PUT /nodes/x").should_succeed( /"x"/ )
knife("list --local /nodes").should_succeed "/nodes/x.json\n"
knife("show -z /nodes/x.json --verbose").should_succeed(/"bar"/)
end
it "knife raw -z -i empty.json -m PUT /roles/x" do
- knife("raw -z -i #{path_to('empty.json')} -m PUT /roles/x").should_succeed( /"x"/ )
+ knife("raw -z -i #{path_to("empty.json")} -m PUT /roles/x").should_succeed( /"x"/ )
knife("list --local /roles").should_succeed "/roles/x.json\n"
end
it "After knife raw -z -i rolestuff.json -m PUT /roles/x, the output is pretty" do
- knife("raw -z -i #{path_to('rolestuff.json')} -m PUT /roles/x").should_succeed( /"x"/ )
+ knife("raw -z -i #{path_to("rolestuff.json")} -m PUT /roles/x").should_succeed( /"x"/ )
expect(IO.read(path_to("roles/x.json"))).to eq <<~EOM.strip
{
"name": "x",
@@ -242,12 +242,12 @@ describe "ChefFSDataStore tests", :workstation do
end
it "knife raw -z -i empty.json -m POST /clients" do
- knife("raw -z -i #{path_to('empty.json')} -m POST /clients").should_succeed( /uri/ )
+ knife("raw -z -i #{path_to("empty.json")} -m POST /clients").should_succeed( /uri/ )
knife("list --local /clients").should_succeed "/clients/z.json\n"
end
it "knife cookbook upload works" do
- knife("cookbook upload -z --cookbook-path #{path_to('cookbooks_to_upload')} z").should_succeed stderr: <<~EOM
+ knife("cookbook upload -z --cookbook-path #{path_to("cookbooks_to_upload")} z").should_succeed stderr: <<~EOM
Uploading z [1.0.0]
Uploaded 1 cookbook.
EOM
@@ -255,34 +255,34 @@ describe "ChefFSDataStore tests", :workstation do
end
it "knife raw -z -i empty.json -m POST /data" do
- knife("raw -z -i #{path_to('empty.json')} -m POST /data").should_succeed( /uri/ )
+ knife("raw -z -i #{path_to("empty.json")} -m POST /data").should_succeed( /uri/ )
knife("list --local -Rfp /data_bags").should_succeed "/data_bags/z/\n"
end
it "knife raw -z -i empty.json -m POST /data/x" do
- knife("raw -z -i #{path_to('empty_x.json')} -m POST /data").should_succeed( /uri/ )
- knife("raw -z -i #{path_to('empty_id.json')} -m POST /data/x").should_succeed( /"z"/ )
+ knife("raw -z -i #{path_to("empty_x.json")} -m POST /data").should_succeed( /uri/ )
+ knife("raw -z -i #{path_to("empty_id.json")} -m POST /data/x").should_succeed( /"z"/ )
knife("list --local -Rfp /data_bags").should_succeed "/data_bags/x/\n/data_bags/x/z.json\n"
end
it "knife raw -z -i empty.json -m POST /environments" do
- knife("raw -z -i #{path_to('empty.json')} -m POST /environments").should_succeed( /uri/ )
+ knife("raw -z -i #{path_to("empty.json")} -m POST /environments").should_succeed( /uri/ )
knife("list --local /environments").should_succeed "/environments/z.json\n"
end
it "knife raw -z -i dummynode.json -m POST /nodes" do
- knife("raw -z -i #{path_to('dummynode.json')} -m POST /nodes").should_succeed( /uri/ )
+ knife("raw -z -i #{path_to("dummynode.json")} -m POST /nodes").should_succeed( /uri/ )
knife("list --local /nodes").should_succeed "/nodes/z.json\n"
knife("show -z /nodes/z.json").should_succeed(/"bar"/)
end
it "knife raw -z -i empty.json -m POST /roles" do
- knife("raw -z -i #{path_to('empty.json')} -m POST /roles").should_succeed( /uri/ )
+ knife("raw -z -i #{path_to("empty.json")} -m POST /roles").should_succeed( /uri/ )
knife("list --local /roles").should_succeed "/roles/z.json\n"
end
it "After knife raw -z -i rolestuff.json -m POST /roles, the output is pretty" do
- knife("raw -z -i #{path_to('rolestuff.json')} -m POST /roles").should_succeed( /uri/ )
+ knife("raw -z -i #{path_to("rolestuff.json")} -m POST /roles").should_succeed( /uri/ )
expect(IO.read(path_to("roles/x.json"))).to eq <<~EOM.strip
{
"name": "x",
@@ -388,23 +388,23 @@ describe "ChefFSDataStore tests", :workstation do
end
it "knife raw -z -i empty.json -m PUT /clients/x fails with 404" do
- knife("raw -z -i #{path_to('empty.json')} -m PUT /clients/x").should_fail( /404/ )
+ knife("raw -z -i #{path_to("empty.json")} -m PUT /clients/x").should_fail( /404/ )
end
it "knife raw -z -i empty.json -m PUT /data/x/y fails with 404" do
- knife("raw -z -i #{path_to('empty.json')} -m PUT /data/x/y").should_fail( /404/ )
+ knife("raw -z -i #{path_to("empty.json")} -m PUT /data/x/y").should_fail( /404/ )
end
it "knife raw -z -i empty.json -m PUT /environments/x fails with 404" do
- knife("raw -z -i #{path_to('empty.json')} -m PUT /environments/x").should_fail( /404/ )
+ knife("raw -z -i #{path_to("empty.json")} -m PUT /environments/x").should_fail( /404/ )
end
it "knife raw -z -i empty.json -m PUT /nodes/x fails with 404" do
- knife("raw -z -i #{path_to('empty.json')} -m PUT /nodes/x").should_fail( /404/ )
+ knife("raw -z -i #{path_to("empty.json")} -m PUT /nodes/x").should_fail( /404/ )
end
it "knife raw -z -i empty.json -m PUT /roles/x fails with 404" do
- knife("raw -z -i #{path_to('empty.json')} -m PUT /roles/x").should_fail( /404/ )
+ knife("raw -z -i #{path_to("empty.json")} -m PUT /roles/x").should_fail( /404/ )
end
end
@@ -485,12 +485,12 @@ describe "ChefFSDataStore tests", :workstation do
end
it "knife raw -z -i empty.json -m PUT /users/x" do
- knife("raw -z -i #{path_to('empty.json')} -m PUT /users/x").should_succeed( /"x"/ )
+ knife("raw -z -i #{path_to("empty.json")} -m PUT /users/x").should_succeed( /"x"/ )
knife("list --local /users").should_succeed "/users/x.json\n"
end
it "After knife raw -z -i rolestuff.json -m PUT /roles/x, the output is pretty" do
- knife("raw -z -i #{path_to('rolestuff.json')} -m PUT /roles/x").should_succeed( /"x"/ )
+ knife("raw -z -i #{path_to("rolestuff.json")} -m PUT /roles/x").should_succeed( /"x"/ )
expect(IO.read(path_to("roles/x.json"))).to eq <<~EOM.strip
{
"name": "x",
@@ -513,7 +513,7 @@ describe "ChefFSDataStore tests", :workstation do
end
it "knife raw -z -i empty.json -m POST /users" do
- knife("raw -z -i #{path_to('empty.json')} -m POST /users").should_succeed( /uri/ )
+ knife("raw -z -i #{path_to("empty.json")} -m POST /users").should_succeed( /uri/ )
knife("list --local /users").should_succeed "/users/z.json\n"
end
end
@@ -548,7 +548,7 @@ describe "ChefFSDataStore tests", :workstation do
end
it "knife raw -z -i empty.json -m PUT /users/x fails with 404" do
- knife("raw -z -i #{path_to('empty.json')} -m PUT /users/x").should_fail( /404/ )
+ knife("raw -z -i #{path_to("empty.json")} -m PUT /users/x").should_fail( /404/ )
end
end
end
diff --git a/spec/integration/knife/chef_repo_path_spec.rb b/spec/integration/knife/chef_repo_path_spec.rb
index 4a133b0181..919741f930 100644
--- a/spec/integration/knife/chef_repo_path_spec.rb
+++ b/spec/integration/knife/chef_repo_path_spec.rb
@@ -59,7 +59,7 @@ describe "chef_repo_path tests", :workstation do
it "knife list --local -Rfp --chef-repo-path chef_repo2 / grabs chef_repo2 stuff" do
Chef::Config.delete(:chef_repo_path)
- knife("list --local -Rfp --chef-repo-path #{path_to('chef_repo2')} /").should_succeed <<~EOM
+ knife("list --local -Rfp --chef-repo-path #{path_to("chef_repo2")} /").should_succeed <<~EOM
/clients/
/clients/client3.json
/cookbooks/
@@ -81,7 +81,7 @@ describe "chef_repo_path tests", :workstation do
it "knife list --local -Rfp --chef-repo-path chef_r~1 / grabs chef_repo2 stuff", :windows_only do
Chef::Config.delete(:chef_repo_path)
- knife("list --local -Rfp --chef-repo-path #{path_to('chef_r~1')} /").should_succeed <<~EOM
+ knife("list --local -Rfp --chef-repo-path #{path_to("chef_r~1")} /").should_succeed <<~EOM
/clients/
/clients/client3.json
/cookbooks/
@@ -103,7 +103,7 @@ describe "chef_repo_path tests", :workstation do
it "knife list --local -Rfp --chef-repo-path chef_r~1 / grabs chef_repo2 stuff", :windows_only do
Chef::Config.delete(:chef_repo_path)
- knife("list -z -Rfp --chef-repo-path #{path_to('chef_r~1')} /").should_succeed <<~EOM
+ knife("list -z -Rfp --chef-repo-path #{path_to("chef_r~1")} /").should_succeed <<~EOM
/acls/
/acls/clients/
/acls/clients/client3.json
@@ -157,7 +157,7 @@ describe "chef_repo_path tests", :workstation do
end
it "knife list --local -Rfp --chef-repo-path chef_repo2 / grabs chef_repo2 stuff" do
- knife("list --local -Rfp --chef-repo-path #{path_to('chef_repo2')} /").should_succeed <<~EOM
+ knife("list --local -Rfp --chef-repo-path #{path_to("chef_repo2")} /").should_succeed <<~EOM
/clients/
/clients/client3.json
/cookbooks/
diff --git a/spec/integration/knife/config_get_spec.rb b/spec/integration/knife/config_get_spec.rb
index f34d096051..98fefd729f 100644
--- a/spec/integration/knife/config_get_spec.rb
+++ b/spec/integration/knife/config_get_spec.rb
@@ -143,7 +143,7 @@ describe "knife config get", :workstation do
let(:cmd_args) { %w{node_name client_key} }
before { file(".chef/credentials", "[default]\nclient_name = \"three\"\nclient_key = \"three.pem\"") }
- it { is_expected.to match(/^client_key:\s+\S*\/.chef\/three.pem\nnode_name:\s+three\Z/) }
+ it { is_expected.to match(%r{^client_key:\s+\S*/.chef/three.pem\nnode_name:\s+three\Z}) }
end
context "with a dotted argument" do
diff --git a/spec/integration/knife/config_list_profiles_spec.rb b/spec/integration/knife/config_list_profiles_spec.rb
index 32846f9999..044b50b5be 100644
--- a/spec/integration/knife/config_list_profiles_spec.rb
+++ b/spec/integration/knife/config_list_profiles_spec.rb
@@ -183,6 +183,7 @@ describe "knife config list-profiles", :workstation do
{ "profile" => "default", "active" => true, "client_name" => "testuser", "client_key" => path_to(".chef/testkey.pem"), "server_url" => "https://example.com/organizations/testorg" },
{ "profile" => "prod", "active" => false, "client_name" => "testuser", "client_key" => path_to(".chef/testkey.pem"), "server_url" => "https://example.com/organizations/prod" },
{ "profile" => "qa", "active" => false, "client_name" => "qauser", "client_key" => path_to("src/qauser.pem"), "server_url" => "https://example.com/organizations/testorg" },
- ] }
+ ]
+ }
end
end
diff --git a/spec/integration/knife/cookbook_api_ipv6_spec.rb b/spec/integration/knife/cookbook_api_ipv6_spec.rb
index a7e3709276..c615d8de7a 100644
--- a/spec/integration/knife/cookbook_api_ipv6_spec.rb
+++ b/spec/integration/knife/cookbook_api_ipv6_spec.rb
@@ -77,7 +77,7 @@ describe "Knife cookbook API integration with IPv6", :workstation, :not_supporte
<<~END_CLIENT_RB
chef_server_url "http://[::1]:8900"
syntax_check_cache_path '#{cache_path}'
- client_key '#{path_to('config/knifeuser.pem')}'
+ client_key '#{path_to("config/knifeuser.pem")}'
node_name 'whoisthisis'
cookbook_path '#{CHEF_SPEC_DATA}/cookbooks'
END_CLIENT_RB
diff --git a/spec/integration/knife/cookbook_download_spec.rb b/spec/integration/knife/cookbook_download_spec.rb
index 3fe801b64c..538c06802b 100644
--- a/spec/integration/knife/cookbook_download_spec.rb
+++ b/spec/integration/knife/cookbook_download_spec.rb
@@ -65,7 +65,7 @@ describe "knife cookbook download", :workstation do
Downloading root_files
Cookbook downloaded to #{tmpdir}/x-1.0.1
EOM
-)
+ )
end
end
end
diff --git a/spec/integration/knife/diff_spec.rb b/spec/integration/knife/diff_spec.rb
index cd08ebdcbd..87cbd1559d 100644
--- a/spec/integration/knife/diff_spec.rb
+++ b/spec/integration/knife/diff_spec.rb
@@ -309,7 +309,7 @@ describe "knife diff", :workstation do
when_the_repository "has an environment with bad JSON" do
before { file "environments/x.json", "{" }
it "knife diff reports an error and does a textual diff" do
- error_text = "WARN: Parse error reading #{path_to('environments/x.json')} as JSON: parse error: premature EOF"
+ error_text = "WARN: Parse error reading #{path_to("environments/x.json")} as JSON: parse error: premature EOF"
error_match = Regexp.new(Regexp.escape(error_text))
knife("diff /environments/x.json").should_succeed(/- "name": "x"/, stderr: error_match)
end
@@ -592,7 +592,7 @@ describe "knife diff", :workstation do
when_the_repository "has an environment with bad JSON" do
before { file "environments/x.json", "{" }
it "knife diff reports an error and does a textual diff" do
- error_text = "WARN: Parse error reading #{path_to('environments/x.json')} as JSON: parse error: premature EOF"
+ error_text = "WARN: Parse error reading #{path_to("environments/x.json")} as JSON: parse error: premature EOF"
error_match = Regexp.new(Regexp.escape(error_text))
knife("diff /environments/x.json").should_succeed(/- "name": "x"/, stderr: error_match)
end
diff --git a/spec/integration/knife/download_spec.rb b/spec/integration/knife/download_spec.rb
index 93d804b749..77f6d3890e 100644
--- a/spec/integration/knife/download_spec.rb
+++ b/spec/integration/knife/download_spec.rb
@@ -561,7 +561,7 @@ describe "knife download", :workstation do
end
it "knife download succeeds" do
warning = <<~EOH
- WARN: Parse error reading #{path_to('environments/x.json')} as JSON: parse error: premature EOF
+ WARN: Parse error reading #{path_to("environments/x.json")} as JSON: parse error: premature EOF
{
(right here) ------^
diff --git a/spec/integration/knife/redirection_spec.rb b/spec/integration/knife/redirection_spec.rb
index d387b10e3b..5e5ef27b9a 100644
--- a/spec/integration/knife/redirection_spec.rb
+++ b/spec/integration/knife/redirection_spec.rb
@@ -34,7 +34,7 @@ describe "redirection", :workstation do
real_chef_server_url = Chef::Config.chef_server_url
Chef::Config.chef_server_url = "http://localhost:9018"
app = lambda do |env|
- [302, { "Content-Type" => "text", "Location" => "#{real_chef_server_url}#{env['PATH_INFO']}" }, ["302 found"] ]
+ [302, { "Content-Type" => "text", "Location" => "#{real_chef_server_url}#{env["PATH_INFO"]}" }, ["302 found"] ]
end
@redirector_server_thread = start_app_server(app, 9018)
end
diff --git a/spec/integration/knife/upload_spec.rb b/spec/integration/knife/upload_spec.rb
index 766f91ab25..1a6ddceb17 100644
--- a/spec/integration/knife/upload_spec.rb
+++ b/spec/integration/knife/upload_spec.rb
@@ -636,7 +636,7 @@ EOM
it "knife upload tries and fails" do
error1 = <<~EOH
- WARN: Parse error reading #{path_to('environments/x.json')} as JSON: parse error: premature EOF
+ WARN: Parse error reading #{path_to("environments/x.json")} as JSON: parse error: premature EOF
{
(right here) ------^
@@ -646,7 +646,7 @@ EOM
EOH
warn = <<~EOH
- WARN: Parse error reading #{path_to('environments/x.json')} as JSON: parse error: premature EOF
+ WARN: Parse error reading #{path_to("environments/x.json")} as JSON: parse error: premature EOF
{
(right here) ------^
diff --git a/spec/integration/recipes/accumulator_spec.rb b/spec/integration/recipes/accumulator_spec.rb
index d19d8637bb..98e3581071 100644
--- a/spec/integration/recipes/accumulator_spec.rb
+++ b/spec/integration/recipes/accumulator_spec.rb
@@ -115,11 +115,11 @@ describe "Accumulators" do
it "should complete with success" do
file "config/client.rb", <<-EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
result.error!
# runs only a single template resource (in the outer run context, as a delayed resource)
expect(result.stdout.scan(/template\S+ action create/).size).to eql(1)
@@ -217,11 +217,11 @@ describe "Accumulators" do
it "should complete with success" do
file "config/client.rb", <<-EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
result.error!
# runs only a single template resource (in the outer run context, as a delayed resource)
expect(result.stdout.scan(/template\S+ action create/).size).to eql(1)
diff --git a/spec/integration/recipes/lwrp_inline_resources_spec.rb b/spec/integration/recipes/lwrp_inline_resources_spec.rb
index 6bc857df48..b96fa1d67d 100644
--- a/spec/integration/recipes/lwrp_inline_resources_spec.rb
+++ b/spec/integration/recipes/lwrp_inline_resources_spec.rb
@@ -53,7 +53,7 @@ describe "LWRPs with inline resources" do
action :fiddle do
file PATH do
content new_resource.content
- action [:create, :delete]
+ action %i{create delete}
end
end
end
@@ -147,12 +147,12 @@ describe "LWRPs with inline resources" do
it "should complete with success" do
file "config/client.rb", <<~EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
- actual = result.stdout.lines.map { |l| l.chomp }.join("\n")
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
+ actual = result.stdout.lines.map(&:chomp).join("\n")
expected = <<EOM
* x_my_machine[me] action create
* x_do_nothing[a] action create (up to date)
@@ -163,7 +163,7 @@ describe "LWRPs with inline resources" do
* x_do_nothing[b] action create (up to date)
(up to date)
EOM
- expected = expected.lines.map { |l| l.chomp }.join("\n")
+ expected = expected.lines.map(&:chomp).join("\n")
expect(actual).to include(expected)
result.error!
end
diff --git a/spec/integration/recipes/lwrp_spec.rb b/spec/integration/recipes/lwrp_spec.rb
index ce2861d43b..957c1ea66f 100644
--- a/spec/integration/recipes/lwrp_spec.rb
+++ b/spec/integration/recipes/lwrp_spec.rb
@@ -40,11 +40,11 @@ describe "LWRPs" do
it "should complete with success" do
file "config/client.rb", <<~EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'l-w-r-p::default'", cwd: chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --no-color -F doc -o 'l-w-r-p::default'", cwd: chef_dir)
expect(result.stdout).to match(/\* l_w_r_p_foo\[me\] action create \(up to date\)/)
expect(result.stdout).not_to match(/WARN: You are overriding l_w_r_p_foo/)
result.error!
diff --git a/spec/integration/recipes/notifies_spec.rb b/spec/integration/recipes/notifies_spec.rb
index 860a109e4d..ae534dcad4 100644
--- a/spec/integration/recipes/notifies_spec.rb
+++ b/spec/integration/recipes/notifies_spec.rb
@@ -28,11 +28,11 @@ describe "notifications" do
it "should complete with success" do
file "config/client.rb", <<~EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
# our delayed notification should run at the end of the parent run_context after the baz resource
expect(result.stdout).to match(/\* apt_update\[\] action nothing \(skipped due to action :nothing\)\s+\* log\[foo\] action write\s+\* log\[bar\] action write\s+\* apt_update\[\] action nothing \(skipped due to action :nothing\)/)
result.error!
@@ -69,11 +69,11 @@ describe "notifications" do
it "should complete with success" do
file "config/client.rb", <<~EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
# our delayed notification should run at the end of the parent run_context after the baz resource
expect(result.stdout).to match(/\* log\[bar\] action write\s+\* log\[baz\] action write\s+\* log\[foo\] action write/)
result.error!
@@ -112,11 +112,11 @@ describe "notifications" do
it "should complete with success" do
file "config/client.rb", <<~EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
# our delayed notification should run at the end of the parent run_context after the baz resource
expect(result.stdout).to match(/\* log\[bar\] action write\s+\* log\[baz\] action write\s+\* log\[foo\] action write/)
# and only run once
@@ -159,11 +159,11 @@ describe "notifications" do
it "should complete with success" do
file "config/client.rb", <<~EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
# the delayed notification from the sub-resource is de-duplicated by the notification already in the parent run_context
expect(result.stdout).to match(/\* log\[quux\] action write\s+\* notifying_test\[whatever\] action run\s+\* log\[bar\] action write\s+\* log\[baz\] action write\s+\* log\[foo\] action write\s+\* log\[baz\] action write/)
# and only run once
@@ -193,11 +193,11 @@ describe "notifications" do
it "should complete with success" do
file "config/client.rb", <<~EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
# the delayed notification from the sub-resource is de-duplicated by the notification already in the parent run_context
expect(result.stdout).to match(/\* log\[bar\] action write\s+\* log\[baz\] action write\s+\* log\[foo\] action write/)
# and only run once
@@ -236,11 +236,11 @@ describe "notifications" do
it "should complete with success" do
file "config/client.rb", <<~EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
expect(result.stdout).to match(/\* log\[bar\] action write\s+\* log\[foo\] action write\s+\* log\[baz\] action write/)
result.error!
end
@@ -276,11 +276,11 @@ describe "notifications" do
it "should complete with success" do
file "config/client.rb", <<~EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
expect(result.stdout).to match(/\* log\[bar\] action write\s+\* log\[foo\] action write\s+\* log\[baz\] action write/)
result.error!
end
@@ -313,11 +313,11 @@ describe "notifications" do
it "should complete with success" do
file "config/client.rb", <<~EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
expect(result.stdout).to match(/Chef::Exceptions::ResourceNotFound/)
expect(result.exitstatus).not_to eql(0)
end
@@ -353,11 +353,11 @@ describe "notifications" do
it "should complete with success" do
file "config/client.rb", <<~EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
expect(result.stdout).not_to match(/CHEF-3694/)
result.error!
end
@@ -381,11 +381,11 @@ describe "notifications" do
it "notifying the resource should work" do
file "config/client.rb", <<~EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
expect(result.stdout).to match /\* log\[a, b\] action write/
result.error!
end
diff --git a/spec/integration/recipes/notifying_block_spec.rb b/spec/integration/recipes/notifying_block_spec.rb
index 753e81dadb..465eca97ed 100644
--- a/spec/integration/recipes/notifying_block_spec.rb
+++ b/spec/integration/recipes/notifying_block_spec.rb
@@ -45,7 +45,7 @@ describe "notifying_block" do
end
file "config/client.rb", <<-EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
log_level :warn
EOM
end
@@ -55,7 +55,7 @@ describe "notifying_block" do
# 2. delayed notifications are de-dup'd in the subcontext
# 3. delayed notifications (to resources inside the subcontext) are run at the end of the subcontext
it "should run alpha, beta, gamma, and delta in that order" do
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
expect(result.stdout).to match(/\* log\[alpha\] action write\s+\* log\[beta\] action write\s+\* log\[gamma\] action write\s+Converging 1 resources\s+\* log\[delta\] action write/)
result.error!
end
@@ -94,7 +94,7 @@ describe "notifying_block" do
end
file "config/client.rb", <<-EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
log_level :warn
EOM
end
@@ -103,7 +103,7 @@ describe "notifying_block" do
# 1. notifying block will correctly update wrapping new_resource updated_by_last_action status
# 2. delayed notifications from a subcontext inside a resource will notify resources in their outer run_context
it "should run foo, quux, bar, and baz in that order" do
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
expect(result.stdout).to match(/\* log\[foo\] action write\s+\* log\[quux\] action write\s+\* log\[bar\] action write\s+\* log\[baz\] action write/)
result.error!
end
diff --git a/spec/integration/recipes/provider_choice.rb b/spec/integration/recipes/provider_choice.rb
index 1895d93891..dea58230db 100644
--- a/spec/integration/recipes/provider_choice.rb
+++ b/spec/integration/recipes/provider_choice.rb
@@ -16,8 +16,7 @@ describe "Recipe DSL methods" do
context "And class Chef::Provider::ProviderThingy with no provides" do
before :context do
class Chef::Provider::ProviderThingy < Chef::Provider
- def load_current_resource
- end
+ def load_current_resource; end
def action_create
Chef::Log.warn("hello from #{self.class.name}")
diff --git a/spec/integration/recipes/recipe_dsl_spec.rb b/spec/integration/recipes/recipe_dsl_spec.rb
index 0250786f0e..766752ac13 100644
--- a/spec/integration/recipes/recipe_dsl_spec.rb
+++ b/spec/integration/recipes/recipe_dsl_spec.rb
@@ -28,8 +28,7 @@ describe "Recipe DSL methods" do
Provider
end
class Provider < Chef::Provider
- def load_current_resource
- end
+ def load_current_resource; end
def action_create
BaseThingy.created_name = new_resource.name
@@ -1154,7 +1153,8 @@ describe "Recipe DSL methods" do
def to_s
"MyResource"
end
- end end
+ end
+ end
let(:my_resource) { :"my_resource#{Namer.current_index}" }
let(:blarghle_blarghle_little_star) { :"blarghle_blarghle_little_star#{Namer.current_index}" }
@@ -1340,10 +1340,10 @@ describe "Recipe DSL methods" do
resource_class.new("blah", run_context)
end
it "The actions are part of actions along with :nothing" do
- expect(resource_class.actions).to eq [ :nothing, :create ]
+ expect(resource_class.actions).to eq %i{nothing create}
end
it "The actions are part of allowed_actions along with :nothing" do
- expect(resource.allowed_actions).to eq [ :nothing, :create ]
+ expect(resource.allowed_actions).to eq %i{nothing create}
end
context "and a subclass that declares more actions" do
@@ -1358,14 +1358,14 @@ describe "Recipe DSL methods" do
end
it "The parent class actions are not part of actions" do
- expect(subresource_class.actions).to eq [ :nothing, :delete ]
+ expect(subresource_class.actions).to eq %i{nothing delete}
end
it "The parent class actions are not part of allowed_actions" do
- expect(subresource.allowed_actions).to eq [ :nothing, :delete ]
+ expect(subresource.allowed_actions).to eq %i{nothing delete}
end
it "The parent class actions do not change" do
- expect(resource_class.actions).to eq [ :nothing, :create ]
- expect(resource.allowed_actions).to eq [ :nothing, :create ]
+ expect(resource_class.actions).to eq %i{nothing create}
+ expect(resource.allowed_actions).to eq %i{nothing create}
end
end
end
diff --git a/spec/integration/recipes/remote_directory.rb b/spec/integration/recipes/remote_directory.rb
index 6f67a38fc8..8332fb1b56 100644
--- a/spec/integration/recipes/remote_directory.rb
+++ b/spec/integration/recipes/remote_directory.rb
@@ -22,7 +22,7 @@ describe Chef::Resource::RemoteDirectory do
before do
file "config/client.rb", <<-EOM
local_mode true
- cookbook_path "#{path_to('cookbooks')}"
+ cookbook_path "#{path_to("cookbooks")}"
EOM
directory "cookbooks/test" do
directory "files/default/source_dir" do
@@ -50,7 +50,7 @@ describe Chef::Resource::RemoteDirectory do
end
EOM
end
- shell_out!("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'test::default'", cwd: chef_dir)
+ shell_out!("#{chef_client} -c \"#{path_to("config/client.rb")}\" -o 'test::default'", cwd: chef_dir)
end
def mode_of(path)
diff --git a/spec/integration/solo/solo_spec.rb b/spec/integration/solo/solo_spec.rb
index 0d24269199..451943e225 100644
--- a/spec/integration/solo/solo_spec.rb
+++ b/spec/integration/solo/solo_spec.rb
@@ -27,7 +27,7 @@ describe Chef::Dist::SOLOEXEC do
file "config/solo.rb", <<~EOM
chef_repo_path "#{@repository_dir}"
EOM
- result = shell_out("bundle exec chef-solo -c \"#{path_to('config/solo.rb')}\" -l debug", cwd: chef_dir)
+ result = shell_out("bundle exec chef-solo -c \"#{path_to("config/solo.rb")}\" -l debug", cwd: chef_dir)
result.error!
end
@@ -76,25 +76,25 @@ describe Chef::Dist::SOLOEXEC do
it "should complete with success" do
file "config/solo.rb", <<~EOM
- cookbook_path "#{path_to('cookbooks')}"
- file_cache_path "#{path_to('config/cache')}"
+ cookbook_path "#{path_to("cookbooks")}"
+ file_cache_path "#{path_to("config/cache")}"
EOM
- result = shell_out("#{chef_solo} -c \"#{path_to('config/solo.rb')}\" -o 'x::default' -l debug", cwd: chef_dir)
+ result = shell_out("#{chef_solo} -c \"#{path_to("config/solo.rb")}\" -o 'x::default' -l debug", cwd: chef_dir)
result.error!
expect(result.stdout).to include("ITWORKS")
end
it "should evaluate its node.json file" do
file "config/solo.rb", <<~EOM
- cookbook_path "#{path_to('cookbooks')}"
- file_cache_path "#{path_to('config/cache')}"
+ cookbook_path "#{path_to("cookbooks")}"
+ file_cache_path "#{path_to("config/cache")}"
EOM
file "config/node.json", <<~E
{"run_list":["x::default"]}
E
- result = shell_out("#{chef_solo} -c \"#{path_to('config/solo.rb')}\" -j '#{path_to('config/node.json')}' -l debug", cwd: chef_dir)
+ result = shell_out("#{chef_solo} -c \"#{path_to("config/solo.rb")}\" -j '#{path_to("config/node.json")}' -l debug", cwd: chef_dir)
result.error!
expect(result.stdout).to include("ITWORKS")
end
@@ -112,10 +112,10 @@ describe Chef::Dist::SOLOEXEC do
it "should exit with an error" do
file "config/solo.rb", <<~EOM
- cookbook_path "#{path_to('cookbooks')}"
- file_cache_path "#{path_to('config/cache')}"
+ cookbook_path "#{path_to("cookbooks")}"
+ file_cache_path "#{path_to("config/cache")}"
EOM
- result = shell_out("#{chef_solo} -c \"#{path_to('config/solo.rb')}\" -o 'x::default' -l debug", cwd: chef_dir)
+ result = shell_out("#{chef_solo} -c \"#{path_to("config/solo.rb")}\" -o 'x::default' -l debug", cwd: chef_dir)
expect(result.exitstatus).to eq(0) # For CHEF-5120 this becomes 1
expect(result.stdout).to include("WARN: MissingCookbookDependency")
end
@@ -126,13 +126,13 @@ describe Chef::Dist::SOLOEXEC do
file "cookbooks/x/metadata.rb", cb_metadata("x", "1.0.0", "\nchef_version '~> 999.0'")
file "cookbooks/x/recipes/default.rb", 'puts "ITWORKS"'
file "config/solo.rb", <<~EOM
- cookbook_path "#{path_to('cookbooks')}"
- file_cache_path "#{path_to('config/cache')}"
+ cookbook_path "#{path_to("cookbooks")}"
+ file_cache_path "#{path_to("config/cache")}"
EOM
end
it "should exit with an error" do
- result = shell_out("#{chef_solo} -c \"#{path_to('config/solo.rb')}\" -o 'x::default' -l debug", cwd: chef_dir)
+ result = shell_out("#{chef_solo} -c \"#{path_to("config/solo.rb")}\" -o 'x::default' -l debug", cwd: chef_dir)
expect(result.exitstatus).to eq(1)
expect(result.stdout).to include("Chef::Exceptions::CookbookChefVersionMismatch")
end
@@ -143,13 +143,13 @@ describe Chef::Dist::SOLOEXEC do
file "cookbooks/x/metadata.rb", cb_metadata("x", "1.0.0", "\nohai_version '~> 999.0'")
file "cookbooks/x/recipes/default.rb", 'puts "ITWORKS"'
file "config/solo.rb", <<~EOM
- cookbook_path "#{path_to('cookbooks')}"
- file_cache_path "#{path_to('config/cache')}"
+ cookbook_path "#{path_to("cookbooks")}"
+ file_cache_path "#{path_to("config/cache")}"
EOM
end
it "should exit with an error" do
- result = shell_out("#{chef_solo} -c \"#{path_to('config/solo.rb')}\" -o 'x::default' -l debug", cwd: chef_dir)
+ result = shell_out("#{chef_solo} -c \"#{path_to("config/solo.rb")}\" -o 'x::default' -l debug", cwd: chef_dir)
expect(result.exitstatus).to eq(1)
expect(result.stdout).to include("Chef::Exceptions::CookbookOhaiVersionMismatch")
end
@@ -175,8 +175,8 @@ describe Chef::Dist::SOLOEXEC do
it "while running solo concurrently" do
file "config/solo.rb", <<~EOM
- cookbook_path "#{path_to('cookbooks')}"
- file_cache_path "#{path_to('config/cache')}"
+ cookbook_path "#{path_to("cookbooks")}"
+ file_cache_path "#{path_to("config/cache")}"
EOM
# We have a timeout protection here so that if due to some bug
# run_lock gets stuck we can discover it.
@@ -188,13 +188,13 @@ describe Chef::Dist::SOLOEXEC do
# Instantiate the first chef-solo run
threads << Thread.new do
- s1 = Process.spawn("#{chef_solo} -c \"#{path_to('config/solo.rb')}\" -o 'x::default' -l debug -L #{path_to('logs/runs.log')}", chdir: chef_dir)
+ s1 = Process.spawn("#{chef_solo} -c \"#{path_to("config/solo.rb")}\" -o 'x::default' -l debug -L #{path_to("logs/runs.log")}", chdir: chef_dir)
Process.waitpid(s1)
end
# Instantiate the second chef-solo run
threads << Thread.new do
- s2 = Process.spawn("#{chef_solo} -c \"#{path_to('config/solo.rb')}\" -o 'x::default' -l debug -L #{path_to('logs/runs.log')}", chdir: chef_dir)
+ s2 = Process.spawn("#{chef_solo} -c \"#{path_to("config/solo.rb")}\" -o 'x::default' -l debug -L #{path_to("logs/runs.log")}", chdir: chef_dir)
Process.waitpid(s2)
end
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index adfb262637..96d02cc5d8 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -52,7 +52,7 @@ require "chef/knife"
Dir["lib/chef/knife/**/*.rb"]
.map { |f| f.gsub("lib/", "") }
- .map { |f| f.gsub(%r{\.rb$}, "") }
+ .map { |f| f.gsub(/\.rb$/, "") }
.each { |f| require f }
require "chef/resource_resolver"
@@ -93,7 +93,7 @@ require "spec/support/shared/unit/mock_shellout"
Dir["spec/support/**/*.rb"]
.reject { |f| f =~ %r{^spec/support/platforms} }
.reject { |f| f =~ %r{^spec/support/pedant} }
- .map { |f| f.gsub(%r{.rb$}, "") }
+ .map { |f| f.gsub(/.rb$/, "") }
.map { |f| f.gsub(%r{spec/}, "") }
.each { |f| require f }
@@ -145,7 +145,7 @@ RSpec.configure do |config|
config.filter_run_excluding windows_only: true unless windows?
config.filter_run_excluding not_supported_on_windows: true if windows?
config.filter_run_excluding not_supported_on_macos: true if mac_osx?
- config.filter_run_excluding macos_only: true if !mac_osx?
+ config.filter_run_excluding macos_only: true unless mac_osx?
config.filter_run_excluding not_supported_on_aix: true if aix?
config.filter_run_excluding not_supported_on_solaris: true if solaris?
config.filter_run_excluding not_supported_on_gce: true if gce?
@@ -159,7 +159,7 @@ RSpec.configure do |config|
config.filter_run_excluding ruby64_only: true unless ruby_64bit?
config.filter_run_excluding ruby32_only: true unless ruby_32bit?
config.filter_run_excluding windows_powershell_dsc_only: true unless windows_powershell_dsc?
- config.filter_run_excluding windows_powershell_no_dsc_only: true unless ! windows_powershell_dsc?
+ config.filter_run_excluding windows_powershell_no_dsc_only: true if windows_powershell_dsc?
config.filter_run_excluding windows_domain_joined_only: true unless windows_domain_joined?
config.filter_run_excluding windows_not_domain_joined_only: true if windows_domain_joined?
# We think this line was causing rspec tests to not run on the Jenkins windows
@@ -311,14 +311,11 @@ require "thread"
module WEBrick
module Utils
class TimeoutHandler
- def initialize
- end
+ def initialize; end
- def register(*args)
- end
+ def register(*args); end
- def cancel(*args)
- end
+ def cancel(*args); end
end
end
end
diff --git a/spec/stress/win32/security_spec.rb b/spec/stress/win32/security_spec.rb
index 0280398ad5..8929a2ff74 100644
--- a/spec/stress/win32/security_spec.rb
+++ b/spec/stress/win32/security_spec.rb
@@ -50,7 +50,7 @@ describe "Chef::ReservedNames::Win32::Security", :windows_only do
it "should not leak when retrieving and reading the ACE from a file", :volatile do
expect do
- sids = Chef::ReservedNames::Win32::Security::SecurableObject.new(@monkeyfoo).security_descriptor.dacl.select { |ace| ace.sid }
+ sids = Chef::ReservedNames::Win32::Security::SecurableObject.new(@monkeyfoo).security_descriptor.dacl.select(&:sid)
GC.start
end.not_to leak_memory(warmup: 50, iterations: 100)
end
diff --git a/spec/support/lib/chef/resource/zen_follower.rb b/spec/support/lib/chef/resource/zen_follower.rb
index 84fc71cc99..72dd67ca97 100644
--- a/spec/support/lib/chef/resource/zen_follower.rb
+++ b/spec/support/lib/chef/resource/zen_follower.rb
@@ -25,7 +25,7 @@ class Chef
provides :follower, platform: "zen"
def master(arg = nil)
- if !arg.nil?
+ unless arg.nil?
@master = arg
end
@master
diff --git a/spec/support/lib/chef/resource/zen_master.rb b/spec/support/lib/chef/resource/zen_master.rb
index 9d6e5d46f7..710742a285 100644
--- a/spec/support/lib/chef/resource/zen_master.rb
+++ b/spec/support/lib/chef/resource/zen_master.rb
@@ -30,7 +30,7 @@ class Chef
end
def something(arg = nil)
- if !arg.nil?
+ unless arg.nil?
@something = arg
end
@something
diff --git a/spec/support/mock/platform.rb b/spec/support/mock/platform.rb
index c6670827f9..2cf605c741 100644
--- a/spec/support/mock/platform.rb
+++ b/spec/support/mock/platform.rb
@@ -19,7 +19,7 @@ def platform_mock(platform = :unix)
mock_constants({ "RUBY_PLATFORM" => (platform == :windows ? "i386-mingw32" : "x86_64-darwin11.2.0"),
"File::PATH_SEPARATOR" => (platform == :windows ? ";" : ":"),
"File::ALT_SEPARATOR" => (platform == :windows ? "\\" : nil) }) do
- yield
- end
+ yield
+ end
end
end
diff --git a/spec/support/platform_helpers.rb b/spec/support/platform_helpers.rb
index 02f8c28345..509ca6e71e 100644
--- a/spec/support/platform_helpers.rb
+++ b/spec/support/platform_helpers.rb
@@ -46,6 +46,7 @@ require "wmi-lite/wmi" if windows?
def windows_domain_joined?
return false unless windows?
+
wmi = WmiLite::Wmi.new
computer_system = wmi.first_of("Win32_ComputerSystem")
computer_system["partofdomain"]
@@ -53,11 +54,13 @@ end
def windows_2012r2?
return false unless windows?
+
(host_version && host_version.start_with?("6.3"))
end
def windows_gte_10?
return false unless windows?
+
Gem::Requirement.new(">= 10").satisfied_by?(Gem::Version.new(host_version))
end
@@ -71,6 +74,7 @@ end
def windows_powershell_dsc?
return false unless windows?
+
supports_dsc = false
begin
wmi = WmiLite::Wmi.new("root/microsoft/windows/desiredstateconfiguration")
@@ -88,6 +92,7 @@ end
def windows_user_right?(right)
return false unless windows?
+
require "chef/win32/security"
Chef::ReservedNames::Win32::Security.get_account_right(ENV["USERNAME"]).include?(right)
end
@@ -217,6 +222,7 @@ end
def root?
return false if windows?
+
Process.euid == 0
end
diff --git a/spec/support/platforms/win32/spec_service.rb b/spec/support/platforms/win32/spec_service.rb
index 5548a79afc..2cc4e40298 100644
--- a/spec/support/platforms/win32/spec_service.rb
+++ b/spec/support/platforms/win32/spec_service.rb
@@ -20,12 +20,12 @@ require "win32/daemon"
class SpecService < ::Win32::Daemon
def service_init
- @test_service_file = "#{ENV['TMP']}/spec_service_file"
+ @test_service_file = "#{ENV["TMP"]}/spec_service_file"
end
def service_main(*startup_parameters)
while running?
- if !File.exists?(@test_service_file)
+ unless File.exists?(@test_service_file)
File.open(@test_service_file, "wb") do |f|
f.write("This file is created by SpecService")
end
@@ -39,17 +39,13 @@ class SpecService < ::Win32::Daemon
# Control Signal Callback Methods
################################################################################
- def service_stop
- end
+ def service_stop; end
- def service_pause
- end
+ def service_pause; end
- def service_resume
- end
+ def service_resume; end
- def service_shutdown
- end
+ def service_shutdown; end
end
# To run this file as a service, it must be called as a script from within
diff --git a/spec/support/shared/functional/execute_resource.rb b/spec/support/shared/functional/execute_resource.rb
index 1a14bb38c3..f56479bb49 100644
--- a/spec/support/shared/functional/execute_resource.rb
+++ b/spec/support/shared/functional/execute_resource.rb
@@ -21,7 +21,7 @@ shared_context "a non-admin Windows user" do
let(:windows_nonadmin_user_domain) { ENV["COMPUTERNAME"] }
let(:windows_nonadmin_user_qualified) { "#{windows_nonadmin_user_domain}\\#{windows_nonadmin_user}" }
- let(:temp_profile_path) { "#{ENV['USERPROFILE']}\\..\\cheftesttempuser" }
+ let(:temp_profile_path) { "#{ENV["USERPROFILE"]}\\..\\cheftesttempuser" }
before do
shell_out!("net.exe user /delete #{windows_nonadmin_user}", returns: [0, 2])
@@ -40,7 +40,7 @@ end
shared_context "alternate user identity" do
let(:windows_alternate_user) { "chef%02d%02d%02d" % [Time.now.year % 100, Time.now.month, Time.now.day] }
let(:windows_alternate_user_password) { "lj28;fx3T!x,2" }
- let(:windows_alternate_user_qualified) { "#{ENV['COMPUTERNAME']}\\#{windows_alternate_user}" }
+ let(:windows_alternate_user_qualified) { "#{ENV["COMPUTERNAME"]}\\#{windows_alternate_user}" }
let(:windows_nonadmin_user) { windows_alternate_user }
let(:windows_nonadmin_user_password) { windows_alternate_user_password }
@@ -58,7 +58,7 @@ shared_context "a command that can be executed as an alternate user" do
include Chef::Mixin::ShellOut
before do
- shell_out!("icacls \"#{script_output_dir.gsub(/\//, '\\')}\" /grant \"authenticated users:(F)\"")
+ shell_out!("icacls \"#{script_output_dir.gsub(%r{/}, '\\')}\" /grant \"authenticated users:(F)\"")
end
after do
@@ -73,7 +73,7 @@ shared_examples_for "an execute resource that supports alternate user identity"
include_context "a command that can be executed as an alternate user"
let(:windows_current_user) { ENV["USERNAME"] }
- let(:windows_current_user_qualified) { "#{ENV['USERDOMAIN'] || ENV['COMPUTERNAME']}\\#{windows_current_user}" }
+ let(:windows_current_user_qualified) { "#{ENV["USERDOMAIN"] || ENV["COMPUTERNAME"]}\\#{windows_current_user}" }
let(:resource_identity_command) { "powershell.exe -noprofile -command \"import-module microsoft.powershell.utility;([Security.Principal.WindowsPrincipal]([Security.Principal.WindowsIdentity]::GetCurrent())).identity.name | out-file -encoding ASCII '#{script_output_path}'\"" }
let(:execute_resource) do
diff --git a/spec/support/shared/functional/file_resource.rb b/spec/support/shared/functional/file_resource.rb
index db947614b3..114971641d 100644
--- a/spec/support/shared/functional/file_resource.rb
+++ b/spec/support/shared/functional/file_resource.rb
@@ -392,9 +392,7 @@ shared_examples_for "a configured file resource" do
end
def binread(file)
- content = File.open(file, "rb") do |f|
- f.read
- end
+ content = File.open(file, "rb", &:read)
content.force_encoding(Encoding::BINARY) if "".respond_to?(:force_encoding)
content
end
diff --git a/spec/support/shared/functional/http.rb b/spec/support/shared/functional/http.rb
index 7450f28e35..f006c6a24a 100644
--- a/spec/support/shared/functional/http.rb
+++ b/spec/support/shared/functional/http.rb
@@ -30,9 +30,7 @@ module ChefHTTPShared
end
def binread(file)
- content = File.open(file, "rb") do |f|
- f.read
- end
+ content = File.open(file, "rb", &:read)
content.force_encoding(Encoding::BINARY) if "".respond_to?(:force_encoding)
content
end
@@ -53,25 +51,19 @@ module ChefHTTPShared
# just a normal file
# (expected_content should be uncompressed)
@api.get("/nyan_cat.png", 200) do
- File.open(nyan_uncompressed_filename, "rb") do |f|
- f.read
- end
+ File.open(nyan_uncompressed_filename, "rb", &:read)
end
# this ends in .gz, we do not uncompress it and drop it on the filesystem as a .gz file (the internet often lies)
# (expected_content should be compressed)
@api.get("/nyan_cat.png.gz", 200, nil, { "Content-Type" => "application/gzip", "Content-Encoding" => "gzip" } ) do
- File.open(nyan_compressed_filename, "rb") do |f|
- f.read
- end
+ File.open(nyan_compressed_filename, "rb", &:read)
end
# this is an uncompressed file that was compressed by some mod_gzip-ish webserver thingy, so we will expand it
# (expected_content should be uncompressed)
@api.get("/nyan_cat_compressed.png", 200, nil, { "Content-Type" => "application/gzip", "Content-Encoding" => "gzip" } ) do
- File.open(nyan_compressed_filename, "rb") do |f|
- f.read
- end
+ File.open(nyan_compressed_filename, "rb", &:read)
end
#
@@ -82,12 +74,9 @@ module ChefHTTPShared
@api.get("/nyan_cat_content_length.png", 200, nil,
{
"Content-Length" => nyan_uncompressed_size.to_s,
- }
- ) do
- File.open(nyan_uncompressed_filename, "rb") do |f|
- f.read
+ }) do
+ File.open(nyan_uncompressed_filename, "rb", &:read)
end
- end
# (expected_content should be uncompressed)
@api.get("/nyan_cat_content_length_compressed.png", 200, nil,
@@ -95,12 +84,9 @@ module ChefHTTPShared
"Content-Length" => nyan_compressed_size.to_s,
"Content-Type" => "application/gzip",
"Content-Encoding" => "gzip",
- }
- ) do
- File.open(nyan_compressed_filename, "rb") do |f|
- f.read
+ }) do
+ File.open(nyan_compressed_filename, "rb", &:read)
end
- end
#
# endpoints that simulate truncated downloads (bad content-length header)
@@ -110,12 +96,9 @@ module ChefHTTPShared
@api.get("/nyan_cat_truncated.png", 200, nil,
{
"Content-Length" => (nyan_uncompressed_size + 1).to_s,
- }
- ) do
- File.open(nyan_uncompressed_filename, "rb") do |f|
- f.read
+ }) do
+ File.open(nyan_uncompressed_filename, "rb", &:read)
end
- end
# (expected_content should be uncompressed)
@api.get("/nyan_cat_truncated_compressed.png", 200, nil,
@@ -123,12 +106,9 @@ module ChefHTTPShared
"Content-Length" => (nyan_compressed_size + 1).to_s,
"Content-Type" => "application/gzip",
"Content-Encoding" => "gzip",
- }
- ) do
- File.open(nyan_compressed_filename, "rb") do |f|
- f.read
+ }) do
+ File.open(nyan_compressed_filename, "rb", &:read)
end
- end
#
# in the presence of a transfer-encoding header, we must ignore the content-length (this bad content-length should work)
@@ -139,12 +119,9 @@ module ChefHTTPShared
{
"Content-Length" => (nyan_uncompressed_size + 1).to_s,
"Transfer-Encoding" => "anything",
- }
- ) do
- File.open(nyan_uncompressed_filename, "rb") do |f|
- f.read
+ }) do
+ File.open(nyan_uncompressed_filename, "rb", &:read)
end
- end
#
# 403 with a Content-Length
@@ -152,8 +129,7 @@ module ChefHTTPShared
@api.get("/forbidden", 403, "Forbidden",
{
"Content-Length" => "Forbidden".bytesize.to_s,
- }
- )
+ })
@api.post("/posty", 200, "Hi!")
diff --git a/spec/support/shared/functional/securable_resource.rb b/spec/support/shared/functional/securable_resource.rb
index 18e7243453..010ef27f47 100644
--- a/spec/support/shared/functional/securable_resource.rb
+++ b/spec/support/shared/functional/securable_resource.rb
@@ -89,7 +89,7 @@ shared_context "use Windows permissions", :windows_only do
end
def explicit_aces
- descriptor.dacl.select { |ace| ace.explicit? }
+ descriptor.dacl.select(&:explicit?)
end
def extract_ace_properties(aces)
@@ -314,7 +314,7 @@ shared_examples_for "a securable resource without existing target" do
end
it "sets owner when owner is specified with a \\" do
- resource.owner "#{ENV['COMPUTERNAME']}\\Guest"
+ resource.owner "#{ENV["COMPUTERNAME"]}\\Guest"
resource.run_action(:create)
expect(descriptor.owner).to eq(SID.Guest)
end
@@ -560,16 +560,12 @@ shared_examples_for "a securable resource without existing target" do
# On certain flavors of Windows the default list of ACLs sometimes includes
# non-inherited ACLs. Filter them out here.
- parent_inherited_acls = parent_acls.dacl.collect do |ace|
- ace.inherited?
- end
+ parent_inherited_acls = parent_acls.dacl.collect(&:inherited?)
resource.run_action(:create)
# Similarly filter out the non-inherited ACLs
- resource_inherited_acls = descriptor.dacl.collect do |ace|
- ace.inherited?
- end
+ resource_inherited_acls = descriptor.dacl.collect(&:inherited?)
expect(resource_inherited_acls).to eq(parent_inherited_acls)
end
diff --git a/spec/support/shared/functional/win32_service.rb b/spec/support/shared/functional/win32_service.rb
index a528db4a53..2d14c6cf86 100644
--- a/spec/support/shared/functional/win32_service.rb
+++ b/spec/support/shared/functional/win32_service.rb
@@ -52,6 +52,6 @@ shared_context "using Win32::Service" do
# for the file it creates under SYSTEM temp directory
let(:test_service_file) do
- "#{ENV['SystemDrive']}\\windows\\temp\\spec_service_file"
+ "#{ENV["SystemDrive"]}\\windows\\temp\\spec_service_file"
end
end
diff --git a/spec/support/shared/functional/windows_script.rb b/spec/support/shared/functional/windows_script.rb
index 5eb68952d7..49fd727055 100644
--- a/spec/support/shared/functional/windows_script.rb
+++ b/spec/support/shared/functional/windows_script.rb
@@ -114,7 +114,8 @@ shared_context Chef::Resource::WindowsScript do
resource.only_if resource_guard_command, architecture: guard_architecture
expect { resource.run_action(:run) }.to raise_error(
Chef::Exceptions::Win32ArchitectureIncorrect,
- /cannot execute script with requested architecture 'i386' on Windows Nano Server/)
+ /cannot execute script with requested architecture 'i386' on Windows Nano Server/
+ )
end
end
end
diff --git a/spec/support/shared/integration/app_server_support.rb b/spec/support/shared/integration/app_server_support.rb
index 7f05b14689..317a5a2679 100644
--- a/spec/support/shared/integration/app_server_support.rb
+++ b/spec/support/shared/integration/app_server_support.rb
@@ -27,10 +27,9 @@ module AppServerSupport
Rack::Handler::WEBrick.run(app,
Port: 9018,
AccessLog: [],
- Logger: WEBrick::Log.new(StringIO.new, 7)
- ) do |found_server|
- server = found_server
- end
+ Logger: WEBrick::Log.new(StringIO.new, 7)) do |found_server|
+ server = found_server
+ end
end
Timeout.timeout(30) do
sleep(0.01) until server && server.status == :Running
diff --git a/spec/support/shared/integration/integration_helper.rb b/spec/support/shared/integration/integration_helper.rb
index 5fc9de4de7..6c0eca98be 100644
--- a/spec/support/shared/integration/integration_helper.rb
+++ b/spec/support/shared/integration/integration_helper.rb
@@ -111,6 +111,7 @@ module IntegrationSupport
RSpec.shared_context "with a chef repo" do
before :each do
raise "Can only create one directory per test" if @repository_dir
+
@repository_dir = Dir.mktmpdir("chef_repo")
Chef::Config.chef_repo_path = @repository_dir
%w{client cookbook data_bag environment node role user}.each do |object_name|
diff --git a/spec/support/shared/integration/knife_support.rb b/spec/support/shared/integration/knife_support.rb
index 87ce1bc0b0..07d95f17cc 100644
--- a/spec/support/shared/integration/knife_support.rb
+++ b/spec/support/shared/integration/knife_support.rb
@@ -58,7 +58,7 @@ module KnifeSupport
old_loggers = Chef::Log.loggers
old_log_level = Chef::Log.level
begin
- puts "knife: #{args.join(' ')}" if DEBUG
+ puts "knife: #{args.join(" ")}" if DEBUG
subcommand_class = Chef::Knife.subcommand_class_from(args)
subcommand_class.options = Chef::Application::Knife.options.merge(subcommand_class.options)
subcommand_class.load_deps
@@ -150,7 +150,7 @@ module KnifeSupport
expected[:stderr] = arg
end
end
- expected[:exit_code] = 1 if !expected[:exit_code]
+ expected[:exit_code] = 1 unless expected[:exit_code]
should_result_in(expected)
end
@@ -169,9 +169,9 @@ module KnifeSupport
private
def should_result_in(expected)
- expected[:stdout] = "" if !expected[:stdout]
- expected[:stderr] = "" if !expected[:stderr]
- expected[:exit_code] = 0 if !expected[:exit_code]
+ expected[:stdout] = "" unless expected[:stdout]
+ expected[:stderr] = "" unless expected[:stderr]
+ expected[:exit_code] = 0 unless expected[:exit_code]
# TODO make this go away
stderr_actual = @stderr.sub(/^WARNING: No knife configuration file found\n/, "")
diff --git a/spec/support/shared/unit/application_dot_d.rb b/spec/support/shared/unit/application_dot_d.rb
index b94fa7c184..0f2f06eff8 100644
--- a/spec/support/shared/unit/application_dot_d.rb
+++ b/spec/support/shared/unit/application_dot_d.rb
@@ -33,13 +33,15 @@ shared_examples_for "an application that loads a dot d" do
# make sure that we are correctly globbing.
let(:client_d_dir) do
Chef::Util::PathHelper.cleanpath(
- File.join(File.dirname(__FILE__), "../../../data/client.d_00")) end
+ File.join(File.dirname(__FILE__), "../../../data/client.d_00")
+ )
+ end
it "loads the configuration in order" do
expect(IO).to receive(:read).with(Pathname.new("#{client_d_dir}/00-foo.rb").cleanpath.to_s).and_return("foo 0")
expect(IO).to receive(:read).with(Pathname.new("#{client_d_dir}/01-bar.rb").cleanpath.to_s).and_return("bar 0")
expect(IO).to receive(:read).with(Pathname.new("#{client_d_dir}/02-strings.rb").cleanpath.to_s).and_return("strings 0")
- allow(app).to receive(:apply_config).with(anything(), Chef::Config.platform_specific_path("/etc/chef/client.rb")).and_call_original.ordered
+ allow(app).to receive(:apply_config).with(anything, Chef::Config.platform_specific_path("/etc/chef/client.rb")).and_call_original.ordered
expect(app).to receive(:apply_config).with("foo 0", Pathname.new("#{client_d_dir}/00-foo.rb").cleanpath.to_s).and_call_original.ordered
expect(app).to receive(:apply_config).with("bar 0", Pathname.new("#{client_d_dir}/01-bar.rb").cleanpath.to_s).and_call_original.ordered
expect(app).to receive(:apply_config).with("strings 0", Pathname.new("#{client_d_dir}/02-strings.rb").cleanpath.to_s).and_call_original.ordered
@@ -50,7 +52,9 @@ shared_examples_for "an application that loads a dot d" do
context "when client_d_dir is set to a directory without configuration" do
let(:client_d_dir) do
Chef::Util::PathHelper.cleanpath(
- File.join(File.dirname(__FILE__), "../../data/client.d_01")) end
+ File.join(File.dirname(__FILE__), "../../data/client.d_01")
+ )
+ end
# client.d_01 has a nested folder with a rb file that if
# executed, would raise an exception. If it is executed,
@@ -66,7 +70,9 @@ shared_examples_for "an application that loads a dot d" do
# foo.rb as a directory should be ignored
let(:client_d_dir) do
Chef::Util::PathHelper.cleanpath(
- File.join(File.dirname(__FILE__), "../../data/client.d_02")) end
+ File.join(File.dirname(__FILE__), "../../data/client.d_02")
+ )
+ end
it "does not raise an exception" do
expect { app.reconfigure }.not_to raise_error
diff --git a/spec/support/shared/unit/file_system_support.rb b/spec/support/shared/unit/file_system_support.rb
index 32bdb1456e..957479f149 100644
--- a/spec/support/shared/unit/file_system_support.rb
+++ b/spec/support/shared/unit/file_system_support.rb
@@ -23,9 +23,10 @@ require "chef/chef_fs/file_system/memory/memory_file"
module FileSystemSupport
def memory_fs(pretty_name, value, cannot_be_in_regex = nil)
- if !value.is_a?(Hash)
+ unless value.is_a?(Hash)
raise "memory_fs() must take a Hash"
end
+
dir = Chef::ChefFS::FileSystem::Memory::MemoryRoot.new(pretty_name, cannot_be_in_regex)
value.each do |key, child|
dir.add_child(memory_fs_value(child, key.to_s, dir))
@@ -55,7 +56,7 @@ module FileSystemSupport
def no_blocking_calls_allowed
[ Chef::ChefFS::FileSystem::Memory::MemoryFile, Chef::ChefFS::FileSystem::Memory::MemoryDir ].each do |c|
- [ :children, :exists?, :read ].each do |m|
+ %i{children exists? read}.each do |m|
allow_any_instance_of(c).to receive(m).and_raise("#{m} should not be called")
end
end
diff --git a/spec/support/shared/unit/platform_introspector.rb b/spec/support/shared/unit/platform_introspector.rb
index 7b9cc0f94e..3b07fdd367 100644
--- a/spec/support/shared/unit/platform_introspector.rb
+++ b/spec/support/shared/unit/platform_introspector.rb
@@ -36,14 +36,14 @@ shared_examples_for "a platform introspector" do
@platform_family_hash = {
"debian" => "debian value",
- [:rhel, :fedora] => "redhatty value",
+ %i{rhel fedora} => "redhatty value",
"suse" => "suse value",
:default => "default value",
}
end
it "returns a default value when there is no known platform" do
- node = Hash.new
+ node = {}
expect(platform_introspector.value_for_platform(@platform_hash)).to eq("default")
end
@@ -125,7 +125,7 @@ shared_examples_for "a platform introspector" do
it "returns true if the node is a provided platform and platforms are provided as symbols" do
node.automatic_attrs[:platform] = "ubuntu"
- expect(platform_introspector.platform?([:redhat, :ubuntu])).to eq(true)
+ expect(platform_introspector.platform?(%i{redhat ubuntu})).to eq(true)
end
it "returns true if the node is a provided platform and platforms are provided as strings" do
@@ -143,7 +143,7 @@ shared_examples_for "a platform introspector" do
it "returns true if the node is in a provided platform family and families are provided as symbols" do
node.automatic_attrs[:platform_family] = "debian"
- expect(platform_introspector.platform_family?([:rhel, :debian])).to eq(true)
+ expect(platform_introspector.platform_family?(%i{rhel debian})).to eq(true)
end
it "returns true if the node is a provided platform and platforms are provided as strings" do
@@ -165,24 +165,24 @@ shared_examples_for "a platform introspector" do
describe "when the value is an array" do
before do
@platform_hash = {
- "debian" => { "4.0" => [ :restart, :reload ], "default" => [ :restart, :reload, :status ] },
- "ubuntu" => { "default" => [ :restart, :reload, :status ] },
- "centos" => { "default" => [ :restart, :reload, :status ] },
- "redhat" => { "default" => [ :restart, :reload, :status ] },
- "fedora" => { "default" => [ :restart, :reload, :status ] },
- "default" => { "default" => [:restart, :reload ] } }
+ "debian" => { "4.0" => %i{restart reload}, "default" => %i{restart reload status} },
+ "ubuntu" => { "default" => %i{restart reload status} },
+ "centos" => { "default" => %i{restart reload status} },
+ "redhat" => { "default" => %i{restart reload status} },
+ "fedora" => { "default" => %i{restart reload status} },
+ "default" => { "default" => %i{restart reload} } }
end
it "returns the correct default for a given platform" do
node.automatic_attrs[:platform] = "debian"
node.automatic_attrs[:platform_version] = "9000"
- expect(platform_introspector.value_for_platform(@platform_hash)).to eq([ :restart, :reload, :status ])
+ expect(platform_introspector.value_for_platform(@platform_hash)).to eq(%i{restart reload status})
end
it "returns the correct platform+version specific value " do
node.automatic_attrs[:platform] = "debian"
node.automatic_attrs[:platform_version] = "4.0"
- expect(platform_introspector.value_for_platform(@platform_hash)).to eq([:restart, :reload])
+ expect(platform_introspector.value_for_platform(@platform_hash)).to eq(%i{restart reload})
end
end
diff --git a/spec/support/shared/unit/provider/file.rb b/spec/support/shared/unit/provider/file.rb
index b3039f9be4..2771a371d4 100644
--- a/spec/support/shared/unit/provider/file.rb
+++ b/spec/support/shared/unit/provider/file.rb
@@ -417,7 +417,7 @@ shared_examples_for Chef::Provider::File do
context "when the enclosing directory does not exist" do
before { setup_missing_enclosing_directory }
- [:create, :create_if_missing, :touch].each do |action|
+ %i{create create_if_missing touch}.each do |action|
context "action #{action}" do
it "raises EnclosingDirectoryDoesNotExist" do
expect { provider.run_action(action) }.to raise_error(Chef::Exceptions::EnclosingDirectoryDoesNotExist)
diff --git a/spec/support/shared/unit/script_resource.rb b/spec/support/shared/unit/script_resource.rb
index 5c4f6eecbb..83d7d9dfe6 100644
--- a/spec/support/shared/unit/script_resource.rb
+++ b/spec/support/shared/unit/script_resource.rb
@@ -66,7 +66,7 @@ shared_examples_for "a script resource" do
it "inherits exactly the :cwd, :environment, :group, :path, :user, and :umask attributes from a parent resource class" do
inherited_difference = Chef::Resource::Script.guard_inherited_attributes -
- [:cwd, :environment, :group, :path, :user, :umask ]
+ %i{cwd environment group path user umask}
expect(inherited_difference).to eq([])
end
diff --git a/spec/support/shared/unit/windows_script_resource.rb b/spec/support/shared/unit/windows_script_resource.rb
index 5b559bb83b..29238a3917 100644
--- a/spec/support/shared/unit/windows_script_resource.rb
+++ b/spec/support/shared/unit/windows_script_resource.rb
@@ -25,7 +25,7 @@ shared_examples_for "a Windows script resource" do
before(:each) do
node = Chef::Node.new
- node.default["kernel"] = Hash.new
+ node.default["kernel"] = {}
node.default["kernel"][:machine] = :x86_64.to_s
run_context = Chef::RunContext.new(node, nil, nil)
diff --git a/spec/tiny_server.rb b/spec/tiny_server.rb
index 948bde04f2..46820cbaae 100644
--- a/spec/tiny_server.rb
+++ b/spec/tiny_server.rb
@@ -135,7 +135,7 @@ module TinyServer
if response = response_for_request(env)
response.call
else
- debug_info = { message: "no data matches the request for #{env['REQUEST_URI']}",
+ debug_info = { message: "no data matches the request for #{env["REQUEST_URI"]}",
available_routes: @routes, request: env }
# Uncomment me for glorious debugging
# pp :not_found => debug_info
diff --git a/spec/unit/api_client/registration_spec.rb b/spec/unit/api_client/registration_spec.rb
index 6fd1d4d0e1..3e786c3c02 100644
--- a/spec/unit/api_client/registration_spec.rb
+++ b/spec/unit/api_client/registration_spec.rb
@@ -98,7 +98,7 @@ describe Chef::ApiClient::Registration do
it "has an HTTP client configured with validator credentials" do
expect(registration.http_api).to be_a_kind_of(Chef::ServerAPI)
expect(registration.http_api.options[:client_name]).to eq("test-validator")
- auth = registration.http_api.middlewares.find { |klass| klass.kind_of? Chef::HTTP::Authenticator }
+ auth = registration.http_api.middlewares.find { |klass| klass.is_a? Chef::HTTP::Authenticator }
expect(auth.client_name).to eq("test-validator")
end
diff --git a/spec/unit/api_client_spec.rb b/spec/unit/api_client_spec.rb
index e6b2eec820..f36cbc721d 100644
--- a/spec/unit/api_client_spec.rb
+++ b/spec/unit/api_client_spec.rb
@@ -41,7 +41,7 @@ describe Chef::ApiClient do
end
it "only allows string values for the name" do
- expect { @client.name Hash.new }.to raise_error(ArgumentError)
+ expect { @client.name({}) }.to raise_error(ArgumentError)
end
it "has an admin flag attribute" do
@@ -55,7 +55,7 @@ describe Chef::ApiClient do
it "allows only boolean values for the admin flag" do
expect { @client.admin(false) }.not_to raise_error
- expect { @client.admin(Hash.new) }.to raise_error(ArgumentError)
+ expect { @client.admin({}) }.to raise_error(ArgumentError)
end
it "has a 'validator' flag attribute" do
@@ -69,7 +69,7 @@ describe Chef::ApiClient do
it "allows only boolean values for the 'validator' flag" do
expect { @client.validator(false) }.not_to raise_error
- expect { @client.validator(Hash.new) }.to raise_error(ArgumentError)
+ expect { @client.validator({}) }.to raise_error(ArgumentError)
end
it "has a public key attribute" do
@@ -79,7 +79,7 @@ describe Chef::ApiClient do
it "accepts only String values for the public key" do
expect { @client.public_key "" }.not_to raise_error
- expect { @client.public_key Hash.new }.to raise_error(ArgumentError)
+ expect { @client.public_key({}) }.to raise_error(ArgumentError)
end
it "has a private key attribute" do
@@ -89,7 +89,7 @@ describe Chef::ApiClient do
it "accepts only String values for the private key" do
expect { @client.private_key "" }.not_to raise_error
- expect { @client.private_key Hash.new }.to raise_error(ArgumentError)
+ expect { @client.private_key({}) }.to raise_error(ArgumentError)
end
describe "when serializing to JSON" do
diff --git a/spec/unit/api_client_v1_spec.rb b/spec/unit/api_client_v1_spec.rb
index 6c4e7fe188..3bad466a13 100644
--- a/spec/unit/api_client_v1_spec.rb
+++ b/spec/unit/api_client_v1_spec.rb
@@ -36,7 +36,7 @@ describe Chef::ApiClientV1 do
end
it "only allows string values for the name" do
- expect { @client.name Hash.new }.to raise_error(ArgumentError)
+ expect { @client.name({}) }.to raise_error(ArgumentError)
end
it "has an admin flag attribute" do
@@ -50,7 +50,7 @@ describe Chef::ApiClientV1 do
it "allows only boolean values for the admin flag" do
expect { @client.admin(false) }.not_to raise_error
- expect { @client.admin(Hash.new) }.to raise_error(ArgumentError)
+ expect { @client.admin({}) }.to raise_error(ArgumentError)
end
it "has an create_key flag attribute" do
@@ -64,7 +64,7 @@ describe Chef::ApiClientV1 do
it "allows only boolean values for the create_key flag" do
expect { @client.create_key(false) }.not_to raise_error
- expect { @client.create_key(Hash.new) }.to raise_error(ArgumentError)
+ expect { @client.create_key({}) }.to raise_error(ArgumentError)
end
it "has a 'validator' flag attribute" do
@@ -78,7 +78,7 @@ describe Chef::ApiClientV1 do
it "allows only boolean values for the 'validator' flag" do
expect { @client.validator(false) }.not_to raise_error
- expect { @client.validator(Hash.new) }.to raise_error(ArgumentError)
+ expect { @client.validator({}) }.to raise_error(ArgumentError)
end
it "has a public key attribute" do
@@ -88,7 +88,7 @@ describe Chef::ApiClientV1 do
it "accepts only String values for the public key" do
expect { @client.public_key "" }.not_to raise_error
- expect { @client.public_key Hash.new }.to raise_error(ArgumentError)
+ expect { @client.public_key({}) }.to raise_error(ArgumentError)
end
it "has a private key attribute" do
@@ -98,7 +98,7 @@ describe Chef::ApiClientV1 do
it "accepts only String values for the private key" do
expect { @client.private_key "" }.not_to raise_error
- expect { @client.private_key Hash.new }.to raise_error(ArgumentError)
+ expect { @client.private_key({}) }.to raise_error(ArgumentError)
end
describe "when serializing to JSON" do
diff --git a/spec/unit/application/exit_code_spec.rb b/spec/unit/application/exit_code_spec.rb
index 6800ad0de5..7a02672796 100644
--- a/spec/unit/application/exit_code_spec.rb
+++ b/spec/unit/application/exit_code_spec.rb
@@ -70,7 +70,8 @@ describe Chef::Application::ExitCode do
it "does write a warning on non-standard exit codes" do
expect(Chef::Log).to receive(:warn).with(
- /attempted to exit with a non-standard exit code of 151/)
+ /attempted to exit with a non-standard exit code of 151/
+ )
expect(exit_codes.normalize_exit_code(151)).to eq(1)
end
@@ -79,7 +80,7 @@ describe Chef::Application::ExitCode do
end
it "returns GENERIC_FAILURE when no exit code is specified" do
- expect(exit_codes.normalize_exit_code()).to eq(1)
+ expect(exit_codes.normalize_exit_code).to eq(1)
end
it "returns SIGINT_RECEIVED when a SIGINT is received" do
diff --git a/spec/unit/application/knife_spec.rb b/spec/unit/application/knife_spec.rb
index f8f5560597..ea5083ac15 100644
--- a/spec/unit/application/knife_spec.rb
+++ b/spec/unit/application/knife_spec.rb
@@ -28,8 +28,7 @@ describe Chef::Application::Knife do
long: "-optwithdefault VALUE",
default: "default-value"
- def run
- end
+ def run; end
end
end
diff --git a/spec/unit/chef_fs/config_spec.rb b/spec/unit/chef_fs/config_spec.rb
index 0adcbbfbfb..bdb9bc2c72 100644
--- a/spec/unit/chef_fs/config_spec.rb
+++ b/spec/unit/chef_fs/config_spec.rb
@@ -23,7 +23,7 @@ require "lib/chef/chef_fs/config.rb"
describe Chef::ChefFS::Config do
describe "initialize" do
it "warns when hosted setups use 'everything'" do
- base_config = Hash.new()
+ base_config = {}
base_config[:repo_mode] = "everything"
base_config[:chef_server_url] = "http://foo.com/organizations/fake_org/"
@@ -34,7 +34,7 @@ describe Chef::ChefFS::Config do
end
it "doesn't warn when hosted setups use 'hosted_everything'" do
- base_config = Hash.new()
+ base_config = {}
base_config[:repo_mode] = "hosted_everything"
base_config[:chef_server_url] = "http://foo.com/organizations/fake_org/"
@@ -45,7 +45,7 @@ describe Chef::ChefFS::Config do
end
it "doesn't warn when non-hosted setups use 'everything'" do
- base_config = Hash.new()
+ base_config = {}
base_config[:repo_mode] = "everything"
base_config[:chef_server_url] = "http://foo.com/"
diff --git a/spec/unit/chef_fs/file_system/repository/directory_spec.rb b/spec/unit/chef_fs/file_system/repository/directory_spec.rb
index 5b2a0a47b8..ec147ba6a8 100644
--- a/spec/unit/chef_fs/file_system/repository/directory_spec.rb
+++ b/spec/unit/chef_fs/file_system/repository/directory_spec.rb
@@ -106,7 +106,7 @@ describe Chef::ChefFS::FileSystem::Repository::Directory do
end
it "filters invalid names" do
- expect(test_directory.children.map { |c| c.name }).to eql %w{ test1.json test2.json test3.json }
+ expect(test_directory.children.map(&:name)).to eql %w{ test1.json test2.json test3.json }
end
end
diff --git a/spec/unit/chef_fs/parallelizer.rb b/spec/unit/chef_fs/parallelizer.rb
index 32e56c4231..d43e48b7bc 100644
--- a/spec/unit/chef_fs/parallelizer.rb
+++ b/spec/unit/chef_fs/parallelizer.rb
@@ -443,7 +443,7 @@ describe Chef::ChefFS::Parallelizer do
threads = 0.upto(99).map do |i|
Thread.new { outputs[i] = parallelizers[i].to_a }
end
- threads.each { |thread| thread.join }
+ threads.each(&:join)
outputs.each { |output| expect(output.sort).to eq(2.upto(501).to_a) }
end
end
diff --git a/spec/unit/client_spec.rb b/spec/unit/client_spec.rb
index 476647a651..5182717af8 100644
--- a/spec/unit/client_spec.rb
+++ b/spec/unit/client_spec.rb
@@ -647,7 +647,7 @@ describe Chef::Client do
EOM
end
it "should not raise an error" do
- expect { client.load_required_recipe(rest, run_context) }.not_to raise_error()
+ expect { client.load_required_recipe(rest, run_context) }.not_to raise_error
end
end
end
diff --git a/spec/unit/config_fetcher_spec.rb b/spec/unit/config_fetcher_spec.rb
index abaea6b2dc..8dadd9e681 100644
--- a/spec/unit/config_fetcher_spec.rb
+++ b/spec/unit/config_fetcher_spec.rb
@@ -7,7 +7,7 @@ describe Chef::ConfigFetcher do
let(:http) { double("Chef::HTTP::Simple") }
let(:config_location_regex) { Regexp.escape(config_location) }
- let(:invalid_json_error_regex) { %r{Could not parse the provided JSON file \(#{config_location_regex}\)} }
+ let(:invalid_json_error_regex) { /Could not parse the provided JSON file \(#{config_location_regex}\)/ }
let(:fetcher) { Chef::ConfigFetcher.new(config_location) }
diff --git a/spec/unit/cookbook/metadata_spec.rb b/spec/unit/cookbook/metadata_spec.rb
index 8d65efbd6a..7f66fe0c32 100644
--- a/spec/unit/cookbook/metadata_spec.rb
+++ b/spec/unit/cookbook/metadata_spec.rb
@@ -26,10 +26,10 @@ describe Chef::Cookbook::Metadata do
describe "when comparing for equality" do
before do
- @fields = [ :name, :description, :long_description, :maintainer,
- :maintainer_email, :license, :platforms, :dependencies,
- :providing, :recipes, :version, :source_url, :issues_url,
- :privacy, :ohai_versions, :chef_versions, :gems ]
+ @fields = %i{name description long_description maintainer
+ maintainer_email license platforms dependencies
+ providing recipes version source_url issues_url
+ privacy ohai_versions chef_versions gems}
end
it "does not depend on object identity for equality" do
diff --git a/spec/unit/cookbook_loader_spec.rb b/spec/unit/cookbook_loader_spec.rb
index 9180f13f33..c747f14dd0 100644
--- a/spec/unit/cookbook_loader_spec.rb
+++ b/spec/unit/cookbook_loader_spec.rb
@@ -88,7 +88,7 @@ describe Chef::CookbookLoader do
describe "each" do
it "should allow you to iterate over cookbooks with each" do
- seen = Hash.new
+ seen = {}
cookbook_loader.each_key do |cookbook_name|
seen[cookbook_name] = true
end
@@ -97,7 +97,7 @@ describe Chef::CookbookLoader do
end
it "should iterate in alphabetical order" do
- seen = Array.new
+ seen = []
cookbook_loader.each_key do |cookbook_name|
seen << cookbook_name
end
@@ -113,19 +113,19 @@ describe Chef::CookbookLoader do
it "should load different attribute files from deeper paths" do
expect(full_paths_for_part(:openldap, "attributes").detect do |f|
- f =~ /cookbooks\/openldap\/attributes\/smokey.rb/
+ f =~ %r{cookbooks/openldap/attributes/smokey.rb}
end).not_to eql(nil)
end
it "should load definition files from deeper paths" do
expect(full_paths_for_part(:openldap, "definitions").detect do |f|
- f =~ /cookbooks\/openldap\/definitions\/server.rb/
+ f =~ %r{cookbooks/openldap/definitions/server.rb}
end).not_to eql(nil)
end
it "should load recipe files from deeper paths" do
expect(full_paths_for_part(:openldap, "recipes").detect do |f|
- f =~ /cookbooks\/openldap\/recipes\/one.rb/
+ f =~ %r{cookbooks/openldap/recipes/one.rb}
end).not_to eql(nil)
end
@@ -134,8 +134,8 @@ describe Chef::CookbookLoader do
f =~ /\.dotfile$/
end).to match(/\.dotfile$/)
expect(full_paths_for_part(:openldap, "files").detect do |f|
- f =~ /\.ssh\/id_rsa$/
- end).to match(/\.ssh\/id_rsa$/)
+ f =~ %r{\.ssh/id_rsa$}
+ end).to match(%r{\.ssh/id_rsa$})
end
it "should load the metadata for the cookbook" do
@@ -173,7 +173,7 @@ describe Chef::CookbookLoader do
end
it "should have loaded the correct cookbook" do
- seen = Hash.new
+ seen = {}
cookbook_loader.each_key do |cookbook_name|
seen[cookbook_name] = true
end
@@ -203,7 +203,7 @@ describe Chef::CookbookLoader do
end
it "should not load the other cookbooks" do
- seen = Hash.new
+ seen = {}
cookbook_loader.each_key do |cookbook_name|
seen[cookbook_name] = true
end
@@ -239,7 +239,7 @@ describe Chef::CookbookLoader do
end
it "should load all cookbooks" do
- seen = Hash.new
+ seen = {}
cookbook_loader.each_key do |cookbook_name|
seen[cookbook_name] = true
end
diff --git a/spec/unit/cookbook_site_streaming_uploader_spec.rb b/spec/unit/cookbook_site_streaming_uploader_spec.rb
index 87ff7abdd7..af714094d0 100644
--- a/spec/unit/cookbook_site_streaming_uploader_spec.rb
+++ b/spec/unit/cookbook_site_streaming_uploader_spec.rb
@@ -25,8 +25,7 @@ class FakeTempfile
@basename = basename
end
- def close
- end
+ def close; end
def path
"#{@basename}.ZZZ"
diff --git a/spec/unit/data_bag_item_spec.rb b/spec/unit/data_bag_item_spec.rb
index 70fcd7041e..78953c6b6f 100644
--- a/spec/unit/data_bag_item_spec.rb
+++ b/spec/unit/data_bag_item_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Adam Jacob (<adam@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");
@@ -43,7 +43,7 @@ describe Chef::DataBagItem do
end
it "should throw an ArgumentError if you feed it anything but a string" do
- expect { data_bag_item.data_bag Hash.new }.to raise_error(ArgumentError)
+ expect { data_bag_item.data_bag({}) }.to raise_error(ArgumentError)
end
end
@@ -148,12 +148,12 @@ describe Chef::DataBagItem do
end
it "implements all the methods of Hash" do
- methods = [:rehash, :to_hash, :[], :fetch, :[]=, :store, :default,
- :default=, :default_proc, :index, :size, :length,
- :empty?, :each_value, :each_key, :each_pair, :each, :keys, :values,
- :values_at, :delete, :delete_if, :reject!, :clear,
- :invert, :update, :replace, :merge!, :merge, :has_key?, :has_value?,
- :key?, :value?]
+ methods = %i{rehash to_hash [] fetch []= store default
+ default= default_proc index size length
+ empty? each_value each_key each_pair each keys values
+ values_at delete delete_if reject! clear
+ invert update replace merge! merge has_key? has_value?
+ key? value?}
methods.each do |m|
expect(data_bag_item).to respond_to(m)
end
diff --git a/spec/unit/data_bag_spec.rb b/spec/unit/data_bag_spec.rb
index 388c35232f..4b0ba42172 100644
--- a/spec/unit/data_bag_spec.rb
+++ b/spec/unit/data_bag_spec.rb
@@ -46,7 +46,7 @@ describe Chef::DataBag do
end
it "should throw an ArgumentError if you feed it anything but a string" do
- expect { @data_bag.name Hash.new }.to raise_error(ArgumentError)
+ expect { @data_bag.name({}) }.to raise_error(ArgumentError)
end
[ ".", "-", "_", "1"].each do |char|
diff --git a/spec/unit/decorator_spec.rb b/spec/unit/decorator_spec.rb
index 6d73db2cc4..80bbd73bdf 100644
--- a/spec/unit/decorator_spec.rb
+++ b/spec/unit/decorator_spec.rb
@@ -28,11 +28,11 @@ def impersonates_a(klass)
end
it "#kind_of?(#{klass}) is true" do
- expect(decorator.kind_of?(klass)).to be true
+ expect(decorator.is_a?(klass)).to be true
end
it "#kind_of?(Chef::Decorator) is true" do
- expect(decorator.kind_of?(Chef::Decorator)).to be true
+ expect(decorator.is_a?(Chef::Decorator)).to be true
end
it "#instance_of?(#{klass}) is false" do
diff --git a/spec/unit/deprecated_spec.rb b/spec/unit/deprecated_spec.rb
index 9c60080cef..7564c042c4 100644
--- a/spec/unit/deprecated_spec.rb
+++ b/spec/unit/deprecated_spec.rb
@@ -44,7 +44,7 @@ describe Chef::Deprecated do
let(:location) { "the location" }
it "displays the full URL" do
- expect(TestDeprecation.new().url).to eql("https://docs.chef.io/deprecations_test.html")
+ expect(TestDeprecation.new.url).to eql("https://docs.chef.io/deprecations_test.html")
end
it "formats a complete deprecation message" do
@@ -59,7 +59,7 @@ describe Chef::Deprecated do
end
collisions = id_map.select { |k, v| v.size != 1 }
unless collisions.empty?
- raise "Found deprecation ID collisions:\n#{collisions.map { |k, v| "* #{k} #{v.map(&:name).join(', ')}" }.join("\n")}"
+ raise "Found deprecation ID collisions:\n#{collisions.map { |k, v| "* #{k} #{v.map(&:name).join(", ")}" }.join("\n")}"
end
end
end
diff --git a/spec/unit/dsl/data_query_spec.rb b/spec/unit/dsl/data_query_spec.rb
index f93f07bc52..afc2eacbd7 100644
--- a/spec/unit/dsl/data_query_spec.rb
+++ b/spec/unit/dsl/data_query_spec.rb
@@ -24,7 +24,7 @@ class DataQueryDSLTester
end
describe Chef::DSL::DataQuery do
- let(:node) { Hash.new }
+ let(:node) { {} }
let(:language) do
language = DataQueryDSLTester.new
@@ -68,7 +68,8 @@ describe Chef::DSL::DataQuery do
"a1" => [1, 2, 3],
"a2" => { "b1" => true },
},
- } end
+ }
+ end
let(:item) do
item = Chef::DataBagItem.new
diff --git a/spec/unit/dsl/declare_resource_spec.rb b/spec/unit/dsl/declare_resource_spec.rb
index 255e85e22e..ead0be2967 100644
--- a/spec/unit/dsl/declare_resource_spec.rb
+++ b/spec/unit/dsl/declare_resource_spec.rb
@@ -34,7 +34,7 @@ describe Chef::ResourceCollection do
describe "mixed in correctly" do
it "the resources() method winds up in the right classes" do
- methods = [ :resources, :find_resource, :find_resource!, :edit_resource, :edit_resource!, :delete_resource, :delete_resource!, :declare_resource, :build_resource ]
+ methods = %i{resources find_resource find_resource! edit_resource edit_resource! delete_resource delete_resource! declare_resource build_resource}
expect(Chef::Resource.instance_methods).to include(*methods)
expect(Chef::Recipe.instance_methods).to include(*methods)
expect(Chef::Provider.instance_methods).to include(*methods)
diff --git a/spec/unit/dsl/platform_introspection_spec.rb b/spec/unit/dsl/platform_introspection_spec.rb
index 51123ba930..7af233a769 100644
--- a/spec/unit/dsl/platform_introspection_spec.rb
+++ b/spec/unit/dsl/platform_introspection_spec.rb
@@ -40,7 +40,7 @@ describe Chef::DSL::PlatformIntrospection::PlatformDependentValue do
before do
platform_hash = {
:openbsd => { default: "free, functional, secure" },
- [:redhat, :centos, :fedora, :scientific] => { default: '"stable"' },
+ %i{redhat centos fedora scientific} => { default: '"stable"' },
:ubuntu => { "10.04" => "using upstart more", :default => "using init more" },
:default => "bork da bork",
}
@@ -84,7 +84,7 @@ describe Chef::DSL::PlatformIntrospection::PlatformDependentValue do
end
describe Chef::DSL::PlatformIntrospection::PlatformFamilyDependentValue do
before do
- @array_values = [:stop, :start, :reload]
+ @array_values = %i{stop start reload}
@platform_family_hash = {
"debian" => "debian value",
diff --git a/spec/unit/encrypted_data_bag_item/check_encrypted_spec.rb b/spec/unit/encrypted_data_bag_item/check_encrypted_spec.rb
index 7e885f8818..f8fcb654d9 100644
--- a/spec/unit/encrypted_data_bag_item/check_encrypted_spec.rb
+++ b/spec/unit/encrypted_data_bag_item/check_encrypted_spec.rb
@@ -47,7 +47,8 @@ describe Chef::EncryptedDataBagItem::CheckEncrypted do
"a1" => [1, 2, 3],
"a2" => { "b1" => true },
},
- } end
+ }
+ end
let(:version) { 1 }
let(:encoded_data) do
diff --git a/spec/unit/encrypted_data_bag_item_spec.rb b/spec/unit/encrypted_data_bag_item_spec.rb
index 14b5d9eb28..f406aa2ad0 100644
--- a/spec/unit/encrypted_data_bag_item_spec.rb
+++ b/spec/unit/encrypted_data_bag_item_spec.rb
@@ -325,7 +325,8 @@ describe Chef::EncryptedDataBagItem do
"id" => "item_name",
"greeting" => "hello",
"nested" => { "a1" => [1, 2, 3], "a2" => { "b1" => true } },
- } end
+ }
+ end
let(:secret) { "abc123SECRET" }
let(:encoded_data) { subject.encrypt_data_bag_item(plaintext_data, secret) }
diff --git a/spec/unit/environment_spec.rb b/spec/unit/environment_spec.rb
index 4da3a9fa0e..42906ef772 100644
--- a/spec/unit/environment_spec.rb
+++ b/spec/unit/environment_spec.rb
@@ -48,8 +48,8 @@ describe Chef::Environment do
end
it "should not accept anything but strings" do
- expect { @environment.name(Array.new) }.to raise_error(ArgumentError)
- expect { @environment.name(Hash.new) }.to raise_error(ArgumentError)
+ expect { @environment.name([]) }.to raise_error(ArgumentError)
+ expect { @environment.name({}) }.to raise_error(ArgumentError)
expect { @environment.name(2) }.to raise_error(ArgumentError)
end
end
@@ -65,8 +65,8 @@ describe Chef::Environment do
end
it "should not accept anything but strings" do
- expect { @environment.description(Array.new) }.to raise_error(ArgumentError)
- expect { @environment.description(Hash.new) }.to raise_error(ArgumentError)
+ expect { @environment.description([]) }.to raise_error(ArgumentError)
+ expect { @environment.description({}) }.to raise_error(ArgumentError)
expect { @environment.description(42) }.to raise_error(ArgumentError)
end
end
@@ -82,7 +82,7 @@ describe Chef::Environment do
end
it "should throw an ArgumentError if we aren't a kind of hash" do
- expect { @environment.default_attributes(Array.new) }.to raise_error(ArgumentError)
+ expect { @environment.default_attributes([]) }.to raise_error(ArgumentError)
end
end
@@ -97,7 +97,7 @@ describe Chef::Environment do
end
it "should throw an ArgumentError if we aren't a kind of hash" do
- expect { @environment.override_attributes(Array.new) }.to raise_error(ArgumentError)
+ expect { @environment.override_attributes([]) }.to raise_error(ArgumentError)
end
end
@@ -121,7 +121,7 @@ describe Chef::Environment do
it "should not accept anything but a hash" do
expect { @environment.cookbook_versions("I am a string!") }.to raise_error(ArgumentError)
- expect { @environment.cookbook_versions(Array.new) }.to raise_error(ArgumentError)
+ expect { @environment.cookbook_versions([]) }.to raise_error(ArgumentError)
expect { @environment.cookbook_versions(42) }.to raise_error(ArgumentError)
end
@@ -257,7 +257,7 @@ describe Chef::Environment do
end
it "should return false if anything other than a hash is passed as the argument" do
- expect(Chef::Environment.validate_cookbook_versions(Array.new)).to eq(false)
+ expect(Chef::Environment.validate_cookbook_versions([])).to eq(false)
expect(Chef::Environment.validate_cookbook_versions(42)).to eq(false)
expect(Chef::Environment.validate_cookbook_versions(Chef::CookbookVersion.new("meta"))).to eq(false)
expect(Chef::Environment.validate_cookbook_versions("cookbook => 1.2.3")).to eq(false)
diff --git a/spec/unit/event_dispatch/dsl_spec.rb b/spec/unit/event_dispatch/dsl_spec.rb
index 979b067fb6..009242f4fb 100644
--- a/spec/unit/event_dispatch/dsl_spec.rb
+++ b/spec/unit/event_dispatch/dsl_spec.rb
@@ -63,7 +63,7 @@ describe Chef::EventDispatch::DSL do
resource = Chef::Resource::RubyBlock.new("foo", run_context)
resource.block {}
resource.run_action(:run)
- expect(calls).to eq([:started, :updated])
+ expect(calls).to eq(%i{started updated})
end
it "preserve instance variables across handler callbacks" do
diff --git a/spec/unit/formatters/error_inspectors/resource_failure_inspector_spec.rb b/spec/unit/formatters/error_inspectors/resource_failure_inspector_spec.rb
index 0cdb06c3b3..7add65150a 100644
--- a/spec/unit/formatters/error_inspectors/resource_failure_inspector_spec.rb
+++ b/spec/unit/formatters/error_inspectors/resource_failure_inspector_spec.rb
@@ -60,7 +60,7 @@ describe Chef::Formatters::ErrorInspectors::ResourceFailureInspector do
@trace = [
"/var/chef/cache/cookbooks/syntax-err/recipes/default.rb:14:in `from_file'",
"/var/chef/cache/cookbooks/syntax-err/recipes/default.rb:11:in `from_file'",
- "/usr/local/lib/ruby/gems/chef/lib/chef/client.rb:123:in `run'" # should not display
+ "/usr/local/lib/ruby/gems/chef/lib/chef/client.rb:123:in `run'", # should not display
]
@exception = Chef::Exceptions::Package.new("No such package 'non-existing-package'")
@exception.set_backtrace(@trace)
@@ -122,7 +122,7 @@ describe Chef::Formatters::ErrorInspectors::ResourceFailureInspector do
source_line = "C:/Users/btm/chef/chef/spec/unit/fake_file.rb:2: undefined local variable or method `non_existent' for main:Object (NameError)"
@resource.source_line = source_line
@inspector = Chef::Formatters::ErrorInspectors::ResourceFailureInspector.new(@resource, :create, @exception)
- expect(@inspector.recipe_snippet).to match(/^# In C:\/Users\/btm/)
+ expect(@inspector.recipe_snippet).to match(%r{^# In C:/Users/btm})
end
it "parses a Windows path" do
@@ -136,7 +136,7 @@ describe Chef::Formatters::ErrorInspectors::ResourceFailureInspector do
source_line = "/home/btm/src/chef/chef/spec/unit/fake_file.rb:2: undefined local variable or method `non_existent' for main:Object (NameError)"
@resource.source_line = source_line
@inspector = Chef::Formatters::ErrorInspectors::ResourceFailureInspector.new(@resource, :create, @exception)
- expect(@inspector.recipe_snippet).to match(/^# In \/home\/btm/)
+ expect(@inspector.recipe_snippet).to match(%r{^# In /home/btm})
end
context "when the recipe file does not exist" do
diff --git a/spec/unit/guard_interpreter/resource_guard_interpreter_spec.rb b/spec/unit/guard_interpreter/resource_guard_interpreter_spec.rb
index b2ca8704b0..6d7f31c6f1 100644
--- a/spec/unit/guard_interpreter/resource_guard_interpreter_spec.rb
+++ b/spec/unit/guard_interpreter/resource_guard_interpreter_spec.rb
@@ -22,7 +22,7 @@ describe Chef::GuardInterpreter::ResourceGuardInterpreter do
let(:node) do
node = Chef::Node.new
- node.default["kernel"] = Hash.new
+ node.default["kernel"] = {}
node.default["kernel"][:machine] = :x86_64.to_s
node.automatic[:os] = "windows"
node
diff --git a/spec/unit/http/authenticator_spec.rb b/spec/unit/http/authenticator_spec.rb
index a2d4cb4815..0713aacc24 100644
--- a/spec/unit/http/authenticator_spec.rb
+++ b/spec/unit/http/authenticator_spec.rb
@@ -23,7 +23,7 @@ describe Chef::HTTP::Authenticator do
let(:class_instance) { Chef::HTTP::Authenticator.new(client_name: "test") }
let(:method) { "GET" }
let(:url) { URI("https://chef.example.com/organizations/test") }
- let(:headers) { Hash.new }
+ let(:headers) { {} }
let(:data) { "" }
context "when handle_request is called" do
@@ -92,7 +92,8 @@ describe Chef::HTTP::Authenticator do
it "calls authentication_headers with the proper input" do
expect(class_instance).to receive(:authentication_headers).with(
method, url, data,
- { "X-Ops-Server-API-Version" => Chef::HTTP::Authenticator::DEFAULT_SERVER_API_VERSION }).and_return({})
+ { "X-Ops-Server-API-Version" => Chef::HTTP::Authenticator::DEFAULT_SERVER_API_VERSION }
+ ).and_return({})
class_instance.handle_request(method, url, headers, data)
end
end
diff --git a/spec/unit/http/json_input_spec.rb b/spec/unit/http/json_input_spec.rb
index a76c8d1dc7..cddad20f55 100644
--- a/spec/unit/http/json_input_spec.rb
+++ b/spec/unit/http/json_input_spec.rb
@@ -21,7 +21,7 @@ require "chef/http/json_input"
describe Chef::HTTP::JSONInput do
- let(:json_encoder) { described_class.new() }
+ let(:json_encoder) { described_class.new }
let(:url) { URI.parse("http://example.com") }
let(:headers) { {} }
diff --git a/spec/unit/key_spec.rb b/spec/unit/key_spec.rb
index e3d9f8e7ad..efae549490 100644
--- a/spec/unit/key_spec.rb
+++ b/spec/unit/key_spec.rb
@@ -66,7 +66,7 @@ describe Chef::Key do
context "when you feed it anything but a string" do
it "should raise an ArgumentError" do
- expect { key.send(field, Hash.new) }.to raise_error(ArgumentError)
+ expect { key.send(field, {}) }.to raise_error(ArgumentError)
end
end
end
diff --git a/spec/unit/knife/bootstrap_spec.rb b/spec/unit/knife/bootstrap_spec.rb
index ee376e2bb4..5f4be8dfa2 100644
--- a/spec/unit/knife/bootstrap_spec.rb
+++ b/spec/unit/knife/bootstrap_spec.rb
@@ -35,7 +35,8 @@ describe Chef::Knife::Bootstrap do
double("TrainConnector",
windows?: windows_test,
linux?: linux_test,
- unix?: unix_test) end
+ unix?: unix_test)
+ end
let(:knife) do
Chef::Log.logger = Logger.new(StringIO.new)
@@ -107,7 +108,7 @@ describe Chef::Knife::Bootstrap do
expect(knife).to receive(:read_secret).and_return("secrets")
expect(rendered_template).to match("cat > /etc/chef/encrypted_data_bag_secret <<'EOP'")
expect(rendered_template).to match('{"run_list":\[\]}')
- expect(rendered_template).to match(%r{secrets})
+ expect(rendered_template).to match(/secrets/)
end
end
end
@@ -127,7 +128,7 @@ describe Chef::Knife::Bootstrap do
knife.render_template
end
it "configures the preinstall command in the bootstrap template correctly" do
- expect(rendered_template).to match(%r{command})
+ expect(rendered_template).to match(/command/)
end
end
@@ -138,7 +139,7 @@ describe Chef::Knife::Bootstrap do
knife.render_template
end
it "configures the https_proxy environment variable in the bootstrap template correctly" do
- expect(rendered_template).to match(%r{https_proxy="1.1.1.1" export https_proxy})
+ expect(rendered_template).to match(/https_proxy="1.1.1.1" export https_proxy/)
end
end
@@ -149,7 +150,7 @@ describe Chef::Knife::Bootstrap do
knife.render_template
end
it "configures the https_proxy environment variable in the bootstrap template correctly" do
- expect(rendered_template).to match(%r{no_proxy="localserver" export no_proxy})
+ expect(rendered_template).to match(/no_proxy="localserver" export no_proxy/)
end
end
@@ -360,7 +361,7 @@ describe Chef::Knife::Bootstrap do
it "should create a hint file when told to" do
knife.parse_options(["--hint", "openstack"])
knife.merge_configs
- expect(knife.render_template).to match(/\/etc\/chef\/ohai\/hints\/openstack.json/)
+ expect(knife.render_template).to match(%r{/etc/chef/ohai/hints/openstack.json})
end
it "should populate a hint file with JSON when given a file to read" do
@@ -393,7 +394,7 @@ describe Chef::Knife::Bootstrap do
let(:setting) { "api.opscode.com" }
it "renders the client.rb with a single FQDN no_proxy entry" do
- expect(rendered_template).to match(%r{.*no_proxy\s*"api.opscode.com".*})
+ expect(rendered_template).to match(/.*no_proxy\s*"api.opscode.com".*/)
end
end
@@ -401,7 +402,7 @@ describe Chef::Knife::Bootstrap do
let(:setting) { "api.opscode.com,172.16.10.*" }
it "renders the client.rb with comma-separated FQDN and wildcard IP address no_proxy entries" do
- expect(rendered_template).to match(%r{.*no_proxy\s*"api.opscode.com,172.16.10.\*".*})
+ expect(rendered_template).to match(/.*no_proxy\s*"api.opscode.com,172.16.10.\*".*/)
end
end
@@ -459,7 +460,7 @@ describe Chef::Knife::Bootstrap do
it "creates a secret file" do
expect(knife).to receive(:encryption_secret_provided_ignore_encrypt_flag?).and_return(true)
expect(knife).to receive(:read_secret).and_return(secret)
- expect(rendered_template).to match(%r{#{secret}})
+ expect(rendered_template).to match(/#{secret}/)
end
it "renders the client.rb with an encrypted_data_bag_secret entry" do
@@ -569,7 +570,9 @@ describe Chef::Knife::Bootstrap do
context "when client_d_dir is set" do
let(:client_d_dir) do
Chef::Util::PathHelper.cleanpath(
- File.join(File.dirname(__FILE__), "../../data/client.d_00")) end
+ File.join(File.dirname(__FILE__), "../../data/client.d_00")
+ )
+ end
it "creates /etc/chef/client.d" do
expect(rendered_template).to match("mkdir -p /etc/chef/client\.d")
@@ -594,7 +597,9 @@ describe Chef::Knife::Bootstrap do
context "a nested directory structure" do
let(:client_d_dir) do
Chef::Util::PathHelper.cleanpath(
- File.join(File.dirname(__FILE__), "../../data/client.d_01")) end
+ File.join(File.dirname(__FILE__), "../../data/client.d_01")
+ )
+ end
it "creates a file foo/bar.rb" do
expect(rendered_template).to match("cat > /etc/chef/client.d/foo/bar.rb <<'EOP'")
expect(rendered_template).to match("1 / 0")
@@ -1554,7 +1559,8 @@ describe Chef::Knife::Bootstrap do
ssl: false,
ssl_peer_fingerprint: nil,
operation_timeout: 60,
- } end
+ }
+ end
it "generates a correct configuration hash with expected defaults" do
expect(knife.winrm_opts).to eq expected
@@ -1730,7 +1736,7 @@ describe Chef::Knife::Bootstrap do
before do
Chef::Config[:validation_key] = "/blah"
allow(vault_handler_mock).to receive(:doing_chef_vault?).and_return false
- allow(File).to receive(:exist?).with(/\/blah/).and_return false
+ allow(File).to receive(:exist?).with(%r{/blah}).and_return false
end
it_behaves_like "creating the client locally"
end
@@ -1738,7 +1744,7 @@ describe Chef::Knife::Bootstrap do
context "when a valid validation key is given and we're doing old-style client creation" do
before do
Chef::Config[:validation_key] = "/blah"
- allow(File).to receive(:exist?).with(/\/blah/).and_return true
+ allow(File).to receive(:exist?).with(%r{/blah}).and_return true
allow(vault_handler_mock).to receive(:doing_chef_vault?).and_return false
end
diff --git a/spec/unit/knife/client_bulk_delete_spec.rb b/spec/unit/knife/client_bulk_delete_spec.rb
index feebab4986..770ba8762f 100644
--- a/spec/unit/knife/client_bulk_delete_spec.rb
+++ b/spec/unit/knife/client_bulk_delete_spec.rb
@@ -42,10 +42,10 @@ describe Chef::Knife::ClientBulkDelete do
let(:nonvalidator_client_names) { %w{tim dan stephen} }
let(:nonvalidator_clients) do
- clients = Hash.new
+ clients = {}
nonvalidator_client_names.each do |client_name|
- client = Chef::ApiClientV1.new()
+ client = Chef::ApiClientV1.new
client.name(client_name)
allow(client).to receive(:destroy).and_return(true)
clients[client_name] = client
@@ -56,10 +56,10 @@ describe Chef::Knife::ClientBulkDelete do
let(:validator_client_names) { %w{myorg-validator} }
let(:validator_clients) do
- clients = Hash.new
+ clients = {}
validator_client_names.each do |validator_client_name|
- validator_client = Chef::ApiClientV1.new()
+ validator_client = Chef::ApiClientV1.new
validator_client.name(validator_client_name)
allow(validator_client).to receive(:validator).and_return(true)
allow(validator_client).to receive(:destroy).and_return(true)
diff --git a/spec/unit/knife/configure_client_spec.rb b/spec/unit/knife/configure_client_spec.rb
index c83ceed6cb..be76250e7c 100644
--- a/spec/unit/knife/configure_client_spec.rb
+++ b/spec/unit/knife/configure_client_spec.rb
@@ -58,7 +58,7 @@ describe Chef::Knife::ConfigureClient do
it "should write out the config file" do
allow(FileUtils).to receive(:mkdir_p)
@knife.run
- expect(@client_file.string).to match /chef_server_url\s+'https\:\/\/chef\.example\.com'/
+ expect(@client_file.string).to match %r{chef_server_url\s+'https\://chef\.example\.com'}
expect(@client_file.string).to match /validation_client_name\s+'chef-validator'/
end
diff --git a/spec/unit/knife/configure_spec.rb b/spec/unit/knife/configure_spec.rb
index 1cdad0cd0e..6b41e54778 100644
--- a/spec/unit/knife/configure_spec.rb
+++ b/spec/unit/knife/configure_spec.rb
@@ -159,7 +159,7 @@ describe Chef::Knife::Configure do
@knife.run
expect(config_file.string).to match(/^client_name[\s]+=[\s]+'#{Etc.getlogin}'$/)
expect(config_file.string).to match(%r{^client_key[\s]+=[\s]+'/home/you/.chef/#{Etc.getlogin}.pem'$})
- expect(config_file.string).to match(%r{^chef_server_url\s+=[\s]+'#{default_server_url}'$})
+ expect(config_file.string).to match(/^chef_server_url\s+=[\s]+'#{default_server_url}'$/)
end
it "creates a new client when given the --initial option" do
diff --git a/spec/unit/knife/cookbook_bulk_delete_spec.rb b/spec/unit/knife/cookbook_bulk_delete_spec.rb
index c8c1873081..d01213227b 100644
--- a/spec/unit/knife/cookbook_bulk_delete_spec.rb
+++ b/spec/unit/knife/cookbook_bulk_delete_spec.rb
@@ -31,7 +31,7 @@ describe Chef::Knife::CookbookBulkDelete do
allow(@knife.ui).to receive(:stdout).and_return(@stdout)
allow(@knife.ui).to receive(:stderr).and_return(@stderr)
allow(@knife.ui).to receive(:confirm).and_return(true)
- @cookbooks = Hash.new
+ @cookbooks = {}
%w{cheezburger pizza lasagna}.each do |cookbook_name|
cookbook = Chef::CookbookVersion.new(cookbook_name)
@cookbooks[cookbook_name] = cookbook
diff --git a/spec/unit/knife/cookbook_delete_spec.rb b/spec/unit/knife/cookbook_delete_spec.rb
index b2f17778cd..4de907e94d 100644
--- a/spec/unit/knife/cookbook_delete_spec.rb
+++ b/spec/unit/knife/cookbook_delete_spec.rb
@@ -77,7 +77,7 @@ describe Chef::Knife::CookbookDelete do
@knife.version = "1.0.0"
expect(@knife).to receive(:delete_object).with(Chef::CookbookVersion,
"foobar version 1.0.0",
- "cookbook").and_yield()
+ "cookbook").and_yield
expect(@knife).to receive(:delete_request).with("cookbooks/foobar/1.0.0")
@knife.delete_explicit_version
end
diff --git a/spec/unit/knife/cookbook_download_spec.rb b/spec/unit/knife/cookbook_download_spec.rb
index 122c284b93..78dd20e2d2 100644
--- a/spec/unit/knife/cookbook_download_spec.rb
+++ b/spec/unit/knife/cookbook_download_spec.rb
@@ -112,7 +112,7 @@ describe Chef::Knife::CookbookDownload do
it "should print an error and exit if the cookbook download directory already exists" do
expect(File).to receive(:exists?).with("/var/tmp/chef/foobar-1.0.0").and_return(true)
- expect(@knife.ui).to receive(:fatal).with(/\/var\/tmp\/chef\/foobar-1\.0\.0 exists/i)
+ expect(@knife.ui).to receive(:fatal).with(%r{/var/tmp/chef/foobar-1\.0\.0 exists}i)
expect { @knife.run }.to raise_error(SystemExit)
end
@@ -141,7 +141,7 @@ describe Chef::Knife::CookbookDownload do
expect(@stderr.string).to match /downloading #{segment}/im
end
expect(@stderr.string).to match /downloading foobar cookbook version 1\.0\.0/im
- expect(@stderr.string).to match /cookbook downloaded to \/var\/tmp\/chef\/foobar-1\.0\.0/im
+ expect(@stderr.string).to match %r{cookbook downloaded to /var/tmp/chef/foobar-1\.0\.0}im
end
describe "with -f or --force" do
diff --git a/spec/unit/knife/cookbook_metadata_spec.rb b/spec/unit/knife/cookbook_metadata_spec.rb
index c19fc5ae2d..04d851be6a 100644
--- a/spec/unit/knife/cookbook_metadata_spec.rb
+++ b/spec/unit/knife/cookbook_metadata_spec.rb
@@ -98,8 +98,8 @@ describe Chef::Knife::CookbookMetadata do
it "should generate the metadata for each cookbook" do
expect(Chef::CookbookLoader).to receive(:new).with(cookbook_dir).and_call_original
knife.run
- expect(stderr.string).to match /generating metadata for foo from #{cookbook_dir}\/foo\/metadata\.rb/im
- expect(stderr.string).to match /generating metadata for bar from #{cookbook_dir}\/bar\/metadata\.rb/im
+ expect(stderr.string).to match %r{generating metadata for foo from #{cookbook_dir}/foo/metadata\.rb}im
+ expect(stderr.string).to match %r{generating metadata for bar from #{cookbook_dir}/bar/metadata\.rb}im
end
it "with -o or --cookbook_path should look in the provided path and generate cookbook metadata" do
@@ -107,8 +107,8 @@ describe Chef::Knife::CookbookMetadata do
knife.config[:cookbook_path] = cookbook_dir
expect(Chef::CookbookLoader).to receive(:new).with(cookbook_dir).and_call_original
knife.run
- expect(stderr.string).to match /generating metadata for foo from #{cookbook_dir}\/foo\/metadata\.rb/im
- expect(stderr.string).to match /generating metadata for bar from #{cookbook_dir}\/bar\/metadata\.rb/im
+ expect(stderr.string).to match %r{generating metadata for foo from #{cookbook_dir}/foo/metadata\.rb}im
+ expect(stderr.string).to match %r{generating metadata for bar from #{cookbook_dir}/bar/metadata\.rb}im
end
end
diff --git a/spec/unit/knife/cookbook_upload_spec.rb b/spec/unit/knife/cookbook_upload_spec.rb
index 8bff31197c..9c371c4140 100644
--- a/spec/unit/knife/cookbook_upload_spec.rb
+++ b/spec/unit/knife/cookbook_upload_spec.rb
@@ -264,7 +264,8 @@ describe Chef::Knife::CookbookUpload do
it "should warn users that no cookbooks exist" do
knife.config[:cookbook_path] = ["/chef-repo/cookbooks", "/home/user/cookbooks"]
expect(knife.ui).to receive(:warn).with(
- /Could not find any cookbooks in your cookbook path: #{knife.config[:cookbook_path].join(', ')}\. Use --cookbook-path to specify the desired path\./)
+ /Could not find any cookbooks in your cookbook path: #{knife.config[:cookbook_path].join(', ')}\. Use --cookbook-path to specify the desired path\./
+ )
knife.run
end
end
@@ -273,7 +274,8 @@ describe Chef::Knife::CookbookUpload do
it "should warn users that no cookbooks exist" do
knife.config[:cookbook_path] = "/chef-repo/cookbooks"
expect(knife.ui).to receive(:warn).with(
- /Could not find any cookbooks in your cookbook path: #{knife.config[:cookbook_path]}\. Use --cookbook-path to specify the desired path\./)
+ /Could not find any cookbooks in your cookbook path: #{knife.config[:cookbook_path]}\. Use --cookbook-path to specify the desired path\./
+ )
knife.run
end
end
diff --git a/spec/unit/knife/core/gem_glob_loader_spec.rb b/spec/unit/knife/core/gem_glob_loader_spec.rb
index 689426de1b..c8bd34d4a9 100644
--- a/spec/unit/knife/core/gem_glob_loader_spec.rb
+++ b/spec/unit/knife/core/gem_glob_loader_spec.rb
@@ -34,7 +34,7 @@ describe Chef::Knife::SubcommandLoader::GemGlobLoader do
it "builds a list of the core subcommand file require paths" do
expect(loader.subcommand_files).not_to be_empty
loader.subcommand_files.each do |require_path|
- expect(require_path).to match(/chef\/knife\/.*|plugins\/knife\/.*/)
+ expect(require_path).to match(%r{chef/knife/.*|plugins/knife/.*})
end
end
@@ -52,7 +52,7 @@ describe Chef::Knife::SubcommandLoader::GemGlobLoader do
expect($LOAD_PATH).to receive(:map).and_return([])
if Gem::Specification.respond_to? :latest_specs
expect(Gem::Specification).to receive(:latest_specs).with(true).and_return(gems)
- expect(gems[0]).to receive(:matches_for_glob).with(/chef\/knife\/\*\.rb\{(.*),\.rb,(.*)\}/).and_return(gem_files)
+ expect(gems[0]).to receive(:matches_for_glob).with(%r{chef/knife/\*\.rb\{(.*),\.rb,(.*)\}}).and_return(gem_files)
else
expect(Gem.source_index).to receive(:latest_specs).with(true).and_return(gems)
expect(gems[0]).to receive(:require_paths).twice.and_return(["lib"])
@@ -185,7 +185,7 @@ describe Chef::Knife::SubcommandLoader::GemGlobLoader do
expect(Gem.source_index).to receive(:latest_specs).and_call_original
end
loader.subcommand_files.each do |require_path|
- expect(require_path).to match(/chef\/knife\/.*|plugins\/knife\/.*/)
+ expect(require_path).to match(%r{chef/knife/.*|plugins/knife/.*})
end
end
@@ -201,7 +201,7 @@ describe Chef::Knife::SubcommandLoader::GemGlobLoader do
expect(Gem.source_index).to receive(:latest_specs).and_call_original
end
loader.subcommand_files.each do |require_path|
- expect(require_path).to match(/chef\/knife\/.*|plugins\/knife\/.*/)
+ expect(require_path).to match(%r{chef/knife/.*|plugins/knife/.*})
end
end
end
diff --git a/spec/unit/knife/core/hashed_command_loader_spec.rb b/spec/unit/knife/core/hashed_command_loader_spec.rb
index c59838478e..c463a36fb4 100644
--- a/spec/unit/knife/core/hashed_command_loader_spec.rb
+++ b/spec/unit/knife/core/hashed_command_loader_spec.rb
@@ -44,7 +44,9 @@ describe Chef::Knife::SubcommandLoader::HashedCommandLoader do
let(:loader) do
Chef::Knife::SubcommandLoader::HashedCommandLoader.new(
File.join(CHEF_SPEC_DATA, "knife-site-subcommands"),
- plugin_manifest) end
+ plugin_manifest
+ )
+ end
describe "#list_commands" do
before do
diff --git a/spec/unit/knife/core/node_editor_spec.rb b/spec/unit/knife/core/node_editor_spec.rb
index ccf6776593..493de3c5b1 100644
--- a/spec/unit/knife/core/node_editor_spec.rb
+++ b/spec/unit/knife/core/node_editor_spec.rb
@@ -44,13 +44,13 @@ describe Chef::Knife::NodeEditor do
describe "#view" do
it "returns a Hash with only the name, chef_environment, normal, " +
"policy_name, policy_group, and run_list properties" do
- expected = node_data.select do |key,|
- %w{ name chef_environment normal
- policy_name policy_group run_list }.include?(key)
- end
+ expected = node_data.select do |key,|
+ %w{ name chef_environment normal
+ policy_name policy_group run_list }.include?(key)
+ end
- expect(subject.view).to eq(expected)
- end
+ expect(subject.view).to eq(expected)
+ end
context "when config[:all_attributes] == true" do
let(:config) { base_config.merge(all_attributes: true) }
@@ -190,8 +190,8 @@ describe Chef::Knife::NodeEditor do
it "returns an array of property names that doesn't include " +
"the non-editable properties" do
- expect(subject.updated?).to eql %w{ chef_environment normal policy_name policy_group run_list }
- end
+ expect(subject.updated?).to eql %w{ chef_environment normal policy_name policy_group run_list }
+ end
end
end
diff --git a/spec/unit/knife/core/windows_bootstrap_context_spec.rb b/spec/unit/knife/core/windows_bootstrap_context_spec.rb
index a662b1c203..e5a4e955e8 100644
--- a/spec/unit/knife/core/windows_bootstrap_context_spec.rb
+++ b/spec/unit/knife/core/windows_bootstrap_context_spec.rb
@@ -157,8 +157,7 @@ describe Chef::Knife::Core::WindowsBootstrapContext do
validation_client_name: "chef-validator-testing",
file_cache_path: "c:/chef/cache",
file_backup_path: "c:/chef/backup",
- cache_options: ({ path: "c:/chef/cache/checksums", skip_expires: true })
- ))
+ cache_options: ({ path: "c:/chef/cache/checksums", skip_expires: true })))
end
it "generates the config file data" do
diff --git a/spec/unit/knife/data_bag_from_file_spec.rb b/spec/unit/knife/data_bag_from_file_spec.rb
index 3bea392ae2..bc0ca330e8 100644
--- a/spec/unit/knife/data_bag_from_file_spec.rb
+++ b/spec/unit/knife/data_bag_from_file_spec.rb
@@ -77,7 +77,8 @@ describe Chef::Knife::DataBagFromFile do
"id" => "item_name",
"greeting" => "hello",
"nested" => { "a1" => [1, 2, 3], "a2" => { "b1" => true } },
- } end
+ }
+ end
let(:enc_data) { Chef::EncryptedDataBagItem.encrypt_data_bag_item(plain_data, secret) }
let(:rest) { double("Chef::ServerAPI") }
diff --git a/spec/unit/knife/data_bag_show_spec.rb b/spec/unit/knife/data_bag_show_spec.rb
index 8dd0669993..6ac6dd3c95 100644
--- a/spec/unit/knife/data_bag_show_spec.rb
+++ b/spec/unit/knife/data_bag_show_spec.rb
@@ -47,7 +47,8 @@ describe Chef::Knife::DataBagShow do
let(:data_bag_contents) do
{ "id" => "id", "baz" => "http://localhost:4000/data/bag_o_data/baz",
- "qux" => "http://localhost:4000/data/bag_o_data/qux" } end
+ "qux" => "http://localhost:4000/data/bag_o_data/qux" }
+ end
let(:enc_hash) { Chef::EncryptedDataBagItem.encrypt_data_bag_item(data_bag_contents, secret) }
let(:data_bag) { Chef::DataBagItem.from_hash(data_bag_contents) }
let(:data_bag_with_encoded_hash) { Chef::DataBagItem.from_hash(enc_hash) }
diff --git a/spec/unit/knife/key_create_spec.rb b/spec/unit/knife/key_create_spec.rb
index fcbfd40381..6437ba2bcd 100644
--- a/spec/unit/knife/key_create_spec.rb
+++ b/spec/unit/knife/key_create_spec.rb
@@ -84,7 +84,7 @@ Tfuc9dUYsFjptWYrV6pfEQ+bgo1OGBXORBFcFL+2D7u9JYquKrMgosznHoEkQNLo
0wIDAQAB
-----END PUBLIC KEY-----"
end
- let(:config) { Hash.new }
+ let(:config) { {} }
let(:actor) { "charmander" }
let(:ui) { instance_double("Chef::Knife::UI") }
diff --git a/spec/unit/knife/key_edit_spec.rb b/spec/unit/knife/key_edit_spec.rb
index 7c409f5ea0..1f8067c160 100644
--- a/spec/unit/knife/key_edit_spec.rb
+++ b/spec/unit/knife/key_edit_spec.rb
@@ -86,7 +86,7 @@ Tfuc9dUYsFjptWYrV6pfEQ+bgo1OGBXORBFcFL+2D7u9JYquKrMgosznHoEkQNLo
0wIDAQAB
-----END PUBLIC KEY-----"
end
- let(:config) { Hash.new }
+ let(:config) { {} }
let(:actor) { "charmander" }
let(:keyname) { "charmander-key" }
let(:ui) { instance_double("Chef::Knife::UI") }
diff --git a/spec/unit/knife/key_list_spec.rb b/spec/unit/knife/key_list_spec.rb
index e221a4da72..c65a11b08c 100644
--- a/spec/unit/knife/key_list_spec.rb
+++ b/spec/unit/knife/key_list_spec.rb
@@ -73,7 +73,7 @@ describe "key list commands that inherit knife" do
end
describe Chef::Knife::KeyList do
- let(:config) { Hash.new }
+ let(:config) { {} }
let(:actor) { "charmander" }
let(:ui) { instance_double("Chef::Knife::UI") }
diff --git a/spec/unit/knife/node_bulk_delete_spec.rb b/spec/unit/knife/node_bulk_delete_spec.rb
index 2a3563e563..db9e2caab1 100644
--- a/spec/unit/knife/node_bulk_delete_spec.rb
+++ b/spec/unit/knife/node_bulk_delete_spec.rb
@@ -28,7 +28,7 @@ describe Chef::Knife::NodeBulkDelete do
@stdout = StringIO.new
allow(@knife.ui).to receive(:stdout).and_return(@stdout)
allow(@knife.ui).to receive(:confirm).and_return(true)
- @nodes = Hash.new
+ @nodes = {}
%w{adam brent jacob}.each do |node_name|
@nodes[node_name] = "http://localhost:4000/nodes/#{node_name}"
end
@@ -44,14 +44,14 @@ describe Chef::Knife::NodeBulkDelete do
# I hate not having == defined for anything :(
actual = @knife.all_nodes
expect(actual.keys).to match_array(expected.keys)
- expect(actual.values.map { |n| n.name }).to match_array(%w{adam brent jacob})
+ expect(actual.values.map(&:name)).to match_array(%w{adam brent jacob})
end
end
describe "run" do
before do
@inflatedish_list = @nodes.keys.inject({}) do |nodes_by_name, name|
- node = Chef::Node.new()
+ node = Chef::Node.new
node.name(name)
allow(node).to receive(:destroy).and_return(true)
nodes_by_name[name] = node
diff --git a/spec/unit/knife/node_delete_spec.rb b/spec/unit/knife/node_delete_spec.rb
index cc2e0b23af..c5b8925fb5 100644
--- a/spec/unit/knife/node_delete_spec.rb
+++ b/spec/unit/knife/node_delete_spec.rb
@@ -29,8 +29,8 @@ describe Chef::Knife::NodeDelete do
allow(@knife).to receive(:output).and_return(true)
allow(@knife).to receive(:confirm).and_return(true)
- @adam_node = Chef::Node.new()
- @ben_node = Chef::Node.new()
+ @adam_node = Chef::Node.new
+ @ben_node = Chef::Node.new
allow(@ben_node).to receive(:destroy).and_return(true)
allow(@adam_node).to receive(:destroy).and_return(true)
allow(Chef::Node).to receive(:load).with("adam").and_return(@adam_node)
diff --git a/spec/unit/knife/node_edit_spec.rb b/spec/unit/knife/node_edit_spec.rb
index dfc0986ebe..83d78b68f1 100644
--- a/spec/unit/knife/node_edit_spec.rb
+++ b/spec/unit/knife/node_edit_spec.rb
@@ -35,7 +35,7 @@ describe Chef::Knife::NodeEdit do
print_after: nil,
}
@knife.name_args = [ "adam" ]
- @node = Chef::Node.new()
+ @node = Chef::Node.new
end
it "should load the node" do
diff --git a/spec/unit/knife/node_environment_set_spec.rb b/spec/unit/knife/node_environment_set_spec.rb
index 7ceafdad78..5b704c4219 100644
--- a/spec/unit/knife/node_environment_set_spec.rb
+++ b/spec/unit/knife/node_environment_set_spec.rb
@@ -24,7 +24,7 @@ describe Chef::Knife::NodeEnvironmentSet do
@knife = Chef::Knife::NodeEnvironmentSet.new
@knife.name_args = %w{adam bar}
allow(@knife).to receive(:output).and_return(true)
- @node = Chef::Node.new()
+ @node = Chef::Node.new
@node.name("knifetest-node")
@node.chef_environment << "foo"
allow(@node).to receive(:save).and_return(true)
diff --git a/spec/unit/knife/node_from_file_spec.rb b/spec/unit/knife/node_from_file_spec.rb
index cf128a80a0..524780c0b8 100644
--- a/spec/unit/knife/node_from_file_spec.rb
+++ b/spec/unit/knife/node_from_file_spec.rb
@@ -30,7 +30,7 @@ describe Chef::Knife::NodeFromFile do
@knife.name_args = [ "adam.rb" ]
allow(@knife).to receive(:output).and_return(true)
allow(@knife).to receive(:confirm).and_return(true)
- @node = Chef::Node.new()
+ @node = Chef::Node.new
allow(@node).to receive(:save)
allow(@knife.loader).to receive(:load_from).and_return(@node)
@stdout = StringIO.new
diff --git a/spec/unit/knife/node_policy_set_spec.rb b/spec/unit/knife/node_policy_set_spec.rb
index 35306937d8..da84019fe1 100644
--- a/spec/unit/knife/node_policy_set_spec.rb
+++ b/spec/unit/knife/node_policy_set_spec.rb
@@ -20,7 +20,7 @@ require "spec_helper"
describe Chef::Knife::NodePolicySet do
let(:node) do
- node = Chef::Node.new()
+ node = Chef::Node.new
node.name("adam")
node.run_list = ["role[base]"]
node
diff --git a/spec/unit/knife/node_run_list_add_spec.rb b/spec/unit/knife/node_run_list_add_spec.rb
index 03c89ff9eb..b793333c99 100644
--- a/spec/unit/knife/node_run_list_add_spec.rb
+++ b/spec/unit/knife/node_run_list_add_spec.rb
@@ -27,7 +27,7 @@ describe Chef::Knife::NodeRunListAdd do
}
@knife.name_args = [ "adam", "role[monkey]" ]
allow(@knife).to receive(:output).and_return(true)
- @node = Chef::Node.new()
+ @node = Chef::Node.new
allow(@node).to receive(:save).and_return(true)
allow(Chef::Node).to receive(:load).and_return(@node)
end
diff --git a/spec/unit/knife/node_run_list_remove_spec.rb b/spec/unit/knife/node_run_list_remove_spec.rb
index 4f753d7991..a62b6f4b71 100644
--- a/spec/unit/knife/node_run_list_remove_spec.rb
+++ b/spec/unit/knife/node_run_list_remove_spec.rb
@@ -24,7 +24,7 @@ describe Chef::Knife::NodeRunListRemove do
@knife = Chef::Knife::NodeRunListRemove.new
@knife.config[:print_after] = nil
@knife.name_args = [ "adam", "role[monkey]" ]
- @node = Chef::Node.new()
+ @node = Chef::Node.new
@node.name("knifetest-node")
@node.run_list << "role[monkey]"
allow(@node).to receive(:save).and_return(true)
diff --git a/spec/unit/knife/node_run_list_set_spec.rb b/spec/unit/knife/node_run_list_set_spec.rb
index bd55edb997..6246dfce6a 100644
--- a/spec/unit/knife/node_run_list_set_spec.rb
+++ b/spec/unit/knife/node_run_list_set_spec.rb
@@ -25,7 +25,7 @@ describe Chef::Knife::NodeRunListSet do
@knife.config = {}
@knife.name_args = [ "adam", "role[monkey]" ]
allow(@knife).to receive(:output).and_return(true)
- @node = Chef::Node.new()
+ @node = Chef::Node.new
allow(@node).to receive(:save).and_return(true)
allow(Chef::Node).to receive(:load).and_return(@node)
end
diff --git a/spec/unit/knife/node_show_spec.rb b/spec/unit/knife/node_show_spec.rb
index 2f684b27f4..f26bae4233 100644
--- a/spec/unit/knife/node_show_spec.rb
+++ b/spec/unit/knife/node_show_spec.rb
@@ -21,7 +21,7 @@ require "spec_helper"
describe Chef::Knife::NodeShow do
let(:node) do
- node = Chef::Node.new()
+ node = Chef::Node.new
node.name("adam")
node.run_list = ["role[base]"]
node
diff --git a/spec/unit/knife/role_bulk_delete_spec.rb b/spec/unit/knife/role_bulk_delete_spec.rb
index d49adb9354..07a9b484c4 100644
--- a/spec/unit/knife/role_bulk_delete_spec.rb
+++ b/spec/unit/knife/role_bulk_delete_spec.rb
@@ -29,9 +29,9 @@ describe Chef::Knife::RoleBulkDelete do
@stdout = StringIO.new
allow(@knife.ui).to receive(:stdout).and_return(@stdout)
allow(@knife.ui).to receive(:confirm).and_return(true)
- @roles = Hash.new
+ @roles = {}
%w{dev staging production}.each do |role_name|
- role = Chef::Role.new()
+ role = Chef::Role.new
role.name(role_name)
allow(role).to receive(:destroy).and_return(true)
@roles[role_name] = role
diff --git a/spec/unit/knife/role_create_spec.rb b/spec/unit/knife/role_create_spec.rb
index 5e2b2caeb5..fa3ef1c9e8 100644
--- a/spec/unit/knife/role_create_spec.rb
+++ b/spec/unit/knife/role_create_spec.rb
@@ -27,7 +27,7 @@ describe Chef::Knife::RoleCreate do
}
@knife.name_args = [ "adam" ]
allow(@knife).to receive(:output).and_return(true)
- @role = Chef::Role.new()
+ @role = Chef::Role.new
allow(@role).to receive(:save)
allow(Chef::Role).to receive(:new).and_return(@role)
allow(@knife).to receive(:edit_data).and_return(@role)
diff --git a/spec/unit/knife/role_delete_spec.rb b/spec/unit/knife/role_delete_spec.rb
index 98c0cde9b2..889287fd04 100644
--- a/spec/unit/knife/role_delete_spec.rb
+++ b/spec/unit/knife/role_delete_spec.rb
@@ -28,7 +28,7 @@ describe Chef::Knife::RoleDelete do
@knife.name_args = [ "adam" ]
allow(@knife).to receive(:output).and_return(true)
allow(@knife).to receive(:confirm).and_return(true)
- @role = Chef::Role.new()
+ @role = Chef::Role.new
allow(@role).to receive(:destroy).and_return(true)
allow(Chef::Role).to receive(:load).and_return(@role)
@stdout = StringIO.new
diff --git a/spec/unit/knife/role_edit_spec.rb b/spec/unit/knife/role_edit_spec.rb
index 5e03b7aef3..3828bc51b9 100644
--- a/spec/unit/knife/role_edit_spec.rb
+++ b/spec/unit/knife/role_edit_spec.rb
@@ -25,7 +25,7 @@ describe Chef::Knife::RoleEdit do
@knife.config[:print_after] = nil
@knife.name_args = [ "adam" ]
allow(@knife.ui).to receive(:output).and_return(true)
- @role = Chef::Role.new()
+ @role = Chef::Role.new
allow(@role).to receive(:save)
allow(Chef::Role).to receive(:load).and_return(@role)
allow(@knife.ui).to receive(:edit_data).and_return(@role)
diff --git a/spec/unit/knife/role_env_run_list_add_spec.rb b/spec/unit/knife/role_env_run_list_add_spec.rb
index 242beeb4a2..39c9740f50 100644
--- a/spec/unit/knife/role_env_run_list_add_spec.rb
+++ b/spec/unit/knife/role_env_run_list_add_spec.rb
@@ -29,7 +29,7 @@ describe Chef::Knife::RoleEnvRunListAdd do
}
@knife.name_args = [ "will", "QA", "role[monkey]" ]
allow(@knife).to receive(:output).and_return(true)
- @role = Chef::Role.new()
+ @role = Chef::Role.new
allow(@role).to receive(:save).and_return(true)
allow(Chef::Role).to receive(:load).and_return(@role)
end
diff --git a/spec/unit/knife/role_env_run_list_clear_spec.rb b/spec/unit/knife/role_env_run_list_clear_spec.rb
index 7a580ecd4a..14d818fa66 100644
--- a/spec/unit/knife/role_env_run_list_clear_spec.rb
+++ b/spec/unit/knife/role_env_run_list_clear_spec.rb
@@ -33,7 +33,7 @@ describe Chef::Knife::RoleEnvRunListClear do
@knife.name_args = %w{will QA}
allow(@knife).to receive(:output).and_return(true)
- @role = Chef::Role.new()
+ @role = Chef::Role.new
@role.name("will")
allow(@role).to receive(:save).and_return(true)
diff --git a/spec/unit/knife/role_env_run_list_remove_spec.rb b/spec/unit/knife/role_env_run_list_remove_spec.rb
index afbabec528..a9eedf9aa1 100644
--- a/spec/unit/knife/role_env_run_list_remove_spec.rb
+++ b/spec/unit/knife/role_env_run_list_remove_spec.rb
@@ -33,7 +33,7 @@ describe Chef::Knife::RoleEnvRunListRemove do
@knife.name_args = [ "will", "QA", "role[monkey]" ]
allow(@knife).to receive(:output).and_return(true)
- @role = Chef::Role.new()
+ @role = Chef::Role.new
@role.name("will")
allow(@role).to receive(:save).and_return(true)
diff --git a/spec/unit/knife/role_env_run_list_replace_spec.rb b/spec/unit/knife/role_env_run_list_replace_spec.rb
index c4d231d638..94ef75fa07 100644
--- a/spec/unit/knife/role_env_run_list_replace_spec.rb
+++ b/spec/unit/knife/role_env_run_list_replace_spec.rb
@@ -33,7 +33,7 @@ describe Chef::Knife::RoleEnvRunListReplace do
@knife.name_args = [ "will", "QA", "role[dude]", "role[person]" ]
allow(@knife).to receive(:output).and_return(true)
- @role = Chef::Role.new()
+ @role = Chef::Role.new
@role.name("will")
allow(@role).to receive(:save).and_return(true)
diff --git a/spec/unit/knife/role_env_run_list_set_spec.rb b/spec/unit/knife/role_env_run_list_set_spec.rb
index 79bd3b152e..4fdef5729f 100644
--- a/spec/unit/knife/role_env_run_list_set_spec.rb
+++ b/spec/unit/knife/role_env_run_list_set_spec.rb
@@ -33,7 +33,7 @@ describe Chef::Knife::RoleEnvRunListSet do
@knife.name_args = [ "will", "QA", "role[owen]", "role[mauntel]" ]
allow(@knife).to receive(:output).and_return(true)
- @role = Chef::Role.new()
+ @role = Chef::Role.new
@role.name("will")
allow(@role).to receive(:save).and_return(true)
diff --git a/spec/unit/knife/role_from_file_spec.rb b/spec/unit/knife/role_from_file_spec.rb
index 827b8ae04d..65a152c1f0 100644
--- a/spec/unit/knife/role_from_file_spec.rb
+++ b/spec/unit/knife/role_from_file_spec.rb
@@ -30,7 +30,7 @@ describe Chef::Knife::RoleFromFile do
@knife.name_args = [ "adam.rb" ]
allow(@knife).to receive(:output).and_return(true)
allow(@knife).to receive(:confirm).and_return(true)
- @role = Chef::Role.new()
+ @role = Chef::Role.new
allow(@role).to receive(:save)
allow(@knife.loader).to receive(:load_from).and_return(@role)
@stdout = StringIO.new
diff --git a/spec/unit/knife/role_run_list_add_spec.rb b/spec/unit/knife/role_run_list_add_spec.rb
index a38b6de9da..38ead92d86 100644
--- a/spec/unit/knife/role_run_list_add_spec.rb
+++ b/spec/unit/knife/role_run_list_add_spec.rb
@@ -29,7 +29,7 @@ describe Chef::Knife::RoleRunListAdd do
}
@knife.name_args = [ "will", "role[monkey]" ]
allow(@knife).to receive(:output).and_return(true)
- @role = Chef::Role.new()
+ @role = Chef::Role.new
allow(@role).to receive(:save).and_return(true)
allow(Chef::Role).to receive(:load).and_return(@role)
end
diff --git a/spec/unit/knife/role_run_list_clear_spec.rb b/spec/unit/knife/role_run_list_clear_spec.rb
index 8bbc816d6f..b62cc06571 100644
--- a/spec/unit/knife/role_run_list_clear_spec.rb
+++ b/spec/unit/knife/role_run_list_clear_spec.rb
@@ -32,7 +32,7 @@ describe Chef::Knife::RoleRunListClear do
@knife.name_args = [ "will" ]
allow(@knife).to receive(:output).and_return(true)
- @role = Chef::Role.new()
+ @role = Chef::Role.new
@role.name("will")
allow(@role).to receive(:save).and_return(true)
diff --git a/spec/unit/knife/role_run_list_remove_spec.rb b/spec/unit/knife/role_run_list_remove_spec.rb
index c18416feca..c4f0e6d32e 100644
--- a/spec/unit/knife/role_run_list_remove_spec.rb
+++ b/spec/unit/knife/role_run_list_remove_spec.rb
@@ -32,7 +32,7 @@ describe Chef::Knife::RoleRunListRemove do
@knife.name_args = [ "will", "role[monkey]" ]
allow(@knife).to receive(:output).and_return(true)
- @role = Chef::Role.new()
+ @role = Chef::Role.new
@role.name("will")
allow(@role).to receive(:save).and_return(true)
diff --git a/spec/unit/knife/role_run_list_replace_spec.rb b/spec/unit/knife/role_run_list_replace_spec.rb
index 9b212de0ae..aa76efe249 100644
--- a/spec/unit/knife/role_run_list_replace_spec.rb
+++ b/spec/unit/knife/role_run_list_replace_spec.rb
@@ -32,7 +32,7 @@ describe Chef::Knife::RoleRunListReplace do
@knife.name_args = [ "will", "role[dude]", "role[person]" ]
allow(@knife).to receive(:output).and_return(true)
- @role = Chef::Role.new()
+ @role = Chef::Role.new
@role.name("will")
allow(@role).to receive(:save).and_return(true)
diff --git a/spec/unit/knife/role_run_list_set_spec.rb b/spec/unit/knife/role_run_list_set_spec.rb
index f8e440f524..69543dbda4 100644
--- a/spec/unit/knife/role_run_list_set_spec.rb
+++ b/spec/unit/knife/role_run_list_set_spec.rb
@@ -32,7 +32,7 @@ describe Chef::Knife::RoleRunListSet do
@knife.name_args = [ "will", "role[owen]", "role[mauntel]" ]
allow(@knife).to receive(:output).and_return(true)
- @role = Chef::Role.new()
+ @role = Chef::Role.new
@role.name("will")
allow(@role).to receive(:save).and_return(true)
diff --git a/spec/unit/knife/status_spec.rb b/spec/unit/knife/status_spec.rb
index 929a0f742b..dc66007c32 100644
--- a/spec/unit/knife/status_spec.rb
+++ b/spec/unit/knife/status_spec.rb
@@ -40,7 +40,8 @@ describe Chef::Knife::Status do
{ filter_result:
{ name: ["name"], ipaddress: ["ipaddress"], ohai_time: ["ohai_time"],
ec2: ["ec2"], run_list: ["run_list"], platform: ["platform"],
- platform_version: ["platform_version"], chef_environment: ["chef_environment"] } } end
+ platform_version: ["platform_version"], chef_environment: ["chef_environment"] } }
+ end
it "should default to searching for everything" do
expect(@query).to receive(:search).with(:node, "*:*", opts)
diff --git a/spec/unit/knife/supermarket_install_spec.rb b/spec/unit/knife/supermarket_install_spec.rb
index d891de9268..9c969106fc 100644
--- a/spec/unit/knife/supermarket_install_spec.rb
+++ b/spec/unit/knife/supermarket_install_spec.rb
@@ -23,12 +23,13 @@ describe Chef::Knife::SupermarketInstall do
let(:knife) { Chef::Knife::SupermarketInstall.new }
let(:stdout) { StringIO.new }
let(:stderr) { StringIO.new }
- let(:downloader) { Hash.new }
+ let(:downloader) { {} }
let(:archive) { double(Mixlib::Archive, extract: true) }
let(:repo) do
double(sanity_check: true, reset_to_default_state: true,
prepare_to_import: true, finalize_updates_to: true,
- merge_updates_from: true) end
+ merge_updates_from: true)
+ end
let(:install_path) do
if Chef::Platform.windows?
"C:/tmp/chef"
diff --git a/spec/unit/knife/supermarket_share_spec.rb b/spec/unit/knife/supermarket_share_spec.rb
index 6601cdcd31..6fdcc6c92f 100644
--- a/spec/unit/knife/supermarket_share_spec.rb
+++ b/spec/unit/knife/supermarket_share_spec.rb
@@ -175,7 +175,7 @@ describe Chef::Knife::SupermarketShare do
response_text = Chef::JSONCompat.to_json({ uri: "https://supermarket.chef.io/cookbooks/cookbook_name" })
allow(@upload_response).to receive(:body).and_return(response_text)
allow(@upload_response).to receive(:code).and_return(201)
- expect(Chef::CookbookSiteStreamingUploader).to receive(:post).with(/supermarket\.chef\.io/, anything(), anything(), anything())
+ expect(Chef::CookbookSiteStreamingUploader).to receive(:post).with(/supermarket\.chef\.io/, anything, anything, anything)
@knife.run
end
diff --git a/spec/unit/knife_spec.rb b/spec/unit/knife_spec.rb
index 2c14e417b4..6ed7ddd70e 100644
--- a/spec/unit/knife_spec.rb
+++ b/spec/unit/knife_spec.rb
@@ -55,7 +55,7 @@ describe Chef::Knife do
allow(knife.ui).to receive(:print)
allow(Chef::Log).to receive(:init)
allow(Chef::Log).to receive(:level)
- [:debug, :info, :warn, :error, :crit].each do |level_sym|
+ %i{debug info warn error crit}.each do |level_sym|
allow(Chef::Log).to receive(level_sym)
end
allow(Chef::Knife).to receive(:puts)
@@ -166,7 +166,8 @@ describe Chef::Knife do
"X-Chef-Version" => Chef::VERSION,
"Host" => "api.opscode.piab",
"X-REMOTE-REQUEST-ID" => request_id,
- } end
+ }
+ end
let(:request_id) { "1234" }
@@ -205,7 +206,7 @@ describe Chef::Knife do
KnifeSpecs.send :remove_const, :TestYourself
end
Kernel.load(File.join(CHEF_SPEC_DATA, "knife_subcommand", "test_yourself.rb"))
- Chef::Knife.subcommands.each { |name, klass| Chef::Knife.subcommands.delete(name) unless klass.kind_of?(Class) }
+ Chef::Knife.subcommands.each { |name, klass| Chef::Knife.subcommands.delete(name) unless klass.is_a?(Class) }
end
it "confirms that the headers include X-Remote-Request-Id" do
@@ -220,7 +221,7 @@ describe Chef::Knife do
KnifeSpecs.send :remove_const, :TestYourself
end
Kernel.load(File.join(CHEF_SPEC_DATA, "knife_subcommand", "test_yourself.rb"))
- Chef::Knife.subcommands.each { |name, klass| Chef::Knife.subcommands.delete(name) unless klass.kind_of?(Class) }
+ Chef::Knife.subcommands.each { |name, klass| Chef::Knife.subcommands.delete(name) unless klass.is_a?(Class) }
end
it "merges the global knife CLI options" do
@@ -468,8 +469,8 @@ describe Chef::Knife do
allow(knife).to receive(:run).and_raise(Net::HTTPClientException.new("403 Forbidden", response))
allow(knife).to receive(:username).and_return("sadpanda")
knife.run_with_pretty_exceptions
- expect(stderr.string).to match(%r{ERROR: You authenticated successfully to http.+ as sadpanda but you are not authorized for this action})
- expect(stderr.string).to match(%r{Response: y u no administrator})
+ expect(stderr.string).to match(/ERROR: You authenticated successfully to http.+ as sadpanda but you are not authorized for this action/)
+ expect(stderr.string).to match(/Response: y u no administrator/)
end
context "when proxy servers are set" do
@@ -488,9 +489,9 @@ describe Chef::Knife do
allow(knife).to receive(:run).and_raise(Net::HTTPClientException.new("403 Forbidden", response))
allow(knife).to receive(:username).and_return("sadpanda")
knife.run_with_pretty_exceptions
- expect(stderr.string).to match(%r{ERROR: You authenticated successfully to http.+ as sadpanda but you are not authorized for this action})
- expect(stderr.string).to match(%r{ERROR: There are proxy servers configured, your server url may need to be added to NO_PROXY.})
- expect(stderr.string).to match(%r{Response: y u no administrator})
+ expect(stderr.string).to match(/ERROR: You authenticated successfully to http.+ as sadpanda but you are not authorized for this action/)
+ expect(stderr.string).to match(/ERROR: There are proxy servers configured, your server url may need to be added to NO_PROXY./)
+ expect(stderr.string).to match(/Response: y u no administrator/)
end
end
@@ -500,8 +501,8 @@ describe Chef::Knife do
allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(error: "y u search wrong"))
allow(knife).to receive(:run).and_raise(Net::HTTPClientException.new("400 Bad Request", response))
knife.run_with_pretty_exceptions
- expect(stderr.string).to match(%r{ERROR: The data in your request was invalid})
- expect(stderr.string).to match(%r{Response: y u search wrong})
+ expect(stderr.string).to match(/ERROR: The data in your request was invalid/)
+ expect(stderr.string).to match(/Response: y u search wrong/)
end
it "formats 404s nicely" do
@@ -510,8 +511,8 @@ describe Chef::Knife do
allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(error: "nothing to see here"))
allow(knife).to receive(:run).and_raise(Net::HTTPClientException.new("404 Not Found", response))
knife.run_with_pretty_exceptions
- expect(stderr.string).to match(%r{ERROR: The object you are looking for could not be found})
- expect(stderr.string).to match(%r{Response: nothing to see here})
+ expect(stderr.string).to match(/ERROR: The object you are looking for could not be found/)
+ expect(stderr.string).to match(/Response: nothing to see here/)
end
it "formats 406s (non-supported API version error) nicely" do
@@ -536,8 +537,8 @@ describe Chef::Knife do
allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(error: "sad trombone"))
allow(knife).to receive(:run).and_raise(Net::HTTPFatalError.new("500 Internal Server Error", response))
knife.run_with_pretty_exceptions
- expect(stderr.string).to match(%r{ERROR: internal server error})
- expect(stderr.string).to match(%r{Response: sad trombone})
+ expect(stderr.string).to match(/ERROR: internal server error/)
+ expect(stderr.string).to match(/Response: sad trombone/)
end
it "formats 502s nicely" do
@@ -546,8 +547,8 @@ describe Chef::Knife do
allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(error: "sadder trombone"))
allow(knife).to receive(:run).and_raise(Net::HTTPFatalError.new("502 Bad Gateway", response))
knife.run_with_pretty_exceptions
- expect(stderr.string).to match(%r{ERROR: bad gateway})
- expect(stderr.string).to match(%r{Response: sadder trombone})
+ expect(stderr.string).to match(/ERROR: bad gateway/)
+ expect(stderr.string).to match(/Response: sadder trombone/)
end
it "formats 503s nicely" do
@@ -556,8 +557,8 @@ describe Chef::Knife do
allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(error: "saddest trombone"))
allow(knife).to receive(:run).and_raise(Net::HTTPFatalError.new("503 Service Unavailable", response))
knife.run_with_pretty_exceptions
- expect(stderr.string).to match(%r{ERROR: Service temporarily unavailable})
- expect(stderr.string).to match(%r{Response: saddest trombone})
+ expect(stderr.string).to match(/ERROR: Service temporarily unavailable/)
+ expect(stderr.string).to match(/Response: saddest trombone/)
end
it "formats other HTTP errors nicely" do
@@ -566,16 +567,16 @@ describe Chef::Knife do
allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(error: "nobugfixtillyoubuy"))
allow(knife).to receive(:run).and_raise(Net::HTTPClientException.new("402 Payment Required", response))
knife.run_with_pretty_exceptions
- expect(stderr.string).to match(%r{ERROR: Payment Required})
- expect(stderr.string).to match(%r{Response: nobugfixtillyoubuy})
+ expect(stderr.string).to match(/ERROR: Payment Required/)
+ expect(stderr.string).to match(/Response: nobugfixtillyoubuy/)
end
it "formats NameError and NoMethodError nicely" do
allow(knife).to receive(:run).and_raise(NameError.new("Undefined constant FUUU"))
knife.run_with_pretty_exceptions
- expect(stderr.string).to match(%r{ERROR: .* encountered an unexpected error})
- expect(stderr.string).to match(%r{This may be a bug in the 'knife' .* command or plugin})
- expect(stderr.string).to match(%r{Exception: NameError: Undefined constant FUUU})
+ expect(stderr.string).to match(/ERROR: .* encountered an unexpected error/)
+ expect(stderr.string).to match(/This may be a bug in the 'knife' .* command or plugin/)
+ expect(stderr.string).to match(/Exception: NameError: Undefined constant FUUU/)
end
it "formats missing private key errors nicely" do
@@ -583,7 +584,7 @@ describe Chef::Knife do
allow(knife).to receive(:api_key).and_return("/home/root/.chef/no-key-here.pem")
knife.run_with_pretty_exceptions
expect(stderr.string).to match(%r{ERROR: Your private key could not be loaded from /home/root/.chef/no-key-here.pem})
- expect(stderr.string).to match(%r{Check your configuration file and ensure that your private key is readable})
+ expect(stderr.string).to match(/Check your configuration file and ensure that your private key is readable/)
end
it "formats connection refused errors nicely" do
@@ -592,8 +593,8 @@ describe Chef::Knife do
# Errno::ECONNREFUSED message differs by platform
# *nix = Errno::ECONNREFUSED: Connection refused
# win32: Errno::ECONNREFUSED: No connection could be made because the target machine actively refused it.
- expect(stderr.string).to match(%r{ERROR: Network Error: .* - y u no shut up})
- expect(stderr.string).to match(%r{Check your .* configuration and network settings})
+ expect(stderr.string).to match(/ERROR: Network Error: .* - y u no shut up/)
+ expect(stderr.string).to match(/Check your .* configuration and network settings/)
end
it "formats SSL errors nicely and suggests to use `knife ssl check` and `knife ssl fetch`" do
diff --git a/spec/unit/lwrp_spec.rb b/spec/unit/lwrp_spec.rb
index a7f95f8bfd..def981801e 100644
--- a/spec/unit/lwrp_spec.rb
+++ b/spec/unit/lwrp_spec.rb
@@ -199,7 +199,7 @@ describe "LWRP" do
end
it "should create a method for each attribute" do
- expect(get_lwrp(:lwrp_foo).new("blah").methods.map { |m| m.to_sym }).to include(:monkey)
+ expect(get_lwrp(:lwrp_foo).new("blah").methods.map(&:to_sym)).to include(:monkey)
end
it "should build attribute methods that respect validation rules" do
@@ -264,12 +264,12 @@ describe "LWRP" do
let(:lwrp) do
Class.new(Chef::Resource::LWRPBase) do
actions :eat, :sleep
- default_action [:eat, :sleep]
+ default_action %i{eat sleep}
end
end
it "returns the array of default actions" do
- expect(lwrp.default_action).to eq([:eat, :sleep])
+ expect(lwrp.default_action).to eq(%i{eat sleep})
end
end
@@ -287,7 +287,7 @@ describe "LWRP" do
end
it "delegates #actions to the parent" do
- expect(child.actions).to eq([:nothing, :eat, :sleep])
+ expect(child.actions).to eq(%i{nothing eat sleep})
end
it "delegates #default_action to the parent" do
@@ -304,7 +304,7 @@ describe "LWRP" do
end
it "does not delegate #actions to the parent" do
- expect(child.actions).to eq([:nothing, :dont_eat, :dont_sleep])
+ expect(child.actions).to eq(%i{nothing dont_eat dont_sleep})
end
it "does not delegate #default_action to the parent" do
@@ -322,7 +322,7 @@ describe "LWRP" do
end
it "amends actions when they are already defined" do
- expect(child.actions).to eq([:nothing, :eat, :sleep, :drink])
+ expect(child.actions).to eq(%i{nothing eat sleep drink})
end
end
end
@@ -330,40 +330,40 @@ describe "LWRP" do
describe "when actions is set to an array" do
let(:resource_class) do
Class.new(Chef::Resource::LWRPBase) do
- actions [ :eat, :sleep ]
+ actions %i{eat sleep}
end
end
let(:resource) do
resource_class.new("blah")
end
it "actions includes those actions" do
- expect(resource_class.actions).to eq [ :nothing, :eat, :sleep ]
+ expect(resource_class.actions).to eq %i{nothing eat sleep}
end
it "allowed_actions includes those actions" do
- expect(resource_class.allowed_actions).to eq [ :nothing, :eat, :sleep ]
+ expect(resource_class.allowed_actions).to eq %i{nothing eat sleep}
end
it "resource.allowed_actions includes those actions" do
- expect(resource.allowed_actions).to eq [ :nothing, :eat, :sleep ]
+ expect(resource.allowed_actions).to eq %i{nothing eat sleep}
end
end
describe "when allowed_actions is set to an array" do
let(:resource_class) do
Class.new(Chef::Resource::LWRPBase) do
- allowed_actions [ :eat, :sleep ]
+ allowed_actions %i{eat sleep}
end
end
let(:resource) do
resource_class.new("blah")
end
it "actions includes those actions" do
- expect(resource_class.actions).to eq [ :nothing, :eat, :sleep ]
+ expect(resource_class.actions).to eq %i{nothing eat sleep}
end
it "allowed_actions includes those actions" do
- expect(resource_class.allowed_actions).to eq [ :nothing, :eat, :sleep ]
+ expect(resource_class.allowed_actions).to eq %i{nothing eat sleep}
end
it "resource.allowed_actions includes those actions" do
- expect(resource.allowed_actions).to eq [ :nothing, :eat, :sleep ]
+ expect(resource.allowed_actions).to eq %i{nothing eat sleep}
end
end
end
@@ -590,7 +590,7 @@ describe "LWRP" do
it "get_lwrp(:lwrp_once).new is an instance of the LWRP class" do
lwrp = get_lwrp(:lwrp_once).new("hi")
- expect(lwrp.kind_of?(test_lwrp_class)).to be_truthy
+ expect(lwrp.is_a?(test_lwrp_class)).to be_truthy
expect(lwrp.is_a?(test_lwrp_class)).to be_truthy
expect(get_lwrp(:lwrp_once) === lwrp).to be_truthy
expect(test_lwrp_class === lwrp).to be_truthy
@@ -603,28 +603,28 @@ describe "LWRP" do
it "subclass.new is a subclass" do
lwrp = subclass.new("hi")
- expect(lwrp.kind_of?(subclass)).to be_truthy
+ expect(lwrp.is_a?(subclass)).to be_truthy
expect(lwrp.is_a?(subclass)).to be_truthy
expect(subclass === lwrp).to be_truthy
expect(lwrp.class === subclass)
end
it "subclass.new is an instance of the LWRP class" do
lwrp = subclass.new("hi")
- expect(lwrp.kind_of?(test_lwrp_class)).to be_truthy
+ expect(lwrp.is_a?(test_lwrp_class)).to be_truthy
expect(lwrp.is_a?(test_lwrp_class)).to be_truthy
expect(test_lwrp_class === lwrp).to be_truthy
expect(lwrp.class === test_lwrp_class)
end
it "subclass.new is a get_lwrp(:lwrp_once)" do
lwrp = subclass.new("hi")
- expect(lwrp.kind_of?(get_lwrp(:lwrp_once))).to be_truthy
+ expect(lwrp.is_a?(get_lwrp(:lwrp_once))).to be_truthy
expect(lwrp.is_a?(get_lwrp(:lwrp_once))).to be_truthy
expect(get_lwrp(:lwrp_once) === lwrp).to be_truthy
expect(lwrp.class === get_lwrp(:lwrp_once))
end
it "get_lwrp(:lwrp_once).new is *not* a subclass" do
lwrp = get_lwrp(:lwrp_once).new("hi")
- expect(lwrp.kind_of?(subclass)).to be_falsey
+ expect(lwrp.is_a?(subclass)).to be_falsey
expect(lwrp.is_a?(subclass)).to be_falsey
expect(subclass === lwrp.class).to be_falsey
expect(subclass === get_lwrp(:lwrp_once)).to be_falsey
diff --git a/spec/unit/mixin/homebrew_user_spec.rb b/spec/unit/mixin/homebrew_user_spec.rb
index df89962cce..7d2da85e2d 100644
--- a/spec/unit/mixin/homebrew_user_spec.rb
+++ b/spec/unit/mixin/homebrew_user_spec.rb
@@ -48,7 +48,7 @@ describe Chef::Mixin::HomebrewUser do
let(:brew_owner) { 2001 }
let(:default_brew_path) { "/usr/local/bin/brew" }
let(:stat_double) do
- d = double()
+ d = double
expect(d).to receive(:uid).and_return(brew_owner)
d
end
diff --git a/spec/unit/mixin/params_validate_spec.rb b/spec/unit/mixin/params_validate_spec.rb
index 1cc7fef58e..489742cb7d 100644
--- a/spec/unit/mixin/params_validate_spec.rb
+++ b/spec/unit/mixin/params_validate_spec.rb
@@ -30,7 +30,7 @@ end
describe Chef::Mixin::ParamsValidate do
before(:each) do
- @vo = TinyClass.new()
+ @vo = TinyClass.new
end
it "should allow a hash and a hash as arguments to validate" do
@@ -44,7 +44,7 @@ describe Chef::Mixin::ParamsValidate do
it "should require validation map keys to be symbols or strings" do
expect { @vo.validate({ one: "two" }, { one: true }) }.not_to raise_error
expect { @vo.validate({ one: "two" }, { "one" => true }) }.not_to raise_error
- expect { @vo.validate({ one: "two" }, { Hash.new => true }) }.to raise_error(ArgumentError)
+ expect { @vo.validate({ one: "two" }, { {} => true }) }.to raise_error(ArgumentError)
end
it "should allow options to be required with true" do
@@ -163,7 +163,7 @@ describe Chef::Mixin::ParamsValidate do
end
it "should let you set a default value with default => value" do
- arguments = Hash.new
+ arguments = {}
@vo.validate(arguments, {
one: {
default: "is the loneliest number",
@@ -236,7 +236,7 @@ describe Chef::Mixin::ParamsValidate do
{
one: {
kind_of: String,
- respond_to: [ :to_s, :upcase ],
+ respond_to: %i{to_s upcase},
regex: /^is good/,
callbacks: {
"should be your friend" => lambda do |a|
@@ -260,7 +260,7 @@ describe Chef::Mixin::ParamsValidate do
{
one: {
kind_of: String,
- respond_to: [ :to_s, :upcase ],
+ respond_to: %i{to_s upcase},
regex: /^is good/,
callbacks: {
"should be your friend" => lambda do |a|
@@ -321,7 +321,7 @@ describe Chef::Mixin::ParamsValidate do
end.not_to raise_error
expect do
@vo.validate(
- { one: Hash.new },
+ { one: {} },
{
one: {
kind_of: [ String, Array ],
@@ -334,22 +334,22 @@ describe Chef::Mixin::ParamsValidate do
it "asserts that a value returns false from a predicate method" do
expect do
@vo.validate({ not_blank: "should pass" },
- { not_blank: { cannot_be: [ :nil, :empty ] } })
+ { not_blank: { cannot_be: %i{nil empty} } })
end.not_to raise_error
expect do
@vo.validate({ not_blank: "" },
- { not_blank: { cannot_be: [ :nil, :empty ] } })
+ { not_blank: { cannot_be: %i{nil empty} } })
end.to raise_error(Chef::Exceptions::ValidationFailed)
end
it "allows a custom validation message" do
expect do
@vo.validate({ not_blank: "should pass" },
- { not_blank: { cannot_be: [ :nil, :empty ], validation_message: "my validation message" } })
+ { not_blank: { cannot_be: %i{nil empty}, validation_message: "my validation message" } })
end.not_to raise_error
expect do
@vo.validate({ not_blank: "" },
- { not_blank: { cannot_be: [ :nil, :empty ], validation_message: "my validation message" } })
+ { not_blank: { cannot_be: %i{nil empty}, validation_message: "my validation message" } })
end.to raise_error(Chef::Exceptions::ValidationFailed, "my validation message")
end
diff --git a/spec/unit/mixin/properties_spec.rb b/spec/unit/mixin/properties_spec.rb
index ee0c252381..25b94178e5 100644
--- a/spec/unit/mixin/properties_spec.rb
+++ b/spec/unit/mixin/properties_spec.rb
@@ -31,7 +31,7 @@ module ChefMixinPropertiesSpec
end
it "A.properties has a, ab, and ac with types 'a', ['a', 'b'], and ['b', 'c']" do
- expect(A.properties.keys).to eq [ :a, :ab, :ac, :d ]
+ expect(A.properties.keys).to eq %i{a ab ac d}
expect(A.properties[:a].validation_options[:is]).to eq "a"
expect(A.properties[:ab].validation_options[:is]).to eq %w{a b}
expect(A.properties[:ac].validation_options[:is]).to eq %w{a c}
@@ -46,13 +46,13 @@ module ChefMixinPropertiesSpec
end
it "B.properties has b, ab, and bc with types 'b', nil and ['b', 'c']" do
- expect(B.properties.keys).to eq [ :b, :ab, :bc ]
+ expect(B.properties.keys).to eq %i{b ab bc}
expect(B.properties[:b].validation_options[:is]).to eq "b"
expect(B.properties[:ab].validation_options[:is]).to be_nil
expect(B.properties[:bc].validation_options[:is]).to eq %w{b c}
end
it "C.properties has a, b, c, ac and bc with merged types" do
- expect(C.properties.keys).to eq [ :a, :ab, :ac, :d, :b, :bc, :c ]
+ expect(C.properties.keys).to eq %i{a ab ac d b bc c}
expect(C.properties[:a].validation_options[:is]).to eq "a"
expect(C.properties[:b].validation_options[:is]).to eq "b"
expect(C.properties[:c].validation_options[:is]).to eq "c"
@@ -99,7 +99,7 @@ module ChefMixinPropertiesSpec
end
it "Outerest.properties.validation_options[:is] inner, outer, outerest" do
- expect(Outerest.properties.keys).to eq [:inner, :outer, :outerest]
+ expect(Outerest.properties.keys).to eq %i{inner outer outerest}
end
end
end
diff --git a/spec/unit/mixin/shell_out_spec.rb b/spec/unit/mixin/shell_out_spec.rb
index 4f8e4dafac..1c4f59b50b 100644
--- a/spec/unit/mixin/shell_out_spec.rb
+++ b/spec/unit/mixin/shell_out_spec.rb
@@ -51,7 +51,7 @@ describe Chef::Mixin::ShellOut do
let(:retobj) { instance_double(Mixlib::ShellOut, "error!" => false) }
let(:cmd) { "echo '#{rand(1000)}'" }
- [ :shell_out, :shell_out! ].each do |method|
+ %i{shell_out shell_out!}.each do |method|
describe "##{method}" do
describe "when the last argument is a Hash" do
@@ -248,7 +248,7 @@ describe Chef::Mixin::ShellOut do
let(:provider) { new_resource.provider_for_action(:install) }
describe "on Chef-15", chef: ">= 15" do
- [ :shell_out, :shell_out! ].each do |method|
+ %i{shell_out shell_out!}.each do |method|
stubbed_method = (method == :shell_out) ? :shell_out_compacted : :shell_out_compacted!
it "#{method} defaults to 900 seconds" do
expect(provider).to receive(stubbed_method).with("foo", timeout: 900)
@@ -284,7 +284,7 @@ describe Chef::Mixin::ShellOut do
let(:new_resource) { Chef::Resource::Package.new("foo") }
let(:provider) { new_resource.provider_for_action(:install) }
- [ :shell_out, :shell_out! ].each do |method|
+ %i{shell_out shell_out!}.each do |method|
stubbed_method = (method == :shell_out) ? :shell_out_compacted : :shell_out_compacted!
it "#{method} defaults to 900 seconds" do
expect(provider).to receive(stubbed_method).with("foo", timeout: 900)
diff --git a/spec/unit/mixin/template_spec.rb b/spec/unit/mixin/template_spec.rb
index 96b983a9dd..04071988ad 100644
--- a/spec/unit/mixin/template_spec.rb
+++ b/spec/unit/mixin/template_spec.rb
@@ -242,17 +242,13 @@ describe Chef::Mixin::Template, "render_template" do
it "emits a warning when overriding 'core' methods" do
mod = Module.new do
- def render
- end
+ def render; end
- def node
- end
+ def node; end
- def render_template
- end
+ def render_template; end
- def render_template_from_string
- end
+ def render_template_from_string; end
end
%w{node render render_template render_template_from_string}.each do |method_name|
expect(Chef::Log).to receive(:warn).with(/^Core template method `#{method_name}' overridden by extension module/)
diff --git a/spec/unit/mixin/unformatter_spec.rb b/spec/unit/mixin/unformatter_spec.rb
index b2b57c150c..3c8dba1962 100644
--- a/spec/unit/mixin/unformatter_spec.rb
+++ b/spec/unit/mixin/unformatter_spec.rb
@@ -22,8 +22,7 @@ require "chef/mixin/unformatter"
class Chef::UnformatterTest
include Chef::Mixin::Unformatter
- def foo
- end
+ def foo; end
end
diff --git a/spec/unit/mixin/user_context_spec.rb b/spec/unit/mixin/user_context_spec.rb
index 896241f173..31e182d042 100644
--- a/spec/unit/mixin/user_context_spec.rb
+++ b/spec/unit/mixin/user_context_spec.rb
@@ -56,8 +56,7 @@ describe "a class that mixes in user_context" do
let(:block_object) do
class BlockClass
- def block_method
- end
+ def block_method; end
end
BlockClass.new
end
diff --git a/spec/unit/mixin/which.rb b/spec/unit/mixin/which.rb
index 1764b3b89f..c47eaf37ab 100644
--- a/spec/unit/mixin/which.rb
+++ b/spec/unit/mixin/which.rb
@@ -88,11 +88,13 @@ describe Chef::Mixin::Which do
test_which("passes in the filename as the arg", "foo1", finds: "/dir1/foo1") do |f|
raise "bad arg to block" unless f == "/dir1/foo1"
+
true
end
test_which("arrays with blocks", "foo1", "foo2", finds: "/dir2/foo1", others: [ "/dir1/foo2" ]) do |f|
raise "bad arg to block" unless f == "/dir2/foo1" || f == "/dir1/foo2"
+
true
end
end
diff --git a/spec/unit/mixin/windows_architecture_helper_spec.rb b/spec/unit/mixin/windows_architecture_helper_spec.rb
index 4559702e1c..ad7bee0ec9 100644
--- a/spec/unit/mixin/windows_architecture_helper_spec.rb
+++ b/spec/unit/mixin/windows_architecture_helper_spec.rb
@@ -23,7 +23,7 @@ describe Chef::Mixin::WindowsArchitectureHelper do
include Chef::Mixin::WindowsArchitectureHelper
before do
- @valid_architectures = [ :i386, :x86_64 ]
+ @valid_architectures = %i{i386 x86_64}
@invalid_architectures = [ "i386", "x86_64", :x64, :x86, :arm ]
@node_i386 = Chef::Node.new
@@ -67,14 +67,14 @@ describe Chef::Mixin::WindowsArchitectureHelper do
it "returns true only when forced_32bit_override_required? has 64-bit node architecture and 32-bit desired architecture" do
with_node_architecture_combinations do |node, desired_arch|
expect(forced_32bit_override_required?(node, desired_arch)).to be true if (node_windows_architecture(node) == :x86_64) && (desired_arch == :i386) && !is_i386_process_on_x86_64_windows?
- expect(forced_32bit_override_required?(node, desired_arch)).to be false if ! ((node_windows_architecture(node) == :x86_64) && (desired_arch == :i386))
+ expect(forced_32bit_override_required?(node, desired_arch)).to be false unless (node_windows_architecture(node) == :x86_64) && (desired_arch == :i386)
end
end
def with_node_architecture_combinations
@valid_architectures.each do |node_architecture|
new_node = Chef::Node.new
- new_node.default["kernel"] = Hash.new
+ new_node.default["kernel"] = {}
new_node.default["kernel"][:machine] = node_architecture.to_s
@valid_architectures.each do |architecture|
diff --git a/spec/unit/node/attribute_spec.rb b/spec/unit/node/attribute_spec.rb
index 29e299566b..5055941d06 100644
--- a/spec/unit/node/attribute_spec.rb
+++ b/spec/unit/node/attribute_spec.rb
@@ -182,7 +182,7 @@ describe Chef::Node::Attribute do
expect { Chef::Node::Attribute.new({}, {}, {}, {}) }.not_to raise_error
end
- [ :normal, :default, :override, :automatic ].each do |accessor|
+ %i{normal default override automatic}.each do |accessor|
it "should set #{accessor}" do
na = Chef::Node::Attribute.new({ normal: true }, { default: true }, { override: true }, { automatic: true })
expect(na.send(accessor)).to eq({ accessor.to_s => true })
@@ -546,7 +546,7 @@ describe Chef::Node::Attribute do
expect(@attributes["music"]["this"]).not_to have_key("must")
end
- [:include?, :key?, :member?].each do |method|
+ %i{include? key? member?}.each do |method|
it "should alias the method #{method} to itself" do
expect(@attributes).to respond_to(method)
end
@@ -589,7 +589,7 @@ describe Chef::Node::Attribute do
end
it "should yield each top level key" do
- collect = Array.new
+ collect = []
@attributes.each_key do |k|
collect << k
end
@@ -602,7 +602,7 @@ describe Chef::Node::Attribute do
end
it "should yield lower if we go deeper" do
- collect = Array.new
+ collect = []
@attributes["one"].each_key do |k|
collect << k
end
@@ -637,7 +637,7 @@ describe Chef::Node::Attribute do
end
it "should yield each top level key and value, post merge rules" do
- collect = Hash.new
+ collect = {}
@attributes.each do |k, v|
collect[k] = v
end
@@ -679,7 +679,7 @@ describe Chef::Node::Attribute do
end
it "should yield each top level key, post merge rules" do
- collect = Array.new
+ collect = []
@attributes.each_key do |k|
collect << k
end
@@ -715,7 +715,7 @@ describe Chef::Node::Attribute do
end
it "should yield each top level key and value pair, post merge rules" do
- collect = Hash.new
+ collect = {}
@attributes.each_pair do |k, v|
collect[k] = v
end
@@ -751,7 +751,7 @@ describe Chef::Node::Attribute do
end
it "should yield each value, post merge rules" do
- collect = Array.new
+ collect = []
@attributes.each_value do |v|
collect << v
end
@@ -762,7 +762,7 @@ describe Chef::Node::Attribute do
end
it "should yield four elements" do
- collect = Array.new
+ collect = []
@attributes.each_value do |v|
collect << v
end
diff --git a/spec/unit/node/immutable_collections_spec.rb b/spec/unit/node/immutable_collections_spec.rb
index 2208c45717..f23e40dc4c 100644
--- a/spec/unit/node/immutable_collections_spec.rb
+++ b/spec/unit/node/immutable_collections_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Daniel DeLeo (<dan@chef.io>)
-# Copyright:: Copyright 2012-2018, Chef Software Inc.
+# Copyright:: Copyright 2012-2019, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -145,25 +145,25 @@ describe Chef::Node::ImmutableMash do
end
end
- [
- :[]=,
- :clear,
- :default=,
- :default_proc=,
- :delete,
- :delete_if,
- :keep_if,
- :merge!,
- :update,
- :reject!,
- :replace,
- :select!,
- :shift,
- :write,
- :write!,
- :unlink,
- :unlink!,
- ].each do |mutator|
+ %i{
+ []=
+ clear
+ default=
+ default_proc=
+ delete
+ delete_if
+ keep_if
+ merge!
+ update
+ reject!
+ replace
+ select!
+ shift
+ write
+ write!
+ unlink
+ unlink!
+ }.each do |mutator|
it "doesn't allow mutation via `#{mutator}'" do
expect { @immutable_mash.send(mutator) }.to raise_error(Chef::Exceptions::ImmutableAttributeModification)
end
@@ -190,36 +190,36 @@ describe Chef::Node::ImmutableArray do
# with ImmutableMash, above
###
- [
- :<<,
- :[]=,
- :clear,
- :collect!,
- :compact!,
- :default=,
- :default_proc=,
- :delete,
- :delete_at,
- :delete_if,
- :fill,
- :flatten!,
- :insert,
- :keep_if,
- :map!,
- :merge!,
- :pop,
- :push,
- :reject!,
- :reverse!,
- :replace,
- :select!,
- :shift,
- :slice!,
- :sort!,
- :sort_by!,
- :uniq!,
- :unshift,
- ].each do |mutator|
+ %i{
+ <<
+ []=
+ clear
+ collect!
+ compact!
+ default=
+ default_proc=
+ delete
+ delete_at
+ delete_if
+ fill
+ flatten!
+ insert
+ keep_if
+ map!
+ merge!
+ pop
+ push
+ reject!
+ reverse!
+ replace
+ select!
+ shift
+ slice!
+ sort!
+ sort_by!
+ uniq!
+ unshift
+ }.each do |mutator|
it "does not allow mutation via `#{mutator}" do
expect { @immutable_array.send(mutator) }.to raise_error(Chef::Exceptions::ImmutableAttributeModification)
end
diff --git a/spec/unit/node_spec.rb b/spec/unit/node_spec.rb
index 2d28a3e961..1c84278ad5 100644
--- a/spec/unit/node_spec.rb
+++ b/spec/unit/node_spec.rb
@@ -21,7 +21,7 @@ require "ostruct"
describe Chef::Node do
- let(:node) { Chef::Node.new() }
+ let(:node) { Chef::Node.new }
let(:platform_introspector) { node }
it_behaves_like "a platform introspector"
@@ -103,7 +103,7 @@ describe Chef::Node do
end
it "should always have a string for name" do
- expect { node.name(Hash.new) }.to raise_error(ArgumentError)
+ expect { node.name({}) }.to raise_error(ArgumentError)
end
it "cannot be blank" do
@@ -126,7 +126,7 @@ describe Chef::Node do
end
it "should disallow non-strings" do
- expect { node.chef_environment(Hash.new) }.to raise_error(ArgumentError)
+ expect { node.chef_environment({}) }.to raise_error(ArgumentError)
expect { node.chef_environment(42) }.to raise_error(ArgumentError)
end
@@ -162,7 +162,7 @@ describe Chef::Node do
end
it "disallows non-strings" do
- expect { node.policy_name(Hash.new) }.to raise_error(Chef::Exceptions::ValidationFailed)
+ expect { node.policy_name({}) }.to raise_error(Chef::Exceptions::ValidationFailed)
expect { node.policy_name(42) }.to raise_error(Chef::Exceptions::ValidationFailed)
end
@@ -198,7 +198,7 @@ describe Chef::Node do
end
it "disallows non-strings" do
- expect { node.policy_group(Hash.new) }.to raise_error(Chef::Exceptions::ValidationFailed)
+ expect { node.policy_group({}) }.to raise_error(Chef::Exceptions::ValidationFailed)
expect { node.policy_group(42) }.to raise_error(Chef::Exceptions::ValidationFailed)
end
@@ -769,7 +769,7 @@ describe Chef::Node do
it "caches both strings and symbols correctly" do
node.force_default[:solr][:version] = "4.10.2"
- node.force_default[:solr][:data_dir] = "/opt/solr-#{node['solr'][:version]}/example/solr"
+ node.force_default[:solr][:data_dir] = "/opt/solr-#{node["solr"][:version]}/example/solr"
node.force_default[:solr][:xms] = "512M"
expect(node[:solr][:xms]).to eql("512M")
expect(node["solr"][:xms]).to eql("512M")
@@ -778,8 +778,8 @@ describe Chef::Node do
it "method interpolation syntax also works" do
Chef::Config[:treat_deprecation_warnings_as_errors] = false
node.default["passenger"]["version"] = "4.0.57"
- node.default["passenger"]["root_path"] = "passenger-#{node['passenger']['version']}"
- node.default["passenger"]["root_path_2"] = "passenger-#{node[:passenger]['version']}"
+ node.default["passenger"]["root_path"] = "passenger-#{node["passenger"]["version"]}"
+ node.default["passenger"]["root_path_2"] = "passenger-#{node[:passenger]["version"]}"
expect(node["passenger"]["root_path_2"]).to eql("passenger-4.0.57")
expect(node[:passenger]["root_path_2"]).to eql("passenger-4.0.57")
end
@@ -793,7 +793,7 @@ describe Chef::Node do
it "should allow you to iterate over attributes with each_attribute" do
node.default["sunshine"] = "is bright"
node.default["canada"] = "is a nice place"
- seen_attributes = Hash.new
+ seen_attributes = {}
node.each_attribute do |a, v|
seen_attributes[a] = v
end
@@ -1207,7 +1207,7 @@ describe Chef::Node do
node.run_list << "role[leninist]"
node.run_list << "recipe[stalinist]"
- @example = Chef::Node.new()
+ @example = Chef::Node.new
@example.name("newname")
@example.chef_environment("prod")
@example.default_attrs = { "alpha" => { "bravo" => "charlie", "delta" => "echo" } }
@@ -1385,7 +1385,7 @@ describe Chef::Node do
describe "inflated" do
it "should return a hash of node names and objects" do
n1 = double("Chef::Node", name: "one")
- allow(n1).to receive(:kind_of?).with(Chef::Node) { true }
+ allow(n1).to receive(:is_a?).with(Chef::Node) { true }
expect(@query).to receive(:search).with(:node).and_yield(n1)
r = Chef::Node.list(true)
expect(r["one"]).to eq(n1)
diff --git a/spec/unit/org_spec.rb b/spec/unit/org_spec.rb
index 79a29b1fff..b291b7cb86 100644
--- a/spec/unit/org_spec.rb
+++ b/spec/unit/org_spec.rb
@@ -52,7 +52,7 @@ describe Chef::Org do
end
it "raises an ArgumentError if you feed it anything but a string" do
- expect { org.name Hash.new }.to raise_error(ArgumentError)
+ expect { org.name({}) }.to raise_error(ArgumentError)
end
end
@@ -63,7 +63,7 @@ describe Chef::Org do
end
it "raises an ArgumentError if you feed it anything but a string" do
- expect { org.name Hash.new }.to raise_error(ArgumentError)
+ expect { org.name({}) }.to raise_error(ArgumentError)
end
end
@@ -74,7 +74,7 @@ describe Chef::Org do
end
it "raises an ArgumentError if you feed it something lame" do
- expect { org.private_key Hash.new }.to raise_error(ArgumentError)
+ expect { org.private_key({}) }.to raise_error(ArgumentError)
end
end
diff --git a/spec/unit/policy_builder/policyfile_spec.rb b/spec/unit/policy_builder/policyfile_spec.rb
index f22e2a74b3..d08a9f5b33 100644
--- a/spec/unit/policy_builder/policyfile_spec.rb
+++ b/spec/unit/policy_builder/policyfile_spec.rb
@@ -403,9 +403,9 @@ describe Chef::PolicyBuilder::Policyfile do
before do
allow(policy_builder).to receive(:run_list)
- .and_return(run_list)
+ .and_return(run_list)
allow(policy_builder).to receive(:cookbook_lock_for)
- .and_return(version_hash)
+ .and_return(version_hash)
end
it "sends the run_list_expanded event" do
diff --git a/spec/unit/property/state_spec.rb b/spec/unit/property/state_spec.rb
index 5c54ec71b2..a6428e8617 100644
--- a/spec/unit/property/state_spec.rb
+++ b/spec/unit/property/state_spec.rb
@@ -28,7 +28,8 @@ describe "Chef::Resource#identity and #state" do
def self.english_join(values)
return "<nothing>" if values.size == 0
return values[0].inspect if values.size == 1
- "#{values[0..-2].map { |v| v.inspect }.join(", ")} and #{values[-1].inspect}"
+
+ "#{values[0..-2].map(&:inspect).join(", ")} and #{values[-1].inspect}"
end
def self.with_property(*properties, &block)
@@ -256,29 +257,29 @@ describe "Chef::Resource#identity and #state" do
with_property ":x, identity: true, default: 'xxx'",
":y, identity: true, default: 'yyy'",
":z, identity: true, default: 'zzz'" do
- it "identity_property raises an error if multiple identity values are defined" do
- expect { resource_class.identity_property }.to raise_error Chef::Exceptions::MultipleIdentityError
- end
- it "identity_attr raises an error if multiple identity values are defined" do
- expect { resource_class.identity_attr }.to raise_error Chef::Exceptions::MultipleIdentityError
- end
- it "identity returns all identity values in a hash if multiple are defined" do
- resource.x "foo"
- resource.y "bar"
- resource.z "baz"
- expect(resource.identity).to eq(x: "foo", y: "bar", z: "baz")
- end
- it "identity returns all values whether any value is set or not" do
- expect(resource.identity).to eq(x: "xxx", y: "yyy", z: "zzz")
- end
- it "identity_properties wipes out any other identity attributes if multiple are defined" do
- resource_class.identity_properties :y
- resource.x "foo"
- resource.y "bar"
- resource.z "baz"
- expect(resource.identity).to eq "bar"
+ it "identity_property raises an error if multiple identity values are defined" do
+ expect { resource_class.identity_property }.to raise_error Chef::Exceptions::MultipleIdentityError
+ end
+ it "identity_attr raises an error if multiple identity values are defined" do
+ expect { resource_class.identity_attr }.to raise_error Chef::Exceptions::MultipleIdentityError
+ end
+ it "identity returns all identity values in a hash if multiple are defined" do
+ resource.x "foo"
+ resource.y "bar"
+ resource.z "baz"
+ expect(resource.identity).to eq(x: "foo", y: "bar", z: "baz")
+ end
+ it "identity returns all values whether any value is set or not" do
+ expect(resource.identity).to eq(x: "xxx", y: "yyy", z: "zzz")
+ end
+ it "identity_properties wipes out any other identity attributes if multiple are defined" do
+ resource_class.identity_properties :y
+ resource.x "foo"
+ resource.y "bar"
+ resource.z "baz"
+ expect(resource.identity).to eq "bar"
+ end
end
- end
with_property ":x, identity: true, name_property: true" do
it "identity when x is not defined returns the value of x" do
diff --git a/spec/unit/property/validation_spec.rb b/spec/unit/property/validation_spec.rb
index b05d8c4e17..dab2be8000 100644
--- a/spec/unit/property/validation_spec.rb
+++ b/spec/unit/property/validation_spec.rb
@@ -55,7 +55,8 @@ describe "Chef::Resource.property validation" do
def self.english_join(values)
return "<nothing>" if values.size == 0
return values[0].inspect if values.size == 1
- "#{values[0..-2].map { |v| v.inspect }.join(", ")} and #{values[-1].inspect}"
+
+ "#{values[0..-2].map(&:inspect).join(", ")} and #{values[-1].inspect}"
end
def self.with_property(*properties, &block)
@@ -231,19 +232,19 @@ describe "Chef::Resource.property validation" do
[ :b ]
validation_test ":a, is: :b",
- [ :a, :b ],
+ %i{a b},
[ :c ]
validation_test ":a, is: [ :b, :c ]",
- [ :a, :b, :c ],
+ %i{a b c},
[ :d ]
validation_test "[ :a, :b ], is: :c",
- [ :a, :b, :c ],
+ %i{a b c},
[ :d ]
validation_test "[ :a, :b ], is: [ :c, :d ]",
- [ :a, :b, :c, :d ],
+ %i{a b c d},
[ :e ]
validation_test "nil",
@@ -279,12 +280,12 @@ describe "Chef::Resource.property validation" do
[ :b ]
validation_test "is: [ :a, :b ]",
- [ :a, :b ],
- [ [ :a, :b ] ]
+ %i{a b},
+ [ %i{a b} ]
validation_test "is: [ [ :a, :b ] ]",
- [ [ :a, :b ] ],
- [ :a, :b ]
+ [ %i{a b} ],
+ %i{a b}
# Regex
validation_test "is: /abc/",
@@ -352,13 +353,13 @@ describe "Chef::Resource.property validation" do
:nil_is_valid
validation_test "equal_to: [ :a, :b ]",
- [ :a, :b ],
- [ [ :a, :b ] ],
+ %i{a b},
+ [ %i{a b} ],
:nil_is_valid
validation_test "equal_to: [ [ :a, :b ] ]",
- [ [ :a, :b ] ],
- [ :a, :b ],
+ [ %i{a b} ],
+ %i{a b},
:nil_is_valid
validation_test "equal_to: nil",
diff --git a/spec/unit/property_spec.rb b/spec/unit/property_spec.rb
index 56e44fd1d1..1fcbb77e8e 100644
--- a/spec/unit/property_spec.rb
+++ b/spec/unit/property_spec.rb
@@ -51,7 +51,8 @@ describe "Chef::Resource.property" do
def self.english_join(values)
return "<nothing>" if values.size == 0
return values[0].inspect if values.size == 1
- "#{values[0..-2].map { |v| v.inspect }.join(", ")} and #{values[-1].inspect}"
+
+ "#{values[0..-2].map(&:inspect).join(", ")} and #{values[-1].inspect}"
end
def self.with_property(*properties, &block)
@@ -1051,19 +1052,19 @@ describe "Chef::Resource.property" do
context "default ordering deprecation warnings" do
it "emits an error for property :x, default: 10, #{name}: true" do
expect { resource_class.property :x, :default => 10, name.to_sym => true }.to raise_error ArgumentError,
- /A property cannot be both a name_property\/name_attribute and have a default value. Use one or the other on property x of resource chef_resource_property_spec_(\d+)/
+ %r{A property cannot be both a name_property/name_attribute and have a default value. Use one or the other on property x of resource chef_resource_property_spec_(\d+)}
end
it "emits an error for property :x, default: nil, #{name}: true" do
expect { resource_class.property :x, :default => nil, name.to_sym => true }.to raise_error ArgumentError,
- /A property cannot be both a name_property\/name_attribute and have a default value. Use one or the other on property x of resource chef_resource_property_spec_(\d+)/
+ %r{A property cannot be both a name_property/name_attribute and have a default value. Use one or the other on property x of resource chef_resource_property_spec_(\d+)}
end
it "emits an error for property :x, #{name}: true, default: 10" do
expect { resource_class.property :x, name.to_sym => true, :default => 10 }.to raise_error ArgumentError,
- /A property cannot be both a name_property\/name_attribute and have a default value. Use one or the other on property x of resource chef_resource_property_spec_(\d+)/
+ %r{A property cannot be both a name_property/name_attribute and have a default value. Use one or the other on property x of resource chef_resource_property_spec_(\d+)}
end
it "emits an error for property :x, #{name}: true, default: nil" do
expect { resource_class.property :x, name.to_sym => true, :default => nil }.to raise_error ArgumentError,
- /A property cannot be both a name_property\/name_attribute and have a default value. Use one or the other on property x of resource chef_resource_property_spec_(\d+)/
+ %r{A property cannot be both a name_property/name_attribute and have a default value. Use one or the other on property x of resource chef_resource_property_spec_(\d+)}
end
end
end
@@ -1085,13 +1086,13 @@ describe "Chef::Resource.property" do
expect do
module ::PropertySpecPropertyTypes
include Chef::Mixin::Properties
- property_type(is: [:a, :b], default: :c)
+ property_type(is: %i{a b}, default: :c)
end
end.to raise_error(Chef::Exceptions::ValidationFailed)
expect do
module ::PropertySpecPropertyTypes
include Chef::Mixin::Properties
- property_type(is: [:a, :b], default: :b)
+ property_type(is: %i{a b}, default: :b)
end
end.not_to raise_error
end
@@ -1100,8 +1101,8 @@ describe "Chef::Resource.property" do
before :all do
module ::PropertySpecPropertyTypes
include Chef::Mixin::Properties
- ABType = property_type(is: [:a, :b])
- CDType = property_type(is: [:c, :d])
+ ABType = property_type(is: %i{a b})
+ CDType = property_type(is: %i{c d})
end
end
@@ -1304,7 +1305,7 @@ describe "Chef::Resource.property" do
it "copies only foo when bar and name are excluded" do
thing_one_resource.foo "foo"
thing_one_resource.bar "bar"
- thing_two_resource.copy_properties_from(thing_one_resource, exclude: [ :name, :bar ])
+ thing_two_resource.copy_properties_from(thing_one_resource, exclude: %i{name bar})
expect(thing_two_resource.name).to eql("name_two")
expect(thing_two_resource.foo).to eql("foo")
expect(thing_two_resource.bar).to eql(nil)
diff --git a/spec/unit/provider/apt_update_spec.rb b/spec/unit/provider/apt_update_spec.rb
index 5cd327b66b..ed91131aff 100644
--- a/spec/unit/provider/apt_update_spec.rb
+++ b/spec/unit/provider/apt_update_spec.rb
@@ -47,7 +47,7 @@ describe Chef::Provider::AptUpdate do
before do
FileUtils.rmdir config_dir
expect(File.exist?(config_dir)).to be false
- allow_any_instance_of(Chef::Provider::Execute).to receive(:shell_out_compacted!).with(*apt_update_cmd, anything())
+ allow_any_instance_of(Chef::Provider::Execute).to receive(:shell_out_compacted!).with(*apt_update_cmd, anything)
end
it "should create the directory" do
@@ -66,7 +66,7 @@ describe Chef::Provider::AptUpdate do
describe "#action_update" do
it "should update the apt cache" do
provider.load_current_resource
- expect_any_instance_of(Chef::Provider::Execute).to receive(:shell_out_compacted!).with(*apt_update_cmd, anything())
+ expect_any_instance_of(Chef::Provider::Execute).to receive(:shell_out_compacted!).with(*apt_update_cmd, anything)
provider.run_action(:update)
expect(new_resource).to be_updated_by_last_action
end
@@ -81,14 +81,14 @@ describe Chef::Provider::AptUpdate do
it "should run if the time stamp is old" do
expect(File).to receive(:mtime).with("#{stamp_dir}/update-success-stamp").and_return(Time.now - 86_500)
- expect_any_instance_of(Chef::Provider::Execute).to receive(:shell_out_compacted!).with(*apt_update_cmd, anything())
+ expect_any_instance_of(Chef::Provider::Execute).to receive(:shell_out_compacted!).with(*apt_update_cmd, anything)
provider.run_action(:periodic)
expect(new_resource).to be_updated_by_last_action
end
it "should not run if the time stamp is new" do
expect(File).to receive(:mtime).with("#{stamp_dir}/update-success-stamp").and_return(Time.now)
- expect_any_instance_of(Chef::Provider::Execute).not_to receive(:shell_out_compacted!).with(*apt_update_cmd, anything())
+ expect_any_instance_of(Chef::Provider::Execute).not_to receive(:shell_out_compacted!).with(*apt_update_cmd, anything)
provider.run_action(:periodic)
expect(new_resource).to_not be_updated_by_last_action
end
@@ -100,14 +100,14 @@ describe Chef::Provider::AptUpdate do
it "should run if the time stamp is old" do
expect(File).to receive(:mtime).with("#{stamp_dir}/update-success-stamp").and_return(Time.now - 500)
- expect_any_instance_of(Chef::Provider::Execute).to receive(:shell_out_compacted!).with(*apt_update_cmd, anything())
+ expect_any_instance_of(Chef::Provider::Execute).to receive(:shell_out_compacted!).with(*apt_update_cmd, anything)
provider.run_action(:periodic)
expect(new_resource).to be_updated_by_last_action
end
it "should not run if the time stamp is new" do
expect(File).to receive(:mtime).with("#{stamp_dir}/update-success-stamp").and_return(Time.now - 300)
- expect_any_instance_of(Chef::Provider::Execute).not_to receive(:shell_out_compacted!).with(*apt_update_cmd, anything())
+ expect_any_instance_of(Chef::Provider::Execute).not_to receive(:shell_out_compacted!).with(*apt_update_cmd, anything)
provider.run_action(:periodic)
expect(new_resource).to_not be_updated_by_last_action
end
diff --git a/spec/unit/provider/cron_spec.rb b/spec/unit/provider/cron_spec.rb
index 6bfc18c359..4cd8a140af 100644
--- a/spec/unit/provider/cron_spec.rb
+++ b/spec/unit/provider/cron_spec.rb
@@ -401,7 +401,7 @@ describe Chef::Provider::Cron do
@provider.current_resource = @current_resource
end
- [:minute, :hour, :day, :month, :weekday, :command, :mailto, :path, :shell, :home].each do |property|
+ %i{minute hour day month weekday command mailto path shell home}.each do |property|
it "should return true if #{property} doesn't match" do
@new_resource.send(property, "something_else")
expect(@provider.cron_different?).to eql(true)
diff --git a/spec/unit/provider/dsc_resource_spec.rb b/spec/unit/provider/dsc_resource_spec.rb
index 6edf0963b8..cf6ab88eb4 100644
--- a/spec/unit/provider/dsc_resource_spec.rb
+++ b/spec/unit/provider/dsc_resource_spec.rb
@@ -36,7 +36,8 @@ describe Chef::Provider::DscResource do
it "raises a ProviderNotFound exception" do
expect(provider).not_to receive(:meta_configuration)
expect { provider.run_action(:run) }.to raise_error(
- Chef::Exceptions::ProviderNotFound, /5\.0\.10018\.0/)
+ Chef::Exceptions::ProviderNotFound, /5\.0\.10018\.0/
+ )
end
end
@@ -52,7 +53,8 @@ describe Chef::Provider::DscResource do
it "raises an exception" do
expect(provider).to receive(:dsc_refresh_mode_disabled?).and_return(false)
expect { provider.run_action(:run) }.to raise_error(
- Chef::Exceptions::ProviderNotFound, /Disabled/)
+ Chef::Exceptions::ProviderNotFound, /Disabled/
+ )
end
end
context "and the WMF is 5 RTM or newer" do
@@ -157,7 +159,8 @@ describe Chef::Provider::DscResource do
[
{ "Module" => { "Name" => "ModuleName1", "Version" => "1.0.0.0" } },
{ "Module" => { "Name" => "ModuleName1", "Version" => "2.0.0.0" } },
- ] end
+ ]
+ end
it "raises MultipleDscResourcesFound" do
expect { provider.run_action(:run) }.to raise_error(Chef::Exceptions::MultipleDscResourcesFound)
diff --git a/spec/unit/provider/dsc_script_spec.rb b/spec/unit/provider/dsc_script_spec.rb
index c880683a0f..a1115150e8 100644
--- a/spec/unit/provider/dsc_script_spec.rb
+++ b/spec/unit/provider/dsc_script_spec.rb
@@ -99,7 +99,7 @@ describe Chef::Provider::DscScript do
it "should noop if neither code or command are provided" do
allow(provider).to receive(:load_current_resource)
generator = double("Chef::Util::DSC::ConfigurationGenerator")
- expect(generator).to receive(:configuration_document_from_script_code).with("", anything(), anything(), anything())
+ expect(generator).to receive(:configuration_document_from_script_code).with("", anything, anything, anything)
allow(Chef::Util::DSC::ConfigurationGenerator).to receive(:new).and_return(generator)
provider.send(:generate_configuration_document, "tmp", nil)
end
diff --git a/spec/unit/provider/group/dscl_spec.rb b/spec/unit/provider/group/dscl_spec.rb
index 94322a89f9..910470b1b7 100644
--- a/spec/unit/provider/group/dscl_spec.rb
+++ b/spec/unit/provider/group/dscl_spec.rb
@@ -121,7 +121,7 @@ describe Chef::Provider::Group::Dscl do
500
)
EOS
- )
+ )
end
it "should run safe_dscl with search /Groups gid" do
diff --git a/spec/unit/provider/group/groupadd_spec.rb b/spec/unit/provider/group/groupadd_spec.rb
index 84997a258d..79586eac71 100644
--- a/spec/unit/provider/group/groupadd_spec.rb
+++ b/spec/unit/provider/group/groupadd_spec.rb
@@ -155,7 +155,7 @@ describe Chef::Provider::Group::Groupadd do
end
end
- [:add_member, :remove_member, :set_members].each do |m|
+ %i{add_member remove_member set_members}.each do |m|
it "should raise an error when calling #{m}" do
expect { provider.send(m, [ ]) }.to raise_error(Chef::Exceptions::Group, "you must override #{m} in #{provider}")
end
diff --git a/spec/unit/provider/group_spec.rb b/spec/unit/provider/group_spec.rb
index bacb711d1b..d7fdfb299c 100644
--- a/spec/unit/provider/group_spec.rb
+++ b/spec/unit/provider/group_spec.rb
@@ -39,8 +39,7 @@ describe Chef::Provider::User do
@pw_group = double("Struct::Group",
name: "wheel",
gid: 20,
- mem: %w{root aj}
- )
+ mem: %w{root aj})
allow(Etc).to receive(:getgrnam).with("wheel").and_return(@pw_group)
end
@@ -85,7 +84,7 @@ describe Chef::Provider::User do
end
describe "when determining if the system is already in the target state" do
- [ :gid, :members ].each do |property|
+ %i{gid members}.each do |property|
it "should return true if #{property} doesn't match" do
allow(@current_resource).to receive(property).and_return("looooooooooooooooooool")
expect(@provider.compare_group).to be_truthy
diff --git a/spec/unit/provider/launchd_spec.rb b/spec/unit/provider/launchd_spec.rb
index 8b5edc68b5..53b56b4960 100644
--- a/spec/unit/provider/launchd_spec.rb
+++ b/spec/unit/provider/launchd_spec.rb
@@ -89,7 +89,8 @@ describe Chef::Provider::Launchd do
"Weekday" => 7,
},
"TimeOut" => 300,
- } end
+ }
+ end
before(:each) do
provider.load_current_resource
@@ -197,9 +198,11 @@ describe Chef::Provider::Launchd do
describe "and the file has been updated" do
before(:each) do
allow(provider).to receive(
- :manage_plist).with(:create).and_return(true)
+ :manage_plist
+ ).with(:create).and_return(true)
allow(provider).to receive(
- :manage_service).with(:restart).and_return(true)
+ :manage_service
+ ).with(:restart).and_return(true)
end
it "should call manage_service with a :restart action" do
@@ -215,9 +218,11 @@ describe Chef::Provider::Launchd do
describe "and the file has not been updated" do
before(:each) do
allow(provider).to receive(
- :manage_plist).with(:create).and_return(nil)
+ :manage_plist
+ ).with(:create).and_return(nil)
allow(provider).to receive(
- :manage_service).with(:enable).and_return(true)
+ :manage_service
+ ).with(:enable).and_return(true)
end
it "should call manage_service with a :enable action" do
@@ -236,9 +241,11 @@ describe Chef::Provider::Launchd do
before(:each) do
allow(File).to receive(:exists?).and_return(true)
allow(provider).to receive(
- :manage_service).with(:disable).and_return(true)
+ :manage_service
+ ).with(:disable).and_return(true)
allow(provider).to receive(
- :manage_plist).with(:delete).and_return(true)
+ :manage_plist
+ ).with(:delete).and_return(true)
end
it "should call manage_service with a :disable action" do
@@ -255,7 +262,8 @@ describe Chef::Provider::Launchd do
before(:each) do
allow(File).to receive(:exists?).and_return(false)
allow(provider).to receive(
- :manage_plist).with(:delete).and_return(true)
+ :manage_plist
+ ).with(:delete).and_return(true)
end
it "works with action :delete" do
diff --git a/spec/unit/provider/link_spec.rb b/spec/unit/provider/link_spec.rb
index 027b318c7e..fff2c1ffa8 100644
--- a/spec/unit/provider/link_spec.rb
+++ b/spec/unit/provider/link_spec.rb
@@ -259,7 +259,8 @@ describe Chef::Resource::Link do
allow(stat).to receive(:gid).and_return(501)
allow(stat).to receive(:mode).and_return(0755)
allow(provider.file_class).to receive(:stat).with(
- "#{CHEF_SPEC_DATA}/fofile-link").and_return(stat)
+ "#{CHEF_SPEC_DATA}/fofile-link"
+ ).and_return(stat)
provider.load_current_resource
end
@@ -267,7 +268,8 @@ describe Chef::Resource::Link do
shared_context "delete link to directories on Windows" do
before do
allow(::File).to receive(:directory?).with(
- "#{CHEF_SPEC_DATA}/fofile-link").and_return(true)
+ "#{CHEF_SPEC_DATA}/fofile-link"
+ ).and_return(true)
end
it "invokes Dir.delete method to delete the link" do
@@ -280,7 +282,8 @@ describe Chef::Resource::Link do
shared_context "delete link to directories on Linux" do
before do
allow(::File).to receive(:directory?).with(
- "#{CHEF_SPEC_DATA}/fofile-link").and_return(true)
+ "#{CHEF_SPEC_DATA}/fofile-link"
+ ).and_return(true)
end
it "invokes File.delete method to delete the link" do
@@ -293,7 +296,8 @@ describe Chef::Resource::Link do
shared_context "delete link to files" do
before do
allow(::File).to receive(:directory?).with(
- "#{CHEF_SPEC_DATA}/fofile-link").and_return(false)
+ "#{CHEF_SPEC_DATA}/fofile-link"
+ ).and_return(false)
end
it "invokes File.delete method to delete the link" do
@@ -306,9 +310,11 @@ describe Chef::Resource::Link do
shared_context "soft links prerequisites" do
before(:each) do
allow(provider.file_class).to receive(:symlink?).with(
- "#{CHEF_SPEC_DATA}/fofile-link").and_return(true)
+ "#{CHEF_SPEC_DATA}/fofile-link"
+ ).and_return(true)
allow(provider.file_class).to receive(:readlink).with(
- "#{CHEF_SPEC_DATA}/fofile-link").and_return("#{CHEF_SPEC_DATA}/fofile")
+ "#{CHEF_SPEC_DATA}/fofile-link"
+ ).and_return("#{CHEF_SPEC_DATA}/fofile")
end
end
@@ -327,15 +333,19 @@ describe Chef::Resource::Link do
allow(stat).to receive(:mode).and_return(0644)
allow(provider.file_class).to receive(:symlink?).with(
- "#{CHEF_SPEC_DATA}/fofile-link").and_return(false)
+ "#{CHEF_SPEC_DATA}/fofile-link"
+ ).and_return(false)
allow(File).to receive(:exists?).with(
- "#{CHEF_SPEC_DATA}/fofile-link").and_return(true)
+ "#{CHEF_SPEC_DATA}/fofile-link"
+ ).and_return(true)
allow(File).to receive(:exists?).with(
- "#{CHEF_SPEC_DATA}/fofile").and_return(true)
+ "#{CHEF_SPEC_DATA}/fofile"
+ ).and_return(true)
allow(provider.file_class).to receive(:stat).with(
- "#{CHEF_SPEC_DATA}/fofile").and_return(stat)
+ "#{CHEF_SPEC_DATA}/fofile"
+ ).and_return(stat)
end
end
@@ -346,7 +356,8 @@ describe Chef::Resource::Link do
before(:each) do
allow(Chef::Resource::Link).to receive(:new).with(
- provider.new_resource.name).and_return(resource_link)
+ provider.new_resource.name
+ ).and_return(resource_link)
allow(resource_link).to receive(:verify_links_supported!)
allow(Chef::Platform).to receive(:windows?).and_return(true)
end
diff --git a/spec/unit/provider/mount/mount_spec.rb b/spec/unit/provider/mount/mount_spec.rb
index 2353d992d0..5e1ffbf208 100644
--- a/spec/unit/provider/mount/mount_spec.rb
+++ b/spec/unit/provider/mount/mount_spec.rb
@@ -67,23 +67,23 @@ describe Chef::Provider::Mount::Mount do
describe "when dealing with network mounts" do
{ "nfs" => "nfsserver:/vol/path",
"cifs" => "//cifsserver/share" }.each do |type, fs_spec|
- it "should detect network fs_spec (#{type})" do
- @new_resource.device fs_spec
- expect(@provider.network_device?).to be_truthy
+ it "should detect network fs_spec (#{type})" do
+ @new_resource.device fs_spec
+ expect(@provider.network_device?).to be_truthy
+ end
+
+ it "should ignore trailing slash and set mounted to true for network mount (#{type})" do
+ @new_resource.device fs_spec
+ allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(stdout: "#{fs_spec}/ on /tmp/foo type #{type} (rw)\n"))
+ @provider.load_current_resource
+ expect(@provider.current_resource.mounted).to be_truthy
+ end
end
-
- it "should ignore trailing slash and set mounted to true for network mount (#{type})" do
- @new_resource.device fs_spec
- allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(stdout: "#{fs_spec}/ on /tmp/foo type #{type} (rw)\n"))
- @provider.load_current_resource
- expect(@provider.current_resource.mounted).to be_truthy
- end
- end
end
it "should raise an error if the mount device does not exist" do
allow(::File).to receive(:exists?).with("/dev/sdz1").and_return false
- expect { @provider.load_current_resource(); @provider.mountable? }.to raise_error(Chef::Exceptions::Mount)
+ expect { @provider.load_current_resource; @provider.mountable? }.to raise_error(Chef::Exceptions::Mount)
end
it "should not call mountable? with load_current_resource - CHEF-1565" do
@@ -100,36 +100,36 @@ describe Chef::Provider::Mount::Mount do
@new_resource.device "d21afe51-a0fe-4dc6-9152-ac733763ae0a"
expect(@provider).to receive(:shell_out_compacted).with("/sbin/findfs", "UUID=d21afe51-a0fe-4dc6-9152-ac733763ae0a").and_return(status)
expect(::File).to receive(:exists?).with("").and_return(false)
- expect { @provider.load_current_resource(); @provider.mountable? }.to raise_error(Chef::Exceptions::Mount)
+ expect { @provider.load_current_resource; @provider.mountable? }.to raise_error(Chef::Exceptions::Mount)
end
it "should raise an error if the mount point does not exist" do
allow(::File).to receive(:exists?).with("/tmp/foo").and_return false
- expect { @provider.load_current_resource(); @provider.mountable? }.to raise_error(Chef::Exceptions::Mount)
+ expect { @provider.load_current_resource; @provider.mountable? }.to raise_error(Chef::Exceptions::Mount)
end
%w{tmpfs fuse cgroup vboxsf zfs}.each do |fstype|
it "does not expect the device to exist for #{fstype}" do
@new_resource.fstype(fstype)
@new_resource.device("whatever")
- expect { @provider.load_current_resource(); @provider.mountable? }.not_to raise_error
+ expect { @provider.load_current_resource; @provider.mountable? }.not_to raise_error
end
end
it "does not expect the device to exist if it's none" do
@new_resource.device("none")
- expect { @provider.load_current_resource(); @provider.mountable? }.not_to raise_error
+ expect { @provider.load_current_resource; @provider.mountable? }.not_to raise_error
end
it "should set mounted true if the mount point is found in the mounts list" do
allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(stdout: "/dev/sdz1 on /tmp/foo type ext3 (rw)\n"))
- @provider.load_current_resource()
+ @provider.load_current_resource
expect(@provider.current_resource.mounted).to be_truthy
end
it "should set mounted false if another mount point beginning with the same path is found in the mounts list" do
allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(stdout: "/dev/sdz1 on /tmp/foobar type ext3 (rw)\n"))
- @provider.load_current_resource()
+ @provider.load_current_resource
expect(@provider.current_resource.mounted).to be_falsey
end
@@ -141,7 +141,7 @@ describe Chef::Provider::Mount::Mount do
allow(::File).to receive(:readlink).with((@new_resource.device).to_s).and_return(target)
allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(stdout: "#{target} on /tmp/foo type ext3 (rw)\n"))
- @provider.load_current_resource()
+ @provider.load_current_resource
expect(@provider.current_resource.mounted).to be_truthy
end
@@ -155,7 +155,7 @@ describe Chef::Provider::Mount::Mount do
allow(::File).to receive(:readlink).with((@new_resource.device).to_s).and_return(target)
allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(stdout: "#{absolute_target} on /tmp/foo type ext3 (rw)\n"))
- @provider.load_current_resource()
+ @provider.load_current_resource
expect(@provider.current_resource.mounted).to be_truthy
end
@@ -164,7 +164,7 @@ describe Chef::Provider::Mount::Mount do
mount << "#{@new_resource.device} on #{@new_resource.mount_point} type ext3 (rw)\n"
allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(stdout: mount))
- @provider.load_current_resource()
+ @provider.load_current_resource
expect(@provider.current_resource.mounted).to be_truthy
end
@@ -173,13 +173,13 @@ describe Chef::Provider::Mount::Mount do
mount << "/dev/sdy1 on #{@new_resource.mount_point} type ext3 (rw)\n"
allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(stdout: mount))
- @provider.load_current_resource()
+ @provider.load_current_resource
expect(@provider.current_resource.mounted).to be_falsey
end
it "mounted should be false if the mount point is not found in the mounts list" do
allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(stdout: "/dev/sdy1 on /tmp/foo type ext3 (rw)\n"))
- @provider.load_current_resource()
+ @provider.load_current_resource
expect(@provider.current_resource.mounted).to be_falsey
end
@@ -297,14 +297,14 @@ describe Chef::Provider::Mount::Mount do
describe "mount_fs" do
it "should mount the filesystem if it is not mounted" do
expect(@provider).to receive(:shell_out_compacted!).with("mount", "-t", "ext3", "-o", "defaults", "/dev/sdz1", "/tmp/foo")
- @provider.mount_fs()
+ @provider.mount_fs
end
it "should mount the filesystem with options if options were passed" do
options = "rw,noexec,noauto"
@new_resource.options(%w{rw noexec noauto})
expect(@provider).to receive(:shell_out_compacted!).with("mount", "-t", "ext3", "-o", "rw,noexec,noauto", "/dev/sdz1", "/tmp/foo")
- @provider.mount_fs()
+ @provider.mount_fs
end
it "should mount the filesystem specified by uuid", :not_supported_on_solaris do
@@ -315,13 +315,13 @@ describe Chef::Provider::Mount::Mount do
@stdout_mock = double("stdout mock")
allow(@stdout_mock).to receive(:each).and_yield("#{@new_resource.device} on #{@new_resource.mount_point}")
expect(@provider).to receive(:shell_out_compacted!).with("mount", "-t", @new_resource.fstype, "-o", "defaults", "-U", @new_resource.device, @new_resource.mount_point).and_return(@stdout_mock)
- @provider.mount_fs()
+ @provider.mount_fs
end
it "should not mount the filesystem if it is mounted" do
allow(@current_resource).to receive(:mounted).and_return(true)
expect(@provider).not_to receive(:shell_out!)
- @provider.mount_fs()
+ @provider.mount_fs
end
end
@@ -330,13 +330,13 @@ describe Chef::Provider::Mount::Mount do
it "should umount the filesystem if it is mounted" do
@current_resource.mounted(true)
expect(@provider).to receive(:shell_out!).with("umount", "/tmp/foo")
- @provider.umount_fs()
+ @provider.umount_fs
end
it "should not umount the filesystem if it is not mounted" do
@current_resource.mounted(false)
expect(@provider).not_to receive(:shell_out!)
- @provider.umount_fs()
+ @provider.umount_fs
end
end
@@ -363,7 +363,7 @@ describe Chef::Provider::Mount::Mount do
expect(@provider).to receive(:umount_fs)
expect(@provider).to receive(:sleep).with(1)
expect(@provider).to receive(:mount_fs)
- @provider.remount_fs()
+ @provider.remount_fs
end
it "should not try to remount at all if mounted is false" do
@@ -371,7 +371,7 @@ describe Chef::Provider::Mount::Mount do
expect(@provider).not_to receive(:shell_out!)
expect(@provider).not_to receive(:umount_fs)
expect(@provider).not_to receive(:mount_fs)
- @provider.remount_fs()
+ @provider.remount_fs
end
end
diff --git a/spec/unit/provider/mount/solaris_spec.rb b/spec/unit/provider/mount/solaris_spec.rb
index 4e73bc77b5..006eb690cb 100644
--- a/spec/unit/provider/mount/solaris_spec.rb
+++ b/spec/unit/provider/mount/solaris_spec.rb
@@ -103,7 +103,7 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
describe "#define_resource_requirements" do
before do
# we're not testing the actual actions so stub them all out
- [:mount_fs, :umount_fs, :remount_fs, :enable_fs, :disable_fs].each { |m| allow(provider).to receive(m) }
+ %i{mount_fs umount_fs remount_fs enable_fs disable_fs}.each { |m| allow(provider).to receive(m) }
end
it "run_action(:mount) should raise an error if the device does not exist" do
@@ -350,7 +350,7 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
expect(File).to receive(:symlink?).with(device).at_least(:once).and_return(true)
expect(File).to receive(:readlink).with(device).at_least(:once).and_return(target)
- provider.load_current_resource()
+ provider.load_current_resource
end
it "should set mounted true if the symlink target of the device is found in the mounts list" do
@@ -387,7 +387,7 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
expect(File).to receive(:symlink?).with(device).at_least(:once).and_return(true)
expect(File).to receive(:readlink).with(device).at_least(:once).and_return(target)
- provider.load_current_resource()
+ provider.load_current_resource
end
it "should set mounted true if the symlink target of the device is found in the mounts list" do
@@ -411,7 +411,7 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
EOF
end
it "should set mounted true" do
- provider.load_current_resource()
+ provider.load_current_resource
expect(provider.current_resource.mounted).to be_truthy
end
end
@@ -424,7 +424,7 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
EOF
end
it "should set mounted false" do
- provider.load_current_resource()
+ provider.load_current_resource
expect(provider.current_resource.mounted).to be_falsey
end
end
@@ -436,7 +436,7 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
EOF
end
it "should set mounted false" do
- provider.load_current_resource()
+ provider.load_current_resource
expect(provider.current_resource.mounted).to be_falsey
end
end
@@ -448,7 +448,7 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
EOF
end
it "should set mounted false" do
- provider.load_current_resource()
+ provider.load_current_resource
expect(provider.current_resource.mounted).to be_falsey
end
end
@@ -539,28 +539,28 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
describe "mount_fs" do
it "should mount the filesystem" do
expect(provider).to receive(:shell_out_compacted!).with("mount", "-F", fstype, device, mountpoint)
- provider.mount_fs()
+ provider.mount_fs
end
it "should mount the filesystem with options if options were passed" do
options = "logging,noatime,largefiles,nosuid,rw,quota"
new_resource.options(options.split(/,/))
expect(provider).to receive(:shell_out_compacted!).with("mount", "-F", fstype, "-o", options, device, mountpoint)
- provider.mount_fs()
+ provider.mount_fs
end
it "should delete the 'noauto' magic option" do
options = "rw,noauto"
new_resource.options(%w{rw noauto})
expect(provider).to receive(:shell_out_compacted!).with("mount", "-F", fstype, "-o", "rw", device, mountpoint)
- provider.mount_fs()
+ provider.mount_fs
end
end
describe "umount_fs" do
it "should umount the filesystem if it is mounted" do
expect(provider).to receive(:shell_out_compacted!).with("umount", mountpoint)
- provider.umount_fs()
+ provider.umount_fs
end
end
diff --git a/spec/unit/provider/osx_profile_spec.rb b/spec/unit/provider/osx_profile_spec.rb
index 8f99ad6817..017041bc60 100644
--- a/spec/unit/provider/osx_profile_spec.rb
+++ b/spec/unit/provider/osx_profile_spec.rb
@@ -132,7 +132,7 @@ describe Chef::Provider::OsxProfile do
provider.load_current_resource
expect(
provider.instance_variable_get(:@new_profile_identifier)
- ).to eql(test_profile["PayloadIdentifier"])
+ ).to eql(test_profile["PayloadIdentifier"])
end
it "should install when not installed" do
@@ -167,7 +167,7 @@ describe Chef::Provider::OsxProfile do
provider.load_current_resource
allow(provider).to receive(:write_profile_to_disk).and_return(profile_path)
expect(provider).to receive(:shell_out_compacted).with("/usr/bin/profiles", "-I", "-F", profile_path).and_return(shell_out_success)
- provider.action_install()
+ provider.action_install
end
it "should fail if there is no identifier inside the profile" do
@@ -228,16 +228,14 @@ describe Chef::Provider::OsxProfile do
new_resource.profile_name "com.testprofile.screensaver"
new_resource.action(:remove)
provider.load_current_resource
- expect(provider.instance_variable_get(:@new_profile_identifier)
- ).to eql(new_resource.profile_name)
+ expect(provider.instance_variable_get(:@new_profile_identifier)).to eql(new_resource.profile_name)
end
it "should use specified identifier" do
new_resource.identifier "com.testprofile.screensaver"
new_resource.action(:remove)
provider.load_current_resource
- expect(provider.instance_variable_get(:@new_profile_identifier)
- ).to eql(new_resource.identifier)
+ expect(provider.instance_variable_get(:@new_profile_identifier)).to eql(new_resource.identifier)
end
it "should work with spaces in the identifier" do
@@ -251,7 +249,7 @@ describe Chef::Provider::OsxProfile do
new_resource.action(:remove)
provider.load_current_resource
expect(provider).to receive(:shell_out_compacted).with("/usr/bin/profiles", "-R", "-p", new_resource.identifier).and_return(shell_out_success)
- provider.action_remove()
+ provider.action_remove
end
end
end
diff --git a/spec/unit/provider/package/apt_spec.rb b/spec/unit/provider/package/apt_spec.rb
index bfc78cbb7f..b2c051d2f1 100644
--- a/spec/unit/provider/package/apt_spec.rb
+++ b/spec/unit/provider/package/apt_spec.rb
@@ -511,8 +511,8 @@ describe Chef::Provider::Package::Apt do
allow(@provider).to receive(:shell_out_compacted!).with(
"apt-mark", "showhold", timeout: 900
).and_return(instance_double(
- Mixlib::ShellOut, stdout: "irssi")
- )
+ Mixlib::ShellOut, stdout: "irssi"
+ ))
expect(logger).to receive(:trace).with("#{@provider.new_resource} is already locked")
@provider.action_lock
@@ -532,8 +532,8 @@ describe Chef::Provider::Package::Apt do
allow(@provider).to receive(:shell_out_compacted!).with(
"apt-mark", "showhold", timeout: 900
).and_return(instance_double(
- Mixlib::ShellOut, stdout: "")
- )
+ Mixlib::ShellOut, stdout: ""
+ ))
expect(logger).to receive(:trace).with("#{@provider.new_resource} is already unlocked")
@provider.action_unlock
diff --git a/spec/unit/provider/package/bff_spec.rb b/spec/unit/provider/package/bff_spec.rb
index 7606092762..b428ec0a72 100644
--- a/spec/unit/provider/package/bff_spec.rb
+++ b/spec/unit/provider/package/bff_spec.rb
@@ -81,7 +81,7 @@ describe Chef::Provider::Package::Bff do
status = double("Status", stdout: info, exitstatus: 0)
expect(@provider).to receive(:shell_out_compacted).with("installp", "-L", "-d", "/tmp/samba.base", timeout: 900).and_return(status)
expect(@provider).to receive(:shell_out_compacted).with("lslpp", "-lcq", "samba.base", timeout: 900).and_return(@empty_status)
- expect(logger).to receive(:warn).once.with(%r{bff package by product name})
+ expect(logger).to receive(:warn).once.with(/bff package by product name/)
@provider.load_current_resource
expect(@provider.current_resource.package_name).to eq("samba.base")
diff --git a/spec/unit/provider/package/cab_spec.rb b/spec/unit/provider/package/cab_spec.rb
index 2ed40566f4..0ffbcd4a51 100644
--- a/spec/unit/provider/package/cab_spec.rb
+++ b/spec/unit/provider/package/cab_spec.rb
@@ -260,7 +260,7 @@ describe Chef::Provider::Package::Cab do
end
before do
- new_resource.source = "#{ENV['TEMP']}/test6.1-kb2664825-v3-x64.cab"
+ new_resource.source = "#{ENV["TEMP"]}/test6.1-kb2664825-v3-x64.cab"
installed_package_list_obj = double(stdout: installed_package_list_stdout)
allow(provider).to receive(:dism_command).with("/Get-Packages").and_return(installed_package_list_obj)
end
diff --git a/spec/unit/provider/package/msu_spec.rb b/spec/unit/provider/package/msu_spec.rb
index b2f0b22963..905d48649f 100644
--- a/spec/unit/provider/package/msu_spec.rb
+++ b/spec/unit/provider/package/msu_spec.rb
@@ -243,7 +243,7 @@ describe Chef::Provider::Package::Msu, :windows_only do
describe "#extract_msu_contents" do
it "extracts the msu contents by using mixlib shellout" do
- expect(provider).to receive(:shell_out!).with("#{ENV['SYSTEMROOT']}\\system32\\expand.exe -f:* msu_file destination")
+ expect(provider).to receive(:shell_out!).with("#{ENV["SYSTEMROOT"]}\\system32\\expand.exe -f:* msu_file destination")
provider.extract_msu_contents("msu_file", "destination")
end
end
diff --git a/spec/unit/provider/package/openbsd_spec.rb b/spec/unit/provider/package/openbsd_spec.rb
index 01d6571f65..c8de4b7471 100644
--- a/spec/unit/provider/package/openbsd_spec.rb
+++ b/spec/unit/provider/package/openbsd_spec.rb
@@ -45,15 +45,16 @@ describe Chef::Provider::Package::Openbsd do
context "when not already installed" do
before do
- allow(provider).to receive(:shell_out_compacted!).with("pkg_info", "-e", "#{name}->0", anything()).and_return(instance_double("shellout", stdout: ""))
+ allow(provider).to receive(:shell_out_compacted!).with("pkg_info", "-e", "#{name}->0", anything).and_return(instance_double("shellout", stdout: ""))
end
context "when there is a single candidate" do
context "when source is not provided" do
it "should run the installation command" do
- expect(provider).to receive(:shell_out_compacted!).with("pkg_info", "-I", name, anything()).and_return(
- instance_double("shellout", stdout: "#{name}-#{version}\n"))
+ expect(provider).to receive(:shell_out_compacted!).with("pkg_info", "-I", name, anything).and_return(
+ instance_double("shellout", stdout: "#{name}-#{version}\n")
+ )
expect(provider).to receive(:shell_out_compacted!).with(
"pkg_add", "-r", "#{name}-#{version}",
{ env: { "PKG_PATH" => "http://ftp.OpenBSD.org/pub/OpenBSD/5.5/packages/amd64/" }, timeout: 900 }
@@ -69,8 +70,9 @@ describe Chef::Provider::Package::Openbsd do
context "if no version is specified" do
it "should raise an exception" do
- expect(provider).to receive(:shell_out_compacted!).with("pkg_info", "-I", name, anything()).and_return(
- instance_double("shellout", stdout: "#{name}-#{version}-#{flavor_a}\n#{name}-#{version}-#{flavor_b}\n"))
+ expect(provider).to receive(:shell_out_compacted!).with("pkg_info", "-I", name, anything).and_return(
+ instance_double("shellout", stdout: "#{name}-#{version}-#{flavor_a}\n#{name}-#{version}-#{flavor_b}\n")
+ )
expect { provider.run_action(:install) }.to raise_error(Chef::Exceptions::Package, /multiple matching candidates/)
end
end
@@ -83,9 +85,10 @@ describe Chef::Provider::Package::Openbsd do
context "if no version is specified" do
it "should run the installation command" do
- expect(provider).to receive(:shell_out_compacted!).with("pkg_info", "-e", "#{package_name}->0", anything()).and_return(instance_double("shellout", stdout: ""))
- expect(provider).to receive(:shell_out_compacted!).with("pkg_info", "-I", name, anything()).and_return(
- instance_double("shellout", stdout: "#{name}-#{version}-#{flavor}\n"))
+ expect(provider).to receive(:shell_out_compacted!).with("pkg_info", "-e", "#{package_name}->0", anything).and_return(instance_double("shellout", stdout: ""))
+ expect(provider).to receive(:shell_out_compacted!).with("pkg_info", "-I", name, anything).and_return(
+ instance_double("shellout", stdout: "#{name}-#{version}-#{flavor}\n")
+ )
expect(provider).to receive(:shell_out_compacted!).with(
"pkg_add", "-r", "#{name}-#{version}-#{flavor}",
{ env: { "PKG_PATH" => "http://ftp.OpenBSD.org/pub/OpenBSD/5.5/packages/amd64/" }, timeout: 900 }
@@ -98,8 +101,9 @@ describe Chef::Provider::Package::Openbsd do
context "if a version is specified" do
it "should use the flavor from the version" do
- expect(provider).to receive(:shell_out_compacted!).with("pkg_info", "-I", "#{name}-#{version}-#{flavor_b}", anything()).and_return(
- instance_double("shellout", stdout: "#{name}-#{version}-#{flavor_a}\n"))
+ expect(provider).to receive(:shell_out_compacted!).with("pkg_info", "-I", "#{name}-#{version}-#{flavor_b}", anything).and_return(
+ instance_double("shellout", stdout: "#{name}-#{version}-#{flavor_a}\n")
+ )
new_resource.version("#{version}-#{flavor_b}")
expect(provider).to receive(:shell_out_compacted!).with(
diff --git a/spec/unit/provider/package/smartos_spec.rb b/spec/unit/provider/package/smartos_spec.rb
index cd85e1b3d9..726420fe23 100644
--- a/spec/unit/provider/package/smartos_spec.rb
+++ b/spec/unit/provider/package/smartos_spec.rb
@@ -75,7 +75,7 @@ describe Chef::Provider::Package::SmartOS, "load_current_resource" do
end
it "should lookup the candidate_version if the variable is not already set (pkgin separated by spaces)" do
- search = double()
+ search = double
expect(search).to receive(:each_line)
.and_yield("something-varnish-1.1.1 something varnish like\n")
.and_yield("varnish-2.3.4 actual varnish\n")
@@ -85,7 +85,7 @@ describe Chef::Provider::Package::SmartOS, "load_current_resource" do
end
it "should lookup the candidate_version if the variable is not already set (pkgin separated by semicolons)" do
- search = double()
+ search = double
expect(search).to receive(:each_line)
.and_yield("something-varnish-1.1.1;;something varnish like\n")
.and_yield("varnish-2.3.4;;actual varnish\n")
diff --git a/spec/unit/provider/package/windows/exe_spec.rb b/spec/unit/provider/package/windows/exe_spec.rb
index 4f6a6121bd..6fa1747b03 100644
--- a/spec/unit/provider/package/windows/exe_spec.rb
+++ b/spec/unit/provider/package/windows/exe_spec.rb
@@ -117,7 +117,7 @@ describe Chef::Provider::Package::Windows::Exe do
context "no version given and one package installed with unquoted uninstall string" do
it "removes installed package and quotes uninstall string" do
allow(::File).to receive(:exist?).with("uninst_dir/uninst_file").and_return(true)
- expect(provider).to receive(:shell_out!).with(/start \"\" \/wait \"uninst_dir\/uninst_file\" \/S \/NCRC & exit %%%%ERRORLEVEL%%%%/, kind_of(Hash))
+ expect(provider).to receive(:shell_out!).with(%r{start \"\" /wait \"uninst_dir/uninst_file\" /S /NCRC & exit %%%%ERRORLEVEL%%%%}, kind_of(Hash))
provider.remove_package
end
end
@@ -126,7 +126,7 @@ describe Chef::Provider::Package::Windows::Exe do
it "removes installed package and quotes uninstall string" do
new_resource.timeout = 300
allow(::File).to receive(:exist?).with("uninst_dir/uninst_file").and_return(true)
- expect(provider).to receive(:shell_out!).with(/start \"\" \/wait \"uninst_dir\/uninst_file\" \/S \/NCRC & exit %%%%ERRORLEVEL%%%%/, timeout: 300, returns: [0])
+ expect(provider).to receive(:shell_out!).with(%r{start \"\" /wait \"uninst_dir/uninst_file\" /S /NCRC & exit %%%%ERRORLEVEL%%%%}, timeout: 300, returns: [0])
provider.remove_package
end
end
@@ -148,15 +148,15 @@ describe Chef::Provider::Package::Windows::Exe do
context "version given and installed" do
it "removes given version" do
new_resource.version("v2")
- expect(provider).to receive(:shell_out!).with(/start \"\" \/wait \"uninst_dir2\/uninst_file2\" \/S \/NCRC & exit %%%%ERRORLEVEL%%%%/, kind_of(Hash))
+ expect(provider).to receive(:shell_out!).with(%r{start \"\" /wait \"uninst_dir2/uninst_file2\" /S /NCRC & exit %%%%ERRORLEVEL%%%%}, kind_of(Hash))
provider.remove_package
end
end
context "no version given" do
it "removes both versions" do
- expect(provider).to receive(:shell_out!).with(/start \"\" \/wait \"uninst_dir1\/uninst_file1\" \/S \/NCRC & exit %%%%ERRORLEVEL%%%%/, kind_of(Hash))
- expect(provider).to receive(:shell_out!).with(/start \"\" \/wait \"uninst_dir2\/uninst_file2\" \/S \/NCRC & exit %%%%ERRORLEVEL%%%%/, kind_of(Hash))
+ expect(provider).to receive(:shell_out!).with(%r{start \"\" /wait \"uninst_dir1/uninst_file1\" /S /NCRC & exit %%%%ERRORLEVEL%%%%}, kind_of(Hash))
+ expect(provider).to receive(:shell_out!).with(%r{start \"\" /wait \"uninst_dir2/uninst_file2\" /S /NCRC & exit %%%%ERRORLEVEL%%%%}, kind_of(Hash))
provider.remove_package
end
end
@@ -167,7 +167,7 @@ describe Chef::Provider::Package::Windows::Exe do
let(:provider) { Chef::Provider::Package::Windows::Exe.new(new_resource, :nsis, uninstall_entry) }
it "calls installer with the correct flags" do
- expect(provider).to receive(:shell_out!).with(/start \"\" \/wait \"#{Regexp.quote(new_resource.source)}\" \/S \/NCRC & exit %%%%ERRORLEVEL%%%%/, kind_of(Hash))
+ expect(provider).to receive(:shell_out!).with(%r{start \"\" /wait \"#{Regexp.quote(new_resource.source)}\" /S /NCRC & exit %%%%ERRORLEVEL%%%%}, kind_of(Hash))
provider.install_package
end
end
@@ -176,7 +176,7 @@ describe Chef::Provider::Package::Windows::Exe do
let(:provider) { Chef::Provider::Package::Windows::Exe.new(new_resource, :installshield, uninstall_entry) }
it "calls installer with the correct flags" do
- expect(provider).to receive(:shell_out!).with(/start \"\" \/wait \"#{Regexp.quote(new_resource.source)}\" \/s \/sms & exit %%%%ERRORLEVEL%%%%/, kind_of(Hash))
+ expect(provider).to receive(:shell_out!).with(%r{start \"\" /wait \"#{Regexp.quote(new_resource.source)}\" /s /sms & exit %%%%ERRORLEVEL%%%%}, kind_of(Hash))
provider.install_package
end
end
@@ -185,7 +185,7 @@ describe Chef::Provider::Package::Windows::Exe do
let(:provider) { Chef::Provider::Package::Windows::Exe.new(new_resource, :inno, uninstall_entry) }
it "calls installer with the correct flags" do
- expect(provider).to receive(:shell_out!).with(/start \"\" \/wait \"#{Regexp.quote(new_resource.source)}\" \/VERYSILENT \/SUPPRESSMSGBOXES \/NORESTART & exit %%%%ERRORLEVEL%%%%/, kind_of(Hash))
+ expect(provider).to receive(:shell_out!).with(%r{start \"\" /wait \"#{Regexp.quote(new_resource.source)}\" /VERYSILENT /SUPPRESSMSGBOXES /NORESTART & exit %%%%ERRORLEVEL%%%%}, kind_of(Hash))
provider.install_package
end
end
@@ -194,7 +194,7 @@ describe Chef::Provider::Package::Windows::Exe do
let(:provider) { Chef::Provider::Package::Windows::Exe.new(new_resource, :wise, uninstall_entry) }
it "calls installer with the correct flags" do
- expect(provider).to receive(:shell_out!).with(/start \"\" \/wait \"#{Regexp.quote(new_resource.source)}\" \/s & exit %%%%ERRORLEVEL%%%%/, kind_of(Hash))
+ expect(provider).to receive(:shell_out!).with(%r{start \"\" /wait \"#{Regexp.quote(new_resource.source)}\" /s & exit %%%%ERRORLEVEL%%%%}, kind_of(Hash))
provider.install_package
end
end
diff --git a/spec/unit/provider/package/windows/msi_spec.rb b/spec/unit/provider/package/windows/msi_spec.rb
index 0e939610db..d2902e1bb1 100644
--- a/spec/unit/provider/package/windows/msi_spec.rb
+++ b/spec/unit/provider/package/windows/msi_spec.rb
@@ -104,14 +104,14 @@ describe Chef::Provider::Package::Windows::MSI do
describe "install_package" do
it "calls msiexec /qn /i" do
- expect(provider).to receive(:shell_out!).with(/msiexec \/qn \/i \"#{Regexp.quote(new_resource.source)}\"/, kind_of(Hash))
+ expect(provider).to receive(:shell_out!).with(%r{msiexec /qn /i \"#{Regexp.quote(new_resource.source)}\"}, kind_of(Hash))
provider.install_package
end
end
describe "remove_package" do
it "calls msiexec /qn /x" do
- expect(provider).to receive(:shell_out!).with(/msiexec \/qn \/x \"#{Regexp.quote(new_resource.source)}\"/, kind_of(Hash))
+ expect(provider).to receive(:shell_out!).with(%r{msiexec /qn /x \"#{Regexp.quote(new_resource.source)}\"}, kind_of(Hash))
provider.remove_package
end
@@ -121,7 +121,7 @@ describe Chef::Provider::Package::Windows::MSI do
end
it "removes installed package" do
- expect(provider).to receive(:shell_out!).with(/msiexec \/x {guid} \/q/, kind_of(Hash))
+ expect(provider).to receive(:shell_out!).with(%r{msiexec /x {guid} /q}, kind_of(Hash))
provider.remove_package
end
@@ -140,8 +140,8 @@ describe Chef::Provider::Package::Windows::MSI do
end
it "removes both installed package" do
- expect(provider).to receive(:shell_out!).with(/msiexec \/x {guid} \/q/, kind_of(Hash))
- expect(provider).to receive(:shell_out!).with(/msiexec \/x {guid2} \/q/, kind_of(Hash))
+ expect(provider).to receive(:shell_out!).with(%r{msiexec /x {guid} /q}, kind_of(Hash))
+ expect(provider).to receive(:shell_out!).with(%r{msiexec /x {guid2} /q}, kind_of(Hash))
provider.remove_package
end
end
@@ -150,7 +150,7 @@ describe Chef::Provider::Package::Windows::MSI do
before { new_resource.options("/Q") }
it "does not duplicate quiet switch" do
- expect(provider).to receive(:shell_out!).with(/msiexec \/x {guid} \/Q/, kind_of(Hash))
+ expect(provider).to receive(:shell_out!).with(%r{msiexec /x {guid} /Q}, kind_of(Hash))
provider.remove_package
end
end
@@ -159,7 +159,7 @@ describe Chef::Provider::Package::Windows::MSI do
before { new_resource.options("/qn") }
it "does not duplicate quiet switch" do
- expect(provider).to receive(:shell_out!).with(/msiexec \/x {guid} \/qn/, kind_of(Hash))
+ expect(provider).to receive(:shell_out!).with(%r{msiexec /x {guid} /qn}, kind_of(Hash))
provider.remove_package
end
end
diff --git a/spec/unit/provider/package/windows_spec.rb b/spec/unit/provider/package/windows_spec.rb
index 6b85013f3d..2fafb3bd0e 100644
--- a/spec/unit/provider/package/windows_spec.rb
+++ b/spec/unit/provider/package/windows_spec.rb
@@ -436,7 +436,8 @@ describe Chef::Provider::Package::Windows, :windows_only do
it "raises the checksum mismatch exception" do
expect { provider.send(:validate_content!) }.to raise_error(
- Chef::Exceptions::ChecksumMismatch)
+ Chef::Exceptions::ChecksumMismatch
+ )
end
end
end
diff --git a/spec/unit/provider/package/yum/yum_cache_spec.rb b/spec/unit/provider/package/yum/yum_cache_spec.rb
index 6b2a617ac8..9867c31c37 100644
--- a/spec/unit/provider/package/yum/yum_cache_spec.rb
+++ b/spec/unit/provider/package/yum/yum_cache_spec.rb
@@ -60,7 +60,7 @@ describe Chef::Provider::Package::Yum::YumCache do
expect( yum_cache.version_available?("foo", "1.2.3", "x86_64") ).to be true
end
- [ :refresh, :reload, :reload_installed, :reload_provides, :reset, :reset_installed ].each do |method|
+ %i{refresh reload reload_installed reload_provides reset reset_installed}.each do |method|
it "restarts the python helper when #{method} is called" do
expect( python_helper ).to receive(:restart)
yum_cache.send(method)
diff --git a/spec/unit/provider/powershell_script_spec.rb b/spec/unit/provider/powershell_script_spec.rb
index 61c415f88d..cca0f34067 100644
--- a/spec/unit/provider/powershell_script_spec.rb
+++ b/spec/unit/provider/powershell_script_spec.rb
@@ -22,9 +22,9 @@ describe Chef::Provider::PowershellScript, "action_run" do
let(:powershell_version) { nil }
let(:node) do
node = Chef::Node.new
- node.default["kernel"] = Hash.new
+ node.default["kernel"] = {}
node.default["kernel"][:machine] = :x86_64.to_s
- if ! powershell_version.nil?
+ unless powershell_version.nil?
node.default[:languages] = { powershell: { version: powershell_version } }
end
node
@@ -107,19 +107,19 @@ describe Chef::Provider::PowershellScript, "action_run" do
"3.6" => "Bypass",
"4.0" => "Bypass",
"5.0" => "Bypass" }.each do |version_policy|
- let(:powershell_version) { version_policy[0].to_f }
- context "when running PowerShell version #{version_policy[0]}" do
let(:powershell_version) { version_policy[0].to_f }
-
- it "sets default -ExecutionPolicy flag to '#{version_policy[1]}'" do
- expect(execution_policy_flag.downcase).to eq(version_policy[1].downcase)
- end
- it "sets user defined -ExecutionPolicy flag to 'RemoteSigned'" do
- set_user_defined_flag
- expect(execution_policy_flag.downcase).to eq("RemoteSigned".downcase)
+ context "when running PowerShell version #{version_policy[0]}" do
+ let(:powershell_version) { version_policy[0].to_f }
+
+ it "sets default -ExecutionPolicy flag to '#{version_policy[1]}'" do
+ expect(execution_policy_flag.downcase).to eq(version_policy[1].downcase)
+ end
+ it "sets user defined -ExecutionPolicy flag to 'RemoteSigned'" do
+ set_user_defined_flag
+ expect(execution_policy_flag.downcase).to eq("RemoteSigned".downcase)
+ end
end
end
- end
end
end
end
diff --git a/spec/unit/provider/registry_key_spec.rb b/spec/unit/provider/registry_key_spec.rb
index 9a7dd9996e..2df2c917f9 100644
--- a/spec/unit/provider/registry_key_spec.rb
+++ b/spec/unit/provider/registry_key_spec.rb
@@ -322,7 +322,7 @@ describe Chef::Provider::RegistryKey do
expect(@double_registry).to receive(:get_values).with(keyname).and_return(
[
{ name: "one", type: :string, data: "initial value" },
- { name: "two", type: :dword, data: 9001 }
+ { name: "two", type: :dword, data: 9001 },
]
)
end
diff --git a/spec/unit/provider/route_spec.rb b/spec/unit/provider/route_spec.rb
index 67311aa6f7..ad5223a04f 100644
--- a/spec/unit/provider/route_spec.rb
+++ b/spec/unit/provider/route_spec.rb
@@ -125,7 +125,7 @@ describe Chef::Provider::Route do
@resource_add.action(:add)
@provider.run_action(:add)
expect(route_file.string.split("\n").size).to eq(1)
- expect(route_file.string).to match(/^192\.168\.1\.0\/24 via 192\.168\.0\.1$/)
+ expect(route_file.string).to match(%r{^192\.168\.1\.0/24 via 192\.168\.0\.1$})
end
end
@@ -150,12 +150,12 @@ describe Chef::Provider::Route do
describe Chef::Provider::Route, "generate_command for action_add" do
it "should include a netmask when a one is specified" do
@new_resource.netmask("255.255.0.0")
- expect(@provider.generate_command(:add).join(" ")).to match(/\/\d{1,2}/)
+ expect(@provider.generate_command(:add).join(" ")).to match(%r{/\d{1,2}})
end
it "should not include a netmask when a one is specified" do
@new_resource.netmask(nil)
- expect(@provider.generate_command(:add).join(" ")).not_to match(/\/\d{1,2}/)
+ expect(@provider.generate_command(:add).join(" ")).not_to match(%r{/\d{1,2}})
end
it "should include ' via $gateway ' when a gateway is specified" do
@@ -176,12 +176,12 @@ describe Chef::Provider::Route do
describe Chef::Provider::Route, "generate_command for action_delete" do
it "should include a netmask when a one is specified" do
@new_resource.netmask("255.255.0.0")
- expect(@provider.generate_command(:delete).join(" ")).to match(/\/\d{1,2}/)
+ expect(@provider.generate_command(:delete).join(" ")).to match(%r{/\d{1,2}})
end
it "should not include a netmask when a one is specified" do
@new_resource.netmask(nil)
- expect(@provider.generate_command(:delete).join(" ")).not_to match(/\/\d{1,2}/)
+ expect(@provider.generate_command(:delete).join(" ")).not_to match(%r{/\d{1,2}})
end
it "should include ' via $gateway ' when a gateway is specified" do
@@ -197,11 +197,11 @@ describe Chef::Provider::Route do
describe Chef::Provider::Route, "config_file_contents for action_add" do
it "should include a netmask when a one is specified" do
@new_resource.netmask("255.255.0.0")
- expect(@provider.config_file_contents(:add, target: @new_resource.target, netmask: @new_resource.netmask)).to match(/\/\d{1,2}.*\n$/)
+ expect(@provider.config_file_contents(:add, target: @new_resource.target, netmask: @new_resource.netmask)).to match(%r{/\d{1,2}.*\n$})
end
it "should not include a netmask when a one is specified" do
- expect(@provider.config_file_contents(:add, target: @new_resource.target)).not_to match(/\/\d{1,2}.*\n$/)
+ expect(@provider.config_file_contents(:add, target: @new_resource.target)).not_to match(%r{/\d{1,2}.*\n$})
end
it "should include ' via $gateway ' when a gateway is specified" do
@@ -261,10 +261,10 @@ describe Chef::Provider::Route do
@provider.action = :add
@provider.generate_config
expect(route_file.string.split("\n").size).to eq(4)
- expect(route_file.string).to match(/^192\.168\.1\.0\/24 via 192\.168\.0\.1$/)
- expect(route_file.string).to match(/^192\.168\.2\.0\/24 via 192\.168\.0\.1$/)
- expect(route_file.string).to match(/^192\.168\.3\.0\/24 via 192\.168\.0\.1$/)
- expect(route_file.string).to match(/^192\.168\.4\.0\/24 via 192\.168\.0\.1$/)
+ expect(route_file.string).to match(%r{^192\.168\.1\.0/24 via 192\.168\.0\.1$})
+ expect(route_file.string).to match(%r{^192\.168\.2\.0/24 via 192\.168\.0\.1$})
+ expect(route_file.string).to match(%r{^192\.168\.3\.0/24 via 192\.168\.0\.1$})
+ expect(route_file.string).to match(%r{^192\.168\.4\.0/24 via 192\.168\.0\.1$})
end
end
end
diff --git a/spec/unit/provider/service/arch_service_spec.rb b/spec/unit/provider/service/arch_service_spec.rb
index faec7ff645..de2bb16a6a 100644
--- a/spec/unit/provider/service/arch_service_spec.rb
+++ b/spec/unit/provider/service/arch_service_spec.rb
@@ -181,7 +181,7 @@ describe Chef::Provider::Service::Arch, "load_current_resource" do
it "should add chef to DAEMONS array" do
allow(::File).to receive(:read).with("/etc/rc.conf").and_return("DAEMONS=(network)")
expect(@provider).to receive(:update_daemons).with(%w{network chef})
- @provider.enable_service()
+ @provider.enable_service
end
end
@@ -202,7 +202,7 @@ describe Chef::Provider::Service::Arch, "load_current_resource" do
it "should remove chef from DAEMONS array" do
allow(::File).to receive(:read).with("/etc/rc.conf").and_return("DAEMONS=(network chef)")
expect(@provider).to receive(:update_daemons).with(["network", "!chef"])
- @provider.disable_service()
+ @provider.disable_service
end
end
@@ -223,12 +223,12 @@ describe Chef::Provider::Service::Arch, "load_current_resource" do
it "should call the start command if one is specified" do
@new_resource.start_command("/etc/rc.d/chef startyousillysally")
expect(@provider).to receive(:shell_out!).with("/etc/rc.d/chef startyousillysally", default_env: false)
- @provider.start_service()
+ @provider.start_service
end
it "should call '/etc/rc.d/service_name start' if no start command is specified" do
expect(@provider).to receive(:shell_out!).with("/etc/rc.d/#{@new_resource.service_name} start", default_env: false)
- @provider.start_service()
+ @provider.start_service
end
end
@@ -249,12 +249,12 @@ describe Chef::Provider::Service::Arch, "load_current_resource" do
it "should call the stop command if one is specified" do
@new_resource.stop_command("/etc/rc.d/chef itoldyoutostop")
expect(@provider).to receive(:shell_out!).with("/etc/rc.d/chef itoldyoutostop", default_env: false)
- @provider.stop_service()
+ @provider.stop_service
end
it "should call '/etc/rc.d/service_name stop' if no stop command is specified" do
expect(@provider).to receive(:shell_out!).with("/etc/rc.d/#{@new_resource.service_name} stop", default_env: false)
- @provider.stop_service()
+ @provider.stop_service
end
end
@@ -276,20 +276,20 @@ describe Chef::Provider::Service::Arch, "load_current_resource" do
it "should call 'restart' on the service_name if the resource supports it" do
@new_resource.supports({ restart: true })
expect(@provider).to receive(:shell_out!).with("/etc/rc.d/#{@new_resource.service_name} restart", default_env: false)
- @provider.restart_service()
+ @provider.restart_service
end
it "should call the restart_command if one has been specified" do
@new_resource.restart_command("/etc/rc.d/chef restartinafire")
expect(@provider).to receive(:shell_out!).with("/etc/rc.d/#{@new_resource.service_name} restartinafire", default_env: false)
- @provider.restart_service()
+ @provider.restart_service
end
it "should just call stop, then start when the resource doesn't support restart and no restart_command is specified" do
expect(@provider).to receive(:stop_service)
expect(@provider).to receive(:sleep).with(1)
expect(@provider).to receive(:start_service)
- @provider.restart_service()
+ @provider.restart_service
end
end
@@ -311,13 +311,13 @@ describe Chef::Provider::Service::Arch, "load_current_resource" do
it "should call 'reload' on the service if it supports it" do
@new_resource.supports({ reload: true })
expect(@provider).to receive(:shell_out!).with("/etc/rc.d/#{@new_resource.service_name} reload", default_env: false)
- @provider.reload_service()
+ @provider.reload_service
end
it "should should run the user specified reload command if one is specified and the service doesn't support reload" do
@new_resource.reload_command("/etc/rc.d/chef lollerpants")
expect(@provider).to receive(:shell_out!).with("/etc/rc.d/#{@new_resource.service_name} lollerpants", default_env: false)
- @provider.reload_service()
+ @provider.reload_service
end
end
end
diff --git a/spec/unit/provider/service/debian_service_spec.rb b/spec/unit/provider/service/debian_service_spec.rb
index 626abb10f7..5f89605b2e 100644
--- a/spec/unit/provider/service/debian_service_spec.rb
+++ b/spec/unit/provider/service/debian_service_spec.rb
@@ -89,7 +89,8 @@ describe Chef::Provider::Service::Debian do
"0" => [:stop, "20"],
"1" => [:stop, "20"],
"6" => [:stop, "20"],
- })
+ }
+ )
end
end
diff --git a/spec/unit/provider/service/freebsd_service_spec.rb b/spec/unit/provider/service/freebsd_service_spec.rb
index d33b97d63d..4392786edc 100644
--- a/spec/unit/provider/service/freebsd_service_spec.rb
+++ b/spec/unit/provider/service/freebsd_service_spec.rb
@@ -261,7 +261,8 @@ describe Chef::Provider::Service::Freebsd do
[
%Q{thing_#{new_resource.service_name}_enable="YES"},
%Q{#{new_resource.service_name}_enable="NO"},
- ] end
+ ]
+ end
it "sets enabled based on the exact match (false)" do
provider.determine_enabled_status!
expect(current_resource.enabled).to be false
@@ -273,7 +274,8 @@ describe Chef::Provider::Service::Freebsd do
[
%Q{#{new_resource.service_name}_thing_enable="YES"},
%Q{#{new_resource.service_name}_enable="NO"},
- ] end
+ ]
+ end
it "sets enabled based on the exact match (false)" do
provider.determine_enabled_status!
expect(current_resource.enabled).to be false
@@ -285,7 +287,8 @@ describe Chef::Provider::Service::Freebsd do
[
%Q{thing_#{new_resource.service_name}_enable="NO"},
%Q{#{new_resource.service_name}_enable="YES"},
- ] end
+ ]
+ end
it "sets enabled based on the exact match (true)" do
provider.determine_enabled_status!
expect(current_resource.enabled).to be true
@@ -297,7 +300,8 @@ describe Chef::Provider::Service::Freebsd do
[
%Q{#{new_resource.service_name}_thing_enable="NO"},
%Q{#{new_resource.service_name}_enable="YES"},
- ] end
+ ]
+ end
it "sets enabled based on the exact match (true)" do
provider.determine_enabled_status!
expect(current_resource.enabled).to be true
@@ -445,12 +449,12 @@ describe Chef::Provider::Service::Freebsd do
it "should call the start command if one is specified" do
new_resource.start_command("/etc/rc.d/chef startyousillysally")
expect(provider).to receive(:shell_out!).with("/etc/rc.d/chef startyousillysally", default_env: false)
- provider.start_service()
+ provider.start_service
end
it "should call '/usr/local/etc/rc.d/service_name faststart' if no start command is specified" do
expect(provider).to receive(:shell_out!).with("/usr/local/etc/rc.d/#{new_resource.service_name} faststart", default_env: false)
- provider.start_service()
+ provider.start_service
end
end
@@ -458,12 +462,12 @@ describe Chef::Provider::Service::Freebsd do
it "should call the stop command if one is specified" do
new_resource.stop_command("/etc/init.d/chef itoldyoutostop")
expect(provider).to receive(:shell_out!).with("/etc/init.d/chef itoldyoutostop", default_env: false)
- provider.stop_service()
+ provider.stop_service
end
it "should call '/usr/local/etc/rc.d/service_name faststop' if no stop command is specified" do
expect(provider).to receive(:shell_out!).with("/usr/local/etc/rc.d/#{new_resource.service_name} faststop", default_env: false)
- provider.stop_service()
+ provider.stop_service
end
end
@@ -471,19 +475,19 @@ describe Chef::Provider::Service::Freebsd do
it "should call 'restart' on the service_name if the resource supports it" do
new_resource.supports({ restart: true })
expect(provider).to receive(:shell_out!).with("/usr/local/etc/rc.d/#{new_resource.service_name} fastrestart", default_env: false)
- provider.restart_service()
+ provider.restart_service
end
it "should call the restart_command if one has been specified" do
new_resource.restart_command("/etc/init.d/chef restartinafire")
expect(provider).to receive(:shell_out!).with("/etc/init.d/chef restartinafire", default_env: false)
- provider.restart_service()
+ provider.restart_service
end
it "otherwise it should call stop and start" do
expect(provider).to receive(:stop_service)
expect(provider).to receive(:start_service)
- provider.restart_service()
+ provider.restart_service
end
end
end
@@ -550,21 +554,21 @@ describe Chef::Provider::Service::Freebsd do
allow(current_resource).to receive(:enabled).and_return(false)
expect(provider).to receive(:read_rc_conf).and_return([ "foo", "#{new_resource.service_name}_enable=\"NO\"", "bar" ])
expect(provider).to receive(:write_rc_conf).with(["foo", "bar", "#{new_resource.service_name}_enable=\"YES\""])
- provider.enable_service()
+ provider.enable_service
end
it "should not partial match an already enabled service" do
allow(current_resource).to receive(:enabled).and_return(false)
expect(provider).to receive(:read_rc_conf).and_return([ "foo", "thing_#{new_resource.service_name}_enable=\"NO\"", "bar" ])
expect(provider).to receive(:write_rc_conf).with(["foo", "thing_#{new_resource.service_name}_enable=\"NO\"", "bar", "#{new_resource.service_name}_enable=\"YES\""])
- provider.enable_service()
+ provider.enable_service
end
it "should enable the service if it is not enabled and not already specified in the rc.conf file" do
allow(current_resource).to receive(:enabled).and_return(false)
expect(provider).to receive(:read_rc_conf).and_return(%w{foo bar})
expect(provider).to receive(:write_rc_conf).with(["foo", "bar", "#{new_resource.service_name}_enable=\"YES\""])
- provider.enable_service()
+ provider.enable_service
end
it "should not enable the service if it is already enabled" do
@@ -577,7 +581,7 @@ describe Chef::Provider::Service::Freebsd do
allow(current_resource).to receive(:enabled).and_return(false)
expect(provider).to receive(:read_rc_conf).and_return([ "foo", "bar", "\# #{new_resource.service_name}_enable=\"YES\"", "\# #{new_resource.service_name}_enable=\"NO\""])
expect(provider).to receive(:write_rc_conf).with(["foo", "bar", "#{new_resource.service_name}_enable=\"YES\""])
- provider.enable_service()
+ provider.enable_service
end
end
@@ -591,27 +595,27 @@ describe Chef::Provider::Service::Freebsd do
allow(current_resource).to receive(:enabled).and_return(true)
expect(provider).to receive(:read_rc_conf).and_return([ "foo", "#{new_resource.service_name}_enable=\"YES\"", "bar" ])
expect(provider).to receive(:write_rc_conf).with(["foo", "bar", "#{new_resource.service_name}_enable=\"NO\""])
- provider.disable_service()
+ provider.disable_service
end
it "should not disable an enabled service that partially matches" do
allow(current_resource).to receive(:enabled).and_return(true)
expect(provider).to receive(:read_rc_conf).and_return([ "foo", "thing_#{new_resource.service_name}_enable=\"YES\"", "bar" ])
expect(provider).to receive(:write_rc_conf).with(["foo", "thing_#{new_resource.service_name}_enable=\"YES\"", "bar", "#{new_resource.service_name}_enable=\"NO\""])
- provider.disable_service()
+ provider.disable_service
end
it "should not disable the service if it is already disabled" do
allow(current_resource).to receive(:enabled).and_return(false)
expect(provider).not_to receive(:write_rc_conf)
- provider.disable_service()
+ provider.disable_service
end
it "should remove commented out versions of it being disabled or enabled" do
allow(current_resource).to receive(:enabled).and_return(true)
expect(provider).to receive(:read_rc_conf).and_return([ "foo", "bar", "\# #{new_resource.service_name}_enable=\"YES\"", "\# #{new_resource.service_name}_enable=\"NO\""])
expect(provider).to receive(:write_rc_conf).with(["foo", "bar", "#{new_resource.service_name}_enable=\"NO\""])
- provider.disable_service()
+ provider.disable_service
end
end
end
diff --git a/spec/unit/provider/service/gentoo_service_spec.rb b/spec/unit/provider/service/gentoo_service_spec.rb
index 6a928d849b..bc3d0b5c04 100644
--- a/spec/unit/provider/service/gentoo_service_spec.rb
+++ b/spec/unit/provider/service/gentoo_service_spec.rb
@@ -129,14 +129,14 @@ describe Chef::Provider::Service::Gentoo do
describe Chef::Provider::Service::Gentoo, "enable_service" do
it "should call rc-update add *service* default" do
expect(@provider).to receive(:shell_out!).with("/sbin/rc-update add chef default")
- @provider.enable_service()
+ @provider.enable_service
end
end
describe Chef::Provider::Service::Gentoo, "disable_service" do
it "should call rc-update del *service* default" do
expect(@provider).to receive(:shell_out!).with("/sbin/rc-update del chef default")
- @provider.disable_service()
+ @provider.disable_service
end
end
end
diff --git a/spec/unit/provider/service/init_service_spec.rb b/spec/unit/provider/service/init_service_spec.rb
index 38e9ad37de..b75d7c4981 100644
--- a/spec/unit/provider/service/init_service_spec.rb
+++ b/spec/unit/provider/service/init_service_spec.rb
@@ -165,12 +165,12 @@ describe Chef::Provider::Service::Init, "load_current_resource" do
it "should call the start command if one is specified" do
@new_resource.start_command("/etc/init.d/chef startyousillysally")
expect(@provider).to receive(:shell_out!).with("/etc/init.d/chef startyousillysally", default_env: false)
- @provider.start_service()
+ @provider.start_service
end
it "should call '/etc/init.d/service_name start' if no start command is specified" do
expect(@provider).to receive(:shell_out!).with("/etc/init.d/#{@new_resource.service_name} start", default_env: false)
- @provider.start_service()
+ @provider.start_service
end
end
@@ -178,12 +178,12 @@ describe Chef::Provider::Service::Init, "load_current_resource" do
it "should call the stop command if one is specified" do
@new_resource.stop_command("/etc/init.d/chef itoldyoutostop")
expect(@provider).to receive(:shell_out!).with("/etc/init.d/chef itoldyoutostop", default_env: false)
- @provider.stop_service()
+ @provider.stop_service
end
it "should call '/etc/init.d/service_name stop' if no stop command is specified" do
expect(@provider).to receive(:shell_out!).with("/etc/init.d/#{@new_resource.service_name} stop", default_env: false)
- @provider.stop_service()
+ @provider.stop_service
end
end
@@ -191,20 +191,20 @@ describe Chef::Provider::Service::Init, "load_current_resource" do
it "should call 'restart' on the service_name if the resource supports it" do
@new_resource.supports({ restart: true })
expect(@provider).to receive(:shell_out!).with("/etc/init.d/#{@new_resource.service_name} restart", default_env: false)
- @provider.restart_service()
+ @provider.restart_service
end
it "should call the restart_command if one has been specified" do
@new_resource.restart_command("/etc/init.d/chef restartinafire")
expect(@provider).to receive(:shell_out!).with("/etc/init.d/#{@new_resource.service_name} restartinafire", default_env: false)
- @provider.restart_service()
+ @provider.restart_service
end
it "should just call stop, then start when the resource doesn't support restart and no restart_command is specified" do
expect(@provider).to receive(:stop_service)
expect(@provider).to receive(:sleep).with(1)
expect(@provider).to receive(:start_service)
- @provider.restart_service()
+ @provider.restart_service
end
end
@@ -212,13 +212,13 @@ describe Chef::Provider::Service::Init, "load_current_resource" do
it "should call 'reload' on the service if it supports it" do
@new_resource.supports({ reload: true })
expect(@provider).to receive(:shell_out!).with("/etc/init.d/chef reload", default_env: false)
- @provider.reload_service()
+ @provider.reload_service
end
it "should should run the user specified reload command if one is specified and the service doesn't support reload" do
@new_resource.reload_command("/etc/init.d/chef lollerpants")
expect(@provider).to receive(:shell_out!).with("/etc/init.d/chef lollerpants", default_env: false)
- @provider.reload_service()
+ @provider.reload_service
end
end
diff --git a/spec/unit/provider/service/invokercd_service_spec.rb b/spec/unit/provider/service/invokercd_service_spec.rb
index fb1a29fa43..1b3344e77b 100644
--- a/spec/unit/provider/service/invokercd_service_spec.rb
+++ b/spec/unit/provider/service/invokercd_service_spec.rb
@@ -152,12 +152,12 @@ describe Chef::Provider::Service::Invokercd, "load_current_resource" do
it "should call the start command if one is specified" do
@new_resource.start_command("/usr/sbin/invoke-rc.d chef startyousillysally")
expect(@provider).to receive(:shell_out!).with("/usr/sbin/invoke-rc.d chef startyousillysally", default_env: false)
- @provider.start_service()
+ @provider.start_service
end
it "should call '/usr/sbin/invoke-rc.d service_name start' if no start command is specified" do
expect(@provider).to receive(:shell_out!).with("/usr/sbin/invoke-rc.d #{@new_resource.service_name} start", default_env: false)
- @provider.start_service()
+ @provider.start_service
end
end
@@ -165,12 +165,12 @@ describe Chef::Provider::Service::Invokercd, "load_current_resource" do
it "should call the stop command if one is specified" do
@new_resource.stop_command("/usr/sbin/invoke-rc.d chef itoldyoutostop")
expect(@provider).to receive(:shell_out!).with("/usr/sbin/invoke-rc.d chef itoldyoutostop", default_env: false)
- @provider.stop_service()
+ @provider.stop_service
end
it "should call '/usr/sbin/invoke-rc.d service_name stop' if no stop command is specified" do
expect(@provider).to receive(:shell_out!).with("/usr/sbin/invoke-rc.d #{@new_resource.service_name} stop", default_env: false)
- @provider.stop_service()
+ @provider.stop_service
end
end
@@ -178,20 +178,20 @@ describe Chef::Provider::Service::Invokercd, "load_current_resource" do
it "should call 'restart' on the service_name if the resource supports it" do
@new_resource.supports({ restart: true })
expect(@provider).to receive(:shell_out!).with("/usr/sbin/invoke-rc.d #{@new_resource.service_name} restart", default_env: false)
- @provider.restart_service()
+ @provider.restart_service
end
it "should call the restart_command if one has been specified" do
@new_resource.restart_command("/usr/sbin/invoke-rc.d chef restartinafire")
expect(@provider).to receive(:shell_out!).with("/usr/sbin/invoke-rc.d #{@new_resource.service_name} restartinafire", default_env: false)
- @provider.restart_service()
+ @provider.restart_service
end
it "should just call stop, then start when the resource doesn't support restart and no restart_command is specified" do
expect(@provider).to receive(:stop_service)
expect(@provider).to receive(:sleep).with(1)
expect(@provider).to receive(:start_service)
- @provider.restart_service()
+ @provider.restart_service
end
end
@@ -199,13 +199,13 @@ describe Chef::Provider::Service::Invokercd, "load_current_resource" do
it "should call 'reload' on the service if it supports it" do
@new_resource.supports({ reload: true })
expect(@provider).to receive(:shell_out!).with("/usr/sbin/invoke-rc.d chef reload", default_env: false)
- @provider.reload_service()
+ @provider.reload_service
end
it "should should run the user specified reload command if one is specified and the service doesn't support reload" do
@new_resource.reload_command("/usr/sbin/invoke-rc.d chef lollerpants")
expect(@provider).to receive(:shell_out!).with("/usr/sbin/invoke-rc.d chef lollerpants", default_env: false)
- @provider.reload_service()
+ @provider.reload_service
end
end
end
diff --git a/spec/unit/provider/service/openbsd_service_spec.rb b/spec/unit/provider/service/openbsd_service_spec.rb
index 913fddc1cf..dfa491fc38 100644
--- a/spec/unit/provider/service/openbsd_service_spec.rb
+++ b/spec/unit/provider/service/openbsd_service_spec.rb
@@ -178,7 +178,8 @@ describe Chef::Provider::Service::Openbsd do
[
%Q{thing_#{provider.builtin_service_enable_variable_name}="YES"},
%Q{#{provider.builtin_service_enable_variable_name}="NO"},
- ] end
+ ]
+ end
it "sets enabled based on the exact match (false)" do
provider.determine_enabled_status!
expect(current_resource.enabled).to be false
@@ -190,7 +191,8 @@ describe Chef::Provider::Service::Openbsd do
[
%Q{#{provider.builtin_service_enable_variable_name}_thing="YES"},
(provider.builtin_service_enable_variable_name).to_s,
- ] end
+ ]
+ end
it "sets enabled based on the exact match (false)" do
provider.determine_enabled_status!
expect(current_resource.enabled).to be false
@@ -202,7 +204,8 @@ describe Chef::Provider::Service::Openbsd do
[
%Q{thing_#{provider.builtin_service_enable_variable_name}="NO"},
%Q{#{provider.builtin_service_enable_variable_name}="YES"},
- ] end
+ ]
+ end
it "sets enabled based on the exact match (true)" do
provider.determine_enabled_status!
expect(current_resource.enabled).to be true
@@ -214,7 +217,8 @@ describe Chef::Provider::Service::Openbsd do
[
%Q{#{provider.builtin_service_enable_variable_name}_thing="NO"},
%Q{#{provider.builtin_service_enable_variable_name}="YES"},
- ] end
+ ]
+ end
it "sets enabled based on the exact match (true)" do
provider.determine_enabled_status!
expect(current_resource.enabled).to be true
@@ -286,12 +290,12 @@ describe Chef::Provider::Service::Openbsd do
it "should call the start command if one is specified" do
new_resource.start_command("/etc/rc.d/chef startyousillysally")
expect(provider).to receive(:shell_out!).with("/etc/rc.d/chef startyousillysally", default_env: false)
- provider.start_service()
+ provider.start_service
end
it "should call '/usr/local/etc/rc.d/service_name start' if no start command is specified" do
expect(provider).to receive(:shell_out!).with("/etc/rc.d/#{new_resource.service_name} start", default_env: false)
- provider.start_service()
+ provider.start_service
end
end
@@ -299,12 +303,12 @@ describe Chef::Provider::Service::Openbsd do
it "should call the stop command if one is specified" do
new_resource.stop_command("/etc/init.d/chef itoldyoutostop")
expect(provider).to receive(:shell_out!).with("/etc/init.d/chef itoldyoutostop", default_env: false)
- provider.stop_service()
+ provider.stop_service
end
it "should call '/usr/local/etc/rc.d/service_name stop' if no stop command is specified" do
expect(provider).to receive(:shell_out!).with("/etc/rc.d/#{new_resource.service_name} stop", default_env: false)
- provider.stop_service()
+ provider.stop_service
end
end
@@ -313,20 +317,20 @@ describe Chef::Provider::Service::Openbsd do
let(:supports) { { restart: true } }
it "should call 'restart' on the service_name if the resource supports it" do
expect(provider).to receive(:shell_out!).with("/etc/rc.d/#{new_resource.service_name} restart", default_env: false)
- provider.restart_service()
+ provider.restart_service
end
end
it "should call the restart_command if one has been specified" do
new_resource.restart_command("/etc/init.d/chef restartinafire")
expect(provider).to receive(:shell_out!).with("/etc/init.d/chef restartinafire", default_env: false)
- provider.restart_service()
+ provider.restart_service
end
it "otherwise it should call stop and start" do
expect(provider).to receive(:stop_service)
expect(provider).to receive(:start_service)
- provider.restart_service()
+ provider.restart_service
end
end
end
diff --git a/spec/unit/provider/service/simple_service_spec.rb b/spec/unit/provider/service/simple_service_spec.rb
index 2a0ebea1dc..2546f9cef7 100644
--- a/spec/unit/provider/service/simple_service_spec.rb
+++ b/spec/unit/provider/service/simple_service_spec.rb
@@ -108,7 +108,7 @@ describe Chef::Provider::Service::Simple, "load_current_resource" do
it "should call the start command if one is specified" do
@new_resource.start_command((@new_resource.start_command).to_s)
expect(@provider).to receive(:shell_out!).with((@new_resource.start_command).to_s, default_env: false)
- @provider.start_service()
+ @provider.start_service
end
it "should raise an exception if no start command is specified" do
@@ -122,7 +122,7 @@ describe Chef::Provider::Service::Simple, "load_current_resource" do
it "should call the stop command if one is specified" do
@new_resource.stop_command("/etc/init.d/themadness stop")
expect(@provider).to receive(:shell_out!).with("/etc/init.d/themadness stop", default_env: false)
- @provider.stop_service()
+ @provider.stop_service
end
it "should raise an exception if no stop command is specified" do
@@ -136,7 +136,7 @@ describe Chef::Provider::Service::Simple, "load_current_resource" do
it "should call the restart command if one has been specified" do
@new_resource.restart_command("/etc/init.d/foo restart")
expect(@provider).to receive(:shell_out!).with("/etc/init.d/foo restart", default_env: false)
- @provider.restart_service()
+ @provider.restart_service
end
it "should raise an exception if the resource doesn't support restart, no restart command is provided, and no stop command is provided" do
@@ -149,7 +149,7 @@ describe Chef::Provider::Service::Simple, "load_current_resource" do
expect(@provider).to receive(:stop_service)
expect(@provider).to receive(:sleep).with(1)
expect(@provider).to receive(:start_service)
- @provider.restart_service()
+ @provider.restart_service
end
end
@@ -163,7 +163,7 @@ describe Chef::Provider::Service::Simple, "load_current_resource" do
it "should should run the user specified reload command if one is specified" do
@new_resource.reload_command("kill -9 1")
expect(@provider).to receive(:shell_out!).with("kill -9 1", default_env: false)
- @provider.reload_service()
+ @provider.reload_service
end
end
end
diff --git a/spec/unit/provider/service/upstart_service_spec.rb b/spec/unit/provider/service/upstart_service_spec.rb
index 365201cb38..572246a807 100644
--- a/spec/unit/provider/service/upstart_service_spec.rb
+++ b/spec/unit/provider/service/upstart_service_spec.rb
@@ -242,7 +242,7 @@ describe Chef::Provider::Service::Upstart do
allow(@current_resource).to receive(:enabled).and_return(false)
expect(@file).to receive(:search_file_replace)
expect(@file).to receive(:write_file)
- @provider.enable_service()
+ @provider.enable_service
end
it "should disable the service if it is enabled" do
@@ -251,7 +251,7 @@ describe Chef::Provider::Service::Upstart do
allow(@current_resource).to receive(:enabled).and_return(true)
expect(@file).to receive(:search_file_replace)
expect(@file).to receive(:write_file)
- @provider.disable_service()
+ @provider.disable_service
end
end
@@ -268,19 +268,19 @@ describe Chef::Provider::Service::Upstart do
@provider.upstart_service_running = false
@new_resource.start_command("/sbin/rsyslog startyousillysally")
expect(@provider).to receive(:shell_out!).with("/sbin/rsyslog startyousillysally", default_env: false)
- @provider.start_service()
+ @provider.start_service
end
it "should call '/sbin/start service_name' if no start command is specified" do
@provider.upstart_service_running = false
expect(@provider).to receive(:shell_out!).with("/sbin/start #{@new_resource.service_name}", default_env: false).and_return(shell_out_success)
- @provider.start_service()
+ @provider.start_service
end
it "should not call '/sbin/start service_name' if it is already running" do
@provider.upstart_service_running = true
expect(@provider).not_to receive(:shell_out!)
- @provider.start_service()
+ @provider.start_service
end
it "should pass parameters to the start command if they are provided" do
@@ -289,14 +289,14 @@ describe Chef::Provider::Service::Upstart do
@provider = Chef::Provider::Service::Upstart.new(@new_resource, @run_context)
@provider.current_resource = @current_resource
expect(@provider).to receive(:shell_out!).with("/sbin/start rsyslog OSD_ID=2", default_env: false).and_return(shell_out_success)
- @provider.start_service()
+ @provider.start_service
end
it "should call the restart command if one is specified" do
allow(@current_resource).to receive(:running).and_return(true)
@new_resource.restart_command("/sbin/rsyslog restartyousillysally")
expect(@provider).to receive(:shell_out!).with("/sbin/rsyslog restartyousillysally", default_env: false)
- @provider.restart_service()
+ @provider.restart_service
end
it "should call start/sleep/stop if no restart command is specified" do
@@ -304,47 +304,47 @@ describe Chef::Provider::Service::Upstart do
expect(@provider).to receive(:stop_service)
expect(@provider).to receive(:sleep).with(1)
expect(@provider).to receive(:start_service)
- @provider.restart_service()
+ @provider.restart_service
end
it "should call '/sbin/start service_name' if restart_service is called for a stopped service" do
@provider.upstart_service_running = false
allow(@current_resource).to receive(:running).and_return(false)
expect(@provider).to receive(:shell_out!).with("/sbin/start #{@new_resource.service_name}", default_env: false).and_return(shell_out_success)
- @provider.restart_service()
+ @provider.restart_service
end
it "should call the reload command if one is specified" do
allow(@current_resource).to receive(:running).and_return(true)
@new_resource.reload_command("/sbin/rsyslog reloadyousillysally")
expect(@provider).to receive(:shell_out!).with("/sbin/rsyslog reloadyousillysally", default_env: false)
- @provider.reload_service()
+ @provider.reload_service
end
it "should call '/sbin/reload service_name' if no reload command is specified" do
allow(@current_resource).to receive(:running).and_return(true)
expect(@provider).to receive(:shell_out!).with("/sbin/reload #{@new_resource.service_name}", default_env: false).and_return(shell_out_success)
- @provider.reload_service()
+ @provider.reload_service
end
it "should call the stop command if one is specified" do
@provider.upstart_service_running = true
@new_resource.stop_command("/sbin/rsyslog stopyousillysally")
expect(@provider).to receive(:shell_out!).with("/sbin/rsyslog stopyousillysally", default_env: false)
- @provider.stop_service()
+ @provider.stop_service
end
it "should call '/sbin/stop service_name' if no stop command is specified" do
@provider.upstart_service_running = true
expect(@provider).to receive(:shell_out!).with("/sbin/stop #{@new_resource.service_name}", default_env: false).and_return(shell_out_success)
- @provider.stop_service()
+ @provider.stop_service
end
it "should not call '/sbin/stop service_name' if it is already stopped" do
@provider.upstart_service_running = false
allow(@current_resource).to receive(:running).and_return(false)
expect(@provider).not_to receive(:shell_out!).with("/sbin/stop #{@new_resource.service_name}", default_env: false)
- @provider.stop_service()
+ @provider.stop_service
expect(@upstart_service_running).to be_falsey
end
end
diff --git a/spec/unit/provider/service/windows_spec.rb b/spec/unit/provider/service/windows_spec.rb
index 9145a0caf4..860c0b1d6a 100644
--- a/spec/unit/provider/service/windows_spec.rb
+++ b/spec/unit/provider/service/windows_spec.rb
@@ -41,8 +41,7 @@ describe Chef::Provider::Service::Windows, "load_current_resource", :windows_onl
tag_id: 0,
dependencies: ["Winmgmt"],
service_start_name: "LocalSystem",
- display_name: "Chef Client Service"
- )
+ display_name: "Chef Client Service")
end
# Actual response from Win32::Service.services
@@ -73,8 +72,7 @@ describe Chef::Provider::Service::Windows, "load_current_resource", :windows_onl
command: nil,
num_actions: 0,
actions: nil,
- delayed_start: 1
- )
+ delayed_start: 1)
end
let(:provider) do
@@ -98,7 +96,8 @@ describe Chef::Provider::Service::Windows, "load_current_resource", :windows_onl
allow(Win32::Service).to receive(:start).with(any_args).and_return(Win32::Service)
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
- double("StatusStruct", current_state: "running"))
+ double("StatusStruct", current_state: "running")
+ )
allow(Win32::Service).to receive(:config_info).with(new_resource.service_name)
.and_return(chef_service_config_info)
@@ -155,8 +154,8 @@ describe Chef::Provider::Service::Windows, "load_current_resource", :windows_onl
tag_id: 0,
dependencies: %w{NSI Tdx Afd},
service_start_name: 'NT Authority\\LocalService',
- display_name: "DHCP Client"
- ))
+ display_name: "DHCP Client")
+ )
end
context "startup_type is neither :automatic or :disabled" do
@@ -171,8 +170,8 @@ describe Chef::Provider::Service::Windows, "load_current_resource", :windows_onl
tag_id: 0,
dependencies: %w{NSI Tdx Afd},
service_start_name: 'NT Authority\\LocalService',
- display_name: "DHCP Client"
- ))
+ display_name: "DHCP Client")
+ )
end
it "does not set the current resources enabled" do
@@ -357,14 +356,14 @@ describe Chef::Provider::Service::Windows, "load_current_resource", :windows_onl
# properties that are Strings
%i{binary_path_name load_order_group dependencies run_as_user
display_name description}.each do |attr|
- it "configures service if #{attr} has changed" do
- provider.current_resource.send("#{attr}=", "old value")
- provider.new_resource.send("#{attr}=", "new value")
+ it "configures service if #{attr} has changed" do
+ provider.current_resource.send("#{attr}=", "old value")
+ provider.new_resource.send("#{attr}=", "new value")
- expect(Win32::Service).to receive(:configure)
- provider.action_configure
- end
- end
+ expect(Win32::Service).to receive(:configure)
+ provider.action_configure
+ end
+ end
# properties that are Integers
%i{service_type error_control}.each do |attr|
@@ -473,7 +472,8 @@ describe Chef::Provider::Service::Windows, "load_current_resource", :windows_onl
before(:each) do
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
double("StatusStruct", current_state: "stopped"),
- double("StatusStruct", current_state: "running"))
+ double("StatusStruct", current_state: "running")
+ )
end
context "run_as_user user is specified" do
@@ -555,7 +555,8 @@ describe Chef::Provider::Service::Windows, "load_current_resource", :windows_onl
it "does nothing if the service is running" do
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
- double("StatusStruct", current_state: "running"))
+ double("StatusStruct", current_state: "running")
+ )
provider.load_current_resource
expect(Win32::Service).not_to receive(:start).with(new_resource.service_name)
provider.start_service
@@ -565,7 +566,8 @@ describe Chef::Provider::Service::Windows, "load_current_resource", :windows_onl
context "service is paused" do
before do
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
- double("StatusStruct", current_state: "paused"))
+ double("StatusStruct", current_state: "paused")
+ )
provider.load_current_resource
end
@@ -590,7 +592,8 @@ describe Chef::Provider::Service::Windows, "load_current_resource", :windows_onl
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
double("StatusStruct", current_state: "start pending"),
double("StatusStruct", current_state: "start pending"),
- double("StatusStruct", current_state: "running"))
+ double("StatusStruct", current_state: "running")
+ )
provider.load_current_resource
end
@@ -614,7 +617,8 @@ describe Chef::Provider::Service::Windows, "load_current_resource", :windows_onl
context "service is in stop_pending" do
before do
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
- double("StatusStruct", current_state: "stop pending"))
+ double("StatusStruct", current_state: "stop pending")
+ )
provider.load_current_resource
end
@@ -665,7 +669,8 @@ describe Chef::Provider::Service::Windows, "load_current_resource", :windows_onl
before(:each) do
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
double("StatusStruct", current_state: "running"),
- double("StatusStruct", current_state: "stopped"))
+ double("StatusStruct", current_state: "stopped")
+ )
end
it "calls the stop command if one is specified" do
@@ -690,7 +695,8 @@ describe Chef::Provider::Service::Windows, "load_current_resource", :windows_onl
it "does nothing if the service is stopped" do
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
- double("StatusStruct", current_state: "stopped"))
+ double("StatusStruct", current_state: "stopped")
+ )
provider.load_current_resource
expect(Win32::Service).not_to receive(:stop).with(new_resource.service_name)
provider.stop_service
@@ -699,7 +705,8 @@ describe Chef::Provider::Service::Windows, "load_current_resource", :windows_onl
it "raises an error if the service is paused" do
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
- double("StatusStruct", current_state: "paused"))
+ double("StatusStruct", current_state: "paused")
+ )
provider.load_current_resource
expect(Win32::Service).not_to receive(:start).with(new_resource.service_name)
expect { provider.stop_service }.to raise_error( Chef::Exceptions::Service )
@@ -710,7 +717,8 @@ describe Chef::Provider::Service::Windows, "load_current_resource", :windows_onl
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
double("StatusStruct", current_state: "stop pending"),
double("StatusStruct", current_state: "stop pending"),
- double("StatusStruct", current_state: "stopped"))
+ double("StatusStruct", current_state: "stopped")
+ )
provider.load_current_resource
expect(Win32::Service).not_to receive(:stop).with(new_resource.service_name)
provider.stop_service
@@ -719,7 +727,8 @@ describe Chef::Provider::Service::Windows, "load_current_resource", :windows_onl
it "fails if the service is in start_pending" do
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
- double("StatusStruct", current_state: "start pending"))
+ double("StatusStruct", current_state: "start pending")
+ )
provider.load_current_resource
expect(Win32::Service).not_to receive(:stop).with(new_resource.service_name)
expect { provider.stop_service }.to raise_error( Chef::Exceptions::Service )
@@ -728,7 +737,8 @@ describe Chef::Provider::Service::Windows, "load_current_resource", :windows_onl
it "passes custom timeout to the stop command if provided" do
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
- double("StatusStruct", current_state: "running"))
+ double("StatusStruct", current_state: "running")
+ )
new_resource.timeout 1
expect(Win32::Service).to receive(:stop).with(new_resource.service_name)
Timeout.timeout(2) do
@@ -753,7 +763,8 @@ describe Chef::Provider::Service::Windows, "load_current_resource", :windows_onl
double("StatusStruct", current_state: "running"),
double("StatusStruct", current_state: "stopped"),
double("StatusStruct", current_state: "stopped"),
- double("StatusStruct", current_state: "running"))
+ double("StatusStruct", current_state: "running")
+ )
expect(Win32::Service).to receive(:stop).with(new_resource.service_name)
expect(Win32::Service).to receive(:start).with(new_resource.service_name)
provider.restart_service
@@ -764,7 +775,8 @@ describe Chef::Provider::Service::Windows, "load_current_resource", :windows_onl
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
double("StatusStruct", current_state: "stopped"),
double("StatusStruct", current_state: "stopped"),
- double("StatusStruct", current_state: "running"))
+ double("StatusStruct", current_state: "running")
+ )
expect(Win32::Service).to receive(:start).with(new_resource.service_name)
provider.restart_service
expect(new_resource).to be_updated_by_last_action
@@ -783,7 +795,8 @@ describe Chef::Provider::Service::Windows, "load_current_resource", :windows_onl
describe Chef::Provider::Service::Windows, "enable_service" do
before(:each) do
allow(Win32::Service).to receive(:config_info).with(new_resource.service_name).and_return(
- double("ConfigStruct", start_type: "disabled"))
+ double("ConfigStruct", start_type: "disabled")
+ )
end
it "enables service" do
@@ -803,14 +816,16 @@ describe Chef::Provider::Service::Windows, "load_current_resource", :windows_onl
describe Chef::Provider::Service::Windows, "action_enable" do
it "does nothing if the service is enabled" do
allow(Win32::Service).to receive(:config_info).with(new_resource.service_name).and_return(
- double("ConfigStruct", start_type: "auto start"))
+ double("ConfigStruct", start_type: "auto start")
+ )
expect(provider).not_to receive(:enable_service)
provider.action_enable
end
it "enables the service if it is not set to automatic start" do
allow(Win32::Service).to receive(:config_info).with(new_resource.service_name).and_return(
- double("ConfigStruct", start_type: "disabled"))
+ double("ConfigStruct", start_type: "disabled")
+ )
expect(provider).to receive(:enable_service)
provider.action_enable
end
@@ -819,14 +834,16 @@ describe Chef::Provider::Service::Windows, "load_current_resource", :windows_onl
describe Chef::Provider::Service::Windows, "action_disable" do
it "does nothing if the service is disabled" do
allow(Win32::Service).to receive(:config_info).with(new_resource.service_name).and_return(
- double("ConfigStruct", start_type: "disabled"))
+ double("ConfigStruct", start_type: "disabled")
+ )
expect(provider).not_to receive(:disable_service)
provider.action_disable
end
it "disables the service if it is not set to disabled" do
allow(Win32::Service).to receive(:config_info).with(new_resource.service_name).and_return(
- double("ConfigStruct", start_type: "auto start"))
+ double("ConfigStruct", start_type: "auto start")
+ )
expect(provider).to receive(:disable_service)
provider.action_disable
end
@@ -835,7 +852,8 @@ describe Chef::Provider::Service::Windows, "load_current_resource", :windows_onl
describe Chef::Provider::Service::Windows, "disable_service" do
before(:each) do
allow(Win32::Service).to receive(:config_info).with(new_resource.service_name).and_return(
- double("ConfigStruct", start_type: "auto start"))
+ double("ConfigStruct", start_type: "auto start")
+ )
end
it "disables service" do
diff --git a/spec/unit/provider/subversion_spec.rb b/spec/unit/provider/subversion_spec.rb
index d3c5073b7e..a70b7cd48b 100644
--- a/spec/unit/provider/subversion_spec.rb
+++ b/spec/unit/provider/subversion_spec.rb
@@ -277,7 +277,8 @@ describe Chef::Provider::Subversion do
allow(ChefConfig).to receive(:windows?) { false }
expect(@provider).to receive(:svn_binary).and_return("svn")
expect(@provider.export_command).to eql(
- "svn export --force -q -r12345 http://svn.example.org/trunk/ /my/deploy/dir")
+ "svn export --force -q -r12345 http://svn.example.org/trunk/ /my/deploy/dir"
+ )
end
it "selects an svn binary with an exe extension on windows" do
@@ -285,21 +286,24 @@ describe Chef::Provider::Subversion do
allow(ChefConfig).to receive(:windows?) { true }
expect(@provider).to receive(:svn_binary).and_return("svn.exe")
expect(@provider.export_command).to eql(
- "svn.exe export --force -q -r12345 http://svn.example.org/trunk/ /my/deploy/dir")
+ "svn.exe export --force -q -r12345 http://svn.example.org/trunk/ /my/deploy/dir"
+ )
end
it "uses a custom svn binary as part of the svn command" do
@resource.svn_binary "teapot"
expect(@provider).to receive(:svn_binary).and_return("teapot")
expect(@provider.export_command).to eql(
- "teapot export --force -q -r12345 http://svn.example.org/trunk/ /my/deploy/dir")
+ "teapot export --force -q -r12345 http://svn.example.org/trunk/ /my/deploy/dir"
+ )
end
it "wraps custom svn binary with quotes if it contains whitespace" do
@resource.svn_binary "c:/program files (x86)/subversion/svn.exe"
expect(@provider).to receive(:svn_binary).and_return("c:/program files (x86)/subversion/svn.exe")
expect(@provider.export_command).to eql(
- '"c:/program files (x86)/subversion/svn.exe" export --force -q -r12345 http://svn.example.org/trunk/ /my/deploy/dir')
+ '"c:/program files (x86)/subversion/svn.exe" export --force -q -r12345 http://svn.example.org/trunk/ /my/deploy/dir'
+ )
end
end
diff --git a/spec/unit/provider/systemd_unit_spec.rb b/spec/unit/provider/systemd_unit_spec.rb
index 00f39d0fd9..899d3dc87e 100644
--- a/spec/unit/provider/systemd_unit_spec.rb
+++ b/spec/unit/provider/systemd_unit_spec.rb
@@ -75,8 +75,8 @@ describe Chef::Provider::SystemdUnit do
before(:each) do
allow(Etc).to receive(:getpwnam).and_return(OpenStruct.new(uid: 1000))
allow(Chef::Resource::SystemdUnit).to receive(:new)
- .with(unit_name)
- .and_return(current_resource)
+ .with(unit_name)
+ .and_return(current_resource)
end
describe "define_resource_requirements" do
@@ -113,8 +113,8 @@ describe Chef::Provider::SystemdUnit do
it "should create a current resource with the name of the new resource" do
expect(Chef::Resource::SystemdUnit).to receive(:new)
- .with(unit_name)
- .and_return(current_resource)
+ .with(unit_name)
+ .and_return(current_resource)
provider.load_current_resource
end
@@ -188,26 +188,26 @@ describe Chef::Provider::SystemdUnit do
it "loads the system unit content if the file exists and user is not set" do
allow(File).to receive(:exist?)
- .with(unit_path_system)
- .and_return(true)
+ .with(unit_path_system)
+ .and_return(true)
allow(File).to receive(:read)
- .with(unit_path_system)
- .and_return(unit_content_string)
+ .with(unit_path_system)
+ .and_return(unit_content_string)
expect(File).to receive(:exist?)
- .with(unit_path_system)
+ .with(unit_path_system)
expect(File).to receive(:read)
- .with(unit_path_system)
+ .with(unit_path_system)
provider.load_current_resource
expect(current_resource.content).to eq(unit_content_string)
end
it "does not load the system unit content if the unit file is not present and the user is not set" do
allow(File).to receive(:exist?)
- .with(unit_path_system)
- .and_return(false)
+ .with(unit_path_system)
+ .and_return(false)
expect(File).to_not receive(:read)
- .with(unit_path_system)
+ .with(unit_path_system)
provider.load_current_resource
expect(current_resource.content).to eq(nil)
end
@@ -215,15 +215,15 @@ describe Chef::Provider::SystemdUnit do
it "loads the user unit content if the file exists and user is set" do
new_resource.user("joe")
allow(File).to receive(:exist?)
- .with(unit_path_user)
- .and_return(true)
+ .with(unit_path_user)
+ .and_return(true)
allow(File).to receive(:read)
- .with(unit_path_user)
- .and_return(unit_content_string)
+ .with(unit_path_user)
+ .and_return(unit_content_string)
expect(File).to receive(:exist?)
- .with(unit_path_user)
+ .with(unit_path_user)
expect(File).to receive(:read)
- .with(unit_path_user)
+ .with(unit_path_user)
provider.load_current_resource
expect(current_resource.content).to eq(unit_content_string)
end
@@ -231,10 +231,10 @@ describe Chef::Provider::SystemdUnit do
it "does not load the user unit if the file does not exist and user is set" do
new_resource.user("joe")
allow(File).to receive(:exist?)
- .with(unit_path_user)
- .and_return(false)
+ .with(unit_path_user)
+ .and_return(false)
expect(File).to_not receive(:read)
- .with(unit_path_user)
+ .with(unit_path_user)
provider.load_current_resource
expect(current_resource.content).to eq(nil)
end
@@ -245,27 +245,27 @@ describe Chef::Provider::SystemdUnit do
before(:each) do
provider.current_resource = current_resource
allow(provider).to receive(:which)
- .with("systemctl")
- .and_return(systemctl_path)
+ .with("systemctl")
+ .and_return(systemctl_path)
end
describe "creates/deletes/presets/reverts the unit" do
it "creates the unit file when it does not exist" do
allow(provider).to receive(:manage_unit_file)
- .with(:create)
- .and_return(true)
+ .with(:create)
+ .and_return(true)
allow(provider).to receive(:daemon_reload)
- .and_return(true)
+ .and_return(true)
expect(provider).to receive(:manage_unit_file).with(:create)
provider.action_create
end
it "creates the file when the unit content is different" do
allow(provider).to receive(:manage_unit_file)
- .with(:create)
- .and_return(true)
+ .with(:create)
+ .and_return(true)
allow(provider).to receive(:daemon_reload)
- .and_return(true)
+ .and_return(true)
expect(provider).to receive(:manage_unit_file).with(:create)
provider.action_create
end
@@ -274,7 +274,7 @@ describe Chef::Provider::SystemdUnit do
current_resource.content(unit_content_string)
allow(provider).to receive(:manage_unit_file).with(:create)
allow(provider).to receive(:daemon_reload)
- .and_return(true)
+ .and_return(true)
expect(provider).to_not receive(:manage_unit_file)
provider.action_create
end
@@ -286,20 +286,20 @@ describe Chef::Provider::SystemdUnit do
expect(new_resource.triggers_reload).to eq true
allow(provider).to receive(:shell_out_compacted!)
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--user", "daemon-reload", **user_cmd_opts, default_env: false)
+ .with(systemctl_path, "--user", "daemon-reload", **user_cmd_opts, default_env: false)
provider.action_create
end
it "triggers a daemon-reload when deleting a unit with triggers_reload" do
new_resource.user("joe")
allow(File).to receive(:exist?)
- .with(unit_path_user)
- .and_return(true)
+ .with(unit_path_user)
+ .and_return(true)
allow(provider).to receive(:manage_unit_file).with(:delete)
expect(new_resource.triggers_reload).to eq true
allow(provider).to receive(:shell_out_compacted!)
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--user", "daemon-reload", **user_cmd_opts, default_env: false)
+ .with(systemctl_path, "--user", "daemon-reload", **user_cmd_opts, default_env: false)
provider.action_delete
end
@@ -309,7 +309,7 @@ describe Chef::Provider::SystemdUnit do
allow(provider).to receive(:manage_unit_file).with(:create)
allow(provider).to receive(:shell_out_compacted!)
expect(provider).to_not receive(:shell_out_compacted!)
- .with(systemctl_path, "--user", "daemon-reload", **user_cmd_opts, default_env: false)
+ .with(systemctl_path, "--user", "daemon-reload", **user_cmd_opts, default_env: false)
provider.action_create
end
@@ -317,23 +317,23 @@ describe Chef::Provider::SystemdUnit do
new_resource.user("joe")
new_resource.triggers_reload(false)
allow(File).to receive(:exist?)
- .with(unit_path_user)
- .and_return(true)
+ .with(unit_path_user)
+ .and_return(true)
allow(provider).to receive(:manage_unit_file).with(:delete)
allow(provider).to receive(:shell_out_compacted!)
expect(provider).to_not receive(:shell_out_compacted!)
- .with(systemctl_path, "--user", "daemon-reload", **user_cmd_opts, default_env: false)
+ .with(systemctl_path, "--user", "daemon-reload", **user_cmd_opts, default_env: false)
provider.action_delete
end
it "deletes the file when it exists" do
new_resource.user("joe")
allow(File).to receive(:exist?)
- .with(unit_path_user)
- .and_return(true)
+ .with(unit_path_user)
+ .and_return(true)
allow(provider).to receive(:manage_unit_file)
- .with(:delete)
- .and_return(true)
+ .with(:delete)
+ .and_return(true)
allow(provider).to receive(:daemon_reload)
expect(provider).to receive(:manage_unit_file).with(:delete)
provider.action_delete
@@ -342,8 +342,8 @@ describe Chef::Provider::SystemdUnit do
it "does not delete the file when it is absent" do
new_resource.user("joe")
allow(File).to receive(:exist?)
- .with(unit_path_user)
- .and_return(false)
+ .with(unit_path_user)
+ .and_return(false)
allow(provider).to receive(:manage_unit_file).with(:delete)
expect(provider).to_not receive(:manage_unit_file)
provider.action_delete
@@ -352,16 +352,16 @@ describe Chef::Provider::SystemdUnit do
it "presets the unit" do
new_resource.user("joe")
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--user", "preset", unit_name, **user_cmd_opts)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--user", "preset", unit_name, **user_cmd_opts)
+ .and_return(shell_out_success)
provider.action_preset
end
it "reverts the unit" do
new_resource.user("joe")
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--user", "revert", unit_name, **user_cmd_opts)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--user", "revert", unit_name, **user_cmd_opts)
+ .and_return(shell_out_success)
provider.action_revert
end
end
@@ -372,19 +372,19 @@ describe Chef::Provider::SystemdUnit do
expect(new_resource.triggers_reload).to eq true
allow(provider).to receive(:shell_out_compacted!)
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--system", "daemon-reload", default_env: false)
+ .with(systemctl_path, "--system", "daemon-reload", default_env: false)
provider.action_create
end
it "triggers a daemon-reload when deleting a unit with triggers_reload" do
allow(File).to receive(:exist?)
- .with(unit_path_system)
- .and_return(true)
+ .with(unit_path_system)
+ .and_return(true)
allow(provider).to receive(:manage_unit_file).with(:delete)
expect(new_resource.triggers_reload).to eq true
allow(provider).to receive(:shell_out_compacted!)
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--system", "daemon-reload", default_env: false)
+ .with(systemctl_path, "--system", "daemon-reload", default_env: false)
provider.action_delete
end
@@ -393,27 +393,27 @@ describe Chef::Provider::SystemdUnit do
allow(provider).to receive(:manage_unit_file).with(:create)
allow(provider).to receive(:shell_out_compacted!)
expect(provider).to_not receive(:shell_out_compacted!)
- .with(systemctl_path, "--system", "daemon-reload", default_env: false)
+ .with(systemctl_path, "--system", "daemon-reload", default_env: false)
provider.action_create
end
it "does not trigger a daemon-reload when deleting a unit without triggers_reload" do
new_resource.triggers_reload(false)
allow(File).to receive(:exist?)
- .with(unit_path_system)
- .and_return(true)
+ .with(unit_path_system)
+ .and_return(true)
allow(provider).to receive(:manage_unit_file).with(:delete)
allow(provider).to receive(:shell_out_compacted!)
expect(provider).to_not receive(:shell_out_compacted!)
- .with(systemctl_path, "--system", "daemon-reload", default_env: false)
+ .with(systemctl_path, "--system", "daemon-reload", default_env: false)
provider.action_delete
end
it "deletes the file when it exists" do
allow(File).to receive(:exist?)
- .with(unit_path_system)
- .and_return(true)
+ .with(unit_path_system)
+ .and_return(true)
allow(provider).to receive(:manage_unit_file)
- .with(:delete)
+ .with(:delete)
allow(provider).to receive(:daemon_reload)
expect(provider).to receive(:manage_unit_file).with(:delete)
provider.action_delete
@@ -421,8 +421,8 @@ describe Chef::Provider::SystemdUnit do
it "does not delete the file when it is absent" do
allow(File).to receive(:exist?)
- .with(unit_path_system)
- .and_return(false)
+ .with(unit_path_system)
+ .and_return(false)
allow(provider).to receive(:manage_unit_file).with(:delete)
allow(provider).to receive(:daemon_reload)
expect(provider).to_not receive(:manage_unit_file)
@@ -431,15 +431,15 @@ describe Chef::Provider::SystemdUnit do
it "presets the unit" do
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--system", "preset", unit_name)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--system", "preset", unit_name)
+ .and_return(shell_out_success)
provider.action_preset
end
it "reverts the unit" do
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--system", "revert", unit_name)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--system", "revert", unit_name)
+ .and_return(shell_out_success)
provider.action_revert
end
end
@@ -450,8 +450,8 @@ describe Chef::Provider::SystemdUnit do
it "reenables the unit" do
current_resource.user(user_name)
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--user", "reenable", unit_name, **user_cmd_opts)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--user", "reenable", unit_name, **user_cmd_opts)
+ .and_return(shell_out_success)
provider.action_reenable
end
@@ -459,8 +459,8 @@ describe Chef::Provider::SystemdUnit do
current_resource.user(user_name)
current_resource.enabled(false)
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--user", "enable", unit_name, **user_cmd_opts)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--user", "enable", unit_name, **user_cmd_opts)
+ .and_return(shell_out_success)
provider.action_enable
end
@@ -482,8 +482,8 @@ describe Chef::Provider::SystemdUnit do
current_resource.user(user_name)
current_resource.enabled(true)
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--user", "disable", unit_name, **user_cmd_opts)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--user", "disable", unit_name, **user_cmd_opts)
+ .and_return(shell_out_success)
provider.action_disable
end
@@ -505,16 +505,16 @@ describe Chef::Provider::SystemdUnit do
context "when no user is specified" do
it "reenables the unit" do
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--system", "reenable", unit_name)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--system", "reenable", unit_name)
+ .and_return(shell_out_success)
provider.action_reenable
end
it "enables the unit when it is disabled" do
current_resource.enabled(false)
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--system", "enable", unit_name)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--system", "enable", unit_name)
+ .and_return(shell_out_success)
provider.action_enable
end
@@ -533,8 +533,8 @@ describe Chef::Provider::SystemdUnit do
it "disables the unit when it is enabled" do
current_resource.enabled(true)
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--system", "disable", unit_name)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--system", "disable", unit_name)
+ .and_return(shell_out_success)
provider.action_disable
end
@@ -559,8 +559,8 @@ describe Chef::Provider::SystemdUnit do
current_resource.user(user_name)
current_resource.masked(false)
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--user", "mask", unit_name, **user_cmd_opts)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--user", "mask", unit_name, **user_cmd_opts)
+ .and_return(shell_out_success)
provider.action_mask
end
@@ -575,8 +575,8 @@ describe Chef::Provider::SystemdUnit do
current_resource.user(user_name)
current_resource.masked(true)
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--user", "unmask", unit_name, **user_cmd_opts)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--user", "unmask", unit_name, **user_cmd_opts)
+ .and_return(shell_out_success)
provider.action_unmask
end
@@ -592,8 +592,8 @@ describe Chef::Provider::SystemdUnit do
it "masks the unit when it is unmasked" do
current_resource.masked(false)
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--system", "mask", unit_name)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--system", "mask", unit_name)
+ .and_return(shell_out_success)
provider.action_mask
end
@@ -606,8 +606,8 @@ describe Chef::Provider::SystemdUnit do
it "unmasks the unit when it is masked" do
current_resource.masked(true)
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--system", "unmask", unit_name)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--system", "unmask", unit_name)
+ .and_return(shell_out_success)
provider.action_unmask
end
@@ -625,8 +625,8 @@ describe Chef::Provider::SystemdUnit do
current_resource.user(user_name)
current_resource.active(false)
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--user", "start", unit_name, **user_cmd_opts, default_env: false)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--user", "start", unit_name, **user_cmd_opts, default_env: false)
+ .and_return(shell_out_success)
provider.action_start
end
@@ -641,8 +641,8 @@ describe Chef::Provider::SystemdUnit do
current_resource.user(user_name)
current_resource.active(true)
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--user", "stop", unit_name, **user_cmd_opts, default_env: false)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--user", "stop", unit_name, **user_cmd_opts, default_env: false)
+ .and_return(shell_out_success)
provider.action_stop
end
@@ -658,8 +658,8 @@ describe Chef::Provider::SystemdUnit do
it "starts the unit when it is inactive" do
current_resource.active(false)
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--system", "start", unit_name, default_env: false)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--system", "start", unit_name, default_env: false)
+ .and_return(shell_out_success)
provider.action_start
end
@@ -672,8 +672,8 @@ describe Chef::Provider::SystemdUnit do
it "stops the unit when it is active" do
current_resource.active(true)
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--system", "stop", unit_name, default_env: false)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--system", "stop", unit_name, default_env: false)
+ .and_return(shell_out_success)
provider.action_stop
end
@@ -690,8 +690,8 @@ describe Chef::Provider::SystemdUnit do
it "restarts the unit" do
current_resource.user(user_name)
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--user", "restart", unit_name, **user_cmd_opts, default_env: false)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--user", "restart", unit_name, **user_cmd_opts, default_env: false)
+ .and_return(shell_out_success)
provider.action_restart
end
@@ -699,8 +699,8 @@ describe Chef::Provider::SystemdUnit do
current_resource.user(user_name)
current_resource.active(true)
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--user", "reload", unit_name, **user_cmd_opts, default_env: false)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--user", "reload", unit_name, **user_cmd_opts, default_env: false)
+ .and_return(shell_out_success)
provider.action_reload
end
@@ -715,16 +715,16 @@ describe Chef::Provider::SystemdUnit do
context "when no user is specified" do
it "restarts the unit" do
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--system", "restart", unit_name, default_env: false)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--system", "restart", unit_name, default_env: false)
+ .and_return(shell_out_success)
provider.action_restart
end
it "reloads the unit if active" do
current_resource.active(true)
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--system", "reload", unit_name, default_env: false)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--system", "reload", unit_name, default_env: false)
+ .and_return(shell_out_success)
provider.action_reload
end
@@ -741,8 +741,8 @@ describe Chef::Provider::SystemdUnit do
it "try-restarts the unit" do
current_resource.user(user_name)
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--user", "try-restart", unit_name, **user_cmd_opts, default_env: false)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--user", "try-restart", unit_name, **user_cmd_opts, default_env: false)
+ .and_return(shell_out_success)
provider.action_try_restart
end
end
@@ -750,8 +750,8 @@ describe Chef::Provider::SystemdUnit do
context "when no user is specified" do
it "try-restarts the unit" do
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--system", "try-restart", unit_name, default_env: false)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--system", "try-restart", unit_name, default_env: false)
+ .and_return(shell_out_success)
provider.action_try_restart
end
end
@@ -762,8 +762,8 @@ describe Chef::Provider::SystemdUnit do
it "reload-or-restarts the unit" do
current_resource.user(user_name)
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--user", "reload-or-restart", unit_name, **user_cmd_opts, default_env: false)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--user", "reload-or-restart", unit_name, **user_cmd_opts, default_env: false)
+ .and_return(shell_out_success)
provider.action_reload_or_restart
end
end
@@ -771,8 +771,8 @@ describe Chef::Provider::SystemdUnit do
context "when no user is specified" do
it "reload-or-restarts the unit" do
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--system", "reload-or-restart", unit_name, default_env: false)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--system", "reload-or-restart", unit_name, default_env: false)
+ .and_return(shell_out_success)
provider.action_reload_or_restart
end
end
@@ -783,8 +783,8 @@ describe Chef::Provider::SystemdUnit do
it "reload-or-try-restarts the unit" do
current_resource.user(user_name)
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--user", "reload-or-try-restart", unit_name, **user_cmd_opts, default_env: false)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--user", "reload-or-try-restart", unit_name, **user_cmd_opts, default_env: false)
+ .and_return(shell_out_success)
provider.action_reload_or_try_restart
end
end
@@ -792,8 +792,8 @@ describe Chef::Provider::SystemdUnit do
context "when no user is specified" do
it "reload-or-try-restarts the unit" do
expect(provider).to receive(:shell_out_compacted!)
- .with(systemctl_path, "--system", "reload-or-try-restart", unit_name, default_env: false)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--system", "reload-or-try-restart", unit_name, default_env: false)
+ .and_return(shell_out_success)
provider.action_reload_or_try_restart
end
end
@@ -809,16 +809,16 @@ describe Chef::Provider::SystemdUnit do
it "returns true when unit is active" do
current_resource.user(user_name)
expect(provider).to receive(:shell_out_compacted)
- .with(systemctl_path, "--user", "is-active", unit_name, user_cmd_opts)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--user", "is-active", unit_name, user_cmd_opts)
+ .and_return(shell_out_success)
expect(provider.active?).to be true
end
it "returns false when unit is inactive" do
current_resource.user(user_name)
expect(provider).to receive(:shell_out_compacted)
- .with(systemctl_path, "--user", "is-active", unit_name, user_cmd_opts)
- .and_return(shell_out_failure)
+ .with(systemctl_path, "--user", "is-active", unit_name, user_cmd_opts)
+ .and_return(shell_out_failure)
expect(provider.active?).to be false
end
end
@@ -826,15 +826,15 @@ describe Chef::Provider::SystemdUnit do
context "when no user is specified" do
it "returns true when unit is active" do
expect(provider).to receive(:shell_out_compacted)
- .with(systemctl_path, "--system", "is-active", unit_name)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--system", "is-active", unit_name)
+ .and_return(shell_out_success)
expect(provider.active?).to be true
end
it "returns false when unit is not active" do
expect(provider).to receive(:shell_out_compacted)
- .with(systemctl_path, "--system", "is-active", unit_name)
- .and_return(shell_out_failure)
+ .with(systemctl_path, "--system", "is-active", unit_name)
+ .and_return(shell_out_failure)
expect(provider.active?).to be false
end
end
@@ -850,16 +850,16 @@ describe Chef::Provider::SystemdUnit do
it "returns true when unit is enabled" do
current_resource.user(user_name)
expect(provider).to receive(:shell_out_compacted)
- .with(systemctl_path, "--user", "is-enabled", unit_name, user_cmd_opts)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--user", "is-enabled", unit_name, user_cmd_opts)
+ .and_return(shell_out_success)
expect(provider.enabled?).to be true
end
it "returns false when unit is not enabled" do
current_resource.user(user_name)
expect(provider).to receive(:shell_out_compacted)
- .with(systemctl_path, "--user", "is-enabled", unit_name, user_cmd_opts)
- .and_return(shell_out_failure)
+ .with(systemctl_path, "--user", "is-enabled", unit_name, user_cmd_opts)
+ .and_return(shell_out_failure)
expect(provider.enabled?).to be false
end
end
@@ -867,15 +867,15 @@ describe Chef::Provider::SystemdUnit do
context "when no user is specified" do
it "returns true when unit is enabled" do
expect(provider).to receive(:shell_out_compacted)
- .with(systemctl_path, "--system", "is-enabled", unit_name)
- .and_return(shell_out_success)
+ .with(systemctl_path, "--system", "is-enabled", unit_name)
+ .and_return(shell_out_success)
expect(provider.enabled?).to be true
end
it "returns false when unit is not enabled" do
expect(provider).to receive(:shell_out_compacted)
- .with(systemctl_path, "--system", "is-enabled", unit_name)
- .and_return(shell_out_failure)
+ .with(systemctl_path, "--system", "is-enabled", unit_name)
+ .and_return(shell_out_failure)
expect(provider.enabled?).to be false
end
end
@@ -891,16 +891,16 @@ describe Chef::Provider::SystemdUnit do
it "returns true when the unit is masked" do
current_resource.user(user_name)
expect(provider).to receive(:shell_out_compacted)
- .with(systemctl_path, "--user", "status", unit_name, user_cmd_opts)
- .and_return(shell_out_masked)
+ .with(systemctl_path, "--user", "status", unit_name, user_cmd_opts)
+ .and_return(shell_out_masked)
expect(provider.masked?).to be true
end
it "returns false when the unit is not masked" do
current_resource.user(user_name)
expect(provider).to receive(:shell_out_compacted)
- .with(systemctl_path, "--user", "status", unit_name, user_cmd_opts)
- .and_return(shell_out_static)
+ .with(systemctl_path, "--user", "status", unit_name, user_cmd_opts)
+ .and_return(shell_out_static)
expect(provider.masked?).to be false
end
end
@@ -908,15 +908,15 @@ describe Chef::Provider::SystemdUnit do
context "when no user is specified" do
it "returns true when the unit is masked" do
expect(provider).to receive(:shell_out_compacted)
- .with(systemctl_path, "--system", "status", unit_name)
- .and_return(shell_out_masked)
+ .with(systemctl_path, "--system", "status", unit_name)
+ .and_return(shell_out_masked)
expect(provider.masked?).to be true
end
it "returns false when the unit is not masked" do
expect(provider).to receive(:shell_out_compacted)
- .with(systemctl_path, "--system", "status", unit_name)
- .and_return(shell_out_static)
+ .with(systemctl_path, "--system", "status", unit_name)
+ .and_return(shell_out_static)
expect(provider.masked?).to be false
end
end
@@ -932,16 +932,16 @@ describe Chef::Provider::SystemdUnit do
it "returns true when the unit is static" do
current_resource.user(user_name)
expect(provider).to receive(:shell_out_compacted)
- .with(systemctl_path, "--user", "is-enabled", unit_name, user_cmd_opts)
- .and_return(shell_out_static)
+ .with(systemctl_path, "--user", "is-enabled", unit_name, user_cmd_opts)
+ .and_return(shell_out_static)
expect(provider.static?).to be true
end
it "returns false when the unit is not static" do
current_resource.user(user_name)
expect(provider).to receive(:shell_out_compacted)
- .with(systemctl_path, "--user", "is-enabled", unit_name, user_cmd_opts)
- .and_return(shell_out_masked)
+ .with(systemctl_path, "--user", "is-enabled", unit_name, user_cmd_opts)
+ .and_return(shell_out_masked)
expect(provider.static?).to be false
end
end
@@ -949,15 +949,15 @@ describe Chef::Provider::SystemdUnit do
context "when no user is specified" do
it "returns true when the unit is static" do
expect(provider).to receive(:shell_out_compacted)
- .with(systemctl_path, "--system", "is-enabled", unit_name)
- .and_return(shell_out_static)
+ .with(systemctl_path, "--system", "is-enabled", unit_name)
+ .and_return(shell_out_static)
expect(provider.static?).to be true
end
it "returns false when the unit is not static" do
expect(provider).to receive(:shell_out_compacted)
- .with(systemctl_path, "--system", "is-enabled", unit_name)
- .and_return(shell_out_masked)
+ .with(systemctl_path, "--system", "is-enabled", unit_name)
+ .and_return(shell_out_masked)
expect(provider.static?).to be false
end
end
diff --git a/spec/unit/provider/windows_task_spec.rb b/spec/unit/provider/windows_task_spec.rb
index 8cce861f2a..74e1dc1de7 100644
--- a/spec/unit/provider/windows_task_spec.rb
+++ b/spec/unit/provider/windows_task_spec.rb
@@ -20,7 +20,7 @@ require "spec_helper"
describe Chef::Provider::WindowsTask, :windows_only do
let(:new_resource) { Chef::Resource::WindowsTask.new("sample_task") }
- let(:current_resource) { Chef::Resource::WindowsTask.new() }
+ let(:current_resource) { Chef::Resource::WindowsTask.new }
let(:provider) do
node = Chef::Node.new
diff --git a/spec/unit/provider_resolver_spec.rb b/spec/unit/provider_resolver_spec.rb
index 9014b873de..94e0d6074b 100644
--- a/spec/unit/provider_resolver_spec.rb
+++ b/spec/unit/provider_resolver_spec.rb
@@ -869,7 +869,7 @@ describe Chef::ProviderResolver do
def self.create_provider_tests(providers, test, expected, filter)
expected = expected.merge(providers.select { |key, value| key.is_a?(Symbol) })
providers.each do |key, value|
- if !key.is_a?(Symbol)
+ unless key.is_a?(Symbol)
next_test = test.merge({ filter => key })
next_filter =
case filter
@@ -888,7 +888,7 @@ describe Chef::ProviderResolver do
end
end
# If there is no filter, we're as deep as we need to go
- if !filter
+ unless filter
on_platform test.delete(:platform), test do
expect_providers(expected)
end
diff --git a/spec/unit/provider_spec.rb b/spec/unit/provider_spec.rb
index 496871614a..d7db8e8c1c 100644
--- a/spec/unit/provider_spec.rb
+++ b/spec/unit/provider_spec.rb
@@ -24,8 +24,7 @@ class NoWhyrunDemonstrator < Chef::Provider
false
end
- def load_current_resource
- end
+ def load_current_resource; end
def action_foo
@system_state_altered = true
@@ -39,8 +38,7 @@ class ConvergeActionDemonstrator < Chef::Provider
true
end
- def load_current_resource
- end
+ def load_current_resource; end
def action_foo
converge_by("running a state changing action") do
diff --git a/spec/unit/recipe_spec.rb b/spec/unit/recipe_spec.rb
index 1bc84745ad..f2ec175243 100644
--- a/spec/unit/recipe_spec.rb
+++ b/spec/unit/recipe_spec.rb
@@ -94,7 +94,7 @@ describe Chef::Recipe do
end
end
- expect(run_context.resource_collection.map { |r| r.name }).to eql(%w{monkey dog cat})
+ expect(run_context.resource_collection.map(&:name)).to eql(%w{monkey dog cat})
end
it "should return the new resource after creating it" do
@@ -115,7 +115,7 @@ describe Chef::Recipe do
node.automatic[:platform_version] = "123"
res = recipe.laughter "timmy"
expect(res.name).to eql("timmy")
- res.kind_of?(ShaunTheSheep)
+ res.is_a?(ShaunTheSheep)
end
it "locate a resource for all platforms" do
@@ -124,7 +124,7 @@ describe Chef::Recipe do
YourMom.provides :love_and_caring
res = recipe.love_and_caring "mommy"
expect(res.name).to eql("mommy")
- res.kind_of?(YourMom)
+ res.is_a?(YourMom)
end
describe "when there is more than one resource that resolves on a node" do
diff --git a/spec/unit/resource/batch_spec.rb b/spec/unit/resource/batch_spec.rb
index c161428a13..dd3082100e 100644
--- a/spec/unit/resource/batch_spec.rb
+++ b/spec/unit/resource/batch_spec.rb
@@ -22,7 +22,7 @@ describe Chef::Resource::Batch do
let(:node) { Chef::Node.new }
before(:each) do
- node.default["kernel"] = Hash.new
+ node.default["kernel"] = {}
node.default["kernel"][:machine] = :x86_64.to_s
node.automatic[:os] = "windows"
diff --git a/spec/unit/resource/cab_package_spec.rb b/spec/unit/resource/cab_package_spec.rb
index 7e80abf41a..e534748a0c 100644
--- a/spec/unit/resource/cab_package_spec.rb
+++ b/spec/unit/resource/cab_package_spec.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");
diff --git a/spec/unit/resource/chef_gem_spec.rb b/spec/unit/resource/chef_gem_spec.rb
index a8429d0812..b512b8b17f 100644
--- a/spec/unit/resource/chef_gem_spec.rb
+++ b/spec/unit/resource/chef_gem_spec.rb
@@ -53,7 +53,7 @@ describe Chef::Resource::ChefGem, "gem_binary" do
end
it "sets the gem_binary based on computing it from RbConfig" do
- expect(resource.gem_binary).to eql("#{RbConfig::CONFIG['bindir']}/gem")
+ expect(resource.gem_binary).to eql("#{RbConfig::CONFIG["bindir"]}/gem")
end
it "sets compile_time to false by default" do
diff --git a/spec/unit/resource/directory_spec.rb b/spec/unit/resource/directory_spec.rb
index 3dd68211db..0c0c0d8287 100644
--- a/spec/unit/resource/directory_spec.rb
+++ b/spec/unit/resource/directory_spec.rb
@@ -38,7 +38,7 @@ describe Chef::Resource::Directory do
it "accepts a string as the path" do
expect { resource.path "/tmp" }.not_to raise_error
expect(resource.path).to eql("/tmp")
- expect { resource.path Hash.new }.to raise_error(ArgumentError)
+ expect { resource.path({}) }.to raise_error(ArgumentError)
end
it "allows you to have specify whether the action is recursive with true/false" do
diff --git a/spec/unit/resource/dnf_package_spec.rb b/spec/unit/resource/dnf_package_spec.rb
index f4262a0396..70d949c340 100644
--- a/spec/unit/resource/dnf_package_spec.rb
+++ b/spec/unit/resource/dnf_package_spec.rb
@@ -64,7 +64,7 @@ describe Chef::Resource::DnfPackage, "flush_cache" do
end
it "allows you to set the flush timing with an array" do
- flush_array = [ :before, :after ]
+ flush_array = %i{before after}
flush_hash = { before: true, after: true }
resource.flush_cache(flush_array)
expect(resource.flush_cache).to eq(flush_hash)
diff --git a/spec/unit/resource/dsc_resource_spec.rb b/spec/unit/resource/dsc_resource_spec.rb
index 04e1305163..e0beb309ab 100644
--- a/spec/unit/resource/dsc_resource_spec.rb
+++ b/spec/unit/resource/dsc_resource_spec.rb
@@ -41,7 +41,7 @@ describe Chef::Resource::DscResource do
end
it "has an ed_actions property with only the `:run` and `:nothing` properties" do
- expect(dsc_test_resource.allowed_actions.to_set).to eq([:run, :nothing].to_set)
+ expect(dsc_test_resource.allowed_actions.to_set).to eq(%i{run nothing}.to_set)
end
it "allows the resource property to be set" do
diff --git a/spec/unit/resource/file/verification_spec.rb b/spec/unit/resource/file/verification_spec.rb
index f0ec999019..57c58249eb 100644
--- a/spec/unit/resource/file/verification_spec.rb
+++ b/spec/unit/resource/file/verification_spec.rb
@@ -128,8 +128,7 @@ describe Chef::Resource::File::Verification do
before(:each) do
class Chef::Resource::File::Verification::Turtle < Chef::Resource::File::Verification
provides :cats
- def verify(path, opts)
- end
+ def verify(path, opts); end
end
allow(Chef::Resource::File::Verification::Turtle).to receive(:new).and_return(registered_verification)
end
diff --git a/spec/unit/resource/file_spec.rb b/spec/unit/resource/file_spec.rb
index 54dc8ab92b..b49fc4564b 100644
--- a/spec/unit/resource/file_spec.rb
+++ b/spec/unit/resource/file_spec.rb
@@ -85,7 +85,7 @@ describe Chef::Resource::File do
it "accepts a string as the path" do
expect { resource.path "/tmp" }.not_to raise_error
expect(resource.path).to eql("/tmp")
- expect { resource.path Hash.new }.to raise_error(ArgumentError)
+ expect { resource.path({}) }.to raise_error(ArgumentError)
end
describe "when it has a path, owner, group, mode, and checksum" do
diff --git a/spec/unit/resource/group_spec.rb b/spec/unit/resource/group_spec.rb
index 6d9df79299..ae7103b9b5 100644
--- a/spec/unit/resource/group_spec.rb
+++ b/spec/unit/resource/group_spec.rb
@@ -96,7 +96,7 @@ end
describe Chef::Resource::Group, "members" do
let(:resource) { Chef::Resource::Group.new("fakey_fakerton") }
- [ :users, :members].each do |method|
+ %i{users members}.each do |method|
it "(#{method}) allows a String and coerces it to an Array" do
resource.send(method, "some_user")
expect(resource.send(method)).to eql(["some_user"])
diff --git a/spec/unit/resource/link_spec.rb b/spec/unit/resource/link_spec.rb
index 05a39835d8..ae32e4aa30 100644
--- a/spec/unit/resource/link_spec.rb
+++ b/spec/unit/resource/link_spec.rb
@@ -63,7 +63,7 @@ describe Chef::Resource::Link do
end
it "does not accept a Hash for the link source via 'to'" do
- expect { resource.to Hash.new }.to raise_error(ArgumentError)
+ expect { resource.to({}) }.to raise_error(ArgumentError)
end
it "allows you to set a link source via 'to'" do
diff --git a/spec/unit/resource/locale_spec.rb b/spec/unit/resource/locale_spec.rb
index 544f6342c5..9d0061eb5b 100644
--- a/spec/unit/resource/locale_spec.rb
+++ b/spec/unit/resource/locale_spec.rb
@@ -91,7 +91,7 @@ describe Chef::Resource::Locale do
end
context "without lang" do
it "returns an empty array" do
- resource.lang()
+ resource.lang
resource.lc_env({ "LC_TIME" => "en_AG.utf8", "LC_MESSAGES" => "en_AG.utf8" })
expect(provider.unavailable_locales).to eq([])
end
@@ -99,14 +99,14 @@ describe Chef::Resource::Locale do
context "without lc_env" do
it "returns an empty array" do
resource.lang("en_US")
- resource.lc_env()
+ resource.lc_env
expect(provider.unavailable_locales).to eq([])
end
end
context "without both" do
it "returns an empty array" do
- resource.lang()
- resource.lc_env()
+ resource.lang
+ resource.lc_env
expect(provider.unavailable_locales).to eq([])
end
end
@@ -122,7 +122,7 @@ describe Chef::Resource::Locale do
end
context "without lang" do
it "returns list" do
- resource.lang()
+ resource.lang
resource.lc_env({ "LC_TIME" => "en_AG.utf8", "LC_MESSAGES" => "en_US.utf8" })
expect(provider.unavailable_locales).to eq(["en_US.utf8"])
end
@@ -130,14 +130,14 @@ describe Chef::Resource::Locale do
context "without lc_env" do
it "returns list" do
resource.lang("de_DE")
- resource.lc_env()
+ resource.lc_env
expect(provider.unavailable_locales).to eq(["de_DE"])
end
end
context "without both" do
it "returns an empty array" do
- resource.lang()
- resource.lc_env()
+ resource.lang
+ resource.lc_env
expect(provider.unavailable_locales).to eq([])
end
end
@@ -166,7 +166,7 @@ describe Chef::Resource::Locale do
end
context "without lang" do
it "returns a valid string" do
- resource.lang()
+ resource.lang
resource.lc_env({ "LC_TIME" => "en_AG.utf8", "LC_MESSAGES" => "en_AG.utf8" })
expect(provider.new_content).to eq("LC_MESSAGES=en_AG.utf8\nLC_TIME=en_AG.utf8\n")
end
@@ -174,14 +174,14 @@ describe Chef::Resource::Locale do
context "without lc_env" do
it "returns a valid string" do
resource.lang("en_US")
- resource.lc_env()
+ resource.lc_env
expect(provider.new_content).to eq("LANG=en_US\n")
end
end
context "without both" do
it "returns string with only new-line character" do
- resource.lang()
- resource.lc_env()
+ resource.lang
+ resource.lc_env
expect(provider.new_content).to eq("\n")
end
end
diff --git a/spec/unit/resource/osx_profile_spec.rb b/spec/unit/resource/osx_profile_spec.rb
index 41a6071893..5653044358 100644
--- a/spec/unit/resource/osx_profile_spec.rb
+++ b/spec/unit/resource/osx_profile_spec.rb
@@ -21,7 +21,8 @@ require "spec_helper"
describe Chef::Resource::OsxProfile do
let(:resource) do
Chef::Resource::OsxProfile.new(
- "fakey_fakerton")
+ "fakey_fakerton"
+ )
end
it "has a resource name of profile" do
diff --git a/spec/unit/resource/powershell_script_spec.rb b/spec/unit/resource/powershell_script_spec.rb
index dc9b62b16c..5566f32725 100644
--- a/spec/unit/resource/powershell_script_spec.rb
+++ b/spec/unit/resource/powershell_script_spec.rb
@@ -23,7 +23,7 @@ describe Chef::Resource::PowershellScript do
before(:each) do
node = Chef::Node.new
- node.default["kernel"] = Hash.new
+ node.default["kernel"] = {}
node.default["kernel"][:machine] = :x86_64.to_s
node.automatic[:os] = "windows"
@@ -61,7 +61,7 @@ describe Chef::Resource::PowershellScript do
it "inherits exactly the :cwd, :environment, :group, :path, :user, :umask, :architecture, :elevated properties from a parent resource class" do
inherited_difference = Chef::Resource::PowershellScript.guard_inherited_attributes -
- [:cwd, :environment, :group, :path, :user, :umask, :architecture, :elevated ]
+ %i{cwd environment group path user umask architecture elevated}
expect(inherited_difference).to eq([])
end
@@ -87,7 +87,8 @@ describe Chef::Resource::PowershellScript do
it "enables convert_boolean_return by default for guards in the context of powershell_script when no guard params are specified" do
allow_any_instance_of(Chef::GuardInterpreter::ResourceGuardInterpreter).to receive(:evaluate_action).and_return(true)
allow_any_instance_of(Chef::GuardInterpreter::ResourceGuardInterpreter).to receive(:block_from_attributes).with(
- { convert_boolean_return: true, code: "$true" }).and_return(Proc.new {})
+ { convert_boolean_return: true, code: "$true" }
+ ).and_return(Proc.new {})
resource.only_if("$true")
end
@@ -98,21 +99,24 @@ describe Chef::Resource::PowershellScript do
file_resource.guard_interpreter :powershell_script
allow_any_instance_of(Chef::GuardInterpreter::ResourceGuardInterpreter).to receive(:block_from_attributes).with(
- { convert_boolean_return: true, code: "$true" }).and_return(Proc.new {})
+ { convert_boolean_return: true, code: "$true" }
+ ).and_return(Proc.new {})
resource.only_if("$true")
end
it "enables convert_boolean_return by default for guards in the context of powershell_script when guard params are specified" do
guard_parameters = { cwd: "/etc/chef", architecture: :x86_64 }
allow_any_instance_of(Chef::GuardInterpreter::ResourceGuardInterpreter).to receive(:block_from_attributes).with(
- { convert_boolean_return: true, code: "$true" }.merge(guard_parameters)).and_return(Proc.new {})
+ { convert_boolean_return: true, code: "$true" }.merge(guard_parameters)
+ ).and_return(Proc.new {})
resource.only_if("$true", guard_parameters)
end
it "passes convert_boolean_return as true if it was specified as true in a guard parameter" do
guard_parameters = { cwd: "/etc/chef", convert_boolean_return: true, architecture: :x86_64 }
allow_any_instance_of(Chef::GuardInterpreter::ResourceGuardInterpreter).to receive(:block_from_attributes).with(
- { convert_boolean_return: true, code: "$true" }.merge(guard_parameters)).and_return(Proc.new {})
+ { convert_boolean_return: true, code: "$true" }.merge(guard_parameters)
+ ).and_return(Proc.new {})
resource.only_if("$true", guard_parameters)
end
@@ -120,7 +124,8 @@ describe Chef::Resource::PowershellScript do
other_guard_parameters = { cwd: "/etc/chef", architecture: :x86_64 }
parameters_with_boolean_disabled = other_guard_parameters.merge({ convert_boolean_return: false, code: "$true" })
allow_any_instance_of(Chef::GuardInterpreter::ResourceGuardInterpreter).to receive(:block_from_attributes).with(
- parameters_with_boolean_disabled).and_return(Proc.new {})
+ parameters_with_boolean_disabled
+ ).and_return(Proc.new {})
resource.only_if("$true", parameters_with_boolean_disabled)
end
end
diff --git a/spec/unit/resource/registry_key_spec.rb b/spec/unit/resource/registry_key_spec.rb
index 47d624a758..c674e3eddd 100644
--- a/spec/unit/resource/registry_key_spec.rb
+++ b/spec/unit/resource/registry_key_spec.rb
@@ -152,7 +152,7 @@ describe Chef::Resource::RegistryKey, "recursive" do
end
it "does not allow an array" do
- expect { resource.recursive([:nose, :chin]) }.to raise_error(ArgumentError)
+ expect { resource.recursive(%i{nose chin}) }.to raise_error(ArgumentError)
end
it "does not allow a string" do
@@ -167,7 +167,7 @@ end
describe Chef::Resource::RegistryKey, "architecture" do
let(:resource) { Chef::Resource::RegistryKey.new('HKCU\Software\Raxicoricofallapatorius') }
- [ :i386, :x86_64, :machine ].each do |arch|
+ %i{i386 x86_64 machine}.each do |arch|
it "allows #{arch} as a symbol" do
resource.architecture(arch)
expect(resource.architecture).to eql(arch)
@@ -183,7 +183,7 @@ describe Chef::Resource::RegistryKey, "architecture" do
end
it "does not allow an array" do
- expect { resource.architecture([:nose, :chin]) }.to raise_error(ArgumentError)
+ expect { resource.architecture(%i{nose chin}) }.to raise_error(ArgumentError)
end
it "does not allow a string" do
diff --git a/spec/unit/resource/service_spec.rb b/spec/unit/resource/service_spec.rb
index 7c2b46a0dc..be88d82f3b 100644
--- a/spec/unit/resource/service_spec.rb
+++ b/spec/unit/resource/service_spec.rb
@@ -167,7 +167,7 @@ describe Chef::Resource::Service do
end
it "allows you to set what features this resource supports as an array" do
- support_array = [ :status, :restart ]
+ support_array = %i{status restart}
support_hash = { status: true, restart: true }
resource.supports(support_array)
expect(resource.supports).to eq(support_hash)
diff --git a/spec/unit/resource/template_spec.rb b/spec/unit/resource/template_spec.rb
index 9ca1f7617f..2f8e234c85 100644
--- a/spec/unit/resource/template_spec.rb
+++ b/spec/unit/resource/template_spec.rb
@@ -147,7 +147,7 @@ describe Chef::Resource::Template do
end
it "compiles helper methods with arguments into a module" do
- resource.helper(:shout) { |quiet| quiet.upcase }
+ resource.helper(:shout, &:upcase)
modules = resource.helper_modules
o = Object.new
modules.each { |m| o.extend(m) }
@@ -186,7 +186,7 @@ describe Chef::Resource::Template do
end
it "raises an error when no block or module name is given for helpers definition" do
- expect { resource.helpers() }.to raise_error(Chef::Exceptions::ValidationFailed)
+ expect { resource.helpers }.to raise_error(Chef::Exceptions::ValidationFailed)
end
it "raises an error when a non-module is given for helpers definition" do
diff --git a/spec/unit/resource/windows_env_spec.rb b/spec/unit/resource/windows_env_spec.rb
index 06b5af630a..3ba5b18881 100644
--- a/spec/unit/resource/windows_env_spec.rb
+++ b/spec/unit/resource/windows_env_spec.rb
@@ -47,7 +47,7 @@ describe Chef::Resource::WindowsEnv do
end
it "does not accept a Hash for the env value via 'to'" do
- expect { resource.value Hash.new }.to raise_error(ArgumentError)
+ expect { resource.value({}) }.to raise_error(ArgumentError)
end
it "allows you to set an env value via 'to'" do
diff --git a/spec/unit/resource/windows_service_spec.rb b/spec/unit/resource/windows_service_spec.rb
index b44a86d04a..a416ca0a05 100644
--- a/spec/unit/resource/windows_service_spec.rb
+++ b/spec/unit/resource/windows_service_spec.rb
@@ -48,7 +48,7 @@ describe Chef::Resource::WindowsService, "initialize" do
expect { resource.action :unmask }.not_to raise_error
end
- [:automatic, :manual, :disabled].each do |type|
+ %i{automatic manual disabled}.each do |type|
it "supports setting startup_type property to #{type.inspect}" do
resource.startup_type type
expect(resource.startup_type).to eql(type)
@@ -69,7 +69,7 @@ describe Chef::Resource::WindowsService, "initialize" do
end
end
- [:automatic, :manual, :disabled].each do |type|
+ %i{automatic manual disabled}.each do |type|
it "supports setting startup_type property to #{type.inspect}" do
resource.startup_type type
expect(resource.startup_type).to eql(type)
@@ -84,11 +84,11 @@ describe Chef::Resource::WindowsService, "initialize" do
# Properties that are Strings
%i{description service_name binary_path_name load_order_group dependencies
run_as_user run_as_password display_name}.each do |prop|
- it "support setting #{prop} property with a String" do
- resource.send("#{prop}=", "some value")
- expect(resource.send(prop)).to eq("some value")
- end
- end
+ it "support setting #{prop} property with a String" do
+ resource.send("#{prop}=", "some value")
+ expect(resource.send(prop)).to eq("some value")
+ end
+ end
# Properties that are Integers
%i{desired_access error_control service_type}.each do |prop|
diff --git a/spec/unit/resource/windows_task_spec.rb b/spec/unit/resource/windows_task_spec.rb
index b152d879f6..d08849d4be 100644
--- a/spec/unit/resource/windows_task_spec.rb
+++ b/spec/unit/resource/windows_task_spec.rb
@@ -356,7 +356,7 @@ describe Chef::Resource::WindowsTask, :windows_only do
context "#validate_idle_time" do
it "raises error if frequency is not :on_idle" do
- [:minute, :hourly, :daily, :weekly, :monthly, :once, :on_logon, :onstart, :none].each do |frequency|
+ %i{minute hourly daily weekly monthly once on_logon onstart none}.each do |frequency|
expect { resource.send(:validate_idle_time, 5, frequency) }.to raise_error(ArgumentError, "idle_time property is only valid for tasks that run on_idle")
end
end
@@ -374,7 +374,7 @@ describe Chef::Resource::WindowsTask, :windows_only do
end
it "does not raises error if idle_time is not set for other frequencies" do
- [:minute, :hourly, :daily, :weekly, :monthly, :once, :on_logon, :onstart, :none].each do |frequency|
+ %i{minute hourly daily weekly monthly once on_logon onstart none}.each do |frequency|
expect { resource.send(:validate_idle_time, nil, frequency) }.not_to raise_error
end
end
diff --git a/spec/unit/resource/windows_uac_spec.rb b/spec/unit/resource/windows_uac_spec.rb
index 05c1cad4a0..6f9137c341 100644
--- a/spec/unit/resource/windows_uac_spec.rb
+++ b/spec/unit/resource/windows_uac_spec.rb
@@ -24,7 +24,7 @@ describe Chef::Resource::WindowsUac do
expect(resource.resource_name).to eql(:windows_uac)
end
- [:no_prompt, :secure_prompt_for_creds, :secure_prompt_for_consent, :prompt_for_creds, :prompt_for_consent, :prompt_for_consent_non_windows_binaries].each do |val|
+ %i{no_prompt secure_prompt_for_creds secure_prompt_for_consent prompt_for_creds prompt_for_consent prompt_for_consent_non_windows_binaries}.each do |val|
it "the consent_behavior_admins property accepts :#{val}" do
expect { resource.consent_behavior_admins val }.not_to raise_error(ArgumentError)
end
@@ -34,7 +34,7 @@ describe Chef::Resource::WindowsUac do
expect { resource.consent_behavior_admins :bogus }.to raise_error(ArgumentError)
end
- [:auto_deny, :secure_prompt_for_creds, :prompt_for_creds].each do |val|
+ %i{auto_deny secure_prompt_for_creds prompt_for_creds}.each do |val|
it "the consent_behavior_users property accepts :#{val}" do
expect { resource.consent_behavior_users val }.not_to raise_error(ArgumentError)
end
diff --git a/spec/unit/resource/yum_package_spec.rb b/spec/unit/resource/yum_package_spec.rb
index 0b79a447a3..d0383a8cec 100644
--- a/spec/unit/resource/yum_package_spec.rb
+++ b/spec/unit/resource/yum_package_spec.rb
@@ -95,7 +95,7 @@ describe Chef::Resource::YumPackage, "flush_cache" do
end
it "should allow you to set the flush timing with an array" do
- flush_array = [ :before, :after ]
+ flush_array = %i{before after}
flush_hash = { before: true, after: true }
@resource.flush_cache(flush_array)
expect(@resource.flush_cache).to eq(flush_hash)
diff --git a/spec/unit/resource_collection/resource_list_spec.rb b/spec/unit/resource_collection/resource_list_spec.rb
index dabb8f037d..05363c20b1 100644
--- a/spec/unit/resource_collection/resource_list_spec.rb
+++ b/spec/unit/resource_collection/resource_list_spec.rb
@@ -19,7 +19,7 @@
require "spec_helper"
describe Chef::ResourceCollection::ResourceList do
- let(:resource_list) { Chef::ResourceCollection::ResourceList.new() }
+ let(:resource_list) { Chef::ResourceCollection::ResourceList.new }
let(:resource) { Chef::Resource::ZenMaster.new("makoto") }
let(:second_resource) { Chef::Resource::ZenMaster.new("hattori") }
diff --git a/spec/unit/resource_collection/resource_set_spec.rb b/spec/unit/resource_collection/resource_set_spec.rb
index 60053d2b71..30a55cd3e1 100644
--- a/spec/unit/resource_collection/resource_set_spec.rb
+++ b/spec/unit/resource_collection/resource_set_spec.rb
@@ -172,7 +172,7 @@ describe Chef::ResourceCollection::ResourceSet do
end
it "should raise an exception if you pass something other than a string or hash to resource" do
- expect { collection.find([Array.new]) }.to raise_error(ArgumentError)
+ expect { collection.find([[]]) }.to raise_error(ArgumentError)
end
it "raises an error when attempting to find a resource that does not exist" do
diff --git a/spec/unit/resource_collection/stepable_iterator_spec.rb b/spec/unit/resource_collection/stepable_iterator_spec.rb
index 6354b1b7fb..ec831c9afe 100644
--- a/spec/unit/resource_collection/stepable_iterator_spec.rb
+++ b/spec/unit/resource_collection/stepable_iterator_spec.rb
@@ -72,7 +72,7 @@ describe Chef::ResourceCollection::StepableIterator do
@collection << lambda { @snitch_var = 42 }
@iterator = CRSI.for_collection(@collection)
- @iterator.each { |proc| proc.call }
+ @iterator.each(&:call)
end
it "allows the iteration to be paused" do
@@ -124,7 +124,7 @@ describe Chef::ResourceCollection::StepableIterator do
it "allows the iteration to start by being stepped" do
@snitch_var = nil
@iterator = CRSI.for_collection(@collection)
- @iterator.iterate_on(:element) { |proc| proc.call }
+ @iterator.iterate_on(:element, &:call)
@iterator.step
expect(@iterator.position).to eq(1)
expect(@snitch_var).to eq(23)
diff --git a/spec/unit/resource_collection_spec.rb b/spec/unit/resource_collection_spec.rb
index 7f59246a88..60f17b6934 100644
--- a/spec/unit/resource_collection_spec.rb
+++ b/spec/unit/resource_collection_spec.rb
@@ -20,7 +20,7 @@
require "spec_helper"
describe Chef::ResourceCollection do
- let(:rc) { Chef::ResourceCollection.new() }
+ let(:rc) { Chef::ResourceCollection.new }
let(:resource) { Chef::Resource::ZenMaster.new("makoto") }
it "should throw an error when calling a non-delegated method" do
@@ -97,7 +97,7 @@ describe Chef::ResourceCollection do
describe "each" do
it "should allow you to iterate over every resource in the collection" do
load_up_resources
- results = Array.new
+ results = []
expect do
rc.each do |r|
results << r.name
@@ -119,7 +119,7 @@ describe Chef::ResourceCollection do
describe "each_index" do
it "should allow you to iterate over every resource by index" do
load_up_resources
- results = Array.new
+ results = []
expect do
rc.each_index do |i|
results << rc[i].name
@@ -246,7 +246,7 @@ describe Chef::ResourceCollection do
end
it "should raise an exception if you pass something other than a string or hash to resource" do
- expect { rc.resources([Array.new]) }.to raise_error(ArgumentError)
+ expect { rc.resources([[]]) }.to raise_error(ArgumentError)
end
it "raises an error when attempting to find a resource that does not exist" do
diff --git a/spec/unit/resource_definition_spec.rb b/spec/unit/resource_definition_spec.rb
index 5be3e59009..a1c59eaaca 100644
--- a/spec/unit/resource_definition_spec.rb
+++ b/spec/unit/resource_definition_spec.rb
@@ -19,7 +19,7 @@
require "spec_helper"
describe Chef::ResourceDefinition do
- let(:defn) { Chef::ResourceDefinition.new() }
+ let(:defn) { Chef::ResourceDefinition.new }
describe "initialize" do
it "should be a Chef::ResourceDefinition" do
@@ -92,7 +92,7 @@ describe Chef::ResourceDefinition do
it "should raise an exception if prototype_params is not a hash" do
expect do
- defn.define :monkey, Array.new do
+ defn.define :monkey, [] do
end
end.to raise_error(ArgumentError)
end
diff --git a/spec/unit/resource_inspector_spec.rb b/spec/unit/resource_inspector_spec.rb
index aef92732b3..c0852be3b2 100644
--- a/spec/unit/resource_inspector_spec.rb
+++ b/spec/unit/resource_inspector_spec.rb
@@ -39,7 +39,7 @@ describe ResourceInspector do
it "returns a hash with required data" do
expect(subject[:description]).to eq "A dummy resource"
- expect(subject[:actions]).to match_array [:nothing, :dummy]
+ expect(subject[:actions]).to match_array %i{nothing dummy}
end
context "excluding built in properties" do
diff --git a/spec/unit/resource_spec.rb b/spec/unit/resource_spec.rb
index 1c8e991566..6745dd448d 100644
--- a/spec/unit/resource_spec.rb
+++ b/spec/unit/resource_spec.rb
@@ -115,14 +115,14 @@ describe Chef::Resource do
it "sets a list of state attributes" do
resource_class = Class.new(Chef::Resource)
resource_class.state_attrs(:checksum, :owner, :group, :mode)
- expect(resource_class.state_attrs).to match_array([:checksum, :owner, :group, :mode])
+ expect(resource_class.state_attrs).to match_array(%i{checksum owner group mode})
end
it "inherits state attributes from the superclass" do
resource_class = Class.new(Chef::Resource)
resource_subclass = Class.new(resource_class)
resource_class.state_attrs(:checksum, :owner, :group, :mode)
- expect(resource_subclass.state_attrs).to match_array([:checksum, :owner, :group, :mode])
+ expect(resource_subclass.state_attrs).to match_array(%i{checksum owner group mode})
end
it "combines inherited state attributes with non-inherited state attributes" do
@@ -130,7 +130,7 @@ describe Chef::Resource do
resource_subclass = Class.new(resource_class)
resource_class.state_attrs(:checksum, :owner)
resource_subclass.state_attrs(:group, :mode)
- expect(resource_subclass.state_attrs).to match_array([:checksum, :owner, :group, :mode])
+ expect(resource_subclass.state_attrs).to match_array(%i{checksum owner group mode})
end
end
@@ -157,7 +157,7 @@ describe Chef::Resource do
it "describes its state" do
resource_state = file_resource.state_for_resource_reporter
- expect(resource_state.keys).to match_array([:checksum, :owner, :group, :mode])
+ expect(resource_state.keys).to match_array(%i{checksum owner group mode})
expect(resource_state[:checksum]).to eq("abc123")
expect(resource_state[:owner]).to eq("root")
expect(resource_state[:group]).to eq("wheel")
@@ -510,11 +510,11 @@ describe Chef::Resource do
context "when the resource has a property with a default" do
let(:resource_class) { Class.new(Chef::Resource) { property :a, default: 1 } }
it "should include the default in the hash" do
- expect(resource.to_hash.keys.sort).to eq([:a, :allowed_actions, :params, :provider, :updated,
- :updated_by_last_action, :before,
- :name, :source_line,
- :action, :elapsed_time,
- :default_guard_interpreter, :guard_interpreter].sort)
+ expect(resource.to_hash.keys.sort).to eq(%i{a allowed_actions params provider updated
+ updated_by_last_action before
+ name source_line
+ action elapsed_time
+ default_guard_interpreter guard_interpreter}.sort)
expect(resource.to_hash[:name]).to eq "funk"
expect(resource.to_hash[:a]).to eq 1
end
@@ -522,11 +522,11 @@ describe Chef::Resource do
it "should convert to a hash" do
hash = resource.to_hash
- expected_keys = [ :allowed_actions, :params, :provider, :updated,
- :updated_by_last_action, :before,
- :name, :source_line,
- :action, :elapsed_time,
- :default_guard_interpreter, :guard_interpreter ]
+ expected_keys = %i{allowed_actions params provider updated
+ updated_by_last_action before
+ name source_line
+ action elapsed_time
+ default_guard_interpreter guard_interpreter}
expect(hash.keys - expected_keys).to eq([])
expect(expected_keys - hash.keys).to eq([])
expect(hash[:name]).to eql("funk")
@@ -838,7 +838,7 @@ describe Chef::Resource do
it "should print \"skipped due to action :nothing\" message for doc formatter when action is :nothing" do
fdoc = Chef::Formatters.new(:doc, STDOUT, STDERR)
allow(run_context).to receive(:events).and_return(fdoc)
- expect(fdoc).to receive(:puts).with(" (skipped due to action :nothing)", anything())
+ expect(fdoc).to receive(:puts).with(" (skipped due to action :nothing)", anything)
resource.should_skip?(:nothing)
end
@@ -1118,8 +1118,8 @@ describe Chef::Resource do
end
context "with an array action" do
- before { resource.action([:two, :one]) }
- it { is_expected.to eq [:two, :one] }
+ before { resource.action(%i{two one}) }
+ it { is_expected.to eq %i{two one} }
end
context "with an assignment" do
@@ -1128,8 +1128,8 @@ describe Chef::Resource do
end
context "with an array assignment" do
- before { resource.action = [:two, :one] }
- it { is_expected.to eq [:two, :one] }
+ before { resource.action = %i{two one} }
+ it { is_expected.to eq %i{two one} }
end
context "with an invalid action" do
@@ -1166,8 +1166,8 @@ describe Chef::Resource do
end
context "with an array default action" do
- let(:default_action) { [:two, :one] }
- it { is_expected.to eq [:two, :one] }
+ let(:default_action) { %i{two one} }
+ it { is_expected.to eq %i{two one} }
end
end
diff --git a/spec/unit/role_spec.rb b/spec/unit/role_spec.rb
index 46ee71bb1c..13932ab3ee 100644
--- a/spec/unit/role_spec.rb
+++ b/spec/unit/role_spec.rb
@@ -113,7 +113,7 @@ describe Chef::Role do
end
it "should throw an ArgumentError if we aren't a kind of hash" do
- expect { @role.default_attributes(Array.new) }.to raise_error(ArgumentError)
+ expect { @role.default_attributes([]) }.to raise_error(ArgumentError)
end
end
@@ -128,7 +128,7 @@ describe Chef::Role do
end
it "should throw an ArgumentError if we aren't a kind of hash" do
- expect { @role.override_attributes(Array.new) }.to raise_error(ArgumentError)
+ expect { @role.override_attributes([]) }.to raise_error(ArgumentError)
end
end
diff --git a/spec/unit/run_context/cookbook_compiler_spec.rb b/spec/unit/run_context/cookbook_compiler_spec.rb
index 607333416d..cc9330a1b6 100644
--- a/spec/unit/run_context/cookbook_compiler_spec.rb
+++ b/spec/unit/run_context/cookbook_compiler_spec.rb
@@ -217,14 +217,14 @@ describe Chef::RunContext::CookbookCompiler do
it "should return an array of cookbook names as symbols without duplicates" do
node.run_list("test-with-circular-deps::default", "circular-dep1::default", "circular-dep2::default")
- expect(compiler.cookbook_order).to eq([:"circular-dep2",
- :"circular-dep1",
- :"test-with-circular-deps"])
+ expect(compiler.cookbook_order).to eq(%i{circular-dep2
+ circular-dep1
+ test-with-circular-deps})
end
it "determines if a cookbook is in the list of cookbooks reachable by dependency" do
node.run_list("test-with-deps::default", "test-with-deps::server")
- expect(compiler.cookbook_order).to eq([:dependency1, :dependency2, :"test-with-deps"])
+ expect(compiler.cookbook_order).to eq(%i{dependency1 dependency2 test-with-deps})
expect(compiler.unreachable_cookbook?(:dependency1)).to be_falsey
expect(compiler.unreachable_cookbook?(:dependency2)).to be_falsey
expect(compiler.unreachable_cookbook?(:'test-with-deps')).to be_falsey
diff --git a/spec/unit/run_list/run_list_expansion_spec.rb b/spec/unit/run_list/run_list_expansion_spec.rb
index 3a39bc79cc..4ddc75f002 100644
--- a/spec/unit/run_list/run_list_expansion_spec.rb
+++ b/spec/unit/run_list/run_list_expansion_spec.rb
@@ -94,12 +94,15 @@ describe Chef::RunList::RunListExpansion do
allow(@expansion).to receive(:fetch_role).and_return(@first_role, @second_role)
@expansion.expand
@json = '{"id":"_default","run_list":[{"type":"recipe","name":"lobster::mastercookbook","version":"0.1.0",'
- .concat(
-'"skipped":false},{"type":"role","name":"rage","children":[{"type":"role","name":"mollusk","children":[],"missing":null,'
- .concat(
-'"error":null,"skipped":null},{"type":"recipe","name":"crabrevenge","version":null,"skipped":false}],"missing":null,'
- .concat(
-'"error":null,"skipped":null},{"type":"recipe","name":"fist","version":"0.1","skipped":false}]}')))
+ .concat(
+ '"skipped":false},{"type":"role","name":"rage","children":[{"type":"role","name":"mollusk","children":[],"missing":null,'
+ .concat(
+ '"error":null,"skipped":null},{"type":"recipe","name":"crabrevenge","version":null,"skipped":false}],"missing":null,'
+ .concat(
+ '"error":null,"skipped":null},{"type":"recipe","name":"fist","version":"0.1","skipped":false}]}'
+ )
+ )
+ )
end
diff --git a/spec/unit/run_list_spec.rb b/spec/unit/run_list_spec.rb
index ac062c665d..5dc877ad9a 100644
--- a/spec/unit/run_list_spec.rb
+++ b/spec/unit/run_list_spec.rb
@@ -133,7 +133,7 @@ describe Chef::RunList do
it "should yield each member to your block" do
@run_list << "foo"
@run_list << "bar"
- seen = Array.new
+ seen = []
@run_list.each { |r| seen << r }
expect(seen).to be_include("recipe[foo]")
expect(seen).to be_include("recipe[bar]")
diff --git a/spec/unit/runner_spec.rb b/spec/unit/runner_spec.rb
index 1effe3157c..ffb0cd523f 100644
--- a/spec/unit/runner_spec.rb
+++ b/spec/unit/runner_spec.rb
@@ -295,7 +295,7 @@ describe Chef::Runner do
# execution, and schedule delayed actions :second and :third on the first
# resource. The duplicate actions should "collapse" to a single notification
# and order should be preserved.
- expect(SnitchyProvider.all_actions_called).to eq([:first, :first, :second, :third])
+ expect(SnitchyProvider.all_actions_called).to eq(%i{first first second third})
end
it "executes delayed notifications in the order they were declared" do
@@ -321,7 +321,7 @@ describe Chef::Runner do
third_resource.notifies(:third_action, first_resource, :delayed)
runner.converge
- expect(SnitchyProvider.all_actions_called).to eq([:first, :first, :second, :third])
+ expect(SnitchyProvider.all_actions_called).to eq(%i{first first second third})
end
it "does not fire notifications if the resource was not updated by the last action executed" do
@@ -347,7 +347,7 @@ describe Chef::Runner do
runner.converge
# All of the resources should only fire once:
- expect(SnitchyProvider.all_actions_called).to eq([:first, :second, :third])
+ expect(SnitchyProvider.all_actions_called).to eq(%i{first second third})
# all of the resources should be marked as updated for reporting purposes
expect(first_resource).to be_updated
diff --git a/spec/unit/search/query_spec.rb b/spec/unit/search/query_spec.rb
index 151fcb51b3..83f988911c 100644
--- a/spec/unit/search/query_spec.rb
+++ b/spec/unit/search/query_spec.rb
@@ -149,7 +149,8 @@ describe Chef::Search::Query do
],
"start" => 0,
"total" => 4,
- } end
+ }
+ end
let(:big_response_empty) do
{
@@ -169,7 +170,7 @@ describe Chef::Search::Query do
it "accepts a type as the first argument" do
expect { query.search("node") }.not_to raise_error
expect { query.search(:node) }.not_to raise_error
- expect { query.search(Hash.new) }.to raise_error(Chef::Exceptions::InvalidSearchQuery, /(Hash)/)
+ expect { query.search({}) }.to raise_error(Chef::Exceptions::InvalidSearchQuery, /(Hash)/)
end
it "queries for every object of a type by default" do
diff --git a/spec/unit/shell/model_wrapper_spec.rb b/spec/unit/shell/model_wrapper_spec.rb
index bcce7c1a08..7ca5f74bef 100644
--- a/spec/unit/shell/model_wrapper_spec.rb
+++ b/spec/unit/shell/model_wrapper_spec.rb
@@ -57,7 +57,7 @@ describe Shell::ModelWrapper do
end
it "maps the listed nodes when given a block" do
- expect(@wrapper.all { |n| n.name }.sort.reverse).to eq(%w{yummy sammich})
+ expect(@wrapper.all(&:name).sort.reverse).to eq(%w{yummy sammich})
end
end
diff --git a/spec/unit/shell/shell_session_spec.rb b/spec/unit/shell/shell_session_spec.rb
index 6644ff6e0c..c98989491d 100644
--- a/spec/unit/shell/shell_session_spec.rb
+++ b/spec/unit/shell/shell_session_spec.rb
@@ -57,8 +57,7 @@ describe Shell::ClientSession do
load_node: true,
build_node: true,
register: true,
- sync_cookbooks: {}
- )
+ sync_cookbooks: {})
end
before do
@@ -94,8 +93,7 @@ describe Shell::SoloSession do
load_node: true,
build_node: true,
register: true,
- sync_cookbooks: {}
- )
+ sync_cookbooks: {})
end
before do
@@ -132,8 +130,7 @@ describe Shell::StandAloneSession do
load_node: true,
build_node: true,
register: true,
- sync_cookbooks: {}
- )
+ sync_cookbooks: {})
end
let(:recipe) { Chef::Recipe.new(nil, nil, run_context) }
let(:run_context) { Chef::RunContext.new(node, {}, events) }
diff --git a/spec/unit/shell_spec.rb b/spec/unit/shell_spec.rb
index 8ba1afa72a..aa573706b1 100644
--- a/spec/unit/shell_spec.rb
+++ b/spec/unit/shell_spec.rb
@@ -30,8 +30,7 @@ ObjectTestHarness = Proc.new do
end
desc "rspecin'"
- def rspec_method
- end
+ def rspec_method; end
end
class TestJobManager
diff --git a/spec/unit/user_spec.rb b/spec/unit/user_spec.rb
index 48dbf010e9..492dc147d9 100644
--- a/spec/unit/user_spec.rb
+++ b/spec/unit/user_spec.rb
@@ -65,7 +65,7 @@ describe Chef::User do
end
it "should throw an ArgumentError if you feed it anything but a string" do
- expect { @user.name Hash.new }.to raise_error(ArgumentError)
+ expect { @user.name({}) }.to raise_error(ArgumentError)
end
end
@@ -84,7 +84,7 @@ describe Chef::User do
end
it "should throw an ArgumentError if you feed it anything but true or false" do
- expect { @user.name Hash.new }.to raise_error(ArgumentError)
+ expect { @user.name({}) }.to raise_error(ArgumentError)
end
end
@@ -99,7 +99,7 @@ describe Chef::User do
end
it "should throw an ArgumentError if you feed it something lame" do
- expect { @user.public_key Hash.new }.to raise_error(ArgumentError)
+ expect { @user.public_key({}) }.to raise_error(ArgumentError)
end
end
@@ -114,7 +114,7 @@ describe Chef::User do
end
it "should throw an ArgumentError if you feed it something lame" do
- expect { @user.private_key Hash.new }.to raise_error(ArgumentError)
+ expect { @user.private_key({}) }.to raise_error(ArgumentError)
end
end
diff --git a/spec/unit/user_v1_spec.rb b/spec/unit/user_v1_spec.rb
index 37b2252492..4bde7278fe 100644
--- a/spec/unit/user_v1_spec.rb
+++ b/spec/unit/user_v1_spec.rb
@@ -37,7 +37,7 @@ describe Chef::UserV1 do
end
it "should throw an ArgumentError if you feed it something lame" do
- expect { @user.send(method, Hash.new) }.to raise_error(ArgumentError)
+ expect { @user.send(method, {}) }.to raise_error(ArgumentError)
end
end
@@ -57,7 +57,7 @@ describe Chef::UserV1 do
end
it "should throw an ArgumentError if you feed it anything but true or false" do
- expect { @user.send(method, Hash.new) }.to raise_error(ArgumentError)
+ expect { @user.send(method, {}) }.to raise_error(ArgumentError)
end
end
@@ -95,7 +95,7 @@ describe Chef::UserV1 do
end
it "should throw an ArgumentError if you feed it anything but a string" do
- expect { @user.username Hash.new }.to raise_error(ArgumentError)
+ expect { @user.username({}) }.to raise_error(ArgumentError)
end
end
diff --git a/spec/unit/util/backup_spec.rb b/spec/unit/util/backup_spec.rb
index 8bc68ec160..3a9a45b841 100644
--- a/spec/unit/util/backup_spec.rb
+++ b/spec/unit/util/backup_spec.rb
@@ -110,7 +110,7 @@ describe Chef::Util::Backup do
end
it "should strip the drive letter off for windows" do
expect(@backup).to receive(:path).and_return('c:\a\b\c.txt')
- expect(@backup.send(:backup_filename)).to match(%r|^\\a\\b\\c.txt.chef-\d{14}.\d{6}$|)
+ expect(@backup.send(:backup_filename)).to match(/^\\a\\b\\c.txt.chef-\d{14}.\d{6}$/)
end
it "should strip the drive letter off for windows (with forwardslashes)" do
expect(@backup).to receive(:path).and_return("c:/a/b/c.txt")
diff --git a/spec/unit/util/editor_spec.rb b/spec/unit/util/editor_spec.rb
index e53bc9662a..ac851a835e 100644
--- a/spec/unit/util/editor_spec.rb
+++ b/spec/unit/util/editor_spec.rb
@@ -9,7 +9,7 @@ describe Chef::Util::Editor do
end
it "makes a copy of an Array" do
- array = Array.new
+ array = []
editor = described_class.new(array)
expect(editor.lines).to_not be(array)
end
diff --git a/spec/unit/util/powershell/ps_credential_spec.rb b/spec/unit/util/powershell/ps_credential_spec.rb
index 6f65174d15..65207d5dfb 100644
--- a/spec/unit/util/powershell/ps_credential_spec.rb
+++ b/spec/unit/util/powershell/ps_credential_spec.rb
@@ -29,8 +29,9 @@ describe Chef::Util::Powershell::PSCredential do
it "should create the script to create a PSCredential when calling" do
allow(ps_credential).to receive(:encrypt).with(password).and_return("encrypted")
expect(ps_credential.to_psobject).to eq(
- "New-Object System.Management.Automation.PSCredential("\
- "'#{username}',('encrypted' | ConvertTo-SecureString))")
+ "New-Object System.Management.Automation.PSCredential("\
+ "'#{username}',('encrypted' | ConvertTo-SecureString))"
+ )
end
end
diff --git a/spec/unit/util/threaded_job_queue_spec.rb b/spec/unit/util/threaded_job_queue_spec.rb
index 8a89943a8a..48a34bce31 100644
--- a/spec/unit/util/threaded_job_queue_spec.rb
+++ b/spec/unit/util/threaded_job_queue_spec.rb
@@ -22,7 +22,7 @@ describe Chef::Util::ThreadedJobQueue do
let(:queue) { Chef::Util::ThreadedJobQueue.new }
it "should pass mutex to jobs with an arity of 1" do
- job = double()
+ job = double
expect(job).to receive(:arity).at_least(:once).and_return(1)
expect(job).to receive(:call).exactly(5).times.with(an_instance_of(Mutex))
@@ -31,7 +31,7 @@ describe Chef::Util::ThreadedJobQueue do
end
it "should pass nothing to jobs with an arity of 0" do
- job = double()
+ job = double
expect(job).to receive(:arity).at_least(:once).and_return(0)
expect(job).to receive(:call).exactly(5).times.with(no_args)
diff --git a/spec/unit/version_class_spec.rb b/spec/unit/version_class_spec.rb
index 9dc981bd4c..c6848491ee 100644
--- a/spec/unit/version_class_spec.rb
+++ b/spec/unit/version_class_spec.rb
@@ -105,7 +105,7 @@ describe Chef::Version do
a = %w{0.0.0 0.0.1 0.1.0 0.1.1 1.0.0 1.1.0 1.1.1}.map do |s|
Chef::Version.new(s)
end
- got = a.sort.map { |v| v.to_s }
+ got = a.sort.map(&:to_s)
expect(got).to eq(%w{0.0.0 0.0.1 0.1.0 0.1.1 1.0.0 1.1.0 1.1.1})
end
@@ -113,7 +113,7 @@ describe Chef::Version do
a = %w{9.8.7 1.0.0 1.2.3 4.4.6 4.5.6 0.8.6 4.5.5 5.9.8 3.5.7}.map do |s|
Chef::Version.new(s)
end
- got = a.sort.map { |v| v.to_s }
+ got = a.sort.map(&:to_s)
expect(got).to eq(%w{0.8.6 1.0.0 1.2.3 3.5.7 4.4.6 4.5.5 4.5.6 5.9.8 9.8.7})
end
@@ -160,7 +160,7 @@ describe Chef::Version do
[ "1.2.2", :<=, "1.2.1", false ],
[ "1.2.2", :<, "1.2.1", false ],
].each do |spec|
- it "(#{spec.first(3).join(' ')}) should be #{spec[3]}" do
+ it "(#{spec.first(3).join(" ")}) should be #{spec[3]}" do
got = Chef::Version.new(spec[0]).send(spec[1],
Chef::Version.new(spec[2]))
expect(got).to eq(spec[3])
diff --git a/spec/unit/win32/registry_spec.rb b/spec/unit/win32/registry_spec.rb
index 574f38d8e2..2485d9ee47 100644
--- a/spec/unit/win32/registry_spec.rb
+++ b/spec/unit/win32/registry_spec.rb
@@ -29,7 +29,7 @@ describe Chef::Win32::Registry do
let(:key_to_delete) { "OpscodeNumbers" }
let(:sub_key) { "OpscodePrimes" }
let(:missing_key_path) { 'HKCU\Software' }
- let(:registry) { Chef::Win32::Registry.new() }
+ let(:registry) { Chef::Win32::Registry.new }
let(:hive_mock) { double("::Win32::Registry::KHKEY_CURRENT_USER") }
let(:reg_mock) { double("reg") }
@@ -252,7 +252,7 @@ describe Chef::Win32::Registry do
expect(registry).to receive(:key_exists!).with(key_path).and_return(true)
expect(registry).to receive(:get_hive_and_key).with(key_path).and_return([hive_mock, key])
expect(hive_mock).to receive(:open).with(key, ::Win32::Registry::KEY_READ | registry.registry_system_architecture).and_yield(reg_mock)
- expect(reg_mock).to receive(:each_key).and_return(no_args())
+ expect(reg_mock).to receive(:each_key).and_return(no_args)
expect(registry.has_subkeys?(key_path)).to eq(false)
end
@@ -290,7 +290,7 @@ describe Chef::Win32::Registry do
expect(registry).to receive(:key_exists!).with(key_path).and_return(true)
expect(registry).to receive(:get_hive_and_key).with(key_path).and_return([hive_mock, key])
expect(hive_mock).to receive(:open).with(key, ::Win32::Registry::KEY_READ | registry.registry_system_architecture).and_yield(reg_mock)
- expect(reg_mock).to receive(:any?).and_yield(no_args())
+ expect(reg_mock).to receive(:any?).and_yield(no_args)
registry.value_exists?(key_path, value1) == false
end
end
@@ -305,7 +305,7 @@ describe Chef::Win32::Registry do
expect(registry).to receive(:key_exists!).with(key_path).and_return(true)
expect(registry).to receive(:get_hive_and_key).with(key_path).and_return([hive_mock, key])
expect(registry).to receive(:get_type_from_name).with(:string).and_return(1)
- expect(reg_mock).to receive(:each).with(no_args()).and_yield("one", 1, "1")
+ expect(reg_mock).to receive(:each).with(no_args).and_yield("one", 1, "1")
expect(hive_mock).to receive(:open).with(key, ::Win32::Registry::KEY_READ | registry.registry_system_architecture).and_yield(reg_mock)
expect(registry.data_exists?(key_path, value1)).to eq(true)
end
@@ -315,7 +315,7 @@ describe Chef::Win32::Registry do
expect(registry).to receive(:get_hive_and_key).with(key_path).and_return([hive_mock, key])
expect(hive_mock).to receive(:open).with(key, ::Win32::Registry::KEY_READ | registry.registry_system_architecture).and_yield(reg_mock)
expect(registry).to receive(:get_type_from_name).with(:string).and_return(1)
- expect(reg_mock).to receive(:each).with(no_args()).and_yield("one", 1, "2")
+ expect(reg_mock).to receive(:each).with(no_args).and_yield("one", 1, "2")
expect(registry.data_exists?(key_path, value1)).to eq(false)
end
end
diff --git a/spec/unit/win32/security_spec.rb b/spec/unit/win32/security_spec.rb
index 3c612aef10..efbb290adf 100644
--- a/spec/unit/win32/security_spec.rb
+++ b/spec/unit/win32/security_spec.rb
@@ -98,7 +98,8 @@ describe "Chef::Win32::Security", :windows_only do
let(:token) do
Chef::ReservedNames::Win32::Security.open_process_token(
Chef::ReservedNames::Win32::Process.get_current_process,
- token_rights)
+ token_rights
+ )
end
it "raises error if GetTokenInformation fails" do
diff --git a/tasks/docs.rb b/tasks/docs.rb
index c74bc55523..619d1a2218 100755
--- a/tasks/docs.rb
+++ b/tasks/docs.rb
@@ -21,6 +21,7 @@ namespace :docs_site do
# @return [String, nil] a pretty defaul value string or nil if we want to skip it
def pretty_default(default)
return nil if default.nil? || default == "" || default == "lazy default"
+
if default.is_a?(String)
return default.inspect unless default[0] == ":"
end
@@ -36,13 +37,13 @@ namespace :docs_site do
# build the resource string with property spacing between property names and comments
text = " #{resource_name} 'name' do\n"
properties.each do |p|
- text << " #{p['name'].ljust(padding_size)}"
+ text << " #{p["name"].ljust(padding_size)}"
text << friendly_types_list(p["is"])
text << " # default value: 'name' unless specified" if p["name_property"]
- text << " # default value: #{pretty_default(p['default'])}" unless pretty_default(p["default"]).nil?
+ text << " # default value: #{pretty_default(p["default"])}" unless pretty_default(p["default"]).nil?
text << "\n"
end
- text << " #{'action'.ljust(padding_size)}Symbol # defaults to :#{@default_action.first} if not specified\n"
+ text << " #{"action".ljust(padding_size)}Symbol # defaults to :#{@default_action.first} if not specified\n"
text << " end"
text
end
@@ -64,7 +65,7 @@ namespace :docs_site do
def friendly_properly_list(arr)
return nil if arr.empty? # resources w/o properties
- props = arr.map { |x| "``#{x['name']}``" }
+ props = arr.map { |x| "``#{x["name"]}``" }
# build the text string containing all properties bolded w/ punctuation
if props.size > 1
@@ -98,11 +99,13 @@ namespace :docs_site do
# @return String
def bolded_description(name, description)
return nil if description.nil? # handle resources missing descriptions
+
description.gsub( "#{name} ", "**#{name}** ").split("Note: ").first.strip
end
def note_text(description)
return nil if description.nil?
+
note = description.split("Note: ")[1]
if note
<<-HEREDOC
@@ -327,6 +330,7 @@ Examples
resources = Chef::JSONCompat.parse(ResourceInspector.inspect)
resources.each do |resource, data|
next if ["scm", "whyrun_safe_ruby_block", "l_w_r_p_base", "user_resource_abstract_base_class", "linux_user", "pw_user", "aix_user", "dscl_user", "solaris_user", "windows_user", ""].include?(resource)
+
puts "Writing out #{resource}."
@name = resource
@description = data["description"]
diff --git a/tasks/rspec.rb b/tasks/rspec.rb
index afd7d12705..2d20a0ffa7 100644
--- a/tasks/rspec.rb
+++ b/tasks/rspec.rb
@@ -77,7 +77,7 @@ begin
t.pattern = FileList["spec/unit/node_spec.rb", "spec/unit/role_spec.rb"]
end
- [:unit, :functional, :integration, :stress].each do |sub|
+ %i{unit functional integration stress}.each do |sub|
desc "Run the specs under spec/#{sub}"
RSpec::Core::RakeTask.new(sub) do |t|
t.rspec_opts = %w{--profile}