From d25f87dc21e32fd8daf2198585ad2bf1e6ec1b2c Mon Sep 17 00:00:00 2001 From: Steven Pritchard Date: Fri, 13 Dec 2024 15:35:23 -0600 Subject: [PATCH] Clean up for rubocop --- .github/workflows/pr_tests.yml | 11 +- .rubocop.yml | 667 ++++++++++++++++-- CHANGELOG | 3 + Gemfile | 11 +- Gemfile.project | 4 - REFERENCE.md | 78 +- lib/facter/acpid_enabled.rb | 4 +- lib/facter/boot_dir_uuid.rb | 5 +- lib/facter/cmdline.rb | 12 +- lib/facter/cpuinfo.rb | 30 +- lib/facter/defaultgateway.rb | 8 +- lib/facter/defaultgatewayiface.rb | 8 +- lib/facter/fips_ciphers.rb | 3 +- lib/facter/fips_enabled.rb | 2 +- lib/facter/fullrun.rb | 11 +- lib/facter/gdm_version.rb | 6 +- lib/facter/ipa.rb | 38 +- lib/facter/ipv6_enabled.rb | 10 +- lib/facter/login_defs.rb | 15 +- lib/facter/prelink.rb | 6 +- lib/facter/reboot_required.rb | 10 +- lib/facter/root_dir_uuid.rb | 4 +- lib/facter/runlevel.rb | 6 +- lib/facter/shmall.rb | 7 +- lib/facter/simp_puppet_settings.rb | 6 +- lib/facter/simplib__auditd.rb | 14 +- lib/facter/simplib__efi_enabled.rb | 4 +- lib/facter/simplib__firewalls.rb | 2 +- lib/facter/simplib__mountpoints.rb | 9 +- lib/facter/simplib__networkmanager.rb | 6 +- lib/facter/simplib__numa.rb | 10 +- lib/facter/simplib__secure_boot_enabled.rb | 20 +- lib/facter/simplib__sshd_config.rb | 26 +- lib/facter/simplib_sysctl.rb | 25 +- lib/facter/tmp_mounts.rb | 25 +- lib/facter/uid_min.rb | 14 +- .../simplib/assert_optional_dependency.rb | 122 ++-- lib/puppet/functions/simplib/bracketize.rb | 15 +- lib/puppet/functions/simplib/caller.rb | 8 +- .../functions/simplib/debug/classtrace.rb | 13 +- lib/puppet/functions/simplib/debug/inspect.rb | 14 +- .../functions/simplib/debug/stacktrace.rb | 13 +- lib/puppet/functions/simplib/deprecation.rb | 7 +- lib/puppet/functions/simplib/dlookup.rb | 4 +- lib/puppet/functions/simplib/filtered.rb | 21 +- .../functions/simplib/gen_random_password.rb | 60 +- lib/puppet/functions/simplib/host_is_me.rb | 5 +- .../functions/simplib/ip/family_hash.rb | 21 +- lib/puppet/functions/simplib/ip_to_cron.rb | 2 - lib/puppet/functions/simplib/ipaddresses.rb | 5 +- .../functions/simplib/join_mount_opts.rb | 42 +- lib/puppet/functions/simplib/lookup.rb | 8 +- lib/puppet/functions/simplib/mock_data.rb | 26 +- lib/puppet/functions/simplib/module_exist.rb | 27 +- lib/puppet/functions/simplib/nets2cidr.rb | 20 +- lib/puppet/functions/simplib/nets2ddq.rb | 25 +- lib/puppet/functions/simplib/params2hash.rb | 9 +- lib/puppet/functions/simplib/parse_hosts.rb | 41 +- lib/puppet/functions/simplib/passgen.rb | 19 +- .../simplib/passgen/gen_password_and_salt.rb | 5 +- .../functions/simplib/passgen/gen_salt.rb | 5 +- lib/puppet/functions/simplib/passgen/get.rb | 18 +- .../simplib/passgen/legacy/common_settings.rb | 5 +- .../functions/simplib/passgen/legacy/get.rb | 11 +- .../functions/simplib/passgen/legacy/list.rb | 13 +- .../simplib/passgen/legacy/passgen.rb | 164 ++--- .../simplib/passgen/legacy/remove.rb | 21 +- .../functions/simplib/passgen/legacy/set.rb | 29 +- lib/puppet/functions/simplib/passgen/list.rb | 18 +- .../functions/simplib/passgen/remove.rb | 3 +- lib/puppet/functions/simplib/passgen/set.rb | 7 +- .../functions/simplib/passgen/simpkv/get.rb | 3 +- .../functions/simplib/passgen/simpkv/list.rb | 6 +- .../simplib/passgen/simpkv/passgen.rb | 60 +- .../simplib/passgen/simpkv/remove.rb | 8 +- .../simplib/passgen/simpkv/root_dir.rb | 1 - .../functions/simplib/passgen/simpkv/set.rb | 15 +- .../passgen/simpkv/valid_password_info.rb | 12 +- lib/puppet/functions/simplib/rand_cron.rb | 38 +- lib/puppet/functions/simplib/simp_version.rb | 9 +- lib/puppet/functions/simplib/strip_ports.rb | 1 - lib/puppet/functions/simplib/to_integer.rb | 9 +- lib/puppet/functions/simplib/to_string.rb | 13 +- .../simplib/validate_array_member.rb | 42 +- .../functions/simplib/validate_between.rb | 14 +- lib/puppet/functions/simplib/validate_bool.rb | 5 +- .../functions/simplib/validate_deep_hash.rb | 43 +- .../functions/simplib/validate_net_list.rb | 23 +- lib/puppet/functions/simplib/validate_port.rb | 4 +- .../functions/simplib/validate_re_array.rb | 15 +- .../simplib/validate_sysctl_value.rb | 38 +- .../functions/simplib/validate_uri_list.rb | 24 +- lib/puppet/provider/init_ulimit/systemd.rb | 22 +- lib/puppet/provider/init_ulimit/sysv.rb | 56 +- lib/puppet/provider/prepend_file_line/ruby.rb | 10 +- lib/puppet/provider/reboot_notify/notify.rb | 43 +- lib/puppet/provider/runlevel/systemd.rb | 36 +- lib/puppet/provider/runlevel/telinit.rb | 27 +- lib/puppet/provider/script_umask/ruby.rb | 26 +- lib/puppet/provider/simp_file_line/ruby.rb | 48 +- lib/puppet/type/ftpusers.rb | 30 +- lib/puppet/type/init_ulimit.rb | 130 ++-- lib/puppet/type/prepend_file_line.rb | 24 +- lib/puppet/type/reboot_notify.rb | 18 +- lib/puppet/type/runlevel.rb | 29 +- lib/puppet/type/script_umask.rb | 10 +- lib/puppet/type/simp_file_line.rb | 18 +- lib/puppetx/simp/simplib.rb | 169 +++-- metadata.json | 2 +- .../suites/caller_function/caller_spec.rb | 21 +- .../suites/default/00_facter_spec.rb | 2 +- .../suites/default/05_cron_mangler_spec.rb | 10 +- .../suites/default/fips_enabled_fact_spec.rb | 3 +- .../acceptance/suites/default/inspect_spec.rb | 13 +- .../suites/default/ipaddresses_spec.rb | 25 +- .../suites/default/nets2ddq_spec.rb | 15 +- .../suites/default/parse_hosts_spec.rb | 15 +- .../acceptance/suites/default/passgen_spec.rb | 51 +- .../suites/default/reboot_notify_spec.rb | 85 ++- .../default/simplib__sshd_config_fact_spec.rb | 11 +- .../suites/default/strip_ports_spec.rb | 15 +- .../suites/default/to_integer_spec.rb | 21 +- .../suites/default/to_string_spec.rb | 21 +- .../default/validate_array_member_spec.rb | 18 +- .../suites/default/validate_between_spec.rb | 18 +- .../suites/default/validate_bool_simp_spec.rb | 18 +- .../suites/default/validate_deep_hash_spec.rb | 18 +- .../suites/default/validate_net_list_spec.rb | 18 +- .../suites/default/validate_port_spec.rb | 14 +- .../validate_simp_puppet_settings_spec.rb | 2 +- .../suites/default/validate_uri_list_spec.rb | 14 +- .../suites/ipa_fact/ipa_fact_spec.rb | 46 +- .../suites/prelink_fact/prelink_fact_spec.rb | 51 +- .../suites/windows/00_facter_spec.rb | 2 +- spec/classes/reboot_notify_spec.rb | 2 +- spec/defines/install_spec.rb | 60 +- spec/functions/assert_metadata_spec.rb | 14 +- spec/functions/cron/to_systemd_spec.rb | 46 +- spec/functions/hash_to_opts_spec.rb | 56 +- spec/functions/knockout_spec.rb | 10 +- spec/functions/ldap/domain_to_dn_spec.rb | 26 +- spec/functions/module_metadata/assert_spec.rb | 50 +- .../module_metadata/os_blacklisted_spec.rb | 62 +- .../module_metadata/os_supported_spec.rb | 166 ++--- .../assert_optional_dependency_spec.rb | 62 +- spec/functions/simplib/bracketize_spec.rb | 20 +- .../simplib/debug/classtrace_spec.rb | 14 +- spec/functions/simplib/debug/inspect_spec.rb | 40 +- .../simplib/debug/stacktrace_spec.rb | 16 +- spec/functions/simplib/deprecation_spec.rb | 12 +- spec/functions/simplib/dlookup_spec.rb | 63 +- spec/functions/simplib/filtered_spec.rb | 95 +-- .../simplib/gen_random_password_spec.rb | 64 +- spec/functions/simplib/host_is_me_spec.rb | 23 +- spec/functions/simplib/inspect_spec.rb | 48 +- spec/functions/simplib/ip/family_hash_spec.rb | 6 +- spec/functions/simplib/ip_to_cron_spec.rb | 16 +- spec/functions/simplib/ipaddresses_spec.rb | 54 +- .../functions/simplib/join_mount_opts_spec.rb | 21 +- spec/functions/simplib/lookup_spec.rb | 34 +- spec/functions/simplib/module_exist_spec.rb | 4 +- spec/functions/simplib/nets2cidr_spec.rb | 24 +- spec/functions/simplib/nets2ddq_spec.rb | 19 +- spec/functions/simplib/params2hash_spec.rb | 130 ++-- spec/functions/simplib/parse_hosts_spec.rb | 62 +- .../functions/simplib/passgen/crypt_helper.rb | 50 +- .../passgen/gen_password_and_salt_spec.rb | 120 ++-- .../simplib/passgen/gen_salt_spec.rb | 40 +- spec/functions/simplib/passgen/get_spec.rb | 53 +- .../passgen/legacy/common_settings_spec.rb | 9 +- .../simplib/passgen/legacy/get_spec.rb | 52 +- .../simplib/passgen/legacy/list_spec.rb | 31 +- .../simplib/passgen/legacy/passgen_spec.rb | 267 ++++--- .../simplib/passgen/legacy/remove_spec.rb | 56 +- .../simplib/passgen/legacy/set_spec.rb | 130 ++-- spec/functions/simplib/passgen/list_spec.rb | 79 +-- spec/functions/simplib/passgen/remove_spec.rb | 57 +- spec/functions/simplib/passgen/set_spec.rb | 107 +-- .../simplib/passgen/simpkv/get_spec.rb | 34 +- .../simplib/passgen/simpkv/list_spec.rb | 83 +-- .../simplib/passgen/simpkv/passgen_spec.rb | 260 ++++--- .../simplib/passgen/simpkv/remove_spec.rb | 14 +- .../simplib/passgen/simpkv/root_dir_spec.rb | 2 +- .../simplib/passgen/simpkv/set_spec.rb | 11 +- .../simpkv/valid_password_info_spec.rb | 22 +- spec/functions/simplib/passgen_spec.rb | 285 ++++---- spec/functions/simplib/rand_cron_spec.rb | 17 +- spec/functions/simplib/simp_version_spec.rb | 30 +- spec/functions/simplib/strip_ports_spec.rb | 19 +- spec/functions/simplib/to_integer_spec.rb | 4 +- spec/functions/simplib/to_string_spec.rb | 10 +- .../simplib/validate_array_member_spec.rb | 30 +- .../simplib/validate_between_spec.rb | 11 +- ...validate_bool.rb => validate_bool_spec.rb} | 9 +- .../simplib/validate_deep_hash_spec.rb | 82 ++- .../simplib/validate_net_list_spec.rb | 33 +- spec/functions/simplib/validate_port_spec.rb | 13 +- .../simplib/validate_re_array_spec.rb | 33 +- .../simplib/validate_sysctl_value_spec.rb | 53 +- .../simplib/validate_uri_list_spec.rb | 31 +- spec/functions/simplib_spec.rb | 4 +- spec/spec_helper.rb | 15 +- spec/spec_helper_acceptance.rb | 51 +- spec/type_aliases/cron/hour_entry_spec.rb | 40 +- spec/type_aliases/cron/hour_spec.rb | 24 +- spec/type_aliases/cron/minute_entry_spec.rb | 34 +- spec/type_aliases/cron/minute_spec.rb | 24 +- spec/type_aliases/cron/month_entry_spec.rb | 56 +- spec/type_aliases/cron/month_spec.rb | 30 +- spec/type_aliases/cron/monthday_entry_spec.rb | 36 +- spec/type_aliases/cron/monthday_spec.rb | 24 +- spec/type_aliases/cron/weekday_entry_spec.rb | 62 +- spec/type_aliases/cron/weekday_spec.rb | 28 +- spec/type_aliases/domain_spec.rb | 4 +- spec/type_aliases/domainlist_spec.rb | 11 +- spec/unit/data_types/emailaddress_spec.rb | 30 +- spec/unit/data_types/host/port_spec.rb | 36 +- spec/unit/data_types/host_spec.rb | 34 +- spec/unit/data_types/hostname/port_spec.rb | 32 +- spec/unit/data_types/hostname_spec.rb | 34 +- spec/unit/data_types/ip/v4/cidr_spec.rb | 34 +- spec/unit/data_types/ip/v4/ddq_spec.rb | 34 +- spec/unit/data_types/ip/v4/port_spec.rb | 34 +- spec/unit/data_types/ip/v4_spec.rb | 34 +- spec/unit/data_types/ip/v6/base_spec.rb | 34 +- spec/unit/data_types/ip/v6/bracketed_spec.rb | 34 +- spec/unit/data_types/ip/v6/cidr_spec.rb | 34 +- spec/unit/data_types/ip/v6/port_spec.rb | 34 +- spec/unit/data_types/ip/v6_spec.rb | 34 +- spec/unit/data_types/ip_spec.rb | 34 +- spec/unit/data_types/netlist/host_spec.rb | 40 +- spec/unit/data_types/netlist/ip/v4_spec.rb | 38 +- spec/unit/data_types/netlist/ip/v6_spec.rb | 40 +- spec/unit/data_types/netlist/ip_spec.rb | 38 +- spec/unit/data_types/netlist/port_spec.rb | 40 +- spec/unit/data_types/netlist_spec.rb | 38 +- spec/unit/data_types/port/dynamic_spec.rb | 32 +- spec/unit/data_types/port/random_spec.rb | 30 +- spec/unit/data_types/port/system_spec.rb | 32 +- spec/unit/data_types/port/user_spec.rb | 32 +- spec/unit/data_types/port_spec.rb | 32 +- spec/unit/data_types/shadowpass_spec.rb | 16 +- spec/unit/data_types/syslog/cfacility_spec.rb | 36 +- spec/unit/data_types/syslog/cpriority_spec.rb | 36 +- spec/unit/data_types/syslog/cseverity_spec.rb | 36 +- spec/unit/data_types/syslog/facility_spec.rb | 36 +- .../data_types/syslog/lowerfacility_spec.rb | 36 +- .../data_types/syslog/lowerpriority_spec.rb | 36 +- .../data_types/syslog/lowerseverity_spec.rb | 36 +- spec/unit/data_types/syslog/priority_spec.rb | 34 +- spec/unit/data_types/syslog/severity_spec.rb | 36 +- .../data_types/syslog/upperfacility_spec.rb | 36 +- .../data_types/syslog/upperpriority_spec.rb | 36 +- .../data_types/syslog/upperseverity_spec.rb | 36 +- .../data_types/systemd/servicename_spec.rb | 34 +- spec/unit/data_types/umask_spec.rb | 32 +- spec/unit/data_types/uri_spec.rb | 32 +- spec/unit/facter/cmdline_spec.rb | 54 +- spec/unit/facter/defaultgateway_spec.rb | 18 +- spec/unit/facter/defaultgatewayiface_spec.rb | 18 +- spec/unit/facter/fips_ciphers_spec.rb | 7 +- spec/unit/facter/ipa_spec.rb | 114 +-- spec/unit/facter/login_defs_spec.rb | 100 +-- spec/unit/facter/prelink_spec.rb | 51 +- spec/unit/facter/puppet_settings_spec.rb | 51 +- spec/unit/facter/simplib__auditd_spec.rb | 96 +-- spec/unit/facter/simplib__firewalls_spec.rb | 5 +- spec/unit/facter/simplib__mountpoints_spec.rb | 12 +- .../facter/simplib__networkmanager_spec.rb | 83 +-- spec/unit/facter/simplib__numa_spec.rb | 172 ++--- .../simplib__secure_boot_enabled_spec.rb | 26 +- spec/unit/facter/simplib__sshd_config_spec.rb | 258 +++---- .../provider/reboot_notify/notify_spec.rb | 219 +++--- .../puppet/provider/runlevel/systemd_spec.rb | 44 +- .../puppet/provider/runlevel/telinit_spec.rb | 56 +- spec/unit/puppet/type/init_ulimit_spec.rb | 30 +- spec/unit/puppet/type/reboot_notify_spec.rb | 34 +- spec/unit/puppet/type/runlevel_spec.rb | 94 ++- 278 files changed, 5493 insertions(+), 4944 deletions(-) mode change 100644 => 100755 spec/functions/simplib/bracketize_spec.rb mode change 100644 => 100755 spec/functions/simplib/filtered_spec.rb mode change 100644 => 100755 spec/functions/simplib/gen_random_password_spec.rb mode change 100644 => 100755 spec/functions/simplib/host_is_me_spec.rb mode change 100644 => 100755 spec/functions/simplib/ip/family_hash_spec.rb mode change 100644 => 100755 spec/functions/simplib/ip_to_cron_spec.rb mode change 100644 => 100755 spec/functions/simplib/ipaddresses_spec.rb mode change 100644 => 100755 spec/functions/simplib/join_mount_opts_spec.rb mode change 100644 => 100755 spec/functions/simplib/lookup_spec.rb mode change 100644 => 100755 spec/functions/simplib/nets2ddq_spec.rb mode change 100644 => 100755 spec/functions/simplib/passgen/gen_password_and_salt_spec.rb mode change 100644 => 100755 spec/functions/simplib/passgen/gen_salt_spec.rb mode change 100644 => 100755 spec/functions/simplib/passgen/get_spec.rb mode change 100644 => 100755 spec/functions/simplib/passgen/legacy/common_settings_spec.rb mode change 100644 => 100755 spec/functions/simplib/passgen/legacy/get_spec.rb mode change 100644 => 100755 spec/functions/simplib/passgen/legacy/list_spec.rb mode change 100644 => 100755 spec/functions/simplib/passgen/legacy/passgen_spec.rb mode change 100644 => 100755 spec/functions/simplib/passgen/legacy/remove_spec.rb mode change 100644 => 100755 spec/functions/simplib/passgen/legacy/set_spec.rb mode change 100644 => 100755 spec/functions/simplib/passgen/list_spec.rb mode change 100644 => 100755 spec/functions/simplib/passgen/remove_spec.rb mode change 100644 => 100755 spec/functions/simplib/passgen/set_spec.rb mode change 100644 => 100755 spec/functions/simplib/passgen/simpkv/get_spec.rb mode change 100644 => 100755 spec/functions/simplib/passgen/simpkv/list_spec.rb mode change 100644 => 100755 spec/functions/simplib/passgen/simpkv/passgen_spec.rb mode change 100644 => 100755 spec/functions/simplib/passgen/simpkv/remove_spec.rb mode change 100644 => 100755 spec/functions/simplib/passgen/simpkv/root_dir_spec.rb mode change 100644 => 100755 spec/functions/simplib/passgen/simpkv/set_spec.rb mode change 100644 => 100755 spec/functions/simplib/passgen/simpkv/valid_password_info_spec.rb mode change 100644 => 100755 spec/functions/simplib/passgen_spec.rb mode change 100644 => 100755 spec/functions/simplib/rand_cron_spec.rb mode change 100644 => 100755 spec/functions/simplib/simp_version_spec.rb mode change 100644 => 100755 spec/functions/simplib/to_integer_spec.rb mode change 100644 => 100755 spec/functions/simplib/to_string_spec.rb rename spec/functions/simplib/{validate_bool.rb => validate_bool_spec.rb} (86%) mode change 100644 => 100755 spec/unit/puppet/type/init_ulimit_spec.rb mode change 100644 => 100755 spec/unit/puppet/type/reboot_notify_spec.rb mode change 100644 => 100755 spec/unit/puppet/type/runlevel_spec.rb diff --git a/.github/workflows/pr_tests.yml b/.github/workflows/pr_tests.yml index 21ca28c1..bcc5fb01 100644 --- a/.github/workflows/pr_tests.yml +++ b/.github/workflows/pr_tests.yml @@ -35,7 +35,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - - name: "Install Ruby ${{matrix.puppet.ruby_version}}" + - name: "Install Ruby 2.7" uses: ruby/setup-ruby@v1 # ruby/setup-ruby@ec106b438a1ff6ff109590de34ddc62c540232e0 with: ruby-version: 2.7 @@ -47,7 +47,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - - name: "Install Ruby ${{matrix.puppet.ruby_version}}" + - name: "Install Ruby 2.7" uses: ruby/setup-ruby@v1 with: ruby-version: 2.7 @@ -56,13 +56,12 @@ jobs: - run: "bundle exec rake metadata_lint" ruby-style: - if: false # TODO Modules will need: rubocop in Gemfile, .rubocop.yml - name: 'Ruby Style (experimental)' + name: 'Ruby Style' runs-on: ubuntu-latest continue-on-error: true steps: - uses: actions/checkout@v3 - - name: "Install Ruby ${{matrix.puppet.ruby_version}}" + - name: "Install Ruby 2.7" uses: ruby/setup-ruby@v1 with: ruby-version: 2.7 @@ -89,7 +88,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - - name: 'Install Ruby ${{matrix.puppet.ruby_version}}' + - name: 'Install Ruby 2.7' uses: ruby/setup-ruby@v1 with: ruby-version: 2.7 diff --git a/.rubocop.yml b/.rubocop.yml index f960a455..65c8c0ab 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,61 +1,41 @@ --- require: -- rubocop-rspec -- rubocop-i18n + - rubocop-performance + - rubocop-rake + - rubocop-rspec AllCops: + NewCops: enable DisplayCopNames: true - TargetRubyVersion: '2.6' + TargetRubyVersion: "2.7" Include: - - "**/*.rb" + - "**/*.rb" Exclude: - - bin/* - - ".vendor/**/*" - - "**/Gemfile" - - "**/Rakefile" - - pkg/**/* - - spec/fixtures/**/* - - vendor/**/* - - "**/Puppetfile" - - "**/Vagrantfile" - - "**/Guardfile" -Layout/EmptyLinesAroundAttributeAccessor: - Enabled: true + - bin/* + - ".vendor/**/*" + - pkg/**/* + - spec/fixtures/**/* + - vendor/**/* + - "**/Puppetfile" + - "**/Vagrantfile" + - "**/Guardfile" Layout/LineLength: Description: People have wide screens, use them. Max: 200 -Layout/SpaceAroundMethodCallOperator: - Enabled: true -Lint/RaiseException: - Enabled: true -Lint/StructNewOverride: - Enabled: false -I18n/GetText: - Enabled: false -I18n/GetText/DecorateString: - Description: We don't want to decorate test output. - Exclude: - - spec/**/* - Enabled: false -Naming/AccessorMethodName: - Exclude: - - spec/**/* RSpec/BeforeAfterAll: - Description: Beware of using after(:all) as it may cause state to leak between tests. + Description: + Beware of using after(:all) as it may cause state to leak between tests. A necessary evil in acceptance testing. Exclude: - - spec/acceptance/**/*.rb -RSpec/ExpectInHook: - Exclude: - - spec/unit/**/*.rb + - spec/acceptance/**/*.rb RSpec/HookArgument: Description: Prefer explicit :each argument, matching existing module's style EnforcedStyle: each -RSpec/NamedSubject: +RSpec/DescribeSymbol: Exclude: - - spec/classes/**/* - - spec/defines/**/* + - spec/unit/facter/**/*.rb Style/BlockDelimiters: - Description: Prefer braces for chaining. Mostly an aesthetical choice. Better to + Description: + Prefer braces for chaining. Mostly an aesthetical choice. Better to be consistent then. EnforcedStyle: braces_for_chaining Style/ClassAndModuleChildren: @@ -64,49 +44,36 @@ Style/ClassAndModuleChildren: Style/EmptyElse: Description: Enforce against empty else clauses, but allow `nil` for clarity. EnforcedStyle: empty -Style/ExponentialNotation: - Enabled: true Style/FormatString: Description: Following the main puppet project's style, prefer the % format format. EnforcedStyle: percent Style/FormatStringToken: - Description: Following the main puppet project's style, prefer the simpler template + Description: + Following the main puppet project's style, prefer the simpler template tokens over annotated ones. EnforcedStyle: template -Style/HashEachMethods: - Enabled: true -Style/HashSyntax: - Enabled: false -Style/HashTransformKeys: - Enabled: false -Style/HashTransformValues: - Enabled: true Style/Lambda: Description: Prefer the keyword for easier discoverability. EnforcedStyle: literal -Style/MixinUsage: - Exclude: - - spec/**/* -Style/RedundantBegin: - Enabled: false Style/RegexpLiteral: Description: Community preference. See https://github.com/voxpupuli/modulesync_config/issues/168 EnforcedStyle: percent_r Style/TernaryParentheses: - Description: Checks for use of parentheses around ternary conditions. Enforce parentheses + Description: + Checks for use of parentheses around ternary conditions. Enforce parentheses on complex expressions for better readability, but seriously consider breaking it up. EnforcedStyle: require_parentheses_when_complex Style/TrailingCommaInArguments: - Description: Prefer always trailing comma on multiline argument lists. This makes + Description: + Prefer always trailing comma on multiline argument lists. This makes diffs, and re-ordering nicer. EnforcedStyleForMultiline: comma Style/TrailingCommaInArrayLiteral: - Description: Prefer always trailing comma on multiline literals. This makes diffs, + Description: + Prefer always trailing comma on multiline literals. This makes diffs, and re-ordering nicer. EnforcedStyleForMultiline: comma -Style/SlicingWithRange: - Enabled: true Style/SymbolArray: Description: Using percent style obscures symbolic intent of array's contents. EnforcedStyle: brackets @@ -114,30 +81,176 @@ RSpec/MessageSpies: EnforcedStyle: receive Style/Documentation: Exclude: - - lib/puppet/parser/functions/**/* - - spec/**/* + - lib/puppet/parser/functions/**/* + - spec/**/* Style/WordArray: EnforcedStyle: brackets +Performance/AncestorsInclude: + Enabled: true +Performance/BigDecimalWithNumericArgument: + Enabled: true +Performance/BlockGivenWithExplicitBlock: + Enabled: true +Performance/CaseWhenSplat: + Enabled: true +Performance/ConstantRegexp: + Enabled: true +Performance/MethodObjectAsBlock: + Enabled: true +Performance/RedundantSortBlock: + Enabled: true +Performance/RedundantStringChars: + Enabled: true +Performance/ReverseFirst: + Enabled: true +Performance/SortReverse: + Enabled: true +Performance/Squeeze: + Enabled: true +Performance/StringInclude: + Enabled: true +Performance/Sum: + Enabled: true Style/CollectionMethods: Enabled: true Style/MethodCalledOnDoEndBlock: Enabled: true Style/StringMethods: Enabled: true -I18n/GetText/DecorateFunctionMessage: +Bundler/GemFilename: + Enabled: false +Bundler/InsecureProtocolSource: + Enabled: false +Gemspec/DuplicatedAssignment: + Enabled: false +Gemspec/OrderedDependencies: + Enabled: false +Gemspec/RequiredRubyVersion: + Enabled: false +Gemspec/RubyVersionGlobalsUsage: + Enabled: false +Layout/ArgumentAlignment: + Enabled: false +Layout/BeginEndAlignment: + Enabled: false +Layout/ClosingHeredocIndentation: + Enabled: false +Layout/EmptyComment: Enabled: false -I18n/GetText/DecorateStringFormattingUsingInterpolation: +Layout/EmptyLineAfterGuardClause: Enabled: false -I18n/GetText/DecorateStringFormattingUsingPercent: +Layout/EmptyLinesAroundArguments: + Enabled: false +Layout/EmptyLinesAroundAttributeAccessor: Enabled: false Layout/EndOfLine: Enabled: false +Layout/FirstArgumentIndentation: + Enabled: false +Layout/HashAlignment: + Enabled: false Layout/HeredocIndentation: Enabled: false +Layout/LeadingEmptyLines: + Enabled: false +Layout/SpaceAroundMethodCallOperator: + Enabled: false +Layout/SpaceInsideArrayLiteralBrackets: + Enabled: false +Layout/SpaceInsideReferenceBrackets: + Enabled: false +Lint/BigDecimalNew: + Enabled: false +Lint/BooleanSymbol: + Enabled: false +Lint/ConstantDefinitionInBlock: + Enabled: false +Lint/DeprecatedOpenSSLConstant: + Enabled: false +Lint/DisjunctiveAssignmentInConstructor: + Enabled: false +Lint/DuplicateElsifCondition: + Enabled: false +Lint/DuplicateRequire: + Enabled: false +Lint/DuplicateRescueException: + Enabled: false +Lint/EmptyConditionalBody: + Enabled: false +Lint/EmptyFile: + Enabled: false +Lint/ErbNewArguments: + Enabled: false +Lint/FloatComparison: + Enabled: false +Lint/HashCompareByIdentity: + Enabled: false +Lint/IdentityComparison: + Enabled: false +Lint/InterpolationCheck: + Enabled: false +Lint/MissingCopEnableDirective: + Enabled: false +Lint/MixedRegexpCaptureTypes: + Enabled: false +Lint/NestedPercentLiteral: + Enabled: false +Lint/NonDeterministicRequireOrder: + Enabled: false +Lint/OrderedMagicComments: + Enabled: false +Lint/OutOfRangeRegexpRef: + Enabled: false +Lint/RaiseException: + Enabled: false +Lint/RedundantCopEnableDirective: + Enabled: false +Lint/RedundantRequireStatement: + Enabled: false +Lint/RedundantSafeNavigation: + Enabled: false +Lint/RedundantWithIndex: + Enabled: false +Lint/RedundantWithObject: + Enabled: false +Lint/RegexpAsCondition: + Enabled: false +Lint/ReturnInVoidContext: + Enabled: false +Lint/SafeNavigationConsistency: + Enabled: false +Lint/SafeNavigationWithEmpty: + Enabled: false +Lint/SelfAssignment: + Enabled: false +Lint/SendWithMixinArgument: + Enabled: false +Lint/ShadowedArgument: + Enabled: false +Lint/StructNewOverride: + Enabled: false +Lint/ToJSON: + Enabled: false +Lint/TopLevelReturnWithArgument: + Enabled: false +Lint/TrailingCommaInAttributeDeclaration: + Enabled: false +Lint/UnreachableLoop: + Enabled: false +Lint/UriEscapeUnescape: + Enabled: false +Lint/UriRegexp: + Enabled: false +Lint/UselessMethodDefinition: + Enabled: false +Lint/UselessTimes: + Enabled: false Metrics/AbcSize: Enabled: false Metrics/BlockLength: Enabled: false +Metrics/BlockNesting: + Enabled: false Metrics/ClassLength: Enabled: false Metrics/CyclomaticComplexity: @@ -150,21 +263,437 @@ Metrics/ParameterLists: Enabled: false Metrics/PerceivedComplexity: Enabled: false +Migration/DepartmentName: + Enabled: false +Naming/AccessorMethodName: + Enabled: false +Naming/BlockParameterName: + Enabled: false +Naming/HeredocDelimiterCase: + Enabled: false +Naming/HeredocDelimiterNaming: + Enabled: false +Naming/MemoizedInstanceVariableName: + Enabled: false +Naming/MethodParameterName: + Enabled: false +Naming/RescuedExceptionsVariableName: + Enabled: false +Naming/VariableNumber: + Enabled: false +Performance/BindCall: + Enabled: false +Performance/DeletePrefix: + Enabled: false +Performance/DeleteSuffix: + Enabled: false +Performance/InefficientHashSearch: + Enabled: false +Performance/UnfreezeString: + Enabled: false +Performance/UriDefaultParser: + Enabled: false +RSpec/Be: + Enabled: false +RSpec/Dialect: + Enabled: false +RSpec/ContainExactly: + Enabled: false +RSpec/ContextMethod: + Enabled: false +RSpec/ContextWording: + Enabled: false RSpec/DescribeClass: Enabled: false +RSpec/EmptyHook: + Enabled: false +RSpec/EmptyLineAfterExample: + Enabled: false +RSpec/EmptyLineAfterExampleGroup: + Enabled: false +RSpec/EmptyLineAfterHook: + Enabled: false RSpec/ExampleLength: Enabled: false -RSpec/MessageExpectation: +RSpec/ExampleWithoutDescription: + Enabled: false +RSpec/ExpectChange: + Enabled: false +RSpec/ExpectInHook: + Enabled: false +RSpec/HooksBeforeExamples: + Enabled: false +RSpec/ImplicitBlockExpectation: + Enabled: false +RSpec/ImplicitSubject: + Enabled: false +RSpec/LeakyConstantDeclaration: + Enabled: false +RSpec/LetBeforeExamples: + Enabled: false +RSpec/MatchArray: + Enabled: false +RSpec/MissingExampleGroupArgument: Enabled: false RSpec/MultipleExpectations: Enabled: false RSpec/MultipleMemoizedHelpers: Enabled: false +RSpec/MultipleSubjects: + Enabled: false RSpec/NestedGroups: Enabled: false -Style/AsciiComments: +RSpec/PredicateMatcher: + Enabled: false +RSpec/ReceiveCounts: + Enabled: false +RSpec/ReceiveNever: + Enabled: false +RSpec/RepeatedExampleGroupBody: + Enabled: false +RSpec/RepeatedExampleGroupDescription: + Enabled: false +RSpec/RepeatedIncludeExample: + Enabled: false +RSpec/ReturnFromStub: + Enabled: false +RSpec/SharedExamples: + Enabled: false +RSpec/StubbedMock: + Enabled: false +RSpec/UnspecifiedException: + Enabled: false +RSpec/VariableDefinition: + Enabled: false +RSpec/VoidExpect: + Enabled: false +RSpec/Yield: + Enabled: false +Security/Open: + Enabled: false +Style/AccessModifierDeclarations: + Enabled: false +Style/AccessorGrouping: + Enabled: false +Style/BisectedAttrAccessor: + Enabled: false +Style/CaseLikeIf: + Enabled: false +Style/ClassEqualityComparison: + Enabled: false +Style/ColonMethodDefinition: + Enabled: false +Style/CombinableLoops: + Enabled: false +Style/CommentedKeyword: + Enabled: false +Style/Dir: + Enabled: false +Style/DoubleCopDisableDirective: + Enabled: false +Style/EmptyBlockParameter: + Enabled: false +Style/EmptyLambdaParameter: + Enabled: false +Style/Encoding: + Enabled: false +Style/EvalWithLocation: + Enabled: false +Style/ExpandPathArguments: + Enabled: false +Style/ExplicitBlockArgument: + Enabled: false +Style/ExponentialNotation: + Enabled: false +Style/FloatDivision: + Enabled: false +Style/FrozenStringLiteralComment: + Enabled: false +Style/GlobalStdStream: + Enabled: false +Style/HashAsLastArrayItem: + Enabled: false +Style/HashLikeCase: + Enabled: false +Style/HashTransformKeys: + Enabled: false +Style/HashTransformValues: Enabled: false Style/IfUnlessModifier: Enabled: false +Style/KeywordParametersOrder: + Enabled: false +Style/MinMax: + Enabled: false +Style/MixinUsage: + Enabled: false +Style/MultilineWhenThen: + Enabled: false +Style/NegatedUnless: + Enabled: false +Style/NumericPredicate: + Enabled: false +Style/OptionalBooleanParameter: + Enabled: false +Style/OrAssignment: + Enabled: false +Style/RandomWithOffset: + Enabled: false +Style/RedundantAssignment: + Enabled: false +Style/RedundantCondition: + Enabled: false +Style/RedundantConditional: + Enabled: false +Style/RedundantFetchBlock: + Enabled: false +Style/RedundantFileExtensionInRequire: + Enabled: false +Style/RedundantRegexpCharacterClass: + Enabled: false +Style/RedundantRegexpEscape: + Enabled: false +Style/RedundantSelfAssignment: + Enabled: false +Style/RedundantSort: + Enabled: false +Style/RescueStandardError: + Enabled: false +Style/SingleArgumentDig: + Enabled: false +Style/SlicingWithRange: + Enabled: false +Style/SoleNestedConditional: + Enabled: false +Style/StderrPuts: + Enabled: false +Style/StringConcatenation: + Enabled: false +Style/Strip: + Enabled: false Style/SymbolProc: Enabled: false +Style/TrailingBodyOnClass: + Enabled: false +Style/TrailingBodyOnMethodDefinition: + Enabled: false +Style/TrailingBodyOnModule: + Enabled: false +Style/TrailingCommaInHashLiteral: + Enabled: false +Style/TrailingMethodEndStatement: + Enabled: false +Style/UnpackFirst: + Enabled: false +Gemspec/DeprecatedAttributeAssignment: + Enabled: false +Gemspec/DevelopmentDependencies: + Enabled: false +Gemspec/RequireMFA: + Enabled: false +Layout/LineContinuationLeadingSpace: + Enabled: false +Layout/LineContinuationSpacing: + Enabled: false +Layout/LineEndStringConcatenationIndentation: + Enabled: false +Layout/SpaceBeforeBrackets: + Enabled: false +Lint/AmbiguousAssignment: + Enabled: false +Lint/AmbiguousOperatorPrecedence: + Enabled: false +Lint/AmbiguousRange: + Enabled: false +Lint/ConstantOverwrittenInRescue: + Enabled: false +Lint/DeprecatedConstants: + Enabled: false +Lint/DuplicateBranch: + Enabled: false +Lint/DuplicateMagicComment: + Enabled: false +Lint/DuplicateMatchPattern: + Enabled: false +Lint/DuplicateRegexpCharacterClassElement: + Enabled: false +Lint/EmptyBlock: + Enabled: false +Lint/EmptyClass: + Enabled: false +Lint/EmptyInPattern: + Enabled: false +Lint/IncompatibleIoSelectWithFiberScheduler: + Enabled: false +Lint/LambdaWithoutLiteralBlock: + Enabled: false +Lint/NoReturnInBeginEndBlocks: + Enabled: false +Lint/NonAtomicFileOperation: + Enabled: false +Lint/NumberedParameterAssignment: + Enabled: false +Lint/OrAssignmentToConstant: + Enabled: false +Lint/RedundantDirGlobSort: + Enabled: false +Lint/RefinementImportMethods: + Enabled: false +Lint/RequireRangeParentheses: + Enabled: false +Lint/RequireRelativeSelfPath: + Enabled: false +Lint/SymbolConversion: + Enabled: false +Lint/ToEnumArguments: + Enabled: false +Lint/TripleQuotes: + Enabled: false +Lint/UnexpectedBlockArity: + Enabled: false +Lint/UnmodifiedReduceAccumulator: + Enabled: false +Lint/UselessRescue: + Enabled: false +Lint/UselessRuby2Keywords: + Enabled: false +Metrics/CollectionLiteralLength: + Enabled: false +Naming/BlockForwarding: + Enabled: false +Performance/CollectionLiteralInLoop: + Enabled: false +Performance/ConcurrentMonotonicTime: + Enabled: false +Performance/MapCompact: + Enabled: false +Performance/RedundantEqualityComparisonBlock: + Enabled: false +Performance/RedundantSplitRegexpArgument: + Enabled: false +Performance/StringIdentifierArgument: + Enabled: false +RSpec/BeEq: + Enabled: false +RSpec/BeNil: + Enabled: false +RSpec/ChangeByZero: + Enabled: false +RSpec/ClassCheck: + Enabled: false +RSpec/DuplicatedMetadata: + Enabled: false +RSpec/ExcessiveDocstringSpacing: + Enabled: false +RSpec/IdenticalEqualityAssertion: + Enabled: false +RSpec/NoExpectationExample: + Enabled: false +RSpec/PendingWithoutReason: + Enabled: false +RSpec/RedundantAround: + Enabled: false +RSpec/SkipBlockInsideExample: + Enabled: false +RSpec/SortMetadata: + Enabled: false +RSpec/SubjectDeclaration: + Enabled: false +RSpec/VerifiedDoubleReference: + Enabled: false +Security/CompoundHash: + Enabled: false +Security/IoMethods: + Enabled: false +Style/ArgumentsForwarding: + Enabled: false +Style/ArrayIntersect: + Enabled: false +Style/CollectionCompact: + Enabled: false +Style/ComparableClamp: + Enabled: false +Style/ConcatArrayLiterals: + Enabled: false +Style/DataInheritance: + Enabled: false +Style/DirEmpty: + Enabled: false +Style/DocumentDynamicEvalDefinition: + Enabled: false +Style/EmptyHeredoc: + Enabled: false +Style/EndlessMethod: + Enabled: false +Style/EnvHome: + Enabled: false +Style/FetchEnvVar: + Enabled: false +Style/FileEmpty: + Enabled: false +Style/FileRead: + Enabled: false +Style/FileWrite: + Enabled: false +Style/HashConversion: + Enabled: false +Style/HashExcept: + Enabled: false +Style/IfWithBooleanLiteralBranches: + Enabled: false +Style/InPatternThen: + Enabled: false +Style/MagicCommentFormat: + Enabled: false +Style/MapCompactWithConditionalBlock: + Enabled: false +Style/MapToHash: + Enabled: false +Style/MapToSet: + Enabled: false +Style/MinMaxComparison: + Enabled: false +Style/MultilineInPatternThen: + Enabled: false +Style/NegatedIfElseCondition: + Enabled: false +Style/NestedFileDirname: + Enabled: false +Style/NilLambda: + Enabled: false +Style/NumberedParameters: + Enabled: false +Style/NumberedParametersLimit: + Enabled: false +Style/ObjectThen: + Enabled: false +Style/OpenStructUse: + Enabled: false +Style/OperatorMethodCall: + Enabled: false +Style/QuotedSymbols: + Enabled: false +Style/RedundantArgument: + Enabled: false +Style/RedundantConstantBase: + Enabled: false +Style/RedundantDoubleSplatHashBraces: + Enabled: false +Style/RedundantEach: + Enabled: false +Style/RedundantHeredocDelimiterQuotes: + Enabled: false +Style/RedundantInitialize: + Enabled: false +Style/RedundantLineContinuation: + Enabled: false +Style/RedundantSelfAssignmentBranch: + Enabled: false +Style/RedundantStringEscape: + Enabled: false +Style/SelectByRegexp: + Enabled: false +Style/StringChars: + Enabled: false +Style/SwapValues: + Enabled: false diff --git a/CHANGELOG b/CHANGELOG index 33ecf654..b449e2d4 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,6 @@ +* Mon Dec 23 2024 Steven Pritchard - 4.13.0 +- Refactor and cleanup for rubocop + * Fri Dec 13 2024 Steven Pritchard - 4.12.3 - Fix `ipa` fact (#296) diff --git a/Gemfile b/Gemfile index 557a0f0f..c65ff977 100644 --- a/Gemfile +++ b/Gemfile @@ -10,16 +10,23 @@ ENV['PDK_DISABLE_ANALYTICS'] ||= 'true' gem_sources.each { |gem_source| source gem_source } +group :syntax do + gem 'metadata-json-lint' + gem 'puppet-lint-trailing_comma-check', require: false + gem 'rubocop', '~> 1.68.0' + gem 'rubocop-performance', '~> 1.23.0' + gem 'rubocop-rake', '~> 0.6.0' + gem 'rubocop-rspec', '~> 3.2.0' +end + group :test do puppet_version = ENV.fetch('PUPPET_VERSION', ['>= 7', '< 9']) major_puppet_version = Array(puppet_version).first.scan(%r{(\d+)(?:\.|\Z)}).flatten.first.to_i gem 'hiera-puppet-helper' - gem 'metadata-json-lint' gem 'pathspec', '~> 0.2' if Gem::Requirement.create('< 2.6').satisfied_by?(Gem::Version.new(RUBY_VERSION.dup)) gem('pdk', ENV.fetch('PDK_VERSION', ['>= 2.0', '< 4.0']), require: false) if major_puppet_version > 5 gem 'puppet', puppet_version gem 'puppetlabs_spec_helper' - gem 'puppet-lint-trailing_comma-check', require: false gem 'puppet-strings' gem 'rake' gem 'rspec' diff --git a/Gemfile.project b/Gemfile.project index 25811be0..da0288b3 100644 --- a/Gemfile.project +++ b/Gemfile.project @@ -1,8 +1,4 @@ group :test do - gem 'rubocop' - gem 'rubocop-rake' - gem 'rubocop-rspec' - gem 'rubocop-i18n' gem 'super_diff' end diff --git a/REFERENCE.md b/REFERENCE.md index b2509103..85953912 100644 --- a/REFERENCE.md +++ b/REFERENCE.md @@ -39,7 +39,7 @@ * [`simplib::filtered`](#simplib--filtered): Hiera v5 backend that takes a list of allowed hiera key names, and only returns results from the underlying backend function that match those * [`simplib::gen_random_password`](#simplib--gen_random_password): Generates a random password string. Terminates catalog compilation if the password cannot be created in the allotted time. * [`simplib::hash_to_opts`](#simplib--hash_to_opts): Turn a hash into a options string, for use in a shell command -* [`simplib::host_is_me`](#simplib--host_is_me): Detect if a local system identifier hostname/IPv4 address matches a specified hostname/IPv4 address or an entry in a list of hostnames and/o +* [`simplib::host_is_me`](#simplib--host_is_me): Detect if a local system identifier hostname/IPv4 address matches a specified hostname/IPv4 address or an entry in a list of hostnames and/or * [`simplib::in_bolt`](#simplib--in_bolt): Returns ``true`` if the run is active inside of Bolt and ``false`` otherwise. Presently, this function is extremely basic. However, this che * [`simplib::inspect`](#simplib--inspect): Prints the passed variable's Ruby type and value for debugging purposes This uses a ``Notify`` resource to print the information during the * [`simplib::ip::family_hash`](#simplib--ip--family_hash): Process an array of IP addresses and return them split by IP family and include metadata and/or processed versions. @@ -295,7 +295,7 @@ The following parameters are available in the `ftpusers` type. Entries to always add to the file -Default value: `['nobody','nfsnobody']` +Default value: `['nobody', 'nfsnobody']` ##### `min_id` @@ -380,7 +380,7 @@ Default value: `present` ##### `value` -Valid values: `hard`, `soft`, `unlimited`, `/^\d+$/` +Valid values: `hard`, `soft`, `unlimited`, `%r{^\d+$}` The value to which to set the new limit. @@ -570,7 +570,7 @@ The following properties are available in the `runlevel` type. ##### `level` -Valid values: `/^[1-5]$/`, `rescue`, `multi-user`, `graphical`, `default` +Valid values: `%r{^[1-5]$}`, `rescue`, `multi-user`, `graphical`, `default` The target runlevel of the system. Defaults to what is specified in :name @@ -594,7 +594,7 @@ The following parameters are available in the `runlevel` type. ##### `name` -Valid values: `/^[1-5]$/`, `rescue`, `multi-user`, `graphical` +Valid values: `%r{^[1-5]$}`, `rescue`, `multi-user`, `graphical` namevar @@ -607,7 +607,7 @@ discover the appropriate provider for your platform. ##### `transition_timeout` -Valid values: `/^\d+$/` +Valid values: `%r{^\d+$}` How many seconds to wait for a runlevel switch before failing @@ -623,7 +623,7 @@ The following properties are available in the `script_umask` type. ##### `umask` -Valid values: `/^[0-7]{3,4}$/` +Valid values: `%r{^[0-7]{3,4}$}` The umask that should be set in the target file. @@ -1597,7 +1597,7 @@ Options hash. It only takes 3 keys, none of them required: Type: Ruby 4.x API Detect if a local system identifier hostname/IPv4 address matches -a specified hostname/IPv4 address or an entry in a list of +a specified hostname/IPv4 address or an entry in a list of hostnames and/or IPv4 addresses #### `simplib::host_is_me(Simplib::Host $host)` @@ -1729,11 +1729,13 @@ include metadata and/or processed versions. ```puppet -simplib::ip::family_hash([ - '1.2.3.4', - '2.3.4.5/8', - '::1' -]) +simplib::ip::family_hash( + [ + '1.2.3.4', + '2.3.4.5/8', + '::1', + ] +) Returns (YAML Formatted for clarity) @@ -1794,11 +1796,13 @@ ipv6: ```puppet -simplib::ip::family_hash([ - '1.2.3.4', - '2.3.4.5/8', - '::1' -]) +simplib::ip::family_hash( + [ + '1.2.3.4', + '2.3.4.5/8', + '::1', + ] +) Returns (YAML Formatted for clarity) @@ -2051,7 +2055,7 @@ $ldap_dn = simplib::ldap::domain_to_dn('test.local', true) returns $ldap_dn = 'dc=test,dc=local' ``` -#### `simplib::ldap::domain_to_dn(String $domain = $facts['domain'], Boolean $downcase_attributes = false)` +#### `simplib::ldap::domain_to_dn(String $domain = $facts['networking']['domain'], Boolean $downcase_attributes = false)` Generates a LDAP Base DN from a domain @@ -2608,11 +2612,13 @@ into a structured `Hash` of host information. ```puppet -simplib::parse_hosts([ - '1.2.3.4', - 'http://1.2.3.4', - 'https://1.2.3.4:443' -]) +simplib::parse_hosts( + [ + '1.2.3.4', + 'http://1.2.3.4', + 'https://1.2.3.4:443', + ] +) Returns: @@ -2621,9 +2627,9 @@ Returns: :ports => ['443'], :protocols => { 'http' => [], - 'https' => ['443'] - } - } + 'https' => ['443'], + }, + }, } ``` @@ -2653,11 +2659,13 @@ Raises: ```puppet -simplib::parse_hosts([ - '1.2.3.4', - 'http://1.2.3.4', - 'https://1.2.3.4:443' -]) +simplib::parse_hosts( + [ + '1.2.3.4', + 'http://1.2.3.4', + 'https://1.2.3.4:443', + ] +) Returns: @@ -2666,9 +2674,9 @@ Returns: :ports => ['443'], :protocols => { 'http' => [], - 'https' => ['443'] - } - } + 'https' => ['443'], + }, + }, } ``` diff --git a/lib/facter/acpid_enabled.rb b/lib/facter/acpid_enabled.rb index f30271d9..d1acef92 100644 --- a/lib/facter/acpid_enabled.rb +++ b/lib/facter/acpid_enabled.rb @@ -2,8 +2,8 @@ # # Return true if ACPI is available on the system. # -if Facter.value(:kernel).downcase == "linux" then - Facter.add("acpid_enabled") do +if Facter.value(:kernel).downcase == 'linux' + Facter.add('acpid_enabled') do setcode do File.exist?('/proc/acpi/event') end diff --git a/lib/facter/boot_dir_uuid.rb b/lib/facter/boot_dir_uuid.rb index efbfa6df..91a5ee85 100644 --- a/lib/facter/boot_dir_uuid.rb +++ b/lib/facter/boot_dir_uuid.rb @@ -3,18 +3,17 @@ @df_cmd = Facter::Util::Resolution.which('df') @blkid_cmd = Facter::Util::Resolution.which('blkid') - confine :kernel => 'Linux' + confine kernel: 'Linux' confine { File.exist?('/boot') } confine { !@df_cmd.nil? } confine { !@blkid_cmd.nil? } setcode do - partition = Facter::Core::Execution.exec("#{@df_cmd} -P /boot").strip.split("\n").last.split(' ').first uuid = Facter::Core::Execution.exec("#{@blkid_cmd} -s UUID -o value #{partition}").strip - uuid = nil if (uuid.nil? || uuid.empty?) + uuid = nil if uuid.nil? || uuid.empty? uuid end diff --git a/lib/facter/cmdline.rb b/lib/facter/cmdline.rb index 08e42f98..a318176c 100644 --- a/lib/facter/cmdline.rb +++ b/lib/facter/cmdline.rb @@ -7,13 +7,13 @@ retval = {} begin File.read('/proc/cmdline').chomp.split.each do |x| - i,j = x.split('=') + i, j = x.split('=') - if retval.has_key?(i) - retval[i] = [retval[i], j].flatten() - else - retval[i] = j - end + retval[i] = if retval.key?(i) + [retval[i], j].flatten + else + j + end end rescue => details Facter.warn("Could not gather data from /proc/cmdline: #{details.message}") diff --git a/lib/facter/cpuinfo.rb b/lib/facter/cpuinfo.rb index a534111e..f46624fe 100644 --- a/lib/facter/cpuinfo.rb +++ b/lib/facter/cpuinfo.rb @@ -9,27 +9,27 @@ setcode do retval = {} begin - File.read('/proc/cpuinfo').split(/^\s*$/).each do |section| - procinfo = section.split("\n").map{|x| x = x.split(':').map(&:strip)} + File.read('/proc/cpuinfo').split(%r{^\s*$}).each do |section| + procinfo = section.split("\n").map { |x| x.split(':').map(&:strip) } - entry_hash = {} - procinfo.each do |entry| - next if (!entry || entry.empty?) + entry_hash = {} + procinfo.each do |entry| + next if !entry || entry.empty? - key = entry.first.gsub(/\s+/,'_') - value = entry.last + key = entry.first.gsub(%r{\s+}, '_') + value = entry.last - if key == 'flags' - value = value.split(/\s+/) - end + if key == 'flags' + value = value.split(%r{\s+}) + end - entry_hash[key] = value - end + entry_hash[key] = value + end - proc_id = entry_hash.delete('processor') + proc_id = entry_hash.delete('processor') - retval[%(processor#{proc_id})] = entry_hash - end + retval[%(processor#{proc_id})] = entry_hash + end rescue => details Facter.warn("Could not gather data from /proc/cpuinfo: #{details.message}") end diff --git a/lib/facter/defaultgateway.rb b/lib/facter/defaultgateway.rb index 522da319..a224f673 100644 --- a/lib/facter/defaultgateway.rb +++ b/lib/facter/defaultgateway.rb @@ -3,16 +3,16 @@ # Return the default IPv4 gateway of the system # Facter.add(:defaultgateway) do - confine :kernel => 'Linux' + confine kernel: 'Linux' setcode do - gw = "unknown" + gw = 'unknown' ip_cmd = Facter::Util::Resolution.which('ip') if ip_cmd route_lines = Facter::Core::Execution.exec("#{ip_cmd} route").split("\n") - gw_lines = route_lines.delete_if { |line| !line.match(/^default\s+via\s+/) } + gw_lines = route_lines.delete_if { |line| !line.match(%r{^default\s+via\s+}) } unless gw_lines.empty? - match = gw_lines.last.match(/default\s+via\s+([0-9\.]*)\s+dev\s+/) + match = gw_lines.last.match(%r{default\s+via\s+([0-9\.]*)\s+dev\s+}) if match gw = match[1] end diff --git a/lib/facter/defaultgatewayiface.rb b/lib/facter/defaultgatewayiface.rb index 2c5122f0..51e3d23e 100644 --- a/lib/facter/defaultgatewayiface.rb +++ b/lib/facter/defaultgatewayiface.rb @@ -3,16 +3,16 @@ # Return the default IPv4 gw interface of the system. # Facter.add(:defaultgatewayiface) do - confine :kernel => 'Linux' + confine kernel: 'Linux' setcode do - gw_iface = "unknown" + gw_iface = 'unknown' ip_cmd = Facter::Util::Resolution.which('ip') if ip_cmd route_lines = Facter::Core::Execution.exec("#{ip_cmd} route").split("\n") - gw_lines = route_lines.delete_if { |line| !line.match(/^default\s+via\s+/) } + gw_lines = route_lines.delete_if { |line| !line.match(%r{^default\s+via\s+}) } unless gw_lines.empty? - match = gw_lines.last.match(/\s+dev\s+(\S+)/) + match = gw_lines.last.match(%r{\s+dev\s+(\S+)}) if match gw_iface = match[1] end diff --git a/lib/facter/fips_ciphers.rb b/lib/facter/fips_ciphers.rb index 05f6429c..53490aa0 100644 --- a/lib/facter/fips_ciphers.rb +++ b/lib/facter/fips_ciphers.rb @@ -1,8 +1,7 @@ # List available FIPS-compatible OpenSSL ciphers on the system # Returns: Array[String] Facter.add('fips_ciphers') do - - confine :kernel => 'Linux' + confine kernel: 'Linux' openssl_bin = Facter::Core::Execution.which('openssl') setcode do diff --git a/lib/facter/fips_enabled.rb b/lib/facter/fips_enabled.rb index 21d48847..6e330d48 100644 --- a/lib/facter/fips_enabled.rb +++ b/lib/facter/fips_enabled.rb @@ -5,7 +5,7 @@ # if it's not present. if Facter.value('fips_enabled').nil? Facter.add('fips_enabled') do - confine :kernel => 'Linux' + confine kernel: 'Linux' setcode do status_file = '/proc/sys/crypto/fips_enabled' diff --git a/lib/facter/fullrun.rb b/lib/facter/fullrun.rb index f78bd2d9..faab4648 100644 --- a/lib/facter/fullrun.rb +++ b/lib/facter/fullrun.rb @@ -6,10 +6,9 @@ # which it was created. # -Facter.add("fullrun") do - confine :kernel => :linux - setcode do - %x{if [ -f /root/.fullrun ]; then echo "true"; else echo "false"; fi}.chomp - end +Facter.add('fullrun') do + confine kernel: :linux + setcode do + `if [ -f /root/.fullrun ]; then echo "true"; else echo "false"; fi`.chomp + end end - diff --git a/lib/facter/gdm_version.rb b/lib/facter/gdm_version.rb index 6078188e..b6b92349 100644 --- a/lib/facter/gdm_version.rb +++ b/lib/facter/gdm_version.rb @@ -3,9 +3,9 @@ # Set a fact to return the version of GDM that is installed. # This is useful for applying the correct configuration file syntax. # -Facter.add("gdm_version") do - confine { File.exist?('/usr/sbin/gdm') && File.executable?("/usr/sbin/gdm") } +Facter.add('gdm_version') do + confine { File.exist?('/usr/sbin/gdm') && File.executable?('/usr/sbin/gdm') } setcode do - %x{/usr/sbin/gdm --version}.chomp.split(/\s+/)[1] + `/usr/sbin/gdm --version`.chomp.split(%r{\s+})[1] end end diff --git a/lib/facter/ipa.rb b/lib/facter/ipa.rb index df7e73a1..84c6737a 100644 --- a/lib/facter/ipa.rb +++ b/lib/facter/ipa.rb @@ -18,7 +18,7 @@ # Returns nil otherwise # Facter.add(:ipa) do - confine :kernel => 'Linux' + confine kernel: 'Linux' kinit = Facter::Core::Execution.which('kinit') confine { kinit } @@ -35,7 +35,7 @@ # In EL8 the ipa command needs LC_ALL set to UTF-8 and this is the only # workaround at this time locale = ENV.fetch('LANG', 'en_US.UTF-8') - locale = 'en_US.UTF-8' unless locale.match?(/UTF-?8/i) + locale = 'en_US.UTF-8' unless locale.match?(%r{UTF-?8}i) ipacmd = "#{truecmd} && LC_ALL=#{locale} #{ipa}" # This file is only present if the host has, at some time, @@ -48,23 +48,21 @@ 'server', 'realm', 'basedn', - 'tls_ca_cert' + 'tls_ca_cert', ] - file_defaults = File.read('/etc/ipa/default.conf').lines. - map(&:strip). - map{ |x| - x.split(/\s*=\s*(.*)/) - }.delete_if{|x| - x.size < 2 - }.flatten + file_defaults = File.read('/etc/ipa/default.conf').lines + .map(&:strip) + .map { |x| x.split(%r{\s*=\s*(.*)}) } + .delete_if { |x| x.size < 2 } + .flatten ipa_timeout = 30 kinit_timeout = 10 defaults = Hash[*file_defaults] - defaults.delete_if { |k,v| !needed_keys.include?(k) } + defaults.delete_if { |k, _v| !needed_keys.include?(k) } # We won't know if we are connected to a server until later defaults['connected'] = false @@ -72,30 +70,30 @@ klist_retval = Puppet::Util::Execution.execute("#{klist} -s", fail_on_fail: false) unless klist_retval.exitstatus.zero? # Obtain host Kerberos token so we can use IPA API - kinit_msg = Facter::Core::Execution.execute("#{kinit} -k 2>&1", options = {:timeout => kinit_timeout}) + Facter::Core::Execution.execute("#{kinit} -k 2>&1", { timeout: kinit_timeout }) end # Grab the necessary information from 'ipa env' - ipa_response = Facter::Core::Execution.execute("#{ipacmd} env #{needed_keys.join(' ')}", options = {:timeout => ipa_timeout}) + ipa_response = Facter::Core::Execution.execute("#{ipacmd} env #{needed_keys.join(' ')}", { timeout: ipa_timeout }) if ipa_response.strip.empty? ipa_response = {} else - ipa_server_response = Facter::Core::Execution.execute("#{ipacmd} env --server host", options = {:timeout => ipa_timeout}) + ipa_server_response = Facter::Core::Execution.execute("#{ipacmd} env --server host", { timeout: ipa_timeout }) defaults['connected'] = !ipa_server_response.strip.empty? - ipa_response = ipa_response.lines.grep(/\S:\s*.+/).map(&:strip). - map{ |x| - x.split(/:\s+(.*)/) - }.flatten + ipa_response = ipa_response.lines.grep(%r{\S:\s*.+}).map(&:strip) + .map { |x| + x.split(%r{:\s+(.*)}) + }.flatten ipa_response = Hash[*ipa_response] ipa_response.keys.each do |key| # Some patch up work for EL6 - if key =~ /^<(.+)>$/ - ipa_response[$1] = ipa_response.delete(key) + if key =~ %r{^<(.+)>$} + ipa_response[Regexp.last_match(1)] = ipa_response.delete(key) end end end diff --git a/lib/facter/ipv6_enabled.rb b/lib/facter/ipv6_enabled.rb index 33f423f9..dc2d177f 100644 --- a/lib/facter/ipv6_enabled.rb +++ b/lib/facter/ipv6_enabled.rb @@ -3,8 +3,9 @@ # Return true if IPv6 is enabled and false if not. # Known to work on 2.4.6 kernels. # -Facter.add("ipv6_enabled") do - confine :kernel => 'Linux' +require 'English' +Facter.add('ipv6_enabled') do + confine kernel: 'Linux' setcode do retval = false ipv6_enabled = Facter::Core::Execution.exec('/sbin/sysctl -n -e net.ipv6.conf.all.disable_ipv6 2>/dev/null') @@ -14,9 +15,8 @@ # Facter.*.exec. # # For now we test around the issue by checking the output if $? is nil: - if ($?.nil? && ipv6_enabled) || - (!$?.nil? && $?.exitstatus.zero? && ipv6_enabled.chomp == "0") - then + if ($CHILD_STATUS.nil? && ipv6_enabled) || + (!$CHILD_STATUS.nil? && $CHILD_STATUS.exitstatus.zero? && ipv6_enabled.chomp == '0') retval = true end diff --git a/lib/facter/login_defs.rb b/lib/facter/login_defs.rb index 25ce03e4..0e9cb2b6 100644 --- a/lib/facter/login_defs.rb +++ b/lib/facter/login_defs.rb @@ -6,11 +6,14 @@ end setcode do - - attribute_hash = File.read('/etc/login.defs').lines. - delete_if{|x| x =~ /^\s*(#|$)/}. - map{|x| x = x.split(/\s+/); x[0].downcase!; x}. - to_h + attribute_hash = File.read('/etc/login.defs').lines + .delete_if { |x| x =~ %r{^\s*(#|$)} } + .map { |x| + x = x.split(%r{\s+}) + x[0].downcase! + x + } + .to_h attribute_hash.each do |k, v| # We have a few special cases to take care of @@ -23,7 +26,7 @@ attribute_hash[k] = true elsif v == 'no' attribute_hash[k] = false - elsif v =~ /^\d+$/ + elsif %r{^\d+$}.match?(v) attribute_hash[k] = v.to_i end end diff --git a/lib/facter/prelink.rb b/lib/facter/prelink.rb index 2e829e6b..aaab9319 100644 --- a/lib/facter/prelink.rb +++ b/lib/facter/prelink.rb @@ -5,18 +5,18 @@ # Prelink is considered to be be disabled if /etc/sysconfig/prelink # does not exist, the PRELINKING variable in /etc/sysconfig/prelink # is not set to 'yes', or the PRELINKING variable is missing from -# /etc/sysconfig/prelink. This logic reflects how the PRELINKING +# /etc/sysconfig/prelink. This logic reflects how the PRELINKING # variable is used in /etc/cron.hourly/prelink. # Facter.add(:prelink) do - confine :kernel => 'Linux' + confine kernel: 'Linux' confine { Facter::Core::Execution.which('prelink') } setcode do prelink_enabled = false if File.exist?('/etc/sysconfig/prelink') - prelink_enabled = !(File.read('/etc/sysconfig/prelink') =~ /^\s*PRELINKING=yes\s*$/).nil? + prelink_enabled = !(File.read('/etc/sysconfig/prelink') =~ %r{^\s*PRELINKING=yes\s*$}).nil? end { 'enabled' => prelink_enabled } diff --git a/lib/facter/reboot_required.rb b/lib/facter/reboot_required.rb index 426ee0ec..cd39bb48 100644 --- a/lib/facter/reboot_required.rb +++ b/lib/facter/reboot_required.rb @@ -13,12 +13,10 @@ setcode do retval = {} - Dir.glob("/var/run/puppet/reboot_triggers/*").each do |trigger| - begin - retval[File.basename(trigger)] = File.read(trigger).strip - rescue => details - Facter.warn("Could not read #{trigger}: #{details.message}") - end + Dir.glob('/var/run/puppet/reboot_triggers/*').each do |trigger| + retval[File.basename(trigger)] = File.read(trigger).strip + rescue => details + Facter.warn("Could not read #{trigger}: #{details.message}") end retval = false if retval.empty? diff --git a/lib/facter/root_dir_uuid.rb b/lib/facter/root_dir_uuid.rb index fd5334c7..b0cde691 100644 --- a/lib/facter/root_dir_uuid.rb +++ b/lib/facter/root_dir_uuid.rb @@ -1,6 +1,6 @@ # Return the UUID of the partition holding the / directory Facter.add('root_dir_uuid') do - confine :kernel => 'Linux' + confine kernel: 'Linux' setcode do df_cmd = Facter::Util::Resolution.which('df') @@ -10,7 +10,7 @@ uuid = Facter::Core::Execution.exec("#{blkid_cmd} -s UUID -o value #{partition}").strip - uuid = nil if (uuid.nil? || uuid.empty?) + uuid = nil if uuid.nil? || uuid.empty? uuid end diff --git a/lib/facter/runlevel.rb b/lib/facter/runlevel.rb index 1d16fbc7..a5acf994 100644 --- a/lib/facter/runlevel.rb +++ b/lib/facter/runlevel.rb @@ -3,9 +3,9 @@ # # Return the current system runlevel # -Facter.add("runlevel") do - confine :kernel => 'Linux' +Facter.add('runlevel') do + confine kernel: 'Linux' setcode do - %x{"/sbin/runlevel"}.split.last + `"/sbin/runlevel"`.split.last end end diff --git a/lib/facter/shmall.rb b/lib/facter/shmall.rb index 219428be..4fdf31b6 100644 --- a/lib/facter/shmall.rb +++ b/lib/facter/shmall.rb @@ -2,10 +2,9 @@ # # Return the value of shmall from sysctl. # -Facter.add("shmall") do - confine :kernel => 'Linux' +Facter.add('shmall') do + confine kernel: 'Linux' setcode do - %x{/sbin/sysctl -n kernel.shmall}.strip + `/sbin/sysctl -n kernel.shmall`.strip end end - diff --git a/lib/facter/simp_puppet_settings.rb b/lib/facter/simp_puppet_settings.rb index 3b6c0ac0..b64891e1 100644 --- a/lib/facter/simp_puppet_settings.rb +++ b/lib/facter/simp_puppet_settings.rb @@ -15,8 +15,8 @@ retval[section.to_s] ||= {} section_values = Puppet.settings.values(nil, section) loader_settings = { - :environmentpath => section_values.interpolate(:environmentpath), - :basemodulepath => section_values.interpolate(:basemodulepath) + environmentpath: section_values.interpolate(:environmentpath), + basemodulepath: section_values.interpolate(:basemodulepath) } # Temporarily override Puppet's run_mode to evaluate this session: @@ -27,7 +27,7 @@ # (in particular, $vardir), and won't agree with `puppet config --section` Puppet.override( Puppet.base_context(loader_settings), - "New loader for facter to inspect section '#{section}' ." + "New loader for facter to inspect section '#{section}' .", ) do # NOW we can lookup values as configured from the section: values = Puppet.settings.values(Puppet[:environment].to_sym, section) diff --git a/lib/facter/simplib__auditd.rb b/lib/facter/simplib__auditd.rb index 59117d6a..48aaa97b 100644 --- a/lib/facter/simplib__auditd.rb +++ b/lib/facter/simplib__auditd.rb @@ -14,7 +14,7 @@ # } # Facter.add('simplib__auditd') do - confine :kernel => 'Linux' + confine kernel: 'Linux' @auditctl = Facter::Util::Resolution.which('auditctl') @ps = Facter::Util::Resolution.which('ps') @@ -29,9 +29,9 @@ 'enabled' => 0 } - audit_version = Facter::Core::Execution.exec("#{@auditctl} -v").split(/\s+/).last + audit_version = Facter::Core::Execution.exec("#{@auditctl} -v").split(%r{\s+}).last - status['version'] = audit_version if (audit_version && !audit_version.empty?) + status['version'] = audit_version if audit_version && !audit_version.empty? auditctl_status = {} @@ -40,7 +40,7 @@ next if l.empty? - k,v = l.split(/\s+/, 2) + k, v = l.split(%r{\s+}, 2) begin v = Integer(v) @@ -52,16 +52,16 @@ end status = status.merge(auditctl_status) - status['enabled'] = status['enabled'] == 1 ? true : false + status['enabled'] = (status['enabled'] == 1) ? true : false if status['enabled'] status['kernel_enforcing'] = true procs = Facter::Core::Execution.exec("#{@ps} -e").lines - status['enforcing'] = procs.any?{|x| x =~ /\sauditd\Z/} + status['enforcing'] = procs.any? { |x| x =~ %r{\sauditd\Z} } else cmdline = Facter.value('cmdline') || {} - status['kernel_enforcing'] = ("#{cmdline['audit']}" == '1') + status['kernel_enforcing'] = ((cmdline['audit']).to_s == '1') end status diff --git a/lib/facter/simplib__efi_enabled.rb b/lib/facter/simplib__efi_enabled.rb index 589fe4b8..a5de64c1 100644 --- a/lib/facter/simplib__efi_enabled.rb +++ b/lib/facter/simplib__efi_enabled.rb @@ -2,8 +2,8 @@ # # Return true if system booted via EFI # -Facter.add("simplib__efi_enabled") do - confine :kernel => 'Linux' +Facter.add('simplib__efi_enabled') do + confine kernel: 'Linux' setcode do File.exist?('/sys/firmware/efi') diff --git a/lib/facter/simplib__firewalls.rb b/lib/facter/simplib__firewalls.rb index ec340e5e..1e39f909 100644 --- a/lib/facter/simplib__firewalls.rb +++ b/lib/facter/simplib__firewalls.rb @@ -20,7 +20,7 @@ 'ipfw' => nil, 'nft' => nil, 'pf' => { - :command => 'pfctl' + command: 'pfctl' } } diff --git a/lib/facter/simplib__mountpoints.rb b/lib/facter/simplib__mountpoints.rb index 68ab0f6c..d0406bb6 100644 --- a/lib/facter/simplib__mountpoints.rb +++ b/lib/facter/simplib__mountpoints.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true + # # This fact provides information about select mountpoints that are of interest # to other SIMP modules. @@ -39,7 +40,7 @@ require 'facter' Facter.add('simplib__mountpoints') do - confine :kernel => :Linux + confine kernel: :Linux confine { File.exist?('/proc/mounts') } setcode do @@ -51,7 +52,7 @@ facter_mountpoints = Facter.value('mountpoints') || {} # Sometimes Ruby has issues with /proc so fall back to a shell command - Facter::Core::Execution.execute('cat /proc/mounts 2> /dev/null', :on_fail => nil).each_line do |line| + Facter::Core::Execution.execute('cat /proc/mounts 2> /dev/null', on_fail: nil).each_line do |line| line.strip! next if line.empty? || line.match(%r{^\s+none\s+}) @@ -75,8 +76,6 @@ else mount_list[path] = path_settings end - - end # Lookup table so we don't constantly lookup found UIDs and GIDs, etc... @@ -88,7 +87,7 @@ mount_list[mnt]['options'] ||= [] unless mount_list[mnt]['options'].include?('bind') - findmnt_output = Facter::Core::Execution.execute("findmnt #{mnt}", :on_fail => nil) + findmnt_output = Facter::Core::Execution.execute("findmnt #{mnt}", on_fail: nil) if findmnt_output mnt_source = findmnt_output.lines.last.split(%r{\s+})[1] diff --git a/lib/facter/simplib__networkmanager.rb b/lib/facter/simplib__networkmanager.rb index de67762d..95f31061 100644 --- a/lib/facter/simplib__networkmanager.rb +++ b/lib/facter/simplib__networkmanager.rb @@ -1,5 +1,5 @@ Facter.add(:simplib__networkmanager) do - confine :kernel => 'Linux' + confine kernel: 'Linux' @nmcli_cmd = Facter::Util::Resolution.which('nmcli') confine { @nmcli_cmd } @@ -12,7 +12,7 @@ general_status = Puppet::Util::Execution.execute(%(#{nmcli_cmd} -m multiline general status)) if general_status.exitstatus.zero? - general_status = general_status.lines.map{|line| line.strip.split(':') } + general_status = general_status.lines.map { |line| line.strip.split(':') } info['enabled'] = true info = { @@ -22,7 +22,7 @@ } end - general_hostname = Puppet::Util::Execution.execute(%{#{nmcli_cmd} general hostname}) + general_hostname = Puppet::Util::Execution.execute(%(#{nmcli_cmd} general hostname)) if general_hostname.exitstatus.zero? info['enabled'] = true diff --git a/lib/facter/simplib__numa.rb b/lib/facter/simplib__numa.rb index 105a2c7a..98325c93 100644 --- a/lib/facter/simplib__numa.rb +++ b/lib/facter/simplib__numa.rb @@ -4,7 +4,7 @@ # and a memory mapping layout # Facter.add('simplib__numa') do - confine :kernel => 'Linux' + confine kernel: 'Linux' confine { File.exist? '/sys/devices/system/node' } setcode do @@ -22,16 +22,16 @@ end require 'pathname' - Dir.glob('/sys/devices/system/node/node*').each do | file | + Dir.glob('/sys/devices/system/node/node*').each do |file| meminfo_file = Pathname.new(File.join(file, 'meminfo')) next unless meminfo_file.exist? nodename = File.basename(file) result['nodes'].push(nodename) - File.foreach(meminfo_file) do | text | - if text =~ /\sMemTotal:\s+(\d+)/ + File.foreach(meminfo_file) do |text| + if text =~ %r{\sMemTotal:\s+(\d+)} result[nodename] ||= {} - result[nodename]['MemTotalBytes'] = ($1.to_i * 1024) + result[nodename]['MemTotalBytes'] = (Regexp.last_match(1).to_i * 1024) end end end diff --git a/lib/facter/simplib__secure_boot_enabled.rb b/lib/facter/simplib__secure_boot_enabled.rb index 99de074f..4e03b874 100644 --- a/lib/facter/simplib__secure_boot_enabled.rb +++ b/lib/facter/simplib__secure_boot_enabled.rb @@ -2,19 +2,19 @@ # # Return true if system booted via UEFI Secure Boot # -Facter.add("simplib__secure_boot_enabled") do - confine :kernel => 'Linux' +Facter.add('simplib__secure_boot_enabled') do + confine kernel: 'Linux' setcode do secure_boot_status = false - Dir.glob('/sys/firmware/efi/efivars/SecureBoot-*').each do | file | + Dir.glob('/sys/firmware/efi/efivars/SecureBoot-*').each do |file| begin - File.open(file, 'r') do | hexcode | + File.open(file, 'r') do |hexcode| # skip leading status codes hexcode.read(4) - code = hexcode.read() + code = hexcode.read # If we didn't get any data, unpacking will fail - secure_boot_status = (1 == code.unpack('H*').first.to_i) if code + secure_boot_status = (code.unpack('H*').first.to_i == 1) if code end rescue Errno::EPERM, Errno::EACCES next @@ -25,14 +25,14 @@ setup_mode_status = false if secure_boot_status - Dir.glob('/sys/firmware/efi/efivars/SetupMode-*').each do | file | + Dir.glob('/sys/firmware/efi/efivars/SetupMode-*').each do |file| begin - File.open(file, 'r') do | hexcode | + File.open(file, 'r') do |hexcode| # skip leading status codes hexcode.read(4) - code = hexcode.read() + code = hexcode.read # If we didn't get any data, unpacking will fail - setup_mode_status = (0 == code.unpack('H*').first.to_i) if code + setup_mode_status = (code.unpack('H*').first.to_i == 0) if code end rescue Errno::EPERM, Errno::EACCES next diff --git a/lib/facter/simplib__sshd_config.rb b/lib/facter/simplib__sshd_config.rb index a4c58389..0a3f69a3 100644 --- a/lib/facter/simplib__sshd_config.rb +++ b/lib/facter/simplib__sshd_config.rb @@ -3,10 +3,9 @@ # Return values from the /etc/ssh/sshd_conf file # Facter.add('simplib__sshd_config') do - confine { File.exist?('/etc/ssh/sshd_config') && File.readable?('/etc/ssh/sshd_config')} + confine { File.exist?('/etc/ssh/sshd_config') && File.readable?('/etc/ssh/sshd_config') } setcode do - # Items that we wish to pull from the configuration # # Format: @@ -17,15 +16,15 @@ sshd = Facter::Util::Resolution.which('sshd') if sshd - full_version = Facter::Core::Execution.execute("#{sshd} -. 2>&1", :on_fail => :failed) + full_version = Facter::Core::Execution.execute("#{sshd} -. 2>&1", on_fail: :failed) unless full_version == :failed sshd_config ||= {} - full_version = full_version.lines.grep(/^\s*OpenSSH_\d/).first + full_version = full_version.lines.grep(%r{^\s*OpenSSH_\d}).first if full_version - sshd_config['version'] = full_version.split(/,|\s/).first.split('_').last + sshd_config['version'] = full_version.split(%r{,|\s}).first.split('_').last sshd_config['full_version'] = full_version end end @@ -41,7 +40,7 @@ next if line.empty? next if line[0].chr == '#' - if config_parts = line.match(/^(?:(?.+?))\s+(?.+)\s*$/) + if (config_parts = line.match(%r{^(?:(?.+?))\s+(?.+)\s*$})) if config_parts[:key] == 'Match' match_section = line next @@ -49,8 +48,8 @@ next unless selected_settings.keys.include?(config_parts[:key]) + sshd_config ||= {} if match_section - sshd_config ||= {} sshd_config[match_section] ||= {} if sshd_config[match_section][config_parts[:key]] @@ -59,15 +58,12 @@ else sshd_config[match_section][config_parts[:key]] = config_parts[:value] end - else - sshd_config ||= {} + elsif sshd_config[config_parts[:key]] - if sshd_config[config_parts[:key]] - sshd_config[config_parts[:key]] = Array(sshd_config[config_parts[:key]]) - sshd_config[config_parts[:key]] << config_parts[:value] - else - sshd_config[config_parts[:key]] = config_parts[:value] - end + sshd_config[config_parts[:key]] = Array(sshd_config[config_parts[:key]]) + sshd_config[config_parts[:key]] << config_parts[:value] + else + sshd_config[config_parts[:key]] = config_parts[:value] end end end diff --git a/lib/facter/simplib_sysctl.rb b/lib/facter/simplib_sysctl.rb index ae830802..02452708 100644 --- a/lib/facter/simplib_sysctl.rb +++ b/lib/facter/simplib_sysctl.rb @@ -4,7 +4,8 @@ # # We don't grab the entire output due to the sheer size of it # -Facter.add("simplib_sysctl") do +require 'English' +Facter.add('simplib_sysctl') do confine { Facter::Core::Execution.which('sysctl') } setcode do @@ -18,7 +19,7 @@ 'kernel.tainted', 'kernel.threads-max', 'net.ipv6.conf.all.disable_ipv6', - 'vm.swappiness' + 'vm.swappiness', ] retval = {} @@ -31,20 +32,18 @@ # Facter.*.exec. # # For now we test around the issue by checking the output if $? is nil: - if ($?.nil? && module_value) || - (!$?.nil? && $?.exitstatus.zero? && module_value && !module_value.strip.empty?) - then - module_value.strip! + next unless ($CHILD_STATUS.nil? && module_value) || + (!$CHILD_STATUS.nil? && $CHILD_STATUS.exitstatus.zero? && module_value && !module_value.strip.empty?) + module_value.strip! - # These can be too big for facter to process as Integers - unless entry.start_with?('kernel.shm') - if module_value =~ /^\d+$/ - module_value = module_value.to_i - end + # These can be too big for facter to process as Integers + unless entry.start_with?('kernel.shm') + if %r{^\d+$}.match?(module_value) + module_value = module_value.to_i end - - retval[entry] = module_value end + + retval[entry] = module_value end retval diff --git a/lib/facter/tmp_mounts.rb b/lib/facter/tmp_mounts.rb index 74e77c7d..ac7e4951 100644 --- a/lib/facter/tmp_mounts.rb +++ b/lib/facter/tmp_mounts.rb @@ -11,42 +11,39 @@ # Please migrate to `simplib__mountpoints` when possible. require 'facter' -simplib__tmp_mount_target_dirs = %w( - /tmp - /var/tmp - /dev/shm -) +simplib__tmp_mount_target_dirs = [ + '/tmp', + '/var/tmp', + '/dev/shm', +] simplib__tmp_mount_list = nil simplib__tmp_mount_target_dirs.each do |dir| - Facter.add("tmp_mount#{dir.gsub('/','_')}") do - confine :kernel => :Linux + Facter.add("tmp_mount#{dir.tr('/', '_')}") do + confine kernel: :Linux confine { File.directory?(dir) } setcode do - simplib__tmp_mount_list ||= Facter.value(:simplib__mountpoints) next unless simplib__tmp_mount_list[dir] simplib__tmp_mount_list[dir]['options'].join(',') end end - Facter.add("tmp_mount_path#{dir.gsub('/','_')}") do - confine :kernel => :Linux + Facter.add("tmp_mount_path#{dir.tr('/', '_')}") do + confine kernel: :Linux confine { File.directory?(dir) } setcode do - simplib__tmp_mount_list ||= Facter.value(:simplib__mountpoints) next unless simplib__tmp_mount_list[dir] simplib__tmp_mount_list[dir]['device'] end end - Facter.add("tmp_mount_fstype#{dir.gsub('/','_')}") do - confine :kernel => :Linux + Facter.add("tmp_mount_fstype#{dir.tr('/', '_')}") do + confine kernel: :Linux confine { File.directory?(dir) } setcode do - simplib__tmp_mount_list ||= Facter.value(:simplib__mountpoints) next unless simplib__tmp_mount_list[dir] simplib__tmp_mount_list[dir]['filesystem'] diff --git a/lib/facter/uid_min.rb b/lib/facter/uid_min.rb index 334709c7..b0359fc0 100644 --- a/lib/facter/uid_min.rb +++ b/lib/facter/uid_min.rb @@ -6,7 +6,7 @@ confine { File.exist?('/etc/login.defs') } setcode do - uid_min = File.open('/etc/login.defs').grep(/UID_MIN/) + uid_min = File.open('/etc/login.defs').grep(%r{UID_MIN}) # Grep returns an Array uid_min = '' if uid_min.empty? @@ -16,12 +16,12 @@ end unless uid_min.empty? - if ['RedHat','CentOS','OracleLinux','Scientific'].include?(Facter.value(:operatingsystem)) && - Facter.value(:operatingsystemmajrelease) < '7' - uid_min = '500' - else - uid_min = '1000' - end + uid_min = if ['RedHat', 'CentOS', 'OracleLinux', 'Scientific'].include?(Facter.value(:operatingsystem)) && + Facter.value(:operatingsystemmajrelease) < '7' + '500' + else + '1000' + end end uid_min diff --git a/lib/puppet/functions/simplib/assert_optional_dependency.rb b/lib/puppet/functions/simplib/assert_optional_dependency.rb index c9da77b2..a47fe266 100644 --- a/lib/puppet/functions/simplib/assert_optional_dependency.rb +++ b/lib/puppet/functions/simplib/assert_optional_dependency.rb @@ -56,20 +56,18 @@ end def get_module_dependencies(dependency_tree_levels, module_metadata) - _levels = Array(dependency_tree_levels.dup) - current_level = _levels.shift + levels = Array(dependency_tree_levels.dup) + current_level = levels.shift metadata_level = module_metadata - while !_levels.empty? - if metadata_level[current_level] - metadata_level = metadata_level[current_level] - current_level = _levels.shift - else - return nil - end + until levels.empty? + return nil unless metadata_level[current_level] + metadata_level = metadata_level[current_level] + current_level = levels.shift + end - return metadata_level[current_level] + metadata_level[current_level] end # Concept lifted from 'node-semver' @@ -84,47 +82,44 @@ def coerce(version) def check_dependency(module_name, module_dependency) require 'semantic_puppet' - _module_author, _module_name = module_name.split('/') + author, name = module_name.split('/') - unless _module_name - _module_name = _module_author.dup - _module_author = nil + unless name + name = author.dup + author = nil end - unless call_function('simplib::module_exist', _module_name) - return "optional dependency '#{_module_name}' not found" + unless call_function('simplib::module_exist', name) + return "optional dependency '#{name}' not found" end - if module_dependency - module_metadata = call_function('load_module_metadata', _module_name) + return unless module_dependency + module_metadata = call_function('load_module_metadata', name) - if _module_author - cmp_author = module_metadata['name'].strip.gsub('-','/').split('/').first - unless _module_author.strip == cmp_author - return %('#{module_name}' does not match '#{module_metadata['name']}') - end + if author + cmp_author = module_metadata['name'].strip.tr('-', '/').split('/').first + unless author.strip == cmp_author + return %('#{module_name}' does not match '#{module_metadata['name']}') end + end - if module_dependency['version_requirement'] - begin - version_requirement = SemanticPuppet::VersionRange.parse(module_dependency['version_requirement']) - rescue ArgumentError - return %(invalid version range '#{module_dependency['version_requirement']}' for '#{_module_name}') - end - - module_version = coerce(module_metadata['version']) + return unless module_dependency['version_requirement'] + begin + version_requirement = SemanticPuppet::VersionRange.parse(module_dependency['version_requirement']) + rescue ArgumentError + return %(invalid version range '#{module_dependency['version_requirement']}' for '#{name}') + end - begin - module_version = SemanticPuppet::Version.parse(module_version) - rescue ArgumentError - return %(invalid version '#{module_version}' found for '#{_module_name}') - end + module_version = coerce(module_metadata['version']) - unless version_requirement.include?(module_version) - return %('#{_module_name}-#{module_version}' does not satisfy '#{version_requirement}') - end - end + begin + module_version = SemanticPuppet::Version.parse(module_version) + rescue ArgumentError + return %(invalid version '#{module_version}' found for '#{name}') end + + return if version_requirement.include?(module_version) + %('#{name}-#{module_version}' does not satisfy '#{version_requirement}') end def raise_error(msg, env) @@ -143,38 +138,37 @@ def assert_optional_dependency( dependency_tree.split(':'), call_function( 'load_module_metadata', - source_module - ) + source_module, + ), ) - if module_dependencies - if target_module - tgt = target_module.gsub('-','/') + return unless module_dependencies + if target_module + tgt = target_module.tr('-', '/') - if tgt.include?('/') - target_dependency = module_dependencies.find {|d| d['name'].gsub('-','/') == tgt} - else - target_dependency = module_dependencies.find {|d| d['name'] =~ %r((/|-)#{tgt}$)} - end + target_dependency = if tgt.include?('/') + module_dependencies.find { |d| d['name'].tr('-', '/') == tgt } + else + module_dependencies.find { |d| d['name'] =~ %r{(/|-)#{tgt}$} } + end - if target_dependency - result = check_dependency(tgt, target_dependency) + if target_dependency + result = check_dependency(tgt, target_dependency) - raise_error(result, current_environment) if result - else - raise_error(%(module '#{target_module}' not found in metadata.json for '#{source_module}'), current_environment) - end + raise_error(result, current_environment) if result else - results = [] + raise_error(%(module '#{target_module}' not found in metadata.json for '#{source_module}'), current_environment) + end + else + results = [] - module_dependencies.each do |dependency| - result = check_dependency(dependency['name'].gsub('-','/'), dependency) - results << result if result - end + module_dependencies.each do |dependency| + result = check_dependency(dependency['name'].tr('-', '/'), dependency) + results << result if result + end - unless results.empty? - raise_error(%(\n* #{results.join("\n* ")}\n), current_environment) - end + unless results.empty? + raise_error(%(\n* #{results.join("\n* ")}\n), current_environment) end end end diff --git a/lib/puppet/functions/simplib/bracketize.rb b/lib/puppet/functions/simplib/bracketize.rb index 77859e06..b6e81120 100644 --- a/lib/puppet/functions/simplib/bracketize.rb +++ b/lib/puppet/functions/simplib/bracketize.rb @@ -6,7 +6,6 @@ # and return those entries untouched. # Puppet::Functions.create_function(:'simplib::bracketize') do - # @param ip_arr The array of IPv6 addresses to bracketize # @return [Variant[String, Array[String]]] converted input # @@ -42,31 +41,31 @@ end def bracketize_string_input(ipaddr_string) - ip_arr = ipaddr_string.split(/\s|,|;/).delete_if{ |y| y.empty? } + ip_arr = ipaddr_string.split(%r{\s|,|;}).delete_if { |y| y.empty? } bracketize(ip_arr) end def bracketize(ip_arr) require 'ipaddr' ipaddr = Array(ip_arr).flatten - retval = Array.new + retval = [] ipaddr.each do |x| begin ip = IPAddr.new(x) rescue - #allowed to fail because input can be string of hostname + # allowed to fail because input can be string of hostname # will just return unaltered input in that case retval << x next end # IPv6 Address? - if ip.ipv6?() then - if x[0].chr != '[' then + if ip.ipv6? + if x[0].chr != '[' y = x.split('/') y[0] = "[#{y[0]}]" retval << y.join('/') else - retval << x + retval << x end else retval << x @@ -74,6 +73,6 @@ def bracketize(ip_arr) end retval = retval.first if retval.size == 1 - return retval + retval end end diff --git a/lib/puppet/functions/simplib/caller.rb b/lib/puppet/functions/simplib/caller.rb index b7468e18..9e16fbf9 100644 --- a/lib/puppet/functions/simplib/caller.rb +++ b/lib/puppet/functions/simplib/caller.rb @@ -6,7 +6,6 @@ # # WARNING: Uses **EXPERIMENTAL** features from Puppet, may break at any time. Puppet::Functions.create_function(:'simplib::caller', Puppet::Functions::InternalFunction) do - # @param depth # The level to walk backwards in the stack. May be useful for popping out # of known function nesting @@ -17,13 +16,12 @@ # @return [Array] # The caller dispatch :caller do - scope_param() + scope_param optional_param 'Integer[0]', :depth optional_param 'Boolean', :print end - def caller(scope, depth=1, print=false) - + def caller(_scope, depth = 1, print = false) calling_file = 'TOPSCOPE' stack_trace = call_function('simplib::debug::stacktrace', print) @@ -32,6 +30,6 @@ def caller(scope, depth=1, print=false) calling_file = stack_trace[-depth] if stack_trace[-depth] end - return calling_file + calling_file end end diff --git a/lib/puppet/functions/simplib/debug/classtrace.rb b/lib/puppet/functions/simplib/debug/classtrace.rb index 69c77d90..3b4066c0 100644 --- a/lib/puppet/functions/simplib/debug/classtrace.rb +++ b/lib/puppet/functions/simplib/debug/classtrace.rb @@ -3,24 +3,23 @@ # # WARNING: Uses **EXPERIMENTAL** features from Puppet, may break at any time. Puppet::Functions.create_function(:'simplib::debug::classtrace', Puppet::Functions::InternalFunction) do - # @param print # Whether or not to print to the visual output # # @return [Array] # The class trace dispatch :classtrace do - scope_param() + scope_param optional_param 'Boolean', :print end - def classtrace(scope, print=true) + def classtrace(scope, print = true) class_stack = collate(scope).reverse if print msg = [ - "Simplib::Debug::Classtrace:", - ' => ' + class_stack.join("\n => ") + 'Simplib::Debug::Classtrace:', + ' => ' + class_stack.join("\n => "), ].join("\n") # This is only required when rspec is loaded @@ -31,12 +30,12 @@ def classtrace(scope, print=true) Puppet.warning(msg) end - return class_stack + class_stack end private - def collate(scope, retval=[]) + def collate(scope, retval = []) scope_s = scope.to_s if scope_s.start_with?('Scope(') scope_s = scope_s.split('Scope(').last[0..-2] diff --git a/lib/puppet/functions/simplib/debug/inspect.rb b/lib/puppet/functions/simplib/debug/inspect.rb index dc4455c1..953c1166 100644 --- a/lib/puppet/functions/simplib/debug/inspect.rb +++ b/lib/puppet/functions/simplib/debug/inspect.rb @@ -3,7 +3,6 @@ # # WARNING: Uses **EXPERIMENTAL** features from Puppet, may break at any time. Puppet::Functions.create_function(:'simplib::debug::inspect', Puppet::Functions::InternalFunction) do - # @param to_inspect # The parameter that you wish to inspect # @@ -13,15 +12,15 @@ # @return [Hash] # Hash of the data that is printed dispatch :inspect do - scope_param() + scope_param required_param 'NotUndef', :to_inspect optional_param 'Boolean', :print end - def inspect(scope, to_inspect, print=true) + def inspect(scope, to_inspect, print = true) data = { - :type => to_inspect.class, - :content => to_inspect.to_json + type: to_inspect.class, + content: to_inspect.to_json } if scope @@ -34,12 +33,11 @@ def inspect(scope, to_inspect, print=true) end end - if print msg = [ 'Simplib::Debug::Inspect:', "Type => '#{data[:type]}'", - "Content => '#{data[:content]}'" + "Content => '#{data[:content]}'", ] if data[:module_name] && !data[:module_name].empty? @@ -64,6 +62,6 @@ def inspect(scope, to_inspect, print=true) Puppet.warning(msg) end - return data + data end end diff --git a/lib/puppet/functions/simplib/debug/stacktrace.rb b/lib/puppet/functions/simplib/debug/stacktrace.rb index aa66996a..29097494 100644 --- a/lib/puppet/functions/simplib/debug/stacktrace.rb +++ b/lib/puppet/functions/simplib/debug/stacktrace.rb @@ -3,24 +3,23 @@ # # WARNING: Uses **EXPERIMENTAL** features from Puppet, may break at any time. Puppet::Functions.create_function(:'simplib::debug::stacktrace', Puppet::Functions::InternalFunction) do - # @param print # Whether or not to print to the visual output # # @return [Array] # The stack trace dispatch :stacktrace do - scope_param() + scope_param optional_param 'Boolean', :print end - def stacktrace(scope, print=true) - stack_trace = Puppet::Pops::PuppetStack.stacktrace.map{|x| x.join(':')} + def stacktrace(_scope, print = true) + stack_trace = Puppet::Pops::PuppetStack.stacktrace.map { |x| x.join(':') } if print msg = [ - "Simplib::Debug::Stacktrace:", - ' => ' + stack_trace.join("\n => ") + 'Simplib::Debug::Stacktrace:', + ' => ' + stack_trace.join("\n => "), ].join("\n") # This is only required when rspec is loaded @@ -31,6 +30,6 @@ def stacktrace(scope, print=true) Puppet.warning(msg) end - return stack_trace + stack_trace end end diff --git a/lib/puppet/functions/simplib/deprecation.rb b/lib/puppet/functions/simplib/deprecation.rb index 1d9fc3cf..44e775ca 100644 --- a/lib/puppet/functions/simplib/deprecation.rb +++ b/lib/puppet/functions/simplib/deprecation.rb @@ -2,7 +2,6 @@ # for a given key. # Puppet::Functions.create_function(:'simplib::deprecation') do - # @param key Uniqueness key, which is used to dedupe messages. # @param message Message to be printed, to which file and line # information will be appended, if available. @@ -22,13 +21,13 @@ end def deprecation(key, message) - if defined? Puppet::Pops::PuppetStack.stacktrace() - stacktrace = Puppet::Pops::PuppetStack.stacktrace() + if defined? Puppet::Pops::PuppetStack.stacktrace + stacktrace = Puppet::Pops::PuppetStack.stacktrace file = stacktrace[0] line = stacktrace[1] message = "#{message} at #{file}:#{line}" end - Puppet.deprecation_warning(message, key) unless ENV['SIMPLIB_NOLOG_DEPRECATIONS'] + Puppet.deprecation_warning(message, key) unless ENV['SIMPLIB_NOLOG_DEPRECATIONS'] end end diff --git a/lib/puppet/functions/simplib/dlookup.rb b/lib/puppet/functions/simplib/dlookup.rb index 0bb54485..f0b1b827 100644 --- a/lib/puppet/functions/simplib/dlookup.rb +++ b/lib/puppet/functions/simplib/dlookup.rb @@ -119,7 +119,7 @@ def dlookup(define_id, param, options) target_param = "#{define_id}::#{param}" - return call_function('simplib::lookup', target_param, options ) + call_function('simplib::lookup', target_param, options) end def dlookup_specific(define_id, param, resource_title, options) @@ -132,6 +132,6 @@ def dlookup_specific(define_id, param, resource_title, options) retval = dlookup(define_id, param, options) end - return retval + retval end end diff --git a/lib/puppet/functions/simplib/filtered.rb b/lib/puppet/functions/simplib/filtered.rb index d03b9a17..36fe1fc4 100644 --- a/lib/puppet/functions/simplib/filtered.rb +++ b/lib/puppet/functions/simplib/filtered.rb @@ -51,10 +51,10 @@ end def filtered(options, context) - backend = call_function(options["function"], options, context) + backend = call_function(options['function'], options, context) data = {} backend.each do |key, value| - check_filter(key, options["filter"]) do |nkey| + check_filter(key, options['filter']) do |nkey| data[nkey] = value end end @@ -63,29 +63,28 @@ def filtered(options, context) def filtered_lookup_key(key, options, context) retval = nil - check_filter(key, options["filter"]) do |key| - retval = call_function(options["function"], key, options, context) - if (retval == nil) + check_filter(key, options['filter']) do |k| + retval = call_function(options['function'], k, options, context) + if retval.nil? context.not_found end end - if (retval == nil) + if retval.nil? context.not_found else retval end end - def check_filter(key, filter, &block) + def check_filter(key, filter) filtered = false filter.each do |keyname| - if (key =~ Regexp.new(keyname)) + if key&.match?(Regexp.new(keyname)) filtered = true end end - if (filtered == false) - yield key - end + return unless filtered == false + yield key end end # vim: set expandtab ts=2 sw=2: diff --git a/lib/puppet/functions/simplib/gen_random_password.rb b/lib/puppet/functions/simplib/gen_random_password.rb index bb65309b..6593070a 100644 --- a/lib/puppet/functions/simplib/gen_random_password.rb +++ b/lib/puppet/functions/simplib/gen_random_password.rb @@ -4,7 +4,6 @@ # in the allotted time. # Puppet::Functions.create_function(:'simplib::gen_random_password') do - # @param length Length of the new password. # # @param complexity Specifies the types of characters to be used in the password @@ -27,51 +26,48 @@ optional_param 'Variant[Integer[0],Float[0]]', :timeout_seconds end - def gen_random_password(length, complexity=nil, complex_only=false, timeout_seconds = 30) + def gen_random_password(length, complexity = nil, complex_only = false, timeout_seconds = 30) require 'timeout' passwd = '' - Timeout::timeout(timeout_seconds) do + Timeout.timeout(timeout_seconds) do lower_charlist = ('a'..'z').to_a upper_charlist = ('A'..'Z').to_a digit_charlist = ('0'..'9').to_a symbol_charlist = nil case complexity - when 1 - symbol_charlist = ['@','%','-','_','+','=','~'] - when 2 - symbol_charlist = (' '..'/').to_a + ('['..'`').to_a + ('{'..'~').to_a - else + when 1 + symbol_charlist = ['@', '%', '-', '_', '+', '=', '~'] + when 2 + symbol_charlist = (' '..'/').to_a + ('['..'`').to_a + ('{'..'~').to_a end - unless symbol_charlist.nil? - if complex_only == true - charlists = [ - symbol_charlist - ] - else - charlists = [ - lower_charlist, - upper_charlist, - digit_charlist, - symbol_charlist - ] - end + charlists = if symbol_charlist.nil? + [ + lower_charlist, + upper_charlist, + digit_charlist, + ] + elsif complex_only == true + [ + symbol_charlist, + ] + else + [ + lower_charlist, + upper_charlist, + digit_charlist, + symbol_charlist, + ] - else - charlists = [ - lower_charlist, - upper_charlist, - digit_charlist - ] - end + end last_list_rand = nil last_char_rand = nil - Integer(length).times do |i| + Integer(length).times do |_i| rand_list_index = rand(charlists.length).floor if rand_list_index == last_list_rand - rand_list_index = rand_list_index-1 + rand_list_index -= 1 end last_list_rand = rand_list_index @@ -79,7 +75,7 @@ def gen_random_password(length, complexity=nil, complex_only=false, timeout_seco rand_index = rand(charlists[rand_list_index].length).floor if rand_index == last_char_rand - rand_index = rand_index-1 + rand_index -= 1 end passwd += charlists[rand_list_index][rand_index] @@ -88,7 +84,7 @@ def gen_random_password(length, complexity=nil, complex_only=false, timeout_seco end end - return passwd + passwd end end # vim: set expandtab ts=2 sw=2: diff --git a/lib/puppet/functions/simplib/host_is_me.rb b/lib/puppet/functions/simplib/host_is_me.rb index b1a5ad0f..b36d621a 100644 --- a/lib/puppet/functions/simplib/host_is_me.rb +++ b/lib/puppet/functions/simplib/host_is_me.rb @@ -1,9 +1,8 @@ # Detect if a local system identifier hostname/IPv4 address matches -# a specified hostname/IPv4 address or an entry in a list of +# a specified hostname/IPv4 address or an entry in a list of # hostnames and/or IPv4 addresses # Puppet::Functions.create_function(:'simplib::host_is_me') do - # @param host Hostname/IPv4 address to compare against; # `127.0.0.1` is never matched, use `localhost` instead # @return [Boolean] true if a local system hostname/IPv4 address matches @@ -32,7 +31,7 @@ def hostlist_contains_me(hosts) scope['facts']['fqdn'], scope['facts']['hostname'], 'localhost', - 'localhost.localdomain' + 'localhost.localdomain', ] # add non-local IPv4 addresses diff --git a/lib/puppet/functions/simplib/ip/family_hash.rb b/lib/puppet/functions/simplib/ip/family_hash.rb index 312b79dc..f733e08c 100644 --- a/lib/puppet/functions/simplib/ip/family_hash.rb +++ b/lib/puppet/functions/simplib/ip/family_hash.rb @@ -28,11 +28,13 @@ # # @example # - # simplib::ip::family_hash([ - # '1.2.3.4', - # '2.3.4.5/8', - # '::1' - # ]) + # simplib::ip::family_hash( + # [ + # '1.2.3.4', + # '2.3.4.5/8', + # '::1', + # ] + # ) # # Returns (YAML Formatted for clarity) # @@ -80,8 +82,8 @@ def family_hash(addresses) begin ip = IPAddr.new(addr) - addr_normalized, cidr_netmask = call_function('simplib::nets2cidr', addr). - first.split('/') + addr_normalized, cidr_netmask = call_function('simplib::nets2cidr', addr) + .first.split('/') addr_normalized.delete!('[]') @@ -91,8 +93,8 @@ def family_hash(addresses) if ip.ipv4? ip_family = 'ipv4' - ip_breakdown['netmask']['ddq'] = call_function('simplib::nets2ddq', addr). - first.split('/')[1] || '255.255.255.255' + ip_breakdown['netmask']['ddq'] = call_function('simplib::nets2ddq', addr) + .first.split('/')[1] || '255.255.255.255' ip_breakdown['netmask']['cidr'] = 32 unless ip_breakdown['netmask']['cidr'] elsif ip.ipv6? @@ -106,7 +108,6 @@ def family_hash(addresses) ip_family = 'unknown' end - results[ip_family] ||= {} results[ip_family][addr] = ip_breakdown end diff --git a/lib/puppet/functions/simplib/ip_to_cron.rb b/lib/puppet/functions/simplib/ip_to_cron.rb index f4954962..cf0bf627 100644 --- a/lib/puppet/functions/simplib/ip_to_cron.rb +++ b/lib/puppet/functions/simplib/ip_to_cron.rb @@ -2,7 +2,6 @@ # This can be used to avoid starting a certain cron job at the same # time on all servers. Puppet::Functions.create_function(:'simplib::ip_to_cron') do - local_types do type "IpToCronAlgorithm = Enum['ip_mod', 'sha256']" end @@ -62,4 +61,3 @@ def ip_to_cron(occurs = 1, max_value = 59, algorithm = 'ip_mod', ip = nil) call_function('simplib::rand_cron', ipaddr, algorithm, occurs, max_value) end end - diff --git a/lib/puppet/functions/simplib/ipaddresses.rb b/lib/puppet/functions/simplib/ipaddresses.rb index 7291ed97..a955376c 100644 --- a/lib/puppet/functions/simplib/ipaddresses.rb +++ b/lib/puppet/functions/simplib/ipaddresses.rb @@ -2,7 +2,6 @@ # client, optionally excluding local addresses. # Puppet::Functions.create_function(:'simplib::ipaddresses') do - # @param only_remote Whether to exclude local addresses # from the return value (e.g., '127.0.0.1'). # @@ -20,10 +19,10 @@ def ipaddresses(only_remote = false) interfaces.split(',').each do |iface| iface_addr = scope['facts']["ipaddress_#{iface}"] - retval << iface_addr unless (iface_addr.nil? or iface_addr.strip.empty?) + retval << iface_addr unless iface_addr.nil? || iface_addr.strip.empty? end - retval.delete_if{|x| x =~ /^127/} if only_remote + retval.delete_if { |x| x =~ %r{^127} } if only_remote end retval diff --git a/lib/puppet/functions/simplib/join_mount_opts.rb b/lib/puppet/functions/simplib/join_mount_opts.rb index b15b8937..f5204a75 100644 --- a/lib/puppet/functions/simplib/join_mount_opts.rb +++ b/lib/puppet/functions/simplib/join_mount_opts.rb @@ -1,7 +1,6 @@ # Merge two sets of `mount` options in a reasonable fashion, giving # precedence to the second set. Puppet::Functions.create_function(:'simplib::join_mount_opts') do - # @param system_mount_opts System mount options # @param new_mount_opts New mount options, which will override # `system_mount_opts` when there are conflicts @@ -19,42 +18,40 @@ def join_mount_opts(system_mount_opts, new_mount_opts) # Remove any items that have a corresponding 'no' item in the # list. Such as 'dev' vs 'nodev', etc... - system_opts.delete_if{|x| + system_opts.delete_if do |x| new_opts.include?("no#{x}") - } + end # Reverse this if the user wants to explicitly set an option and a no* # option is already present. - system_opts.delete_if{|x| + system_opts.delete_if do |x| found = false - if x =~ /^no(.*)/ - found = new_opts.include?($1) + if x =~ %r{^no(.*)} + found = new_opts.include?(Regexp.last_match(1)) end found - } + end mount_options = {} scope = closure_scope selinux_current_mode = scope['facts']['selinux_current_mode'] - if !selinux_current_mode or selinux_current_mode == 'disabled' + if !selinux_current_mode || (selinux_current_mode == 'disabled') # SELinux is off, get rid of selinux related items in the options - system_opts.delete_if{|x| x =~ /^(((fs|def|root)?context=)|seclabel)/ } - new_opts.delete_if{|x| x =~ /^(((fs|def|root)?context=)|seclabel)/ } - else + system_opts.delete_if { |x| x =~ %r{^(((fs|def|root)?context=)|seclabel)} } + new_opts.delete_if { |x| x =~ %r{^(((fs|def|root)?context=)|seclabel)} } + elsif system_opts.include?('seclabel') # Remove any SELinux context items if 'seclabel' is set. This # means that we can't remount it with new options. - if system_opts.include?('seclabel') - # These two aren't compatible for remounts and can cause - # issues unless done *very* carefully. - system_opts.delete_if{|x| x =~ /^(fs|def|root)?context=/ } - new_opts.delete_if{|x| x =~ /^(fs|def|root)?context=/ } - end + system_opts.delete_if { |x| x =~ %r{^(fs|def|root)?context=} } + new_opts.delete_if { |x| x =~ %r{^(fs|def|root)?context=} } + # These two aren't compatible for remounts and can cause + # issues unless done *very* carefully. end (system_opts + new_opts).each do |opt| - k,v = opt.split('=') - if v and v.include?('"\'') # special case with "' that will cause problems + k, v = opt.split('=') + if v&.include?('"\'') # special case with "' that will cause problems v.delete!('"\'') # Anything with a comma must be double quoted! v = '"' + v + '"' if v.include?(',') @@ -62,12 +59,11 @@ def join_mount_opts(system_mount_opts, new_mount_opts) mount_options[k] = v end - retval = [] - mount_options.keys.sort.each do |k| + retval = mount_options.keys.sort.map do |k| if mount_options[k] - retval << "#{k}=#{mount_options[k]}" + "#{k}=#{mount_options[k]}" else - retval << k + k end end diff --git a/lib/puppet/functions/simplib/lookup.rb b/lib/puppet/functions/simplib/lookup.rb index 27cde331..b46cf3ff 100644 --- a/lib/puppet/functions/simplib/lookup.rb +++ b/lib/puppet/functions/simplib/lookup.rb @@ -82,10 +82,8 @@ def lookup(param, options = nil) return global_param if global_param - if options - return call_function('lookup', param, options ) - else - return call_function('lookup', param ) - end + return call_function('lookup', param, options) if options + + call_function('lookup', param) end end diff --git a/lib/puppet/functions/simplib/mock_data.rb b/lib/puppet/functions/simplib/mock_data.rb index 27779446..93e7bb98 100644 --- a/lib/puppet/functions/simplib/mock_data.rb +++ b/lib/puppet/functions/simplib/mock_data.rb @@ -20,21 +20,21 @@ param 'Puppet::LookupContext', :context end - def mock_data(options, context) - case options["path"] - when "/path/1" + def mock_data(options, _context) + case options['path'] + when '/path/1' { - "profiles::test1::variable" => "goodvar", - "profiles::test2::variable" => "badvar", - "profiles::test::test1::variable" => "goodvar", - "apache::sync" => "badvar", - "user::root_password" => "badvar", + 'profiles::test1::variable' => 'goodvar', + 'profiles::test2::variable' => 'badvar', + 'profiles::test::test1::variable' => 'goodvar', + 'apache::sync' => 'badvar', + 'user::root_password' => 'badvar', } - when "/path/2" + when '/path/2' { - "profiles::test1::variable" => "goodvar", - "profiles::test2::variable" => "badvar", - "profiles::test::test1::variable" => "goodvar", + 'profiles::test1::variable' => 'goodvar', + 'profiles::test2::variable' => 'badvar', + 'profiles::test::test1::variable' => 'goodvar', } else {} @@ -43,7 +43,7 @@ def mock_data(options, context) def mock_data_lookup_key(key, options, context) data = mock_data(options, context) - if (data.key?(key)) + if data.key?(key) data[key] else context.not_found diff --git a/lib/puppet/functions/simplib/module_exist.rb b/lib/puppet/functions/simplib/module_exist.rb index 2c16b337..845383cc 100644 --- a/lib/puppet/functions/simplib/module_exist.rb +++ b/lib/puppet/functions/simplib/module_exist.rb @@ -3,7 +3,6 @@ # If passed with an author, such as `simp/simplib` or `simp-simplib`, will # return whether or not that *specific* module exists. Puppet::Functions.create_function(:'simplib::module_exist') do - # @param module_name The module name to check # @return [Boolean] Whether or not the module exists in the current environment dispatch :module_exist do @@ -11,25 +10,17 @@ end def module_exist(module_name) - _module_author, _module_name = module_name.split(%r(/|-)) + author, name = module_name.split(%r{/|-}) - unless _module_name - _module_name = _module_author.dup - _module_author = nil + unless name + name = author.dup + author = nil end - if Puppet::Module.find(_module_name, closure_scope.compiler.environment.to_s) - if _module_author - if _module_author.strip == call_function('load_module_metadata', _module_name)['name'].strip.split(%r(/|-)).first - return true - else - return false - end - else - return true - end - else - return false - end + return false unless Puppet::Module.find(name, closure_scope.compiler.environment.to_s) + return true unless author + return true if author.strip == call_function('load_module_metadata', name)['name'].strip.split(%r{/|-}).first + + false end end diff --git a/lib/puppet/functions/simplib/nets2cidr.rb b/lib/puppet/functions/simplib/nets2cidr.rb index 405d730b..1dfc27c9 100644 --- a/lib/puppet/functions/simplib/nets2cidr.rb +++ b/lib/puppet/functions/simplib/nets2cidr.rb @@ -6,7 +6,6 @@ # valid network or hostname. # Puppet::Functions.create_function(:'simplib::nets2cidr') do - # @param network_list List of 1 or more networks separated by spaces, # commas, or semicolons # @return [Array[String]] Array of networks in CIDR notation @@ -48,16 +47,15 @@ end def nets2cidr_list(network_list) - networks = network_list.split(/\s|,|;/).delete_if{ |y| y.empty? } + networks = network_list.split(%r{\s|,|;}).delete_if { |y| y.empty? } nets2cidr(networks) end def nets2cidr(networks) - - require File.expand_path(File.dirname(__FILE__) + '/../../../puppetx/simp/simplib.rb') + require File.expand_path(File.dirname(__FILE__) + '/../../../puppetx/simp/simplib.rb') require 'ipaddr' - retval = Array.new + retval = [] networks.each do |lnet| # Skip any hostnames that we find. if PuppetX::SIMP::Simplib.hostname_only?(lnet) @@ -68,15 +66,15 @@ def nets2cidr(networks) begin ipaddr = IPAddr.new(lnet) rescue - fail("simplib::nets2cidr: '#{lnet}' is not a valid network!") + raise("simplib::nets2cidr: '#{lnet}' is not a valid network!") end # Just add it if it doesn't have a specified netmask. - if lnet =~ /\// - retval << "#{ipaddr.to_s}/#{IPAddr.new(ipaddr.inspect.split('/').last.chop).to_i.to_s(2).count('1')}" - else - retval << lnet - end + retval << if lnet.include?('/') + "#{ipaddr}/#{IPAddr.new(ipaddr.inspect.split('/').last.chop).to_i.to_s(2).count('1')}" + else + lnet + end end retval end diff --git a/lib/puppet/functions/simplib/nets2ddq.rb b/lib/puppet/functions/simplib/nets2ddq.rb index 061ecf22..ccf928d0 100644 --- a/lib/puppet/functions/simplib/nets2ddq.rb +++ b/lib/puppet/functions/simplib/nets2ddq.rb @@ -7,7 +7,6 @@ # valid network or hostname. # Puppet::Functions.create_function(:'simplib::nets2ddq') do - # @param networks The networks to convert # @return [Array[String]] Converted input # @raise [RuntimeError] if any input item is not a valid network @@ -59,7 +58,7 @@ end def nets2ddq_string_input(networks_string) - networks = networks_string.split(/\s|,|;/).delete_if{ |y| y.empty? } + networks = networks_string.split(%r{\s|,|;}).delete_if { |y| y.empty? } nets2ddq(networks) end @@ -67,27 +66,27 @@ def nets2ddq(networks) require 'ipaddr' require File.expand_path(File.dirname(__FILE__) + '/../../../puppetx/simp/simplib.rb') - retval = Array.new + retval = [] networks.each do |lnet| begin ipaddr = IPAddr.new(lnet) rescue - if PuppetX::SIMP::Simplib.hostname?(lnet) then + if PuppetX::SIMP::Simplib.hostname?(lnet) retval << lnet next end - fail("simplib::nets2ddq(): '#{lnet}' is not a valid network.") + raise("simplib::nets2ddq(): '#{lnet}' is not a valid network.") end # Just add it without touching if it is an ipv6 addr - if ipaddr.ipv6?() - retval << lnet - # Just add it if it doesn't have a specified netmask. - elsif lnet =~ /\// - retval << "#{ipaddr.to_s}/#{ipaddr.inspect.split('/').last.chop}" - else - retval << lnet - end + retval << if ipaddr.ipv6? + lnet + # Just add it if it doesn't have a specified netmask. + elsif lnet.include?('/') + "#{ipaddr}/#{ipaddr.inspect.split('/').last.chop}" + else + lnet + end end retval end diff --git a/lib/puppet/functions/simplib/params2hash.rb b/lib/puppet/functions/simplib/params2hash.rb index 31911bb5..b3326e11 100644 --- a/lib/puppet/functions/simplib/params2hash.rb +++ b/lib/puppet/functions/simplib/params2hash.rb @@ -3,27 +3,26 @@ # This is meant to get the parameters of classes and defined types. # The behavior when calling from other contexts is undefined Puppet::Functions.create_function(:'simplib::params2hash', Puppet::Functions::InternalFunction) do - # @param prune # Parameters that you wish to exclude from the output # # @return [Hash] # All in-scope parameters dispatch :params2hash do - scope_param() + scope_param optional_param 'Array[String[1]]', :prune end - def params2hash(scope, prune=[]) + def params2hash(scope, prune = []) param_hash = scope.resource.to_hash - prune << :name if (scope.resource.type == 'Class') + prune << :name if scope.resource.type == 'Class' prune.each do |to_prune| next if to_prune.nil? param_hash.delete(to_prune.to_sym) end - return param_hash + param_hash end end diff --git a/lib/puppet/functions/simplib/parse_hosts.rb b/lib/puppet/functions/simplib/parse_hosts.rb index 451649bd..31df6d8a 100644 --- a/lib/puppet/functions/simplib/parse_hosts.rb +++ b/lib/puppet/functions/simplib/parse_hosts.rb @@ -10,7 +10,6 @@ # * Any input item that contains a port specifies an invalid port. # Puppet::Functions.create_function(:'simplib::parse_hosts') do - # @param hosts Array of host entries, where each entry may contain # a protocol or both a protocol and port # @return [Hash] Structured Hash of the host information @@ -20,11 +19,13 @@ # specifies an invalid port # @example Input with multiple host formats: # - # simplib::parse_hosts([ - # '1.2.3.4', - # 'http://1.2.3.4', - # 'https://1.2.3.4:443' - # ]) + # simplib::parse_hosts( + # [ + # '1.2.3.4', + # 'http://1.2.3.4', + # 'https://1.2.3.4:443', + # ] + # ) # # Returns: # @@ -33,9 +34,9 @@ # :ports => ['443'], # :protocols => { # 'http' => [], - # 'https' => ['443'] - # } - # } + # 'https' => ['443'], + # }, + # }, # } dispatch :parse_hosts do required_param 'Array[String[1],1]', :hosts @@ -45,15 +46,12 @@ def parse_hosts(hosts) # Parse! parsed_hosts = {} hosts.each do |host| - host = host.strip next if host.nil? || host.empty? - tmp_host = host # Initialize. protocol = nil - port = nil hostname = nil # Get the protocol. @@ -68,14 +66,14 @@ def parse_hosts(hosts) # Validate with the protocol stripped off call_function('simplib::validate_net_list', Array(hostname)) - hostname,port = PuppetX::SIMP::Simplib.split_port(hostname) - call_function('simplib::validate_port', Array(port)) if (port && !port.empty?) + hostname, port = PuppetX::SIMP::Simplib.split_port(hostname) + call_function('simplib::validate_port', Array(port)) if port && !port.empty? # Build a unique list of parsed hosts. unless parsed_hosts.key?(hostname) parsed_hosts[hostname] = { - :ports => [], - :protocols => {} + ports: [], + protocols: {} } end @@ -83,15 +81,14 @@ def parse_hosts(hosts) parsed_hosts[hostname][:ports] << port end - if protocol - parsed_hosts[hostname][:protocols] = {} unless parsed_hosts[hostname][:protocols] - parsed_hosts[hostname][:protocols][protocol] = [] unless parsed_hosts[hostname][:protocols][protocol] + next unless protocol + parsed_hosts[hostname][:protocols] = {} unless parsed_hosts[hostname][:protocols] + parsed_hosts[hostname][:protocols][protocol] = [] unless parsed_hosts[hostname][:protocols][protocol] - parsed_hosts[hostname][:protocols][protocol] << port if port - end + parsed_hosts[hostname][:protocols][protocol] << port if port end - parsed_hosts.keys.each do |host| + parsed_hosts.each_key do |host| unless parsed_hosts[host][:ports].empty? parsed_hosts[host][:ports].uniq! parsed_hosts[host][:ports].sort! diff --git a/lib/puppet/functions/simplib/passgen.rb b/lib/puppet/functions/simplib/passgen.rb index a6ce7fe2..49c55074 100644 --- a/lib/puppet/functions/simplib/passgen.rb +++ b/lib/puppet/functions/simplib/passgen.rb @@ -20,7 +20,6 @@ # characters. # Puppet::Functions.create_function(:'simplib::passgen') do - # @param identifier Unique `String` to identify the password usage. # Must conform to the following: # * Identifier must contain only the following characters: @@ -153,18 +152,16 @@ optional_param 'Hash', :simpkv_options end - def passgen(identifier, password_options={}, simpkv_options={'app_id' => 'simplib::passgen'}) + def passgen(identifier, password_options = {}, simpkv_options = { 'app_id' => 'simplib::passgen' }) use_simpkv = call_function('lookup', 'simplib::passgen::simpkv', { 'default_value' => false }) - - password = nil - if use_simpkv - password = call_function('simplib::passgen::simpkv::passgen', identifier, - password_options, simpkv_options) - else - password = call_function('simplib::passgen::legacy::passgen', identifier, - password_options) - end + password = if use_simpkv + call_function('simplib::passgen::simpkv::passgen', identifier, + password_options, simpkv_options) + else + call_function('simplib::passgen::legacy::passgen', identifier, + password_options) + end password end end diff --git a/lib/puppet/functions/simplib/passgen/gen_password_and_salt.rb b/lib/puppet/functions/simplib/passgen/gen_password_and_salt.rb index c5c7e0a7..807d5dbb 100644 --- a/lib/puppet/functions/simplib/passgen/gen_password_and_salt.rb +++ b/lib/puppet/functions/simplib/passgen/gen_password_and_salt.rb @@ -9,7 +9,6 @@ # in the allotted time. # Puppet::Functions.create_function(:'simplib::passgen::gen_password_and_salt') do - # @param length Length of the new password. # # @param complexity Specifies the types of characters to be used in the @@ -40,12 +39,10 @@ def gen_password_and_salt(length, complexity, complex_only, timeout_seconds) length, complexity, complex_only, - timeout_seconds - ) + timeout_seconds) salt = call_function('simplib::passgen::gen_salt', timeout_seconds) [password, salt] end end - diff --git a/lib/puppet/functions/simplib/passgen/gen_salt.rb b/lib/puppet/functions/simplib/passgen/gen_salt.rb index 58c048c9..81b66aca 100644 --- a/lib/puppet/functions/simplib/passgen/gen_salt.rb +++ b/lib/puppet/functions/simplib/passgen/gen_salt.rb @@ -4,7 +4,6 @@ # in the allotted time. # Puppet::Functions.create_function(:'simplib::passgen::gen_salt') do - # @param timeout_seconds Maximum time allotted to generate the salt; # a value of 0 disables the timeout # @@ -23,10 +22,8 @@ def gen_salt(timeout_seconds = 30) 16, # length 0, # complexity false, # complex_only - timeout_seconds - ) + timeout_seconds) salt end end - diff --git a/lib/puppet/functions/simplib/passgen/get.rb b/lib/puppet/functions/simplib/passgen/get.rb index d6aefdce..a5214aaf 100644 --- a/lib/puppet/functions/simplib/passgen/get.rb +++ b/lib/puppet/functions/simplib/passgen/get.rb @@ -15,7 +15,6 @@ # is inaccessible by the user. # Puppet::Functions.create_function(:'simplib::passgen::get') do - # @param identifier Unique `String` to identify the password usage. # Must conform to the following: # * Identifier must contain only the following characters: @@ -107,18 +106,15 @@ optional_param 'Hash', :simpkv_options end - def get(identifier, simpkv_options={'app_id' => 'simplib::passgen'}) + def get(identifier, simpkv_options = { 'app_id' => 'simplib::passgen' }) use_simpkv = call_function('lookup', 'simplib::passgen::simpkv', { 'default_value' => false }) - - password_info = nil - if use_simpkv - password_info = call_function('simplib::passgen::simpkv::get', identifier, - simpkv_options) - else - password_info = call_function('simplib::passgen::legacy::get', identifier) - end + password_info = if use_simpkv + call_function('simplib::passgen::simpkv::get', identifier, + simpkv_options) + else + call_function('simplib::passgen::legacy::get', identifier) + end password_info end end - diff --git a/lib/puppet/functions/simplib/passgen/legacy/common_settings.rb b/lib/puppet/functions/simplib/passgen/legacy/common_settings.rb index 4ed6f05e..d8fbb230 100644 --- a/lib/puppet/functions/simplib/passgen/legacy/common_settings.rb +++ b/lib/puppet/functions/simplib/passgen/legacy/common_settings.rb @@ -1,7 +1,6 @@ # Returns common settings used by simplib::passgen in legacy mode # Puppet::Functions.create_function(:'simplib::passgen::legacy::common_settings') do - # @return [Hash] Settings Hash containing 'keydir', 'user', 'group', # 'dir_mode' and 'file_mode' attributes # @@ -19,8 +18,8 @@ def common_settings scope.lookupvar('::environment'), 'simp_autofiles', 'gen_passwd'), 'user' => Etc.getpwuid(Process.uid).name, 'group' => Etc.getgrgid(Process.gid).name, - 'dir_mode' => 0750, - 'file_mode' => 0640 + 'dir_mode' => 0o750, + 'file_mode' => 0o640, } end end diff --git a/lib/puppet/functions/simplib/passgen/legacy/get.rb b/lib/puppet/functions/simplib/passgen/legacy/get.rb index fc2438d3..0caa8d2d 100644 --- a/lib/puppet/functions/simplib/passgen/legacy/get.rb +++ b/lib/puppet/functions/simplib/passgen/legacy/get.rb @@ -5,7 +5,6 @@ # Terminates catalog compilation if a legacy password file is inaccessible by # the user. Puppet::Functions.create_function(:'simplib::passgen::legacy::get') do - # @param identifier Unique `String` to identify the password usage. # Must conform to the following: # * Identifier must contain only the following characters: @@ -66,11 +65,11 @@ def get_password_info(keydir, identifier, type) if password.empty? password = nil else - if File.exist?(salt_file) - salt = IO.readlines(salt_file)[0].to_s.chomp - else - salt = '' - end + salt = if File.exist?(salt_file) + IO.readlines(salt_file)[0].to_s.chomp + else + '' + end end end [ password, salt ] diff --git a/lib/puppet/functions/simplib/passgen/legacy/list.rb b/lib/puppet/functions/simplib/passgen/legacy/list.rb index 077be5a6..7ca7a717 100644 --- a/lib/puppet/functions/simplib/passgen/legacy/list.rb +++ b/lib/puppet/functions/simplib/passgen/legacy/list.rb @@ -8,7 +8,6 @@ # accessed by the user. # Puppet::Functions.create_function(:'simplib::passgen::legacy::list') do - # @return [Hash] Hash of results or {} if folder does not exist # # * 'keys' = Hash of password information @@ -34,17 +33,15 @@ def list ids = Dir.glob('*').delete_if do |id| # Exclude sub-directories (which legacy simplib::passgen doesn't # create), salt files and backup files - File.directory?(id) || !(id =~ /(\.salt|\.last)$/).nil? + File.directory?(id) || !(id =~ %r{(\.salt|\.last)$}).nil? end results = { 'keys' => {}, 'folders' => [] } ids.each do |id| - begin - info = call_function('simplib::passgen::legacy::get', id) - results['keys'][id] = info unless info.empty? - rescue Exception =>e - Puppet.warning("Ignoring file for simplib::passgen id '#{id}': #{e.message}") - end + info = call_function('simplib::passgen::legacy::get', id) + results['keys'][id] = info unless info.empty? + rescue => e + Puppet.warning("Ignoring file for simplib::passgen id '#{id}': #{e.message}") end end end diff --git a/lib/puppet/functions/simplib/passgen/legacy/passgen.rb b/lib/puppet/functions/simplib/passgen/legacy/passgen.rb index c49833c4..bfc9e1e2 100644 --- a/lib/puppet/functions/simplib/passgen/legacy/passgen.rb +++ b/lib/puppet/functions/simplib/passgen/legacy/passgen.rb @@ -11,7 +11,6 @@ # user are present in the password storage directory. # Puppet::Functions.create_function(:'simplib::passgen::legacy::passgen') do - # @param identifier Unique `String` to identify the password usage. # # @param modifier_hash Options `Hash`. May include any @@ -51,10 +50,10 @@ def initialize(closure_scope, loader) require 'puppet/util/symbolic_file_mode' # mixin Puppet::Util::SymbolicFileMode module for symbolic_mode_to_int() - self.extend(Puppet::Util::SymbolicFileMode) + extend(Puppet::Util::SymbolicFileMode) end - def passgen(identifier, modifier_hash={}) + def passgen(identifier, modifier_hash = {}) require 'etc' require 'timeout' @@ -69,22 +68,21 @@ def passgen(identifier, modifier_hash={}) rescue ArgumentError debug_msg = "simpkv::passgen (legacy): Puppet user '#{user}' not found on system, " user = Etc.getpwuid(Process.uid).name - debug_msg += "defaulting to process owner uid (#{user})" + debug_msg + "defaulting to process owner uid (#{user})" end begin Etc.getgrnam(group) rescue ArgumentError debug_msg = "simpkv::passgen (legacy): Puppet group '#{group}' not found on system, " group = Etc.getgrgid(Process.gid).name - debug_msg += "defaulting to process owner gid (#{group})" + debug_msg + "defaulting to process owner gid (#{group})" end settings['user'] = user settings['group'] = group settings['keydir'] = File.join(Puppet.settings[:vardir], 'simp', 'environments', scope.lookupvar('::environment'), - 'simp_autofiles', 'gen_passwd' - ) + 'simp_autofiles', 'gen_passwd') settings['min_password_length'] = 8 settings['default_password_length'] = 32 settings['crypt_map'] = { @@ -107,39 +105,35 @@ def passgen(identifier, modifier_hash={}) unless File.directory?(settings['keydir']) begin - FileUtils.mkdir_p(settings['keydir'], mode: 0750) + FileUtils.mkdir_p(settings['keydir'], mode: 0o750) # This chown is applicable as long as it is applied # by puppet, not puppetserver. FileUtils.chown(settings['user'], - settings['group'], settings['keydir'] - ) + settings['group'], settings['keydir']) rescue SystemCallError => e - err_msg = "simplib::passgen: Could not make directory" + - " #{settings['keydir']}: #{e.message}. Ensure that" + - " #{File.dirname(settings['keydir'])} is writable by" + - " '#{settings['user']}'" - fail(err_msg) + err_msg = 'simplib::passgen: Could not make directory' \ + " #{settings['keydir']}: #{e.message}. Ensure that" \ + " #{File.dirname(settings['keydir'])} is writable by" \ + " '#{settings['user']}'" + raise(err_msg) end end if options['last'] - passwd,salt = get_last_password(identifier, options, settings) + passwd, salt = get_last_password(identifier, options, settings) else - passwd,salt = get_current_password(identifier, options, settings) + passwd, salt = get_current_password(identifier, options, settings) end lockdown_stored_password_perms(settings) # Return the hash, not the password - if options['hash'] - return passwd.crypt("$#{settings['crypt_map'][options['hash']]}$#{salt}") - else - return passwd - end - rescue Timeout::Error => e - fail("simplib::passgen timed out for #{identifier}!") - end + return passwd.crypt("$#{settings['crypt_map'][options['hash']]}$#{salt}") if options['hash'] + passwd + rescue Timeout::Error + raise("simplib::passgen timed out for #{identifier}!") + end # Build a merged options hash and validate the options # raises ArgumentError if any option in the modifier_hash is invalid @@ -152,7 +146,7 @@ def build_options(base_options, modifier_hash, settings) options.merge!(modifier_hash) - if options['length'].to_s !~ /^\d+$/ + if !%r{^\d+$}.match?(options['length'].to_s) raise ArgumentError, "simplib::passgen: Error: Length '#{options['length']}' must be an integer!" else @@ -164,14 +158,14 @@ def build_options(base_options, modifier_hash, settings) end end - if options['complexity'].to_s !~ /^\d+$/ + if !%r{^\d+$}.match?(options['complexity'].to_s) raise ArgumentError, "simplib::passgen: Error: Complexity '#{options['complexity']}' must be an integer!" else options['complexity'] = options['complexity'].to_i end - if options['gen_timeout_seconds'].to_s !~ /^\d+$/ + if !%r{^\d+$}.match?(options['gen_timeout_seconds'].to_s) raise ArgumentError, "simplib::passgen: Error: Password generation timeout '#{options['gen_timeout_seconds']}' must be an integer!" else @@ -182,11 +176,11 @@ def build_options(base_options, modifier_hash, settings) if options['hash'] == true options['hash'] = 'sha256' end - if options['hash'] and !settings['crypt_map'].keys.include?(options['hash']) + if options['hash'] && !settings['crypt_map'].keys.include?(options['hash']) raise ArgumentError, "simplib::passgen: Error: '#{options['hash']}' is not a valid hash." end - return options + options end # Generate a password @@ -195,15 +189,13 @@ def gen_password(options) options['length'], options['complexity'], options['complex_only'], - options['gen_timeout_seconds'] - ) + options['gen_timeout_seconds']) end # Generate the salt to be used to encrypt a password def gen_salt(options) call_function('simplib::passgen::gen_salt', - options['gen_timeout_seconds'] - ) + options['gen_timeout_seconds']) end # Retrieve or generate a current password @@ -223,50 +215,50 @@ def gen_salt(options) def get_current_password(identifier, options, settings) # Open the file in append + read mode to prepare for what is to # come. - tgt = File.new("#{settings['keydir']}/#{identifier}","a+") - tgt_hash = File.new("#{tgt.path}.salt","a+") + tgt = File.new("#{settings['keydir']}/#{identifier}", 'a+') + tgt_hash = File.new("#{tgt.path}.salt", 'a+') # These chowns are applicable as long as they are applied # by puppet, not puppetserver. - FileUtils.chown(settings['user'],settings['group'],tgt.path) - FileUtils.chown(settings['user'],settings['group'],tgt_hash.path) + FileUtils.chown(settings['user'], settings['group'], tgt.path) + FileUtils.chown(settings['user'], settings['group'], tgt_hash.path) passwd = '' salt = '' # Create salt file if not there, no matter what, just in case we have an # upgraded system. - if tgt_hash.stat.size.zero? - if options.key?('salt') - salt = options['salt'] - else - salt = gen_salt(options) - end + if tgt_hash.stat.size.zero? # rubocop:disable Style/ZeroLengthPredicate + salt = if options.key?('salt') + options['salt'] + else + gen_salt(options) + end tgt_hash.puts(salt) tgt_hash.rewind end - if tgt.stat.size.zero? - if options.key?('password') - passwd = options['password'] - else - passwd = gen_password(options) - end + if tgt.stat.size.zero? # rubocop:disable Style/ZeroLengthPredicate + passwd = if options.key?('password') + options['password'] + else + gen_password(options) + end tgt.puts(passwd) else passwd = tgt.gets.chomp salt = tgt_hash.gets.chomp - if !options['return_current'] and passwd.length != options['length'] - tgt_last = File.new("#{tgt.path}.last","w+") + if !options['return_current'] && (passwd.length != options['length']) + tgt_last = File.new("#{tgt.path}.last", 'w+') tgt_last.puts(passwd) - tgt_last.chmod(0640) + tgt_last.chmod(0o640) tgt_last.flush tgt_last.close - tgt_hash_last = File.new("#{tgt_hash.path}.last","w+") + tgt_hash_last = File.new("#{tgt_hash.path}.last", 'w+') tgt_hash_last.puts(salt) - tgt_hash_last.chmod(0640) + tgt_hash_last.chmod(0o640) tgt_hash_last.flush tgt_hash_last.close @@ -280,7 +272,7 @@ def get_current_password(identifier, options, settings) end end - tgt.chmod(0640) + tgt.chmod(0o640) tgt.flush tgt.close @@ -293,40 +285,39 @@ def get_current_password(identifier, options, settings) # user about manifest ordering problems, if we had to use the # 'password' in options or had to generate a password. def get_last_password(identifier, options, settings) - toread = nil - if File.exist?("#{settings['keydir']}/#{identifier}.last") - toread = "#{settings['keydir']}/#{identifier}.last" - else - toread = "#{settings['keydir']}/#{identifier}" - end + toread = if File.exist?("#{settings['keydir']}/#{identifier}.last") + "#{settings['keydir']}/#{identifier}.last" + else + "#{settings['keydir']}/#{identifier}" + end passwd = '' salt = '' if File.exist?(toread) passwd = IO.readlines(toread)[0].to_s.chomp - sf = "#{File.dirname(toread)}/#{File.basename(toread,'.last')}.salt.last" - saltfile = File.open(sf,'a+',0640) - if saltfile.stat.size.zero? - if options.key?('salt') - salt = options['salt'] - else - salt = gen_salt(options) - end + sf = "#{File.dirname(toread)}/#{File.basename(toread, '.last')}.salt.last" + saltfile = File.open(sf, 'a+', 0o640) + if saltfile.stat.size.zero? # rubocop:disable Style/ZeroLengthPredicate + salt = if options.key?('salt') + options['salt'] + else + gen_salt(options) + end saltfile.puts(salt) saltfile.close end salt = IO.readlines(sf)[0].to_s.chomp else - warn_msg = "Could not find a primary or 'last' file for " + - "#{identifier}, please ensure that you have included this" + - " function in the proper order in your manifest!" + warn_msg = "Could not find a primary or 'last' file for " \ + "#{identifier}, please ensure that you have included this" \ + ' function in the proper order in your manifest!' Puppet.warning warn_msg - if options.key?('password') - passwd = options['password'] - else - #FIXME? Why doesn't this persist the password? - passwd = gen_password(options) - end + passwd = if options.key?('password') + options['password'] + else + # FIXME? Why doesn't this persist the password? + gen_password(options) + end end [passwd, salt] end @@ -344,7 +335,7 @@ def lockdown_stored_password_perms(settings) file_owner = Etc.getpwuid(file_stat.uid).name file_group = Etc.getgrgid(file_stat.gid).name - unowned_files << file unless (file_owner == settings['user'] || file_group == settings['group'] ) + unowned_files << file unless file_owner == settings['user'] || file_group == settings['group'] rescue ArgumentError => e debug("simplib::passgen: Error getting UID/GID for #{file}: #{e}") @@ -357,20 +348,19 @@ def lockdown_stored_password_perms(settings) FileUtils.chown(settings['user'], settings['group'], file) file_mode = file_stat.mode - desired_mode = symbolic_mode_to_int('u+rwX,g+rX,o-rwx',file_mode,File.directory?(file)) + desired_mode = symbolic_mode_to_int('u+rwX,g+rX,o-rwx', file_mode, File.directory?(file)) - unless (file_mode & 007777) == desired_mode - FileUtils.chmod(desired_mode,file) + unless (file_mode & 0o07777) == desired_mode + FileUtils.chmod(desired_mode, file) end end - unless unowned_files.empty? - err_msg = <<-EOM.gsub(/^\s+/,'') + return if unowned_files.empty? + err_msg = <<-EOM.gsub(%r{^\s+}, '') simplib::passgen: Error: Could not verify ownership by '#{settings['user']}' on the following files: * #{unowned_files.join("\n* ")} EOM - fail(err_msg) - end + raise(err_msg) end end diff --git a/lib/puppet/functions/simplib/passgen/legacy/remove.rb b/lib/puppet/functions/simplib/passgen/legacy/remove.rb index 611b749b..5230e1dd 100644 --- a/lib/puppet/functions/simplib/passgen/legacy/remove.rb +++ b/lib/puppet/functions/simplib/passgen/legacy/remove.rb @@ -10,7 +10,6 @@ # removed by the user. # Puppet::Functions.create_function(:'simplib::passgen::legacy::remove') do - # @param identifier Unique `String` to identify the password usage. # Must conform to the following: # * Identifier must contain only the following characters: @@ -39,23 +38,21 @@ def remove(identifier) File.join(keydir, "#{identifier}.last"), File.join(keydir, "#{identifier}.salt.last"), File.join(keydir, "#{identifier}.last.last"), - File.join(keydir, "#{identifier}.salt.last.last") + File.join(keydir, "#{identifier}.salt.last.last"), ] failures = [] password_files.each do |file| - if File.exist?(file) - begin - File.unlink(file) - rescue Exception => e - failures << "#{file}: #{e.message}" - end + next unless File.exist?(file) + begin + File.unlink(file) + rescue => e + failures << "#{file}: #{e.message}" end end - unless failures.empty? - msg = "Unable to remove all files:\n#{failures.join("\n")}" - raise("simplib::passgen::legacy::delete failed: #{msg}") - end + return if failures.empty? + msg = "Unable to remove all files:\n#{failures.join("\n")}" + raise("simplib::passgen::legacy::delete failed: #{msg}") end end diff --git a/lib/puppet/functions/simplib/passgen/legacy/set.rb b/lib/puppet/functions/simplib/passgen/legacy/set.rb index 00a06e34..6fbe202f 100644 --- a/lib/puppet/functions/simplib/passgen/legacy/set.rb +++ b/lib/puppet/functions/simplib/passgen/legacy/set.rb @@ -9,7 +9,6 @@ # * Terminates catalog compilation if any password files cannot be created/modified by the user. # Puppet::Functions.create_function(:'simplib::passgen::legacy::set') do - # @param identifier Unique `String` to identify the password usage. # Must conform to the following: # * Identifier must contain only the following characters: @@ -46,7 +45,7 @@ optional_param 'String[1]', :group end - def set(identifier, password, salt, user=nil, group=nil) + def set(identifier, password, salt, user = nil, group = nil) settings = call_function('simplib::passgen::legacy::common_settings') # override settings for user and group when those parameters are set @@ -83,11 +82,11 @@ def backup_password_info(keydir, identifier) def move_files(files, source_prefix, dest_prefix) FileUtils.mv(files["#{source_prefix}password"], files["#{dest_prefix}password"], - :force => true) + force: true) if File.exist?(files["#{source_prefix}salt"]) FileUtils.mv(files["#{source_prefix}salt"], files["#{dest_prefix}salt"], - :force => true) + force: true) else # make sure we are clean for manual transaction rollback if needed FileUtils.rm_f(files["#{dest_prefix}salt"]) @@ -103,16 +102,14 @@ def set_password_info(settings, identifier, password, salt) # Create keydir and set permissions # @raise RuntimeError if fails to create or set permissions on keydir def set_up_keydir(settings) - begin - FileUtils.mkdir_p(settings['keydir'], mode: settings['dir_mode']) - FileUtils.chown(settings['user'], settings['group'], settings['keydir']) - rescue SystemCallError => e - err_msg = "simplib::passgen::legacy::set: Could not make directory" + - " #{settings['keydir']}: #{e.message}. Ensure that" + - " #{File.dirname(settings['keydir'])} is writable by" + - " '#{settings['user']}'" - fail(err_msg) - end + FileUtils.mkdir_p(settings['keydir'], mode: settings['dir_mode']) + FileUtils.chown(settings['user'], settings['group'], settings['keydir']) + rescue SystemCallError => e + err_msg = 'simplib::passgen::legacy::set: Could not make directory' \ + " #{settings['keydir']}: #{e.message}. Ensure that" \ + " #{File.dirname(settings['keydir'])} is writable by" \ + " '#{settings['user']}'" + raise(err_msg) end def transaction_filenames(keydir, identifier) @@ -121,14 +118,14 @@ def transaction_filenames(keydir, identifier) 'salt' => File.join(keydir, "#{identifier}.salt"), 'prev_password' => File.join(keydir, "#{identifier}.last"), 'prev_salt' => File.join(keydir, "#{identifier}.salt.last"), - # for manual transaction rollback + # for manual transaction rollback 'prev_prev_password' => File.join(keydir, "#{identifier}.last.last"), 'prev_prev_salt' => File.join(keydir, "#{identifier}.salt.last.last") } end def write_file(file, content, settings) - File.open(file, 'w') { |file| file.puts content } + File.open(file, 'w') { |fh| fh.puts content } File.chmod(settings['file_mode'], file) FileUtils.chown(settings['user'], settings['group'], file) end diff --git a/lib/puppet/functions/simplib/passgen/list.rb b/lib/puppet/functions/simplib/passgen/list.rb index 0191ec5e..4917c54e 100644 --- a/lib/puppet/functions/simplib/passgen/list.rb +++ b/lib/puppet/functions/simplib/passgen/list.rb @@ -20,7 +20,6 @@ # in hieradata. When that setting absent or false, legacy mode will be used. # Puppet::Functions.create_function(:'simplib::passgen::list') do - # @param folder Unique `String` to identify the password sub-folder # of the root folder for simplib::passgen # * Only applies when in simpkv mode @@ -112,18 +111,15 @@ optional_param 'Hash', :simpkv_options end - def list(folder='/', simpkv_options={'app_id' => 'simplib::passgen'}) + def list(folder = '/', simpkv_options = { 'app_id' => 'simplib::passgen' }) use_simpkv = call_function('lookup', 'simplib::passgen::simpkv', { 'default_value' => false }) - - results = nil - if use_simpkv - results = call_function('simplib::passgen::simpkv::list', folder, - simpkv_options) - else - results = call_function('simplib::passgen::legacy::list') - end + results = if use_simpkv + call_function('simplib::passgen::simpkv::list', folder, + simpkv_options) + else + call_function('simplib::passgen::legacy::list') + end results end end - diff --git a/lib/puppet/functions/simplib/passgen/remove.rb b/lib/puppet/functions/simplib/passgen/remove.rb index f3a7d1dc..3cce45c4 100644 --- a/lib/puppet/functions/simplib/passgen/remove.rb +++ b/lib/puppet/functions/simplib/passgen/remove.rb @@ -20,7 +20,6 @@ # in hieradata. When that setting absent or false, legacy mode will be used. # Puppet::Functions.create_function(:'simplib::passgen::remove') do - # @param identifier Unique `String` to identify the password usage. # Must conform to the following: # * Identifier must contain only the following characters: @@ -104,7 +103,7 @@ optional_param 'Hash', :simpkv_options end - def remove(identifier, simpkv_options={'app_id' => 'simplib::passgen'}) + def remove(identifier, simpkv_options = { 'app_id' => 'simplib::passgen' }) use_simpkv = call_function('lookup', 'simplib::passgen::simpkv', { 'default_value' => false }) diff --git a/lib/puppet/functions/simplib/passgen/set.rb b/lib/puppet/functions/simplib/passgen/set.rb index a84b56e8..a93e0c5b 100644 --- a/lib/puppet/functions/simplib/passgen/set.rb +++ b/lib/puppet/functions/simplib/passgen/set.rb @@ -30,7 +30,6 @@ # in hieradata. When that setting absent or false, legacy mode will be used. # Puppet::Functions.create_function(:'simplib::passgen::set') do - # @param identifier Unique `String` to identify the password usage. # Must conform to the following: # * Identifier must contain only the following characters: @@ -155,7 +154,7 @@ end def set(identifier, password, salt, password_options, - simpkv_options={'app_id' => 'simplib::passgen'}) + simpkv_options = { 'app_id' => 'simplib::passgen' }) use_simpkv = call_function('lookup', 'simplib::passgen::simpkv', { 'default_value' => false }) @@ -163,12 +162,12 @@ def set(identifier, password, salt, password_options, if use_simpkv unless password_options.key?('complexity') msg = "simplib::passgen::set: password_options must contain 'complexity' in simpkv mode" - raise ArgumentError.new(msg) + raise ArgumentError, msg end unless password_options.key?('complex_only') msg = "simplib::passgen::set: password_options must contain 'complex_only' in simpkv mode" - raise ArgumentError.new(msg) + raise ArgumentError, msg end call_function('simplib::passgen::simpkv::set', identifier, password, salt, diff --git a/lib/puppet/functions/simplib/passgen/simpkv/get.rb b/lib/puppet/functions/simplib/passgen/simpkv/get.rb index 960cdca0..a7b79881 100644 --- a/lib/puppet/functions/simplib/passgen/simpkv/get.rb +++ b/lib/puppet/functions/simplib/passgen/simpkv/get.rb @@ -4,7 +4,6 @@ # Terminates catalog compilation if any simpkv operation fails. # Puppet::Functions.create_function(:'simplib::passgen::simpkv::get') do - # @param identifier Unique `String` to identify the password usage. # Must conform to the following: # * Identifier must contain only the following characters: @@ -91,7 +90,7 @@ optional_param 'Hash', :simpkv_options end - def get(identifier, simpkv_options={'app_id' => 'simplib::passgen'}) + def get(identifier, simpkv_options = { 'app_id' => 'simplib::passgen' }) key_root_dir = call_function('simplib::passgen::simpkv::root_dir') key = "#{key_root_dir}/#{identifier}" password_info = {} diff --git a/lib/puppet/functions/simplib/passgen/simpkv/list.rb b/lib/puppet/functions/simplib/passgen/simpkv/list.rb index a8e9e010..1059ca4d 100644 --- a/lib/puppet/functions/simplib/passgen/simpkv/list.rb +++ b/lib/puppet/functions/simplib/passgen/simpkv/list.rb @@ -6,7 +6,6 @@ # * Terminates catalog compilation if any simpkv operation fails. # Puppet::Functions.create_function(:'simplib::passgen::simpkv::list') do - # @param folder Unique `String` to identify the password sub-folder # of the root folder for simplib::passgen # * When unset or '', the list operation will be for the root folder @@ -96,7 +95,7 @@ optional_param 'Hash', :simpkv_options end - def list(folder='/', simpkv_options={'app_id' => 'simplib::passgen'}) + def list(folder = '/', simpkv_options = { 'app_id' => 'simplib::passgen' }) root_dir = call_function('simplib::passgen::simpkv::root_dir') keydir = File.join(root_dir, folder) @@ -104,7 +103,7 @@ def list(folder='/', simpkv_options={'app_id' => 'simplib::passgen'}) if call_function('simpkv::exists', keydir, simpkv_options) raw_results = call_function('simpkv::list', keydir, simpkv_options) results = { 'keys' => {}, 'folders' => raw_results['folders'] } - raw_results['keys'].each do |id,info| + raw_results['keys'].each do |id, info| if call_function('simplib::passgen::simpkv::valid_password_info', info) results['keys'][id] = info else @@ -118,4 +117,3 @@ def list(folder='/', simpkv_options={'app_id' => 'simplib::passgen'}) results end end - diff --git a/lib/puppet/functions/simplib/passgen/simpkv/passgen.rb b/lib/puppet/functions/simplib/passgen/simpkv/passgen.rb index 79c56a86..758ec5be 100644 --- a/lib/puppet/functions/simplib/passgen/simpkv/passgen.rb +++ b/lib/puppet/functions/simplib/passgen/simpkv/passgen.rb @@ -9,7 +9,6 @@ # in the allotted time. # Puppet::Functions.create_function(:'simplib::passgen::simpkv::passgen') do - # @param identifier Unique `String` to identify the password usage. # Must conform to the following: # * Identifier must contain only the following characters: @@ -138,7 +137,7 @@ optional_param 'Hash', :simpkv_options end - def passgen(identifier, password_options={}, simpkv_options={'app_id' => 'simplib::passgen'}) + def passgen(identifier, password_options = {}, simpkv_options = { 'app_id' => 'simplib::passgen' }) require 'timeout' # internal settings @@ -166,23 +165,20 @@ def passgen(identifier, password_options={}, simpkv_options={'app_id' => 'simpli salt = nil begin if options['last'] - password,salt = get_last_password(identifier, options, simpkv_options) + password, salt = get_last_password(identifier, options, simpkv_options) else - password,salt = get_current_password(identifier, options, simpkv_options) + password, salt = get_current_password(identifier, options, simpkv_options) end - rescue Timeout::Error => e + rescue Timeout::Error # can get here if password/salt generation timed out - fail("simplib::passgen timed out for '#{identifier}'!") + raise("simplib::passgen timed out for '#{identifier}'!") end # Return the hash, not the password - if options['hash'] - return password.crypt("$#{settings['crypt_map'][options['hash']]}$#{salt}") - else - return password - end - end + return password.crypt("$#{settings['crypt_map'][options['hash']]}$#{salt}") if options['hash'] + password + end # Build a merged options hash and validate the options # @raise ArgumentError if any option in the password_options is invalid @@ -192,11 +188,11 @@ def build_options(base_options, password_options, settings) # set internal options that help us validate whether a retrieved # password meets current criteria - options['length_configured'] = password_options.has_key?('length') - options['complexity_configured'] = password_options.has_key?('complexity') - options['complex_only_configured'] = password_options.has_key?('complex_only') + options['length_configured'] = password_options.key?('length') + options['complexity_configured'] = password_options.key?('complexity') + options['complex_only_configured'] = password_options.key?('complex_only') - if options['length'].to_s !~ /^\d+$/ + if !%r{^\d+$}.match?(options['length'].to_s) raise ArgumentError, "simplib::passgen: Error: Length '#{options['length']}' must be an integer!" else @@ -208,14 +204,14 @@ def build_options(base_options, password_options, settings) end end - if options['complexity'].to_s !~ /^\d+$/ + if !%r{^\d+$}.match?(options['complexity'].to_s) raise ArgumentError, "simplib::passgen: Error: Complexity '#{options['complexity']}' must be an integer!" else options['complexity'] = options['complexity'].to_i end - if options['gen_timeout_seconds'].to_s !~ /^\d+$/ + if !%r{^\d+$}.match?(options['gen_timeout_seconds'].to_s) raise ArgumentError, "simplib::passgen: Error: Password generation timeout '#{options['gen_timeout_seconds']}' must be an integer!" else @@ -226,12 +222,12 @@ def build_options(base_options, password_options, settings) if options['hash'] == true options['hash'] = 'sha256' end - if options['hash'] and !settings['crypt_map'].keys.include?(options['hash']) + if options['hash'] && !settings['crypt_map'].keys.include?(options['hash']) raise ArgumentError, "simplib::passgen: Error: '#{options['hash']}' is not a valid hash." end - return options + options end # Create a pair and then store it, pertinent options, and @@ -248,8 +244,7 @@ def create_and_store_password(identifier, options, simpkv_options) options['length'], options['complexity'], options['complex_only'], - options['gen_timeout_seconds'] - ) + options['gen_timeout_seconds']) call_function('simplib::passgen::simpkv::set', identifier, password, salt, options['complexity'], @@ -275,7 +270,6 @@ def create_and_store_password(identifier, options, simpkv_options) def get_current_password(identifier, options, simpkv_options) password = nil salt = nil - history = [] generate = false password_info = call_function('simplib::passgen::simpkv::get', identifier, @@ -320,16 +314,16 @@ def get_last_password(identifier, options, simpkv_options) simpkv_options) if password_info.empty? - warn_msg = "Could not retrieve a last or current value for" + - " #{identifier}. Generating a new value for 'last'. Please ensure" + - " that you have used simplib::passgen in the proper order in your" + - " manifest!" + warn_msg = 'Could not retrieve a last or current value for' \ + " #{identifier}. Generating a new value for 'last'. Please ensure" \ + ' that you have used simplib::passgen in the proper order in your' \ + ' manifest!' Puppet.warning warn_msg # generate password and salt and then store password, salt = create_and_store_password(identifier, options, simpkv_options) elsif !password_info['metadata']['history'].empty? - password,salt = password_info['metadata']['history'].first + password, salt = password_info['metadata']['history'].first else password = password_info['value']['password'] salt = password_info['value']['salt'] @@ -344,21 +338,21 @@ def get_last_password(identifier, options, simpkv_options) # @param options current options def valid_password?(password_info, options) if options['length_configured'] - unless (password_info['value']['password'].length == options['length']) + unless password_info['value']['password'].length == options['length'] return false end end if options['complexity_configured'] - unless ( password_info['metadata'].key?('complexity') && - (password_info['metadata']['complexity'] == options['complexity']) ) + unless password_info['metadata'].key?('complexity') && + (password_info['metadata']['complexity'] == options['complexity']) return false end end if options['complex_only_configured'] - unless ( password_info['metadata'].key?('complex_only') && - (password_info['metadata']['complex_only'] == options['complex_only']) ) + unless password_info['metadata'].key?('complex_only') && + (password_info['metadata']['complex_only'] == options['complex_only']) return false end end diff --git a/lib/puppet/functions/simplib/passgen/simpkv/remove.rb b/lib/puppet/functions/simplib/passgen/simpkv/remove.rb index 6a76762a..3602c211 100644 --- a/lib/puppet/functions/simplib/passgen/simpkv/remove.rb +++ b/lib/puppet/functions/simplib/passgen/simpkv/remove.rb @@ -5,7 +5,6 @@ # * Terminates catalog compilation if any simpkv operation fails. # Puppet::Functions.create_function(:'simplib::passgen::simpkv::remove') do - # @param identifier Unique `String` to identify the password usage. # Must conform to the following: # * Identifier must contain only the following characters: @@ -87,11 +86,10 @@ optional_param 'Hash', :simpkv_options end - def remove(identifier, simpkv_options={'app_id' => 'simplib::passgen'}) + def remove(identifier, simpkv_options = { 'app_id' => 'simplib::passgen' }) key_root_dir = call_function('simplib::passgen::simpkv::root_dir') key = "#{key_root_dir}/#{identifier}" - if call_function('simpkv::exists', key, simpkv_options) - call_function('simpkv::delete', key, simpkv_options) - end + return unless call_function('simpkv::exists', key, simpkv_options) + call_function('simpkv::delete', key, simpkv_options) end end diff --git a/lib/puppet/functions/simplib/passgen/simpkv/root_dir.rb b/lib/puppet/functions/simplib/passgen/simpkv/root_dir.rb index 25de69c9..3b04c8a7 100644 --- a/lib/puppet/functions/simplib/passgen/simpkv/root_dir.rb +++ b/lib/puppet/functions/simplib/passgen/simpkv/root_dir.rb @@ -2,7 +2,6 @@ # simplib::passgen # Puppet::Functions.create_function(:'simplib::passgen::simpkv::root_dir') do - # @return [String] root directory in simpkv for password info generated by # simplib::passgen # diff --git a/lib/puppet/functions/simplib/passgen/simpkv/set.rb b/lib/puppet/functions/simplib/passgen/simpkv/set.rb index abf114f3..221c4f68 100644 --- a/lib/puppet/functions/simplib/passgen/simpkv/set.rb +++ b/lib/puppet/functions/simplib/passgen/simpkv/set.rb @@ -13,7 +13,6 @@ # * Terminates catalog compilation if any simpkv operation fails. # Puppet::Functions.create_function(:'simplib::passgen::simpkv::set') do - # @param identifier # Unique `String` to identify the password usage. # Must conform to the following: @@ -114,7 +113,7 @@ end def set(identifier, password, salt, complexity, complex_only, - simpkv_options={'app_id' => 'simplib::passgen'}) + simpkv_options = { 'app_id' => 'simplib::passgen' }) key_root_dir = call_function('simplib::passgen::simpkv::root_dir') key = "#{key_root_dir}/#{identifier}" @@ -125,7 +124,7 @@ def set(identifier, password, salt, complexity, complex_only, 'history' => get_history(identifier, simpkv_options) } - # TODO If simpkv is updated to allow transaction locks, lock prior to + # TODO: If simpkv is updated to allow transaction locks, lock prior to # get_history() which calls simpkv::get under the hood, and release the # lock after this simpkv::put call. call_function('simpkv::put', key, key_info, metadata, simpkv_options) @@ -138,10 +137,12 @@ def get_history(identifier, simpkv_options) history = [] unless last_password_info.empty? history = last_password_info['metadata']['history'].dup - history.unshift([ - last_password_info['value']['password'], - last_password_info['value']['salt'] - ]) + history.unshift( + [ + last_password_info['value']['password'], + last_password_info['value']['salt'], + ], + ) # only keep the last 10 pairs history = history[0..9] diff --git a/lib/puppet/functions/simplib/passgen/simpkv/valid_password_info.rb b/lib/puppet/functions/simplib/passgen/simpkv/valid_password_info.rb index 4a278bd6..732f9b6d 100644 --- a/lib/puppet/functions/simplib/passgen/simpkv/valid_password_info.rb +++ b/lib/puppet/functions/simplib/passgen/simpkv/valid_password_info.rb @@ -1,7 +1,6 @@ # Returns whether password information retrieved from simpkv is valid # Puppet::Functions.create_function(:'simplib::passgen::simpkv::valid_password_info') do - # @param password_info Hash of password information retrieved from simpkv # * 'value'- Hash that should contain 'password' and 'salt' attributes # * 'metadata' - Hash that should contain 'complexity', 'complex_only' and @@ -17,11 +16,10 @@ def valid_password_info(password_info) password_info['value'].key?('password') && - password_info['value'].key?('salt') && - password_info.key?('metadata') && - password_info['metadata'].key?('complexity') && - password_info['metadata'].key?('complex_only') && - password_info['metadata'].key?('history') + password_info['value'].key?('salt') && + password_info.key?('metadata') && + password_info['metadata'].key?('complexity') && + password_info['metadata'].key?('complex_only') && + password_info['metadata'].key?('history') end end - diff --git a/lib/puppet/functions/simplib/rand_cron.rb b/lib/puppet/functions/simplib/rand_cron.rb index f5890abc..e3e007f2 100644 --- a/lib/puppet/functions/simplib/rand_cron.rb +++ b/lib/puppet/functions/simplib/rand_cron.rb @@ -3,7 +3,6 @@ # time on all servers. Puppet::Functions.create_function(:'simplib::rand_cron') do - local_types do type "RandCronAlgorithm = Enum['crc32', 'ip_mod', 'sha256']" end @@ -79,17 +78,16 @@ def generate_ip_mod_number(input_string) ip_num = nil begin - ip_num = IPAddr.new(input_string).to_i + ip_num = IPAddr.new(input_string).to_i rescue IPAddr::Error + # do nothing end - - num = nil - if ip_num.nil? - # crc32 calculation for backward compatibility - num = generate_crc32_number(input_string) - else - num = ip_num - end + num = if ip_num.nil? + # crc32 calculation for backward compatibility + generate_crc32_number(input_string) + else + ip_num + end num end @@ -105,7 +103,7 @@ def generate_sha256_number(input_string) # # @return Integer to be used as a basis for generated cron values def generate_numeric_modifier(modifier, algorithm) - eval("generate_#{algorithm}_number(modifier)") + send("generate_#{algorithm}_number", modifier) end def rand_cron(modifier, algorithm, occurs = 1, max_value = 59) @@ -113,15 +111,13 @@ def rand_cron(modifier, algorithm, occurs = 1, max_value = 59) modulus = max_value + 1 base = range_modifier % modulus - values = [] - if occurs == 1 - values << base - else - values = Array.new - (1..occurs).each do |i| - values << ((base - (modulus / occurs * i)) % modulus) - end - end - return values.sort + values = if occurs == 1 + [base] + else + (1..occurs).map do |i| + ((base - (modulus / occurs * i)) % modulus) + end + end + values.sort end end diff --git a/lib/puppet/functions/simplib/simp_version.rb b/lib/puppet/functions/simplib/simp_version.rb index 21dd0ef1..3b7bdea2 100644 --- a/lib/puppet/functions/simplib/simp_version.rb +++ b/lib/puppet/functions/simplib/simp_version.rb @@ -1,6 +1,5 @@ # Return the version of SIMP that this server is running or "unknown\n" Puppet::Functions.create_function(:'simplib::simp_version') do - # @param strip_whitespace Whether to strip whitespace from the # version string. Without stripping, the string may end with # a "\n" @@ -19,15 +18,15 @@ def simp_version(strip_whitespace = false) version_file = 'C:\ProgramData\SIMP\simp.version' if is_windows if File.readable?(version_file) - # TODO Figure out under what circumstances the version string is prefaced + # TODO: Figure out under what circumstances the version string is prefaced # with 'simp-'. This is not true for SIMP 6.x - version = File.read(version_file).gsub('simp-','') + version = File.read(version_file).gsub('simp-', '') retval = version unless version.strip.empty? elsif !is_windows - rpm_query = %q{PATH='/usr/local/bin:/usr/bin:/bin' rpm -q --qf '%{VERSION}-%{RELEASE}\n' simp 2>/dev/null} + rpm_query = %q(PATH='/usr/local/bin:/usr/bin:/bin' rpm -q --qf '%{VERSION}-%{RELEASE}\n' simp 2>/dev/null) begin - version = Puppet::Util::Execution.execute(rpm_query, :failonfail => true) + version = Puppet::Util::Execution.execute(rpm_query, failonfail: true) rescue version = nil end diff --git a/lib/puppet/functions/simplib/strip_ports.rb b/lib/puppet/functions/simplib/strip_ports.rb index 30e6110a..c2c051ae 100644 --- a/lib/puppet/functions/simplib/strip_ports.rb +++ b/lib/puppet/functions/simplib/strip_ports.rb @@ -7,7 +7,6 @@ # * Any input item that contains a port specifies an invalid port. # Puppet::Functions.create_function(:'simplib::strip_ports') do - # @param hosts List of hosts which may contain protocols and port numbers. # # @return [Array[String]] Non-port portion of hostnames diff --git a/lib/puppet/functions/simplib/to_integer.rb b/lib/puppet/functions/simplib/to_integer.rb index 2fa8c870..8b49fc0e 100644 --- a/lib/puppet/functions/simplib/to_integer.rb +++ b/lib/puppet/functions/simplib/to_integer.rb @@ -4,7 +4,6 @@ # does not respond to the `to_i()` Ruby method. # Puppet::Functions.create_function(:'simplib::to_integer') do - # @param input The argument to convert into an `Integer` # @return [Integer] Converted input # @raise [RuntimeError] if ``input`` does not implement a ``to_i()`` @@ -16,10 +15,8 @@ def to_integer(input) return input if input.is_a?(Integer) - if input.respond_to?(:to_i) - return input.to_i - else - fail("simplib::to_integer(): Object type '#{input.class}' cannot be converted to an Integer") - end + return input.to_i if input.respond_to?(:to_i) + + raise("simplib::to_integer(): Object type '#{input.class}' cannot be converted to an Integer") end end diff --git a/lib/puppet/functions/simplib/to_string.rb b/lib/puppet/functions/simplib/to_string.rb index 90d15859..4467c13d 100644 --- a/lib/puppet/functions/simplib/to_string.rb +++ b/lib/puppet/functions/simplib/to_string.rb @@ -1,7 +1,6 @@ # Converts the argument into a `String`. # Puppet::Functions.create_function(:'simplib::to_string') do - # @param input The argument to convert into a `String` # @return [String] Converted input dispatch :to_string do @@ -11,12 +10,10 @@ def to_string(input) return input if input.is_a?(String) - if input.respond_to?(:to_s) - return input.to_s - else - # Should not be able to get here with Puppet, especially since - # Ruby provides a `to_s()` method for all objects - fail("simplib::to_string(): Object type '#{input.class}' cannot be converted to a String") - end + return input.to_s if input.respond_to?(:to_s) + + # Should not be able to get here with Puppet, especially since + # Ruby provides a `to_s()` method for all objects + raise("simplib::to_string(): Object type '#{input.class}' cannot be converted to a String") end end diff --git a/lib/puppet/functions/simplib/validate_array_member.rb b/lib/puppet/functions/simplib/validate_array_member.rb index 2d4810eb..ce712fb1 100644 --- a/lib/puppet/functions/simplib/validate_array_member.rb +++ b/lib/puppet/functions/simplib/validate_array_member.rb @@ -5,7 +5,6 @@ # * Terminates catalog compilation if validation fails. # Puppet::Functions.create_function(:'simplib::validate_array_member') do - local_types do type 'SimpleTypes = Variant[String,Numeric,Boolean]' end @@ -31,39 +30,36 @@ # validate_array_member(['foo','bar'],['FOO','BAR','BAZ'], 'i') # succeeds # dispatch :validate_array_member do - required_param 'Variant[SimpleTypes,Array[SimpleTypes]]',:input - required_param 'Array[SimpleTypes]',:target + required_param 'Variant[SimpleTypes,Array[SimpleTypes]]', :input + required_param 'Array[SimpleTypes]', :target optional_param "Enum['i']", :modifier end - def validate_array_member(input, target, modifier=nil) + def validate_array_member(input, target, modifier = nil) to_compare = Array(input).dup target_array = target.dup if modifier if modifier == 'i' - to_compare.map!{ |x| - if x.is_a?(String) - x.downcase - else - x - end - } + to_compare.map! do |x| + if x.is_a?(String) + x.downcase + else + x + end + end - target_array.map!{ |x| - if x.is_a?(String) - x.downcase - else - x - end - } + target_array.map! do |x| + if x.is_a?(String) + x.downcase + else + x + end + end end end - unless (to_compare - target_array).empty? - fail("simplib::validate_array_member(): '#{target}' does not contain '#{input}'") - end - + return if (to_compare - target_array).empty? + raise("simplib::validate_array_member(): '#{target}' does not contain '#{input}'") end - end diff --git a/lib/puppet/functions/simplib/validate_between.rb b/lib/puppet/functions/simplib/validate_between.rb index 36616ff2..0869c274 100644 --- a/lib/puppet/functions/simplib/validate_between.rb +++ b/lib/puppet/functions/simplib/validate_between.rb @@ -4,7 +4,6 @@ # Terminates catalog compilation if validation fails. # Puppet::Functions.create_function(:'simplib::validate_between') do - # @param value Value to validate # @param min_value Minimum value that is valid # @param max_value Maximum value that is valid @@ -29,12 +28,11 @@ def validate_between(value, min_value, max_value) numeric_value = value.to_f - unless numeric_value >= min_value and numeric_value <= max_value - # The original method was used in SIMP modules as if it raised an - # exception, so this implementation will work as expected. - err_msg = "simplib::validate_between: '#{value}' is not between" + - " '#{min_value}' and '#{max_value}'" - fail(err_msg) - end + return if (numeric_value >= min_value) && (numeric_value <= max_value) + # The original method was used in SIMP modules as if it raised an + # exception, so this implementation will work as expected. + err_msg = "simplib::validate_between: '#{value}' is not between" \ + " '#{min_value}' and '#{max_value}'" + raise(err_msg) end end diff --git a/lib/puppet/functions/simplib/validate_bool.rb b/lib/puppet/functions/simplib/validate_bool.rb index 10ceaa39..9337935e 100644 --- a/lib/puppet/functions/simplib/validate_bool.rb +++ b/lib/puppet/functions/simplib/validate_bool.rb @@ -4,7 +4,6 @@ # Terminates catalog compilation if validation fails. # Puppet::Functions.create_function(:'simplib::validate_bool') do - # @param values_to_validate One or more values to validate # @return [Nil] # @raise [RuntimeError] if validation fails @@ -29,8 +28,8 @@ def validate_bool(*values_to_validate) valid_entries = [true, false, 'true', 'false'] values_to_validate.each do |value| - unless valid_entries.include?(value) then - fail("simplib::validate_bool: '#{value}' is not a boolean.") + unless valid_entries.include?(value) + raise("simplib::validate_bool: '#{value}' is not a boolean.") end end end diff --git a/lib/puppet/functions/simplib/validate_deep_hash.rb b/lib/puppet/functions/simplib/validate_deep_hash.rb index 865f3609..499dbd97 100644 --- a/lib/puppet/functions/simplib/validate_deep_hash.rb +++ b/lib/puppet/functions/simplib/validate_deep_hash.rb @@ -11,7 +11,6 @@ # * Terminates catalog compilation if validation fails. # Puppet::Functions.create_function(:'simplib::validate_deep_hash') do - # @param reference Hash to validate against. Keys at all levels of # the hash define the structure of the hash and the value at each # final leaf in the hash tree contains a regular expression string, @@ -84,18 +83,18 @@ def validate_deep_hash(reference, to_check) invalid = deep_validate(reference, to_check) - if invalid.size > 0 then - err_msg = "simplib::validate_deep_hash failed validation:\n " - err_msg += invalid.join("\n ") - fail(err_msg) - end + return unless !invalid.empty? + + err_msg = "simplib::validate_deep_hash failed validation:\n " + err_msg += invalid.join("\n ") + raise(err_msg) end def valid_value(value) [String, TrueClass, FalseClass, Numeric, NilClass].each do |allowed_class| return true if value.is_a?(allowed_class) end - return false + false end def compare(ref_value, to_check_value) @@ -107,20 +106,20 @@ def compare(ref_value, to_check_value) return :invalid_check_type unless value.respond_to?(:to_s) return :failed_check unless Regexp.new(ref_string).match(value.to_s) end - return :success + :success end - def deep_validate(reference, to_check, level="TOP", invalid = Array.new) - to_check.each do |key,value| - if reference.has_key?(key) + def deep_validate(reference, to_check, level = 'TOP', invalid = []) + to_check.each do |key, value| + if reference.key?(key) # skip over keys for which further validation has been disabled - next if reference[key].nil? or reference[key] == 'nil' + next if reference[key].nil? || (reference[key] == 'nil') # Step down a level if value is another hash if value.is_a?(Hash) if reference[key].is_a?(Hash) ref_key_hash = reference[key] - deep_validate(ref_key_hash, value, level+"-->#{key}", invalid) + deep_validate(ref_key_hash, value, level + "-->#{key}", invalid) else invalid << level + "-->#{key} should not be a Hash" end @@ -130,23 +129,23 @@ def deep_validate(reference, to_check, level="TOP", invalid = Array.new) result = compare(reference[key], to_check[key]) case result when :invalid_ref_type - err_msg = "simplib::validate_deep_hash(): Check for " + - level + "-->#{key} has invalid type '#{reference[key].class}'" - raise ArgumentError.new(err_msg) + err_msg = 'simplib::validate_deep_hash(): Check for ' + + level + "-->#{key} has invalid type '#{reference[key].class}'" + raise ArgumentError, err_msg when :invalid_check_type - invalid << level + "-->#{key} #{to_check[key].class} cannot" + - " be converted to string for comparison" + invalid << level + "-->#{key} #{to_check[key].class} cannot" \ + ' be converted to string for comparison' when :failed_check - invalid << level + "-->#{key} '#{to_check[key]}' must" + - " validate against '/#{reference[key]}/'" + invalid << level + "-->#{key} '#{to_check[key]}' must" \ + " validate against '/#{reference[key]}/'" end end else - invalid << (level+"-->#{key} not in reference hash") + invalid << (level + "-->#{key} not in reference hash") end end - return invalid + invalid end end diff --git a/lib/puppet/functions/simplib/validate_net_list.rb b/lib/puppet/functions/simplib/validate_net_list.rb index bb24d37e..1b609ae3 100644 --- a/lib/puppet/functions/simplib/validate_net_list.rb +++ b/lib/puppet/functions/simplib/validate_net_list.rb @@ -8,7 +8,6 @@ # * Terminates catalog compilation if validation fails. # Puppet::Functions.create_function(:'simplib::validate_net_list') do - # @param net Single network to be validated. # @param str_match Stringified regular expression (regex without # the `//` delimiters) @@ -68,32 +67,32 @@ optional_param 'String', :str_match end - def validate_net(net, str_match=nil) + def validate_net(net, str_match = nil) validate_net_list(Array(net), str_match) end - def validate_net_list(net_list, str_match=nil) - local_net_list = Array(net_list.dup) # not allowed to modify arguments + def validate_net_list(net_list, str_match = nil) + local_net_list = Array(net_list.dup) # not allowed to modify arguments if str_match - # hack to be backward compatible + # HACK: to be backward compatible local_str_match = str_match.dup local_str_match = '\*' if local_str_match == '*' local_str_match = Regexp.new(local_str_match) - local_net_list.delete_if{|x| local_str_match.match(x)} + local_net_list.delete_if { |x| local_str_match.match(x) } end require File.expand_path(File.dirname(__FILE__) + '/../../../puppetx/simp/simplib.rb') require 'ipaddr' # Needed to use other functions inside of this one -# Puppet::Parser::Functions.autoloader.loadall + # Puppet::Parser::Functions.autoloader.loadall local_net_list.each do |net| # Do we have a port? - host,port = PuppetX::SIMP::Simplib.split_port(net) - call_function('simplib::validate_port', port) if (port && !port.empty?) + host, port = PuppetX::SIMP::Simplib.split_port(net) + call_function('simplib::validate_port', port) if port && !port.empty? # Valid quad-dotted IPv4 addresses will validate as hostnames. # So check for IP addresses first @@ -106,13 +105,13 @@ def validate_net_list(net_list, str_match=nil) # it is not an oddly-named host, but a bad IPv4 address in which # one or more of the octets is out of range (configuration # fat-finger....) - if host.match(/^([0-9]+)(\.[0-9]+){3}$/) - fail("simplib::validate_net_list(): '#{net}' is not a valid network.") + if host.match?(%r{^([0-9]+)(\.[0-9]+){3}$}) + raise("simplib::validate_net_list(): '#{net}' is not a valid network.") end # assume OK if this looks like hostname unless PuppetX::SIMP::Simplib.hostname_only?(host) - fail("simplib::validate_net_list(): '#{net}' is not a valid network.") + raise("simplib::validate_net_list(): '#{net}' is not a valid network.") end end end diff --git a/lib/puppet/functions/simplib/validate_port.rb b/lib/puppet/functions/simplib/validate_port.rb index b2c63c67..06927fb9 100644 --- a/lib/puppet/functions/simplib/validate_port.rb +++ b/lib/puppet/functions/simplib/validate_port.rb @@ -36,8 +36,8 @@ def validate_ports(*port_args) ports = Array(port_args).flatten ports.each do |port| - if not port.to_i.between?(1,65535) then - fail("simplib::validate_ports: '#{port}' is not a valid port.") + unless port.to_i.between?(1, 65_535) + raise("simplib::validate_ports: '#{port}' is not a valid port.") end end end diff --git a/lib/puppet/functions/simplib/validate_re_array.rb b/lib/puppet/functions/simplib/validate_re_array.rb index 0f44ea60..6d96ff8b 100644 --- a/lib/puppet/functions/simplib/validate_re_array.rb +++ b/lib/puppet/functions/simplib/validate_re_array.rb @@ -5,7 +5,6 @@ # * Terminates catalog compilation if validation fails. # Puppet::Functions.create_function(:'simplib::validate_re_array') do - # @param input String to be validated # @param regex Stringified regex expression (regex without the `//` # delimiters) @@ -100,24 +99,23 @@ optional_param 'String', :err_msg end - def validate_re_array_1_to_1(input, regex, err_msg=nil) + def validate_re_array_1_to_1(input, regex, err_msg = nil) validate_re_array([ input ], [ regex ], err_msg) end - def validate_re_array_n_to_1(inputs, regex, err_msg=nil) + def validate_re_array_n_to_1(inputs, regex, err_msg = nil) validate_re_array(inputs, [ regex ], err_msg) end - def validate_re_array_1_to_n(input, regex_list, err_msg=nil) + def validate_re_array_1_to_n(input, regex_list, err_msg = nil) validate_re_array([ input ], regex_list, err_msg) end - def validate_re_array(inputs, regex_list, err_msg=nil) - + def validate_re_array(inputs, regex_list, err_msg = nil) inputs.each do |to_check| valid = false regex_list.each do |re_str| - if "#{to_check}" =~ Regexp.compile(re_str) + if to_check.to_s&.match?(Regexp.compile(re_str)) valid = true break end @@ -126,9 +124,8 @@ def validate_re_array(inputs, regex_list, err_msg=nil) # Bail at the first failure. unless valid msg = err_msg || "simplib::validate_re_array(): #{to_check.inspect} does not match #{regex_list.inspect}" - fail(msg) + raise(msg) end end - end end diff --git a/lib/puppet/functions/simplib/validate_sysctl_value.rb b/lib/puppet/functions/simplib/validate_sysctl_value.rb index d23ff9a6..9520422f 100644 --- a/lib/puppet/functions/simplib/validate_sysctl_value.rb +++ b/lib/puppet/functions/simplib/validate_sysctl_value.rb @@ -4,7 +4,6 @@ # * Terminates catalog compilation if validation fails. # Puppet::Functions.create_function(:'simplib::validate_sysctl_value') do - # @param key sysctl setting whose value is to be validated # @param value Value to be validated # @return [Nil] @@ -13,15 +12,14 @@ # validate_sysctl_value('kernel.core_pattern','/var/core/%u_%g_%p_%t_%h_%e.core') dispatch :validate_sysctl_value do - required_param 'String',:key - required_param 'NotUndef',:value + required_param 'String', :key + required_param 'NotUndef', :value end def validate_sysctl_value(key, value) + key_method_name = key.to_s.gsub('.', '__') - key_method_name = key.to_s.gsub('.','__') - - self.send(key_method_name, key, value) if self.respond_to?(key_method_name) + send(key_method_name, key, value) if respond_to?(key_method_name) end # Below are the recognized validation methods @@ -35,12 +33,10 @@ def kernel__core_pattern(key, value) validate_sysctl_err("Values for #{key} must be less than 129 characters") end - if value =~ /\|\s*(\S*)/ - require 'puppet/util' - unless Puppet::Util.absolute_path?($1, :posix) - validate_sysctl_err("Piped commands for #{key} must have an absolute path") - end - end + return unless value =~ %r{\|\s*(\S*)} + require 'puppet/util' + return if Puppet::Util.absolute_path?(Regexp.last_match(1), :posix) + validate_sysctl_err("Piped commands for #{key} must have an absolute path") end def fs__inotify__max_user_watches(key, value) @@ -50,21 +46,19 @@ def fs__inotify__max_user_watches(key, value) system_ram_mb = closure_scope['facts']['memorysize_mb'] - if system_ram_mb - system_ram_mb = system_ram_mb.to_i + return unless system_ram_mb + system_ram_mb = system_ram_mb.to_i - size_multiplier = 512 - size_multiplier = 1024 if (closure_scope['facts']['architecture'] == 'x86_64') + size_multiplier = 512 + size_multiplier = 1024 if closure_scope['facts']['architecture'] == 'x86_64' - inode_ram_mb = (value.to_i * size_multiplier)/1024/1024 + inode_ram_mb = (value.to_i * size_multiplier) / 1024 / 1024 - if inode_ram_mb >= system_ram_mb - validate_sysctl_err("#{key} set to #{value} would exceed system RAM") - end - end + return unless inode_ram_mb >= system_ram_mb + validate_sysctl_err("#{key} set to #{value} would exceed system RAM") end def validate_sysctl_err(msg) - fail("simplib::validate_sysctl_value(): #{msg}") + raise("simplib::validate_sysctl_value(): #{msg}") end end diff --git a/lib/puppet/functions/simplib/validate_uri_list.rb b/lib/puppet/functions/simplib/validate_uri_list.rb index 51334dad..0d81b7b8 100644 --- a/lib/puppet/functions/simplib/validate_uri_list.rb +++ b/lib/puppet/functions/simplib/validate_uri_list.rb @@ -1,12 +1,11 @@ # Validate that a passed list (`Array` or single `String`) of URIs is # valid according to Ruby's URI parser. -# +# # * *Caution*: No scheme (protocol type) validation is done if the # `scheme_list` parameter is not set. # * Terminates catalog compilation if validation fails. # Puppet::Functions.create_function(:'simplib::validate_uri_list') do - # @param uri URI to be validated. # @param scheme_list List of schemes (protocol types) allowed for the URI. # @return [Nil] @@ -39,25 +38,22 @@ optional_param 'Array[String]', :scheme_list end - def validate_uri(uri, scheme_list=[]) + def validate_uri(uri, scheme_list = []) validate_uri_list(Array(uri), scheme_list) end - def validate_uri_list(uri_list, scheme_list=[]) + def validate_uri_list(uri_list, scheme_list = []) uri_list.each do |uri| + require 'uri' + uri_obj = URI(uri) - begin - require 'uri' - uri_obj = URI(uri) - - unless scheme_list.empty? - unless scheme_list.include?(uri_obj.scheme) - fail("simplib::validate_uri_list(): Scheme '#{uri_obj.scheme}' must be one of #{scheme_list.to_s}") - end + unless scheme_list.empty? + unless scheme_list.include?(uri_obj.scheme) + raise("simplib::validate_uri_list(): Scheme '#{uri_obj.scheme}' must be one of #{scheme_list}") end - rescue URI::InvalidURIError - fail("simplib::validate_uri_list(): '#{uri}' is not a valid URI") end + rescue URI::InvalidURIError + raise("simplib::validate_uri_list(): '#{uri}' is not a valid URI") end end end diff --git a/lib/puppet/provider/init_ulimit/systemd.rb b/lib/puppet/provider/init_ulimit/systemd.rb index 51b4a3ec..2e614974 100644 --- a/lib/puppet/provider/init_ulimit/systemd.rb +++ b/lib/puppet/provider/init_ulimit/systemd.rb @@ -1,30 +1,30 @@ Puppet::Type.type(:init_ulimit).provide(:systemd) do - desc <<-EOM + desc <<~EOM Provides the ability to set ``ulimit`` settings for ``systemd`` scripts. Deprecated: The ``systemd`` module shoould be used for this now. EOM - defaultfor :kernel => 'Linux' + defaultfor kernel: 'Linux' - commands :systemctl => 'systemctl' + commands systemctl: 'systemctl' def exists? # This is always true for systemd systems since values will always be # returned from systemctl show .service. debug('init_ulimit: systemd limits always exist') - return true + true end def create # Stub, never called debug('init_ulimit: If you got here, something very bad happened!') - return true + true end def destroy warning('init_ulimit: ulimits cannot be removed when targeting systemd artifacts') - return true + true end def value @@ -47,7 +47,7 @@ def value } @item = @systemd_xlat[@resource[:item]] - @svc_name = File.basename(@resource[:target],'.service') + '.service' + @svc_name = File.basename(@resource[:target], '.service') + '.service' unless @item warning("Systemd systems do not have a match for ulimit option '#{@resource[:item]}'") @@ -57,11 +57,11 @@ def value return @resource[:value] end - current_value = execute([command(:systemctl),'show','-p',@item,@svc_name]).chomp.split('=').last + current_value = execute([command(:systemctl), 'show', '-p', @item, @svc_name]).chomp.split('=').last current_value = 'unlimited' if current_value == (2**([''].pack('p').size * 8) - 1).to_s - return current_value + current_value end def value=(new_value) @@ -70,7 +70,7 @@ def value=(new_value) new_value = 'infinity' if new_value == 'unlimited' config_file = Puppet::Util::IniConfig::PhysicalFile.new(execute( - [command(:systemctl),'show','-p','FragmentPath',@svc_name] + [command(:systemctl), 'show', '-p', 'FragmentPath', @svc_name], ).chomp.split('=').last) config_file.read @@ -81,6 +81,6 @@ def value=(new_value) end def flush - execute([command(:systemctl),'daemon-reload']) + execute([command(:systemctl), 'daemon-reload']) end end diff --git a/lib/puppet/provider/init_ulimit/sysv.rb b/lib/puppet/provider/init_ulimit/sysv.rb index 6ebedf16..40bbb0f2 100644 --- a/lib/puppet/provider/init_ulimit/sysv.rb +++ b/lib/puppet/provider/init_ulimit/sysv.rb @@ -1,22 +1,21 @@ require 'puppet/util/selinux' Puppet::Type.type(:init_ulimit).provide(:sysv) do - desc <<-EOM + desc <<~EOM A provider for updating ulimits in SYSV init.d startup scripts EOM # TODO: Remove this when Puppet::Util::SELinux is fixed - class SELinux_kludge + class SELinuxKludge # :nodoc: include Puppet::Util::SELinux def replace_file(target, mode, &content) - selinux_current_context = self.get_selinux_current_context(target) + selinux_current_context = get_selinux_current_context(target) - Puppet::Util.replace_file(target,mode,&content) + Puppet::Util.replace_file(target, mode, &content) - self.set_selinux_context(target, selinux_current_context) + set_selinux_context(target, selinux_current_context) end - end def exists? @@ -24,25 +23,25 @@ def exists? determine_target # TODO: Finish refactoring all of this! - @source_file = File.readlines("#{@target}") + @source_file = File.readlines(@target.to_s) @warning_comment = "# Puppet-'#{resource[:item]}' Remove this line if removing the value below." # If we have the warning comment, assume that we've got the item. # This is mainly done so that we don't mess up any existing code by accident. @source_file.find do |line| - line =~ /^#\s*Puppet-'#{resource[:item]}'/ + line =~ %r{^#\s*Puppet-'#{resource[:item]}'} end end def create - new_content = "" + new_content = '' initial_comments = true wrote_content = false @source_file.each do |line| if initial_comments - if line =~ /^\s*#/ + if %r{^\s*#}.match?(line) new_content << line next else @@ -57,23 +56,22 @@ def create new_content << line end - SELinux_kludge.new.replace_file("#{@target}",0644) { |f| f.puts new_content } + SELinuxKludge.new.replace_file(@target.to_s, 0o644) { |f| f.puts new_content } end def destroy - new_content = "" + new_content = '' skip_line = false @source_file.each do |line| - # Skip the actual item. - if skip_line && (line =~ /^\s*ulimit -#{resource[:item]}/) + if skip_line && (line =~ %r{^\s*ulimit -#{resource[:item]}}) skip_line = false next end # Skip the comment - if line =~ /^#\s*Puppet-'#{resource[:item]}'/ + if %r{^#\s*Puppet-'#{resource[:item]}'}.match?(line) skip_line = true next end @@ -81,7 +79,7 @@ def destroy new_content << line end - SELinux_kludge.new.replace_file("#{@target}",0644) { |f| f.puts new_content } + SELinuxKludge.new.replace_file(@target.to_s, 0o644) { |f| f.puts new_content } end def value @@ -91,14 +89,12 @@ def value if found_comment # This really shouldn't happen, but it's possible that someone might # stuff some empty lines in there or something. - if line =~ /^\s*ulimit -#{resource[:item]} (.*)/ - retval = $1 - break - else - next - end + next unless line =~ %r{^\s*ulimit -#{resource[:item]} (.*)} + retval = Regexp.last_match(1) + break + end - if line =~ /^#\s*Puppet-'#{resource[:item]}'/ + if %r{^#\s*Puppet-'#{resource[:item]}'}.match?(line) found_comment = true next end @@ -107,27 +103,27 @@ def value retval end - def value=(should) + def value=(_should) new_content = @source_file.dup - comment_line = @source_file.find_index{|x| x =~ /^#\s*Puppet-'#{resource[:item]}'/} - ulimit_match = @source_file.find_index{|x| x =~ /^\s*ulimit -#{resource[:item]}/} + comment_line = @source_file.find_index { |x| x =~ %r{^#\s*Puppet-'#{resource[:item]}'} } + ulimit_match = @source_file.find_index { |x| x =~ %r{^\s*ulimit -#{resource[:item]}} } if comment_line && !ulimit_match # Someone deleted the ulimit, but not the comment! - new_content.insert(comment_line+1, ulimit_string) + new_content.insert(comment_line + 1, ulimit_string) elsif ulimit_match < comment_line # Well, this is a bit of a mess, delete the comment and insert above the # ulimit new_content.delete_at[comment_line] - new_content.insert(ulimit_match,@warning_comment) + new_content.insert(ulimit_match, @warning_comment) else # Get rid of the current ulimit and replace it with the new one. new_content[ulimit_match] = ulimit_string end - SELinux_kludge.new.replace_file("#{@target}",0644) { |f| f.puts new_content } + SELinuxKludge.new.replace_file(@target.to_s, 0o644) { |f| f.puts new_content } end private @@ -151,6 +147,6 @@ def determine_target @target = "/etc/init.d/#{@target}" end - raise(Puppet::ParseError,"File '#{@target}' not found.") unless File.exist?(@target) + raise(Puppet::ParseError, "File '#{@target}' not found.") unless File.exist?(@target) end end diff --git a/lib/puppet/provider/prepend_file_line/ruby.rb b/lib/puppet/provider/prepend_file_line/ruby.rb index cc4c1488..cc51ce00 100644 --- a/lib/puppet/provider/prepend_file_line/ruby.rb +++ b/lib/puppet/provider/prepend_file_line/ruby.rb @@ -1,5 +1,5 @@ Puppet::Type.type(:prepend_file_line).provide(:ruby) do - desc <<-EOM + desc <<~EOM Prepend a line to a file. EOM @@ -13,19 +13,19 @@ def create tmpfile = "#{File.dirname(resource[:path])}/.~puppet_#{File.basename(resource[:path])}" begin File.exist?(tmpfile) and File.unlink(tmpfile) - tmp_fh = File.open(tmpfile,'w') + tmp_fh = File.open(tmpfile, 'w') tmp_fh.puts(resource[:line]) - orig_fh = File.open(resource[:path],'r') + orig_fh = File.open(resource[:path], 'r') orig_fh.each_line do |ln| tmp_fh.puts(ln) end orig_fh.close tmp_fh.close - FileUtils.mv(tmpfile,resource[:path]) + FileUtils.mv(tmpfile, resource[:path]) rescue - fail(Puppet::Error,"Error when prepending line to #{resource[:path]}") + raise(Puppet::Error, "Error when prepending line to #{resource[:path]}") end end end diff --git a/lib/puppet/provider/reboot_notify/notify.rb b/lib/puppet/provider/reboot_notify/notify.rb index 3d1c3a4a..b519b700 100644 --- a/lib/puppet/provider/reboot_notify/notify.rb +++ b/lib/puppet/provider/reboot_notify/notify.rb @@ -7,15 +7,15 @@ def self.target end # Instance syntactic sugar - def target - self.class.target - end + def target + self.class.target + end # The default control metadata if none other is specified # # Used in both class and instance methods def self.default_control_metadata - return { + { 'reboot_control_metadata' => { 'log_level' => 'notice' } @@ -23,7 +23,7 @@ def self.default_control_metadata end def initialize(*args) - super(*args) + super @records = self.class.default_control_metadata end @@ -35,9 +35,8 @@ def exists? @records = JSON.parse(File.read(target)) if @resource[:control_only] - @records = @records.deep_merge( self.class.default_control_metadata ) + @records = @records.deep_merge(self.class.default_control_metadata) end - rescue => e # Cheap and easy way to ensure that the file gets created and/or fixed if # there is something wrong with it. @@ -61,14 +60,14 @@ def exists? # This is OK, we only want this provider to add records if the file is not # there or if the resource is hit with a refresh since reboot notifications # always happen because of some event. - return true + true end def create update_record begin - File.open(target,'w'){|fh| fh.puts(JSON.pretty_generate(@records))} + File.open(target, 'w') { |fh| fh.puts(JSON.pretty_generate(@records)) } rescue => e raise(Puppet::Error, "reboot_notify: Could not create '#{target}': #{e}") end @@ -85,7 +84,7 @@ def update update_record begin - File.open(target,'w') { |fh| fh.puts(JSON.pretty_generate(@records)) } + File.open(target, 'w') { |fh| fh.puts(JSON.pretty_generate(@records)) } rescue => e raise(Puppet::Error, "reboot_notify: Could not update '#{target}': #{e}") end @@ -112,30 +111,30 @@ def self.post_resource_eval current_time = Time.now.tv_sec # Need to pull this out of the data structure - if records['reboot_control_metadata'] - reboot_control_metadata = records.delete('reboot_control_metadata') - else - reboot_control_metadata = self.default_control_metadata['reboot_control_metadata'] - end + reboot_control_metadata = if records['reboot_control_metadata'] + records.delete('reboot_control_metadata') + else + default_control_metadata['reboot_control_metadata'] + end # Purge any records older than our uptime (we rebooted). - records.delete_if{|k,v| + records.delete_if do |_k, v| next unless v['updated'] # If the number of seconds between the time that the record was written # and the current time is greater than the system uptime then we should # remove the record (current_time - v['updated']) > Facter.value(:uptime_seconds) - } + end unless records.empty? msg = ['System Reboot Required Because:'] - records.each_pair do |k,v| + records.each_pair do |k, v| next unless v['updated'] # This is a fail safe for empty 'reasons' - records[k]['reason'] = 'modified' if ( records[k]['reason'].nil? || records[k]['reason'].empty? ) + records[k]['reason'] = 'modified' if records[k]['reason'].nil? || records[k]['reason'].empty? msg << [" #{k} => #{v['reason']}"] end @@ -151,7 +150,7 @@ def self.post_resource_eval begin reboot_control_hash = { 'reboot_control_metadata' => reboot_control_metadata } - File.open(target,'w'){|fh| fh.puts(JSON.pretty_generate(reboot_control_hash.merge(records)))} + File.open(target, 'w') { |fh| fh.puts(JSON.pretty_generate(reboot_control_hash.merge(records))) } rescue raise(Puppet::Error, "reboot_notify: Could not update '#{target}': #{e}") end @@ -164,8 +163,8 @@ def update_record @records['reboot_control_metadata']['log_level'] = @resource[:log_level] else @records[@resource[:name]] = { - :reason => @resource[:reason], - :updated => Time.now.tv_sec + reason: @resource[:reason], + updated: Time.now.tv_sec } end end diff --git a/lib/puppet/provider/runlevel/systemd.rb b/lib/puppet/provider/runlevel/systemd.rb index 47d2648d..c39f1401 100644 --- a/lib/puppet/provider/runlevel/systemd.rb +++ b/lib/puppet/provider/runlevel/systemd.rb @@ -1,12 +1,12 @@ Puppet::Type.type(:runlevel).provide(:systemd) do - desc <<-EOM + desc <<~EOM Set the system runlevel using systemd EOM - commands :systemctl => '/usr/bin/systemctl' - commands :pgrep => 'pgrep' + commands systemctl: '/usr/bin/systemctl' + commands pgrep: 'pgrep' - defaultfor :kernel => 'Linux' + defaultfor kernel: 'Linux' def level Facter.value(:runlevel) @@ -18,24 +18,24 @@ def level_insync?(should, is) # The `execute` method calls `Kernel.exec()` and that cannot accept quotes # around strings in arguments for some reason. - if execute([command(:pgrep),'-f', %(^(#{systemctl_path}/)?#{systemctl_cmd}[[:space:]]+isolate)], :failonfail => false).strip.empty? - return should == is + if execute([command(:pgrep), '-f', %(^(#{systemctl_path}/)?#{systemctl_cmd}[[:space:]]+isolate)], failonfail: false).strip.empty? + should == is else Puppet.warning('System currently attempting to transition runlevels, will not respawn') # Returning that the level is in sync here so that the system does not # attempt to respawn a new systemctl instance while one is already # running. - return true + true end end - def level=(should) + def level=(_should) require 'timeout' begin - Timeout::timeout(@resource[:transition_timeout]) do - execute([command(:systemctl),'isolate',init2systemd(@resource[:name])]) + Timeout.timeout(@resource[:transition_timeout]) do + execute([command(:systemctl), 'isolate', init2systemd(@resource[:name])]) end rescue Timeout::Error raise(Puppet::Error, "Could not transition to runlevel #{@resource[:name]} within #{@resource[:transition_timeout]} seconds") @@ -43,15 +43,15 @@ def level=(should) end def persist - if execute([command(:systemctl),'get-default']).strip == init2systemd(@resource[:name]) - return :true + if execute([command(:systemctl), 'get-default']).strip == init2systemd(@resource[:name]) + :true else - return :false + :false end end - def persist=(should) - execute([command(:systemctl),'set-default',init2systemd(@resource[:name])]) + def persist=(_should) + execute([command(:systemctl), 'set-default', init2systemd(@resource[:name])]) end private @@ -63,12 +63,12 @@ def init2systemd(input) runlevel = 'graphical.target' elsif input == '1' runlevel = 'rescue.target' - elsif input =~ /^\d+$/ + elsif %r{^\d+$}.match?(input) runlevel = 'multi-user.target' - elsif input !~ /.*\.target/ + elsif !%r{.*\.target}.match?(input) runlevel = "#{input}.target" end - return runlevel + runlevel end end diff --git a/lib/puppet/provider/runlevel/telinit.rb b/lib/puppet/provider/runlevel/telinit.rb index 8c7f8e3f..f611f646 100644 --- a/lib/puppet/provider/runlevel/telinit.rb +++ b/lib/puppet/provider/runlevel/telinit.rb @@ -1,23 +1,23 @@ Puppet::Type.type(:runlevel).provide(:telinit) do - desc <<-EOM + desc <<~EOM Set the system runlevel using telinit EOM - commands :telinit => '/sbin/telinit' + commands telinit: '/sbin/telinit' def level Facter.value(:runlevel) end def level_insync?(should, is) - return should == is + should == is end - def level=(should) + def level=(_should) require 'timeout' begin - Timeout::timeout(@resource[:transition_timeout]) do + Timeout.timeout(@resource[:transition_timeout]) do execute([command(:telinit), @resource[:name]]) end rescue Timeout::Error @@ -31,12 +31,11 @@ def persist if @resource[:persist] == :true inittab = File.open('/etc/inittab', 'r') inittab.each_line do |line| - if line =~ /^\s*id/ - # We have the initdefault line - current_value = line.split(':').at(1) - if current_value.eql?(@resource[:name]) - retval = :true - end + next unless %r{^\s*id}.match?(line) + # We have the initdefault line + current_value = line.split(':').at(1) + if current_value.eql?(@resource[:name]) + retval = :true end end inittab.close @@ -45,15 +44,15 @@ def persist retval end - def persist=(should) + def persist=(_should) # Essentially do the same as the read, but save contents to new file - newfile = String.new + newfile = '' inittab = File.open('/etc/inittab', 'r') found_line = false inittab.each_line do |line| - if line =~ /^\s*id/ + if %r{^\s*id}.match?(line) # We've found the default line, so rewrite found_line = true newfile << "id:#{@resource[:name]}:initdefault:nil\n" diff --git a/lib/puppet/provider/script_umask/ruby.rb b/lib/puppet/provider/script_umask/ruby.rb index d432ffff..4fbee0ea 100644 --- a/lib/puppet/provider/script_umask/ruby.rb +++ b/lib/puppet/provider/script_umask/ruby.rb @@ -1,21 +1,21 @@ Puppet::Type.type(:script_umask).provide(:ruby) do - desc <<-EOM + desc <<~EOM Set the ``umask`` at the top of a shell script EOM def umask # Just skip it all if the file doesn't exist. - if not File.exist?(@resource[:name]) then + unless File.exist?(@resource[:name]) return @resource[:umask] end umasks = [] - fh = File.open(@resource[:name],'r') + fh = File.open(@resource[:name], 'r') fh.each_line do |line| - next if line =~ /\s*#/ + next if %r{\s*#}.match?(line) - if line =~ /^\s*umask\s+(\d{3,4})/ then - umasks << $1 + if line =~ %r{^\s*umask\s+(\d{3,4})} + umasks << Regexp.last_match(1) end end fh.close @@ -28,16 +28,16 @@ def umask def umask=(should) output = [] File.read(@resource[:name]).each_line do |line| - if line =~ /^(\s*umask\s+)(\d{3,4})(.*)/ then - output << "#{$1}#{should}#{$3}" - else - output << line.chomp - end + output << if line =~ %r{^(\s*umask\s+)(\d{3,4})(.*)} + "#{Regexp.last_match(1)}#{should}#{Regexp.last_match(3)}" + else + line.chomp + end end - File.open(@resource[:name],'w') { |fh| + File.open(@resource[:name], 'w') do |fh| fh.rewind fh.puts(output.join("\n")) - } + end end end diff --git a/lib/puppet/provider/simp_file_line/ruby.rb b/lib/puppet/provider/simp_file_line/ruby.rb index 980d643a..991bbb34 100644 --- a/lib/puppet/provider/simp_file_line/ruby.rb +++ b/lib/puppet/provider/simp_file_line/ruby.rb @@ -1,14 +1,14 @@ Puppet::Type.type(:simp_file_line).provide(:ruby) do - desc <<-EOM + desc <<~EOM Provides the ability to prepend, append, or simply add lines to a file. Will create the file if it doesn't exist. EOM def exists? - if file_managed? then + if file_managed? Puppet.debug("Skipping #{resource.ref} due to deconflict = :true") - return true + true else lines.find do |line| line.chomp == resource[:line].chomp @@ -18,20 +18,21 @@ def exists? def create if resource[:match] - handle_create_with_match() + handle_create_with_match else - handle_create_without_match() + handle_create_without_match end end def destroy local_lines = lines - File.open(resource[:path],'w') do |fh| - fh.write(local_lines.reject{|l| l.chomp == resource[:line] }.join('')) + File.open(resource[:path], 'w') do |fh| + fh.write(local_lines.reject { |l| l.chomp == resource[:line] }.join('')) end end private + def file_managed? # Return true/false based on whether or not the target file already has its # content managed by a File resource. @@ -39,21 +40,19 @@ def file_managed? file_resource = resource.catalog.resource("File[#{resource[:path]}]") - if file_resource and file_resource[:replace] and - ( file_resource[:source] or file_resource[:content] ) - then - if resource[:deconflict] == :true then - return true - else - raise Puppet::Error, "'#{resource.ref}' conflicts with #{file_resource.ref}" + - " resource in file #{file_resource.file} at line" + - " #{file_resource.line}. If you wish to have the File" + - " resource win, use the 'deconflict' option in #{resource.ref}" + - " in #{resource.file}:#{resource.line}." - end + if file_resource && file_resource[:replace] && + (file_resource[:source] || file_resource[:content]) + return true if resource[:deconflict] == :true + + raise Puppet::Error, "'#{resource.ref}' conflicts with #{file_resource.ref}" \ + " resource in file #{file_resource.file} at line" \ + " #{file_resource.line}. If you wish to have the File" \ + " resource win, use the 'deconflict' option in #{resource.ref}" \ + " in #{resource.file}:#{resource.line}." + end - return false + false end def lines @@ -65,9 +64,9 @@ def lines @lines ||= File.readlines(resource[:path]) end - def handle_create_with_match() + def handle_create_with_match regex = resource[:match] ? Regexp.new(resource[:match]) : nil - match_count = lines.select { |l| regex.match(l) }.count + match_count = lines.count { |l| regex.match(l) } if match_count > 1 raise Puppet::Error, "More than one line in file '#{resource[:path]}' matches pattern '#{resource[:match]}'" end @@ -78,7 +77,7 @@ def handle_create_with_match() newlines << (regex.match(l) ? resource[:line] : l) end - if (match_count == 0) + if match_count == 0 if resource[:prepend] != :true newlines << newlines.shift end @@ -91,7 +90,7 @@ def handle_create_with_match() end def handle_create_without_match - if resource[:prepend] != :true then + if resource[:prepend] != :true File.open(resource[:path], 'a') do |fh| fh.puts resource[:line] end @@ -103,5 +102,4 @@ def handle_create_without_match end end end - end diff --git a/lib/puppet/type/ftpusers.rb b/lib/puppet/type/ftpusers.rb index 98c39b1e..9a7dcc9a 100644 --- a/lib/puppet/type/ftpusers.rb +++ b/lib/puppet/type/ftpusers.rb @@ -4,20 +4,20 @@ newparam(:name) do isnamevar - desc "The file to which to write the values" + desc 'The file to which to write the values' validate do |value| - value =~ /^\// or raise(ArgumentError,"Error: :name must be an absolute path") + value =~ %r{^/} or raise(ArgumentError, 'Error: :name must be an absolute path') end end newparam(:min_id) do - desc "The UID below which all values will be considered system users" + desc 'The UID below which all values will be considered system users' defaultto '500' validate do |value| - if value !~ /^\d+$/ then - raise(ArgumentError,"Error: '#{value}' is not a numeric UID.") + unless %r{^\d+$}.match?(value) + raise(ArgumentError, "Error: '#{value}' is not a numeric UID.") end end @@ -27,8 +27,8 @@ end newparam(:always_deny) do - desc "Entries to always add to the file" - defaultto ['nobody','nfsnobody'] + desc 'Entries to always add to the file' + defaultto ['nobody', 'nfsnobody'] munge do |value| Array(value) @@ -36,7 +36,7 @@ end newproperty(:to_write) do - desc "Ignored, auto-populated from /etc/passwd" + desc 'Ignored, auto-populated from /etc/passwd' defaultto 'default' def insync?(is) @@ -60,28 +60,28 @@ def sync tmpfile = "#{File.dirname(resource[:name])}/.~puppet_#{File.basename(resource[:name])}" begin File.exist?(tmpfile) and File.unlink(tmpfile) - tmp_fh = File.open(tmpfile,'w') + tmp_fh = File.open(tmpfile, 'w') tmp_fh.puts('#FTP Users file autogenerated by Puppet') tmp_fh.puts((@should | @old_vals).join("\n")) tmp_fh.close - FileUtils.mv(tmpfile,resource[:name]) - rescue Exception => e + FileUtils.mv(tmpfile, resource[:name]) + rescue => e debug(e) err = true ensure File.exist?(tmpfile) and File.unlink(tmpfile) end - fail(Puppet::Error,"Error when adding names to #{resource[:name]}") if err + raise(Puppet::Error, "Error when adding names to #{resource[:name]}") if err end def retrieve - vals = Array.new + vals = [] begin vals = File.read(resource[:name]).split("\n") - vals.delete_if{|x| x[0].chr == '#'} - rescue Exception => e + vals.delete_if { |x| x[0].chr == '#' } + rescue => e debug(e) end diff --git a/lib/puppet/type/init_ulimit.rb b/lib/puppet/type/init_ulimit.rb index c9ec35a2..c0955acf 100644 --- a/lib/puppet/type/init_ulimit.rb +++ b/lib/puppet/type/init_ulimit.rb @@ -1,54 +1,54 @@ Puppet::Type.newtype(:init_ulimit) do - desc <<-EOT - Please use the ``systemd`` module for systems that support ``systemd`` - - Update ``ulimit`` settings in init scripts. - - The resource name does have to be unique but is meaningless. - - Valid ``limit_type`` names are: - - * b|socket_buffer_size - * c|max_core_size - * d|max_data_segment - * e|max_nice - * f|max_file_size - * i|max_pending_signals - * l|max_memory_lock_size - * m|max_resident_set_size - * n|max_open_files (default) - * p|max_queue_size - * r|max_real_time_pri - * s|max_stack_size - * t|max_cpu_time - * u|max_num_procs - * v|max_virt_memory - * x|max_file_locks - * T|max_threads - - All of these are explained in the ``ulimit`` section of ``bash_builtins(1)`` - - The parameter names are taken from the descriptive field names used in - ``limits.conf``. - - @example Long Names - - init_ulimit { 'rsyslog': - ensure => 'present', - limit_type => 'both' - item => 'max_open_files', - value => 'unlimited' - } - - @example Short Names - - init_ulimit { 'rsyslog': - item => 'n', - value => 'unlimited' - } + desc <<~EOT + Please use the ``systemd`` module for systems that support ``systemd`` + + Update ``ulimit`` settings in init scripts. + + The resource name does have to be unique but is meaningless. + + Valid ``limit_type`` names are: + + * b|socket_buffer_size + * c|max_core_size + * d|max_data_segment + * e|max_nice + * f|max_file_size + * i|max_pending_signals + * l|max_memory_lock_size + * m|max_resident_set_size + * n|max_open_files (default) + * p|max_queue_size + * r|max_real_time_pri + * s|max_stack_size + * t|max_cpu_time + * u|max_num_procs + * v|max_virt_memory + * x|max_file_locks + * T|max_threads + + All of these are explained in the ``ulimit`` section of ``bash_builtins(1)`` + + The parameter names are taken from the descriptive field names used in + ``limits.conf``. + + @example Long Names + + init_ulimit { 'rsyslog': + ensure => 'present', + limit_type => 'both' + item => 'max_open_files', + value => 'unlimited' + } + + @example Short Names + + init_ulimit { 'rsyslog': + item => 'n', + value => 'unlimited' + } EOT - $init_ulimit_opt_map = { + init_ulimit_opt_map = { 'b' => 'b', 'c' => 'c', 'd' => 'd', @@ -90,21 +90,20 @@ def self.title_patterns [ [ - /^(.+?)\|?(.+)$/, + %r{^(.+?)\|?(.+)$}, [ - [:item], - [:target] - ] - ] + [:item], + [:target], + ], + ], ] end def initialize(*args) - super(*args) + super - if File.dirname(self[:target]) == '/etc/init.d' - self.provider = 'sysv' - end + return unless File.dirname(self[:target]) == '/etc/init.d' + self.provider = 'sysv' end newparam(:name) do @@ -116,14 +115,13 @@ def initialize(*args) desc 'The service that will be modified. If you specify a full path, that will be used instead.' munge do |value| - if value !~ /^\// + unless %r{^/}.match?(value) # Prevent unexpected directory traversing! - value = value.gsub('/','_') unless value[0].chr == '/' + value = value.tr('/', '_') unless value[0].chr == '/' end value end - end newparam(:limit_type) do @@ -143,25 +141,25 @@ def initialize(*args) defaultto 'max_open_files' munge do |value| - $init_ulimit_opt_map[value.downcase] + init_ulimit_opt_map[value.downcase] end validate do |value| - unless $init_ulimit_opt_map.keys.include?(value.downcase) - raise(Puppet::Error, "'item' must be one of '#{$init_ulimit_opt_map.keys.join(', ')}, got #{value}") + unless init_ulimit_opt_map.keys.include?(value.downcase) + raise(Puppet::Error, "'item' must be one of '#{init_ulimit_opt_map.keys.join(', ')}, got #{value}") end end end newproperty(:value) do desc 'The value to which to set the new limit.' - newvalues(:hard, :soft, :unlimited, /^\d+$/) + newvalues(:hard, :soft, :unlimited, %r{^\d+$}) munge do |value| value = value.downcase.strip # Unlimited doesn't work in the case of file descriptors so munge it to the system max. - value = '1048576' if ((resource[:item] == 'n') && (value == 'unlimited')) + value = '1048576' if (resource[:item] == 'n') && (value == 'unlimited') value end @@ -182,7 +180,7 @@ def initialize(*args) def finish dep = @catalog.resource("Service[#{File.basename(self[:target])}]") res_comp = [] - res_comp = self[:notify].map{|x| x.to_s} if self[:notify] + res_comp = self[:notify].map { |x| x.to_s } if self[:notify] if dep if self[:notify] && !self[:notify].empty? && !res_comp.include?(dep.to_s) diff --git a/lib/puppet/type/prepend_file_line.rb b/lib/puppet/type/prepend_file_line.rb index 6763441d..1c34a2ec 100644 --- a/lib/puppet/type/prepend_file_line.rb +++ b/lib/puppet/type/prepend_file_line.rb @@ -1,15 +1,13 @@ Puppet::Type.newtype(:prepend_file_line) do + desc <<~EOT + Type that can prepend whole a line to a file if it does not already contain it. - desc <<-EOT - Type that can prepend whole a line to a file if it does not already contain it. - - Example: - - file_prepend_line { 'sudo_rule': - path => '/etc/sudoers', - line => '%admin ALL=(ALL) ALL', - } + Example: + file_prepend_line { 'sudo_rule': + path => '/etc/sudoers', + line => '%admin ALL=(ALL) ALL', + } EOT ensurable do @@ -20,7 +18,7 @@ end end - newparam(:name, :namevar => true) do + newparam(:name, namevar: true) do desc 'arbitrary name used as identity' end @@ -31,15 +29,15 @@ newparam(:path) do desc 'File to possibly prepend a line to.' validate do |value| - unless (Puppet.features.posix? and value =~ /^\//) or (Puppet.features.microsoft_windows? and (value =~ /^.:\// or value =~ /^\/\/[^\/]+\/[^\/]+/)) + unless (Puppet.features.posix? && value =~ (%r{^/})) || (Puppet.features.microsoft_windows? && (value =~ (%r{^.:/}) || value =~ (%r{^//[^/]+/[^/]+}))) raise(Puppet::Error, "File paths must be fully qualified, not '#{value}'") end end end validate do - unless self[:line] and self[:path] - raise(Puppet::Error, "Both line and path are required attributes") + unless self[:line] && self[:path] + raise(Puppet::Error, 'Both line and path are required attributes') end end end diff --git a/lib/puppet/type/reboot_notify.rb b/lib/puppet/type/reboot_notify.rb index aaba63d6..b2350a01 100644 --- a/lib/puppet/type/reboot_notify.rb +++ b/lib/puppet/type/reboot_notify.rb @@ -36,21 +36,21 @@ defaultto('modified') end - newparam(:control_only, :boolean => true, :parent => Puppet::Parameter::Boolean) do - desc <<-EOM - This resource is only for control and should not add an item to the notification list + newparam(:control_only, boolean: true, parent: Puppet::Parameter::Boolean) do + desc <<~EOM + This resource is only for control and should not add an item to the notification list - You may only have ONE resource with this set to `true` in your catalog + You may only have ONE resource with this set to `true` in your catalog EOM defaultto(:false) end newparam(:log_level) do - desc <<-EOM - Set the message log level for notifications + desc <<~EOM + Set the message log level for notifications - This is only active with :control_only set to `true` + This is only active with :control_only set to `true` EOM defaultto(:notice) @@ -63,10 +63,10 @@ validate do if self[:control_only] - existing_resource = catalog.resources.find { |res| (res.type == self.type) && res[:control_only] } + existing_resource = catalog.resources.find { |res| (res.type == type) && res[:control_only] } if existing_resource - err = ["You can only have one #{self.type} resource with :control_only set to 'true'"] + err = ["You can only have one #{type} resource with :control_only set to 'true'"] err << "Conflicting resource found in file '#{existing_resource.file}' on line '#{existing_resource.line}'" raise(Puppet::Error, err.join("\n")) diff --git a/lib/puppet/type/runlevel.rb b/lib/puppet/type/runlevel.rb index 8217a770..5f50d782 100644 --- a/lib/puppet/type/runlevel.rb +++ b/lib/puppet/type/runlevel.rb @@ -1,5 +1,4 @@ Puppet::Type.newtype(:runlevel) do - @doc = "Changes the system runlevel by re-evaluating the inittab or systemd link. Arguments: @@ -15,32 +14,32 @@ " def initialize(*args) - super(*args) + super found_resource = nil - if not catalog.resources.find_all { |r| - r.is_a?(Puppet::Type.type(:runlevel)) and found_resource = r - }.empty? then + unless catalog.resources.none? do |r| + r.is_a?(Puppet::Type.type(:runlevel)) && (found_resource = r) + end msg = "Duplicate declaration: Runlevel is already declared in file #{found_resource.file} at line #{found_resource.line}. Can not declare more than one instance of Runlevel." - raise Puppet::Resource::Catalog::DuplicateResourceError.new(msg) + raise Puppet::Resource::Catalog::DuplicateResourceError, msg end end def runlevel_xlat(value) case value - when 'rescue' then '1' - when 'multi-user' then '3' - when 'graphical' then '5' - else value + when 'rescue' then '1' + when 'multi-user' then '3' + when 'graphical' then '5' + else value end end - newparam(:name, :namevar => true) do + newparam(:name, namevar: true) do desc 'The target runlevel of the system' - newvalues(/^[1-5]$/, 'rescue', 'multi-user', 'graphical') + newvalues(%r{^[1-5]$}, 'rescue', 'multi-user', 'graphical') munge do |value| @resource.runlevel_xlat(value) @@ -49,18 +48,18 @@ def runlevel_xlat(value) newparam(:transition_timeout) do desc 'How many seconds to wait for a runlevel switch before failing' - newvalues(/^\d+$/) + newvalues(%r{^\d+$}) defaultto 60 munge do |value| - "#{value}".to_i + value.to_s.to_i end end newproperty(:level) do desc 'The target runlevel of the system. Defaults to what is specified in :name' - newvalues(/^[1-5]$/, 'rescue', 'multi-user', 'graphical', 'default') + newvalues(%r{^[1-5]$}, 'rescue', 'multi-user', 'graphical', 'default') defaultto 'default' diff --git a/lib/puppet/type/script_umask.rb b/lib/puppet/type/script_umask.rb index 3c218265..2d2ddf50 100644 --- a/lib/puppet/type/script_umask.rb +++ b/lib/puppet/type/script_umask.rb @@ -1,19 +1,19 @@ Puppet::Type.newtype(:script_umask) do - @doc = "Alters the umask settings in the passed file." + @doc = 'Alters the umask settings in the passed file.' newparam(:name) do isnamevar - desc "The file to alter." + desc 'The file to alter.' validate do |value| - value =~ /^\// or raise(ArgumentError,"Error: :name must be an absolute path") + value =~ %r{^/} or raise(ArgumentError, 'Error: :name must be an absolute path') end end newproperty(:umask) do - desc "The umask that should be set in the target file." + desc 'The umask that should be set in the target file.' defaultto '077' - newvalues(/^[0-7]{3,4}$/) + newvalues(%r{^[0-7]{3,4}$}) end autorequire(:file) do diff --git a/lib/puppet/type/simp_file_line.rb b/lib/puppet/type/simp_file_line.rb index 472bfe75..beaf56c7 100644 --- a/lib/puppet/type/simp_file_line.rb +++ b/lib/puppet/type/simp_file_line.rb @@ -1,6 +1,5 @@ Puppet::Type.newtype(:simp_file_line) do - - desc <<-EOT + desc <<~EOT Ensures that a given line is contained within a file. The implementation matches the full line, including whitespace at the beginning and end. If the line is not contained in the given file, Puppet will add the line to @@ -35,12 +34,12 @@ defaultto :present end - newparam(:name, :namevar => true) do + newparam(:name, namevar: true) do desc 'An arbitrary name used as the identity of the resource.' end newparam(:match) do - desc <<-EOF + desc <<~EOF An optional regular expression to run against existing lines in the file. If a match is found, we replace that line rather than adding a new line. EOF @@ -53,27 +52,26 @@ newparam(:path) do desc 'The file Puppet will ensure contains the line specified by the line parameter.' validate do |value| - unless (Puppet.features.posix? and value =~ /^\//) or (Puppet.features.microsoft_windows? and (value =~ /^.:\// or value =~ /^\/\/[^\/]+\/[^\/]+/)) + unless (Puppet.features.posix? && value =~ (%r{^/})) || (Puppet.features.microsoft_windows? && (value =~ (%r{^.:/}) || value =~ (%r{^//[^/]+/[^/]+}))) raise(Puppet::Error, "File paths must be fully qualified, not '#{value}'") end end end validate do - unless self[:line] and self[:path] - raise(Puppet::Error, "Both line and path are required attributes") + unless self[:line] && self[:path] + raise(Puppet::Error, 'Both line and path are required attributes') end - if (self[:match]) + if self[:match] unless Regexp.new(self[:match]).match(self[:line]) raise(Puppet::Error, "When providing a 'match' parameter, the value must be a regex that matches against the value of your 'line' parameter") end end - end newparam(:deconflict) do - desc <<-EOM + desc <<~EOM Do not execute this type if there is a file type that already manages the content of the target file unless $replace == false EOM diff --git a/lib/puppetx/simp/simplib.rb b/lib/puppetx/simp/simplib.rb index 13a30867..7b2d2e93 100644 --- a/lib/puppetx/simp/simplib.rb +++ b/lib/puppetx/simp/simplib.rb @@ -1,96 +1,95 @@ -module PuppetX - module SIMP - module Simplib +# PuppetX +module PuppetX; end +# PuppetX::SIMP +module PuppetX::SIMP; end - # Sort a list of values based on usual human sorting semantics. - # - # This regex taken from - # http://www.bofh.org.uk/2007/12/16/comprehensible-sorting-in-ruby - # - def self.human_sort(obj) - obj.to_s.split(/((?:(?:^|\s)[-+])?(?:\.\d+|\d+(?:\.\d+?(?:[eE]\d+)?(?:$|(?![eE\.])))?))/ms).map { |v| - begin - Float(v) - rescue - v.downcase - end - } - end - - # Determine whether or not the passed value is a valid hostname. - # - # Returns false if is not comprised of ASCII letters (upper or lower case), - # digits, hypens (except at the beginning and end), and dots (except at - # beginning and end) - # - # *NOTE*: This returns true for an IPv4 address, as it conforms to RFC 1123. - def self.hostname_only?(obj) - # This regex shamelessly lifted from - # http://stackoverflow.com/questions/106179/regular-expression-to-match-hostname-or-ip-address - hname_regex = Regexp.new(/^ - ( - ([a-zA-Z0-9]| - [a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\. - )* - ( - [A-Za-z0-9]| - [A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9] - )$/x) +# PuppetX::SIMP::Simplib +module PuppetX::SIMP::Simplib + # Sort a list of values based on usual human sorting semantics. + # + # This regex taken from + # http://www.bofh.org.uk/2007/12/16/comprehensible-sorting-in-ruby + # + def self.human_sort(obj) + obj.to_s.split(%r{((?:(?:^|\s)[-+])?(?:\.\d+|\d+(?:\.\d+?(?:[eE]\d+)?(?:$|(?![eE\.])))?))}ms).map do |v| + Float(v) + rescue + v.downcase + end + end - !hname_regex.match(obj).nil? - end + # Determine whether or not the passed value is a valid hostname. + # + # Returns false if is not comprised of ASCII letters (upper or lower case), + # digits, hypens (except at the beginning and end), and dots (except at + # beginning and end) + # + # *NOTE*: This returns true for an IPv4 address, as it conforms to RFC 1123. + def self.hostname_only?(obj) + # This regex shamelessly lifted from + # http://stackoverflow.com/questions/106179/regular-expression-to-match-hostname-or-ip-address + hname_regex = %r{^ + ( + ([a-zA-Z0-9]| + [a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\. + )* + ( + [A-Za-z0-9]| + [A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9] + )$}x - # Determine whether or not the passed value is a valid hostname, - # optionally postpended with ':' or '/'. - # - # Returns false if is not comprised of ASCII letters (upper or lower case), - # digits, hypens (except at the beginning and end), and dots (except at - # beginning and end), excluding an optional, trailing ':' or - # '/' - # - # *NOTE*: This returns true for an IPv4 address, as it conforms to RFC 1123. - def self.hostname?(obj) - # This regex shamelessly lifted from - # http://stackoverflow.com/questions/106179/regular-expression-to-match-hostname-or-ip-address - # and then augmented for postpends - hname_regex = Regexp.new(/^ - ( - ([a-zA-Z0-9]| - [a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\. - )* - ( - [A-Za-z0-9]| - [A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9] - )((:|\/)?(\d+))?$/x) + !hname_regex.match(obj).nil? + end - !hname_regex.match(obj).nil? - end + # Determine whether or not the passed value is a valid hostname, + # optionally postpended with ':' or '/'. + # + # Returns false if is not comprised of ASCII letters (upper or lower case), + # digits, hypens (except at the beginning and end), and dots (except at + # beginning and end), excluding an optional, trailing ':' or + # '/' + # + # *NOTE*: This returns true for an IPv4 address, as it conforms to RFC 1123. + def self.hostname?(obj) + # This regex shamelessly lifted from + # http://stackoverflow.com/questions/106179/regular-expression-to-match-hostname-or-ip-address + # and then augmented for postpends + hname_regex = %r{^ + ( + ([a-zA-Z0-9]| + [a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\. + )* + ( + [A-Za-z0-9]| + [A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9] + )((:|/)?(\d+))?$}x - # Return a host/port pair - def self.split_port(host_string) - return [nil,nil] if host_string.nil? or host_string.empty? + !hname_regex.match(obj).nil? + end - # CIDR addresses do not have ports - return [host_string, nil] if host_string.include?('/') + # Return a host/port pair + def self.split_port(host_string) + return [nil, nil] if host_string.nil? || host_string.empty? - # IPv6 Easy - if host_string.include?(']') - host_pair = host_string.split(/\]:?/) - host_pair[0] = host_pair[0] + ']' - host_pair[1] = nil if host_pair.size == 1 - # IPv6 Fallback - elsif host_string.count(':') > 1 - # Normalize IPv6 addresses to have '[]' for clarity - host_pair = [%([#{host_string}]),nil] - # Everything Else - elsif host_string.include?(':') - host_pair = host_string.split(':') - else - host_pair = [host_string,nil] - end + # CIDR addresses do not have ports + return [host_string, nil] if host_string.include?('/') - host_pair - end + # IPv6 Easy + if host_string.include?(']') + host_pair = host_string.split(%r{\]:?}) + host_pair[0] = host_pair[0] + ']' + host_pair[1] = nil if host_pair.size == 1 + # IPv6 Fallback + elsif host_string.count(':') > 1 + # Normalize IPv6 addresses to have '[]' for clarity + host_pair = [%([#{host_string}]), nil] + # Everything Else + elsif host_string.include?(':') + host_pair = host_string.split(':') + else + host_pair = [host_string, nil] end + + host_pair end end diff --git a/metadata.json b/metadata.json index 5390338d..edc18da5 100644 --- a/metadata.json +++ b/metadata.json @@ -1,6 +1,6 @@ { "name": "simp-simplib", - "version": "4.12.3", + "version": "4.13.0", "author": "SIMP Team", "summary": "A collection of common SIMP functions, facts, and types", "license": "Apache-2.0", diff --git a/spec/acceptance/suites/caller_function/caller_spec.rb b/spec/acceptance/suites/caller_function/caller_spec.rb index 05e075d6..12185ed8 100644 --- a/spec/acceptance/suites/caller_function/caller_spec.rb +++ b/spec/acceptance/suites/caller_function/caller_spec.rb @@ -3,22 +3,23 @@ test_name 'simplib::caller function' describe 'simplib::caller function' do - let(:manifest){ - <<-EOM - include testmod + let(:manifest) do + <<~EOM + include testmod EOM - } + end hosts.each do |host| host_modulepath = puppet_modulepath_on(host).first - copy_module_to(host, { - :source => File.absolute_path(File.join(__dir__, 'files', 'modules', 'testmod')), - :module_name => 'testmod', - :target_module_path => host_modulepath - }) + copy_module_to(host, + { + source: File.absolute_path(File.join(__dir__, 'files', 'modules', 'testmod')), + module_name: 'testmod', + target_module_path: host_modulepath, + }) - it 'should return the correct location' do + it 'returns the correct location' do results = apply_manifest_on(host, manifest).output expect(results).to match(%r{#{host_modulepath}/testmod/manifests/init.pp}m) diff --git a/spec/acceptance/suites/default/00_facter_spec.rb b/spec/acceptance/suites/default/00_facter_spec.rb index fe35f23f..b555cbb4 100644 --- a/spec/acceptance/suites/default/00_facter_spec.rb +++ b/spec/acceptance/suites/default/00_facter_spec.rb @@ -8,7 +8,7 @@ it do result = on(host, 'puppet facts').output.strip.lines - expect(result.grep(/Error/).grep(/Facter/)).to be_empty + expect(result.grep(%r{Error}).grep(%r{Facter})).to be_empty end end end diff --git a/spec/acceptance/suites/default/05_cron_mangler_spec.rb b/spec/acceptance/suites/default/05_cron_mangler_spec.rb index f57bd610..8b426f53 100644 --- a/spec/acceptance/suites/default/05_cron_mangler_spec.rb +++ b/spec/acceptance/suites/default/05_cron_mangler_spec.rb @@ -15,7 +15,7 @@ "'15', '14', '1', '*', '*'", "'0', '22', '*', '*', '1-5'", "'23', '0-20/2', '*', '*', '*'", - "'5', '4', '*', '*', 'sun'" + "'5', '4', '*', '*', 'sun'", ] hosts.each do |host| @@ -44,12 +44,12 @@ } MANIFEST - it 'should run successfully' do - apply_manifest_on(host, manifest, :catch_failures => true) + it 'runs successfully' do + apply_manifest_on(host, manifest, catch_failures: true) end - it 'should be idempotent' do - apply_manifest_on(host, manifest, :catch_changes => true) + it 'is idempotent' do + apply_manifest_on(host, manifest, catch_changes: true) end end end diff --git a/spec/acceptance/suites/default/fips_enabled_fact_spec.rb b/spec/acceptance/suites/default/fips_enabled_fact_spec.rb index a0d9094b..34d01b70 100644 --- a/spec/acceptance/suites/default/fips_enabled_fact_spec.rb +++ b/spec/acceptance/suites/default/fips_enabled_fact_spec.rb @@ -10,12 +10,11 @@ end describe 'fips_enabled fact' do - hosts.each do |host| context "when FIPS is #{fips_state} on #{host}" do it "fips_enabled fact should be #{expected_fips_enabled}" do results = on(host, 'puppet facts') - expect(results.output).to match(/"fips_enabled": #{expected_fips_enabled}/) + expect(results.output).to match(%r{"fips_enabled": #{expected_fips_enabled}}) end end end diff --git a/spec/acceptance/suites/default/inspect_spec.rb b/spec/acceptance/suites/default/inspect_spec.rb index ea7d56b9..8cf1a3f2 100644 --- a/spec/acceptance/suites/default/inspect_spec.rb +++ b/spec/acceptance/suites/default/inspect_spec.rb @@ -3,15 +3,14 @@ test_name 'simplib::inspect function' describe 'simplib::inspect function' do - # Only return simplib::inspect lines from the Puppet log minus any ANSI # escape sequences for formatting (e.g. color). # # NOTE: Have to remove ANSI formatting because beaker does not provide a # mechanism to enable the `--color=false` option on `puppet apply`. def normalize_inspect_lines(puppet_log) - normalized_lines = puppet_log.gsub(/\e\[\d*(;\d+)*m/, "").split("\n").select do |line| - line.match(/^Notice: .*Type =>/) + normalized_lines = puppet_log.gsub(%r{\e\[\d*(;\d+)*m}, '').split("\n").select do |line| + line.match(%r{^Notice: .*Type =>}) end normalized_lines.join("\n") @@ -19,7 +18,7 @@ def normalize_inspect_lines(puppet_log) hosts.each do |server| context "logs variables with simplib::inspect on #{server}" do - let (:manifest) { + let(:manifest) do <<~EOS $var1 = "var1 value" $var2 = true @@ -31,11 +30,11 @@ def normalize_inspect_lines(puppet_log) simplib::inspect('var3', 'oneline_json') simplib::inspect('var4', 'oneline_json') EOS - } + end - it 'should be log variables' do + it 'is log variables' do results = apply_manifest_on(server, manifest) - output = results.output + results.output # this is ugly, but is logged twice expected = <<~EOM diff --git a/spec/acceptance/suites/default/ipaddresses_spec.rb b/spec/acceptance/suites/default/ipaddresses_spec.rb index 3c338a1d..f25c63f4 100644 --- a/spec/acceptance/suites/default/ipaddresses_spec.rb +++ b/spec/acceptance/suites/default/ipaddresses_spec.rb @@ -3,7 +3,6 @@ test_name 'simplib::ipaddresses function' describe 'simplib::ipaddresses function' do - hosts.each do |server| let(:all_ips) do ifaces = fact_on(server, 'interfaces').split(',').map(&:strip) @@ -25,31 +24,31 @@ retval = all_ips.dup retval.delete_if do |ip| - ip =~ /^127\./ + ip =~ %r{^127\.} end retval end context "when simplib::ipaddresses called with/without arguments on #{server}" do - let (:manifest) { - <<-EOS - $var1 = simplib::ipaddresses() - $var2 = simplib::ipaddresses(true) + let(:manifest) do + <<~EOS + $var1 = simplib::ipaddresses() + $var2 = simplib::ipaddresses(true) - simplib::inspect('var1') - simplib::inspect('var2') + simplib::inspect('var1') + simplib::inspect('var2') EOS - } + end - it 'should return IP addresses' do + it 'returns IP addresses' do results = apply_manifest_on(server, manifest).output.lines.map(&:strip) - ip_matches = all_ips.map do |ip| + ip_matches = all_ips.map { |ip| results.grep(Regexp.new(Regexp.escape(ip))) - end.flatten.compact + }.flatten.compact - expect(ip_matches).to_not be_empty + expect(ip_matches).not_to be_empty end end end diff --git a/spec/acceptance/suites/default/nets2ddq_spec.rb b/spec/acceptance/suites/default/nets2ddq_spec.rb index e6c2c638..9b5a433f 100644 --- a/spec/acceptance/suites/default/nets2ddq_spec.rb +++ b/spec/acceptance/suites/default/nets2ddq_spec.rb @@ -3,19 +3,18 @@ test_name 'simplib::nets2ddq function' describe 'simplib::nets2ddq function' do - hosts.each do |server| context "when simplib::nets2ddq called on #{server}" do - let (:manifest) { - <<-EOS - $var1 = [ '10.0.1.0/24', '10.0.2.0/255.255.255.0', '10.0.3.25', 'myhost' ] - $var2 = simplib::nets2ddq($var1) + let(:manifest) do + <<~EOS + $var1 = [ '10.0.1.0/24', '10.0.2.0/255.255.255.0', '10.0.3.25', 'myhost' ] + $var2 = simplib::nets2ddq($var1) - simplib::inspect('var2') + simplib::inspect('var2') EOS - } + end - it 'should return a converted array' do + it 'returns a converted array' do results = apply_manifest_on(server, manifest) expected_regex = %r{\["10.0.1.0\/255.255.255.0","10.0.2.0\/255.255.255.0","10.0.3.25","myhost"\]} diff --git a/spec/acceptance/suites/default/parse_hosts_spec.rb b/spec/acceptance/suites/default/parse_hosts_spec.rb index 93b0699c..772eb325 100644 --- a/spec/acceptance/suites/default/parse_hosts_spec.rb +++ b/spec/acceptance/suites/default/parse_hosts_spec.rb @@ -3,23 +3,22 @@ test_name 'simplib::parse_hosts function' describe 'simplib::parse_hosts function' do - hosts.each do |server| context "when simplib::parse_hosts called on #{server}" do - let (:manifest) { - <<-EOS - $var1 = simplib::parse_hosts(['my.example.net:900', 'my.example.net:700']) + let(:manifest) do + <<~EOS + $var1 = simplib::parse_hosts(['my.example.net:900', 'my.example.net:700']) - simplib::inspect('var1', 'oneline_json') + simplib::inspect('var1', 'oneline_json') EOS - } + end - it 'should transform the host list' do + it 'transforms the host list' do results = apply_manifest_on(server, manifest) expected_content = %q({"my.example.net":{"ports":\["700","900"\],"protocols":{}}}) expect(results.output).to match( - %r(Notice: Type => Hash Content => #{expected_content}) + %r{Notice: Type => Hash Content => #{expected_content}}, ) end end diff --git a/spec/acceptance/suites/default/passgen_spec.rb b/spec/acceptance/suites/default/passgen_spec.rb index fee3fe50..05813670 100644 --- a/spec/acceptance/suites/default/passgen_spec.rb +++ b/spec/acceptance/suites/default/passgen_spec.rb @@ -2,41 +2,40 @@ require 'shellwords' test_name 'simplib::passgen function' -if ENV['BEAKER_fips'] == 'yes' - hash_algorithms = [ "sha256", "sha512" ] -else - hash_algorithms = [ "md5", "sha256", "sha512"] -end +hash_algorithms = if ENV['BEAKER_fips'] == 'yes' + [ 'sha256', 'sha512' ] + else + [ 'md5', 'sha256', 'sha512'] + end shared_examples_for 'a password generator' do |host| hash_algorithms.each do |hash| (1..5).each do |round| - # This test does exercise simplib::passgen, but since simplib::passgen # does not validate a generated password against any pam settings, # (e.g., make sure it passes pwscore), using it for local user passwords # IRL may not be advised. context "when set user 'testuser#{round}#{hash}' password of hash type == #{hash} on #{host}" do - let(:manifest) { - <<-EOS - # generate the most complex password possible and print out so - # we have access to it - $password = simplib::passgen('testuser-#{hash}-#{round}', {'complexity' => 2, 'complex_only' => true}) - notify { "password=<${password}> for testuser-#{hash}-#{round}": } + let(:manifest) do + <<~EOS + # generate the most complex password possible and print out so + # we have access to it + $password = simplib::passgen('testuser-#{hash}-#{round}', {'complexity' => 2, 'complex_only' => true}) + notify { "password=<${password}> for testuser-#{hash}-#{round}": } - # use hash of the generated password for a user's password - $hashed_password = simplib::passgen('testuser-#{hash}-#{round}', {'hash' => '#{hash}', 'complexity' => 2, 'complex_only' => true}) - user { "testuser#{round}#{hash}": - shell => "/bin/bash", - managehome => true, - password => $password, - } + # use hash of the generated password for a user's password + $hashed_password = simplib::passgen('testuser-#{hash}-#{round}', {'hash' => '#{hash}', 'complexity' => 2, 'complex_only' => true}) + user { "testuser#{round}#{hash}": + shell => "/bin/bash", + managehome => true, + password => $password, + } EOS - } + end - it 'should be able to create user with the generated password and then login with that password' do + it 'is able to create user with the generated password and then login with that password' do result = apply_manifest_on(host, manifest) - password = result.stdout.match(/password=<(.*)> for testuser/)[1] + password = result.stdout.match(%r{password=<(.*)> for testuser})[1] result = on(host, "echo #{Shellwords.escape(password)} | su -c whoami testuser#{round}#{hash}") expect(result.stdout).to eql("testuser#{round}#{hash}\n") @@ -48,11 +47,11 @@ describe 'simplib::passgen function' do context 'simpkv mode' do - let(:hieradata) {{ 'simplib::passgen::simpkv' => true }} + let(:hieradata) { { 'simplib::passgen::simpkv' => true } } hosts.each do |server| context 'test prep' do - it 'should enable simpkv mode for simplib::passgen' do + it 'enables simpkv mode for simplib::passgen' do set_hieradata_on(server, hieradata) end end @@ -64,11 +63,11 @@ end context 'legacy mode' do - let(:hieradata) {{ 'simplib::passgen::simpkv' => false }} + let(:hieradata) { { 'simplib::passgen::simpkv' => false } } hosts.each do |server| context 'test prep' do - it 'should disable simpkv mode for simplib::passgen' do + it 'disables simpkv mode for simplib::passgen' do set_hieradata_on(server, hieradata) end end diff --git a/spec/acceptance/suites/default/reboot_notify_spec.rb b/spec/acceptance/suites/default/reboot_notify_spec.rb index 5038d457..ba2ab22b 100644 --- a/spec/acceptance/suites/default/reboot_notify_spec.rb +++ b/spec/acceptance/suites/default/reboot_notify_spec.rb @@ -2,77 +2,76 @@ test_name 'reboot_notify' describe 'reboot_notify' do - hosts.each do |host| context "on #{host}" do context 'when hooked into a trigger' do - let (:manifest) { - <<-EOS - exec { '/bin/touch /tmp/__tmpfile__': - creates => '/tmp/__tmpfile__', - notify => [ - Reboot_notify['test'], - Class['simplib::reboot_notify'] - ] - } - reboot_notify { 'test': } - include 'simplib::reboot_notify' - reboot_notify { 'test2': reason => 'second test' } + let(:manifest) do + <<~EOS + exec { '/bin/touch /tmp/__tmpfile__': + creates => '/tmp/__tmpfile__', + notify => [ + Reboot_notify['test'], + Class['simplib::reboot_notify'] + ] + } + reboot_notify { 'test': } + include 'simplib::reboot_notify' + reboot_notify { 'test2': reason => 'second test' } EOS - } + end - it 'should apply cleanly' do - apply_manifest_on(host, manifest, :catch_failures => true) + it 'applies cleanly' do + apply_manifest_on(host, manifest, catch_failures: true) end - it 'should be idempotent' do - apply_manifest_on(host, manifest, :catch_changes => true) + it 'is idempotent' do # rubocop:disable RSpec/RepeatedExample + apply_manifest_on(host, manifest, catch_changes: true) end - it 'should not display notifications after reboot' do + it 'does not display notifications after reboot' do if host[:hypervisor] == 'docker' skip 'Reboot notification clearing does not work in Docker' else host.reboot result = apply_manifest_on(host, manifest).stdout - expect(result).to_not match(/System Reboot Required Because:/) + expect(result).not_to match(%r{System Reboot Required Because:}) end end - it 'should remain idempotent' do - apply_manifest_on(host, manifest, :catch_changes => true) + it 'remains idempotent' do # rubocop:disable RSpec/RepeatedExample + apply_manifest_on(host, manifest, catch_changes: true) end end context 'with log_level set to debug' do - let (:manifest) { - <<-EOS - reboot_notify { 'test': } - exec { '/bin/touch /tmp/__tmpfile2__': - creates => '/tmp/__tmpfile2__', - notify => [ - Reboot_notify['test'], - Class['simplib::reboot_notify'] - ] - } - class { 'simplib::reboot_notify': - log_level => 'debug' - } - reboot_notify { 'test2': reason => 'second test' } + let(:manifest) do + <<~EOS + reboot_notify { 'test': } + exec { '/bin/touch /tmp/__tmpfile2__': + creates => '/tmp/__tmpfile2__', + notify => [ + Reboot_notify['test'], + Class['simplib::reboot_notify'] + ] + } + class { 'simplib::reboot_notify': + log_level => 'debug' + } + reboot_notify { 'test2': reason => 'second test' } EOS - } + end - it 'should apply cleanly' do - apply_manifest_on(host, manifest, :catch_failures => true) + it 'applies cleanly' do + apply_manifest_on(host, manifest, catch_failures: true) end - it 'should be idempotent' do - apply_manifest_on(host, manifest, :catch_changes => true) + it 'is idempotent' do + apply_manifest_on(host, manifest, catch_changes: true) end - it 'should not display reboot notifications' do + it 'does not display reboot notifications' do result = apply_manifest_on(host, manifest).stdout - expect(result).to_not match(/System Reboot Required Because:/) + expect(result).not_to match(%r{System Reboot Required Because:}) end end end diff --git a/spec/acceptance/suites/default/simplib__sshd_config_fact_spec.rb b/spec/acceptance/suites/default/simplib__sshd_config_fact_spec.rb index af805833..5cd694f1 100644 --- a/spec/acceptance/suites/default/simplib__sshd_config_fact_spec.rb +++ b/spec/acceptance/suites/default/simplib__sshd_config_fact_spec.rb @@ -3,18 +3,17 @@ test_name 'simplib__sshd_config fact' describe 'simplib__sshd_config fact' do - hosts.each do |host| it 'The SSH version should be gathered' do fact_info = pfact_on(host, 'simplib__sshd_config') - expect(fact_info['version']).to match(/^\d+\.\d+/) - expect(fact_info['version']).to match(/[^\s]/) + expect(fact_info['version']).to match(%r{^\d+\.\d+}) + expect(fact_info['version']).to match(%r{[^\s]}) - expect(fact_info['full_version']).to match(/^OpenSSH_\d+\.\d+/) - expect(fact_info['full_version']).to match(/\s/) + expect(fact_info['full_version']).to match(%r{^OpenSSH_\d+\.\d+}) + expect(fact_info['full_version']).to match(%r{\s}) - expect(fact_info['AuthorizedKeysFile']).to match(/.+/) + expect(fact_info['AuthorizedKeysFile']).to match(%r{.+}) end end end diff --git a/spec/acceptance/suites/default/strip_ports_spec.rb b/spec/acceptance/suites/default/strip_ports_spec.rb index a6a68323..b9bccbeb 100644 --- a/spec/acceptance/suites/default/strip_ports_spec.rb +++ b/spec/acceptance/suites/default/strip_ports_spec.rb @@ -3,22 +3,21 @@ test_name 'simplib::strip_ports function' describe 'simplib::strip_ports function' do - hosts.each do |server| context "when simplib::strip_ports called on #{server}" do - let (:manifest) { - <<-EOS - $var1 = simplib::strip_ports(['my.example.net:900', 'my.example.net:700']) + let(:manifest) do + <<~EOS + $var1 = simplib::strip_ports(['my.example.net:900', 'my.example.net:700']) - simplib::inspect('var1', 'oneline_json') + simplib::inspect('var1', 'oneline_json') EOS - } + end - it 'should transform the host list' do + it 'transforms the host list' do results = apply_manifest_on(server, manifest) expect(results.output).to match( - %r(Notice: Type => Array Content => \["my.example.net"\]) + %r{Notice: Type => Array Content => \["my.example.net"\]}, ) end end diff --git a/spec/acceptance/suites/default/to_integer_spec.rb b/spec/acceptance/suites/default/to_integer_spec.rb index 6bbf1e2b..b73cf14c 100644 --- a/spec/acceptance/suites/default/to_integer_spec.rb +++ b/spec/acceptance/suites/default/to_integer_spec.rb @@ -3,24 +3,23 @@ test_name 'simplib::to_integer function' describe 'simplib::to_integer function' do - hosts.each do |server| context "when simplib::to_integer called on #{server}" do - let (:manifest) { - <<-EOS - $var1 = simplib::to_integer('-1') - $var2 = simplib::to_integer('24') + let(:manifest) do + <<~EOS + $var1 = simplib::to_integer('-1') + $var2 = simplib::to_integer('24') - simplib::inspect('var1', 'oneline_json') - simplib::inspect('var2', 'oneline_json') + simplib::inspect('var1', 'oneline_json') + simplib::inspect('var2', 'oneline_json') EOS - } + end - it 'should return an integer' do + it 'returns an integer' do results = apply_manifest_on(server, manifest) - expect(results.output).to match(/Notice: Type => (Fixnum|Integer) Content => -1/) - expect(results.output).to match(/Notice: Type => (Fixnum|Integer) Content => 24/) + expect(results.output).to match(%r{Notice: Type => (Fixnum|Integer) Content => -1}) + expect(results.output).to match(%r{Notice: Type => (Fixnum|Integer) Content => 24}) end end end diff --git a/spec/acceptance/suites/default/to_string_spec.rb b/spec/acceptance/suites/default/to_string_spec.rb index f5da47f6..eef985fa 100644 --- a/spec/acceptance/suites/default/to_string_spec.rb +++ b/spec/acceptance/suites/default/to_string_spec.rb @@ -3,24 +3,23 @@ test_name 'simplib::to_string function' describe 'simplib::to_string function' do - hosts.each do |server| context "when simplib::to_string called on #{server}" do - let (:manifest) { - <<-EOS - $var1 = simplib::to_string(-1) - $var2 = undef + let(:manifest) do + <<~EOS + $var1 = simplib::to_string(-1) + $var2 = undef - simplib::inspect('var1', 'oneline_json') - simplib::inspect('var2', 'oneline_json') + simplib::inspect('var1', 'oneline_json') + simplib::inspect('var2', 'oneline_json') EOS - } + end - it 'should return a string' do + it 'returns a string' do results = apply_manifest_on(server, manifest) - expect(results.output).to match(/Notice: Type => String Content => "-1"/) - expect(results.output).to match(/Notice: Type => NilClass Content => null/) + expect(results.output).to match(%r{Notice: Type => String Content => "-1"}) + expect(results.output).to match(%r{Notice: Type => NilClass Content => null}) end end end diff --git a/spec/acceptance/suites/default/validate_array_member_spec.rb b/spec/acceptance/suites/default/validate_array_member_spec.rb index 74064f7e..2ba3e152 100644 --- a/spec/acceptance/suites/default/validate_array_member_spec.rb +++ b/spec/acceptance/suites/default/validate_array_member_spec.rb @@ -5,24 +5,24 @@ describe 'simplib::validate_array_member function' do let(:opts_with_exit_1) do { - :acceptable_exit_codes => [1] + acceptable_exit_codes: [1], } end hosts.each do |server| context "when simplib::validate_array_member called on #{server}" do - it 'should accept element that is in array' do - manifest = <<-EOS - $var1 = 'foo' - simplib::validate_array_member($var1, ['foo', 'FOO']) + it 'accepts element that is in array' do + manifest = <<~EOS + $var1 = 'foo' + simplib::validate_array_member($var1, ['foo', 'FOO']) EOS apply_manifest_on(server, manifest) end - it 'should reject element that is not in array' do - manifest = <<-EOS - $var1 = 'foo' - simplib::validate_array_member($var1, ['bar', 'BAR']) + it 'rejects element that is not in array' do + manifest = <<~EOS + $var1 = 'foo' + simplib::validate_array_member($var1, ['bar', 'BAR']) EOS apply_manifest_on(server, manifest, opts_with_exit_1) end diff --git a/spec/acceptance/suites/default/validate_between_spec.rb b/spec/acceptance/suites/default/validate_between_spec.rb index 975ca028..958df465 100644 --- a/spec/acceptance/suites/default/validate_between_spec.rb +++ b/spec/acceptance/suites/default/validate_between_spec.rb @@ -5,25 +5,25 @@ describe 'simplib::validate_between function' do let(:opts_with_exit_1) do { - :acceptable_exit_codes => [1] + acceptable_exit_codes: [1], } end hosts.each do |server| context "when simplib::validate_between called on #{server}" do - it 'should accept element within range' do - manifest = <<-EOS - $var1 = 7 - simplib::validate_between($var1, 0, 60) + it 'accepts element within range' do + manifest = <<~EOS + $var1 = 7 + simplib::validate_between($var1, 0, 60) EOS apply_manifest_on(server, manifest) end # bug in the old Puppet 3 function returned false instead of failing - it 'should reject element outside of range' do - manifest = <<-EOS - $var1 = 70 - simplib::validate_between($var1, 0, 60) + it 'rejects element outside of range' do + manifest = <<~EOS + $var1 = 70 + simplib::validate_between($var1, 0, 60) EOS apply_manifest_on(server, manifest, opts_with_exit_1) end diff --git a/spec/acceptance/suites/default/validate_bool_simp_spec.rb b/spec/acceptance/suites/default/validate_bool_simp_spec.rb index 5ebcc92e..ee3d6405 100644 --- a/spec/acceptance/suites/default/validate_bool_simp_spec.rb +++ b/spec/acceptance/suites/default/validate_bool_simp_spec.rb @@ -5,24 +5,24 @@ describe 'simplib::validate_bool function' do let(:opts_with_exit_1) do { - :acceptable_exit_codes => [1] + acceptable_exit_codes: [1], } end hosts.each do |server| context "when simplib::validate_bool called on #{server}" do - it 'should accept valid bool equivalent' do - manifest = <<-EOS - $var1 = "true" - simplib::validate_bool($var1) + it 'accepts valid bool equivalent' do + manifest = <<~EOS + $var1 = "true" + simplib::validate_bool($var1) EOS apply_manifest_on(server, manifest) end - it 'should reject invalid bool equivalent' do - manifest = <<-EOS - $var1 = "True" - simplib::validate_bool($var1) + it 'rejects invalid bool equivalent' do + manifest = <<~EOS + $var1 = "True" + simplib::validate_bool($var1) EOS apply_manifest_on(server, manifest, opts_with_exit_1) end diff --git a/spec/acceptance/suites/default/validate_deep_hash_spec.rb b/spec/acceptance/suites/default/validate_deep_hash_spec.rb index bd61cb35..b0333e1b 100644 --- a/spec/acceptance/suites/default/validate_deep_hash_spec.rb +++ b/spec/acceptance/suites/default/validate_deep_hash_spec.rb @@ -5,24 +5,24 @@ describe 'simplib::validate_deep_hash function' do let(:opts_with_exit_1) do { - :acceptable_exit_codes => [1] + acceptable_exit_codes: [1], } end hosts.each do |server| context "when simplib::validate_deep_hash called on #{server}" do - it 'should accept valid hash' do - manifest = <<-EOS - $var1 = { 'server' => 'foo.bar.com' } - simplib::validate_deep_hash({ 'server' => 'bar.com$' }, $var1) + it 'accepts valid hash' do + manifest = <<~EOS + $var1 = { 'server' => 'foo.bar.com' } + simplib::validate_deep_hash({ 'server' => 'bar.com$' }, $var1) EOS apply_manifest_on(server, manifest) end - it 'should reject invalid hash' do - manifest = <<-EOS - $var1 = { 'server' => 'foo.baz.com' } - simplib::validate_deep_hash({ 'server' => 'bar.com$' }, $var1) + it 'rejects invalid hash' do + manifest = <<~EOS + $var1 = { 'server' => 'foo.baz.com' } + simplib::validate_deep_hash({ 'server' => 'bar.com$' }, $var1) EOS apply_manifest_on(server, manifest, opts_with_exit_1) end diff --git a/spec/acceptance/suites/default/validate_net_list_spec.rb b/spec/acceptance/suites/default/validate_net_list_spec.rb index 2de06348..7c707a83 100644 --- a/spec/acceptance/suites/default/validate_net_list_spec.rb +++ b/spec/acceptance/suites/default/validate_net_list_spec.rb @@ -5,24 +5,24 @@ describe 'simplib::validate_net_list function' do let(:opts_with_exit_1) do { - :acceptable_exit_codes => [1] + acceptable_exit_codes: [1], } end hosts.each do |server| context "when simplib::validate_net_list called on #{server}" do - it 'should accept valid netlists' do - manifest = <<-EOS - $var1 = ['20.20.20.0/24','4.3.2.1','6.4.3.1:800'] - simplib::validate_net_list($var1) + it 'accepts valid netlists' do + manifest = <<~EOS + $var1 = ['20.20.20.0/24','4.3.2.1','6.4.3.1:800'] + simplib::validate_net_list($var1) EOS apply_manifest_on(server, manifest) end - it 'should reject invalid netlists' do - manifest = <<-EOS - $var1 = 'bad stuff' - simplib::validate_net_list($var1) + it 'rejects invalid netlists' do + manifest = <<~EOS + $var1 = 'bad stuff' + simplib::validate_net_list($var1) EOS apply_manifest_on(server, manifest, opts_with_exit_1) end diff --git a/spec/acceptance/suites/default/validate_port_spec.rb b/spec/acceptance/suites/default/validate_port_spec.rb index 021f8bf6..ce45197b 100644 --- a/spec/acceptance/suites/default/validate_port_spec.rb +++ b/spec/acceptance/suites/default/validate_port_spec.rb @@ -5,22 +5,22 @@ describe 'validate_port function' do let(:opts_with_exit_1) do { - :acceptable_exit_codes => [1] + acceptable_exit_codes: [1], } end hosts.each do |server| context "when simplib::validate_port called on #{server}" do - it 'should accept valid ports' do - manifest = <<-EOS - $var1 = simplib::validate_port(20) + it 'accepts valid ports' do + manifest = <<~EOS + $var1 = simplib::validate_port(20) EOS apply_manifest_on(server, manifest) end - it 'should reject invalid ports' do - manifest = <<-EOS - $var1 = simplib::validate_port('65535') + it 'rejects invalid ports' do + manifest = <<~EOS + $var1 = simplib::validate_port('65535') EOS apply_manifest_on(server, manifest, opts_with_exit_1) end diff --git a/spec/acceptance/suites/default/validate_simp_puppet_settings_spec.rb b/spec/acceptance/suites/default/validate_simp_puppet_settings_spec.rb index 942d5898..10c14fb8 100644 --- a/spec/acceptance/suites/default/validate_simp_puppet_settings_spec.rb +++ b/spec/acceptance/suites/default/validate_simp_puppet_settings_spec.rb @@ -13,7 +13,7 @@ end hosts.each do |host| - context "when [main] and [master] have different vardirs in puppet.conf" do + context 'when [main] and [master] have different vardirs in puppet.conf' do it 'master.server_datadir should start with the [master] vardir' do tmp_dir = create_tmpdir_on(host, 'validate_simp_puppet_settings_spec') tmp_puppet_conf_path = "#{tmp_dir}/validate_simp_puppet_settings_spec--puppet.conf" diff --git a/spec/acceptance/suites/default/validate_uri_list_spec.rb b/spec/acceptance/suites/default/validate_uri_list_spec.rb index e5706c8e..0e416c59 100644 --- a/spec/acceptance/suites/default/validate_uri_list_spec.rb +++ b/spec/acceptance/suites/default/validate_uri_list_spec.rb @@ -5,22 +5,22 @@ describe 'simplib::validate_uri_list function' do let(:opts_with_exit_1) do { - :acceptable_exit_codes => [1] + acceptable_exit_codes: [1], } end hosts.each do |server| context "when simplib::validate_uri_list called on #{server}" do - it 'should accept valid URIs' do - manifest = <<-EOS - $var1 = simplib::validate_uri_list('https://1.2.3.4:56', ['http','https']) + it 'accepts valid URIs' do + manifest = <<~EOS + $var1 = simplib::validate_uri_list('https://1.2.3.4:56', ['http','https']) EOS apply_manifest_on(server, manifest) end - it 'should reject invalid URIs' do - manifest = <<-EOS - $var1 = simplib::validate_uri_list('ldap://1.2.3.4:56', ['http','https']) + it 'rejects invalid URIs' do + manifest = <<~EOS + $var1 = simplib::validate_uri_list('ldap://1.2.3.4:56', ['http','https']) EOS apply_manifest_on(server, manifest, opts_with_exit_1) end diff --git a/spec/acceptance/suites/ipa_fact/ipa_fact_spec.rb b/spec/acceptance/suites/ipa_fact/ipa_fact_spec.rb index 7b6fa95b..ab6e4faa 100644 --- a/spec/acceptance/suites/ipa_fact/ipa_fact_spec.rb +++ b/spec/acceptance/suites/ipa_fact/ipa_fact_spec.rb @@ -3,20 +3,18 @@ test_name 'ipa fact' def skip_fips(host) - if fips_enabled(host) && host.host_hash[:roles].include?('no_fips') - return true - else - return false - end + return true if fips_enabled(host) && host.host_hash[:roles].include?('no_fips') + + false end describe 'ipa fact' do - let (:manifest) { - <<-EOS + let(:manifest) do + <<~EOS $ipa_value = $facts['ipa'] simplib::inspect('ipa_value', 'oneline_json') EOS - } + end admin_password = '@dm1n=P@ssw0r!' ipa_domain = 'test.case' @@ -26,12 +24,12 @@ def skip_fips(host) next if skip_fips(host) # IPA requires entropy! - it 'should be running haveged or rngd for entropy' do - apply_manifest_on(host, 'include haveged', :accept_all_exit_codes => true) + it 'is running haveged or rngd for entropy' do + apply_manifest_on(host, 'include haveged', accept_all_exit_codes: true) apply_manifest_on(host, 'include haveged') end - it 'should install IPA client package' do + it 'installs IPA client package' do on(host, 'puppet resource package ipa-client ensure=present') end @@ -44,7 +42,7 @@ def skip_fips(host) on(host, 'systemctl is-active firewalld.service && firewall-cmd --add-port={{80,443,389,636,88,464,53}/tcp,{88,464,53,123}/udp} --permanent') end - it 'should ensure hostname is set to the FQDN' do + it 'ensures hostname is set to the FQDN' do hostname = pfact_on(host, 'networking.fqdn') on(host, "hostnamectl set-hostname #{hostname}") @@ -59,7 +57,7 @@ def skip_fips(host) context 'when IPA is not installed' do it 'ipa fact should be nil' do results = apply_manifest_on(server, manifest) - expect(results.output).to match(/Notice: Type => NilClass Content => null/) + expect(results.output).to match(%r{Notice: Type => NilClass Content => null}) expect(pfact_on(server, 'ipa')).to be_nil.or be_empty end @@ -72,7 +70,7 @@ def skip_fips(host) server.reboot # WORKAROUND: https://bugzilla.redhat.com/show_bug.cgi?id=1504688 results = apply_manifest_on(server, manifest) - expect(results.output).to match(/Notice: Type => NilClass Content => null/) + expect(results.output).to match(%r{Notice: Type => NilClass Content => null}) expect(pfact_on(server, 'ipa')).to be_nil.or be_empty end @@ -80,6 +78,7 @@ def skip_fips(host) context 'when IPA is installed and host has joined IPA domain' do let(:ipa_domain) { "#{server.name.downcase}.example.com" } + it 'ipa fact should contain domain and IPA server' do # ipa-server-install installs both the IPA server and client. # The fact uses the client env. @@ -94,14 +93,14 @@ def skip_fips(host) "--hostname #{fqdn}", '--ds-password "d1r3ct0ry=P@ssw0r!"', "--admin-password '#{admin_password}'", - '--unattended' + '--unattended', ] puts "\e[1;34m>>>>> The next step takes a very long time ... Please be patient! \e[0m" on(server, cmd.join(' ')) on(server, 'ipactl status') # We only care about this data - expect(apply_manifest_on(server, manifest).output).to match(/Hash Content => {"/) + expect(apply_manifest_on(server, manifest).output).to match(%r{Hash Content => \{"}) results = pfact_on(server, 'ipa') @@ -124,7 +123,7 @@ def skip_fips(host) expect(results['connected']).to eq false end - it 'should restart the IPA server for further tests' do + it 'restarts the IPA server for further tests' do on(server, 'ipactl start') end end @@ -134,19 +133,18 @@ def skip_fips(host) next if skip_fips(client) context 'as an IPA client' do - context 'prior to registration' do - it 'should not have an IPA fact' do + it 'does not have an IPA fact' do expect(pfact_on(client, 'ipa')).to be_nil.or be_empty end end context 'after registration' do - let(:ipa_server) { + let(:ipa_server) do pfact_on(hosts_with_role(hosts, 'server').first, 'networking.fqdn') - } + end - it 'should register with the IPA server' do + it 'registers with the IPA server' do os = fact_on(client, 'os') ipa_command = [ # Unattended installation @@ -170,7 +168,7 @@ def skip_fips(host) on(client, ipa_command) end - it 'should have the IPA fact populated' do + it 'has the IPA fact populated' do results = pfact_on(client, 'ipa') expect(results).to be_a(Hash) @@ -194,7 +192,7 @@ def skip_fips(host) expect(results['connected']).to eq false end - it 'should restart the IPA server for further tests' do + it 'restarts the IPA server for further tests' do hosts_with_role(hosts, 'server').each do |server| on(server, 'ipactl start') end diff --git a/spec/acceptance/suites/prelink_fact/prelink_fact_spec.rb b/spec/acceptance/suites/prelink_fact/prelink_fact_spec.rb index 4c6cc5d3..8aaa4618 100644 --- a/spec/acceptance/suites/prelink_fact/prelink_fact_spec.rb +++ b/spec/acceptance/suites/prelink_fact/prelink_fact_spec.rb @@ -3,18 +3,18 @@ test_name 'prelink fact' describe 'prelink fact' do - let (:manifest) { - <<-EOS + let(:manifest) do + <<~EOS $prelink_value = $facts['prelink'] simplib::inspect('prelink_value', 'oneline_json') EOS - } + end hosts.each do |server| context 'prepare clean environment' do it 'removes prelink when installed' do - installed = check_for_package(server, 'prelink') - if (installed) + installed = check_for_package(server, 'prelink') + if installed on(server, "sed -i '/PRELINKING=yes/ c\\PRELINKING=no' /etc/sysconfig/prelink") # remove prelinking, if appropriate, before uninstalling on(server, '/etc/cron.daily/prelink') @@ -26,35 +26,34 @@ context 'when prelink is not installed' do it 'prelink fact should be nil' do results = apply_manifest_on(server, manifest) - expect(results.output).to match(/Notice: Type => NilClass Content => null/) + expect(results.output).to match(%r{Notice: Type => NilClass Content => null}) results = on(server, 'puppet facts') - expect(results.output).to_not match(/"prelink": {/) + expect(results.output).not_to match(%r{"prelink": \{}) end end - if server.host_hash[:roles].include?('prelink') - context 'when prelink is installed but disabled' do - it 'prelink fact should report prelink as disabled' do - server.install_package('prelink') - # prelinking is enabled by default on el6 - on(server, "sed -i '/PRELINKING=yes/ c\\PRELINKING=no' /etc/sysconfig/prelink") + next unless server.host_hash[:roles].include?('prelink') + context 'when prelink is installed but disabled' do + it 'prelink fact should report prelink as disabled' do + server.install_package('prelink') + # prelinking is enabled by default on el6 + on(server, "sed -i '/PRELINKING=yes/ c\\PRELINKING=no' /etc/sysconfig/prelink") - results = apply_manifest_on(server, manifest) - expect(results.output).to match(/Notice: Type => Hash Content => {"enabled":false}/) - results = on(server, 'puppet facts') - expect(results.output).to match(/"prelink": {/) - end + results = apply_manifest_on(server, manifest) + expect(results.output).to match(%r{Notice: Type => Hash Content => {"enabled":false}}) + results = on(server, 'puppet facts') + expect(results.output).to match(%r{"prelink": \{}) end + end - context 'when prelink is installed and enabled' do - it 'prelink fact should report prelink as enabled' do - on(server, "sed -i '/PRELINKING=no/ c\\PRELINKING=yes' /etc/sysconfig/prelink") + context 'when prelink is installed and enabled' do + it 'prelink fact should report prelink as enabled' do + on(server, "sed -i '/PRELINKING=no/ c\\PRELINKING=yes' /etc/sysconfig/prelink") - results = apply_manifest_on(server, manifest) - expect(results.output).to match(/Notice: Type => Hash Content => {"enabled":true}/) - results = on(server, 'puppet facts') - expect(results.output).to match(/"prelink": {/) - end + results = apply_manifest_on(server, manifest) + expect(results.output).to match(%r{Notice: Type => Hash Content => \{"enabled":true\}}) + results = on(server, 'puppet facts') + expect(results.output).to match(%r{"prelink": \{}) end end end diff --git a/spec/acceptance/suites/windows/00_facter_spec.rb b/spec/acceptance/suites/windows/00_facter_spec.rb index fe35f23f..b555cbb4 100644 --- a/spec/acceptance/suites/windows/00_facter_spec.rb +++ b/spec/acceptance/suites/windows/00_facter_spec.rb @@ -8,7 +8,7 @@ it do result = on(host, 'puppet facts').output.strip.lines - expect(result.grep(/Error/).grep(/Facter/)).to be_empty + expect(result.grep(%r{Error}).grep(%r{Facter})).to be_empty end end end diff --git a/spec/classes/reboot_notify_spec.rb b/spec/classes/reboot_notify_spec.rb index af02865a..6aca5fac 100644 --- a/spec/classes/reboot_notify_spec.rb +++ b/spec/classes/reboot_notify_spec.rb @@ -2,7 +2,7 @@ describe 'simplib::reboot_notify' do context 'on supported operating systems' do - on_supported_os.each do |os, facts| + on_supported_os.each_key do |os| context "on #{os}" do it { is_expected.to compile.with_all_deps } it { is_expected.to create_reboot_notify('__simplib_control__').with_log_level('notice') } diff --git a/spec/defines/install_spec.rb b/spec/defines/install_spec.rb index fd810f45..a6df6b13 100644 --- a/spec/defines/install_spec.rb +++ b/spec/defines/install_spec.rb @@ -1,6 +1,6 @@ require 'spec_helper' -describe 'simplib::install', :type => :define do +describe 'simplib::install', type: :define do on_supported_os.each do |os, os_facts| context "on #{os}" do let(:facts) do @@ -10,22 +10,26 @@ let(:title) { 'Test' } context 'with defaults' do - let(:params) {{ - :packages => { - 'foo' => :undef + let(:params) do + { + packages: { + 'foo' => :undef + } } - }} + end it { is_expected.to compile.with_all_deps } it { is_expected.to create_package('foo').with_ensure('installed') } end context 'with an empty hash for options' do - let(:params) {{ - :packages => { - 'foo' => {} + let(:params) do + { + packages: { + 'foo' => {} + } } - }} + end it { is_expected.to compile.with_all_deps } it { is_expected.to create_package('foo').with_ensure('installed') } @@ -33,31 +37,35 @@ unless os_facts[:kernel].casecmp('windows') context 'with alternate defaults' do - let(:params) {{ - :packages => { - 'foo' => :undef - }, - :defaults => { - 'ensure' => 'latest' + let(:params) do + { + packages: { + 'foo' => :undef + }, + defaults: { + 'ensure' => 'latest' + } } - }} + end it { is_expected.to compile.with_all_deps } it { is_expected.to create_package('foo').with_ensure('latest') } end context 'with package specific overrides' do - let(:params) {{ - :packages => { - 'foo' => :undef, - 'bar' => { - 'ensure' => 'installed' - } - }, - :defaults => { - 'ensure' => 'latest' + let(:params) do + { + packages: { + 'foo' => :undef, + 'bar' => { + 'ensure' => 'installed' + } + }, + defaults: { + 'ensure' => 'latest' + } } - }} + end it { is_expected.to compile.with_all_deps } it { is_expected.to create_package('foo').with_ensure('latest') } diff --git a/spec/functions/assert_metadata_spec.rb b/spec/functions/assert_metadata_spec.rb index f75ebaed..e6d2ebc9 100644 --- a/spec/functions/assert_metadata_spec.rb +++ b/spec/functions/assert_metadata_spec.rb @@ -11,12 +11,12 @@ { 'operatingsystem' => 'Ubuntu', 'operatingsystemrelease' => ['14.04'] - } + }, ] }.to_json valid_facts = { - :os => { + os: { 'name' => 'Ubuntu', 'release' => { 'major' => '14', @@ -26,7 +26,7 @@ } bad_os = { - :os => { + os: { 'name' => 'Foo', 'release' => { 'major' => '14', @@ -36,7 +36,7 @@ } bad_version = { - :os => { + os: { 'name' => 'Ubuntu', 'release' => { 'major' => '10', @@ -110,19 +110,19 @@ context 'at the OS' do let(:facts) { bad_os } - it { expect { is_expected.to run.with_params('simplib') }.to raise_error(/OS '#{facts[:os]['name']} #{facts[:os]['release']['full']}' is not supported by 'simplib'/) } + it { expect { is_expected.to run.with_params('simplib') }.to raise_error(%r{OS '#{facts[:os]['name']} #{facts[:os]['release']['full']}' is not supported by 'simplib'}) } end context 'at the major version' do let(:facts) { bad_version } - it { expect { is_expected.to run.with_params('simplib', options_major) }.to raise_error(/OS '#{facts[:os]['name']} #{facts[:os]['release']['full']}' is not supported by 'simplib'/) } + it { expect { is_expected.to run.with_params('simplib', options_major) }.to raise_error(%r{OS '#{facts[:os]['name']} #{facts[:os]['release']['full']}' is not supported by 'simplib'}) } end context 'at the full version' do let(:facts) { bad_version } - it { expect { is_expected.to run.with_params('simplib', options_full) }.to raise_error(/OS '#{facts[:os]['name']} #{facts[:os]['release']['full']}' is not supported by 'simplib'/) } + it { expect { is_expected.to run.with_params('simplib', options_full) }.to raise_error(%r{OS '#{facts[:os]['name']} #{facts[:os]['release']['full']}' is not supported by 'simplib'}) } end end end diff --git a/spec/functions/cron/to_systemd_spec.rb b/spec/functions/cron/to_systemd_spec.rb index 205d854a..07dd8534 100644 --- a/spec/functions/cron/to_systemd_spec.rb +++ b/spec/functions/cron/to_systemd_spec.rb @@ -8,31 +8,31 @@ test_hash = { [] => '*-* *:*', [0] => '*-* *:0', - [['27','57']] => '*-* *:27,57', - [nil,0] => '*-* 0:*', - [0,0] => '*-* 0:0', - [0,0,1,nil,0] => 'Sun 1-* 0:0', - [nil,nil,5] => '5-* *:*', - [nil,nil,'*',3] => '*-3 *:*', - [nil,nil,5,3] => '5-3 *:*', - [nil,nil,'MAY',3] => '5-3 *:*', - [nil,nil,['MAY','jan'],3] => '5,1-3 *:*', - [nil,nil,nil,nil,'tue'] => 'tue *-* *:*', - [nil,nil,nil,nil,0] => 'Sun *-* *:*', - [nil,nil,nil,nil,'0'] => 'Sun *-* *:*', - [nil,nil,nil,nil,[0,1]] => 'Sun,Mon *-* *:*', - [nil,nil,nil,nil,['1-5']] => 'Mon,Tue,Wed,Thu,Fri *-* *:*', - ['0,3',nil,nil,nil,[0,1]] => 'Sun,Mon *-* *:0,3', - ['0-3',nil,nil,nil,[0,1]] => 'Sun,Mon *-* *:0,1,2,3', - ['0-3/2',nil,nil,nil,[0,1]] => 'Sun,Mon *-* *:0,1,2,3/2', - ['0/3',nil,nil,nil,[0,1]] => 'Sun,Mon *-* *:0/3', - [nil,'0,5',nil,nil,[0,1]] => 'Sun,Mon *-* 0,5:*', - [nil,'0-5',nil,nil,[0,1]] => 'Sun,Mon *-* 0,1,2,3,4,5:*', - [nil,'0-5/2',nil,nil,[0,1]] => 'Sun,Mon *-* 0,1,2,3,4,5/2:*', - [nil,'0/5',nil,nil,[0,1]] => 'Sun,Mon *-* 0/5:*', + [['27', '57']] => '*-* *:27,57', + [nil, 0] => '*-* 0:*', + [0, 0] => '*-* 0:0', + [0, 0, 1, nil, 0] => 'Sun 1-* 0:0', + [nil, nil, 5] => '5-* *:*', + [nil, nil, '*', 3] => '*-3 *:*', + [nil, nil, 5, 3] => '5-3 *:*', + [nil, nil, 'MAY', 3] => '5-3 *:*', + [nil, nil, ['MAY', 'jan'], 3] => '5,1-3 *:*', + [nil, nil, nil, nil, 'tue'] => 'tue *-* *:*', + [nil, nil, nil, nil, 0] => 'Sun *-* *:*', + [nil, nil, nil, nil, '0'] => 'Sun *-* *:*', + [nil, nil, nil, nil, [0, 1]] => 'Sun,Mon *-* *:*', + [nil, nil, nil, nil, ['1-5']] => 'Mon,Tue,Wed,Thu,Fri *-* *:*', + ['0,3', nil, nil, nil, [0, 1]] => 'Sun,Mon *-* *:0,3', + ['0-3', nil, nil, nil, [0, 1]] => 'Sun,Mon *-* *:0,1,2,3', + ['0-3/2', nil, nil, nil, [0, 1]] => 'Sun,Mon *-* *:0,1,2,3/2', + ['0/3', nil, nil, nil, [0, 1]] => 'Sun,Mon *-* *:0/3', + [nil, '0,5', nil, nil, [0, 1]] => 'Sun,Mon *-* 0,5:*', + [nil, '0-5', nil, nil, [0, 1]] => 'Sun,Mon *-* 0,1,2,3,4,5:*', + [nil, '0-5/2', nil, nil, [0, 1]] => 'Sun,Mon *-* 0,1,2,3,4,5/2:*', + [nil, '0/5', nil, nil, [0, 1]] => 'Sun,Mon *-* 0/5:*', } test_hash.each_pair do |input, output| - it_behaves_like 'simplib::cron::to_systemd()', input.map{|x| x ||= '*'}, output + it_behaves_like 'simplib::cron::to_systemd()', input.map { |x| x || '*' }, output end end diff --git a/spec/functions/hash_to_opts_spec.rb b/spec/functions/hash_to_opts_spec.rb index 3dc9a0aa..1a0564b3 100644 --- a/spec/functions/hash_to_opts_spec.rb +++ b/spec/functions/hash_to_opts_spec.rb @@ -1,56 +1,60 @@ require 'spec_helper' describe 'simplib::hash_to_opts' do - tests = [ { - content: {'iface' => 'eth1'}, + content: { 'iface' => 'eth1' }, result: '--iface=eth1' }, { - content: { 'iface' => 'eth1', 'arg2' => 'junk value' }, + content: { 'iface' => 'eth1', 'arg2' => 'junk value' }, result: '--iface=eth1 --arg2="junk value"' }, { - content: {'key' => 8}, + content: { 'key' => 8 }, result: '--key=8' }, { - content: {'key' => false}, + content: { 'key' => false }, result: '--key=false' }, { - content: {'key' => ['yes',true,1]}, + content: { 'key' => ['yes', true, 1] }, result: '--key=yes,true,1' }, { - content: {'key' => :undef}, + content: { 'key' => :undef }, result: '--key' }, { - content: {'key' => nil}, + content: { 'key' => nil }, result: '--key' }, ] - - it { is_expected.to run.with_params() \ - .and_raise_error(/between 1 and 2 arguments, got none/) } + it { + is_expected.to run.with_params \ + .and_raise_error(%r{between 1 and 2 arguments, got none}) + } context 'with default secondary options' do tests.each do |params| - it { is_expected.to run.with_params(params[:content]) \ - .and_return(params[:result]) } + it { + is_expected.to run.with_params(params[:content]) \ + .and_return(params[:result]) + } end end context 'with some secondary options set' do tests.each do |params| opts = { 'connector' => ' ' } - result = params[:result].gsub(/=/,' ') + result = params[:result].tr('=', ' ') - it { is_expected.to run.with_params(params[:content],opts) \ - .and_return(result) } + it { + is_expected.to run.with_params(params[:content], opts) \ + .and_return(result) + } end end @@ -62,20 +66,24 @@ 'delimiter' => ':' } result = params[:result] \ - .gsub(/=/,' ') - .gsub(/--/,'-') - .gsub(/,/,':') + .tr('=', ' ') + .gsub('--', '-') + .tr(',', ':') - it { is_expected.to run.with_params(params[:content],opts) \ - .and_return(result) } + it { + is_expected.to run.with_params(params[:content], opts) \ + .and_return(result) + } end end context 'with repeat set to repeat' do - params = { 'key' => ['yes',true,1] } + params = { 'key' => ['yes', true, 1] } opts = { 'repeat' => 'repeat' } result = '--key=yes --key=true --key=1' - it { is_expected.to run.with_params(params,opts) \ - .and_return(result) } + it { + is_expected.to run.with_params(params, opts) \ + .and_return(result) + } end end diff --git a/spec/functions/knockout_spec.rb b/spec/functions/knockout_spec.rb index d021fa02..00e4ed82 100644 --- a/spec/functions/knockout_spec.rb +++ b/spec/functions/knockout_spec.rb @@ -7,19 +7,19 @@ describe 'simplib::knockout' do context 'when a simple array is passed' do it_behaves_like 'simplib::knockout()', - %w(socrates plato aristotle), - %w(socrates plato aristotle) + ['socrates', 'plato', 'aristotle'], + ['socrates', 'plato', 'aristotle'] end context 'when passed a mixed array' do it_behaves_like 'simplib::knockout()', - %w(socrates plato aristotle --socrates), - %w(plato aristotle) + ['socrates', 'plato', 'aristotle', '--socrates'], + ['plato', 'aristotle'] end context 'when passed a mixed array where everything is knocked out' do it_behaves_like 'simplib::knockout()', - %w(socrates plato aristotle --plato --aristotle --socrates), + ['socrates', 'plato', 'aristotle', '--plato', '--aristotle', '--socrates'], [] end end diff --git a/spec/functions/ldap/domain_to_dn_spec.rb b/spec/functions/ldap/domain_to_dn_spec.rb index 35869839..6cb64eaa 100644 --- a/spec/functions/ldap/domain_to_dn_spec.rb +++ b/spec/functions/ldap/domain_to_dn_spec.rb @@ -1,39 +1,31 @@ require 'spec_helper' describe 'simplib::ldap::domain_to_dn' do - on_supported_os.each do |os, os_facts| + on_supported_os.each_value do |os_facts| context 'with a regular domain' do - let(:facts) { + let(:facts) do os_facts[:networking][:domain] = 'test.domain' os_facts - } - - it do - expect( subject.execute() ).to eq 'DC=test,DC=domain' end + + it { is_expected.to run.and_return('DC=test,DC=domain') } end context 'with a short domain' do - let(:facts) { + let(:facts) do os_facts[:networking][:domain] = 'domain' os_facts - } - - it do - expect( subject.execute() ).to eq 'DC=domain' end + + it { is_expected.to run.and_return('DC=domain') } end context 'when passed a domain' do - it do - expect( subject.execute('test.domain') ).to eq 'DC=test,DC=domain' - end + it { is_expected.to run.with_params('test.domain').and_return('DC=test,DC=domain') } end context 'when told to downcase the attributes' do - it do - expect( subject.execute('test.domain', true) ).to eq 'dc=test,dc=domain' - end + it { is_expected.to run.with_params('test.domain', true).and_return('dc=test,dc=domain') } end end end diff --git a/spec/functions/module_metadata/assert_spec.rb b/spec/functions/module_metadata/assert_spec.rb index c7745328..9ba3856e 100644 --- a/spec/functions/module_metadata/assert_spec.rb +++ b/spec/functions/module_metadata/assert_spec.rb @@ -11,12 +11,12 @@ { 'operatingsystem' => 'Ubuntu', 'operatingsystemrelease' => ['14.04'] - } + }, ] }.to_json valid_facts = { - :os => { + os: { 'name' => 'Ubuntu', 'release' => { 'major' => '14', @@ -26,7 +26,7 @@ } bad_os = { - :os => { + os: { 'name' => 'Foo', 'release' => { 'major' => '14', @@ -36,7 +36,7 @@ } bad_version = { - :os => { + os: { 'name' => 'Ubuntu', 'release' => { 'major' => '10', @@ -78,7 +78,7 @@ } blacklist_no_match = { - 'blacklist' => [ 'Foo', {'Bar' => '1.1.1'} ] + 'blacklist' => [ 'Foo', { 'Bar' => '1.1.1' } ] } blacklist_base = { @@ -86,7 +86,7 @@ } blacklist_advanced = { - 'blacklist' => [ {'Ubuntu' => '14.04'} ] + 'blacklist' => [ { 'Ubuntu' => '14.04' } ] } blacklist_major = { @@ -136,7 +136,7 @@ context 'at the OS' do let(:facts) { bad_os } - it { expect { is_expected.to run.with_params('simplib') }.to raise_error(/OS '#{facts[:os]['name']} #{facts[:os]['release']['full']}' is not supported by 'simplib'/) } + it { expect { is_expected.to run.with_params('simplib') }.to raise_error(%r{OS '#{facts[:os]['name']} #{facts[:os]['release']['full']}' is not supported by 'simplib'}) } context 'when disabled globally' do it { is_expected.to run.with_params('simplib', options_disable_global) } @@ -150,7 +150,7 @@ context 'at the major version' do let(:facts) { bad_version } - it { expect { is_expected.to run.with_params('simplib', options_major) }.to raise_error(/OS '#{facts[:os]['name']} #{facts[:os]['release']['full']}' is not supported by 'simplib'/) } + it { expect { is_expected.to run.with_params('simplib', options_major) }.to raise_error(%r{OS '#{facts[:os]['name']} #{facts[:os]['release']['full']}' is not supported by 'simplib'}) } context 'when disabled globally' do it { is_expected.to run.with_params('simplib', options_major.merge(options_disable_global)) } @@ -164,7 +164,7 @@ context 'at the full version' do let(:facts) { bad_version } - it { expect { is_expected.to run.with_params('simplib', options_full) }.to raise_error(/OS '#{facts[:os]['name']} #{facts[:os]['release']['full']}' is not supported by 'simplib'/) } + it { expect { is_expected.to run.with_params('simplib', options_full) }.to raise_error(%r{OS '#{facts[:os]['name']} #{facts[:os]['release']['full']}' is not supported by 'simplib'}) } context 'when disabled globally' do it { is_expected.to run.with_params('simplib', options_full.merge(options_disable_global)) } @@ -179,16 +179,16 @@ context 'with a blacklist' do context 'with no match' do - let(:facts){ valid_facts } + let(:facts) { valid_facts } it { is_expected.to run.with_params('simplib', blacklist_no_match) } end context 'with an OS match' do - let(:facts){ valid_facts } + let(:facts) { valid_facts } context 'with a simple list' do - it { expect { is_expected.to run.with_params('simplib', blacklist_base) }.to raise_error(/OS '#{facts[:os]['name']} #{facts[:os]['release']['full']}' is not supported at '/) } + it { expect { is_expected.to run.with_params('simplib', blacklist_base) }.to raise_error(%r{OS '#{facts[:os]['name']} #{facts[:os]['release']['full']}' is not supported at '}) } context 'when disabled globally' do it { is_expected.to run.with_params('simplib', blacklist_base.merge(options_disable_global)) } @@ -199,7 +199,11 @@ end context 'at the major version' do - it { expect { is_expected.to run.with_params('simplib', blacklist_base.merge(blacklist_major)) }.to raise_error(/OS '#{facts[:os]['name']} #{facts[:os]['release']['full']}' is not supported at '/) } + it { + expect { + is_expected.to run.with_params('simplib', blacklist_base.merge(blacklist_major)) + }.to raise_error(%r{OS '#{facts[:os]['name']} #{facts[:os]['release']['full']}' is not supported at '}) + } context 'when disabled globally' do it { is_expected.to run.with_params('simplib', blacklist_base.merge(options_disable_global)) } @@ -211,7 +215,11 @@ end context 'at the full version' do - it { expect { is_expected.to run.with_params('simplib', blacklist_base.merge(blacklist_full)) }.to raise_error(/OS '#{facts[:os]['name']} #{facts[:os]['release']['full']}' is not supported at '/) } + it { + expect { + is_expected.to run.with_params('simplib', blacklist_base.merge(blacklist_full)) + }.to raise_error(%r{OS '#{facts[:os]['name']} #{facts[:os]['release']['full']}' is not supported at '}) + } context 'when disabled globally' do it { is_expected.to run.with_params('simplib', blacklist_base.merge(options_disable_global)) } @@ -224,7 +232,7 @@ end context 'with complex options' do - it { expect { is_expected.to run.with_params('simplib', blacklist_advanced) }.to raise_error(/OS '#{facts[:os]['name']} #{facts[:os]['release']['full']}' is not supported at '/) } + it { expect { is_expected.to run.with_params('simplib', blacklist_advanced) }.to raise_error(%r{OS '#{facts[:os]['name']} #{facts[:os]['release']['full']}' is not supported at '}) } context 'when disabled globally' do it { is_expected.to run.with_params('simplib', blacklist_advanced.merge(options_disable_global)) } @@ -235,7 +243,11 @@ end context 'at the major version' do - it { expect { is_expected.to run.with_params('simplib', blacklist_advanced.merge(blacklist_major)) }.to raise_error(/OS '#{facts[:os]['name']} #{facts[:os]['release']['full']}' is not supported at '/) } + it { + expect { + is_expected.to run.with_params('simplib', blacklist_advanced.merge(blacklist_major)) + }.to raise_error(%r{OS '#{facts[:os]['name']} #{facts[:os]['release']['full']}' is not supported at '}) + } context 'when disabled globally' do it { is_expected.to run.with_params('simplib', blacklist_advanced.merge(blacklist_major.merge(options_disable_global))) } @@ -247,7 +259,11 @@ end context 'at the full version' do - it { expect { is_expected.to run.with_params('simplib', blacklist_advanced.merge(blacklist_full)) }.to raise_error(/OS '#{facts[:os]['name']} #{facts[:os]['release']['full']}' is not supported at '/) } + it { + expect { + is_expected.to run.with_params('simplib', blacklist_advanced.merge(blacklist_full)) + }.to raise_error(%r{OS '#{facts[:os]['name']} #{facts[:os]['release']['full']}' is not supported at '}) + } context 'when disabled globally' do it { is_expected.to run.with_params('simplib', blacklist_advanced.merge(blacklist_full.merge(options_disable_global))) } diff --git a/spec/functions/module_metadata/os_blacklisted_spec.rb b/spec/functions/module_metadata/os_blacklisted_spec.rb index 16a1a3fc..24f27fa5 100644 --- a/spec/functions/module_metadata/os_blacklisted_spec.rb +++ b/spec/functions/module_metadata/os_blacklisted_spec.rb @@ -2,52 +2,50 @@ describe 'simplib::module_metadata::os_blacklisted' do context 'on a supported, but blacklisted, OS' do - before(:each) do - @module_metadata = scope.function_load_module_metadata(['simplib']) - end + let(:module_metadata) { scope.function_load_module_metadata(['simplib']) } - facts = { - :os => { - 'name' => 'Ubuntu', - 'release' => { - 'major' => '14', - 'full' => '14.999' + let(:facts) do + { + os: { + 'name' => 'Ubuntu', + 'release' => { + 'major' => '14', + 'full' => '14.999' + } } } - } - - let(:facts) { facts } + end context 'with no version matching' do context 'with a match' do - it 'should return true' do - is_expected.to run.with_params(@module_metadata, ['Banana', 'Ubuntu', 'Chicken'] ).and_return(true) + it 'returns true' do + is_expected.to run.with_params(module_metadata, ['Banana', 'Ubuntu', 'Chicken']).and_return(true) end end context 'without a match' do - it 'should return false' do - is_expected.to run.with_params(@module_metadata, ['Banana', 'Ubuntwo', 'Chicken'] ).and_return(false) + it 'returns false' do + is_expected.to run.with_params(module_metadata, ['Banana', 'Ubuntwo', 'Chicken']).and_return(false) end end end context 'with full version matching' do context 'with a match' do - it 'should return true' do + it 'returns true' do is_expected.to run.with_params( - @module_metadata, - ['Banana', {'Ubuntu' => '14.999'}, {'Chicken' => ['14.999', '15.1']}], - { 'release_match' => 'full' } + module_metadata, + ['Banana', { 'Ubuntu' => '14.999' }, { 'Chicken' => ['14.999', '15.1'] }], + { 'release_match' => 'full' }, ).and_return(true) end context 'without a match' do - it 'should return false' do + it 'returns false' do is_expected.to run.with_params( - @module_metadata, - ['Banana', {'Ubuntu' => '14.888'}, {'Chicken' => ['14.999', '15.1']}], - { 'release_match' => 'full' } + module_metadata, + ['Banana', { 'Ubuntu' => '14.888' }, { 'Chicken' => ['14.999', '15.1'] }], + { 'release_match' => 'full' }, ).and_return(false) end end @@ -56,21 +54,21 @@ context 'with major version matching' do context 'with a match' do - it 'should return true' do + it 'returns true' do is_expected.to run.with_params( - @module_metadata, - ['Banana', {'Ubuntu' => '14.999'}, {'Chicken' => ['14.999', '15.1']}], - { 'release_match' => 'major' } + module_metadata, + ['Banana', { 'Ubuntu' => '14.999' }, { 'Chicken' => ['14.999', '15.1'] }], + { 'release_match' => 'major' }, ).and_return(true) end end context 'without a match' do - it 'should return false' do + it 'returns false' do is_expected.to run.with_params( - @module_metadata, - ['Banana', {'Ubuntu' => '13.999'}, {'Chicken' => ['14.999', '15.1']}], - { 'release_match' => 'major' } + module_metadata, + ['Banana', { 'Ubuntu' => '13.999' }, { 'Chicken' => ['14.999', '15.1'] }], + { 'release_match' => 'major' }, ).and_return(false) end end diff --git a/spec/functions/module_metadata/os_supported_spec.rb b/spec/functions/module_metadata/os_supported_spec.rb index ef87cb08..51a954e4 100644 --- a/spec/functions/module_metadata/os_supported_spec.rb +++ b/spec/functions/module_metadata/os_supported_spec.rb @@ -3,7 +3,7 @@ describe 'simplib::module_metadata::os_supported' do context 'on a supported OS' do facts = { - :os => { + os: { 'name' => 'Ubuntu', 'release' => { 'major' => '14', @@ -14,49 +14,53 @@ let(:facts) { facts } - let(:module_metadata){{ - 'name' => 'test-module', - 'version' => '0.0.1', - 'operatingsystem_support' => [ - { - 'operatingsystem' => 'Aardvark', - 'operatingsystemrelease' => [ '14.999' ] - }, - { - 'operatingsystem' => 'Ubuntu', - 'operatingsystemrelease' => [ '14.999' ] - }, - { - 'operatingsystem' => 'Banana', - 'operatingsystemrelease' => [ '1.2', '2.3' ] - } - ] - }} + let(:module_metadata) do + { + 'name' => 'test-module', + 'version' => '0.0.1', + 'operatingsystem_support' => [ + { + 'operatingsystem' => 'Aardvark', + 'operatingsystemrelease' => [ '14.999' ] + }, + { + 'operatingsystem' => 'Ubuntu', + 'operatingsystemrelease' => [ '14.999' ] + }, + { + 'operatingsystem' => 'Banana', + 'operatingsystemrelease' => [ '1.2', '2.3' ] + }, + ] + } + end context 'with no version matching' do context 'with a match' do - it 'should return true' do + it 'returns true' do is_expected.to run.with_params(module_metadata).and_return(true) end end context 'without a match' do - let(:module_metadata){{ - 'name' => 'test-module', - 'version' => '0.0.1', - 'operatingsystem_support' => [ - { - 'operatingsystem' => 'Aardvark', - 'operatingsystemrelease' => [ '14.999' ] - }, - { - 'operatingsystem' => 'Banana', - 'operatingsystemrelease' => [ '15.123' ] - } - ] - }} + let(:module_metadata) do + { + 'name' => 'test-module', + 'version' => '0.0.1', + 'operatingsystem_support' => [ + { + 'operatingsystem' => 'Aardvark', + 'operatingsystemrelease' => [ '14.999' ] + }, + { + 'operatingsystem' => 'Banana', + 'operatingsystemrelease' => [ '15.123' ] + }, + ] + } + end - it 'should return false' do + it 'returns false' do is_expected.to run.with_params(module_metadata).and_return(false) end end @@ -64,37 +68,39 @@ context 'with full version matching' do context 'with a match' do - it 'should return true' do + it 'returns true' do is_expected.to run.with_params( module_metadata, - { 'release_match' => 'full' } + { 'release_match' => 'full' }, ).and_return(true) end context 'without a match' do - let(:module_metadata){{ - 'name' => 'test-module', - 'version' => '0.0.1', - 'operatingsystem_support' => [ - { - 'operatingsystem' => 'Aardvark', - 'operatingsystemrelease' => [ '14.999' ] - }, - { - 'operatingsystem' => 'Ubuntu', - 'operatingsystemrelease' => [ '14.111' ] - }, - { - 'operatingsystem' => 'Banana', - 'operatingsystemrelease' => [ '1.2', '2.3' ] - } - ] - }} + let(:module_metadata) do + { + 'name' => 'test-module', + 'version' => '0.0.1', + 'operatingsystem_support' => [ + { + 'operatingsystem' => 'Aardvark', + 'operatingsystemrelease' => [ '14.999' ] + }, + { + 'operatingsystem' => 'Ubuntu', + 'operatingsystemrelease' => [ '14.111' ] + }, + { + 'operatingsystem' => 'Banana', + 'operatingsystemrelease' => [ '1.2', '2.3' ] + }, + ] + } + end - it 'should return false' do + it 'returns false' do is_expected.to run.with_params( module_metadata, - { 'release_match' => 'full' } + { 'release_match' => 'full' }, ).and_return(false) end end @@ -103,38 +109,40 @@ context 'with major version matching' do context 'with a match' do - it 'should return true' do + it 'returns true' do is_expected.to run.with_params( module_metadata, - { 'release_match' => 'major' } + { 'release_match' => 'major' }, ).and_return(true) end end context 'without a match' do - let(:module_metadata){{ - 'name' => 'test-module', - 'version' => '0.0.1', - 'operatingsystem_support' => [ - { - 'operatingsystem' => 'Aardvark', - 'operatingsystemrelease' => [ '14.999' ] - }, - { - 'operatingsystem' => 'Ubuntu', - 'operatingsystemrelease' => [ '15.999' ] - }, - { - 'operatingsystem' => 'Banana', - 'operatingsystemrelease' => [ '1.2', '2.3' ] - } - ] - }} + let(:module_metadata) do + { + 'name' => 'test-module', + 'version' => '0.0.1', + 'operatingsystem_support' => [ + { + 'operatingsystem' => 'Aardvark', + 'operatingsystemrelease' => [ '14.999' ] + }, + { + 'operatingsystem' => 'Ubuntu', + 'operatingsystemrelease' => [ '15.999' ] + }, + { + 'operatingsystem' => 'Banana', + 'operatingsystemrelease' => [ '1.2', '2.3' ] + }, + ] + } + end - it 'should return false' do + it 'returns false' do is_expected.to run.with_params( module_metadata, - { 'release_match' => 'major' } + { 'release_match' => 'major' }, ).and_return(false) end end diff --git a/spec/functions/simplib/assert_optional_dependency_spec.rb b/spec/functions/simplib/assert_optional_dependency_spec.rb index 07c449f4..ff7fa305 100644 --- a/spec/functions/simplib/assert_optional_dependency_spec.rb +++ b/spec/functions/simplib/assert_optional_dependency_spec.rb @@ -3,7 +3,7 @@ describe 'simplib::assert_optional_dependency' do let(:func) { subject.func } - let(:source_metadata) { + let(:source_metadata) do { 'name' => 'my/module', 'version' => '1.2.3', @@ -19,50 +19,49 @@ { 'name' => 'dep-three', 'version_requirement' => '>= 1.2.3 < 2.0.0' - } + }, ] } } - } + end - let(:dep_one_metadata) { + let(:dep_one_metadata) do { 'name' => 'dep/one', 'version' => '1.0.0' } - } + end - let(:dep_two_metadata) { + let(:dep_two_metadata) do { 'name' => 'dep-two', 'version' => '3.4.5' } - } + end - let(:dep_three_metadata) { + let(:dep_three_metadata) do { 'name' => 'dep-three', 'version' => '1.2.3-alpha' } - } + end - let(:dep_one_bad_author) { + let(:dep_one_bad_author) do { 'name' => 'narp/one', 'version' => '1.0.0' } - } + end - let(:dep_one_bad_version) { + let(:dep_one_bad_version) do { 'name' => 'dep/one', 'version' => '5.5.5' } - } + end context 'with a source module' do - - it 'should run with no errors' do + it 'runs with no errors' do expect(func).to receive(:call_function).with('load_module_metadata', 'my/module').and_return(source_metadata) expect(func).to receive(:call_function).with('simplib::module_exist', 'one').and_return(true) expect(func).to receive(:call_function).with('load_module_metadata', 'one').and_return(dep_one_metadata) @@ -73,32 +72,32 @@ is_expected.to run.with_params('my/module') end - it 'should fail on one missing module' do + it 'fails on one missing module' do expect(func).to receive(:call_function).with('load_module_metadata', 'my/module').and_return(source_metadata) expect(func).to receive(:call_function).with('simplib::module_exist', 'one').and_return(true) expect(func).to receive(:call_function).with('load_module_metadata', 'one').and_return(dep_one_metadata) expect(func).to receive(:call_function).with('simplib::module_exist', 'two').and_return(false) - expect(func).to_not receive(:call_function).with('load_module_metadata', 'two') + expect(func).not_to receive(:call_function).with('load_module_metadata', 'two') - expect{ is_expected.to run.with_params('my/module') }.to raise_error(%r(optional dependency 'two' not found)m) + expect { is_expected.to run.with_params('my/module') }.to raise_error(%r{optional dependency 'two' not found}m) end - it 'should fail on all missing modules' do + it 'fails on all missing modules' do expect(func).to receive(:call_function).with('load_module_metadata', 'my/module').and_return(source_metadata) expect(func).to receive(:call_function).with('simplib::module_exist', 'one').and_return(false) - expect(func).to_not receive(:call_function).with('load_module_metadata', 'one') + expect(func).not_to receive(:call_function).with('load_module_metadata', 'one') expect(func).to receive(:call_function).with('simplib::module_exist', 'two').and_return(false) - expect(func).to_not receive(:call_function).with('load_module_metadata', 'two') + expect(func).not_to receive(:call_function).with('load_module_metadata', 'two') - expect{ is_expected.to run.with_params('my/module') }.to raise_error(%r(optional dependency 'one' not found.+optional dependency 'two' not found)m) + expect { is_expected.to run.with_params('my/module') }.to raise_error(%r{optional dependency 'one' not found.+optional dependency 'two' not found}m) end end context 'with a target module' do before(:each) do expect(func).to receive(:call_function).with('load_module_metadata', 'my/module').and_return(source_metadata) - expect(func).to_not receive(:call_function).with('simplib::module_exist', 'two') - expect(func).to_not receive(:call_function).with('load_module_metadata', 'two') + expect(func).not_to receive(:call_function).with('simplib::module_exist', 'two') + expect(func).not_to receive(:call_function).with('load_module_metadata', 'two') end context 'that exists' do @@ -116,7 +115,7 @@ end it 'hyphen name' do - is_expected.to run.with_params('my/module', 'dep/one') + is_expected.to run.with_params('my/module', 'dep-one') end it 'short name' do @@ -128,23 +127,22 @@ it 'author' do expect(func).to receive(:call_function).with('load_module_metadata', 'one').and_return(dep_one_bad_author) - expect{ is_expected.to run.with_params('my/module', 'dep/one') }.to raise_error(%r('dep/one' does not match 'narp/one')) + expect { is_expected.to run.with_params('my/module', 'dep/one') }.to raise_error(%r{'dep/one' does not match 'narp/one'}) end - end end context 'that is not in the metadata' do - it 'should fail' do - expect(func).to_not receive(:call_function).with('simplib::module_exist', 'one') + it 'fails' do + expect(func).not_to receive(:call_function).with('simplib::module_exist', 'one') - expect{is_expected.to run.with_params('my/module', 'badmod')}.to raise_error(%r('badmod' not found in metadata.json)) + expect { is_expected.to run.with_params('my/module', 'badmod') }.to raise_error(%r{'badmod' not found in metadata.json}) end end end context 'with an out of range module' do - it 'should fail on the invalid module' do + it 'fails on the invalid module' do expect(func).to receive(:call_function).with('load_module_metadata', 'my/module').and_return(source_metadata) expect(func).to receive(:call_function).with('simplib::module_exist', 'one').and_return(true) expect(func).to receive(:call_function).with('load_module_metadata', 'one').and_return(dep_one_bad_version) @@ -153,7 +151,7 @@ expect(func).to receive(:call_function).with('simplib::module_exist', 'three').and_return(true) expect(func).to receive(:call_function).with('load_module_metadata', 'three').and_return(dep_three_metadata) - expect{ is_expected.to run.with_params('my/module') }.to raise_error(%r('one-.+' does not satisfy)m) + expect { is_expected.to run.with_params('my/module') }.to raise_error(%r{'one-.+' does not satisfy}m) end end end diff --git a/spec/functions/simplib/bracketize_spec.rb b/spec/functions/simplib/bracketize_spec.rb old mode 100644 new mode 100755 index b9a4e8bd..f3fb2c8d --- a/spec/functions/simplib/bracketize_spec.rb +++ b/spec/functions/simplib/bracketize_spec.rb @@ -6,32 +6,32 @@ it 'converts an Array of networks' do input = [ '2001:0db8:85a3:0000:0000:8a2e:0370:7334', - '2001:0db8:85a3:0000:0000:8a2e:0370:7334/24' + '2001:0db8:85a3:0000:0000:8a2e:0370:7334/24', ] expected_output = [ '[2001:0db8:85a3:0000:0000:8a2e:0370:7334]', - '[2001:0db8:85a3:0000:0000:8a2e:0370:7334]/24' + '[2001:0db8:85a3:0000:0000:8a2e:0370:7334]/24', ] is_expected.to run.with_params(input).and_return(expected_output) input = '2001:0db8:85a3:0000:0000:8a2e:0370:7334 2001:0db8:85a3:0000:0000:8a2e:0370:7334/24' expected_output = [ '[2001:0db8:85a3:0000:0000:8a2e:0370:7334]', - '[2001:0db8:85a3:0000:0000:8a2e:0370:7334]/24' + '[2001:0db8:85a3:0000:0000:8a2e:0370:7334]/24', ] is_expected.to run.with_params(input).and_return(expected_output) input = '2001:0db8:85a3:0000:0000:8a2e:0370:7334, 2001:0db8:85a3:0000:0000:8a2e:0370:7334/24' expected_output = [ '[2001:0db8:85a3:0000:0000:8a2e:0370:7334]', - '[2001:0db8:85a3:0000:0000:8a2e:0370:7334]/24' + '[2001:0db8:85a3:0000:0000:8a2e:0370:7334]/24', ] is_expected.to run.with_params(input).and_return(expected_output) input = '2001:0db8:85a3:0000:0000:8a2e:0370:7334; 2001:0db8:85a3:0000:0000:8a2e:0370:7334/24' expected_output = [ '[2001:0db8:85a3:0000:0000:8a2e:0370:7334]', - '[2001:0db8:85a3:0000:0000:8a2e:0370:7334]/24' + '[2001:0db8:85a3:0000:0000:8a2e:0370:7334]/24', ] is_expected.to run.with_params(input).and_return(expected_output) @@ -40,7 +40,7 @@ '[2001:0db8:85a3:0000:0000:8a2e:0370:7334]', '[2001:0db8:85a3:0000:0000:8a2e:0370:7334]/24', '[3456:0db8:85a3:0000:0000:8a2e:0370:7334]', - '[1274:0db8:85a3:0000:0000:8a2e:0370:7334]' + '[1274:0db8:85a3:0000:0000:8a2e:0370:7334]', ] is_expected.to run.with_params(input).and_return(expected_output) end @@ -58,18 +58,18 @@ it 'returns same input if ipv6 is already in brackets' do input_string = [ '[2001:0db8:85a3:0000:0000:8a2e:0370:7334]', - '[2001:0db8:85a3:0000:0000:8a2e:0370:7334]/24' + '[2001:0db8:85a3:0000:0000:8a2e:0370:7334]/24', ] expected_output = [ '[2001:0db8:85a3:0000:0000:8a2e:0370:7334]', - '[2001:0db8:85a3:0000:0000:8a2e:0370:7334]/24' + '[2001:0db8:85a3:0000:0000:8a2e:0370:7334]/24', ] is_expected.to run.with_params(input_string).and_return(expected_output) input_string = '[2001:0db8:85a3:0000:0000:8a2e:0370:7334] [2001:0db8:85a3:0000:0000:8a2e:0370:7334]/24' expected_output = [ '[2001:0db8:85a3:0000:0000:8a2e:0370:7334]', - '[2001:0db8:85a3:0000:0000:8a2e:0370:7334]/24' + '[2001:0db8:85a3:0000:0000:8a2e:0370:7334]/24', ] is_expected.to run.with_params(input_string).and_return(expected_output) end @@ -80,7 +80,7 @@ 'still', 'correct', '[2001:0db8:85a3:0000:0000:8a2e:0370:7334]', - '127.0.0.1' + '127.0.0.1', ] is_expected.to run.with_params(input_string).and_return(expected_output) end diff --git a/spec/functions/simplib/debug/classtrace_spec.rb b/spec/functions/simplib/debug/classtrace_spec.rb index b1b4e37b..ac2fb59a 100644 --- a/spec/functions/simplib/debug/classtrace_spec.rb +++ b/spec/functions/simplib/debug/classtrace_spec.rb @@ -1,15 +1,17 @@ require 'spec_helper' describe 'simplib::debug::classtrace' do - let(:pre_condition) {%{ - class foo { simplib::debug::classtrace() } + let(:pre_condition) do + <<~END + class foo { simplib::debug::classtrace() } - define bar { include foo } + define bar { include foo } - class baz { bar { 'test': } } + class baz { bar { 'test': } } - include baz - }} + include baz + END + end it { expect(Puppet).to receive(:warning).with(%(Simplib::Debug::Classtrace:\n => Class[main]\n => Class[Baz]\n => Bar[test]\n => Class[Foo])).once diff --git a/spec/functions/simplib/debug/inspect_spec.rb b/spec/functions/simplib/debug/inspect_spec.rb index 17bdcc84..d46fb6ef 100644 --- a/spec/functions/simplib/debug/inspect_spec.rb +++ b/spec/functions/simplib/debug/inspect_spec.rb @@ -1,34 +1,38 @@ require 'spec_helper' describe 'simplib::debug::inspect' do - let(:pre_condition) {%{ - $foo = 'test_value' + let(:pre_condition) do + <<~END + $foo = 'test_value' - simplib::debug::inspect($foo) + simplib::debug::inspect($foo) - class test { - $bar = 'other value' + class test { + $bar = 'other value' - simplib::debug::inspect($bar) - } + simplib::debug::inspect($bar) + } - include 'test' - }} + include 'test' + END + end it { expect(Puppet).to receive(:warning).with(%(Simplib::Debug::Inspect: Type => 'String' Content => '"test_value"' Scope: 'Scope(Class[main])')) - expect(Puppet).to receive(:warning).with(%(Simplib::Debug::Inspect: Type => 'String' Content => '"other value"' Location: ':6' Scope: 'Scope(Class[Test])')) + expect(Puppet).to receive(:warning).with(%(Simplib::Debug::Inspect: Type => 'String' Content => '"other value"' Location: ':5' Scope: 'Scope(Class[Test])')) expect(Puppet).to receive(:warning).with(%(Simplib::Debug::Inspect: Type => 'String' Content => '"foo"' Scope: 'Scope(Class[main])')) retval = scope.call_function('simplib::debug::inspect', 'foo') - expect(retval).to eq({ - :type => String, - :content => '"foo"', - :module_name => '', - :scope => "Scope(Class[main])", - :file => nil, - :line => nil - }) + expect(retval).to eq( + { + type: String, + content: '"foo"', + module_name: '', + scope: 'Scope(Class[main])', + file: nil, + line: nil, + }, + ) } end diff --git a/spec/functions/simplib/debug/stacktrace_spec.rb b/spec/functions/simplib/debug/stacktrace_spec.rb index 5440cfe2..a84eb88c 100644 --- a/spec/functions/simplib/debug/stacktrace_spec.rb +++ b/spec/functions/simplib/debug/stacktrace_spec.rb @@ -1,18 +1,20 @@ require 'spec_helper' describe 'simplib::debug::stacktrace' do - let(:pre_condition) {%{ - class foo { simplib::debug::stacktrace() } + let(:pre_condition) do + <<~END + class foo { simplib::debug::stacktrace() } - define bar { include foo } + define bar { include foo } - class baz { bar { 'test': } } + class baz { bar { 'test': } } - include baz - }} + include baz + END + end it { - expect(Puppet).to receive(:warning).with(%(Simplib::Debug::Stacktrace:\n => unknown:2\n => unknown:4)) + expect(Puppet).to receive(:warning).with(%(Simplib::Debug::Stacktrace:\n => unknown:1\n => unknown:3)) retval = scope.call_function('simplib::debug::stacktrace', false) diff --git a/spec/functions/simplib/deprecation_spec.rb b/spec/functions/simplib/deprecation_spec.rb index 55f6cda6..9692f462 100644 --- a/spec/functions/simplib/deprecation_spec.rb +++ b/spec/functions/simplib/deprecation_spec.rb @@ -10,14 +10,14 @@ expect(ENV).to receive(:[]).with('SIMPLIB_NOLOG_DEPRECATIONS').and_return(nil) end - it 'should display a single warning' do - expect(Puppet).to receive(:warning).with(/test_func is deprecated/) + it 'displays a single warning' do + expect(Puppet).to receive(:warning).with(%r{test_func is deprecated}) is_expected.to run.with_params('test_key', 'test_func is deprecated') end - it 'should display a single warning, despite multiple calls' do - expect(Puppet).to receive(:warning).with(/test_func is deprecated/) + it 'displays a single warning, despite multiple calls' do + expect(Puppet).to receive(:warning).with(%r{test_func is deprecated}) is_expected.to run.with_params('test_key', 'test_func is deprecated') is_expected.to run.with_params('test_key', 'test_func is deprecated') @@ -25,9 +25,9 @@ end context 'with SIMPLIB_NOLOG_DEPRECATIONS=true' do - it 'should not display a warning' do + it 'does not display a warning' do expect(ENV).to receive(:[]).with('SIMPLIB_NOLOG_DEPRECATIONS').and_return('true') - expect(Puppet).to_not receive(:warning).with(/test_func is deprecated/) + expect(Puppet).not_to receive(:warning).with(%r{test_func is deprecated}) is_expected.to run.with_params('test_key', 'test_func is deprecated') end diff --git a/spec/functions/simplib/dlookup_spec.rb b/spec/functions/simplib/dlookup_spec.rb index c991e5b0..6ec8a6e7 100644 --- a/spec/functions/simplib/dlookup_spec.rb +++ b/spec/functions/simplib/dlookup_spec.rb @@ -2,36 +2,37 @@ # This just gives us a hook so that we can call the function later on describe 'simplib::stages', type: :class do + let(:pre_condition) do + <<~END + define mydef::test ( + $attribute = simplib::dlookup('mydef::test', 'attribute', $title, { 'default_value' => 'lucille2' }) + ) { + notify { "$title says": message => $attribute } + } - let(:pre_condition) {%( - define mydef::test ( - $attribute = simplib::dlookup('mydef::test', 'attribute', $title, { 'default_value' => 'lucille2' }) - ){ - notify { "$title says": message => $attribute } - } + define mydef::othertest ( + $attribute = simplib::dlookup('mydef::test', 'attribute', { 'default_value' => 'lucille2' }) + ) { + notify { "other $title says": message => $attribute } + } - define mydef::othertest ( - $attribute = simplib::dlookup('mydef::test', 'attribute', { 'default_value' => 'lucille2' }) - ){ - notify { "other $title says": message => $attribute } - } + mydef::test { 'gob': } + mydef::test { 'tobias': } + mydef::test { 'michael': attribute => 'bananastand' } - mydef::test { 'gob': } - mydef::test { 'tobias': } - mydef::test { 'michael': attribute => 'bananastand' } - - mydef::othertest { 'gob': } - mydef::othertest { 'tobias': } - mydef::othertest { 'michael': attribute => 'bananastand' } - )} + mydef::othertest { 'gob': } + mydef::othertest { 'tobias': } + mydef::othertest { 'michael': attribute => 'bananastand' } + END + end - let(:gob){catalogue.resource('Mydef::Test[gob]')} - let(:tobias){catalogue.resource('Mydef::Test[tobias]')} - let(:michael){catalogue.resource('Mydef::Test[michael]')} + let(:gob) { catalogue.resource('Mydef::Test[gob]') } + let(:tobias) { catalogue.resource('Mydef::Test[tobias]') } + let(:michael) { catalogue.resource('Mydef::Test[michael]') } - let(:gob_other){catalogue.resource('Mydef::Othertest[gob]')} - let(:tobias_other){catalogue.resource('Mydef::Othertest[tobias]')} - let(:michael_other){catalogue.resource('Mydef::Othertest[michael]')} + let(:gob_other) { catalogue.resource('Mydef::Othertest[gob]') } + let(:tobias_other) { catalogue.resource('Mydef::Othertest[tobias]') } + let(:michael_other) { catalogue.resource('Mydef::Othertest[michael]') } it { is_expected.to compile.with_all_deps } @@ -45,12 +46,14 @@ end context 'overrides' do - let(:facts){{ - :cache_bust => Time.now.to_s, - :hieradata => 'simplib_dlookup_overrides' - }} + let(:facts) do + { + cache_bust: Time.now.to_s, + hieradata: 'simplib_dlookup_overrides', + } + end - let(:hieradata){ 'simplib_dlookup_overrides' } + let(:hieradata) { 'simplib_dlookup_overrides' } context 'with global overrides' do it { expect(gob[:attribute]).to eq('illusions') } diff --git a/spec/functions/simplib/filtered_spec.rb b/spec/functions/simplib/filtered_spec.rb old mode 100644 new mode 100755 index a18728ff..31c12445 --- a/spec/functions/simplib/filtered_spec.rb +++ b/spec/functions/simplib/filtered_spec.rb @@ -3,75 +3,76 @@ require 'spec_helper' require 'semantic_puppet' puppetver = SemanticPuppet::Version.parse(Puppet.version) -requiredver = SemanticPuppet::Version.parse("4.9.0") -if (puppetver > requiredver) +requiredver = SemanticPuppet::Version.parse('4.9.0') +if puppetver > requiredver describe 'simplib::filtered' do shared_options = { - "function" => "simplib::mock_data", + 'function' => 'simplib::mock_data', } - context "using data_hash dispatch" do - it 'should run successfully' do - result = subject.execute(shared_options.dup.merge({"path" => "nofile"}), Puppet::Pops::Lookup::Context.new('rp_env', 'simplib')) + context 'using data_hash dispatch' do + it 'runs successfully' do + result = subject.execute(shared_options.dup.merge({ 'path' => 'nofile' }), Puppet::Pops::Lookup::Context.new('rp_env', 'simplib')) # rubocop:disable RSpec/NamedSubject expect(result).to eql({}) end { - "with no filters" => { - "all_results" => true, - "filter" => [], + 'with no filters' => { + 'all_results' => true, + 'filter' => [], }, - "with simple filter" => { - "all_results" => false, - "filter" => [ + 'with simple filter' => { + 'all_results' => false, + 'filter' => [ 'profiles::test2::variable', 'apache::sync', 'user::root_password', ], }, - "with regex filter" => { - "all_results" => false, - "filter" => [ + 'with regex filter' => { + 'all_results' => false, + 'filter' => [ '^profiles::test2::.*$', '^apache::.*$', '^user.*root_password$', ], }, }.each do |key, value| - context key do - { - "with path = 'nofile'" => { - "path" => "nofile", - "retval" => {}, - }, - "with path = '/path/1'" => { - "path" => "/path/1", - "retval" => {"profiles::test1::variable"=>"goodvar", "profiles::test2::variable"=>"badvar", "profiles::test::test1::variable"=>"goodvar", "apache::sync"=>"badvar", "user::root_password"=>"badvar"}, - }, - "with path = '/path/2'" => { - "path" => "/path/2", - "retval" => {"profiles::test1::variable"=>"goodvar", "profiles::test2::variable"=>"badvar", "profiles::test::test1::variable"=>"goodvar"}, - }, - }.each do |name, data| - context name do - if (value["all_results"] == true) - it 'should return all results' do - result = subject.execute(shared_options.dup.merge({"path" => data["path"], "filter" => value["filter"]}), Puppet::Pops::Lookup::Context.new('rp_env', 'simplib')) - expect(result).to eql(data["retval"]) - end - end - if (value["all_results"] == false) - it 'should not return all results' do - result = subject.execute(shared_options.dup.merge({"path" => data["path"], "filter" => value["filter"]}), Puppet::Pops::Lookup::Context.new('rp_env', 'simplib')) - if (data["retval"] == {}) - expect(result).to eql(data["retval"]) - else - expect(result).to_not eql(data["retval"]) - end - end - end + context key do + { + "with path = 'nofile'" => { + 'path' => 'nofile', + 'retval' => {}, + }, + "with path = '/path/1'" => { + 'path' => '/path/1', + 'retval' => { 'profiles::test1::variable' => 'goodvar', 'profiles::test2::variable' => 'badvar', 'profiles::test::test1::variable' => 'goodvar', 'apache::sync' => 'badvar', +'user::root_password' => 'badvar' }, + }, + "with path = '/path/2'" => { + 'path' => '/path/2', + 'retval' => { 'profiles::test1::variable' => 'goodvar', 'profiles::test2::variable' => 'badvar', 'profiles::test::test1::variable' => 'goodvar' }, + }, + }.each do |name, data| + context name do + if value['all_results'] == true + it 'returns all results' do + result = subject.execute(shared_options.dup.merge({ 'path' => data['path'], 'filter' => value['filter'] }), Puppet::Pops::Lookup::Context.new('rp_env', 'simplib')) # rubocop:disable RSpec/NamedSubject + expect(result).to eql(data['retval']) + end + end + if value['all_results'] == false + it 'does not return all results' do + result = subject.execute(shared_options.dup.merge({ 'path' => data['path'], 'filter' => value['filter'] }), Puppet::Pops::Lookup::Context.new('rp_env', 'simplib')) # rubocop:disable RSpec/NamedSubject + if data['retval'] == {} + expect(result).to eql(data['retval']) + else + expect(result).not_to eql(data['retval']) end end + end end end + end + end end end end diff --git a/spec/functions/simplib/gen_random_password_spec.rb b/spec/functions/simplib/gen_random_password_spec.rb old mode 100644 new mode 100755 index a1230708..e2d845a2 --- a/spec/functions/simplib/gen_random_password_spec.rb +++ b/spec/functions/simplib/gen_random_password_spec.rb @@ -3,60 +3,60 @@ describe 'simplib::gen_random_password' do let(:default_chars) do - (("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a).map do|x| - x = Regexp.escape(x) + (('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a).map do |x| + Regexp.escape(x) end end let(:safe_special_chars) do - ['@','%','-','_','+','=','~'].map do |x| - x = Regexp.escape(x) + ['@', '%', '-', '_', '+', '=', '~'].map do |x| + Regexp.escape(x) end end let(:unsafe_special_chars) do - (((' '..'/').to_a + ('['..'`').to_a + ('{'..'~').to_a)).map do |x| - x = Regexp.escape(x) - end - safe_special_chars + (((' '..'/').to_a + ('['..'`').to_a + ('{'..'~').to_a)).map { |x| + Regexp.escape(x) + } - safe_special_chars end let(:base64_regex) do '^[a-zA-Z0-9+/=]+$' end context 'successful password generation' do - it 'should run successfully with default arguments' do - result = subject.execute(16) - expect(result).to match(/^(#{default_chars.join('|')})+$/) + it 'runs successfully with default arguments' do + result = subject.execute(16) # rubocop:disable RSpec/NamedSubject + expect(result).to match(%r{^(#{default_chars.join('|')})+$}) end - it 'should return a password that contains "safe" special characters if complexity is 1' do - result = subject.execute(32, 1) - expect(result.length).to eql(32) - expect(result).to match(/(#{default_chars.join('|')})/) - expect(result).to match(/(#{(safe_special_chars).join('|')})/) - expect(result).not_to match(/(#{(unsafe_special_chars).join('|')})/) + it 'returns a password that contains "safe" special characters if complexity is 1' do + result = subject.execute(32, 1) # rubocop:disable RSpec/NamedSubject + expect(result.length).to be(32) + expect(result).to match(%r{(#{default_chars.join('|')})}) + expect(result).to match(%r{(#{safe_special_chars.join('|')})}) + expect(result).not_to match(%r{(#{unsafe_special_chars.join('|')})}) end - it 'should return a password that only contains "safe" special characters if complexity is 1 and complex_only is true' do - result = subject.execute(32, 1, true) - expect(result.length).to eql(32) - expect(result).not_to match(/(#{default_chars.join('|')})/) - expect(result).to match(/(#{(safe_special_chars).join('|')})/) - expect(result).not_to match(/(#{(unsafe_special_chars).join('|')})/) + it 'returns a password that only contains "safe" special characters if complexity is 1 and complex_only is true' do + result = subject.execute(32, 1, true) # rubocop:disable RSpec/NamedSubject + expect(result.length).to be(32) + expect(result).not_to match(%r{(#{default_chars.join('|')})}) + expect(result).to match(%r{(#{safe_special_chars.join('|')})}) + expect(result).not_to match(%r{(#{unsafe_special_chars.join('|')})}) end - it 'should return a password that contains all normal and special characters if complexity is 2' do - result = subject.execute(32, 2) - expect(result.length).to eql(32) - expect(result).to match(/(#{default_chars.join('|')})/) - expect(result).to match(/(#{(unsafe_special_chars).join('|')})/) + it 'returns a password that contains all normal and special characters if complexity is 2' do + result = subject.execute(32, 2) # rubocop:disable RSpec/NamedSubject + expect(result.length).to be(32) + expect(result).to match(%r{(#{default_chars.join('|')})}) + expect(result).to match(%r{(#{unsafe_special_chars.join('|')})}) end - it 'should return a password that only contains all special characters if complexity is 2 and complex_only is true' do - result = subject.execute(32, 2, true) - expect(result.length).to eql(32) - expect(result).to_not match(/(#{default_chars.join('|')})/) - expect(result).to match(/(#{(unsafe_special_chars).join('|')})/) + it 'returns a password that only contains all special characters if complexity is 2 and complex_only is true' do + result = subject.execute(32, 2, true) # rubocop:disable RSpec/NamedSubject + expect(result.length).to be(32) + expect(result).not_to match(%r{(#{default_chars.join('|')})}) + expect(result).to match(%r{(#{unsafe_special_chars.join('|')})}) end end diff --git a/spec/functions/simplib/host_is_me_spec.rb b/spec/functions/simplib/host_is_me_spec.rb old mode 100644 new mode 100755 index 8acecb2a..377a1668 --- a/spec/functions/simplib/host_is_me_spec.rb +++ b/spec/functions/simplib/host_is_me_spec.rb @@ -2,16 +2,17 @@ require 'spec_helper' describe 'simplib::host_is_me' do - context 'FQDN, hostname, and iterface facts exist' do - let(:facts) {{ - :fqdn => 'myhost.example.com', - :hostname => 'myhost', - :interfaces => 'eth0,eth1,lo', - :ipaddress_eth0 => '1.2.3.4', - :ipaddress_eth1 => '5.6.7.8', - :ipaddress_lo => '127.0.0.1' - }} + let(:facts) do + { + fqdn: 'myhost.example.com', + hostname: 'myhost', + interfaces: 'eth0,eth1,lo', + ipaddress_eth0: '1.2.3.4', + ipaddress_eth1: '5.6.7.8', + ipaddress_lo: '127.0.0.1', + } + end context "one of host's hostname/IPv4 addresses matches the argument" do [ @@ -40,9 +41,9 @@ end context 'FQDN, hostname, and iterface facts do not exist' do - let(:facts) {{ }} + let(:facts) { {} } - context "a localhost variant matches the argument" do + context 'a localhost variant matches the argument' do [ 'localhost', 'localhost.localdomain', diff --git a/spec/functions/simplib/inspect_spec.rb b/spec/functions/simplib/inspect_spec.rb index 22a38226..a09f02b1 100644 --- a/spec/functions/simplib/inspect_spec.rb +++ b/spec/functions/simplib/inspect_spec.rb @@ -6,49 +6,55 @@ describe 'simplib::inspect' do context 'when default output_type is used' do - let(:pre_condition) {%{ - $foo = 'test_value' - }} + let(:pre_condition) do + <<~END + $foo = 'test_value' + END + end it { is_expected.to run.with_params('foo') expect(catalogue.resource('Notify[DEBUG_INSPECT_foo]')).not_to be_nil resource = catalogue.resource('Notify[DEBUG_INSPECT_foo]') - expected_msg = < String -Content => -"test_value" -EOM + expected_msg = <<~EOM + Type => String + Content => + "test_value" + EOM expect(resource[:message]).to eq expected_msg.chomp } end context 'when yaml output_type is used' do - let(:pre_condition) {%{ - $foo = ['a', {'b' => 'c'} ] - }} + let(:pre_condition) do + <<~END + $foo = ['a', {'b' => 'c'} ] + END + end it { is_expected.to run.with_params('foo', 'yaml') resource = catalogue.resource('Notify[DEBUG_INSPECT_foo]') - expected_msg= < Array -Content => ---- -- a -- b: c -EOM + expected_msg = <<~EOM + Type => Array + Content => + --- + - a + - b: c + EOM expect(resource[:message]).to eq expected_msg } end context 'when oneline_json output_type is used' do - let(:pre_condition) {%{ - $foo = ['a', {'b' => 'c'} ] - }} + let(:pre_condition) do + <<~END + $foo = ['a', {'b' => 'c'} ] + END + end it { is_expected.to run.with_params('foo', 'oneline_json') diff --git a/spec/functions/simplib/ip/family_hash_spec.rb b/spec/functions/simplib/ip/family_hash_spec.rb old mode 100644 new mode 100755 index 231ec977..c13e0b11 --- a/spec/functions/simplib/ip/family_hash_spec.rb +++ b/spec/functions/simplib/ip/family_hash_spec.rb @@ -9,10 +9,10 @@ '3.4.5.0/255.255.255.0', '2001:0db8:85a3:0000:0000:8a2e:0370:7334', '[2001:0db8:85a3:0000:0000:8a2e:0370:7334]', - '2001:0db8:85a3:0000:0000:8a2e:0370:7334/24' + '2001:0db8:85a3:0000:0000:8a2e:0370:7334/24', ] - output ={ + output = { 'ipv4' => { '1.2.3.4/24' => { 'address' => '1.2.3.0', @@ -104,7 +104,7 @@ input = [ '1.2.3.4', '2001:0db8:85a3:0000:0000:8a2e:0370:7334/24', - 'bob.the.builder' + 'bob.the.builder', ] output = { diff --git a/spec/functions/simplib/ip_to_cron_spec.rb b/spec/functions/simplib/ip_to_cron_spec.rb old mode 100644 new mode 100755 index e5df389a..55cda0c3 --- a/spec/functions/simplib/ip_to_cron_spec.rb +++ b/spec/functions/simplib/ip_to_cron_spec.rb @@ -2,33 +2,33 @@ require 'spec_helper' describe 'simplib::ip_to_cron' do - let(:facts) {{ :ipaddress => '10.0.10.154' }} + let(:facts) { { ipaddress: '10.0.10.154' } } context 'with default parameters' do - it { is_expected.to run.with_params().and_return([54]) } + it { is_expected.to run.with_params.and_return([54]) } end context 'occurs specified' do - it { is_expected.to run.with_params(2).and_return([24,54]) } + it { is_expected.to run.with_params(2).and_return([24, 54]) } end context 'occurs and max_value specified' do - it { is_expected.to run.with_params(2,23).and_return([6,18]) } + it { is_expected.to run.with_params(2, 23).and_return([6, 18]) } end context 'occurs, max_value, and algorithm specified' do - it { is_expected.to run.with_params(2,23,'sha256').and_return([5,17]) } + it { is_expected.to run.with_params(2, 23, 'sha256').and_return([5, 17]) } end context 'occurs, max_value, algorithm, and IPv4 specified' do - it { is_expected.to run.with_params(2,23,'sha256', '10.0.20.35').and_return([4,16]) } + it { is_expected.to run.with_params(2, 23, 'sha256', '10.0.20.35').and_return([4, 16]) } end context 'occurs, max_value, algorithm, and IPv6 specified' do - it { is_expected.to run.with_params(2,23,'sha256','2001:0db8:85a3:0000:0000:8a2e:0370:7395').and_return([6,18]) } + it { is_expected.to run.with_params(2, 23, 'sha256', '2001:0db8:85a3:0000:0000:8a2e:0370:7395').and_return([6, 18]) } end context 'invalid ip specified' do - it { is_expected.to run.with_params(2,23,'sha256', '300.0.20.35').and_raise_error(ArgumentError) } + it { is_expected.to run.with_params(2, 23, 'sha256', '300.0.20.35').and_raise_error(ArgumentError) } end end diff --git a/spec/functions/simplib/ipaddresses_spec.rb b/spec/functions/simplib/ipaddresses_spec.rb old mode 100644 new mode 100755 index e508386e..778f497a --- a/spec/functions/simplib/ipaddresses_spec.rb +++ b/spec/functions/simplib/ipaddresses_spec.rb @@ -3,50 +3,52 @@ describe 'simplib::ipaddresses' do shared_examples_for 'a host' do - before(:each) do - @result = subject.execute - end + let(:result) { subject.execute } - it 'should return an Array' do - expect(@result.is_a?(Array)).to be true + it 'returns an Array' do + expect(result.is_a?(Array)).to be true end - it 'should return an Array with no nil values' do - expect(@result.include?(nil)).to_not be true + it 'returns an Array with no nil values' do + expect(result.include?(nil)).not_to be true end - it 'should return an Array with no empty values' do - expect(@result.include?(/^(\S*)$/)).to_not be true + it 'returns an Array with no empty values' do + expect(result.include?(%r{^(\S*)$})).not_to be true end end # Mock out the Facts - context "All Interfaces Have IP Addresses" do - let(:facts) {{ - :interfaces => 'eth0,eth1,lo', - :ipaddress_eth0 => '1.2.3.4', - :ipaddress_eth1 => '5.6.7.8', - :ipaddress_lo => '127.0.0.1' - }} + context 'All Interfaces Have IP Addresses' do + let(:facts) do + { + interfaces: 'eth0,eth1,lo', + ipaddress_eth0: '1.2.3.4', + ipaddress_eth1: '5.6.7.8', + ipaddress_lo: '127.0.0.1', + } + end it_behaves_like 'a host' end - context "All Interfaces Do Not Have IP Addresses" do - let(:facts) {{ - :interfaces => 'eth0,eth1,lo', - :ipaddress_eth0 => '1.2.3.4', - :ipaddress_lo => '127.0.0.1' - }} + context 'All Interfaces Do Not Have IP Addresses' do + let(:facts) do + { + interfaces: 'eth0,eth1,lo', + ipaddress_eth0: '1.2.3.4', + ipaddress_lo: '127.0.0.1', + } + end it_behaves_like 'a host' end - context "The system has no interfaces" do - let(:facts) {{ }} + context 'The system has no interfaces' do + let(:facts) { {} } - it 'should not raise an error' do - expect{ subject.execute }.to_not raise_error + it 'does not raise an error' do + expect { subject.execute }.not_to raise_error # rubocop:disable RSpec/NamedSubject end end end diff --git a/spec/functions/simplib/join_mount_opts_spec.rb b/spec/functions/simplib/join_mount_opts_spec.rb old mode 100644 new mode 100755 index 67a278d3..3e469975 --- a/spec/functions/simplib/join_mount_opts_spec.rb +++ b/spec/functions/simplib/join_mount_opts_spec.rb @@ -2,16 +2,16 @@ require 'spec_helper' describe 'simplib::join_mount_opts' do -# "tmp_mount_dev_shm": "rw,seclabel,nosuid,nodev,noexec,relatime" -# "tmp_mount_tmp": "rw,seclabel,nosuid,nodev,noexec,relatime,attr2,inode64,noquota" -# "tmp_mount_var_tmp": "rw,seclabel,nosuid,nodev,noexec,relatime,attr2,inode64,noquota" + # "tmp_mount_dev_shm": "rw,seclabel,nosuid,nodev,noexec,relatime" + # "tmp_mount_tmp": "rw,seclabel,nosuid,nodev,noexec,relatime,attr2,inode64,noquota" + # "tmp_mount_var_tmp": "rw,seclabel,nosuid,nodev,noexec,relatime,attr2,inode64,noquota" context 'without selinux mount options specified' do - let(:facts) {{ :selinux_current_mode => 'enforcing' }} + let(:facts) { { selinux_current_mode: 'enforcing' } } context 'with no mount options overlap' do it 'concatenates system and new options' do sys_opts = ['bind'] - new_opts = ['noexec','nodev','nosuid'] + new_opts = ['noexec', 'nodev', 'nosuid'] exp_out = 'bind,nodev,noexec,nosuid' is_expected.to run.with_params(sys_opts, new_opts).and_return(exp_out) end @@ -26,7 +26,7 @@ end it "removes 'no