diff --git a/.github/workflows/pr_tests.yml b/.github/workflows/pr_tests.yml index 21ca28c..bcc5fb0 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 new file mode 100644 index 0000000..65c8c0a --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,699 @@ +--- +require: + - rubocop-performance + - rubocop-rake + - rubocop-rspec +AllCops: + NewCops: enable + DisplayCopNames: true + TargetRubyVersion: "2.7" + Include: + - "**/*.rb" + Exclude: + - bin/* + - ".vendor/**/*" + - pkg/**/* + - spec/fixtures/**/* + - vendor/**/* + - "**/Puppetfile" + - "**/Vagrantfile" + - "**/Guardfile" +Layout/LineLength: + Description: People have wide screens, use them. + Max: 200 +RSpec/BeforeAfterAll: + 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/HookArgument: + Description: Prefer explicit :each argument, matching existing module's style + EnforcedStyle: each +RSpec/DescribeSymbol: + Exclude: + - spec/unit/facter/**/*.rb +Style/BlockDelimiters: + Description: + Prefer braces for chaining. Mostly an aesthetical choice. Better to + be consistent then. + EnforcedStyle: braces_for_chaining +Style/ClassAndModuleChildren: + Description: Compact style reduces the required amount of indentation. + EnforcedStyle: compact +Style/EmptyElse: + Description: Enforce against empty else clauses, but allow `nil` for clarity. + EnforcedStyle: empty +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 + tokens over annotated ones. + EnforcedStyle: template +Style/Lambda: + Description: Prefer the keyword for easier discoverability. + EnforcedStyle: literal +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 + 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 + diffs, and re-ordering nicer. + EnforcedStyleForMultiline: comma +Style/TrailingCommaInArrayLiteral: + Description: + Prefer always trailing comma on multiline literals. This makes diffs, + and re-ordering nicer. + EnforcedStyleForMultiline: comma +Style/SymbolArray: + Description: Using percent style obscures symbolic intent of array's contents. + EnforcedStyle: brackets +RSpec/MessageSpies: + EnforcedStyle: receive +Style/Documentation: + Exclude: + - 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 +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 +Layout/EmptyLineAfterGuardClause: + Enabled: false +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: + Enabled: false +Metrics/MethodLength: + Enabled: false +Metrics/ModuleLength: + Enabled: false +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/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 +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/Gemfile b/Gemfile index e74c3da..7c330d6 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/lib/puppet/provider/rsync/rsync.rb b/lib/puppet/provider/rsync/rsync.rb index cdb96f0..bc7f4d1 100644 --- a/lib/puppet/provider/rsync/rsync.rb +++ b/lib/puppet/provider/rsync/rsync.rb @@ -5,11 +5,11 @@ desc 'Rsync provider' - confine :kernel => 'Linux' - commands :rsync => 'rsync' + confine kernel: 'Linux' + commands rsync: 'rsync' def initialize(*args) - super(*args) + super end def action @@ -27,7 +27,7 @@ def action_insync? cmd = build_command.join(' ') debug %(Executing command #{cmd} with password #{get_password}) - output = Puppet::Util::Execution.execute(cmd, :failonfail => false, :combine => true) + output = Puppet::Util::Execution.execute(cmd, failonfail: false, combine: true) # We're done with the password file here... @passfile.close @@ -39,30 +39,28 @@ def action_insync? if @resource[:logoutput] != :false output.each_line do |line| - if ( Facter[:selinux_current_mode] != 'disabled' ) && - line =~ /attr\(.*security.selinux/ - then + if (Facter[:selinux_current_mode] != 'disabled') && + line =~ %r{attr\(.*security.selinux} selinux_failure = true end if selinux_failure && @resource[:ignore_selinux] == :true - self.send(:debug, line.chomp) + send(:debug, line.chomp) else - self.send(@resource[:loglevel], line.chomp) + send(@resource[:loglevel], line.chomp) end end end - unless (selinux_failure && @resource[:ignore_selinux] == :true) - self.fail %(Rsync exited with code #{output.exitstatus.to_s}\n) + unless selinux_failure && @resource[:ignore_selinux] == :true + self.fail %(Rsync exited with code #{output.exitstatus}\n) end - elsif output !~ /^\s*$/ + elsif !%r{^\s*$}.match?(output) if @resource[:logoutput] != false && @resource[:logoutput] != :false && @resource[:logoutput] != :on_failure - then output.each_line do |line| - self.send(@resource[:loglevel], line.chomp) + send(@resource[:loglevel], line.chomp) end end is_insync = false @@ -70,7 +68,7 @@ def action_insync? is_insync end - def action=(should) + def action=(_should) debug 'syncing...' end @@ -78,23 +76,23 @@ def action=(should) def get_source source = '' - if @resource[:source] - resource_source = @resource[:source] - else - resource_source = @resource[:source_path] - end - - if @resource[:protocol] - resource_protocol = @resource[:protocol] - else - resource_protocol = @resource[:proto] - end - - if @resource[:server] - resource_server = @resource[:server] - else - resource_server = @resource[:rsync_server] - end + resource_source = if @resource[:source] + @resource[:source] + else + @resource[:source_path] + end + + resource_protocol = if @resource[:protocol] + @resource[:protocol] + else + @resource[:proto] + end + + resource_server = if @resource[:server] + @resource[:server] + else + @resource[:rsync_server] + end if ( @resource[:server] || @@ -102,39 +100,36 @@ def get_source ) && ( @resource[:action] == :pull || @resource[:action].eql?('pull') - ) - then + ) source << resource_protocol source << '://' if @resource[:user] source << %(#{@resource[:user]}@) end source << resource_server - source << '/' unless resource_source =~ /^\// - source << resource_source - else - source << resource_source + source << '/' unless %r{^/}.match?(resource_source) end + source << resource_source source end def get_target target = '' - if @resource[:target] - resource_target = @resource[:target] - else - resource_target = @resource[:target_path] - end - if @resource[:protocol] - resource_protocol = @resource[:protocol] - else - resource_protocol = @resource[:proto] - end - if @resource[:server] - resource_server = @resource[:server] - else - resource_server = @resource[:rsync_server] - end + resource_target = if @resource[:target] + @resource[:target] + else + @resource[:target_path] + end + resource_protocol = if @resource[:protocol] + @resource[:protocol] + else + @resource[:proto] + end + resource_server = if @resource[:server] + @resource[:server] + else + @resource[:rsync_server] + end if ( @resource[:server] || @@ -142,25 +137,22 @@ def get_target ) && ( @resource[:action] == :push || @resource[:action].eql?('push') - ) - then + ) target << resource_protocol target << '://' if @resource[:user] target << %(#{@resource[:user]}@) end target << resource_server - target << '/' unless resource_target =~ /^\// - target << resource_target - else - target << resource_target + target << '/' unless %r{^/}.match?(resource_target) end + target << resource_target end def get_flags flags = [] flags << '-p' if @resource.preserve_perms? - flags << '--chmod=u=rwX,g=rX,o-rwx' if not @resource.preserve_perms? + flags << '--chmod=u=rwX,g=rX,o-rwx' unless @resource.preserve_perms? flags << '-A' if @resource.preserve_acl? flags << '-X' if @resource.preserve_xattrs? flags << '-o' if @resource.preserve_owner? @@ -171,26 +163,26 @@ def get_flags flags << '-z' if @resource.compress? flags << '-r' if @resource.recurse? flags << '-H' if @resource.hard_links? - if @resource.copy_links? - flags << '-L' - else - flags << '-l' - end - if @resource.size_only? - flags << '--size-only' - else - flags << '-c' - end + flags << if @resource.copy_links? + '-L' + else + '-l' + end + flags << if @resource.size_only? + '--size-only' + else + '-c' + end end def get_timeout - if @resource[:timeout] - timeout = @resource[:timeout].to_s - elsif @resource[:rsync_timeout] - timeout = @resource[:rsync_timeout].to_s - else - timeout = @resource[:contimeout] - end + timeout = if @resource[:timeout] + @resource[:timeout].to_s + elsif @resource[:rsync_timeout] + @resource[:rsync_timeout].to_s + else + @resource[:contimeout] + end timeout and timeout = %(--contimeout=#{timeout}) @@ -207,10 +199,8 @@ def get_iotimeout def get_exclude exclude = [] - if @resource[:exclude] - @resource[:exclude].each do |val| - exclude << %(--exclude='#{val}') - end + @resource[:exclude]&.each do |val| + exclude << %(--exclude='#{val}') end exclude end @@ -218,7 +208,7 @@ def get_exclude def get_bwlimit bwlimit = '' if @resource[:bwlimit] - bwlimit << %(--bwlimit=#{@resource[:bwlimit].to_s}) + bwlimit << %(--bwlimit=#{@resource[:bwlimit]}) end bwlimit end @@ -228,7 +218,7 @@ def get_password password = @resource[:pass] unless password # We *always* set a password so that we don't hang at a prompt! - if !password || ( password =~ /^(\s*)$/ ) + if !password || (password =~ %r{^(\s*)$}) password = '__*invalid_password_provided*__' end @@ -239,16 +229,16 @@ def get_password_file @passfile.puts(get_password) @passfile.flush - return %(--password-file=#{@passfile.path}) + %(--password-file=#{@passfile.path}) end def build_command cmd = [] - if @resource[:path] - cmd << @resource[:path] - else - cmd << command('rsync') - end + cmd << if @resource[:path] + @resource[:path] + else + command('rsync') + end cmd << ['-i', '-S'] cmd << ['--dry-run'] if Puppet[:noop] cmd << get_flags @@ -260,8 +250,7 @@ def build_command cmd << get_source cmd << get_target cmd.flatten! - cmd = cmd.reject{ |x| x =~ /^\s*$/ } + cmd = cmd.reject { |x| x =~ %r{^\s*$} } cmd end - end diff --git a/lib/puppet/type/rsync.rb b/lib/puppet/type/rsync.rb index 4c205d0..316cf49 100644 --- a/lib/puppet/type/rsync.rb +++ b/lib/puppet/type/rsync.rb @@ -17,7 +17,7 @@ def initialize(args) super - self.tags = [Array(self.tags),'rsync'].flatten + self.tags = [Array(tags), 'rsync'].flatten end def finish @@ -83,11 +83,11 @@ def finish newvalues(:push, :pull) defaultto :pull - def insync?(is) + def insync?(_is) provider.action_insync? end - def change_to_s(currentvalue, newvalue) + def change_to_s(_currentvalue, _newvalue) 'executed successfully' end end @@ -112,20 +112,20 @@ def change_to_s(currentvalue, newvalue) desc 'The hostname or IP of the rsync server' validate do |value| - if value !~ /[a-zA-Z][a-zA-Z\-]*(\.[a-zA-Z][a-zA-Z\-]*)*/ && - value !~ /^(?-mix:\A((?x-mi:0|1(?:[0-9][0-9]?)?|2(?:[0-4][0-9]?|5[0-5]?|[6-9])?|[3-9][0-9]?))\.((?x-mi:0|1(?:[0-9][0-9]?)?|2(?:[0-4][0-9]?|5[0-5]?|[6-9])?|[3-9][0-9]?))\.((?x-mi:0|1(?:[0-9][0-9]?)?|2(?:[0-4][0-9]?|5[0-5]?|[6-9])?|[3-9][0-9]?))\.((?x-mi:0|1(?:[0-9][0-9]?)?|2(?:[0-4][0-9]?|5[0-5]?|[6-9])?|[3-9][0-9]?)):([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])\z)$/ && - value !~ /^(?x-mi:(?:(?x-mi:\A\[(?:[0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}\]:([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])\z))|(?:(?x-mi:\A\[((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)\]:([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])\z))|(?:(?x-mi:\A\[((?:[0-9A-Fa-f]{1,4}:){6,6})(\d+)\.(\d+)\.(\d+)\.(\d+)\]:([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])\z))|(?:(?x-mi:\A\[((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}:)*)(\d+)\.(\d+)\.(\d+)\.(\d+)\]:([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])\z)))$/ + if value !~ %r{[a-zA-Z][a-zA-Z\-]*(\.[a-zA-Z][a-zA-Z\-]*)*} && + value !~ %r{^(?-mix:\A((?x-mi:0|1(?:[0-9][0-9]?)?|2(?:[0-4][0-9]?|5[0-5]?|[6-9])?|[3-9][0-9]?))\.((?x-mi:0|1(?:[0-9][0-9]?)?|2(?:[0-4][0-9]?|5[0-5]?|[6-9])?|[3-9][0-9]?))\.((?x-mi:0|1(?:[0-9][0-9]?)?|2(?:[0-4][0-9]?|5[0-5]?|[6-9])?|[3-9][0-9]?))\.((?x-mi:0|1(?:[0-9][0-9]?)?|2(?:[0-4][0-9]?|5[0-5]?|[6-9])?|[3-9][0-9]?)):([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])\z)$} && + value !~ %r{^(?x-mi:(?:(?x-mi:\A\[(?:[0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}\]:([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])\z))|(?:(?x-mi:\A\[((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)\]:([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])\z))|(?:(?x-mi:\A\[((?:[0-9A-Fa-f]{1,4}:){6,6})(\d+)\.(\d+)\.(\d+)\.(\d+)\]:([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])\z))|(?:(?x-mi:\A\[((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}:)*)(\d+)\.(\d+)\.(\d+)\.(\d+)\]:([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])\z)))$} begin require 'ipaddr' IPAddr.new(value) rescue Exception - fail Puppet::Error, %(#{value} does not appear to be a valid hostname or IP address) + raise Puppet::Error, %(#{value} does not appear to be a valid hostname or IP address) end end end end - newparam(:rsync_server, :parent => self.paramclass(:server)) do + newparam(:rsync_server, parent: paramclass(:server)) do desc 'The hostname or IP of the rsync server' end @@ -145,55 +145,55 @@ def change_to_s(currentvalue, newvalue) desc 'The fully qualified path to the rsync executable' end - newparam(:preserve_perms, :boolean => true) do + newparam(:preserve_perms, boolean: true) do desc 'Whether or not to preserve permissions. Defaults to true.' newvalues(:true, :false) defaultto :true end - newparam(:preserve_acl, :boolean => true) do + newparam(:preserve_acl, boolean: true) do desc 'Whether or not to preserve ACL. Defaults to true.' newvalues(:true, :false) defaultto :true end - newparam(:preserve_xattrs, :boolean => true) do + newparam(:preserve_xattrs, boolean: true) do desc 'Whether or not to preserve extended attributes. Defaults to true.' newvalues(:true, :false) defaultto :true end - newparam(:preserve_owner, :boolean => true) do + newparam(:preserve_owner, boolean: true) do desc 'Whether or not to preserve owner. Defaults to true.' newvalues(:true, :false) defaultto :true end - newparam(:preserve_group, :boolean => true) do + newparam(:preserve_group, boolean: true) do desc 'Whether or not to preserve group. Defaults to true.' newvalues(:true, :false) defaultto :true end - newparam(:preserve_devices, :boolean => true) do + newparam(:preserve_devices, boolean: true) do desc 'Whether or not to preserve device files. Defaults to false.' newvalues(:true, :false) defaultto :false end - newparam(:compress, :boolean => true) do + newparam(:compress, boolean: true) do desc 'Whether or not to compress content prior to transfer. Defaults to true.' newvalues(:true, :false) defaultto :true end - newparam(:recurse, :boolean => true) do + newparam(:recurse, boolean: true) do desc 'Whether or not to recursively copy. Defaults to true.' newvalues(:true, :false) defaultto :true end - newparam(:hard_links, :boolean => true) do + newparam(:hard_links, boolean: true) do desc 'Preserve hard links. Defaults to true.' newvalues(:true, :false) defaultto :true @@ -208,7 +208,7 @@ def change_to_s(currentvalue, newvalue) munge do |value| [value].flatten end - defaultto ['.svn/','.git/'] + defaultto ['.svn/', '.git/'] end newparam(:timeout) do @@ -220,8 +220,8 @@ def change_to_s(currentvalue, newvalue) munge do |value| if value.is_a?(String) - unless value =~ /^\d+$/ - fail Puppet::Error, 'Timeout must be an integer' + unless %r{^\d+$}.match?(value) + raise Puppet::Error, 'Timeout must be an integer' end Integer(value) else @@ -230,15 +230,15 @@ def change_to_s(currentvalue, newvalue) end end - newparam(:contimeout, :parent => self.paramclass(:timeout)) do + newparam(:contimeout, parent: paramclass(:timeout)) do desc 'Connection timeout in seconds.' end - newparam(:rsync_timeout, :parent => self.paramclass(:contimeout)) do + newparam(:rsync_timeout, parent: paramclass(:contimeout)) do desc 'Alias for :timeout' end - newparam(:iotimeout, :parent => self.paramclass(:timeout)) do + newparam(:iotimeout, parent: paramclass(:timeout)) do desc 'I/O timeout in seconds.' end @@ -254,7 +254,7 @@ def change_to_s(currentvalue, newvalue) defaultto :on_failure end - newparam(:delete, :boolean => true) do + newparam(:delete, boolean: true) do desc 'Whether to delete files that do not exist on server. Defaults to false' newvalues(:true, :false) defaultto :false @@ -265,8 +265,8 @@ def change_to_s(currentvalue, newvalue) munge do |value| if value.is_a?(String) - unless value =~ /^\d+$/ - fail Puppet::Error, 'bwlimit must be an integer' + unless %r{^\d+$}.match?(value) + raise Puppet::Error, 'bwlimit must be an integer' end Integer(value) else @@ -275,19 +275,19 @@ def change_to_s(currentvalue, newvalue) end end - newparam(:copy_links, :boolean => true) do + newparam(:copy_links, boolean: true) do desc 'Whether to copy links as symlinks. Defaults to false' newvalues(:true, :false) defaultto :false end - newparam(:size_only, :boolean => true) do + newparam(:size_only, boolean: true) do desc 'Whether to skip files that match in size. Defaults to true' newvalues(:true, :false) defaultto :false end - newparam(:no_implied_dirs, :boolean => true) do + newparam(:no_implied_dirs, boolean: true) do desc 'Do not send implied dirs. Defaults to true' newvalues(:true, :false) defaultto :true @@ -299,7 +299,7 @@ def change_to_s(currentvalue, newvalue) autorequire(:user) do # Autorequire users if they are specified by name - if user = self[:user] && user !~ /^\d+$/ + if (user = self[:user] && user !~ %r{^\d+$}) debug %(Autorequiring User[#{user}]) user end @@ -312,7 +312,7 @@ def change_to_s(currentvalue, newvalue) if !self[:server] path << self[:target] path << self[:source] - elsif self[:action] == :pull or self[:action].eql?('pull') + elsif (self[:action] == :pull) || self[:action].eql?('pull') path << self[:target] else path << self[:source] @@ -346,7 +346,7 @@ def change_to_s(currentvalue, newvalue) end autorequire(:service) do - svcs = ['rsync','stunnel'] + svcs = ['rsync', 'stunnel'] svcs.each do |val| debug %(Autorequiring Service[#{val}]) @@ -364,42 +364,41 @@ def change_to_s(currentvalue, newvalue) [:protocol, :proto], [:timeout, :rsync_timeout], [:timeout, :contimeout], - [:password, :pass] + [:password, :pass], ] unless @parameters.include?(:protocol) || @parameters.include?(:proto) - self[:protocol] = "rsync" + self[:protocol] = 'rsync' end unless @parameters.include?(:timeout) || @parameters.include?(:rsync_timeout) - fail Puppet::Error, "You must specify an rsync timeout." + raise Puppet::Error, 'You must specify an rsync timeout.' end required_fields.each do |req| unless @parameters.include?(req.first) || @parameters.include?(req.last) - fail Puppet::Error, "You must specify one of #{req.first} or #{req.last}." + raise Puppet::Error, "You must specify one of #{req.first} or #{req.last}." end end aliases.each do |a| if @parameters.include?(a.first) && @parameters.include?(a.last) - fail Puppet::Error, %(You can only specify one of #{a.first} and #{a.last}) + raise Puppet::Error, %(You can only specify one of #{a.first} and #{a.last}) end end - if (self[:server] || self[:rsync_server]) && self[:action] == :pull - full_paths = [:path, :rsync_path, :target, :target_path] - elsif self[:server] || self[:rsync_server] - full_paths = [:path, :rsync_path, :source, :source_path] - else - full_paths = [:path, :rsync_path, :source, :source_path, :target, :target_path] - end + full_paths = if (self[:server] || self[:rsync_server]) && self[:action] == :pull + [:path, :rsync_path, :target, :target_path] + elsif self[:server] || self[:rsync_server] + [:path, :rsync_path, :source, :source_path] + else + [:path, :rsync_path, :source, :source_path, :target, :target_path] + end full_paths.each do |path| - if self[path] - unless self[path] =~ /^\/$/ || self[path] =~ /^\/[^\/]/ - fail Puppet::Error, %(File paths must be fully qualified, not '#{self[path]}') - end + next unless self[path] + unless self[path] =~ %r{^/$} || self[path] =~ %r{^/[^/]} + raise Puppet::Error, %(File paths must be fully qualified, not '#{self[path]}') end end @@ -432,8 +431,7 @@ def change_to_s(currentvalue, newvalue) if @parameters.include?(:user) && !(@parameters.include?(:password) || @parameters.include?(:pass)) - then - fail Puppet::Error, 'You must specify a password if you specify a user.' + raise Puppet::Error, 'You must specify a password if you specify a user.' end end end diff --git a/spec/acceptance/helpers/utils.rb b/spec/acceptance/helpers/utils.rb index db9f47d..b918873 100644 --- a/spec/acceptance/helpers/utils.rb +++ b/spec/acceptance/helpers/utils.rb @@ -2,7 +2,6 @@ module Acceptance; end module Acceptance::Helpers; end module Acceptance::Helpers::Utils - # @return Array of pairs of host indices that contains the position-invariant # permutations of hosts in which the indices are unique # diff --git a/spec/acceptance/suites/default/00_default_spec.rb b/spec/acceptance/suites/default/00_default_spec.rb index a81d1b3..064e96a 100644 --- a/spec/acceptance/suites/default/00_default_spec.rb +++ b/spec/acceptance/suites/default/00_default_spec.rb @@ -3,7 +3,7 @@ test_name 'rsync class' describe 'rsync class' do - let(:manifest) { + let(:manifest) do <<-EOS include 'rsync::server' @@ -43,31 +43,33 @@ require => Rsync::Server::Section['test'] } EOS - } + end - let(:hieradata) {{ - 'iptables::precise_match' => true, - 'simp_options::pki' => false, - 'rsync::server::stunnel' => false - }} + let(:hieradata) do + { + 'iptables::precise_match' => true, + 'simp_options::pki' => false, + 'rsync::server::stunnel' => false + } + end hosts.each do |host| - it 'should work with no errors' do + it 'works with no errors' do set_hieradata_on(host, hieradata) - apply_manifest_on(host, manifest, :catch_failures => true) + apply_manifest_on(host, manifest, catch_failures: true) end - it 'should be idempotent' do - # FIXME - Workaround for systemd::dropin_file idempotency issue: - # Selinux type of the override unit file (from simp-rsyslog module) - # gets fixed with a second puppet run. - apply_manifest_on(host, manifest, :catch_failures => true) + it 'is idempotent' do + # FIXME: - Workaround for systemd::dropin_file idempotency issue: + # Selinux type of the override unit file (from simp-rsyslog module) + # gets fixed with a second puppet run. + apply_manifest_on(host, manifest, catch_failures: true) - apply_manifest_on(host, manifest, {:catch_changes => true}) + apply_manifest_on(host, manifest, { catch_changes: true }) end - it 'should have a file transferred' do - on(host, 'ls /tmp/test_file', :acceptable_exit_codes => [0]) + it 'has a file transferred' do + on(host, 'ls /tmp/test_file', acceptable_exit_codes: [0]) end end end diff --git a/spec/acceptance/suites/default/10_server_client_spec.rb b/spec/acceptance/suites/default/10_server_client_spec.rb index 02cde0f..fab3555 100644 --- a/spec/acceptance/suites/default/10_server_client_spec.rb +++ b/spec/acceptance/suites/default/10_server_client_spec.rb @@ -9,18 +9,17 @@ end else index_pairs = unique_host_pairs(hosts) - index_pairs.each do |index1,index2| + index_pairs.each do |index1, index2| # Test interoperability between a pair of hosts in the node set, each # acting as a rsync server to the other. server1 = hosts[index1] server2 = hosts[index2] context "Interoperability between #{server1} and #{server2}" do - - let(:file_content) { + let(:file_content) do "What a Test File for #{server1} and #{server2} testing" - } + end - let(:manifest) { + let(:manifest) do <<-EOS include 'rsync::server' @@ -53,9 +52,9 @@ require => File['/srv/rsync/test/test_file_srvcli'] } EOS - } + end - let(:manifest_test_server1) { + let(:manifest_test_server1) do <<-EOS rsync::retrieve { 'test_pull': user => 'test_user', @@ -65,9 +64,9 @@ rsync_server => '#{server2_fqdn}:8873', } EOS - } + end - let(:manifest_test_server2) { + let(:manifest_test_server2) do <<-EOS rsync::retrieve { 'test_pull': user => 'test_user', @@ -77,28 +76,32 @@ rsync_server => '#{server1_fqdn}', } EOS - } - - let(:hieradata_server1) {{ - 'iptables::precise_match' => true, - 'simp_options::pki' => false, - 'simp_options::firewall' => true, - 'rsync::server::stunnel' => false, - 'rsync::server::trusted_nets' => [server2_ip], - 'rsync::server::global::trusted_nets' => [server2_ip], - 'rsync::server::global::address' => '0.0.0.0', - }} - - let(:hieradata_server2) {{ - 'iptables::precise_match' => true, - 'simp_options::pki' => false, - 'simp_options::firewall' => true, - 'rsync::server::stunnel' => false, - 'rsync::server::global::port' => 8873, - 'rsync::server::trusted_nets' => [server1_ip], - 'rsync::server::global::trusted_nets' => [server1_ip], - 'rsync::server::global::address' => '0.0.0.0', - }} + end + + let(:hieradata_server1) do + { + 'iptables::precise_match' => true, + 'simp_options::pki' => false, + 'simp_options::firewall' => true, + 'rsync::server::stunnel' => false, + 'rsync::server::trusted_nets' => [server2_ip], + 'rsync::server::global::trusted_nets' => [server2_ip], + 'rsync::server::global::address' => '0.0.0.0', + } + end + + let(:hieradata_server2) do + { + 'iptables::precise_match' => true, + 'simp_options::pki' => false, + 'simp_options::firewall' => true, + 'rsync::server::stunnel' => false, + 'rsync::server::global::port' => 8873, + 'rsync::server::trusted_nets' => [server1_ip], + 'rsync::server::global::trusted_nets' => [server1_ip], + 'rsync::server::global::address' => '0.0.0.0', + } + end let(:server1_interface) { get_private_network_interface(server1) } let(:server1_ip) { fact_on(server1, %(ipaddress_#{server1_interface})) } @@ -108,22 +111,22 @@ let(:server2_fqdn) { fact_on(server2, 'fqdn') } context 'setup server and client hosts' do - it "should set hieradata on #{server1}" do + it "sets hieradata on #{server1}" do set_hieradata_on(server1, hieradata_server1) end - it "should set hieradata on #{server2}" do + it "sets hieradata on #{server2}" do set_hieradata_on(server2, hieradata_server2) end [server1, server2].each do |host| context "on #{host}" do - it 'should work with no errors' do - apply_manifest_on(host, manifest, :catch_failures => true) + it 'works with no errors' 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 @@ -131,24 +134,24 @@ context 'test a file retrieval' do [server1, server2].each do |host| - it 'should start with a clean state' do + it 'starts with a clean state' do on(host, 'rm -rf /tmp/test_file_srvcli') end end - it "should run retrieval code on #{server1}" do - apply_manifest_on(server1, manifest_test_server1, :catch_failures => true) + it "runs retrieval code on #{server1}" do + apply_manifest_on(server1, manifest_test_server1, catch_failures: true) end - it "should run retrieval code on #{server2}" do - apply_manifest_on(server2, manifest_test_server2, :catch_failures => true) + it "runs retrieval code on #{server2}" do + apply_manifest_on(server2, manifest_test_server2, catch_failures: true) end [server1, server2].each do |host| - it 'should have a file transferred' do - on(host, 'ls /tmp/test_file_srvcli', :acceptable_exit_codes => [0]) + it 'has a file transferred' do + on(host, 'ls /tmp/test_file_srvcli', acceptable_exit_codes: [0]) result = on(host, 'cat /tmp/test_file_srvcli').stdout - expect( result ).to match(/#{Regexp.escape(file_content)}/) + expect(result).to match(%r{#{Regexp.escape(file_content)}}) end end end diff --git a/spec/acceptance/suites/default/20_server_client_stunnel_spec.rb b/spec/acceptance/suites/default/20_server_client_stunnel_spec.rb index a17dc58..99c4816 100644 --- a/spec/acceptance/suites/default/20_server_client_stunnel_spec.rb +++ b/spec/acceptance/suites/default/20_server_client_stunnel_spec.rb @@ -9,22 +9,21 @@ end else index_pairs = unique_host_pairs(hosts) - index_pairs.each do |index1,index2| + index_pairs.each do |index1, index2| # Test interoperability between a pair of hosts in the node set, each # acting as a rsync server to the other. server1 = hosts[index1] server2 = hosts[index2] context "Interoperability between #{server1} and #{server2}" do - - let(:file_content1) { + let(:file_content1) do "What a Test File for #{server1} and #{server2} testing" - } + end - let(:file_content2) { + let(:file_content2) do "What a Test File for #{server2} and #{server1} testing" - } + end - let(:manifest_server1) { + let(:manifest_server1) do <<-EOS include 'rsync::server' @@ -61,9 +60,9 @@ accept => '127.0.0.1:8873' } EOS - } + end - let(:manifest_server2) { + let(:manifest_server2) do <<-EOS include 'rsync::server' @@ -100,9 +99,9 @@ accept => '127.0.0.1:873' } EOS - } + end - let(:manifest_test_server1) { + let(:manifest_test_server1) do <<-EOS rsync::retrieve { 'test_pull': user => 'test_user', @@ -112,9 +111,9 @@ rsync_server => '127.0.0.1', } EOS - } + end - let(:manifest_test_server2) { + let(:manifest_test_server2) do <<-EOS rsync::retrieve { 'test_pull': user => 'test_user', @@ -124,26 +123,30 @@ rsync_server => '127.0.0.1:8873', } EOS - } - - let(:hieradata_server1) {{ - 'iptables::precise_match' => true, - 'simp_options::pki' => true, - 'simp_options::pki::source' => '/etc/pki/simp-testing/pki', - 'simp_options::firewall' => true, - 'rsync::server::stunnel' => true, - 'rsync::server::trusted_nets' => [server2_ip], - }} - - let(:hieradata_server2) {{ - 'iptables::precise_match' => true, - 'simp_options::pki' => true, - 'simp_options::pki::source' => '/etc/pki/simp-testing/pki', - 'simp_options::firewall' => true, - 'rsync::server::stunnel' => true, - 'rsync::server::global::port' => 8873, - 'rsync::server::trusted_nets' => [server1_ip], - }} + end + + let(:hieradata_server1) do + { + 'iptables::precise_match' => true, + 'simp_options::pki' => true, + 'simp_options::pki::source' => '/etc/pki/simp-testing/pki', + 'simp_options::firewall' => true, + 'rsync::server::stunnel' => true, + 'rsync::server::trusted_nets' => [server2_ip], + } + end + + let(:hieradata_server2) do + { + 'iptables::precise_match' => true, + 'simp_options::pki' => true, + 'simp_options::pki::source' => '/etc/pki/simp-testing/pki', + 'simp_options::firewall' => true, + 'rsync::server::stunnel' => true, + 'rsync::server::global::port' => 8873, + 'rsync::server::trusted_nets' => [server1_ip], + } + end let(:server1_interface) { get_private_network_interface(server1) } let(:server1_ip) { fact_on(server1, %(ipaddress_#{server1_interface})) } @@ -154,59 +157,58 @@ context 'setup server and client hosts' do context "on #{server1}" do - it "should set hieradata" do + it 'sets hieradata' do set_hieradata_on(server1, hieradata_server1) end - it 'should work with no errors' do - apply_manifest_on(server1, manifest_server1, :catch_failures => true) + it 'works with no errors' do + apply_manifest_on(server1, manifest_server1, catch_failures: true) end - it 'should be idempotent' do - apply_manifest_on(server1, manifest_server1, :catch_changes => true) + it 'is idempotent' do + apply_manifest_on(server1, manifest_server1, catch_changes: true) end end context "on #{server2}" do - it "should set hieradata" do + it 'sets hieradata' do set_hieradata_on(server2, hieradata_server2) end - it 'should work with no errors' do - apply_manifest_on(server2, manifest_server2, :catch_failures => true) + it 'works with no errors' do + apply_manifest_on(server2, manifest_server2, catch_failures: true) end - it 'should be idempotent' do - apply_manifest_on(server2, manifest_server2, :catch_changes => true) + it 'is idempotent' do + apply_manifest_on(server2, manifest_server2, catch_changes: true) end end - end context 'test a file retrieval' do [server1, server2].each do |host| - it 'should start with a clean state' do + it 'starts with a clean state' do on(host, 'rm -rf /tmp/test_file_srvcli*') end - it "should run server1 retrieval code on #{host}" do - apply_manifest_on(host, manifest_test_server1, :catch_failures => true) + it "runs server1 retrieval code on #{host}" do + apply_manifest_on(host, manifest_test_server1, catch_failures: true) end - it 'should have a file transferred' do - on(host, 'ls /tmp/test_file_srvcli2_server1', :acceptable_exit_codes => [0]) + it 'has a file transferred' do + on(host, 'ls /tmp/test_file_srvcli2_server1', acceptable_exit_codes: [0]) result = on(host, 'cat /tmp/test_file_srvcli2_server1').stdout - expect( result ).to match(/#{Regexp.escape(file_content1)}/) + expect(result).to match(%r{#{Regexp.escape(file_content1)}}) end - it "should run server2 retrieval code on #{host}" do - apply_manifest_on(host, manifest_test_server2, :catch_failures => true) + it "runs server2 retrieval code on #{host}" do + apply_manifest_on(host, manifest_test_server2, catch_failures: true) end - it 'should have a file transferred' do - on(host, 'ls /tmp/test_file_srvcli2_server2', :acceptable_exit_codes => [0]) + it 'has a file transferred' do + on(host, 'ls /tmp/test_file_srvcli2_server2', acceptable_exit_codes: [0]) result = on(host, 'cat /tmp/test_file_srvcli2_server2').stdout - expect( result ).to match(/#{Regexp.escape(file_content2)}/) + expect(result).to match(%r{#{Regexp.escape(file_content2)}}) end end end diff --git a/spec/classes/init_spec.rb b/spec/classes/init_spec.rb index 178d98f..a356495 100644 --- a/spec/classes/init_spec.rb +++ b/spec/classes/init_spec.rb @@ -33,6 +33,7 @@ def mock_selinux_disabled_facts(os_facts) os_facts = mock_selinux_enforcing_facts(os_facts) os_facts end + it { is_expected.to compile.with_all_deps } it { is_expected.to create_class('rsync::selinux') } it { is_expected.to create_selboolean('rsync_client') } @@ -47,7 +48,7 @@ def mock_selinux_disabled_facts(os_facts) end it { is_expected.to compile.with_all_deps } - it { is_expected.to_not create_class('rsync::selinux') } + it { is_expected.not_to create_class('rsync::selinux') } end end end diff --git a/spec/classes/server/global_spec.rb b/spec/classes/server/global_spec.rb index 37cbaa2..3d655ae 100644 --- a/spec/classes/server/global_spec.rb +++ b/spec/classes/server/global_spec.rb @@ -3,7 +3,7 @@ describe 'rsync::server::global' do before(:each) do # Mask 'assert_private' for testing - Puppet::Parser::Functions.newfunction(:assert_private, :type => :rvalue) { |args| } + Puppet::Parser::Functions.newfunction(:assert_private, type: :rvalue) { |args| } end context 'supported operating systems' do @@ -12,16 +12,18 @@ context "on #{os}" do it { is_expected.to compile.with_all_deps } - it { is_expected.to create_concat__fragment('rsync_global').with_content(/address = 127.0.0.1/) } - it { is_expected.to_not create_tcpwrappers__allow('rsync') } + it { is_expected.to create_concat__fragment('rsync_global').with_content(%r{address = 127.0.0.1}) } + it { is_expected.not_to create_tcpwrappers__allow('rsync') } context 'with tcpwrappers' do - let(:params) {{ - :tcpwrappers => true - }} + let(:params) do + { + tcpwrappers: true + } + end it { is_expected.to compile.with_all_deps } - it { is_expected.to create_concat__fragment('rsync_global').with_content(/address = 127.0.0.1/) } + it { is_expected.to create_concat__fragment('rsync_global').with_content(%r{address = 127.0.0.1}) } it { is_expected.to create_tcpwrappers__allow('rsync_server') } end end diff --git a/spec/classes/server_spec.rb b/spec/classes/server_spec.rb index 227c265..beb9bbc 100644 --- a/spec/classes/server_spec.rb +++ b/spec/classes/server_spec.rb @@ -14,7 +14,7 @@ it { is_expected.to create_service('rsyncd').that_subscribes_to('Service[stunnel]') } context 'no_stunnel' do - let(:params){{ :stunnel => false }} + let(:params) { { stunnel: false } } it { is_expected.to compile.with_all_deps } it { is_expected.to create_concat('/etc/rsyncd.conf').that_notifies('Service[rsyncd]') } diff --git a/spec/defines/push_spec.rb b/spec/defines/push_spec.rb index 7360937..a980253 100644 --- a/spec/defines/push_spec.rb +++ b/spec/defines/push_spec.rb @@ -6,7 +6,8 @@ let(:facts) { os_facts } # rsync::retrieve defined type isn't available in this rspec environment - let(:pre_condition) { <<-EOM + let(:pre_condition) do + <<-EOM include "::rsync::server" define rsync::retrieve ( @@ -37,17 +38,19 @@ ) { } EOM - } + end context "on #{os}" do - let(:title){ 'test' } - let(:params){{ - :source_path => 'foo/bar', - :target_path => '/foo/bar', - :rsync_server => 'rsync.bar.baz' - }} + let(:title) { 'test' } + let(:params) do + { + source_path: 'foo/bar', + target_path: '/foo/bar', + rsync_server: 'rsync.bar.baz' + } + end - it { should compile.with_all_deps } + it { is_expected.to compile.with_all_deps } it { is_expected.to create_rsync__retrieve("push_#{title}") } end end diff --git a/spec/defines/retrieve_spec.rb b/spec/defines/retrieve_spec.rb index 629d427..effabdb 100644 --- a/spec/defines/retrieve_spec.rb +++ b/spec/defines/retrieve_spec.rb @@ -5,18 +5,20 @@ on_supported_os.each do |os, os_facts| let(:facts) { os_facts } - let(:pre_condition) { + let(:pre_condition) do 'include "::rsync::server"' - } + end context "on #{os}" do - let(:title){ 'test' } + let(:title) { 'test' } - let(:params){{ - :source_path => 'foo/bar', - :target_path => '/foo/bar', - :rsync_server => 'rsync.bar.baz' - }} + let(:params) do + { + source_path: 'foo/bar', + target_path: '/foo/bar', + rsync_server: 'rsync.bar.baz' + } + end it { is_expected.to compile.with_all_deps } it { is_expected.to create_rsync(title) } diff --git a/spec/defines/server/section_spec.rb b/spec/defines/server/section_spec.rb index 3dfb891..f1daa65 100644 --- a/spec/defines/server/section_spec.rb +++ b/spec/defines/server/section_spec.rb @@ -20,36 +20,40 @@ def mock_selinux_enforcing_facts(os_facts) os_facts end - let(:pre_condition) { + let(:pre_condition) do 'include "::rsync::server"' - } + end context 'with default parameters' do - let(:params) {{ - :path => '/test/dir' - }} + let(:params) do + { + path: '/test/dir' + } + end it { is_expected.to compile.with_all_deps } it { is_expected.to create_concat__fragment("rsync_#{title}.section") } - it { is_expected.to_not create_file("/etc/rsync/#{title}.rsyncd.secrets") } + it { is_expected.not_to create_file("/etc/rsync/#{title}.rsyncd.secrets") } end context 'with user_pass and comment parameters set' do - let(:params) {{ - :path => '/test/dir', - :user_pass => [ 'user1:user1password', 'user2:user2password', 'skipme'], - :comment => 'section TEST' - }} + let(:params) do + { + path: '/test/dir', + user_pass: [ 'user1:user1password', 'user2:user2password', 'skipme'], + comment: 'section TEST' + } + end it { is_expected.to compile.with_all_deps } it do is_expected.to create_file("/etc/rsync/#{title}.rsyncd.secrets").with( - :ensure => 'file', - :owner => 'root', - :group => 'root', - :mode => '0600', - :show_diff => false, - :content => <<-EOM + ensure: 'file', + owner: 'root', + group: 'root', + mode: '0600', + show_diff: false, + content: <<-EOM, user1:user1password user2:user2password EOM @@ -58,13 +62,16 @@ def mock_selinux_enforcing_facts(os_facts) end context 'with auth_users parameter set' do - let(:params) {{ - :path => '/test/dir', - :auth_users => [ 'authuser1', 'authuser2'], - }} + let(:params) do + { + path: '/test/dir', + auth_users: [ 'authuser1', 'authuser2'], + } + end + it { is_expected.to compile.with_all_deps } - it { is_expected.to create_file("/etc/rsync/#{title}.rsyncd.secrets").with_content(/^authuser1:/) } - it { is_expected.to create_file("/etc/rsync/#{title}.rsyncd.secrets").with_content(/^authuser2:/) } + it { is_expected.to create_file("/etc/rsync/#{title}.rsyncd.secrets").with_content(%r{^authuser1:}) } + it { is_expected.to create_file("/etc/rsync/#{title}.rsyncd.secrets").with_content(%r{^authuser2:}) } end end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 1b21aa4..5799a78 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true + # # ------------------------------------------------------------------------------ # NOTICE: **This file is maintained with puppetsync** @@ -90,7 +91,7 @@ def set_hieradata(hieradata) # If nothing else... c.default_facts = { production: { - #:fqdn => 'production.rspec.test.localdomain', + # :fqdn => 'production.rspec.test.localdomain', path: '/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin', concat_basedir: '/tmp' } @@ -151,9 +152,9 @@ def set_hieradata(hieradata) # sanitize hieradata if defined?(hieradata) - set_hieradata(hieradata.gsub(':', '_')) + set_hieradata(hieradata.tr(':', '_')) elsif defined?(class_name) - set_hieradata(class_name.gsub(':', '_')) + set_hieradata(class_name.tr(':', '_')) end end @@ -165,9 +166,7 @@ def set_hieradata(hieradata) end Dir.glob("#{RSpec.configuration.module_path}/*").each do |dir| - begin - Pathname.new(dir).realpath - rescue StandardError - raise "ERROR: The module '#{dir}' is not installed. Tests cannot continue." - end + Pathname.new(dir).realpath +rescue StandardError + raise "ERROR: The module '#{dir}' is not installed. Tests cannot continue." end diff --git a/spec/spec_helper_acceptance.rb b/spec/spec_helper_acceptance.rb index 337f350..7cc3ec7 100644 --- a/spec/spec_helper_acceptance.rb +++ b/spec/spec_helper_acceptance.rb @@ -18,7 +18,6 @@ end end - RSpec.configure do |c| # ensure that environment OS is ready on each host fix_errata_on hosts @@ -32,30 +31,26 @@ # Configure all nodes in nodeset c.before :suite do + # Install modules and dependencies from spec/fixtures/modules + copy_fixture_modules_to(hosts) begin - # Install modules and dependencies from spec/fixtures/modules - copy_fixture_modules_to( hosts ) - begin - server = only_host_with_role(hosts, 'server') - rescue ArgumentError =>e - server = only_host_with_role(hosts, 'default') - end - - # Generate and install PKI certificates on each SUT - Dir.mktmpdir do |cert_dir| - run_fake_pki_ca_on(server, hosts, cert_dir ) - hosts.each{ |sut| copy_pki_to( sut, cert_dir, '/etc/pki/simp-testing' )} - end + server = only_host_with_role(hosts, 'server') + rescue ArgumentError => e + server = only_host_with_role(hosts, 'default') + end - # add PKI keys - copy_keydist_to(server) - rescue StandardError, ScriptError => e - if ENV['PRY'] - require 'pry'; binding.pry - else - raise e - end + # Generate and install PKI certificates on each SUT + Dir.mktmpdir do |cert_dir| + run_fake_pki_ca_on(server, hosts, cert_dir) + hosts.each { |sut| copy_pki_to(sut, cert_dir, '/etc/pki/simp-testing') } end + + # add PKI keys + copy_keydist_to(server) + rescue StandardError, ScriptError => e + raise e unless ENV['PRY'] + require 'pry' + binding.pry end end @@ -65,10 +60,10 @@ def get_private_network_interface(host) # remove interfaces we know are not the private network interface interfaces.delete_if do |ifc| ifc == 'lo' or - ifc.include?('ip_') or # IPsec tunnel - ifc == 'enp0s3' or # public interface for puppetlabs/centos-7.2-64-nocm virtual box - ifc == 'eth0' # public interface for centos/7 virtual box + ifc.include?('ip_') or # IPsec tunnel + ifc == 'enp0s3' or # public interface for puppetlabs/centos-7.2-64-nocm virtual box + ifc == 'eth0' # public interface for centos/7 virtual box end - fail("Could not determine the interface for the #{host}'s private network") unless interfaces.size == 1 + raise("Could not determine the interface for the #{host}'s private network") unless interfaces.size == 1 interfaces[0] end diff --git a/spec/unit/compliance_engine/compliance_engine_enforce_spec.rb b/spec/unit/compliance_engine/compliance_engine_enforce_spec.rb index 2f7ccd6..c802a3e 100644 --- a/spec/unit/compliance_engine/compliance_engine_enforce_spec.rb +++ b/spec/unit/compliance_engine/compliance_engine_enforce_spec.rb @@ -7,10 +7,9 @@ # This is the class that needs to be added to the catalog last to make the # reporting work. describe 'compliance_markup', type: :class do - compliance_profiles = [ 'disa_stig', - 'nist_800_53:rev4' + 'nist_800_53:rev4', ] # A list of classes that we expect to be included for compliance @@ -19,14 +18,14 @@ # defaults expected_classes = [ 'rsync', - 'rsync::server' + 'rsync::server', ] allowed_failures = { 'documented_missing_parameters' => [ - ] + expected_classes.map{|c| Regexp.new("^(?!#{c}(::.*)?)")}, + ] + expected_classes.map { |c| Regexp.new("^(?!#{c}(::.*)?)") }, 'documented_missing_resources' => [ - ] + expected_classes.map{|c| Regexp.new("^(?!#{c}(::.*)?)")} + ] + expected_classes.map { |c| Regexp.new("^(?!#{c}(::.*)?)") } } on_supported_os.each do |os, os_facts| @@ -35,8 +34,8 @@ context "with compliance profile '#{target_profile}'" do let(:facts) do _facts = os_facts.merge({ - :target_compliance_profile => target_profile - }) + target_compliance_profile: target_profile + }) _facts[:os] ||= {} _facts[:os]['selinux'] ||= {} @@ -44,34 +43,34 @@ _facts end - - let(:pre_condition) {%( - #{expected_classes.map{|c| %{include #{c}}}.join("\n")} - )} - - let(:hieradata){ 'compliance-engine' } - - it { is_expected.to compile } - - let(:compliance_report) { - @compliance_report ||= JSON.load( - catalogue.resource("File[#{facts[:puppet_vardir]}/compliance_report.json]")[:content] + let(:compliance_report) do + @compliance_report ||= JSON.parse( + catalogue.resource("File[#{facts[:puppet_vardir]}/compliance_report.json]")[:content], ) @compliance_report - } - - let(:compliance_profile_data) { + end + let(:compliance_profile_data) do @compliance_profile_data ||= compliance_report['compliance_profiles'][target_profile] @compliance_profile_data - } + end + + let(:pre_condition) do + %( + #{expected_classes.map { |c| %(include #{c}) }.join("\n")} + ) + end + + let(:hieradata) { 'compliance-engine' } + + it { is_expected.to compile } - it 'should have a compliance profile report' do - expect(compliance_profile_data).to_not be_nil + it 'has a compliance profile report' do + expect(compliance_profile_data).not_to be_nil end - it 'should have a 100% compliant report' do + it 'has a 100% compliant report' do expect(compliance_profile_data['summary']['percent_compliant']).to eq(100) end @@ -91,29 +90,29 @@ # classes included, this report may be useless and is disabled by # default. # - 'documented_missing_resources' + 'documented_missing_resources', ] report_validators.each do |report_section| - it "should have no issues with the '#{report_section}' report" do + it "has no issues with the '#{report_section}' report" do if compliance_profile_data[report_section] # This just gets us a good print out of what went wrong - compliance_profile_data[report_section].delete_if{ |item| - rm = false - - Array(allowed_failures[report_section]).each do |allowed| - if allowed.is_a?(Regexp) - if allowed.match?(item) - rm = true - break - end - else - rm = (allowed == item) + compliance_profile_data[report_section].delete_if do |item| + rm = false + + Array(allowed_failures[report_section]).each do |allowed| + if allowed.is_a?(Regexp) + if allowed.match?(item) + rm = true + break end + else + rm = (allowed == item) end + end - rm - } + rm + end expect(compliance_profile_data[report_section]).to eq([]) end