diff --git a/.rubocop.yml b/.rubocop.yml index 547737a..c2a2c07 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,34 +1,8 @@ --- inherit_from: .rubocop_todo.yml -require: -- rubocop-performance -- rubocop-rake -- rubocop-rspec - -AllCops: - NewCops: enable - TargetRubyVersion: '2.7' - Exclude: - - vendor/**/* - -Style/TrailingCommaInHashLiteral: - Enabled: True - EnforcedStyleForMultiline: consistent_comma - -Style/TrailingCommaInArrayLiteral: - Enabled: True - EnforcedStyleForMultiline: consistent_comma - -Style/TrailingCommaInArguments: - Enabled: True - EnforcedStyleForMultiline: comma +inherit_gem: + voxpupuli-rubocop: rubocop.yml Metrics: Enabled: false - -Style: - Enabled: false - -Layout: - Enabled: false diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 5433c4f..f705c6d 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -1,20 +1,12 @@ # This configuration was generated by # `rubocop --auto-gen-config` -# on 2023-03-15 20:57:21 UTC using RuboCop version 1.12.1. +# on 2023-07-07 07:29:59 UTC using RuboCop version 1.50.2. # The point is for the user to remove these configuration records # one by one as the offenses are removed from the code base. # Note that changes in the inspected code, or installation of new # versions of RuboCop, may require this file to be generated again. -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: TreatCommentsAsGroupSeparators, ConsiderPunctuation, Include. -# Include: **/*.gemspec -Gemspec/OrderedDependencies: - Exclude: - - 'puppet-syntax.gemspec' - -# Offense count: 1 +# Offense count: 2 # Configuration parameters: IgnoreLiteralBranches, IgnoreConstantBranches. Lint/DuplicateBranch: Exclude: @@ -25,12 +17,6 @@ Lint/MissingSuper: Exclude: - 'lib/puppet-syntax/tasks/puppet-syntax.rb' -# Offense count: 1 -# Cop supports --auto-correct. -Lint/ParenthesesAsGroupedExpression: - Exclude: - - 'spec/puppet-syntax/manifests_spec.rb' - # Offense count: 1 Lint/RescueException: Exclude: @@ -42,27 +28,14 @@ Lint/SuppressedException: Exclude: - 'Rakefile' -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: IgnoreEmptyBlocks, AllowUnusedKeywordArguments. -Lint/UnusedBlockArgument: - Exclude: - - 'lib/puppet-syntax/templates.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: AllowUnusedKeywordArguments, IgnoreEmptyMethods, IgnoreNotImplementedMethods. -Lint/UnusedMethodArgument: - Exclude: - - 'lib/puppet-syntax/tasks/puppet-syntax.rb' - # Offense count: 1 Lint/UselessAssignment: Exclude: - 'lib/puppet-syntax/templates.rb' # Offense count: 4 -# Configuration parameters: ExpectMatchingDefinition, CheckDefinitionPathHierarchy, Regex, IgnoreExecutableScripts, AllowedAcronyms. +# Configuration parameters: ExpectMatchingDefinition, CheckDefinitionPathHierarchy, CheckDefinitionPathHierarchyRoots, Regex, IgnoreExecutableScripts, AllowedAcronyms. +# CheckDefinitionPathHierarchyRoots: lib, spec, test, src # AllowedAcronyms: CLI, DSL, ACL, API, ASCII, CPU, CSS, DNS, EOF, GUID, HTML, HTTP, HTTPS, ID, IP, JSON, LHS, QPS, RAM, RHS, RPC, SLA, SMTP, SQL, SSH, TCP, TLS, TTL, UDP, UI, UID, UUID, URI, URL, UTF8, VM, XML, XMPP, XSRF, XSS Naming/FileName: Exclude: @@ -71,31 +44,15 @@ Naming/FileName: - 'spec/puppet-syntax/tasks/puppet-syntax_spec.rb' - 'spec/puppet-syntax_spec.rb' -# Offense count: 6 -# Cop supports --auto-correct. -# Configuration parameters: PreferredName. -Naming/RescuedExceptionsVariableName: - Exclude: - - 'lib/puppet-syntax/hiera.rb' - - 'lib/puppet-syntax/manifests.rb' - - 'lib/puppet-syntax/templates.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -Performance/RedundantSplitRegexpArgument: +# Offense count: 11 +# This cop supports unsafe autocorrection (--autocorrect-all). +RSpec/BeEq: Exclude: - - 'lib/puppet-syntax/hiera.rb' - -# Offense count: 7 -# Cop supports --auto-correct. -Performance/RegexpMatch: - Exclude: - - 'Rakefile' - - 'lib/puppet-syntax/hiera.rb' - - 'spec/puppet-syntax/hiera_spec.rb' + - 'spec/puppet-syntax/manifests_spec.rb' + - 'spec/puppet-syntax_spec.rb' # Offense count: 1 -# Configuration parameters: Prefixes. +# Configuration parameters: Prefixes, AllowedPatterns. # Prefixes: when, with, without RSpec/ContextWording: Exclude: @@ -105,10 +62,15 @@ RSpec/ContextWording: # Configuration parameters: IgnoredMetadata. RSpec/DescribeClass: Exclude: + - '**/spec/features/**/*' + - '**/spec/requests/**/*' + - '**/spec/routing/**/*' + - '**/spec/system/**/*' + - '**/spec/views/**/*' - 'spec/puppet-syntax/tasks/puppet-syntax_spec.rb' # Offense count: 19 -# Cop supports --auto-correct. +# This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: SkipBlocks, EnforcedStyle. # SupportedStyles: described_class, explicit RSpec/DescribedClass: @@ -118,22 +80,11 @@ RSpec/DescribedClass: - 'spec/puppet-syntax/templates_spec.rb' - 'spec/puppet-syntax_spec.rb' -# Offense count: 8 +# Offense count: 7 # Configuration parameters: CountAsOne. RSpec/ExampleLength: Max: 14 -# Offense count: 40 -# Cop supports --auto-correct. -# Configuration parameters: CustomTransform, IgnoredWords. -RSpec/ExampleWording: - Exclude: - - 'spec/puppet-syntax/hiera_spec.rb' - - 'spec/puppet-syntax/manifests_spec.rb' - - 'spec/puppet-syntax/tasks/puppet-syntax_spec.rb' - - 'spec/puppet-syntax/templates_spec.rb' - - 'spec/puppet-syntax_spec.rb' - # Offense count: 4 # Configuration parameters: Include, CustomTransform, IgnoreMethods, SpecSuffixOnly. # Include: **/*_spec*rb*, **/spec/**/* @@ -144,21 +95,13 @@ RSpec/FilePath: - 'spec/puppet-syntax/templates_spec.rb' - 'spec/puppet-syntax_spec.rb' -# Offense count: 2 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: implicit, each, example -RSpec/HookArgument: - Exclude: - - 'spec/puppet-syntax/hiera_spec.rb' - - 'spec/puppet-syntax/templates_spec.rb' - # Offense count: 29 RSpec/MultipleExpectations: Max: 8 # Offense count: 30 -# Configuration parameters: IgnoreSharedExamples. +# Configuration parameters: EnforcedStyle, IgnoreSharedExamples. +# SupportedStyles: always, named_only RSpec/NamedSubject: Exclude: - 'spec/puppet-syntax/hiera_spec.rb' @@ -170,8 +113,127 @@ RSpec/RepeatedDescription: Exclude: - 'spec/puppet-syntax/templates_spec.rb' +# Offense count: 3 +RSpec/SubjectDeclaration: + Exclude: + - 'spec/puppet-syntax/hiera_spec.rb' + - 'spec/puppet-syntax/manifests_spec.rb' + - 'spec/puppet-syntax/templates_spec.rb' + # Offense count: 1 -# Cop supports --auto-correct. +# This cop supports safe autocorrection (--autocorrect). Rake/Desc: Exclude: - 'Rakefile' + +# Offense count: 2 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: always, conditionals +Style/AndOr: + Exclude: + - 'lib/puppet-syntax/manifests.rb' + - 'lib/puppet-syntax/templates.rb' + +# Offense count: 1 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: MinBranchesCount. +Style/CaseLikeIf: + Exclude: + - 'lib/puppet-syntax/hiera.rb' + +# Offense count: 5 +# Configuration parameters: AllowedConstants. +Style/Documentation: + Exclude: + - 'spec/**/*' + - 'test/**/*' + - 'lib/puppet-syntax.rb' + - 'lib/puppet-syntax/hiera.rb' + - 'lib/puppet-syntax/manifests.rb' + - 'lib/puppet-syntax/tasks/puppet-syntax.rb' + - 'lib/puppet-syntax/templates.rb' + +# Offense count: 15 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: always, always_true, never +Style/FrozenStringLiteralComment: + Exclude: + - 'Gemfile' + - 'Rakefile' + - 'lib/puppet-syntax.rb' + - 'lib/puppet-syntax/hiera.rb' + - 'lib/puppet-syntax/manifests.rb' + - 'lib/puppet-syntax/tasks/puppet-syntax.rb' + - 'lib/puppet-syntax/templates.rb' + - 'lib/puppet-syntax/version.rb' + - 'puppet-syntax.gemspec' + - 'spec/puppet-syntax/hiera_spec.rb' + - 'spec/puppet-syntax/manifests_spec.rb' + - 'spec/puppet-syntax/tasks/puppet-syntax_spec.rb' + - 'spec/puppet-syntax/templates_spec.rb' + - 'spec/puppet-syntax_spec.rb' + - 'spec/spec_helper.rb' + +# Offense count: 2 +# This cop supports unsafe autocorrection (--autocorrect-all). +Style/IdenticalConditionalBranches: + Exclude: + - 'lib/puppet-syntax/templates.rb' + +# Offense count: 1 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: literals, strict +Style/MutableConstant: + Exclude: + - 'lib/puppet-syntax/version.rb' + +# Offense count: 1 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: EnforcedStyle, AllowedMethods, AllowedPatterns. +# SupportedStyles: predicate, comparison +Style/NumericPredicate: + Exclude: + - 'spec/**/*' + - 'lib/puppet-syntax/hiera.rb' + +# Offense count: 1 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle, AllowInnerSlashes. +# SupportedStyles: slashes, percent_r, mixed +Style/RegexpLiteral: + Exclude: + - 'spec/puppet-syntax/templates_spec.rb' + +# Offense count: 1 +# This cop supports unsafe autocorrection (--autocorrect-all). +Style/SelectByRegexp: + Exclude: + - 'lib/puppet-syntax/manifests.rb' + +# Offense count: 1 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: RequireEnglish, EnforcedStyle. +# SupportedStyles: use_perl_names, use_english_names, use_builtin_english_names +Style/SpecialGlobalVars: + Exclude: + - 'puppet-syntax.gemspec' + +# Offense count: 4 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: AllowMethodsWithArguments, AllowedMethods, AllowedPatterns, AllowComments. +# AllowedMethods: define_method +Style/SymbolProc: + Exclude: + - 'lib/puppet-syntax/hiera.rb' + - 'lib/puppet-syntax/manifests.rb' + - 'lib/puppet-syntax/templates.rb' + +# Offense count: 3 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, AllowedPatterns. +# URISchemes: http, https +Layout/LineLength: + Max: 211 diff --git a/Gemfile b/Gemfile index 955b39e..3af6bbd 100644 --- a/Gemfile +++ b/Gemfile @@ -6,11 +6,11 @@ source 'https://rubygems.org' # is specified as `file://some/location/on/disk`. def location_for(place_or_version, fake_version = nil) if place_or_version =~ /^(https[:@][^#]*)#(.*)/ - [fake_version, { :git => $1, :branch => $2, :require => false }].compact - elsif place_or_version =~ /^file:\/\/(.*)/ - ['>= 0', { :path => File.expand_path($1), :require => false }] + [fake_version, { git: Regexp.last_match(1), branch: Regexp.last_match(2), require: false }].compact + elsif place_or_version =~ %r{^file://(.*)} + ['>= 0', { path: File.expand_path(Regexp.last_match(1)), require: false }] else - [place_or_version, { :require => false }] + [place_or_version, { require: false }] end end diff --git a/Rakefile b/Rakefile index fe86167..377af0d 100644 --- a/Rakefile +++ b/Rakefile @@ -7,15 +7,15 @@ task :publish_gem do puts "Published #{gem}" if gem end -task :default => [:spec] +task default: [:spec] begin require 'github_changelog_generator/task' require 'puppet-syntax/version' GitHubChangelogGenerator::RakeTask.new :changelog do |config| version = PuppetSyntax::VERSION - config.future_release = "v#{version}" if version =~ /^\d+\.\d+.\d+$/ + config.future_release = "v#{version}" if /^\d+\.\d+.\d+$/.match?(version) config.header = "# Changelog\n\nAll notable changes to this project will be documented in this file." - config.exclude_labels = %w{duplicate question invalid wontfix wont-fix modulesync skip-changelog} + config.exclude_labels = %w[duplicate question invalid wontfix wont-fix modulesync skip-changelog] config.user = 'voxpupuli' config.project = 'puppet-syntax' end diff --git a/lib/puppet-syntax.rb b/lib/puppet-syntax.rb index 9e70ba4..8b352da 100644 --- a/lib/puppet-syntax.rb +++ b/lib/puppet-syntax.rb @@ -1,4 +1,4 @@ -require "puppet-syntax/version" +require 'puppet-syntax/version' module PuppetSyntax autoload :Hiera, 'puppet-syntax/hiera' @@ -7,9 +7,9 @@ module PuppetSyntax @exclude_paths = [] @hieradata_paths = [ - "**/data/**/*.*{yaml,yml}", - "hieradata/**/*.*{yaml,yml}", - "hiera*.*{yaml,yml}", + '**/data/**/*.*{yaml,yml}', + 'hieradata/**/*.*{yaml,yml}', + 'hiera*.*{yaml,yml}', ] @manifests_paths = [ '**/*.pp', diff --git a/lib/puppet-syntax/hiera.rb b/lib/puppet-syntax/hiera.rb index 12dc8a6..50400e2 100644 --- a/lib/puppet-syntax/hiera.rb +++ b/lib/puppet-syntax/hiera.rb @@ -6,17 +6,17 @@ class Hiera def check_hiera_key(key) if key.is_a? Symbol if key.to_s.start_with?(':') - return "Puppet automatic lookup will not use leading '::'" - elsif key !~ /^[a-z]+$/ # we allow Hiera's own configuration - return "Puppet automatic lookup will not look up symbols" - end - elsif key !~ /^[a-z][a-z0-9_]+(::[a-z][a-z0-9_]+)*$/ - if key =~ /[^:]:[^:]/ - # be extra helpful - return "Looks like a missing colon" - else - return "Not a valid Puppet variable name for automatic lookup" + "Puppet automatic lookup will not use leading '::'" + elsif !/^[a-z]+$/.match?(key) # we allow Hiera's own configuration + 'Puppet automatic lookup will not look up symbols' end + elsif !/^[a-z][a-z0-9_]+(::[a-z][a-z0-9_]+)*$/.match?(key) + return 'Looks like a missing colon' if /[^:]:[^:]/.match?(key) + + # be extra helpful + + 'Not a valid Puppet variable name for automatic lookup' + end end @@ -41,34 +41,32 @@ def check_eyaml_data(name, val) end def check_eyaml_blob(val) - return unless val =~ /^ENC\[/ + return unless /^ENC\[/.match?(val) val.sub!('ENC[', '') val.gsub!(/\s+/, '') - if val !~ /\]$/ - return "has unterminated eyaml value" - else - val.sub!(/\]$/, '') - method, base64 = val.split(/,/) - if base64 == nil - base64 = method - method = 'PKCS7' - end - - return "has unknown eyaml method #{method}" unless ['PKCS7', 'GPG', 'GKMS', 'KMS'].include? method - return "has unpadded or truncated base64 data" unless base64.length % 4 == 0 + return 'has unterminated eyaml value' unless /\]$/.match?(val) - # Base64#decode64 will silently ignore characters outside the alphabet, - # so we check resulting length of binary data instead - pad_length = base64.gsub(/[^=]/, '').length - if Base64.decode64(base64).length != base64.length * 3 / 4 - pad_length - return "has corrupt base64 data" - end + val.sub!(/\]$/, '') + method, base64 = val.split(',') + if base64.nil? + base64 = method + method = 'PKCS7' end + + return "has unknown eyaml method #{method}" unless %w[PKCS7 GPG GKMS KMS].include? method + return 'has unpadded or truncated base64 data' unless base64.length % 4 == 0 + + # Base64#decode64 will silently ignore characters outside the alphabet, + # so we check resulting length of binary data instead + pad_length = base64.gsub(/[^=]/, '').length + return unless Base64.decode64(base64).length != (base64.length * 3 / 4) - pad_length + + 'has corrupt base64 data' end def check(filelist) - raise "Expected an array of files" unless filelist.is_a?(Array) + raise 'Expected an array of files' unless filelist.is_a?(Array) errors = [] @@ -77,19 +75,19 @@ def check(filelist) filelist.each do |hiera_file| begin yamldata = YAML.load_file(hiera_file, **yamlargs) - rescue Exception => error - errors << "ERROR: Failed to parse #{hiera_file}: #{error}" + rescue Exception => e + errors << "ERROR: Failed to parse #{hiera_file}: #{e}" next end - if yamldata - yamldata.each do |k, v| - if PuppetSyntax.check_hiera_keys - key_msg = check_hiera_key(k) - errors << "WARNING: #{hiera_file}: Key :#{k}: #{key_msg}" if key_msg - end - eyaml_msg = check_eyaml_data(k, v) - errors << "WARNING: #{hiera_file}: #{eyaml_msg}" if eyaml_msg + next unless yamldata + + yamldata.each do |k, v| + if PuppetSyntax.check_hiera_keys + key_msg = check_hiera_key(k) + errors << "WARNING: #{hiera_file}: Key :#{k}: #{key_msg}" if key_msg end + eyaml_msg = check_eyaml_data(k, v) + errors << "WARNING: #{hiera_file}: #{eyaml_msg}" if eyaml_msg end end diff --git a/lib/puppet-syntax/manifests.rb b/lib/puppet-syntax/manifests.rb index 162d9a7..1b22cce 100644 --- a/lib/puppet-syntax/manifests.rb +++ b/lib/puppet-syntax/manifests.rb @@ -1,7 +1,7 @@ module PuppetSyntax class Manifests def check(filelist) - raise "Expected an array of files" unless filelist.is_a?(Array) + raise 'Expected an array of files' unless filelist.is_a?(Array) require 'puppet' require 'puppet/version' @@ -22,14 +22,12 @@ def check(filelist) Puppet::Test::TestHelper.before_each_test begin error = validate_manifest(puppet_file) - if error.is_a?(Hash) # Puppet 6.5.0 onwards - output << error.values.first unless error.empty? - end + output << error.values.first if error.is_a?(Hash) && !error.empty? # Puppet 6.5.0 onwards rescue SystemExit # Disregard exit(1) from face. # This is how puppet < 6.5.0 `validate_manifest` worked. - rescue => error - output << error + rescue StandardError => e + output << e ensure Puppet::Test::TestHelper.after_each_test end @@ -39,23 +37,23 @@ def check(filelist) output.map! { |e| e.to_s } # Exported resources will raise warnings when outside a puppetmaster. - output.reject! { |e| + output.reject! do |e| e =~ /^You cannot collect( exported resources)? without storeconfigs being set/ - } + end # tag and schedule parameters in class raise warnings notice in output that prevent from succeed - output.reject! { |e| + output.reject! do |e| e =~ /^(tag|schedule) is a metaparam; this value will inherit to all contained resources in the / - } + end - deprecations = output.select { |e| + deprecations = output.select do |e| e =~ /^Deprecation notice:|is deprecated/ - } + end # Errors exist if there is any output that isn't a deprecation notice. has_errors = (output != deprecations) - return output, has_errors + [output, has_errors] ensure Puppet::Test::TestHelper.after_all_tests if called_before_all_tests end @@ -63,7 +61,7 @@ def check(filelist) private def validate_manifest(file) - Puppet[:tasks] = true if Puppet::Util::Package.versioncmp(Puppet.version, '5.4.0') >= 0 and file.match(/.*plans\/.*\.pp$/) + Puppet[:tasks] = true if Puppet::Util::Package.versioncmp(Puppet.version, '5.4.0') >= 0 and file.match(%r{.*plans/.*\.pp$}) Puppet::Face[:parser, :current].validate(file) end end diff --git a/lib/puppet-syntax/tasks/puppet-syntax.rb b/lib/puppet-syntax/tasks/puppet-syntax.rb index 2f5f45f..337e850 100644 --- a/lib/puppet-syntax/tasks/puppet-syntax.rb +++ b/lib/puppet-syntax/tasks/puppet-syntax.rb @@ -25,9 +25,9 @@ def filelist_hiera_yaml filelist(PuppetSyntax.hieradata_paths) end - def initialize(*args) + def initialize(*_args) desc 'Syntax check Puppet manifests and templates' - task :syntax => [ + task syntax: [ 'syntax:manifests', 'syntax:templates', 'syntax:hiera', @@ -36,7 +36,7 @@ def initialize(*args) namespace :syntax do desc 'Syntax check Puppet manifests' task :manifests do |t| - $stderr.puts "---> #{t.name}" + warn "---> #{t.name}" c = PuppetSyntax::Manifests.new output, has_errors = c.check(filelist_manifests) @@ -46,29 +46,29 @@ def initialize(*args) desc 'Syntax check Puppet templates' task :templates do |t| - $stderr.puts "---> #{t.name}" + warn "---> #{t.name}" c = PuppetSyntax::Templates.new result = c.check(filelist_templates) unless result[:warnings].empty? - $stdout.puts "WARNINGS:" + $stdout.puts 'WARNINGS:' $stdout.puts result[:warnings].join("\n") end unless result[:errors].empty? - $stderr.puts "ERRORS:" - $stderr.puts result[:errors].join("\n") + warn 'ERRORS:' + warn result[:errors].join("\n") exit 1 end end desc 'Syntax check Hiera config files' - task :hiera => [ + task hiera: [ 'syntax:hiera:yaml', ] namespace :hiera do task :yaml do |t| - $stderr.puts "---> #{t.name}" + warn "---> #{t.name}" c = PuppetSyntax::Hiera.new errors = c.check(filelist_hiera_yaml) $stdout.puts "#{errors.join("\n")}\n" unless errors.empty? diff --git a/lib/puppet-syntax/templates.rb b/lib/puppet-syntax/templates.rb index 8e840bd..a12fbee 100644 --- a/lib/puppet-syntax/templates.rb +++ b/lib/puppet-syntax/templates.rb @@ -4,10 +4,10 @@ module PuppetSyntax class Templates def check(filelist) - raise "Expected an array of files" unless filelist.is_a?(Array) + raise 'Expected an array of files' unless filelist.is_a?(Array) # We now have to redirect STDERR in order to capture warnings. - $stderr = warnings = StringIO.new() + $stderr = warnings = StringIO.new result = { warnings: [], errors: [] } filelist.each do |file| @@ -16,7 +16,7 @@ def check(filelist) elsif File.extname(file) == '.erb' tmp = validate_erb(file) end - result.merge!(tmp) { |k, a, b| a.concat(b) } unless tmp.nil? + result.merge!(tmp) { |_k, a, b| a.concat(b) } unless tmp.nil? end $stderr = STDERR @@ -33,8 +33,8 @@ def validate_epp(filename) require 'puppet/pops' result = { warnings: [], errors: [] } formatter = Puppet::Pops::Validation::DiagnosticFormatterPuppetStyle.new - evaluating_parser = Puppet::Pops::Parser::EvaluatingParser::EvaluatingEppParser.new() - parser = evaluating_parser.parser() + evaluating_parser = Puppet::Pops::Parser::EvaluatingParser::EvaluatingEppParser.new + parser = evaluating_parser.parser begin parse_result = parser.parse_file(filename) validation_result = evaluating_parser.validate(parse_result.model) @@ -56,10 +56,10 @@ def validate_epp(filename) column = err.source_pos.pos result[:errors] << "#{file}:#{line}:#{column}: #{message}" end - rescue Puppet::ParseError, SyntaxError => exc - result[:errors] << exc - rescue => exc - result[:errors] << exc + rescue Puppet::ParseError, SyntaxError => e + result[:errors] << e + rescue StandardError => e + result[:errors] << e end result @@ -77,14 +77,14 @@ def validate_erb(filename) end erb.filename = filename erb.result - rescue NameError => error + rescue NameError => e # This is normal because we don't have the variables that would # ordinarily be bound by the parent Puppet manifest. rescue TypeError # This is normal because we don't have the variables that would # ordinarily be bound by the parent Puppet manifest. - rescue SyntaxError => error - result[:errors] << error + rescue SyntaxError => e + result[:errors] << e end result diff --git a/puppet-syntax.gemspec b/puppet-syntax.gemspec index 5dd65d0..45f895e 100644 --- a/puppet-syntax.gemspec +++ b/puppet-syntax.gemspec @@ -1,34 +1,28 @@ -# coding: utf-8 - -lib = File.expand_path('../lib', __FILE__) +lib = File.expand_path('lib', __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'puppet-syntax/version' Gem::Specification.new do |spec| - spec.name = "puppet-syntax" + spec.name = 'puppet-syntax' spec.version = PuppetSyntax::VERSION - spec.authors = ["Vox Pupuli"] - spec.email = ["voxpupuli@groups.io"] - spec.description = %q{Syntax checks for Puppet manifests and templates} - spec.summary = %q{Syntax checks for Puppet manifests, templates, and Hiera YAML} - spec.homepage = "https://github.com/voxpupuli/puppet-syntax" - spec.license = "MIT" + spec.authors = ['Vox Pupuli'] + spec.email = ['voxpupuli@groups.io'] + spec.description = 'Syntax checks for Puppet manifests and templates' + spec.summary = 'Syntax checks for Puppet manifests, templates, and Hiera YAML' + spec.homepage = 'https://github.com/voxpupuli/puppet-syntax' + spec.license = 'MIT' spec.files = `git ls-files`.split($/) spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } - spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) - spec.require_paths = ["lib"] + spec.require_paths = ['lib'] - spec.required_ruby_version = ">= 2.7" + spec.required_ruby_version = '>= 2.7' - spec.add_dependency "rake" - spec.add_dependency "puppet", ">= 7" + spec.add_dependency 'puppet', '>= 7' + spec.add_dependency 'rake' - spec.add_development_dependency "pry" - spec.add_development_dependency "rb-readline" + spec.add_development_dependency 'pry' + spec.add_development_dependency 'rb-readline' - spec.add_development_dependency 'rubocop', '~> 1.12.0' - spec.add_development_dependency 'rubocop-performance', '~> 1.10' - spec.add_development_dependency 'rubocop-rake', '~> 0.2' - spec.add_development_dependency 'rubocop-rspec', '>= 1.44' + spec.add_development_dependency 'voxpupuli-rubocop', '~> 1.4.0' end diff --git a/spec/puppet-syntax/hiera_spec.rb b/spec/puppet-syntax/hiera_spec.rb index 333c706..ccca1b5 100644 --- a/spec/puppet-syntax/hiera_spec.rb +++ b/spec/puppet-syntax/hiera_spec.rb @@ -3,17 +3,17 @@ describe PuppetSyntax::Hiera do let(:subject) { PuppetSyntax::Hiera.new } - it 'should expect an array of files' do + it 'expects an array of files' do expect { subject.check(nil) }.to raise_error(/Expected an array of files/) end - it "should return nothing from valid YAML" do + it 'returns nothing from valid YAML' do files = fixture_hiera('hiera_good.yaml') res = subject.check(files) expect(res).to be == [] end - it "should return an error from invalid YAML" do + it 'returns an error from invalid YAML' do files = fixture_hiera('hiera_bad.yaml') expected = /ERROR: Failed to parse #{files[0]}:/ res = subject.check(files) @@ -22,11 +22,11 @@ end context 'check_hiera_keys = true' do - before(:each) { + before do PuppetSyntax.check_hiera_keys = true - } + end - it "should return warnings for invalid keys" do + it 'returns warnings for invalid keys' do hiera_yaml = 'hiera_badkey.yaml' examples = 5 files = fixture_hiera(hiera_yaml) @@ -42,7 +42,7 @@ expect(res[4]).to match('Key :picky::warning5: Puppet automatic lookup will not look up symbols') end - it "should return warnings for bad eyaml values" do + it 'returns warnings for bad eyaml values' do hiera_yaml = 'hiera_bad.eyaml' examples = 6 files = fixture_hiera(hiera_yaml) @@ -59,7 +59,7 @@ expect(res[5]).to match('Key acme::warning6\[\'hash_key\'\]\[2\] has corrupt base64 data') end - it "should handle empty files" do + it 'handles empty files' do hiera_yaml = 'hiera_key_empty.yaml' files = fixture_hiera(hiera_yaml) res = subject.check(files) diff --git a/spec/puppet-syntax/manifests_spec.rb b/spec/puppet-syntax/manifests_spec.rb index 693d12c..6c5b092 100644 --- a/spec/puppet-syntax/manifests_spec.rb +++ b/spec/puppet-syntax/manifests_spec.rb @@ -4,11 +4,11 @@ describe PuppetSyntax::Manifests do let(:subject) { PuppetSyntax::Manifests.new } - it 'should expect an array of files' do + it 'expects an array of files' do expect { subject.check(nil) }.to raise_error(/Expected an array of files/) end - it 'should return nothing from a valid file' do + it 'returns nothing from a valid file' do files = fixture_manifests('pass.pp') output, has_errors = subject.check(files) @@ -16,7 +16,7 @@ expect(has_errors).to eq(false) end - it 'should return nothing from a valid file with a class using tag parameter' do + it 'returns nothing from a valid file with a class using tag parameter' do files = fixture_manifests('tag_notice.pp') output, has_errors = subject.check(files) @@ -24,7 +24,7 @@ expect(has_errors).to eq(false) end - it 'should return nothing from a valid file with a class using schedule parameter' do + it 'returns nothing from a valid file with a class using schedule parameter' do files = fixture_manifests('schedule_notice.pp') output, has_errors = subject.check(files) @@ -32,7 +32,7 @@ expect(has_errors).to eq(false) end - it 'should return an error from an invalid file' do + it 'returns an error from an invalid file' do files = fixture_manifests('fail_error.pp') output, has_errors = subject.check(files) @@ -41,7 +41,7 @@ expect(has_errors).to eq(true) end - it 'should return a warning from an invalid file' do + it 'returns a warning from an invalid file' do files = fixture_manifests('fail_warning.pp') output, has_errors = subject.check(files) @@ -52,7 +52,7 @@ expect(output[1]).to match(/Unrecogni(s|z)ed escape sequence '\\\]'/) end - it 'should ignore warnings about storeconfigs' do + it 'ignores warnings about storeconfigs' do files = fixture_manifests('pass_storeconfigs.pp') output, has_errors = subject.check(files) @@ -60,7 +60,7 @@ expect(has_errors).to eq(false) end - it 'should read more than one valid file' do + it 'reads more than one valid file' do files = fixture_manifests(['pass.pp', 'pass_storeconfigs.pp']) output, has_errors = subject.check(files) @@ -68,27 +68,27 @@ expect(has_errors).to eq(false) end - it 'should continue after finding an error in the first file' do + it 'continues after finding an error in the first file' do files = fixture_manifests(['fail_error.pp', 'fail_warning.pp']) output, has_errors = subject.check(files) expect(has_errors).to eq(true) expect(output.size).to eq(5) - expect(output[0]).to match(/This Name has no effect. A Host Class Definition can not end with a value-producing expression without other effect \(file: \S*\/fail_error.pp, line: 2, column: 32\)$/) - expect(output[1]).to match(/This Name has no effect. A value was produced and then forgotten \(one or more preceding expressions may have the wrong form\) \(file: \S*\/fail_error.pp, line: 2, column: 3\)$/) + expect(output[0]).to match(%r{This Name has no effect. A Host Class Definition can not end with a value-producing expression without other effect \(file: \S*/fail_error.pp, line: 2, column: 32\)$}) + expect(output[1]).to match(%r{This Name has no effect. A value was produced and then forgotten \(one or more preceding expressions may have the wrong form\) \(file: \S*/fail_error.pp, line: 2, column: 3\)$}) expect(output[2]).to match('2 errors. Giving up') expect(output[3]).to match(/Unrecogni(s|z)ed escape sequence '\\\['/) expect(output[4]).to match(/Unrecogni(s|z)ed escape sequence '\\\]'/) end describe 'deprecation notices' do - it 'should instead be failures' do + it 'insteads be failures' do files = fixture_manifests('deprecation_notice.pp') output, has_errors = subject.check(files) expect(has_errors).to eq(true) expect(output.size).to eq(1) - expect(output[0]).to match (/Node inheritance is not supported in Puppet >= 4.0.0/) + expect(output[0]).to match(/Node inheritance is not supported in Puppet >= 4.0.0/) end end end diff --git a/spec/puppet-syntax/tasks/puppet-syntax_spec.rb b/spec/puppet-syntax/tasks/puppet-syntax_spec.rb index dc81068..fe6022f 100644 --- a/spec/puppet-syntax/tasks/puppet-syntax_spec.rb +++ b/spec/puppet-syntax/tasks/puppet-syntax_spec.rb @@ -9,25 +9,25 @@ known_eyaml_subdir = 'spec/fixtures/hiera/data/test/hiera_4.eyaml' describe 'PuppetSyntax rake tasks' do - it 'should filter directories' do + it 'filters directories' do list = PuppetSyntax::RakeTask.new.filelist(['**/lib', known_pp]) expect(list.count).to eq 1 expect(list).to include(known_pp) end - it 'should generate FileList of manifests relative to Rakefile' do + it 'generates FileList of manifests relative to Rakefile' do list = PuppetSyntax::RakeTask.new.filelist_manifests expect(list).to include(known_pp) expect(list.count).to eq 9 end - it 'should generate FileList of templates relative to Rakefile' do + it 'generates FileList of templates relative to Rakefile' do list = PuppetSyntax::RakeTask.new.filelist_templates expect(list).to include(known_erb) expect(list.count).to eq 9 end - it 'should generate FileList of Hiera yaml files relative to Rakefile' do + it 'generates FileList of Hiera yaml files relative to Rakefile' do list = PuppetSyntax::RakeTask.new.filelist_hiera_yaml expect(list).to include(known_yaml) expect(list).to include(known_eyaml) diff --git a/spec/puppet-syntax/templates_spec.rb b/spec/puppet-syntax/templates_spec.rb index 3ee8564..00d79a8 100644 --- a/spec/puppet-syntax/templates_spec.rb +++ b/spec/puppet-syntax/templates_spec.rb @@ -4,17 +4,17 @@ let(:subject) { PuppetSyntax::Templates.new } let(:conditional_warning_regex) do if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('2.6.0') - %r{2: warning: found `= literal' in conditional} + /2: warning: found `= literal' in conditional/ else - %r{2: warning: found = in conditional} + /2: warning: found = in conditional/ end end - it 'should expect an array of files' do + it 'expects an array of files' do expect { subject.check(nil) }.to raise_error(/Expected an array of files/) end - it 'should return nothing from a valid file' do + it 'returns nothing from a valid file' do files = fixture_templates('pass.erb') res = subject.check(files) @@ -22,7 +22,7 @@ expect(res[:errors]).to match([]) end - it 'should ignore NameErrors from unbound variables' do + it 'ignores NameErrors from unbound variables' do files = fixture_templates('pass_unbound_var.erb') res = subject.check(files) @@ -30,7 +30,7 @@ expect(res[:errors]).to match([]) end - it 'should catch SyntaxError' do + it 'catches SyntaxError' do files = fixture_templates('fail_error.erb') res = subject.check(files) @@ -38,7 +38,7 @@ expect(res[:errors][0]).to match(/2: syntax error, unexpected/) end - it 'should catch Ruby warnings' do + it 'catches Ruby warnings' do files = fixture_templates('fail_warning.erb') res = subject.check(files) @@ -46,7 +46,7 @@ expect(res[:warnings][0]).to match(conditional_warning_regex) end - it 'should read more than one valid file' do + it 'reads more than one valid file' do files = fixture_templates(['pass.erb', 'pass_unbound_var.erb']) res = subject.check(files) @@ -54,7 +54,7 @@ expect(res[:errors]).to match([]) end - it 'should continue after finding an error in the first file' do + it 'continues after finding an error in the first file' do files = fixture_templates(['fail_error.erb', 'fail_warning.erb']) res = subject.check(files) @@ -64,7 +64,7 @@ expect(res[:warnings][0]).to match(conditional_warning_regex) end - it 'should ignore a TypeError' do + it 'ignores a TypeError' do files = fixture_templates('typeerror_shouldwin.erb') res = subject.check(files) @@ -72,7 +72,7 @@ expect(res[:errors]).to match([]) end - it 'should ignore files without .erb extension' do + it 'ignores files without .erb extension' do files = fixture_templates('ignore.tpl') res = subject.check(files) @@ -80,7 +80,7 @@ expect(res[:errors]).to match([]) end - it 'should return nothing from a valid file' do + it 'returns nothing from a valid file' do files = fixture_templates('pass.epp') res = subject.check(files) @@ -88,7 +88,7 @@ expect(res[:errors]).to match([]) end - it 'should catch SyntaxError' do + it 'catches SyntaxError' do files = fixture_templates('fail_error.epp') res = subject.check(files) @@ -96,7 +96,7 @@ expect(res[:errors][0]).to match(/This Type-Name has no effect/) end - it 'should read more than one valid file' do + it 'reads more than one valid file' do files = fixture_templates(['pass.epp', 'pass_also.epp']) res = subject.check(files) @@ -104,7 +104,7 @@ expect(res[:errors]).to match([]) end - it 'should continue after finding an error in the first file' do + it 'continues after finding an error in the first file' do files = fixture_templates(['fail_error.epp', 'fail_error_also.epp']) res = subject.check(files) @@ -114,11 +114,11 @@ end context "when the 'epp_only' options is set" do - before(:each) { + before do PuppetSyntax.epp_only = true - } + end - it 'should process an ERB as EPP and find an error' do + it 'processes an ERB as EPP and find an error' do files = fixture_templates('pass.erb') res = subject.check(files) diff --git a/spec/puppet-syntax_spec.rb b/spec/puppet-syntax_spec.rb index 7095ecb..72959ce 100644 --- a/spec/puppet-syntax_spec.rb +++ b/spec/puppet-syntax_spec.rb @@ -5,35 +5,35 @@ PuppetSyntax.exclude_paths = [] end - it 'should default exclude_paths to include the pkg directory' do + it 'defaults exclude_paths to include the pkg directory' do expect(PuppetSyntax.exclude_paths).to include('pkg/**/*') end - it 'should support setting exclude_paths' do - PuppetSyntax.exclude_paths = ["foo", "bar/baz"] - expect(PuppetSyntax.exclude_paths).to eq(["foo", "bar/baz"]) + it 'supports setting exclude_paths' do + PuppetSyntax.exclude_paths = ['foo', 'bar/baz'] + expect(PuppetSyntax.exclude_paths).to eq(['foo', 'bar/baz']) end - it 'should support appending exclude_paths' do - PuppetSyntax.exclude_paths << "foo" - expect(PuppetSyntax.exclude_paths).to eq(["foo"]) + it 'supports appending exclude_paths' do + PuppetSyntax.exclude_paths << 'foo' + expect(PuppetSyntax.exclude_paths).to eq(['foo']) end - it 'should support a fail_on_deprecation_notices setting' do + it 'supports a fail_on_deprecation_notices setting' do PuppetSyntax.fail_on_deprecation_notices = false expect(PuppetSyntax.fail_on_deprecation_notices).to eq(false) end - it 'should support forcing EPP only templates' do + it 'supports forcing EPP only templates' do PuppetSyntax.epp_only = true expect(PuppetSyntax.epp_only).to eq(true) end - it 'should support setting paths for manifests, templates and hiera' do + it 'supports setting paths for manifests, templates and hiera' do PuppetSyntax.hieradata_paths = [] expect(PuppetSyntax.hieradata_paths).to eq([]) - PuppetSyntax.manifests_paths = ["**/environments/production/**/*.pp"] - expect(PuppetSyntax.manifests_paths).to eq(["**/environments/production/**/*.pp"]) + PuppetSyntax.manifests_paths = ['**/environments/production/**/*.pp'] + expect(PuppetSyntax.manifests_paths).to eq(['**/environments/production/**/*.pp']) PuppetSyntax.templates_paths = [] expect(PuppetSyntax.templates_paths).to eq([]) end