From a95a22f1e0422f82f038eb3345fc72e95f0f8d47 Mon Sep 17 00:00:00 2001 From: Craig Gumbley Date: Mon, 26 Sep 2022 10:19:42 +0100 Subject: [PATCH 01/16] (MAINT) Add CI workflow Prior to this commit puppet-strings relied on travis for ci. We have since moved away from travis and use github actions. This commit creates a new ci.yml workflow that runs on: * A nightly cron * pull request to main * workflow_dispatch --- .github/workflows/ci.yml | 81 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 .github/workflows/ci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..7fc9f32e7 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,81 @@ +name: "ci" + +on: + schedule: + - cron: "0 0 * * *" + workflow_dispatch: + pull_request: + branches: + - "main" + +jobs: + spec: + name: "spec" + runs-on: "ubuntu-latest" + + steps: + + - name: "checkout" + uses: "actions/checkout@v3" + + - name: "setup ruby" + uses: ruby/setup-ruby@v1 + with: + ruby-version: "2.7" + bundler-cache: true + + - name: "bundle environment" + run: | + echo ::group::bundler environment + bundle env + echo ::endgroup:: + + - name: "rubocop" + run : | + bundle exec rubocop + + - name: "spec" + run: | + bundle exec rake spec + + acceptance: + name: "acceptance" + runs-on: "ubuntu-latest" + needs: "spec" + strategy: + matrix: + puppet: ["puppet6", "puppet7"] + + steps: + + - name: "checkout" + uses: "actions/checkout@v3" + + - name: "setup ruby" + uses: ruby/setup-ruby@v1 + with: + ruby-version: "2.7" + bundler-cache: true + + - name: "bundle environment" + run: | + echo ::group::bundler environment + bundle env + echo ::endgroup:: + + - name: "provision" + run: | + bundle exec rake 'litmus:provision[docker, ubuntu]' + + - name: "install agent" + run: | + bundle exec rake 'litmus:install_agent[${{ matrix.puppet }}]' + + - name: "install module" + run: | + bundle exec rake 'litmus:install_modules_from_directory[./spec/fixtures/acceptance/modules]' + bundle exec rake litmus:install_gems + + - name: "execute tests" + run: | + bundle exec rake litmus:acceptance:parallel From 491b72f59c565e93b899a7f280bf487a147c69f4 Mon Sep 17 00:00:00 2001 From: Craig Gumbley Date: Mon, 26 Sep 2022 10:22:44 +0100 Subject: [PATCH 02/16] (MAINT) Remove travis This commit removes the legacy travis workflow from this repository --- .travis.yml | 40 ---------------------------------------- 1 file changed, 40 deletions(-) delete mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index c15cf786b..000000000 --- a/.travis.yml +++ /dev/null @@ -1,40 +0,0 @@ ---- -os: linux -dist: xenial -language: ruby - -bundler_args: --without development acceptance - -notifications: - email: false - -before_install: - - gem update bundler - -script: 'SPEC_OPTS="--format documentation" COVERAGE="yes" bundle exec rake $CHECK' - -jobs: - fast_finish: true - include: - - rvm: 2.5 - env: PUPPET_GEM_VERSION="~> 6" CHECK=spec - - rvm: 2.7 - env: PUPPET_GEM_VERSION="~> 7" CHECK=spec - - bundler_args: "" - rvm: 2.5 - before_script: - - bundle exec rake 'litmus:provision[docker, centos:7]' - - bundle exec rake 'litmus:install_agent[puppet6]' - - bundle exec rake 'litmus:install_modules_from_directory[./spec/fixtures/acceptance/modules]' - - bundle exec rake litmus:install_gems - script: - - bundle exec rake litmus:acceptance:parallel - - bundler_args: "" - rvm: 2.7 - before_script: - - bundle exec rake 'litmus:provision[docker, centos:7]' - - bundle exec rake 'litmus:install_agent[puppet7]' - - bundle exec rake 'litmus:install_modules_from_directory[./spec/fixtures/acceptance/modules]' - - bundle exec rake litmus:install_gems - script: - - bundle exec rake litmus:acceptance:parallel From ab6125e4db7686b9f8a78ced3d00837413ec849f Mon Sep 17 00:00:00 2001 From: Craig Gumbley Date: Mon, 26 Sep 2022 10:35:29 +0100 Subject: [PATCH 03/16] (MAINT) Remove version constraints on rubocop Prior to this commit Rubocop was constrained to an older version. This was causing cop errors when executed with newer rubies. This commit removes the version constraint from the Gemfile and bumps the target ruby version in rubocops config to 2.5 which is the current minimum supported version. --- .rubocop.yml | 6 +++--- Gemfile | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.rubocop.yml b/.rubocop.yml index 4b2266fde..557685c6d 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -29,7 +29,7 @@ Lint/ElseLayout: Lint/UnreachableCode: Enabled: true -Lint/UselessComparison: +Lint/BinaryOperatorWithIdenticalOperands: Enabled: true # MAYBE useful - no return inside ensure block. @@ -201,7 +201,7 @@ Style/WordArray: Style/RedundantPercentQ: Enabled: false -Layout/Tab: +Layout/IndentationStyle: Enabled: false Layout/SpaceBeforeSemicolon: @@ -511,7 +511,7 @@ Layout/MultilineMethodCallBraceLayout: Layout/MultilineBlockLayout: Enabled: false -Lint/UselessAssignment: +Lint/BinaryOperatorWithIdenticalOperands: Enabled: false Lint/DuplicateMethods: diff --git a/Gemfile b/Gemfile index b1fe82ea5..7795b4a49 100644 --- a/Gemfile +++ b/Gemfile @@ -36,7 +36,7 @@ group :development do gem 'pry-byebug' end -gem 'rubocop', '~> 0.81.0' # Requires work to upgrade +gem 'rubocop' gem 'rubocop-rspec' gem 'rubocop-performance' From 13495b89d519703aa0343fe3d85e00f518180ce1 Mon Sep 17 00:00:00 2001 From: Craig Gumbley Date: Mon, 26 Sep 2022 11:30:19 +0100 Subject: [PATCH 04/16] (MAINT) Standardise rubocop configs Prior to this commit the rubocop config in this repository differed from configs used across the modules ecosystem. This commit attempts to align the config and versions used. --- .rubocop.yml | 766 +++++++++++++++++++++------------------------- .rubocop_todo.yml | 71 ----- Gemfile | 6 +- 3 files changed, 345 insertions(+), 498 deletions(-) delete mode 100644 .rubocop_todo.yml diff --git a/.rubocop.yml b/.rubocop.yml index 557685c6d..85aac0a87 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,601 +1,519 @@ -require: rubocop-performance -inherit_from: .rubocop_todo.yml - +--- +require: +- rubocop-performance +- rubocop-rspec AllCops: - TargetRubyVersion: 2.5 + DisplayCopNames: true + TargetRubyVersion: '2.5' + Include: + - "**/*.rb" Exclude: - # Ignore HTML related things - - '**/*.erb' - - 'lib/puppet-strings/yard/templates/**/*' - # Ignore fixtures we do not control - - spec/fixtures/modules/**/* - - spec/fixtures/ruby/**/* - - -# DISABLED - not useful -Bundler/OrderedGems: - Enabled: false - -# DISABLED - Doesn't understand conditionals that result in different versions of a gem. -Bundler/DuplicatedGem: - Enabled: false - -Layout/ConditionPosition: + - bin/* + - ".vendor/**/*" + - "**/Gemfile" + - "**/Rakefile" + - pkg/**/* + - spec/fixtures/**/* + - vendor/**/* + - "**/Puppetfile" + - "**/Vagrantfile" + - "**/Guardfile" + - '**/*.erb' + - 'lib/puppet-strings/yard/templates/**/*' +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 +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: + - 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 - -Lint/ElseLayout: +Performance/MethodObjectAsBlock: Enabled: true - -Lint/UnreachableCode: +Performance/RedundantSortBlock: Enabled: true - -Lint/BinaryOperatorWithIdenticalOperands: +Performance/RedundantStringChars: Enabled: true - -# MAYBE useful - no return inside ensure block. -Lint/EnsureReturn: +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/InsecureProtocolSource: Enabled: false - -# MAYBE useful - errors when rescue {} happens. -Lint/SuppressedException: +Gemspec/DuplicatedAssignment: Enabled: false - -# MAYBE useful - but too many instances -Lint/ShadowingOuterLocalVariable: +Gemspec/OrderedDependencies: Enabled: false - -# Can catch complicated strings. -Lint/LiteralInInterpolation: - Enabled: true - -# DISABLED really useless. Detects return as last statement. -Style/RedundantReturn: +Gemspec/RequiredRubyVersion: Enabled: false - -# DISABLED since the instances do not seem to indicate any specific errors. -Lint/AmbiguousOperator: +Gemspec/RubyVersionGlobalsUsage: Enabled: false - -Lint/AssignmentInCondition: - Enabled: true - -# DISABLED - not useful -Layout/SpaceBeforeComment: +Layout/ArgumentAlignment: Enabled: false - -# DISABLED - not useful -Style/HashSyntax: +Layout/BeginEndAlignment: Enabled: false - -# USES: as shortcut for non nil&valid checking a = x() and a.empty? -# DISABLED - not useful -Style/AndOr: +Layout/ClosingHeredocIndentation: Enabled: false - -# DISABLED - not useful -Style/RedundantSelf: +Layout/EmptyComment: Enabled: false - -# DISABLED - not useful -Metrics/MethodLength: +Layout/EmptyLineAfterGuardClause: Enabled: false - -Metrics/ModuleLength: +Layout/EmptyLinesAroundArguments: Enabled: false - -# DISABLED - not useful -Style/WhileUntilModifier: +Layout/EmptyLinesAroundAttributeAccessor: Enabled: false - -# DISABLED -Security/Eval: +Layout/EndOfLine: Enabled: false - -# DISABLED - the offender is just haskell envy -Lint/AmbiguousRegexpLiteral: +Layout/FirstArgumentIndentation: Enabled: false - -# DISABLED -Layout/BlockAlignment: +Layout/HashAlignment: Enabled: false - -# DISABLED -Layout/DefEndAlignment: +Layout/HeredocIndentation: Enabled: false - -# DISABLED -Layout/EndAlignment: +Layout/LeadingEmptyLines: Enabled: false - -# DISABLED -Lint/DeprecatedClassMethods: +Layout/SpaceAroundMethodCallOperator: Enabled: false - -# DISABLED -Lint/Loop: +Layout/SpaceInsideArrayLiteralBrackets: Enabled: false - -# DISABLED -Lint/ParenthesesAsGroupedExpression: +Layout/SpaceInsideReferenceBrackets: Enabled: false - -Lint/RescueException: +Lint/BigDecimalNew: Enabled: false - -Lint/RedundantStringCoercion: +Lint/BooleanSymbol: Enabled: false - -Lint/UnusedBlockArgument: +Lint/ConstantDefinitionInBlock: Enabled: false - -Lint/UnusedMethodArgument: +Lint/DeprecatedOpenSSLConstant: Enabled: false - -Lint/UselessAccessModifier: - Enabled: true - -Lint/Void: - Enabled: true - -Layout/AccessModifierIndentation: +Lint/DisjunctiveAssignmentInConstructor: Enabled: false - -Naming/AccessorMethodName: +Lint/DuplicateElsifCondition: Enabled: false - -Style/Alias: +Lint/DuplicateRequire: Enabled: false - -Layout/ArrayAlignment: +Lint/DuplicateRescueException: Enabled: false - -Layout/HashAlignment: +Lint/EmptyConditionalBody: Enabled: false - -Layout/ParameterAlignment: +Lint/EmptyFile: Enabled: false - -Metrics/BlockNesting: +Lint/ErbNewArguments: Enabled: false - -Style/AsciiComments: +Lint/FloatComparison: Enabled: false - -Style/Attr: +Lint/HashCompareByIdentity: Enabled: false - -Style/CaseEquality: +Lint/IdentityComparison: Enabled: false - -Layout/CaseIndentation: +Lint/InterpolationCheck: Enabled: false - -Style/CharacterLiteral: +Lint/MissingCopEnableDirective: Enabled: false - -Naming/ClassAndModuleCamelCase: +Lint/MixedRegexpCaptureTypes: Enabled: false - -Style/ClassAndModuleChildren: +Lint/NestedPercentLiteral: Enabled: false - -Style/ClassCheck: +Lint/NonDeterministicRequireOrder: Enabled: false - -Metrics/ClassLength: +Lint/OrderedMagicComments: Enabled: false - -Style/ClassMethods: +Lint/OutOfRangeRegexpRef: Enabled: false - -Style/ClassVars: +Lint/RaiseException: Enabled: false - -Style/WhenThen: +Lint/RedundantCopEnableDirective: Enabled: false - -# DISABLED - not useful -Style/WordArray: +Lint/RedundantRequireStatement: Enabled: false - -Style/RedundantPercentQ: +Lint/RedundantSafeNavigation: Enabled: false - -Layout/IndentationStyle: +Lint/RedundantWithIndex: Enabled: false - -Layout/SpaceBeforeSemicolon: +Lint/RedundantWithObject: Enabled: false - -Layout/TrailingEmptyLines: +Lint/RegexpAsCondition: Enabled: false - -Layout/SpaceInsideBlockBraces: +Lint/ReturnInVoidContext: Enabled: false - -Layout/SpaceInsideHashLiteralBraces: +Lint/SafeNavigationConsistency: Enabled: false - -Layout/SpaceInsideParens: +Lint/SafeNavigationWithEmpty: Enabled: false - -Layout/LeadingCommentSpace: +Lint/SelfAssignment: Enabled: false - -Layout/SpaceBeforeFirstArg: +Lint/SendWithMixinArgument: Enabled: false - -Layout/SpaceAfterColon: +Lint/ShadowedArgument: Enabled: false - -Layout/SpaceAfterComma: +Lint/StructNewOverride: Enabled: false - -Layout/SpaceAroundKeyword: +Lint/ToJSON: Enabled: false - -Layout/SpaceAfterMethodName: +Lint/TopLevelReturnWithArgument: Enabled: false - -Layout/SpaceAfterNot: +Lint/TrailingCommaInAttributeDeclaration: Enabled: false - -Layout/SpaceAfterSemicolon: +Lint/UnreachableLoop: Enabled: false - -Layout/SpaceAroundEqualsInParameterDefault: +Lint/UriEscapeUnescape: Enabled: false - -Layout/SpaceAroundOperators: +Lint/UriRegexp: Enabled: false - -Layout/SpaceBeforeBlockBraces: +Lint/UselessMethodDefinition: Enabled: false - -Layout/SpaceBeforeComma: +Lint/UselessTimes: Enabled: false - -Style/CollectionMethods: +Metrics/AbcSize: Enabled: false - -Layout/CommentIndentation: +Metrics/BlockLength: Enabled: false - -Style/ColonMethodCall: +Metrics/BlockNesting: Enabled: false - -Style/CommentAnnotation: +Metrics/ClassLength: Enabled: false - Metrics/CyclomaticComplexity: Enabled: false - -Naming/ConstantName: +Metrics/MethodLength: Enabled: false - -Style/Documentation: +Metrics/ModuleLength: Enabled: false - -Style/DefWithParentheses: +Metrics/ParameterLists: Enabled: false - -Layout/DotPosition: +Metrics/PerceivedComplexity: Enabled: false - -# DISABLED - used for converting to bool -Style/DoubleNegation: +Migration/DepartmentName: Enabled: false - -Style/EachWithObject: +Naming/AccessorMethodName: Enabled: false - -Layout/EmptyLineBetweenDefs: +Naming/BlockParameterName: Enabled: false - -Layout/FirstArrayElementIndentation: +Naming/HeredocDelimiterCase: Enabled: false - -Layout/FirstHashElementIndentation: +Naming/HeredocDelimiterNaming: Enabled: false - -Layout/IndentationConsistency: - Enabled: true - -Layout/IndentationWidth: - Enabled: true - -Layout/EmptyLines: +Naming/MemoizedInstanceVariableName: Enabled: false - -Layout/EmptyLinesAroundAccessModifier: +Naming/MethodParameterName: Enabled: false - -Style/EmptyLiteral: +Naming/RescuedExceptionsVariableName: Enabled: false - -Layout/LineLength: +Naming/VariableNumber: Enabled: false - -Style/MethodCallWithoutArgsParentheses: +Performance/BindCall: Enabled: false - -Style/MethodDefParentheses: +Performance/DeletePrefix: Enabled: false - -Style/LineEndConcatenation: +Performance/DeleteSuffix: Enabled: false - -Layout/TrailingWhitespace: +Performance/InefficientHashSearch: Enabled: false - -Style/StringLiterals: +Performance/UnfreezeString: Enabled: false - -Style/TrailingCommaInArrayLiteral: +Performance/UriDefaultParser: Enabled: false - -Style/TrailingCommaInHashLiteral: +RSpec/Be: Enabled: false - -Style/TrailingCommaInArguments: +RSpec/Capybara/CurrentPathExpectation: Enabled: false - -Style/GlobalVars: +RSpec/Capybara/FeatureMethods: Enabled: false - -Style/GuardClause: +RSpec/Capybara/VisibilityMatcher: Enabled: false - -Style/IfUnlessModifier: +RSpec/ContextMethod: Enabled: false - -Style/MultilineIfThen: +RSpec/ContextWording: Enabled: false - -Style/NegatedIf: +RSpec/DescribeClass: Enabled: false - -Style/NegatedWhile: +RSpec/EmptyHook: Enabled: false - -Style/Next: +RSpec/EmptyLineAfterExample: Enabled: false - -Style/SingleLineBlockParams: +RSpec/EmptyLineAfterExampleGroup: Enabled: false - -Style/SingleLineMethods: +RSpec/EmptyLineAfterHook: Enabled: false - -Style/SpecialGlobalVars: +RSpec/ExampleLength: Enabled: false - -Style/TrivialAccessors: +RSpec/ExampleWithoutDescription: Enabled: false - -Style/UnlessElse: +RSpec/ExpectChange: Enabled: false - -Style/VariableInterpolation: +RSpec/ExpectInHook: Enabled: false - -Naming/VariableName: +RSpec/FactoryBot/AttributeDefinedStatically: Enabled: false - -Style/WhileUntilDo: +RSpec/FactoryBot/CreateList: Enabled: false - -Style/EvenOdd: +RSpec/FactoryBot/FactoryClassName: Enabled: false - -Naming/FileName: +RSpec/FilePath: Enabled: false - -Style/For: +RSpec/HooksBeforeExamples: Enabled: false - -Style/Lambda: +RSpec/ImplicitBlockExpectation: Enabled: false - -Naming/MethodName: +RSpec/ImplicitSubject: Enabled: false - -Style/MultilineTernaryOperator: +RSpec/LeakyConstantDeclaration: Enabled: false - -Style/NestedTernaryOperator: +RSpec/LetBeforeExamples: Enabled: false - -Style/NilComparison: +RSpec/MissingExampleGroupArgument: Enabled: false - -Style/FormatString: +RSpec/MultipleExpectations: Enabled: false - -Style/MultilineBlockChain: +RSpec/MultipleMemoizedHelpers: Enabled: false - -Style/Semicolon: +RSpec/MultipleSubjects: Enabled: false - -Style/SignalException: +RSpec/NestedGroups: Enabled: false - -Style/NonNilCheck: +RSpec/PredicateMatcher: Enabled: false - -Style/Not: +RSpec/ReceiveCounts: Enabled: false - -Style/NumericLiterals: +RSpec/ReceiveNever: Enabled: false - -Style/NumericPredicate: +RSpec/RepeatedExampleGroupBody: Enabled: false - -Style/OneLineConditional: +RSpec/RepeatedExampleGroupDescription: Enabled: false - -Naming/BinaryOperatorParameterName: +RSpec/RepeatedIncludeExample: Enabled: false - -Style/ParenthesesAroundCondition: +RSpec/ReturnFromStub: Enabled: false - -Style/PercentLiteralDelimiters: +RSpec/SharedExamples: Enabled: false - -Style/PerlBackrefs: +RSpec/StubbedMock: Enabled: false - -Naming/PredicateName: +RSpec/UnspecifiedException: Enabled: false - -Style/RedundantException: +RSpec/VariableDefinition: Enabled: false - -Style/SelfAssignment: +RSpec/VoidExpect: Enabled: false - -Style/Proc: +RSpec/Yield: Enabled: false - -Style/RaiseArgs: +Security/Open: Enabled: false - -Style/RedundantBegin: +Style/AccessModifierDeclarations: Enabled: false - -Style/RescueModifier: +Style/AccessorGrouping: Enabled: false - -Style/RegexpLiteral: +Style/AsciiComments: Enabled: false - -Lint/UnderscorePrefixedVariableName: +Style/BisectedAttrAccessor: Enabled: false - -Metrics/ParameterLists: +Style/CaseLikeIf: + Enabled: false +Style/ClassEqualityComparison: + Enabled: false +Style/ColonMethodDefinition: Enabled: false - -Lint/RequireParentheses: +Style/CombinableLoops: Enabled: false - -Style/ModuleFunction: +Style/CommentedKeyword: Enabled: false - -Lint/Debugger: +Style/Dir: Enabled: false - -Style/IfWithSemicolon: +Style/DoubleCopDisableDirective: + Enabled: false +Style/EmptyBlockParameter: + Enabled: false +Style/EmptyLambdaParameter: Enabled: false - Style/Encoding: Enabled: false - -Layout/MultilineOperationIndentation: +Style/EvalWithLocation: Enabled: false - -Style/BlockDelimiters: +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 - -Layout/ExtraSpacing: +Style/OptionalBooleanParameter: Enabled: false - -Layout/MultilineHashBraceLayout: +Style/OrAssignment: Enabled: false - -Layout/MultilineMethodCallBraceLayout: +Style/RandomWithOffset: Enabled: false - -Layout/MultilineBlockLayout: +Style/RedundantAssignment: Enabled: false - -Lint/BinaryOperatorWithIdenticalOperands: +Style/RedundantCondition: Enabled: false - -Lint/DuplicateMethods: +Style/RedundantConditional: Enabled: false - -Layout/EmptyLinesAroundMethodBody: +Style/RedundantFetchBlock: Enabled: false - -Layout/EmptyLinesAroundModuleBody: +Style/RedundantFileExtensionInRequire: Enabled: false - -Layout/EmptyLinesAroundBlockBody: +Style/RedundantRegexpCharacterClass: Enabled: false - -Layout/EmptyLinesAroundClassBody: +Style/RedundantRegexpEscape: Enabled: false - -Style/RedundantInterpolation: +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/ConditionalAssignment: +Style/TrailingBodyOnClass: Enabled: false - -Style/ZeroLengthPredicate: +Style/TrailingBodyOnMethodDefinition: Enabled: false - -Style/TrailingUnderscoreVariable: +Style/TrailingBodyOnModule: Enabled: false - -Style/StringLiteralsInInterpolation: +Style/TrailingCommaInHashLiteral: Enabled: false - -Style/RedundantParentheses: +Style/TrailingMethodEndStatement: Enabled: false - -Style/MutableConstant: +Style/UnpackFirst: Enabled: false - -Performance/RedundantMatch: +Lint/DuplicateBranch: Enabled: false - -Performance/FlatMap: +Lint/DuplicateRegexpCharacterClassElement: Enabled: false - -Performance/StringReplacement: +Lint/EmptyBlock: Enabled: false - -Metrics/AbcSize: +Lint/EmptyClass: Enabled: false - -Metrics/PerceivedComplexity: +Lint/NoReturnInBeginEndBlocks: Enabled: false - -Metrics/BlockLength: +Lint/ToEnumArguments: Enabled: false - -Naming/VariableNumber: +Lint/UnexpectedBlockArity: Enabled: false - -# Enforce LF line endings, even when on Windows -Layout/EndOfLine: - EnforcedStyle: lf - -Layout/HeredocIndentation: # Not appicable on Ruby 2.1 +Lint/UnmodifiedReduceAccumulator: + Enabled: false +Performance/CollectionLiteralInLoop: + Enabled: false +Style/ArgumentsForwarding: + Enabled: false +Style/CollectionCompact: + Enabled: false +Style/DocumentDynamicEvalDefinition: + Enabled: false +Style/NegatedIfElseCondition: + Enabled: false +Style/NilLambda: + Enabled: false +Style/RedundantArgument: + Enabled: false +Style/SwapValues: Enabled: false - -Lint/RaiseException: - Enabled: true - -Lint/StructNewOverride: - Enabled: true - -Style/HashEachMethods: - Enabled: true - -Style/HashTransformKeys: - Enabled: false # requires Ruby 2.5 - -Style/HashTransformValues: - Enabled: false # requires Ruby 2.4 - -Naming/MethodParameterName: - Enabled: true - AllowedNames: [ o ] diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml deleted file mode 100644 index d897ebb74..000000000 --- a/.rubocop_todo.yml +++ /dev/null @@ -1,71 +0,0 @@ -# This configuration was generated by -# `rubocop --auto-gen-config` -# on 2019-06-19 16:03:20 +0800 using RuboCop version 0.57.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: Include, TreatCommentsAsGroupSeparators. -# Include: **/*.gemspec -Gemspec/OrderedDependencies: - Exclude: - - 'puppet-strings.gemspec' - -# Offense count: 108 -# Cop supports --auto-correct. -Layout/ClosingHeredocIndentation: - Enabled: false - -# Offense count: 5 -# Configuration parameters: Denylist. -# Denylist: (?-mix:(^|\s)(EO[A-Z]{1}|END)(\s|$)) -Naming/HeredocDelimiterNaming: - Exclude: - - 'spec/acceptance/generate_markdown_spec.rb' - - 'spec/acceptance/lib/util.rb' - -# Offense count: 2 -# Configuration parameters: EnforcedStyle. -# SupportedStyles: inline, group -Style/AccessModifierDeclarations: - Exclude: - - 'spec/acceptance/lib/util.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -Style/ExpandPathArguments: - Exclude: - - 'puppet-strings.gemspec' - -# Offense count: 6 -# Configuration parameters: EnforcedStyle. -# SupportedStyles: annotated, template, unannotated -Style/FormatStringToken: - Exclude: - - 'lib/puppet-strings/describe.rb' - - 'lib/puppet-strings/yard.rb' - -# Offense count: 3 -Style/MixinUsage: - Exclude: - - 'spec/acceptance/emit_json_options.rb' - - 'spec/acceptance/generate_markdown_spec.rb' - - 'spec/acceptance/running_strings_generate.rb' - -# Offense count: 3 -Style/MultipleComparison: - Exclude: - - 'lib/puppet-strings/yard/handlers/ruby/function_handler.rb' - - 'lib/puppet-strings/yard/handlers/ruby/provider_handler.rb' - - 'lib/puppet-strings/yard/handlers/ruby/type_handler.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: . -# SupportedStyles: percent, brackets -Style/SymbolArray: - EnforcedStyle: percent - MinSize: 5 diff --git a/Gemfile b/Gemfile index 7795b4a49..7451d7a06 100644 --- a/Gemfile +++ b/Gemfile @@ -36,9 +36,9 @@ group :development do gem 'pry-byebug' end -gem 'rubocop' -gem 'rubocop-rspec' -gem 'rubocop-performance' +gem 'rubocop', '~> 1.6.1' +gem 'rubocop-rspec', '~> 2.0.1' +gem 'rubocop-performance', '~> 1.9.1' # Evaluate Gemfile.local if it exists if File.exists? "#{__FILE__}.local" From a613e6915764632f0a3b25c684fa06e75244bd3b Mon Sep 17 00:00:00 2001 From: Craig Gumbley Date: Wed, 28 Sep 2022 09:53:29 +0100 Subject: [PATCH 05/16] (MAINT) Rubocop - (spec) fixes for acceptance --- spec/acceptance/emit_json_options_spec.rb | 80 ++++++++------- spec/acceptance/generate_markdown_spec.rb | 19 ++-- .../running_strings_generate_spec.rb | 98 ++++++++++--------- 3 files changed, 103 insertions(+), 94 deletions(-) diff --git a/spec/acceptance/emit_json_options_spec.rb b/spec/acceptance/emit_json_options_spec.rb index 12a3e4587..a66faf967 100644 --- a/spec/acceptance/emit_json_options_spec.rb +++ b/spec/acceptance/emit_json_options_spec.rb @@ -3,66 +3,70 @@ require 'spec_helper_acceptance' describe 'Emitting JSON' do - before(:all) do - @test_module_path = sut_module_path(/Module test/) - @remote_tmp_path = sut_tmp_path + let(:test_module_path) do + sut_module_path(%r{Module test}) + end + + let(:remote_tmp_path) do + sut_tmp_path end let(:expected) do { - "puppet_classes" => [], - "data_types" => [], - "data_type_aliases" => [], - "defined_types" => [], - "resource_types" => [], - "providers" => [], - "puppet_functions" => [ - "name" => "function3x", - "file" => "#{@test_module_path}/lib/puppet/parser/functions/function3x.rb", - "line" => 3, - "type" => "ruby3x", - "signatures" => [ + 'puppet_classes' => [], + 'data_types' => [], + 'data_type_aliases' => [], + 'defined_types' => [], + 'resource_types' => [], + 'providers' => [], + 'puppet_functions' => [ + 'name' => 'function3x', + 'file' => "#{test_module_path}/lib/puppet/parser/functions/function3x.rb", + 'line' => 3, + 'type' => 'ruby3x', + 'signatures' => [ { - "signature" =>"function3x()", - "docstring" => { - "text" => "This is the function documentation for `function3x`", - "tags" => [ + 'signature' => 'function3x()', + 'docstring' => { + 'text' => 'This is the function documentation for `function3x`', + 'tags' => [ { - "tag_name"=>"return", - "text"=>"", - "types"=>["Any"] - } + 'tag_name' => 'return', + 'text' => '', + 'types' => ['Any'] + }, ] } }, ], - "docstring" => { - "text" => "This is the function documentation for `function3x`", - "tags" => ["tag_name" => "return", "text" => "", "types" => ["Any"]]}, - "source" => "Puppet::Parser::Functions.newfunction(:function3x, :doc => \"This is the function documentation for `function3x`\") do |args|\nend" + 'docstring' => { + 'text' => 'This is the function documentation for `function3x`', + 'tags' => ['tag_name' => 'return', 'text' => '', 'types' => ['Any']] + }, + 'source' => "Puppet::Parser::Functions.newfunction(:function3x, :doc => \"This is the function documentation for `function3x`\") do |args|\nend", ], - "puppet_tasks" => [], - "puppet_plans" => [] + 'puppet_tasks' => [], + 'puppet_plans' => [] } end [ - { :title => '--format json and STDOUT', :cmd_line => '--format json' }, - { :title => '--emit-json-stdout', :cmd_line => '--emit-json-stdout' } + { title: '--format json and STDOUT', cmd_line: '--format json' }, + { title: '--emit-json-stdout', cmd_line: '--emit-json-stdout' }, ].each do |testcase| - it "should emit JSON to stdout when using #{testcase[:title]}" do - output = run_shell("puppet strings generate #{testcase[:cmd_line]} \"#{@test_module_path}/lib/puppet/parser/functions/function3x.rb\"").stdout.chomp + it "emits JSON to stdout when using #{testcase[:title]}" do + output = run_shell("puppet strings generate #{testcase[:cmd_line]} \"#{test_module_path}/lib/puppet/parser/functions/function3x.rb\"").stdout.chomp expect(JSON.parse(output)).to eq(expected) end end [ - { :title => '--format json and --out', :cmd_line => '--format json --out "TMPFILE"' }, - { :title => '--emit-json', :cmd_line => '--emit-json "TMPFILE"' }, + { title: '--format json and --out', cmd_line: '--format json --out "TMPFILE"' }, + { title: '--emit-json', cmd_line: '--emit-json "TMPFILE"' }, ].each do |testcase| - it "should write JSON to a file when using #{testcase[:title]}" do - tmpfile = File.join(@remote_tmp_path, 'json_output.json') - cmd = "puppet strings generate #{testcase[:cmd_line].gsub('TMPFILE', tmpfile)} \"#{@test_module_path}/lib/puppet/parser/functions/function3x.rb\"" + it "writes JSON to a file when using #{testcase[:title]}" do + tmpfile = File.join(remote_tmp_path, 'json_output.json') + cmd = "puppet strings generate #{testcase[:cmd_line].gsub('TMPFILE', tmpfile)} \"#{test_module_path}/lib/puppet/parser/functions/function3x.rb\"" run_shell(cmd) output = JSON.parse(file(tmpfile).content) expect(output).to eq(expected) diff --git a/spec/acceptance/generate_markdown_spec.rb b/spec/acceptance/generate_markdown_spec.rb index 71a488c50..d7a257864 100644 --- a/spec/acceptance/generate_markdown_spec.rb +++ b/spec/acceptance/generate_markdown_spec.rb @@ -3,9 +3,12 @@ require 'spec_helper_acceptance' describe 'Generating Markdown' do - before(:all) do - @test_module_path = sut_module_path(/Module test/) - @remote_tmp_path = sut_tmp_path + let(:test_module_path) do + sut_module_path(%r{Module test}) + end + + let(:remote_tmp_path) do + sut_tmp_path end expected = <<-EOF @@ -35,15 +38,15 @@ class { "test": } EOF - it 'should render Markdown to stdout when using --format markdown' do + it 'renders Markdown to stdout when using --format markdown' do skip('This test is broken. Does not output to STDOUT by default.') - output = PuppetLitmus::PuppetHelpers.run_shell("puppet strings generate --format markdown \"#{@test_module_path}/manifests/init.pp\"").stdout.chomp + output = PuppetLitmus::PuppetHelpers.run_shell("puppet strings generate --format markdown \"#{test_module_path}/manifests/init.pp\"").stdout.chomp expect(output).to eq(expected) end - it 'should write Markdown to a file when using --format markdown and --out' do - tmpfile = File.join(@remote_tmp_path, 'md_output.md') - remote = PuppetLitmus::PuppetHelpers.run_shell("puppet strings generate --format markdown --out \"#{tmpfile}\" \"#{@test_module_path}/manifests/init.pp\"") + it 'writes Markdown to a file when using --format markdown and --out' do + tmpfile = File.join(remote_tmp_path, 'md_output.md') + PuppetLitmus::PuppetHelpers.run_shell("puppet strings generate --format markdown --out \"#{tmpfile}\" \"#{test_module_path}/manifests/init.pp\"") expect(file(tmpfile)).to contain expected end end diff --git a/spec/acceptance/running_strings_generate_spec.rb b/spec/acceptance/running_strings_generate_spec.rb index c78ac5428..af37a9a4d 100644 --- a/spec/acceptance/running_strings_generate_spec.rb +++ b/spec/acceptance/running_strings_generate_spec.rb @@ -1,93 +1,95 @@ # frozen_string_literal: true require 'spec_helper_acceptance' -include PuppetLitmus # rubocop:disable Style/MixinUsage This is fine +include PuppetLitmus describe 'Generating module documentation using generate action' do + let(:sut_work_dir) do + PuppetLitmus::PuppetHelpers.run_shell('pwd').stdout.chomp + end + before :all do # TODO: Linux only - @sut_work_dir = PuppetLitmus::PuppetHelpers.run_shell("pwd").stdout.chomp - - test_module_path = sut_module_path(/Module test/) + test_module_path = sut_module_path(%r{Module test}) PuppetLitmus::PuppetHelpers.run_shell("puppet strings generate \"#{test_module_path}/**/*.{rb,pp}\"") end def expect_file_contain(path, expected_contents) - file_path = File.join(@sut_work_dir, path) + file_path = File.join(sut_work_dir, path) file_content = file(file_path).content expected_contents.each do |expected| expect(file_content).to include(expected) end end - it 'should generate documentation for manifests' do + it 'generates documentation for manifests' do expect_file_contain('doc/puppet_classes/test.html', ['Class: test']) end - it 'should generate documentation for puppet functions' do + it 'generates documentation for puppet functions' do skip('This test is failing. Appear to be legitimate failures.') expect_file_contain('doc/puppet_functions_puppet/test_3A_3Aadd.html', [ - 'Adds two integers together.', - # These tests are failing. Appear to be legitimate failures. - '

The first integer to add.

', - '

The second integer to add.

', - '

Returns the sum of x and y.

' - ]) + 'Adds two integers together.', + # These tests are failing. Appear to be legitimate failures. + '

The first integer to add.

', + '

The second integer to add.

', + '

Returns the sum of x and y.

', + ]) end - it 'should generate documentation for 3x functions' do + it 'generates documentation for 3x functions' do expect_file_contain('doc/puppet_functions_ruby3x/function3x.html', ['This is the function documentation for function3x']) end - it 'should generate documentation for 4x functions' do + it 'generates documentation for 4x functions' do expect_file_contain('doc/puppet_functions_ruby4x/function4x.html', ['This is a function which is used to test puppet strings']) end - it 'should generate documentation for custom types' do + it 'generates documentation for custom types' do expect_file_contain('doc/puppet_types/database.html', [ - '

An example server resource type.

', - '

The database file to use.

', - '

Documentation for a dynamic property.

', - '

The database server name.

', - '

Documentation for a dynamic parameter.

', - '

The provider supports encryption.

', - ]) + '

An example server resource type.

', + '

The database file to use.

', + '

Documentation for a dynamic property.

', + '

The database server name.

', + '

Documentation for a dynamic parameter.

', + '

The provider supports encryption.

', + ]) end - it 'should generate documentation for custom providers' do + it 'generates documentation for custom providers' do expect_file_contain('doc/puppet_providers_database/linux.html', [ - 'The database provider on Linux', - 'osfamily — linux', - 'database — /usr/bin/database', - ]) + 'The database provider on Linux', + 'osfamily — linux', + 'database — /usr/bin/database', + ]) end - it 'should generate documentation for puppet data types' do + it 'generates documentation for puppet data types' do expect_file_contain('doc/puppet_data_types/AcceptanceDataType.html', [ - 'A variant parameter called param1', - 'Optional String parameter called param2', - '

func1

', - '

func1 documentation

', - '

param1 func1 documentation

', - '

param2 func1 documentation

', - ]) + 'A variant parameter called param1', + 'Optional String parameter called param2', + '

func1

', + '

func1 documentation

', + '

param1 func1 documentation

', + '

param2 func1 documentation

', + ]) end - it 'should generate documentation for puppet data type aliases' do + it 'generates documentation for puppet data type aliases' do expect_file_contain('doc/puppet_data_type_aliases/Test_3A_3AElephant.html', [ - 'Data Type: Test::Elephant', - 'types/elephant.pp', - 'A simple elephant type.', - ]) + 'Data Type: Test::Elephant', + 'types/elephant.pp', + 'A simple elephant type.', + ]) end - it 'should generate documentation for enum tag' do + it 'generates documentation for enum tag' do expect_file_contain('doc/puppet_classes/test.html', [ - '

Enum Options (myenum):

', - 'a', - "—
\n

Option A

\n
", - 'b', - "—
\n

Option B

\n
", - ]) + '

Enum Options (myenum):

', + 'a', + "—
\n

Option A

\n
", + 'b', + "—
\n

Option B

\n
", + ]) end end From b11a02c35296cb07bd736544100b26225d4c2cb7 Mon Sep 17 00:00:00 2001 From: Craig Gumbley Date: Wed, 28 Sep 2022 09:54:13 +0100 Subject: [PATCH 06/16] (MAINT) Rubocop - (spec) fixes for yard --- .../yard/code_objects/task_spec.rb | 68 ++--- .../yard/handlers/json/task_handler_spec.rb | 45 +-- .../handlers/puppet/class_handler_spec.rb | 106 +++---- .../puppet/data_type_alias_handler_spec.rb | 38 +-- .../puppet/defined_type_handler_spec.rb | 108 +++---- .../handlers/puppet/function_handler_spec.rb | 178 ++++++------ .../handlers/ruby/data_type_handler_spec.rb | 210 +++++++------- .../handlers/ruby/function_handler_spec.rb | 265 ++++++++++-------- .../handlers/ruby/provider_handler_spec.rb | 96 ++++--- .../yard/handlers/ruby/rsapi_handler_spec.rb | 90 +++--- .../handlers/ruby/type_extras_handler_spec.rb | 31 +- .../yard/handlers/ruby/type_handler_spec.rb | 154 +++++----- .../yard/parsers/json/parser_spec.rb | 41 +-- .../yard/parsers/json/task_statement_spec.rb | 22 +- .../yard/parsers/puppet/parser_spec.rb | 132 +++++---- spec/unit/puppet-strings/yard/util_spec.rb | 30 +- 16 files changed, 881 insertions(+), 733 deletions(-) diff --git a/spec/unit/puppet-strings/yard/code_objects/task_spec.rb b/spec/unit/puppet-strings/yard/code_objects/task_spec.rb index d4c7cf861..42857702d 100644 --- a/spec/unit/puppet-strings/yard/code_objects/task_spec.rb +++ b/spec/unit/puppet-strings/yard/code_objects/task_spec.rb @@ -5,7 +5,10 @@ require 'puppet-strings/yard/parsers/json/task_statement' describe PuppetStrings::Yard::CodeObjects::Task do - let(:source) { <<-SOURCE + subject(:spec_subject) { described_class.new(statement) } + + let(:source) do + <<-SOURCE { "description": "Allows you to backup your database to local file.", "input_method": "stdin", @@ -29,66 +32,65 @@ } } SOURCE - } + end let(:json) { JSON.parse(source) } - let(:statement) { PuppetStrings::Yard::Parsers::JSON::TaskStatement.new(json, source, "test.json") } - subject { PuppetStrings::Yard::CodeObjects::Task.new(statement) } + let(:statement) { PuppetStrings::Yard::Parsers::JSON::TaskStatement.new(json, source, 'test.json') } describe '#type' do it 'returns the correct type' do - expect(subject.type).to eq(:puppet_task) + expect(spec_subject.type).to eq(:puppet_task) end end describe '#source' do it 'returns the source' do - expect(subject.source).to eq(source) + expect(spec_subject.source).to eq(source) end end describe '#to_hash' do let(:expected) do { - :name => "test", - :supports_noop => false, - :docstring => { - :text=>"Allows you to backup your database to local file.", - :tags=> [ + name: 'test', + supports_noop: false, + docstring: { + text: 'Allows you to backup your database to local file.', + tags: [ { - :name=>"database", - :tag_name=>"param", - :text=>"Database to connect to", - :types=> ["Optional[String[1]]"] + name: 'database', + tag_name: 'param', + text: 'Database to connect to', + types: ['Optional[String[1]]'] }, { - :name=>"user", - :tag_name=>"param", - :text=>"The user", - :types=> ["Optional[String[1]]"] + name: 'user', + tag_name: 'param', + text: 'The user', + types: ['Optional[String[1]]'] }, { - :name=>"password", - :tag_name=>"param", - :text=>"The password", - :types=> ["Optional[String[1]]"] + name: 'password', + tag_name: 'param', + text: 'The password', + types: ['Optional[String[1]]'] }, { - :name=>"sql", - :tag_name=>"param", - :text=>"Path to file you want backup to", - :types=>["String[1]"] - } + name: 'sql', + tag_name: 'param', + text: 'Path to file you want backup to', + types: ['String[1]'] + }, ] }, - :file => "test.json", - :input_method => "stdin", - :line => 0, - :source => "{\n \"description\": \"Allows you to backup your database to local file.\",\n \"input_method\": \"stdin\",\n \"parameters\": {\n \"database\": {\n \"description\": \"Database to connect to\",\n \"type\": \"Optional[String[1]]\"\n },\n \"user\": {\n \"description\": \"The user\",\n \"type\": \"Optional[String[1]]\"\n },\n \"password\": {\n \"description\": \"The password\",\n \"type\": \"Optional[String[1]]\"\n },\n \"sql\": {\n \"description\": \"Path to file you want backup to\",\n \"type\": \"String[1]\"\n }\n }\n}\n" + file: 'test.json', + input_method: 'stdin', + line: 0, + source: "{\n \"description\": \"Allows you to backup your database to local file.\",\n \"input_method\": \"stdin\",\n \"parameters\": {\n \"database\": {\n \"description\": \"Database to connect to\",\n \"type\": \"Optional[String[1]]\"\n },\n \"user\": {\n \"description\": \"The user\",\n \"type\": \"Optional[String[1]]\"\n },\n \"password\": {\n \"description\": \"The password\",\n \"type\": \"Optional[String[1]]\"\n },\n \"sql\": {\n \"description\": \"Path to file you want backup to\",\n \"type\": \"String[1]\"\n }\n }\n}\n" # rubocop:disable Layout/LineLength } end it 'returns the correct hash' do - expect(subject.to_hash).to eq(expected) + expect(spec_subject.to_hash).to eq(expected) end end end diff --git a/spec/unit/puppet-strings/yard/handlers/json/task_handler_spec.rb b/spec/unit/puppet-strings/yard/handlers/json/task_handler_spec.rb index d1af655d7..60609ae18 100644 --- a/spec/unit/puppet-strings/yard/handlers/json/task_handler_spec.rb +++ b/spec/unit/puppet-strings/yard/handlers/json/task_handler_spec.rb @@ -4,13 +4,14 @@ require 'puppet-strings/yard' describe PuppetStrings::Yard::Handlers::JSON::TaskHandler do - subject { + subject(:spec_subject) do YARD::Parser::SourceParser.parse_string(source, :json) YARD::Registry.all(:puppet_task) - } + end describe 'parsing task metadata with a syntax error' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE { "input_method": "stdin", "parameters": @@ -21,16 +22,17 @@ } } SOURCE - } + end - it 'should log an error' do - expect{ subject }.to output(/\[error\]: Failed to parse \(stdin\):/).to_stdout_from_any_process - expect(subject.empty?).to eq(true) + it 'logs an error' do + expect { spec_subject }.to output(%r{\[error\]: Failed to parse \(stdin\):}).to_stdout_from_any_process + expect(spec_subject.empty?).to eq(true) end end describe 'parsing task metadata with a missing description' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE { "input_method": "stdin", "parameters": { @@ -53,15 +55,16 @@ } } SOURCE - } + end - it 'should log a warning' do - expect{ subject }.to output(/\[warn\]: Missing a description for Puppet Task \(stdin\)/).to_stdout_from_any_process + it 'logs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: Missing a description for Puppet Task \(stdin\)}).to_stdout_from_any_process end end describe 'parsing task metadata with a description' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE { "description": "Allows you to backup your database to local file.", "input_method": "stdin", @@ -86,18 +89,19 @@ } SOURCE - } + end - it 'should register a task object' do - expect(subject.size).to eq(1) - object = subject.first + it 'registers a task object' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::Task) expect(object.namespace).to eq(PuppetStrings::Yard::CodeObjects::Tasks.instance) end end describe 'parsing task metadata with a missing parameter description' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE { "description": "Allows you to backup your database to local file.", "input_method": "stdin", @@ -108,11 +112,10 @@ } } SOURCE - } + end - it 'should output a warning' do - expect{ subject }.to output(/\[warn\]: Missing description for param 'database' in Puppet Task \(stdin\)/).to_stdout_from_any_process + it 'outputs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: Missing description for param 'database' in Puppet Task \(stdin\)}).to_stdout_from_any_process end end - end diff --git a/spec/unit/puppet-strings/yard/handlers/puppet/class_handler_spec.rb b/spec/unit/puppet-strings/yard/handlers/puppet/class_handler_spec.rb index 9d00adc2a..3f919f6ce 100644 --- a/spec/unit/puppet-strings/yard/handlers/puppet/class_handler_spec.rb +++ b/spec/unit/puppet-strings/yard/handlers/puppet/class_handler_spec.rb @@ -4,38 +4,39 @@ require 'puppet-strings/yard' describe PuppetStrings::Yard::Handlers::Puppet::ClassHandler do - subject { + subject(:spec_subject) do YARD::Parser::SourceParser.parse_string(source, :puppet) YARD::Registry.all(:puppet_class) - } + end describe 'parsing source without a class definition' do let(:source) { 'notice hi' } it 'no classes should be in the registry' do - expect(subject.empty?).to eq(true) + expect(spec_subject.empty?).to eq(true) end end describe 'parsing source with a syntax error' do let(:source) { 'class foo{' } - it 'should log an error' do - expect{ subject }.to output(/\[error\]: Failed to parse \(stdin\): Syntax error at end of (file|input)/).to_stdout_from_any_process - expect(subject.empty?).to eq(true) + it 'logs an error' do + expect { spec_subject }.to output(%r{\[error\]: Failed to parse \(stdin\): Syntax error at end of (file|input)}).to_stdout_from_any_process + expect(spec_subject.empty?).to eq(true) end end describe 'parsing a class with a missing docstring' do let(:source) { 'class foo{}' } - it 'should log a warning' do - expect{ subject }.to output(/\[warn\]: Missing documentation for Puppet class 'foo' at \(stdin\):1\./).to_stdout_from_any_process + it 'logs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: Missing documentation for Puppet class 'foo' at \(stdin\):1\.}).to_stdout_from_any_process end end describe 'parsing a class with a docstring' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo class. # @param param1 First param. # @param param2 Second param. @@ -46,11 +47,11 @@ class foo(Integer $param1, $param2, String $param3 = hi) inherits foo::bar { } } SOURCE - } + end - it 'should register a class object' do - expect(subject.size).to eq(1) - object = subject.first + it 'registers a class object' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::Class) expect(object.namespace).to eq(PuppetStrings::Yard::CodeObjects::Classes.instance) expect(object.name).to eq(:foo) @@ -76,7 +77,8 @@ class foo(Integer $param1, $param2, String $param3 = hi) inherits foo::bar { end describe 'parsing a class with a missing parameter' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo class. # @param param1 First param. # @param param2 Second param. @@ -88,15 +90,16 @@ class foo(Integer $param1, $param2, String $param3 = hi) inherits foo::bar { } } SOURCE - } + end - it 'should output a warning' do - expect{ subject }.to output(/\[warn\]: The @param tag for parameter 'param4' has no matching parameter at \(stdin\):6\./).to_stdout_from_any_process + it 'outputs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: The @param tag for parameter 'param4' has no matching parameter at \(stdin\):6\.}).to_stdout_from_any_process end end describe 'parsing a class with a missing @param tag' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo class. # @param param1 First param. # @param param2 Second param. @@ -106,15 +109,16 @@ class foo(Integer $param1, $param2, String $param3 = hi) inherits foo::bar { } } SOURCE - } + end - it 'should output a warning' do - expect{ subject }.to output(/\[warn\]: Missing @param tag for parameter 'param3' near \(stdin\):4\./).to_stdout_from_any_process + it 'outputs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: Missing @param tag for parameter 'param3' near \(stdin\):4\.}).to_stdout_from_any_process end end describe 'parsing a class with a typed parameter that also has a @param tag type which matches' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo class. # @param [Integer] param1 First param. # @param param2 Second param. @@ -125,19 +129,20 @@ class foo(Integer $param1, $param2, String $param3 = hi) inherits foo::bar { } } SOURCE - } + end - it 'should respect the type that was documented' do - expect{ subject }.to output('').to_stdout_from_any_process - expect(subject.size).to eq(1) - tags = subject.first.tags(:param) + it 'respects the type that was documented' do + expect { spec_subject }.to output('').to_stdout_from_any_process + expect(spec_subject.size).to eq(1) + tags = spec_subject.first.tags(:param) expect(tags.size).to eq(3) expect(tags[0].types).to eq(['Integer']) end end describe 'parsing a class with a typed parameter that also has a @param tag type which does not match' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo class. # @param [Boolean] param1 First param. # @param param2 Second param. @@ -148,15 +153,20 @@ class foo(Integer $param1, $param2, String $param3 = hi) inherits foo::bar { } } SOURCE - } + end - it 'should output a warning' do - expect{ subject }.to output(/\[warn\]: The type of the @param tag for parameter 'param1' does not match the parameter type specification near \(stdin\):5: ignoring in favor of parameter type information./).to_stdout_from_any_process + it 'outputs a warning' do + expect { spec_subject } + .to output( + %r{\[warn\]: The type of the @param tag for parameter 'param1' does not match the parameter type specification near \(stdin\):5: ignoring in favor of parameter type information.}, + ) + .to_stdout_from_any_process end end describe 'parsing a class with a untyped parameter that also has a @param tag type' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo class. # @param param1 First param. # @param [Boolean] param2 Second param. @@ -167,12 +177,12 @@ class foo(Integer $param1, $param2, String $param3 = hi) inherits foo::bar { } } SOURCE - } + end - it 'should respect the type that was documented' do - expect{ subject }.to output('').to_stdout_from_any_process - expect(subject.size).to eq(1) - tags = subject.first.tags(:param) + it 'respects the type that was documented' do + expect { spec_subject }.to output('').to_stdout_from_any_process + expect(spec_subject.size).to eq(1) + tags = spec_subject.first.tags(:param) expect(tags.size).to eq(3) expect(tags[1].types).to eq(['Boolean']) end @@ -180,7 +190,8 @@ class foo(Integer $param1, $param2, String $param3 = hi) inherits foo::bar { describe 'parsing a class with a summary' do context 'when the summary has fewer than 140 characters' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo class. # @summary A short summary. class foo() { @@ -189,18 +200,19 @@ class foo() { } } SOURCE - } + end - it 'should parse the summary' do - expect{ subject }.to output('').to_stdout_from_any_process - expect(subject.size).to eq(1) - summary = subject.first.tags(:summary) + it 'parses the summary' do + expect { spec_subject }.to output('').to_stdout_from_any_process + expect(spec_subject.size).to eq(1) + summary = spec_subject.first.tags(:summary) expect(summary.first.text).to eq('A short summary.') end end context 'when the summary has more than 140 characters' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo class. # @summary A short summary that is WAY TOO LONG. AHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH this is not what a summary is for! It should be fewer than 140 characters!! class foo() { @@ -209,10 +221,10 @@ class foo() { } } SOURCE - } + end - it 'should log a warning' do - expect{ subject }.to output(/\[warn\]: The length of the summary for puppet_class 'foo' exceeds the recommended limit of 140 characters./).to_stdout_from_any_process + it 'logs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: The length of the summary for puppet_class 'foo' exceeds the recommended limit of 140 characters.}).to_stdout_from_any_process end end end diff --git a/spec/unit/puppet-strings/yard/handlers/puppet/data_type_alias_handler_spec.rb b/spec/unit/puppet-strings/yard/handlers/puppet/data_type_alias_handler_spec.rb index 8bf55ee2d..fd7e57372 100644 --- a/spec/unit/puppet-strings/yard/handlers/puppet/data_type_alias_handler_spec.rb +++ b/spec/unit/puppet-strings/yard/handlers/puppet/data_type_alias_handler_spec.rb @@ -4,63 +4,65 @@ require 'puppet-strings/yard' describe PuppetStrings::Yard::Handlers::Puppet::DataTypeAliasHandler, if: TEST_PUPPET_DATATYPES do - subject { + subject(:spec_subject) do YARD::Parser::SourceParser.parse_string(source, :puppet) YARD::Registry.all(:puppet_data_type_alias) - } + end describe 'parsing source without a type alias definition' do let(:source) { 'notice hi' } it 'no aliases should be in the registry' do - expect(subject.empty?).to eq(true) + expect(spec_subject.empty?).to eq(true) end end describe 'parsing source with a syntax error' do let(:source) { 'type Testype =' } - it 'should log an error' do - expect{ subject }.to output(/\[error\]: Failed to parse \(stdin\): Syntax error at end of (file|input)/).to_stdout_from_any_process - expect(subject.empty?).to eq(true) + it 'logs an error' do + expect { spec_subject }.to output(%r{\[error\]: Failed to parse \(stdin\): Syntax error at end of (file|input)}).to_stdout_from_any_process + expect(spec_subject.empty?).to eq(true) end end describe 'parsing a data type alias with a missing docstring' do let(:source) { 'type Testype = String[1]' } - it 'should log a warning' do - expect{ subject }.to output(/\[warn\]: Missing documentation for Puppet type alias 'Testype' at \(stdin\):1\./).to_stdout_from_any_process + it 'logs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: Missing documentation for Puppet type alias 'Testype' at \(stdin\):1\.}).to_stdout_from_any_process end end describe 'parsing a data type alias with a summary' do context 'when the summary has fewer than 140 characters' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo type. # @summary A short summary. type Testype = String[1] SOURCE - } + end - it 'should parse the summary' do - expect{ subject }.to output('').to_stdout_from_any_process - expect(subject.size).to eq(1) - summary = subject.first.tags(:summary) + it 'parses the summary' do + expect { spec_subject }.to output('').to_stdout_from_any_process + expect(spec_subject.size).to eq(1) + summary = spec_subject.first.tags(:summary) expect(summary.first.text).to eq('A short summary.') end end context 'when the summary has more than 140 characters' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo type. # @summary A short summary that is WAY TOO LONG. AHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH this is not what a summary is for! It should be fewer than 140 characters!! type Testype = String[1] SOURCE - } + end - it 'should log a warning' do - expect{ subject }.to output(/\[warn\]: The length of the summary for puppet_data_type_alias 'Testype' exceeds the recommended limit of 140 characters./).to_stdout_from_any_process + it 'logs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: The length of the summary for puppet_data_type_alias 'Testype' exceeds the recommended limit of 140 characters.}).to_stdout_from_any_process end end end diff --git a/spec/unit/puppet-strings/yard/handlers/puppet/defined_type_handler_spec.rb b/spec/unit/puppet-strings/yard/handlers/puppet/defined_type_handler_spec.rb index 265c9db82..c7ab7e218 100644 --- a/spec/unit/puppet-strings/yard/handlers/puppet/defined_type_handler_spec.rb +++ b/spec/unit/puppet-strings/yard/handlers/puppet/defined_type_handler_spec.rb @@ -4,38 +4,39 @@ require 'puppet-strings/yard' describe PuppetStrings::Yard::Handlers::Puppet::DefinedTypeHandler do - subject { + subject(:spec_subject) do YARD::Parser::SourceParser.parse_string(source, :puppet) YARD::Registry.all(:puppet_defined_type) - } + end describe 'parsing source without a defined type definition' do let(:source) { 'notice hi' } it 'no defined types should be in the registry' do - expect(subject.empty?).to eq(true) + expect(spec_subject.empty?).to eq(true) end end describe 'parsing source with a syntax error' do let(:source) { 'define foo{' } - it 'should log an error' do - expect{ subject }.to output(/\[error\]: Failed to parse \(stdin\): Syntax error at end of (file|input)/).to_stdout_from_any_process - expect(subject.empty?).to eq(true) + it 'logs an error' do + expect { spec_subject }.to output(%r{\[error\]: Failed to parse \(stdin\): Syntax error at end of (file|input)}).to_stdout_from_any_process + expect(spec_subject.empty?).to eq(true) end end describe 'parsing a defined type with a missing docstring' do let(:source) { 'define foo{}' } - it 'should log a warning' do - expect{ subject }.to output(/\[warn\]: Missing documentation for Puppet defined type 'foo' at \(stdin\):1\./).to_stdout_from_any_process + it 'logs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: Missing documentation for Puppet defined type 'foo' at \(stdin\):1\.}).to_stdout_from_any_process end end describe 'parsing a defined type with a docstring' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo defined type. # @param name The type name. # @param param1 First param. @@ -47,14 +48,15 @@ } } SOURCE - } + end + it 'does not output a warning for title/name' do - expect{ subject }.not_to output(/\[warn\].*(name|title).*/).to_stdout_from_any_process + expect { spec_subject }.not_to output(%r{\[warn\].*(name|title).*}).to_stdout_from_any_process end - it 'should register a defined type object' do - expect(subject.size).to eq(1) - object = subject.first + it 'registers a defined type object' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::DefinedType) expect(object.namespace).to eq(PuppetStrings::Yard::CodeObjects::DefinedTypes.instance) expect(object.name).to eq(:foo) @@ -83,7 +85,8 @@ end describe 'parsing a defined type with a missing parameter' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo defined type. # @param param1 First param. # @param param2 Second param. @@ -95,15 +98,16 @@ } } SOURCE - } + end - it 'should output a warning' do - expect{ subject }.to output(/\[warn\]: The @param tag for parameter 'param4' has no matching parameter at \(stdin\):6\./).to_stdout_from_any_process + it 'outputs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: The @param tag for parameter 'param4' has no matching parameter at \(stdin\):6\.}).to_stdout_from_any_process end end describe 'parsing a defined type with a missing @param tag' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo defined type. # @param param1 First param. # @param param2 Second param. @@ -113,15 +117,16 @@ } } SOURCE - } + end - it 'should output a warning' do - expect{ subject }.to output(/\[warn\]: Missing @param tag for parameter 'param3' near \(stdin\):4\./).to_stdout_from_any_process + it 'outputs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: Missing @param tag for parameter 'param3' near \(stdin\):4\.}).to_stdout_from_any_process end end describe 'parsing a defined type with a typed parameter that also has a @param tag type which matches' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo defined type. # @param [Integer] param1 First param. # @param param2 Second param. @@ -132,19 +137,20 @@ } } SOURCE - } + end - it 'should respect the type that was documented' do - expect{ subject }.to output('').to_stdout_from_any_process - expect(subject.size).to eq(1) - tags = subject.first.tags(:param) + it 'respects the type that was documented' do + expect { spec_subject }.to output('').to_stdout_from_any_process + expect(spec_subject.size).to eq(1) + tags = spec_subject.first.tags(:param) expect(tags.size).to eq(3) expect(tags[0].types).to eq(['Integer']) end end describe 'parsing a defined type with a typed parameter that also has a @param tag type which does not match' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo defined type. # @param [Boolean] param1 First param. # @param param2 Second param. @@ -155,15 +161,18 @@ } } SOURCE - } + end - it 'should output a warning' do - expect{ subject }.to output(/\[warn\]: The type of the @param tag for parameter 'param1' does not match the parameter type specification near \(stdin\):5: ignoring in favor of parameter type information./).to_stdout_from_any_process + it 'outputs a warning' do + expect { spec_subject } + .to output(%r{\[warn\]: The type of the @param tag for parameter 'param1' does not match the parameter type specification near \(stdin\):5: ignoring in favor of parameter type information.}) + .to_stdout_from_any_process end end describe 'parsing a defined type with a untyped parameter that also has a @param tag type' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo defined type. # @param param1 First param. # @param [Boolean] param2 Second param. @@ -174,21 +183,21 @@ } } SOURCE - } + end - it 'should respect the type that was documented' do - expect{ subject }.to output('').to_stdout_from_any_process - expect(subject.size).to eq(1) - tags = subject.first.tags(:param) + it 'respects the type that was documented' do + expect { spec_subject }.to output('').to_stdout_from_any_process + expect(spec_subject.size).to eq(1) + tags = spec_subject.first.tags(:param) expect(tags.size).to eq(3) expect(tags[1].types).to eq(['Boolean']) end end describe 'parsing a defined type with a summary' do - context 'when the summary has fewer than 140 characters' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo defined type. # @summary A short summary. # @param param1 First param. @@ -200,18 +209,19 @@ } } SOURCE - } + end - it 'should parse the summary' do - expect{ subject }.to output('').to_stdout_from_any_process - expect(subject.size).to eq(1) - summary = subject.first.tags(:summary) + it 'parses the summary' do + expect { spec_subject }.to output('').to_stdout_from_any_process + expect(spec_subject.size).to eq(1) + summary = spec_subject.first.tags(:summary) expect(summary.first.text).to eq('A short summary.') end end context 'when the summary has more than 140 characters' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo defined type. # @summary A short summary that is WAY TOO LONG. AHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH this is not what a summary is for! It should be fewer than 140 characters!! # @param param1 First param. @@ -223,10 +233,10 @@ } } SOURCE - } + end - it 'should log a warning' do - expect{ subject }.to output(/\[warn\]: The length of the summary for puppet_defined_type 'foo' exceeds the recommended limit of 140 characters./).to_stdout_from_any_process + it 'logs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: The length of the summary for puppet_defined_type 'foo' exceeds the recommended limit of 140 characters.}).to_stdout_from_any_process end end end diff --git a/spec/unit/puppet-strings/yard/handlers/puppet/function_handler_spec.rb b/spec/unit/puppet-strings/yard/handlers/puppet/function_handler_spec.rb index c9e86644b..0eeb1d1c9 100644 --- a/spec/unit/puppet-strings/yard/handlers/puppet/function_handler_spec.rb +++ b/spec/unit/puppet-strings/yard/handlers/puppet/function_handler_spec.rb @@ -5,38 +5,39 @@ # Limit this spec to Puppet 4.1+ (when functions in Puppet were implemented) describe PuppetStrings::Yard::Handlers::Puppet::FunctionHandler, if: TEST_PUPPET_FUNCTIONS do - subject { + subject(:spec_subject) do YARD::Parser::SourceParser.parse_string(source, :puppet) YARD::Registry.all(:puppet_function) - } + end describe 'parsing source without a function definition' do let(:source) { 'notice hi' } it 'no functions should be in the registry' do - expect(subject.empty?).to eq(true) + expect(spec_subject.empty?).to eq(true) end end describe 'parsing source with a syntax error' do let(:source) { 'function foo{' } - it 'should log an error' do - expect{ subject }.to output(/\[error\]: Failed to parse \(stdin\): Syntax error at end of/).to_stdout_from_any_process - expect(subject.empty?).to eq(true) + it 'logs an error' do + expect { spec_subject }.to output(%r{\[error\]: Failed to parse \(stdin\): Syntax error at end of}).to_stdout_from_any_process + expect(spec_subject.empty?).to eq(true) end end describe 'parsing a function with a missing docstring' do let(:source) { 'function foo{}' } - it 'should log a warning' do - expect{ subject }.to output(/\[warn\]: Missing documentation for Puppet function 'foo' at \(stdin\):1\./).to_stdout_from_any_process + it 'logs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: Missing documentation for Puppet function 'foo' at \(stdin\):1\.}).to_stdout_from_any_process end end describe 'parsing a function with a docstring' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo function. # @param param1 First param. # @param param2 Second param. @@ -47,11 +48,11 @@ undef } SOURCE - } + end - it 'should register a function object' do - expect(subject.size).to eq(1) - object = subject.first + it 'registers a function object' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::Function) expect(object.namespace).to eq(PuppetStrings::Yard::CodeObjects::Functions.instance(PuppetStrings::Yard::CodeObjects::Function::PUPPET)) expect(object.name).to eq(:foo) @@ -82,7 +83,8 @@ end describe 'parsing a function with a missing parameter' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo function. # @param param1 First param. # @param param2 Second param. @@ -93,15 +95,18 @@ notice 'hello world' } SOURCE - } + end - it 'should output a warning' do - expect{ subject }.to output(/\[warn\]: The @param tag for parameter 'param4' has no matching parameter at \(stdin\):7\./).to_stdout_from_any_process + it 'outputs a warning' do + expect { spec_subject } + .to output(%r{\[warn\]: The @param tag for parameter 'param4' has no matching parameter at \(stdin\):7\.}) + .to_stdout_from_any_process end end describe 'parsing a function with a missing @param tag' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo function. # @param param1 First param. # @param param2 Second param. @@ -110,15 +115,16 @@ notice 'hello world' } SOURCE - } + end - it 'should output a warning' do - expect{ subject }.to output(/\[warn\]: Missing @param tag for parameter 'param3' near \(stdin\):5\./).to_stdout_from_any_process + it 'outputs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: Missing @param tag for parameter 'param3' near \(stdin\):5\.}).to_stdout_from_any_process end end describe 'parsing a function with a typed parameter that also has a @param tag type which matches' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo function. # @param [Integer] param1 First param. # @param param2 Second param. @@ -128,19 +134,20 @@ notice 'hello world' } SOURCE - } + end - it 'should respect the type that was documented' do - expect{ subject }.to output('').to_stdout_from_any_process - expect(subject.size).to eq(1) - tags = subject.first.tags(:param) + it 'respects the type that was documented' do + expect { spec_subject }.to output('').to_stdout_from_any_process + expect(spec_subject.size).to eq(1) + tags = spec_subject.first.tags(:param) expect(tags.size).to eq(3) expect(tags[0].types).to eq(['Integer']) end end describe 'parsing a function with a typed parameter that also has a @param tag type which does not match' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo function. # @param [Boolean] param1 First param. # @param param2 Second param. @@ -150,15 +157,20 @@ notice 'hello world' } SOURCE - } + end - it 'should output a warning' do - expect{ subject }.to output(/\[warn\]: The type of the @param tag for parameter 'param1' does not match the parameter type specification near \(stdin\):6: ignoring in favor of parameter type information./).to_stdout_from_any_process + it 'outputs a warning' do + expect { spec_subject } + .to output( + %r{\[warn\]: The type of the @param tag for parameter 'param1' does not match the parameter type specification near \(stdin\):6: ignoring in favor of parameter type information.}, + ) + .to_stdout_from_any_process end end describe 'parsing a function with a untyped parameter that also has a @param tag type' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo function. # @param param1 First param. # @param [Boolean] param2 Second param. @@ -168,19 +180,20 @@ notice 'hello world' } SOURCE - } + end - it 'should respect the type that was documented' do - expect{ subject }.to output('').to_stdout_from_any_process - expect(subject.size).to eq(1) - tags = subject.first.tags(:param) + it 'respects the type that was documented' do + expect { spec_subject }.to output('').to_stdout_from_any_process + expect(spec_subject.size).to eq(1) + tags = spec_subject.first.tags(:param) expect(tags.size).to eq(3) expect(tags[1].types).to eq(['Boolean']) end end describe 'parsing a function with a missing @return tag' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo function. # @param param1 First param. # @param param2 Second param. @@ -189,26 +202,27 @@ notice 'hello world' } SOURCE - } + end - it 'should output a warning' do - expect{ subject }.to output(/\[warn\]: Missing @return tag near \(stdin\):5\./).to_stdout_from_any_process + it 'outputs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: Missing @return tag near \(stdin\):5\.}).to_stdout_from_any_process end end describe 'parsing a function with a missing @return tag and return type specified in the function definition', if: TEST_FUNCTION_RETURN_TYPE do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo function. function foo() >> String { notice 'hello world' } SOURCE - } + end - it 'should register a function object with the correct return type' do - expect{ subject }.to output(/\[warn\]: Missing @return tag near \(stdin\):2\./).to_stdout_from_any_process - expect(subject.size).to eq(1) - object = subject.first + it 'registers a function object with the correct return type' do + expect { spec_subject }.to output(%r{\[warn\]: Missing @return tag near \(stdin\):2\.}).to_stdout_from_any_process + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::Function) tags = object.docstring.tags(:return) expect(tags.size).to eq(1) @@ -219,34 +233,36 @@ end describe 'parsing a function with a non-conflicting return tag and type in function definition', if: TEST_FUNCTION_RETURN_TYPE do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo function # @return [String] Hi there function foo() >> String { notice 'hi there' } SOURCE - } + end - it 'should not output a warning if return types match' do - expect{ subject }.not_to output(/Documented return type does not match return type in function definition/).to_stdout_from_any_process + it 'does not output a warning if return types match' do + expect { spec_subject }.not_to output(%r{Documented return type does not match return type in function definition}).to_stdout_from_any_process end end describe 'parsing a function with a conflicting return tag and type in function definition', if: TEST_FUNCTION_RETURN_TYPE do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo function. # @return [Integer] this is a lie. function foo() >> Struct[{'a' => Integer[1, 10]}] { notice 'hello world' } SOURCE - } + end - it 'should prefer the return type from the function definition' do - expect{ subject }.to output(/\[warn\]: Documented return type does not match return type in function definition near \(stdin\):3\./).to_stdout_from_any_process - expect(subject.size).to eq(1) - object = subject.first + it 'prefers the return type from the function definition' do + expect { spec_subject }.to output(%r{\[warn\]: Documented return type does not match return type in function definition near \(stdin\):3\.}).to_stdout_from_any_process + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::Function) tags = object.docstring.tags(:return) expect(tags.size).to eq(1) @@ -257,19 +273,20 @@ end describe 'parsing a function with return tag without type', if: TEST_FUNCTION_RETURN_TYPE do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo function. # @return This is something. function foo() >> Struct[{'a' => Integer[1, 10]}] { notice 'hello world' } SOURCE - } + end - it 'should get the return type from the function definition' do - expect{ subject }.to output('').to_stdout_from_any_process - expect(subject.size).to eq(1) - object = subject.first + it 'gets the return type from the function definition' do + expect { spec_subject }.to output('').to_stdout_from_any_process + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::Function) tags = object.docstring.tags(:return) expect(tags.size).to eq(1) @@ -280,18 +297,19 @@ end describe 'parsing a function without a return tag or return type in the function definition' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo function. function foo() { notice 'hello world' } SOURCE - } + end - it 'should add a return tag with a default type value of Any' do - expect{ subject }.to output(/\[warn\]: Missing @return tag near \(stdin\):2\./).to_stdout_from_any_process - expect(subject.size).to eq(1) - object = subject.first + it 'adds a return tag with a default type value of Any' do + expect { spec_subject }.to output(%r{\[warn\]: Missing @return tag near \(stdin\):2\.}).to_stdout_from_any_process + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::Function) tags = object.docstring.tags(:return) expect(tags.size).to eq(1) @@ -303,7 +321,8 @@ describe 'parsing a function with a summary' do context 'when the summary has fewer than 140 characters' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo function. # @summary A short summary. # @return [String] foo @@ -311,18 +330,19 @@ notice 'hello world' } SOURCE - } + end - it 'should parse the summary' do - expect{ subject }.to output('').to_stdout_from_any_process - expect(subject.size).to eq(1) - summary = subject.first.tags(:summary) + it 'parses the summary' do + expect { spec_subject }.to output('').to_stdout_from_any_process + expect(spec_subject.size).to eq(1) + summary = spec_subject.first.tags(:summary) expect(summary.first.text).to eq('A short summary.') end end context 'when the summary has more than 140 characters' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo function. # @summary A short summary that is WAY TOO LONG. AHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH this is not what a summary is for! It should be fewer than 140 characters!! function foo() { @@ -330,10 +350,10 @@ } SOURCE - } + end - it 'should log a warning' do - expect{ subject }.to output(/\[warn\]: The length of the summary for puppet_function 'foo' exceeds the recommended limit of 140 characters./).to_stdout_from_any_process + it 'logs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: The length of the summary for puppet_function 'foo' exceeds the recommended limit of 140 characters.}).to_stdout_from_any_process end end end diff --git a/spec/unit/puppet-strings/yard/handlers/ruby/data_type_handler_spec.rb b/spec/unit/puppet-strings/yard/handlers/ruby/data_type_handler_spec.rb index 0d9a759a9..c2858fa7d 100644 --- a/spec/unit/puppet-strings/yard/handlers/ruby/data_type_handler_spec.rb +++ b/spec/unit/puppet-strings/yard/handlers/ruby/data_type_handler_spec.rb @@ -4,20 +4,18 @@ require 'puppet-strings/yard' describe PuppetStrings::Yard::Handlers::Ruby::DataTypeHandler, if: TEST_PUPPET_DATATYPES do - subject { + subject(:spec_subject) do YARD::Parser::SourceParser.parse_string(source, :ruby) YARD::Registry.all(:puppet_data_type) - } - - before(:each) do - # Tests may suppress logging to make it easier to read results, - # so remember the logging object prior to running the test - @original_yard_logging_object = YARD::Logger.instance.io end + # Tests may suppress logging to make it easier to read results, + # so remember the logging object prior to running the test. + original_yard_logging_object = YARD::Logger.instance.io + after(:each) do # Restore the original logging IO object - YARD::Logger.instance.io = @original_yard_logging_object + YARD::Logger.instance.io = original_yard_logging_object end def suppress_yard_logging @@ -28,20 +26,21 @@ def suppress_yard_logging let(:source) { 'puts "hi"' } it 'no data types should be in the registry' do - expect(subject.empty?).to eq(true) + expect(spec_subject.empty?).to eq(true) end end describe 'parsing an empty data type definition' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::DataTypes.create_type('RubyDataType') do end SOURCE - } + end - it 'should register a data type object with no param tags or functions' do - expect(subject.size).to eq(1) - object = subject.first + it 'registers a data type object with no param tags or functions' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::DataType) expect(object.namespace).to eq(PuppetStrings::Yard::CodeObjects::DataTypes.instance) expect(object.name).to eq(:RubyDataType) @@ -57,7 +56,8 @@ def suppress_yard_logging end describe 'parsing a data type definition with missing param tags' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # An example Puppet Data Type in Ruby. Puppet::DataTypes.create_type('RubyDataType') do interface <<-PUPPET @@ -67,17 +67,17 @@ def suppress_yard_logging PUPPET end SOURCE - } + end - it 'should output a warning' do - expect{ subject }.to output(/\[warn\]: Missing @param tag for attribute 'msg' near \(stdin\):2/).to_stdout_from_any_process + it 'outputs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: Missing @param tag for attribute 'msg' near \(stdin\):2}).to_stdout_from_any_process end - it 'should register a data type object with all param tags' do + it 'registers a data type object with all param tags' do suppress_yard_logging - expect(subject.size).to eq(1) - object = subject.first + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::DataType) expect(object.namespace).to eq(PuppetStrings::Yard::CodeObjects::DataTypes.instance) expect(object.name).to eq(:RubyDataType) @@ -102,7 +102,8 @@ def suppress_yard_logging describe 'parsing a data type definition with missing function' do context 'which has parameters' do - let(:source) do <<-SOURCE + let(:source) do + <<-SOURCE # An example Puppet Data Type in Ruby. Puppet::DataTypes.create_type('RubyDataType') do interface <<-PUPPET @@ -114,15 +115,15 @@ def suppress_yard_logging SOURCE end - it 'should output a warning about the missing functions' do - expect { subject }.to output(/\[warn\]: Missing @!method tag for function 'func1' near \(stdin\):2/m).to_stdout_from_any_process + it 'outputs a warning about the missing functions' do + expect { spec_subject }.to output(%r{\[warn\]: Missing @!method tag for function 'func1' near \(stdin\):2}m).to_stdout_from_any_process end - it 'should register a data type object with all functions' do + it 'registers a data type object with all functions' do suppress_yard_logging - expect(subject.size).to eq(1) - object = subject.first + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::DataType) expect(object.namespace).to eq(PuppetStrings::Yard::CodeObjects::DataTypes.instance) expect(object.name).to eq(:RubyDataType) @@ -137,7 +138,7 @@ def suppress_yard_logging func = object.functions.first expect(func.docstring).to eq('') expect(func.signature).to eq('RubyDataType.func1(param1, param2)') - expect(func.tag(:return)).to_not be_nil + expect(func.tag(:return)).not_to be_nil expect(func.tag(:return).types).to eq(['String']) param_tags = func.docstring.tags(:param) expect(param_tags.size).to eq(2) @@ -150,7 +151,8 @@ def suppress_yard_logging end context 'which has multiple functions' do - let(:source) do <<-SOURCE + let(:source) do + <<-SOURCE # An example Puppet Data Type in Ruby. Puppet::DataTypes.create_type('RubyDataType') do interface <<-PUPPET @@ -163,19 +165,19 @@ def suppress_yard_logging SOURCE end - it 'should output a warning about the first missing function' do - expect { subject }.to output(/\[warn\]: Missing @!method tag for function 'func1' near \(stdin\):2/m).to_stdout_from_any_process + it 'outputs a warning about the first missing function' do + expect { spec_subject }.to output(%r{\[warn\]: Missing @!method tag for function 'func1' near \(stdin\):2}m).to_stdout_from_any_process end - it 'should output a warning about the second missing function' do - expect { subject }.to output(/\[warn\]: Missing @!method tag for function 'func2' near \(stdin\):2/m).to_stdout_from_any_process + it 'outputs a warning about the second missing function' do + expect { spec_subject }.to output(%r{\[warn\]: Missing @!method tag for function 'func2' near \(stdin\):2}m).to_stdout_from_any_process end - it 'should register a data type object with all functions' do + it 'registers a data type object with all functions' do suppress_yard_logging - expect(subject.size).to eq(1) - object = subject.first + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::DataType) # Check for functions @@ -199,7 +201,8 @@ def suppress_yard_logging end describe 'parsing a data type definition with extra tags' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # An example Puppet Data Type in Ruby. # @param msg A message parameter. # @param arg1 Optional String parameter. Defaults to 'param'. @@ -217,21 +220,21 @@ def suppress_yard_logging PUPPET end SOURCE - } + end - it 'should output a warning about the extra attribute' do - expect{ subject }.to output(/\[warn\]: The @param tag for 'arg1' has no matching attribute near \(stdin\):7/m).to_stdout_from_any_process + it 'outputs a warning about the extra attribute' do + expect { spec_subject }.to output(%r{\[warn\]: The @param tag for 'arg1' has no matching attribute near \(stdin\):7}m).to_stdout_from_any_process end - it 'should output a warning about the extra function' do - expect{ subject }.to output(/\[warn\]: The @!method tag for 'does_not_exist' has no matching function definition near \(stdin\):7/m).to_stdout_from_any_process + it 'outputs a warning about the extra function' do + expect { spec_subject }.to output(%r{\[warn\]: The @!method tag for 'does_not_exist' has no matching function definition near \(stdin\):7}m).to_stdout_from_any_process end - it 'should register a data type object with extra information removed' do + it 'registers a data type object with extra information removed' do suppress_yard_logging - expect(subject.size).to eq(1) - object = subject.first + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::DataType) expect(object.namespace).to eq(PuppetStrings::Yard::CodeObjects::DataTypes.instance) expect(object.name).to eq(:RubyDataType) @@ -262,7 +265,8 @@ def suppress_yard_logging describe 'parsing a valid data type definition' do # TODO: What about testing for `type_parameters => {}` # e.g. https://github.com/puppetlabs/puppet/blob/main/lib/puppet/datatypes/error.rb - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # An example Puppet Data Type in Ruby. # # @param msg A message parameter5. @@ -286,11 +290,11 @@ def suppress_yard_logging PUPPET end SOURCE - } + end - it 'should register a data type object' do - expect(subject.size).to eq(1) - object = subject.first + it 'registers a data type object' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::DataType) expect(object.namespace).to eq(PuppetStrings::Yard::CodeObjects::DataTypes.instance) expect(object.name).to eq(:RubyDataType) @@ -320,7 +324,7 @@ def suppress_yard_logging func = object.functions.first expect(func.name).to eq(:func1) expect(func.docstring).to eq('func1 documentation') - expect(func.tag(:return)).to_not be_nil + expect(func.tag(:return)).not_to be_nil expect(func.tag(:return).types).to eq(['Optional[String]']) param_tags = func.docstring.tags(:param) expect(param_tags.size).to eq(2) @@ -333,7 +337,8 @@ def suppress_yard_logging end context 'with multiple interfaces' do - let(:source) do <<-SOURCE + let(:source) do + <<-SOURCE # An example Puppet Data Type in Ruby. # # @param msg A message parameter5. @@ -379,11 +384,11 @@ def suppress_yard_logging SOURCE end - it 'should register only the first valid interface' do + it 'registers only the first valid interface' do suppress_yard_logging - expect(subject.size).to eq(1) - object = subject.first + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object.name).to eq(:RubyDataType) # Check that the param tags are set @@ -398,7 +403,8 @@ def suppress_yard_logging end context 'with missing, partial and addition function parameters' do - let(:source) do <<-SOURCE + let(:source) do + <<-SOURCE # An example Puppet Data Type in Ruby. # # @!method func1(foo1, foo2) @@ -425,27 +431,31 @@ def suppress_yard_logging SOURCE end - it 'should output a warning about the incorrect return type' do - expect{ subject }.to output(/\[warn\]: The @return tag for 'func1' has a different type definition .+ Expected \["Optional\[String\]"\]/m).to_stdout_from_any_process + it 'outputs a warning about the incorrect return type' do + expect { spec_subject }.to output(%r{\[warn\]: The @return tag for 'func1' has a different type definition .+ Expected \["Optional\[String\]"\]}m).to_stdout_from_any_process end - it 'should output a warning about the additional parameter' do - expect{ subject }.to output(/\[warn\]: The @param tag for 'extra' should not exist for function 'func1' that is defined near/m).to_stdout_from_any_process + it 'outputs a warning about the additional parameter' do + expect { spec_subject }.to output(%r{\[warn\]: The @param tag for 'extra' should not exist for function 'func1' that is defined near}m).to_stdout_from_any_process end - it 'should output a warning about the wrong parameter type (func1)' do - expect{ subject }.to output(/\[warn\]: The @param tag for 'foo1' for function 'func1' has a different type definition than the actual function near .+ Expected \["Integer"\]/m).to_stdout_from_any_process + it 'outputs a warning about the wrong parameter type (func1)' do + expect { + spec_subject + } .to output(%r{\[warn\]: The @param tag for 'foo1' for function 'func1' has a different type definition than the actual function near .+ Expected \["Integer"\]}m).to_stdout_from_any_process end - it 'should output a warning about the wrong parameter type (func2)' do - expect{ subject }.to output(/\[warn\]: The @param tag for 'param1' for function 'func2' has a different type definition than the actual function near .+ Expected \["Integer"\]/m).to_stdout_from_any_process + it 'outputs a warning about the wrong parameter type (func2)' do + expect { + spec_subject + } .to output(%r{\[warn\]: The @param tag for 'param1' for function 'func2' has a different type definition than the actual function near .+ Expected \["Integer"\]}m).to_stdout_from_any_process end it 'automatically fixes function parameters, except for differring types' do suppress_yard_logging - expect(subject.size).to eq(1) - object = subject.first + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::DataType) # Check for functions @@ -453,7 +463,7 @@ def suppress_yard_logging func = object.functions.first expect(func.docstring).to eq('func1 docs') - expect(func.tag(:return)).to_not be_nil + expect(func.tag(:return)).not_to be_nil expect(func.tag(:return).types).to eq(['Optional[String]']) param_tags = func.docstring.tags(:param) expect(param_tags.size).to eq(2) @@ -478,18 +488,19 @@ def suppress_yard_logging end end - testcases = [ - { :value => '-1', :expected => -1 }, - { :value => '0', :expected => 0 }, - { :value => '10', :expected => 10 }, - { :value => '0777', :expected => 511 }, - { :value => '0xFF', :expected => 255 }, - { :value => '0.1', :expected => 0.1 }, - { :value => '31.415e-1', :expected => 3.1415 }, - { :value => '0.31415e1', :expected => 3.1415 } + [ + { value: '-1', expected: -1 }, + { value: '0', expected: 0 }, + { value: '10', expected: 10 }, + { value: '0777', expected: 511 }, + { value: '0xFF', expected: 255 }, + { value: '0.1', expected: 0.1 }, + { value: '31.415e-1', expected: 3.1415 }, + { value: '0.31415e1', expected: 3.1415 }, ].each do |testcase| describe "parsing a valid data type definition with numeric default #{testcase[:value]}" do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # An example Puppet Data Type in Ruby. # @param num1 A numeric parameter Puppet::DataTypes.create_type('RubyDataType') do @@ -500,11 +511,11 @@ def suppress_yard_logging PUPPET end SOURCE - } + end - it 'should register a data type object' do - expect(subject.size).to eq(1) - object = subject.first + it 'registers a data type object' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::DataType) expect(object.parameters.size).to eq(1) expect(object.parameters[0]).to eq(['num1', testcase[:expected]]) @@ -513,7 +524,8 @@ def suppress_yard_logging end describe 'parsing an invalid data type definition' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # The msg attribute is missing a comma. # # @param msg A message parameter5. @@ -530,13 +542,13 @@ def suppress_yard_logging PUPPET end SOURCE - } + end - it 'should register a partial data type object' do + it 'registers a partial data type object' do suppress_yard_logging - expect(subject.size).to eq(1) - object = subject.first + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::DataType) expect(object.namespace).to eq(PuppetStrings::Yard::CodeObjects::DataTypes.instance) expect(object.name).to eq(:RubyDataType) @@ -558,14 +570,15 @@ def suppress_yard_logging expect(object.functions.size).to eq(0) end - it 'should log a warning' do - expect{ subject }.to output(/\[warn\]: Invalid datatype definition at (.+):[0-9]+: Syntax error at 'arg1'/).to_stdout_from_any_process + it 'logs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: Invalid datatype definition at (.+):[0-9]+: Syntax error at 'arg1'}).to_stdout_from_any_process end end describe 'parsing a data type with a summary' do context 'when the summary has fewer than 140 characters' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # An example Puppet Data Type in Ruby. # # @summary A short summary. @@ -575,18 +588,19 @@ def suppress_yard_logging PUPPET end SOURCE - } + end - it 'should parse the summary' do - expect{ subject }.to output('').to_stdout_from_any_process - expect(subject.size).to eq(1) - summary = subject.first.tags(:summary) + it 'parses the summary' do + expect { spec_subject }.to output('').to_stdout_from_any_process + expect(spec_subject.size).to eq(1) + summary = spec_subject.first.tags(:summary) expect(summary.first.text).to eq('A short summary.') end end context 'when the summary has more than 140 characters' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # An example Puppet Data Type in Ruby. # # @summary A short summary that is WAY TOO LONG. AHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH this is not what a summary is for! It should be fewer than 140 characters!! @@ -596,10 +610,10 @@ def suppress_yard_logging PUPPET end SOURCE - } + end - it 'should log a warning' do - expect{ subject }.to output(/\[warn\]: The length of the summary for puppet_data_type 'RubyDataType' exceeds the recommended limit of 140 characters./).to_stdout_from_any_process + it 'logs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: The length of the summary for puppet_data_type 'RubyDataType' exceeds the recommended limit of 140 characters.}).to_stdout_from_any_process end end end diff --git a/spec/unit/puppet-strings/yard/handlers/ruby/function_handler_spec.rb b/spec/unit/puppet-strings/yard/handlers/ruby/function_handler_spec.rb index b54425f74..50f8889cf 100644 --- a/spec/unit/puppet-strings/yard/handlers/ruby/function_handler_spec.rb +++ b/spec/unit/puppet-strings/yard/handlers/ruby/function_handler_spec.rb @@ -4,34 +4,36 @@ require 'puppet-strings/yard' describe PuppetStrings::Yard::Handlers::Ruby::FunctionHandler do - subject { + subject(:spec_subject) do YARD::Parser::SourceParser.parse_string(source, :ruby) YARD::Registry.all(:puppet_function) - } + end describe 'parsing source without a function definition' do let(:source) { 'puts "hi"' } it 'no functions should be in the registry' do - expect(subject.empty?).to eq(true) + expect(spec_subject.empty?).to eq(true) end end describe 'parsing 3.x API functions' do describe 'parsing a function with a missing docstring' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::Parser::Functions.newfunction(:foo) do |*args| end SOURCE - } + end - it 'should log a warning' do - expect{ subject }.to output(/\[warn\]: Missing documentation for Puppet function 'foo' at \(stdin\):1\./).to_stdout_from_any_process + it 'logs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: Missing documentation for Puppet function 'foo' at \(stdin\):1\.}).to_stdout_from_any_process end end describe 'parsing a function with a doc parameter' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::Parser::Functions.newfunction(:foo, doc: <<-DOC An example 3.x function. @param [String] first The first parameter. @@ -41,11 +43,11 @@ ) do |*args| end SOURCE - } + end - it 'should register a function object' do - expect(subject.size).to eq(1) - object = subject.first + it 'registers a function object' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::Function) expect(object.namespace).to eq(PuppetStrings::Yard::CodeObjects::Functions.instance(PuppetStrings::Yard::CodeObjects::Function::RUBY_3X)) expect(object.name).to eq(:foo) @@ -73,7 +75,8 @@ end describe 'parsing a function with a doc parameter which has a newline between the namespace and the newfunction call' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE module Puppet::Parser::Functions newfunction(:foo, doc: <<-DOC An example 3.x function. @@ -85,11 +88,11 @@ module Puppet::Parser::Functions end end SOURCE - } + end - it 'should register a function object' do - expect(subject.size).to eq(1) - object = subject.first + it 'registers a function object' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::Function) expect(object.namespace).to eq(PuppetStrings::Yard::CodeObjects::Functions.instance(PuppetStrings::Yard::CodeObjects::Function::RUBY_3X)) expect(object.name).to eq(:foo) @@ -117,7 +120,8 @@ module Puppet::Parser::Functions end describe 'parsing a function with a missing @return tag' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::Parser::Functions.newfunction(:foo, doc: <<-DOC) do |*args| An example 3.x function. @param [String] first The first parameter. @@ -125,38 +129,40 @@ module Puppet::Parser::Functions DOC end SOURCE - } + end - it 'should log a warning' do - expect{ subject }.to output(/\[warn\]: Missing @return tag near \(stdin\):1/).to_stdout_from_any_process + it 'logs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: Missing @return tag near \(stdin\):1}).to_stdout_from_any_process end end end describe 'parsing 4.x API functions' do describe 'parsing a function with a missing docstring' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::Functions.create_function(:foo) do end SOURCE - } + end - it 'should log a warning' do - expect{ subject }.to output(/\[warn\]: Missing documentation for Puppet function 'foo' at \(stdin\):1\./).to_stdout_from_any_process + it 'logs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: Missing documentation for Puppet function 'foo' at \(stdin\):1\.}).to_stdout_from_any_process end end describe 'parsing a function with a simple docstring' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # An example 4.x function. Puppet::Functions.create_function(:foo) do end SOURCE - } + end - it 'should register a function object' do - expect(subject.size).to eq(1) - object = subject.first + it 'registers a function object' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::Function) expect(object.namespace).to eq(PuppetStrings::Yard::CodeObjects::Functions.instance(PuppetStrings::Yard::CodeObjects::Function::RUBY_4X)) expect(object.name).to eq(:foo) @@ -171,7 +177,8 @@ module Puppet::Parser::Functions end describe 'parsing a function without any dispatches' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # An example 4.x function. Puppet::Functions.create_function(:foo) do # @param [Integer] param1 The first parameter. @@ -182,11 +189,11 @@ def foo(param1, param2, param3 = nil) end end SOURCE - } + end - it 'should register a function object' do - expect(subject.size).to eq(1) - object = subject.first + it 'registers a function object' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::Function) expect(object.namespace).to eq(PuppetStrings::Yard::CodeObjects::Functions.instance(PuppetStrings::Yard::CodeObjects::Function::RUBY_4X)) expect(object.name).to eq(:foo) @@ -217,7 +224,8 @@ def foo(param1, param2, param3 = nil) end describe 'parsing a function with a single dispatch' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # An example 4.x function. Puppet::Functions.create_function(:foo) do # @param param1 The first parameter. @@ -234,11 +242,11 @@ def foo(param1, param2, param3 = nil) end end SOURCE - } + end - it 'should register a function object without any overload tags' do - expect(subject.size).to eq(1) - object = subject.first + it 'registers a function object without any overload tags' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::Function) expect(object.namespace).to eq(PuppetStrings::Yard::CodeObjects::Functions.instance(PuppetStrings::Yard::CodeObjects::Function::RUBY_4X)) expect(object.name).to eq(:foo) @@ -270,7 +278,8 @@ def foo(param1, param2, param3 = nil) end describe 'parsing a function using only return_type' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # An example 4.x function. Puppet::Functions.create_function(:foo) do # @param param1 The first parameter. @@ -288,14 +297,14 @@ def foo(param1, param2, param3 = nil) end end SOURCE - } + end it 'does not throw an error with no @return' do - expect { subject }.not_to raise_error + expect { spec_subject }.not_to raise_error end it 'contains a return data type' do - tags = subject.first.docstring.tags(:return) + tags = spec_subject.first.docstring.tags(:return) expect(tags.size).to eq(1) expect(tags[0].name).to be_nil expect(tags[0].types).to eq(['String']) @@ -303,7 +312,8 @@ def foo(param1, param2, param3 = nil) end describe 'parsing a function with various dispatch parameters.' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # An example 4.x function. Puppet::Functions.create_function(:foo) do # @param param1 The first parameter. @@ -319,11 +329,11 @@ def foo(param1, param2, param3 = nil) end end SOURCE - } + end - it 'should register a function object with the expected parameters' do - expect(subject.size).to eq(1) - object = subject.first + it 'registers a function object with the expected parameters' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::Function) expect(object.namespace).to eq(PuppetStrings::Yard::CodeObjects::Functions.instance(PuppetStrings::Yard::CodeObjects::Function::RUBY_4X)) expect(object.name).to eq(:foo) @@ -358,7 +368,8 @@ def foo(param1, param2, param3 = nil) end describe 'parsing a function with an optional repeated param.' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # An example 4.x function. Puppet::Functions.create_function(:foo) do # @param param The first parameter. @@ -368,11 +379,11 @@ def foo(param1, param2, param3 = nil) end end SOURCE - } + end - it 'should register a function object with the expected parameters' do - expect(subject.size).to eq(1) - object = subject.first + it 'registers a function object with the expected parameters' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::Function) expect(object.namespace).to eq(PuppetStrings::Yard::CodeObjects::Functions.instance(PuppetStrings::Yard::CodeObjects::Function::RUBY_4X)) expect(object.name).to eq(:foo) @@ -398,7 +409,8 @@ def foo(param1, param2, param3 = nil) end describe 'parsing a function with a block param with one parameter' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # An example 4.x function. Puppet::Functions.create_function(:foo) do # @param a_block The block parameter. @@ -408,11 +420,11 @@ def foo(param1, param2, param3 = nil) end end SOURCE - } + end - it 'should register a function object with the expected parameters' do - expect(subject.size).to eq(1) - object = subject.first + it 'registers a function object with the expected parameters' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::Function) expect(object.namespace).to eq(PuppetStrings::Yard::CodeObjects::Functions.instance(PuppetStrings::Yard::CodeObjects::Function::RUBY_4X)) expect(object.name).to eq(:foo) @@ -438,7 +450,8 @@ def foo(param1, param2, param3 = nil) end describe 'parsing a function with a block param with two parameter' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # An example 4.x function. Puppet::Functions.create_function(:foo) do # @param a_block The block parameter. @@ -448,11 +461,11 @@ def foo(param1, param2, param3 = nil) end end SOURCE - } + end - it 'should register a function object with the expected parameters' do - expect(subject.size).to eq(1) - object = subject.first + it 'registers a function object with the expected parameters' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::Function) expect(object.namespace).to eq(PuppetStrings::Yard::CodeObjects::Functions.instance(PuppetStrings::Yard::CodeObjects::Function::RUBY_4X)) expect(object.name).to eq(:foo) @@ -479,7 +492,8 @@ def foo(param1, param2, param3 = nil) end describe 'parsing a function with a multiple dispatches' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # An example 4.x function. Puppet::Functions.create_function(:foo) do # The first overload. @@ -510,11 +524,11 @@ def other(b) end end SOURCE - } + end - it 'should register a function object with overload tags' do - expect(subject.size).to eq(1) - object = subject.first + it 'registers a function object with overload tags' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::Function) expect(object.namespace).to eq(PuppetStrings::Yard::CodeObjects::Functions.instance(PuppetStrings::Yard::CodeObjects::Function::RUBY_4X)) expect(object.name).to eq(:foo) @@ -570,7 +584,8 @@ def other(b) end describe 'parsing a function with a namespaced name' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # An example 4.x function. Puppet::Functions.create_function(:'foo::bar::baz') do # @return [Undef] @@ -578,16 +593,17 @@ def other(b) end end SOURCE - } + end - it 'should output the name correctly as a symbol' do - expect(subject.size).to eq(1) - expect(subject.first.name).to eq(:'foo::bar::baz') + it 'outputs the name correctly as a symbol' do + expect(spec_subject.size).to eq(1) + expect(spec_subject.first.name).to eq(:'foo::bar::baz') end end describe 'parsing a function with a missing parameter' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # An example 4.x function. Puppet::Functions.create_function(:foo) do # @param missing A missing parameter. @@ -596,15 +612,16 @@ def other(b) end end SOURCE - } + end - it 'should output a warning' do - expect{ subject }.to output(/\[warn\]: The @param tag for parameter 'missing' has no matching parameter at \(stdin\):5/).to_stdout_from_any_process + it 'outputs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: The @param tag for parameter 'missing' has no matching parameter at \(stdin\):5}).to_stdout_from_any_process end end describe 'parsing a function with a missing @param tag' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # An example 4.x function. Puppet::Functions.create_function(:foo) do # @return [Undef] Returns nothing. @@ -613,15 +630,16 @@ def other(b) end end SOURCE - } + end - it 'should output a warning' do - expect{ subject }.to output(/\[warn\]: Missing @param tag for parameter 'param1' near \(stdin\):5/).to_stdout_from_any_process + it 'outputs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: Missing @param tag for parameter 'param1' near \(stdin\):5}).to_stdout_from_any_process end end describe 'parsing a function with a typed @param tag' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # An example 4.x function. Puppet::Functions.create_function(:foo) do # @param [Integer] param1 The first parameter. @@ -631,15 +649,20 @@ def other(b) end end SOURCE - } + end - it 'should output a warning' do - expect{ subject }.to output(/\[warn\]: The @param tag for parameter 'param1' should not contain a type specification near \(stdin\):6: ignoring in favor of dispatch type information\./).to_stdout_from_any_process + it 'outputs a warning' do + expect { spec_subject } + .to output( + %r{\[warn\]: The @param tag for parameter 'param1' should not contain a type specification near \(stdin\):6: ignoring in favor of dispatch type information\.}, + ) + .to_stdout_from_any_process end end describe 'parsing a function with a typed @param tag' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # An example 4.x function. Puppet::Functions.create_function(:foo) do # @param param1 The first parameter. @@ -648,15 +671,16 @@ def other(b) end end SOURCE - } + end - it 'should output a warning' do - expect{ subject }.to output(/\[warn\]: Missing @return tag near \(stdin\):4/).to_stdout_from_any_process + it 'outputs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: Missing @return tag near \(stdin\):4}).to_stdout_from_any_process end end describe 'parsing a function with a root @param tag' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # An example 4.x function. # @param param Nope. Puppet::Functions.create_function(:foo) do @@ -665,16 +689,20 @@ def other(b) end end SOURCE - } + end - it 'should output a warning' do - expect{ subject }.to output(/\[warn\]: The docstring for Puppet 4.x function 'foo' contains @param tags near \(stdin\):3: parameter documentation should be made on the dispatch call\./).to_stdout_from_any_process + it 'outputs a warning' do + expect { spec_subject } + .to output( + %r{\[warn\]: The docstring for Puppet 4.x function 'foo' contains @param tags near \(stdin\):3: parameter documentation should be made on the dispatch call\.}, + ) + .to_stdout_from_any_process end end - describe 'parsing a function with a root @overload tag' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # An example 4.x function. # @overload foo Puppet::Functions.create_function(:foo) do @@ -683,15 +711,20 @@ def other(b) end end SOURCE - } + end - it 'should output a warning' do - expect{ subject }.to output(/\[warn\]: The docstring for Puppet 4.x function 'foo' contains @overload tags near \(stdin\):3: overload tags are automatically generated from the dispatch calls\./).to_stdout_from_any_process + it 'outputs a warning' do + expect { spec_subject } + .to output( + %r{\[warn\]: The docstring for Puppet 4.x function 'foo' contains @overload tags near \(stdin\):3: overload tags are automatically generated from the dispatch calls\.}, + ) + .to_stdout_from_any_process end end describe 'parsing a function with a root @return tag' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # An example 4.x function. # @return [Undef] foo Puppet::Functions.create_function(:foo) do @@ -700,16 +733,21 @@ def other(b) end end SOURCE - } + end - it 'should output a warning' do - expect{ subject }.to output(/\[warn\]: The docstring for Puppet 4.x function 'foo' contains @return tags near \(stdin\):3: return value documentation should be made on the dispatch call\./).to_stdout_from_any_process + it 'outputs a warning' do + expect { spec_subject } + .to output( + %r{\[warn\]: The docstring for Puppet 4.x function 'foo' contains @return tags near \(stdin\):3: return value documentation should be made on the dispatch call\.}, + ) + .to_stdout_from_any_process end end describe 'parsing a function with a summary' do context 'when the summary has fewer than 140 characters' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # An example 4.x function. # @summary A short summary. Puppet::Functions.create_function(:foo) do @@ -718,18 +756,19 @@ def other(b) end end SOURCE - } + end - it 'should parse the summary' do - expect{ subject }.to output('').to_stdout_from_any_process - expect(subject.size).to eq(1) - summary = subject.first.tags(:summary) + it 'parses the summary' do + expect { spec_subject }.to output('').to_stdout_from_any_process + expect(spec_subject.size).to eq(1) + summary = spec_subject.first.tags(:summary) expect(summary.first.text).to eq('A short summary.') end end context 'when the summary has more than 140 characters' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # An example 4.x function. # @summary A short summary that is WAY TOO LONG. AHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH this is not what a summary is for! It should be fewer than 140 characters!! Puppet::Functions.create_function(:foo) do @@ -738,10 +777,10 @@ def other(b) end end SOURCE - } + end - it 'should log a warning' do - expect{ subject }.to output(/\[warn\]: The length of the summary for puppet_function 'foo' exceeds the recommended limit of 140 characters./).to_stdout_from_any_process + it 'logs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: The length of the summary for puppet_function 'foo' exceeds the recommended limit of 140 characters.}).to_stdout_from_any_process end end end diff --git a/spec/unit/puppet-strings/yard/handlers/ruby/provider_handler_spec.rb b/spec/unit/puppet-strings/yard/handlers/ruby/provider_handler_spec.rb index cc1edd9bd..31cf0fae3 100644 --- a/spec/unit/puppet-strings/yard/handlers/ruby/provider_handler_spec.rb +++ b/spec/unit/puppet-strings/yard/handlers/ruby/provider_handler_spec.rb @@ -4,78 +4,83 @@ require 'puppet-strings/yard' describe PuppetStrings::Yard::Handlers::Ruby::ProviderHandler do - subject { + subject(:spec_subject) do YARD::Parser::SourceParser.parse_string(source, :ruby) YARD::Registry.all(:puppet_provider) - } + end describe 'parsing source without a provider definition' do let(:source) { 'puts "hi"' } it 'no providers should be in the registry' do - expect(subject.empty?).to eq(true) + expect(spec_subject.empty?).to eq(true) end end describe 'parsing a provider with a missing description' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::Type.type(:custom).provide :linux do end SOURCE - } + end - it 'should log a warning' do - expect{ subject }.to output(/\[warn\]: Missing a description for Puppet provider 'linux' \(resource type 'custom'\) at \(stdin\):1\./).to_stdout_from_any_process + it 'logs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: Missing a description for Puppet provider 'linux' \(resource type 'custom'\) at \(stdin\):1\.}).to_stdout_from_any_process end end describe 'parsing a provider with an invalid docstring assignment' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::Type.type(:custom).provide :linux do @doc = 123 end SOURCE - } + end - it 'should log an error' do - expect { subject }.to output(/Failed to parse docstring/).to_stdout_from_any_process + it 'logs an error' do + expect { spec_subject }.to output(%r{Failed to parse docstring}).to_stdout_from_any_process end end describe 'parsing a provider with a valid docstring assignment' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::Type.type(:custom).provide :linux do @doc = 'An example provider on Linux.' end SOURCE - } + end - it 'should correctly detect the docstring' do - expect(subject.size).to eq(1) - object = subject.first + it 'correctlies detect the docstring' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object.docstring).to eq('An example provider on Linux.') end end describe 'parsing a provider with a docstring which uses ruby `%Q` notation' do - let(:source) { <<-'SOURCE' + let(:source) do + <<-'SOURCE' Puppet::Type.type(:custom).provide :linux do test = 'hello world!' desc %Q{This is a multi-line doc in %Q with #{test}} end SOURCE - } + end - it 'should strip the `%Q{}` and render the interpolation expression literally' do - expect(subject.size).to eq(1) - object = subject.first + it 'strips the `%Q{}` and render the interpolation expression literally' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object.docstring).to eq("This is a multi-line\ndoc in %Q with \#{test}") end end describe 'parsing a provider definition' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::Type.type(:custom).provide :linux do desc 'An example provider on Linux.' confine kernel: 'Linux' @@ -87,11 +92,11 @@ commands foo: '/usr/bin/foo' end SOURCE - } + end - it 'should register a provider object' do - expect(subject.size).to eq(1) - object = subject.first + it 'registers a provider object' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::Provider) expect(object.namespace).to eq(PuppetStrings::Yard::CodeObjects::Providers.instance('custom')) expect(object.name).to eq(:linux) @@ -101,24 +106,25 @@ tags = object.docstring.tags(:api) expect(tags.size).to eq(1) expect(tags[0].text).to eq('public') - expect(object.confines).to eq({ 'kernel' => 'Linux', 'osfamily' => 'RedHat'}) - expect(object.defaults).to eq([[["kernel", "Linux"]], [["osfamily", "RedHat"], ["operatingsystemmajrelease", "7"]]]) + expect(object.confines).to eq({ 'kernel' => 'Linux', 'osfamily' => 'RedHat' }) + expect(object.defaults).to eq([[['kernel', 'Linux']], [['osfamily', 'RedHat'], ['operatingsystemmajrelease', '7']]]) expect(object.features).to eq(['implements_some_feature', 'some_other_feature']) - expect(object.commands).to eq({'foo' => '/usr/bin/foo'}) + expect(object.commands).to eq({ 'foo' => '/usr/bin/foo' }) end end describe 'parsing a provider definition with a string based name' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::Type.type(:'custom').provide :'linux' do desc 'An example provider on Linux.' end SOURCE - } + end - it 'should register a provider object' do - expect(subject.size).to eq(1) - object = subject.first + it 'registers a provider object' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::Provider) expect(object.namespace).to eq(PuppetStrings::Yard::CodeObjects::Providers.instance('custom')) expect(object.name).to eq(:linux) @@ -129,31 +135,33 @@ describe 'parsing a provider with a summary' do context 'when the summary has fewer than 140 characters' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::Type.type(:custom).provide :linux do @doc = '@summary A short summary.' end SOURCE - } + end - it 'should parse the summary' do - expect{ subject }.to output('').to_stdout_from_any_process - expect(subject.size).to eq(1) - summary = subject.first.tags(:summary) + it 'parses the summary' do + expect { spec_subject }.to output('').to_stdout_from_any_process + expect(spec_subject.size).to eq(1) + summary = spec_subject.first.tags(:summary) expect(summary.first.text).to eq('A short summary.') end end context 'when the summary has more than 140 characters' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::Type.type(:custom).provide :linux do @doc = '@summary A short summary that is WAY TOO LONG. AHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH this is not what a summary is for! It should be fewer than 140 characters!!' end SOURCE - } + end - it 'should log a warning' do - expect{ subject }.to output(/\[warn\]: The length of the summary for puppet_provider 'linux' exceeds the recommended limit of 140 characters./).to_stdout_from_any_process + it 'logs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: The length of the summary for puppet_provider 'linux' exceeds the recommended limit of 140 characters.}).to_stdout_from_any_process end end end diff --git a/spec/unit/puppet-strings/yard/handlers/ruby/rsapi_handler_spec.rb b/spec/unit/puppet-strings/yard/handlers/ruby/rsapi_handler_spec.rb index 3bcde409f..b5f1c3d68 100644 --- a/spec/unit/puppet-strings/yard/handlers/ruby/rsapi_handler_spec.rb +++ b/spec/unit/puppet-strings/yard/handlers/ruby/rsapi_handler_spec.rb @@ -4,50 +4,53 @@ require 'puppet-strings/yard' describe PuppetStrings::Yard::Handlers::Ruby::RsapiHandler do - subject { + subject(:spec_subject) do YARD::Parser::SourceParser.parse_string(source, :ruby) YARD::Registry.all(:puppet_type) - } + end describe 'parsing source without a type definition' do let(:source) { 'puts "hi"' } it 'no types should be in the registry' do - expect(subject.empty?).to eq(true) + expect(spec_subject.empty?).to eq(true) end end describe 'parsing a type with a missing description' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::ResourceApi.register_type( name: 'database' ) SOURCE - } + end - it 'should log a warning' do - expect{ subject }.to output(/\[warn\]: Missing a description for Puppet resource type 'database' at \(stdin\):1\./).to_stdout_from_any_process + it 'logs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: Missing a description for Puppet resource type 'database' at \(stdin\):1\.}).to_stdout_from_any_process end end describe 'parsing a type with a valid docstring assignment' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::ResourceApi.register_type( name: 'database', docs: 'An example database server resource type.', ) SOURCE - } + end - it 'should correctly detect the docstring' do - expect(subject.size).to eq(1) - object = subject.first + it 'correctlies detect the docstring' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object.docstring).to eq('An example database server resource type.') end end describe 'parsing a type with a docstring which uses ruby `%Q` notation' do - let(:source) { <<-'SOURCE' + let(:source) do + <<-'SOURCE' test = 'hello world!' Puppet::ResourceApi.register_type( @@ -56,17 +59,18 @@ doc in %Q with #{test}}, ) SOURCE - } + end - it 'should strip the `%Q{}` and render the interpolation expression literally' do - expect(subject.size).to eq(1) - object = subject.first + it 'strips the `%Q{}` and render the interpolation expression literally' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object.docstring).to eq("This is a multi-line\ndoc in %Q with \#{test}") end end describe 'parsing a type definition' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # @!puppet.type.param [value1, value2] dynamic_param Documentation for a dynamic parameter. # @!puppet.type.property [foo, bar] dynamic_prop Documentation for a dynamic property. Puppet::ResourceApi.register_type( @@ -113,11 +117,11 @@ }, ) SOURCE - } + end - it 'should register a type object' do - expect(subject.size).to eq(1) - object = subject.first + it 'registers a type object' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::Type) expect(object.namespace).to eq(PuppetStrings::Yard::CodeObjects::Types.instance) expect(object.name).to eq(:database) @@ -131,7 +135,7 @@ expect(object.properties[0].name).to eq('dynamic_prop') expect(object.properties[0].docstring).to eq('Documentation for a dynamic property.') expect(object.properties[0].isnamevar).to eq(false) - expect(object.properties[0].values).to eq(%w(foo bar)) + expect(object.properties[0].values).to eq(['foo', 'bar']) expect(object.properties[1].name).to eq('ensure') expect(object.properties[1].docstring).to eq('What state the database should be in.') expect(object.properties[1].isnamevar).to eq(false) @@ -154,7 +158,7 @@ expect(object.parameters[0].name).to eq('dynamic_param') expect(object.parameters[0].docstring).to eq('Documentation for a dynamic parameter.') expect(object.parameters[0].isnamevar).to eq(false) - expect(object.parameters[0].values).to eq(%w(value1 value2)) + expect(object.parameters[0].values).to eq(['value1', 'value2']) expect(object.parameters[1].name).to eq('address') expect(object.parameters[1].docstring).to eq('The database server name.') expect(object.parameters[1].isnamevar).to eq(true) @@ -165,57 +169,60 @@ expect(object.parameters[2].docstring).to eq('Whether or not to encrypt the database.') expect(object.parameters[2].isnamevar).to eq(false) expect(object.parameters[2].default).to eq(false) - expect(object.parameters[2].data_type).to eq("Boolean") + expect(object.parameters[2].data_type).to eq('Boolean') expect(object.parameters[2].aliases).to eq({}) expect(object.parameters[3].name).to eq('encryption_key') expect(object.parameters[3].docstring).to eq('The encryption key to use.') expect(object.parameters[3].isnamevar).to eq(false) expect(object.parameters[3].default).to be_nil - expect(object.parameters[3].data_type).to eq("Optional[String]") + expect(object.parameters[3].data_type).to eq('Optional[String]') expect(object.parameters[3].aliases).to eq({}) expect(object.parameters[4].name).to eq('backup') expect(object.parameters[4].docstring).to eq('How often to backup the database.') expect(object.parameters[4].isnamevar).to eq(false) expect(object.parameters[4].default).to eq('never') - expect(object.parameters[4].data_type).to eq("Enum[daily, monthly, never]") + expect(object.parameters[4].data_type).to eq('Enum[daily, monthly, never]') end end describe 'parsing a type with a summary' do context 'when the summary has fewer than 140 characters' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::ResourceApi.register_type( name: 'database', docs: '@summary A short summary.', ) SOURCE - } + end - it 'should parse the summary' do - expect{ subject }.to output('').to_stdout_from_any_process - expect(subject.size).to eq(1) - summary = subject.first.tags(:summary) + it 'parses the summary' do + expect { spec_subject }.to output('').to_stdout_from_any_process + expect(spec_subject.size).to eq(1) + summary = spec_subject.first.tags(:summary) expect(summary.first.text).to eq('A short summary.') end end context 'when the summary has more than 140 characters' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::ResourceApi.register_type( name: 'database', docs: '@summary A short summary that is WAY TOO LONG. AHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH this is not what a summary is for! It should be fewer than 140 characters!!', ) SOURCE - } + end - it 'should log a warning' do - expect{ subject }.to output(/\[warn\]: The length of the summary for puppet_type 'database' exceeds the recommended limit of 140 characters./).to_stdout_from_any_process + it 'logs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: The length of the summary for puppet_type 'database' exceeds the recommended limit of 140 characters.}).to_stdout_from_any_process end end end describe 'parsing a type with title_patterns' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::ResourceApi.register_type( name: 'database', docs: 'An example database server resource type.', @@ -227,11 +234,10 @@ ] ) SOURCE - } + end - it 'should not emit a warning' do - expect{ subject }.not_to output(/\[warn\].*unexpected construct regexp_literal/).to_stdout_from_any_process + it 'does not emit a warning' do + expect { spec_subject }.not_to output(%r{\[warn\].*unexpected construct regexp_literal}).to_stdout_from_any_process end end - end diff --git a/spec/unit/puppet-strings/yard/handlers/ruby/type_extras_handler_spec.rb b/spec/unit/puppet-strings/yard/handlers/ruby/type_extras_handler_spec.rb index 141c3feda..ada072717 100644 --- a/spec/unit/puppet-strings/yard/handlers/ruby/type_extras_handler_spec.rb +++ b/spec/unit/puppet-strings/yard/handlers/ruby/type_extras_handler_spec.rb @@ -4,13 +4,14 @@ require 'puppet-strings/yard' describe PuppetStrings::Yard::Handlers::Ruby::TypeExtrasHandler do - subject { + subject(:spec_subject) do YARD::Parser::SourceParser.parse_string(source, :ruby) YARD::Registry.all(:puppet_type) - } + end describe 'parsing source with newproperty' do - let(:source) { <<~SOURCE + let(:source) do + <<~SOURCE Puppet::Type.newtype(:database) do desc 'database' end @@ -18,11 +19,11 @@ desc 'The database file to use.' end SOURCE - } + end it 'generates a doc string for a property' do - expect(subject.size).to eq(1) - object = subject.first + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object.properties.size).to eq(1) expect(object.properties[0].name).to eq('file') expect(object.properties[0].docstring).to eq('The database file to use.') @@ -30,7 +31,8 @@ end describe 'parsing source with newparam' do - let(:source) { <<~SOURCE + let(:source) do + <<~SOURCE Puppet::Type.newtype(:database) do desc 'database' end @@ -38,11 +40,11 @@ desc 'The database server name.' end SOURCE - } + end it 'generates a doc string for a parameter that is also a namevar' do - expect(subject.size).to eq(1) - object = subject.first + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object.parameters.size).to eq(1) expect(object.parameters[0].name).to eq('name') expect(object.parameters[0].docstring).to eq('The database server name.') @@ -51,7 +53,8 @@ end describe 'parsing source with ensurable' do - let(:source) { <<~SOURCE + let(:source) do + <<~SOURCE Puppet::Type.newtype(:database) do desc 'database' end @@ -59,11 +62,11 @@ desc 'What state the database should be in.' end SOURCE - } + end it 'generates a doc string for an ensurable' do - expect(subject.size).to eq(1) - object = subject.first + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object.properties.size).to eq(1) expect(object.properties[0].name).to eq('ensure') expect(object.properties[0].docstring).to eq('What state the database should be in.') diff --git a/spec/unit/puppet-strings/yard/handlers/ruby/type_handler_spec.rb b/spec/unit/puppet-strings/yard/handlers/ruby/type_handler_spec.rb index dd7a8a6a0..604912b4f 100644 --- a/spec/unit/puppet-strings/yard/handlers/ruby/type_handler_spec.rb +++ b/spec/unit/puppet-strings/yard/handlers/ruby/type_handler_spec.rb @@ -4,78 +4,83 @@ require 'puppet-strings/yard' describe PuppetStrings::Yard::Handlers::Ruby::TypeHandler do - subject { + subject(:spec_subject) do YARD::Parser::SourceParser.parse_string(source, :ruby) YARD::Registry.all(:puppet_type) - } + end describe 'parsing source without a type definition' do let(:source) { 'puts "hi"' } it 'no types should be in the registry' do - expect(subject.empty?).to eq(true) + expect(spec_subject.empty?).to eq(true) end end describe 'parsing a type with a missing description' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::Type.newtype(:database) do end SOURCE - } + end - it 'should log a warning' do - expect{ subject }.to output(/\[warn\]: Missing a description for Puppet resource type 'database' at \(stdin\):1\./).to_stdout_from_any_process + it 'logs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: Missing a description for Puppet resource type 'database' at \(stdin\):1\.}).to_stdout_from_any_process end end describe 'parsing a type with an invalid docstring assignment' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::Type.newtype(:database) do @doc = 123 end SOURCE - } + end - it 'should log an error' do - expect { subject }.to output(/Failed to parse docstring/).to_stdout_from_any_process + it 'logs an error' do + expect { spec_subject }.to output(%r{Failed to parse docstring}).to_stdout_from_any_process end end describe 'parsing a type with a valid docstring assignment' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::Type.newtype(:database) do @doc = 'An example database server resource type.' end SOURCE - } + end - it 'should correctly detect the docstring' do - expect(subject.size).to eq(1) - object = subject.first + it 'correctlies detect the docstring' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object.docstring).to eq('An example database server resource type.') end end describe 'parsing a type with a docstring which uses ruby `%Q` notation' do - let(:source) { <<-'SOURCE' + let(:source) do + <<-'SOURCE' Puppet::Type.newtype(:database) do test = 'hello world!' desc %Q{This is a multi-line doc in %Q with #{test}} end SOURCE - } + end - it 'should strip the `%Q{}` and render the interpolation expression literally' do - expect(subject.size).to eq(1) - object = subject.first + it 'strips the `%Q{}` and render the interpolation expression literally' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object.docstring).to eq("This is a multi-line\ndoc in %Q with \#{test}") end end describe 'parsing a type with a param with arguments' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::Type.newtype(:database) do feature :encryption, 'The provider supports encryption.', methods: [:encrypt] @@ -85,23 +90,24 @@ end end SOURCE - } + end - it 'should correctly detect the required_feature' do - expect(subject.size).to eq(1) - object = subject.first + it 'correctlies detect the required_feature' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object.parameters[0].required_features).to eq('encryption') end - it 'should correctly detect a boolean parent' do - expect(subject.size).to eq(1) - object = subject.first + it 'correctlies detect a boolean parent' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object.parameters[0].default).to eq('false') end end describe 'parsing a type definition' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # @!puppet.type.param [value1, value2] dynamic_param Documentation for a dynamic parameter. # @!puppet.type.property [foo, bar] dynamic_prop Documentation for a dynamic property. Puppet::Type.newtype(:database) do @@ -153,11 +159,11 @@ end end SOURCE - } + end - it 'should register a type object' do - expect(subject.size).to eq(1) - object = subject.first + it 'registers a type object' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object).to be_a(PuppetStrings::Yard::CodeObjects::Type) expect(object.namespace).to eq(PuppetStrings::Yard::CodeObjects::Types.instance) expect(object.name).to eq(:database) @@ -170,12 +176,12 @@ expect(object.properties[0].name).to eq('dynamic_prop') expect(object.properties[0].docstring).to eq('Documentation for a dynamic property.') expect(object.properties[0].isnamevar).to eq(false) - expect(object.properties[0].values).to eq(%w(foo bar)) + expect(object.properties[0].values).to eq(['foo', 'bar']) expect(object.properties[1].name).to eq('ensure') expect(object.properties[1].docstring).to eq('What state the database should be in.') expect(object.properties[1].isnamevar).to eq(false) expect(object.properties[1].default).to eq('up') - expect(object.properties[1].values).to eq(%w(present absent up down)) + expect(object.properties[1].values).to eq(['present', 'absent', 'up', 'down']) expect(object.properties[1].aliases).to eq({ 'down' => 'absent', 'up' => 'present' }) expect(object.properties[2].name).to eq('file') expect(object.properties[2].docstring).to eq('The database file to use.') @@ -187,13 +193,13 @@ expect(object.properties[3].docstring).to eq('The log level to use.') expect(object.properties[3].isnamevar).to eq(false) expect(object.properties[3].default).to eq('warn') - expect(object.properties[3].values).to eq(%w(debug warn error)) + expect(object.properties[3].values).to eq(['debug', 'warn', 'error']) expect(object.properties[3].aliases).to eq({}) expect(object.parameters.size).to eq(5) expect(object.parameters[0].name).to eq('dynamic_param') expect(object.parameters[0].docstring).to eq('Documentation for a dynamic parameter.') expect(object.parameters[0].isnamevar).to eq(false) - expect(object.parameters[0].values).to eq(%w(value1 value2)) + expect(object.parameters[0].values).to eq(['value1', 'value2']) expect(object.parameters[1].name).to eq('address') expect(object.parameters[1].docstring).to eq('The database server name.') expect(object.parameters[1].isnamevar).to eq(true) @@ -210,13 +216,13 @@ expect(object.parameters[3].docstring).to eq('Whether or not to encrypt the database.') expect(object.parameters[3].isnamevar).to eq(false) expect(object.parameters[3].default).to eq('false') - expect(object.parameters[3].values).to eq(%w(true false yes no)) + expect(object.parameters[3].values).to eq(['true', 'false', 'yes', 'no']) expect(object.parameters[3].aliases).to eq({}) expect(object.parameters[4].name).to eq('backup') expect(object.parameters[4].docstring).to eq('How often to backup the database.') expect(object.parameters[4].isnamevar).to eq(false) expect(object.parameters[4].default).to eq('never') - expect(object.parameters[4].values).to eq(%w(daily monthly never)) + expect(object.parameters[4].values).to eq(['daily', 'monthly', 'never']) expect(object.features.size).to eq(2) expect(object.features[0].name).to eq('encryption') expect(object.features[0].docstring).to eq('The provider supports encryption.') @@ -226,42 +232,45 @@ end describe 'parsing a valid type with string based name' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::Type.newtype(:'database') do desc 'An example database server resource type.' ensurable end SOURCE - } + end - it 'should register a type object with default ensure values' do - expect(subject.size).to eq(1) - object = subject.first + it 'registers a type object with default ensure values' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object.name).to eq(:database) end end describe 'parsing an ensurable type with default ensure values' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::Type.newtype(:database) do desc 'An example database server resource type.' ensurable end SOURCE - } + end - it 'should register a type object with default ensure values' do - expect(subject.size).to eq(1) - object = subject.first + it 'registers a type object with default ensure values' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object.properties[0].name).to eq('ensure') expect(object.properties[0].docstring).to eq('The basic property that the resource should be in.') expect(object.properties[0].default).to eq('present') - expect(object.properties[0].values).to eq(%w(present absent)) + expect(object.properties[0].values).to eq(['present', 'absent']) end end describe 'parsing a type with a parameter with the name of "name"' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::Type.newtype(:database) do desc 'An example database server resource type.' newparam(:name) do @@ -269,11 +278,11 @@ end end SOURCE - } + end - it 'should register a type object with the "name" parameter as the namevar' do - expect(subject.size).to eq(1) - object = subject.first + it 'registers a type object with the "name" parameter as the namevar' do + expect(spec_subject.size).to eq(1) + object = spec_subject.first expect(object.parameters.size).to eq(1) expect(object.parameters[0].name).to eq('name') expect(object.parameters[0].isnamevar).to eq(true) @@ -281,7 +290,8 @@ end describe 'parsing a type with a check with the name of "onlyif"' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::Type.newtype(:testexec) do desc 'An example exec type with a check.' newcheck(:onlyif) do @@ -289,11 +299,11 @@ end end SOURCE - } + end - it 'should register a check object on the parent type object' do - expect(subject.size).to eq(1) - type_object = subject.first + it 'registers a check object on the parent type object' do + expect(spec_subject.size).to eq(1) + type_object = spec_subject.first expect(type_object.checks.size).to eq(1) expect(type_object.checks[0].name).to eq('onlyif') end @@ -301,31 +311,33 @@ describe 'parsing a type with a summary' do context 'when the summary has fewer than 140 characters' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::Type.newtype(:database) do @doc = '@summary A short summary.' end SOURCE - } + end - it 'should parse the summary' do - expect{ subject }.to output('').to_stdout_from_any_process - expect(subject.size).to eq(1) - summary = subject.first.tags(:summary) + it 'parses the summary' do + expect { spec_subject }.to output('').to_stdout_from_any_process + expect(spec_subject.size).to eq(1) + summary = spec_subject.first.tags(:summary) expect(summary.first.text).to eq('A short summary.') end end context 'when the summary has more than 140 characters' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE Puppet::Type.newtype(:database) do @doc = '@summary A short summary that is WAY TOO LONG. AHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH this is not what a summary is for! It should be fewer than 140 characters!!' end SOURCE - } + end - it 'should log a warning' do - expect{ subject }.to output(/\[warn\]: The length of the summary for puppet_type 'database' exceeds the recommended limit of 140 characters./).to_stdout_from_any_process + it 'logs a warning' do + expect { spec_subject }.to output(%r{\[warn\]: The length of the summary for puppet_type 'database' exceeds the recommended limit of 140 characters.}).to_stdout_from_any_process end end end diff --git a/spec/unit/puppet-strings/yard/parsers/json/parser_spec.rb b/spec/unit/puppet-strings/yard/parsers/json/parser_spec.rb index d764231a1..b378aceb0 100644 --- a/spec/unit/puppet-strings/yard/parsers/json/parser_spec.rb +++ b/spec/unit/puppet-strings/yard/parsers/json/parser_spec.rb @@ -4,41 +4,43 @@ require 'puppet-strings/yard' describe PuppetStrings::Yard::Parsers::JSON::Parser do - subject { PuppetStrings::Yard::Parsers::JSON::Parser.new(source, file) } + subject(:spec_subject) { described_class.new(source, file) } + let(:file) { 'test.json' } describe 'initialization of the parser' do let(:source) { '{}' } - it 'should store the original source' do - expect(subject.source).to eq(source) + it 'stores the original source' do + expect(spec_subject.source).to eq(source) end - it 'should store the original file name' do - expect(subject.file).to eq(file) + it 'stores the original file name' do + expect(spec_subject.file).to eq(file) end - it 'should have no relevant statements' do - subject.parse + it 'has no relevant statements' do + spec_subject.parse - expect(subject.enumerator.empty?).to be_truthy + expect(spec_subject.enumerator.empty?).to be_truthy end end describe 'parsing invalid JSON' do - let(:source) { < 0).to be true + expect(!spec_subject.parameters.empty?).to be true end end context 'no params' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE { "description": "Allows you to backup your database to local file.", "input_method": "stdin" } SOURCE - } + end + it 'returns an empty hash' do - expect(subject.parameters).to eq({}) + expect(spec_subject.parameters).to eq({}) end end end - end diff --git a/spec/unit/puppet-strings/yard/parsers/puppet/parser_spec.rb b/spec/unit/puppet-strings/yard/parsers/puppet/parser_spec.rb index eefc0da4c..a3baa0492 100644 --- a/spec/unit/puppet-strings/yard/parsers/puppet/parser_spec.rb +++ b/spec/unit/puppet-strings/yard/parsers/puppet/parser_spec.rb @@ -4,39 +4,42 @@ require 'puppet-strings/yard' describe PuppetStrings::Yard::Parsers::Puppet::Parser do - subject { PuppetStrings::Yard::Parsers::Puppet::Parser.new(source, file) } + subject(:spec_subject) { described_class.new(source, file) } + let(:file) { 'test.pp' } describe 'initialization of the parser' do let(:source) { 'notice hi' } - it 'should store the original source' do - expect(subject.source).to eq(source) + it 'stores the original source' do + expect(spec_subject.source).to eq(source) end - it 'should store the original file name' do - expect(subject.file).to eq(file) + it 'stores the original file name' do + expect(spec_subject.file).to eq(file) end - it 'should have no relevant statements' do - subject.parse - expect(subject.enumerator.empty?).to be_truthy + it 'has no relevant statements' do + spec_subject.parse + expect(spec_subject.enumerator.empty?).to be_truthy end end describe 'parsing invalid Puppet source code' do - let(:source) { < present\n }\n}") expect(statement.file).to eq(file) @@ -75,22 +78,23 @@ class foo(Integer $param1, $param2, String $param3 = hi) inherits foo::bar { end describe 'parsing nested class definitions' do - let(:source) { < present\n }\n}") @@ -136,7 +141,8 @@ class bar { end describe 'parsing puppet functions', if: TEST_PUPPET_FUNCTIONS do - let(:source) { <> String { notice world } SOURCE - } + end - it 'should parse the puppet function statement' do - subject.parse - expect(subject.enumerator.size).to eq(1) - statement = subject.enumerator.first + it 'parses the puppet function statement' do + spec_subject.parse + expect(spec_subject.enumerator.size).to eq(1) + statement = spec_subject.enumerator.first expect(statement).to be_a(PuppetStrings::Yard::Parsers::Puppet::FunctionStatement) expect(statement.type).to eq('String') end end describe 'parsing puppet functions with complex return types in defintion', if: TEST_FUNCTION_RETURN_TYPE do - let(:source) { <> Struct[{'a' => Integer[1, 10]}] { notice world } SOURCE - } + end - it 'should parse the puppet function statement' do - subject.parse - expect(subject.enumerator.size).to eq(1) - statement = subject.enumerator.first + it 'parses the puppet function statement' do + spec_subject.parse + expect(spec_subject.enumerator.size).to eq(1) + statement = spec_subject.enumerator.first expect(statement).to be_a(PuppetStrings::Yard::Parsers::Puppet::FunctionStatement) expect(statement.type).to eq("Struct\[{'a' => Integer[1, 10]}\]") end @@ -211,16 +219,17 @@ class bar { describe 'parsing type alias definitions', if: TEST_PUPPET_DATATYPES do context 'given a type alias on a single line' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A simple foo type. type Module::Typename = Variant[Stdlib::Windowspath, Stdlib::Unixpath] SOURCE - } + end - it 'should parse the puppet type statement' do - subject.parse - expect(subject.enumerator.size).to eq(1) - statement = subject.enumerator.first + it 'parses the puppet type statement' do + spec_subject.parse + expect(spec_subject.enumerator.size).to eq(1) + statement = spec_subject.enumerator.first expect(statement).to be_a(PuppetStrings::Yard::Parsers::Puppet::DataTypeAliasStatement) expect(statement.docstring).to eq('A simple foo type.') expect(statement.name).to eq('Module::Typename') @@ -229,7 +238,8 @@ class bar { end context 'given a type alias over multiple lines' do - let(:source) { <<-SOURCE + let(:source) do + <<-SOURCE # A multiline foo type # with long docs type OptionsWithoutName = Struct[{ @@ -237,12 +247,12 @@ class bar { merge => Optional[MergeType] }] SOURCE - } + end - it 'should parse the puppet type statement' do - subject.parse - expect(subject.enumerator.size).to eq(1) - statement = subject.enumerator.first + it 'parses the puppet type statement' do + spec_subject.parse + expect(spec_subject.enumerator.size).to eq(1) + statement = spec_subject.enumerator.first expect(statement).to be_a(PuppetStrings::Yard::Parsers::Puppet::DataTypeAliasStatement) expect(statement.docstring).to eq("A multiline foo type\nwith long docs") expect(statement.name).to eq('OptionsWithoutName') diff --git a/spec/unit/puppet-strings/yard/util_spec.rb b/spec/unit/puppet-strings/yard/util_spec.rb index 148f9c0f6..051644e35 100644 --- a/spec/unit/puppet-strings/yard/util_spec.rb +++ b/spec/unit/puppet-strings/yard/util_spec.rb @@ -4,47 +4,47 @@ require 'puppet-strings/yard' describe PuppetStrings::Yard::Util do - subject {PuppetStrings::Yard::Util} + subject(:spec_subject) { described_class } describe 'scrub_string' do - it 'should remove `%Q` and its brackets from a string ' do - str = "%Q{this is a test string}" - expect(subject.scrub_string(str)).to eq('this is a test string') + it 'removes `%Q` and its brackets from a string' do + str = '%Q{this is a test string}' + expect(spec_subject.scrub_string(str)).to eq('this is a test string') end - it 'should remove `%q` and its brackets from a string' do - str = "%q{this is a test string}" - expect(subject.scrub_string(str)).to eq('this is a test string') + it 'removes `%q` and its brackets from a string' do + str = '%q{this is a test string}' + expect(spec_subject.scrub_string(str)).to eq('this is a test string') end - it 'should not affect newlines when %Q notation is used' do + it 'does not affect newlines when %Q notation is used' do str = <<-STR %Q{this is a test string} STR - expect(subject.scrub_string(str)).to eq("this is\na test string") + expect(spec_subject.scrub_string(str)).to eq("this is\na test string") end - it 'should not affect a string which does not use %Q notation' do - str = "this is a test string" - expect(subject.scrub_string(str)).to eq('this is a test string') + it 'does not affect a string which does not use %Q notation' do + str = 'this is a test string' + expect(spec_subject.scrub_string(str)).to eq('this is a test string') end end describe 'github_to_yard_links' do it 'converts a link correctly' do str = '' - expect(subject.github_to_yard_links(str)).to eq('') + expect(spec_subject.github_to_yard_links(str)).to eq('') end it 'leaves other links with hashes alone' do str = '' - expect(subject.github_to_yard_links(str)).to eq(str) + expect(spec_subject.github_to_yard_links(str)).to eq(str) end it 'leaves plain text alone' do str = ' module-description' - expect(subject.github_to_yard_links(str)).to eq(' module-description') + expect(spec_subject.github_to_yard_links(str)).to eq(' module-description') end end end From 5ceb042f197c85f61b51fe6463f4ead5101a28cc Mon Sep 17 00:00:00 2001 From: Craig Gumbley Date: Wed, 28 Sep 2022 09:54:51 +0100 Subject: [PATCH 07/16] (MAINT) Rubocop - (spec) fixes for puppet-strings --- spec/unit/puppet-strings/describe_spec.rb | 16 ++-- spec/unit/puppet-strings/json_spec.rb | 26 +++--- .../unit/puppet-strings/markdown/base_spec.rb | 25 +++--- spec/unit/puppet-strings/markdown_spec.rb | 90 +++++++++---------- 4 files changed, 77 insertions(+), 80 deletions(-) diff --git a/spec/unit/puppet-strings/describe_spec.rb b/spec/unit/puppet-strings/describe_spec.rb index bd3b90894..100d8fe1f 100644 --- a/spec/unit/puppet-strings/describe_spec.rb +++ b/spec/unit/puppet-strings/describe_spec.rb @@ -4,11 +4,10 @@ require 'puppet-strings/describe' require 'tempfile' -#TODO: -#basic describe -#params from other files (e.g. file content) +# TODO: basic describe +# params from other files (e.g. file content) #--providers - list providers in detail -#X--list - list all providers summary +# X--list - list all providers summary #--meta - List all metaparameters #--short - only list params @@ -16,7 +15,6 @@ before :each do # Populate the YARD registry with both Puppet and Ruby source - YARD::Parser::SourceParser.parse_string(<<-SOURCE, :ruby) Puppet::Type.newtype(:database) do desc 'An example database server resource type.' @@ -98,16 +96,16 @@ end describe 'rendering DESCRIBE to stdout' do - it 'should output the expected describe content for the list of types' do + it 'outputs the expected describe content for the list of types' do output = <<-DATA These are the types known to puppet: apt_key - This type provides Puppet with the capabiliti ... database - An example database server resource type. file - Manages files, including their content, owner ... DATA - expect{ PuppetStrings::Describe.render(nil, true) }.to output(output).to_stdout + expect { described_class.render(nil, true) }.to output(output).to_stdout end - it 'should output the expected describe content for a type' do + it 'outputs the expected describe content for a type' do output = <<-DATA file @@ -137,7 +135,7 @@ Providers --------- DATA - expect{ PuppetStrings::Describe.render(['file']) }.to output(output).to_stdout + expect { described_class.render(['file']) }.to output(output).to_stdout end end end diff --git a/spec/unit/puppet-strings/json_spec.rb b/spec/unit/puppet-strings/json_spec.rb index 6274bc857..a22feb6b1 100644 --- a/spec/unit/puppet-strings/json_spec.rb +++ b/spec/unit/puppet-strings/json_spec.rb @@ -226,49 +226,49 @@ class klass(Integer $param1, $param2, String $param3 = hi) inherits foo::bar { SOURCE end - RSpec.shared_examples "correct JSON" do - it 'should include data for Puppet Classes' do + RSpec.shared_examples 'correct JSON' do + it 'includes data for Puppet Classes' do puppet_class_json = YARD::Registry.all(:puppet_class).sort_by!(&:name).map!(&:to_hash).to_json expect(json_output).to include_json(puppet_class_json) end - it 'should include data for Puppet Data Types' do + it 'includes data for Puppet Data Types' do data_types_json = YARD::Registry.all(:puppet_data_type).sort_by!(&:name).map!(&:to_hash).to_json expect(json_output).to include_json(data_types_json) end - it 'should include data for Puppet Defined Types' do + it 'includes data for Puppet Defined Types' do defined_types_json = YARD::Registry.all(:puppet_defined_type).sort_by!(&:name).map!(&:to_hash).to_json expect(json_output).to include_json(defined_types_json) end - it 'should include data for Puppet Resource Types' do + it 'includes data for Puppet Resource Types' do resource_types_json = YARD::Registry.all(:puppet_type).sort_by!(&:name).map!(&:to_hash).to_json expect(json_output).to include_json(resource_types_json) end - it 'should include data for Puppet Providers' do + it 'includes data for Puppet Providers' do providers_json = YARD::Registry.all(:puppet_provider).sort_by!(&:name).map!(&:to_hash).to_json expect(json_output).to include_json(providers_json) end - it 'should include data for Puppet Functions', if: TEST_PUPPET_FUNCTIONS do + it 'includes data for Puppet Functions', if: TEST_PUPPET_FUNCTIONS do puppet_functions_json = YARD::Registry.all(:puppet_function).sort_by!(&:name).map!(&:to_hash).to_json expect(json_output).to include_json(puppet_functions_json) end - it 'should include data for Puppet Tasks' do + it 'includes data for Puppet Tasks' do puppet_tasks_json = YARD::Registry.all(:puppet_task).sort_by!(&:name).map!(&:to_hash).to_json expect(json_output).to include_json(puppet_tasks_json) end - it 'should include data for Puppet Plans', if: TEST_PUPPET_PLANS do + it 'includes data for Puppet Plans', if: TEST_PUPPET_PLANS do puppet_plans_json = YARD::Registry.all(:puppet_plan).sort_by!(&:name).map!(&:to_hash).to_json expect(json_output).to include_json(puppet_plans_json) @@ -280,7 +280,7 @@ class klass(Integer $param1, $param2, String $param3 = hi) inherits foo::bar { json_output = nil Tempfile.open('json') do |file| - PuppetStrings::Json.render(file.path) + described_class.render(file.path) json_output = File.read(file.path) end @@ -288,7 +288,7 @@ class klass(Integer $param1, $param2, String $param3 = hi) inherits foo::bar { json_output end - include_examples "correct JSON" + include_examples 'correct JSON' end describe 'rendering JSON to stdout' do @@ -300,13 +300,13 @@ class klass(Integer $param1, $param2, String $param3 = hi) inherits foo::bar { old_stdout = $stdout $stdout = output - PuppetStrings::Json.render(nil) + described_class.render(nil) $stdout = old_stdout @json_output = output.string end - include_examples "correct JSON" + include_examples 'correct JSON' end end diff --git a/spec/unit/puppet-strings/markdown/base_spec.rb b/spec/unit/puppet-strings/markdown/base_spec.rb index d46aa63a0..710cc26ca 100644 --- a/spec/unit/puppet-strings/markdown/base_spec.rb +++ b/spec/unit/puppet-strings/markdown/base_spec.rb @@ -18,7 +18,7 @@ class klass(Integer $param1, $param2, String $param3 = hi) inherits foo::bar { end let(:reg) { YARD::Registry.all(:puppet_class).sort_by!(&:name).map!(&:to_hash)[0] } - let(:component) { PuppetStrings::Markdown::Base.new(reg, 'class') } + let(:component) { described_class.new(reg, 'class') } describe '#name' do it 'returns the expected name' do @@ -27,16 +27,15 @@ class klass(Integer $param1, $param2, String $param3 = hi) inherits foo::bar { end ['examples', - 'see', - 'since', - 'return_val', - 'return_type',].each do |method| + 'see', + 'since', + 'return_val', + 'return_type'].each do |method| describe "##{method}" do it 'returns nil' do expect(component.method(method.to_sym).call).to be_nil end end - end describe '#private?' do @@ -59,6 +58,7 @@ class klass(Integer $param1, $param2, String $param3 = hi) inherits foo::bar { describe '#toc_info' do let(:toc) { component.toc_info } + it 'returns a hash' do expect(toc).to be_instance_of Hash end @@ -91,7 +91,7 @@ class klass::yeah( end let(:reg) { YARD::Registry.all(:puppet_class).sort_by!(&:name).map!(&:to_hash)[0] } - let(:component) { PuppetStrings::Markdown::Base.new(reg, 'class') } + let(:component) { described_class.new(reg, 'class') } describe '#name' do it 'returns the expected name' do @@ -100,10 +100,10 @@ class klass::yeah( end ['summary', - 'see', - 'since', - 'return_val', - 'return_type'].each do |method| + 'see', + 'since', + 'return_val', + 'return_type'].each do |method| describe "##{method}" do it 'returns nil' do expect(component.method(method.to_sym).call).to be_nil @@ -112,7 +112,7 @@ class klass::yeah( end describe '#examples' do - it 'should return one example' do + it 'returns one example' do expect(component.examples.size).to eq 1 end end @@ -131,6 +131,7 @@ class klass::yeah( describe '#toc_info' do let(:toc) { component.toc_info } + it 'returns a hash' do expect(toc).to be_instance_of Hash end diff --git a/spec/unit/puppet-strings/markdown_spec.rb b/spec/unit/puppet-strings/markdown_spec.rb index 96246e58b..15652d2d7 100644 --- a/spec/unit/puppet-strings/markdown_spec.rb +++ b/spec/unit/puppet-strings/markdown_spec.rb @@ -7,46 +7,44 @@ describe PuppetStrings::Markdown do let(:fixture_path) do - File.expand_path("../../fixtures", __dir__) + File.expand_path('../../fixtures', __dir__) end + let(:output) { described_class.generate } def fixture_content(fixture) - @fixtures ||= {} - @fixtures[fixture] ||= File.read(File.join(fixture_path, fixture)) + File.read(File.join(fixture_path, fixture)) end def parse_shared_content # Populate the YARD registry with both Puppet and Ruby source - YARD::Parser::SourceParser.parse_string(fixture_content("puppet/class.pp"), :puppet) - YARD::Parser::SourceParser.parse_string(fixture_content("puppet/function.pp"), :puppet) - YARD::Parser::SourceParser.parse_string(fixture_content("ruby/func4x.rb"), :ruby) - YARD::Parser::SourceParser.parse_string(fixture_content("ruby/func4x_1.rb"), :ruby) - YARD::Parser::SourceParser.parse_string(fixture_content("ruby/func3x.rb"), :ruby) - YARD::Parser::SourceParser.parse_string(fixture_content("ruby/func3x.rb"), :ruby) - YARD::Parser::SourceParser.parse_string(fixture_content("ruby/provider.rb"), :ruby) - YARD::Parser::SourceParser.parse_string(fixture_content("ruby/resource_type.rb"), :ruby) - YARD::Parser::SourceParser.parse_string(fixture_content("ruby/resource_api.rb"), :ruby) + YARD::Parser::SourceParser.parse_string(fixture_content('puppet/class.pp'), :puppet) + YARD::Parser::SourceParser.parse_string(fixture_content('puppet/function.pp'), :puppet) + YARD::Parser::SourceParser.parse_string(fixture_content('ruby/func4x.rb'), :ruby) + YARD::Parser::SourceParser.parse_string(fixture_content('ruby/func4x_1.rb'), :ruby) + YARD::Parser::SourceParser.parse_string(fixture_content('ruby/func3x.rb'), :ruby) + YARD::Parser::SourceParser.parse_string(fixture_content('ruby/func3x.rb'), :ruby) + YARD::Parser::SourceParser.parse_string(fixture_content('ruby/provider.rb'), :ruby) + YARD::Parser::SourceParser.parse_string(fixture_content('ruby/resource_type.rb'), :ruby) + YARD::Parser::SourceParser.parse_string(fixture_content('ruby/resource_api.rb'), :ruby) # task metadata derives the task name from the filename, so we have to parse # directly from the filesystem to correctly pick up the name - YARD::Parser::SourceParser.parse(File.join(fixture_path, "json/backup.json")) + YARD::Parser::SourceParser.parse(File.join(fixture_path, 'json/backup.json')) end def parse_plan_content # the parser behaves differently when parsing puppet files in the the plans directory, # so we have to parse directly from the filesystem to correctly pick up the name - YARD::Parser::SourceParser.parse(File.join(fixture_path, "plans/plan.pp")) + YARD::Parser::SourceParser.parse(File.join(fixture_path, 'plans/plan.pp')) end def parse_data_type_content - YARD::Parser::SourceParser.parse_string(fixture_content("ruby/data_type.rb"), :ruby) - YARD::Parser::SourceParser.parse_string(fixture_content("puppet/type_alias.pp"), :puppet) + YARD::Parser::SourceParser.parse_string(fixture_content('ruby/data_type.rb'), :ruby) + YARD::Parser::SourceParser.parse_string(fixture_content('puppet/type_alias.pp'), :puppet) end - let(:output) { PuppetStrings::Markdown.generate } - - RSpec.shared_examples 'markdown lint checker' do |parameter| - it 'should not generate markdown lint errors from the rendered markdown' do + RSpec.shared_examples 'markdown lint checker' do |_parameter| + it 'does not generate markdown lint errors from the rendered markdown' do expect(output).to have_no_markdown_lint_errors end end @@ -60,55 +58,55 @@ def parse_data_type_content describe 'table of contents' do it 'includes links to public classes' do - expect(output).to match(/\[`klass`\]\(#.*\).*simple class/i) + expect(output).to match(%r{\[`klass`\]\(#.*\).*simple class}i) end it 'includes links to private classes' do - expect(output).to match(/`noparams`.*overview.*noparams/i) + expect(output).to match(%r{`noparams`.*overview.*noparams}i) end it 'includes links to defined types' do - expect(output).to match(/\[`klass::dt`\]\(#.*\).*simple defined type/i) + expect(output).to match(%r{\[`klass::dt`\]\(#.*\).*simple defined type}i) end it 'includes links to resource types' do - expect(output).to match(/\[`apt_key`\]\(#.*\).*resource type.*new api/i) - expect(output).to match(/\[`database`\]\(#.*\).*example database.*type/i) + expect(output).to match(%r{\[`apt_key`\]\(#.*\).*resource type.*new api}i) + expect(output).to match(%r{\[`database`\]\(#.*\).*example database.*type}i) end it 'includes links to functions' do - expect(output).to match(/\[`func`\]\(#.*\).*simple puppet function/i) - expect(output).to match(/\[`func3x`\]\(#.*\).*example 3\.x function/i) - expect(output).to match(/\[`func4x`\]\(#.*\).*example 4\.x function/i) - expect(output).to match(/\[`func4x_1`\]\(#.*\).*example 4\.x function.*one signature/i) + expect(output).to match(%r{\[`func`\]\(#.*\).*simple puppet function}i) + expect(output).to match(%r{\[`func3x`\]\(#.*\).*example 3\.x function}i) + expect(output).to match(%r{\[`func4x`\]\(#.*\).*example 4\.x function}i) + expect(output).to match(%r{\[`func4x_1`\]\(#.*\).*example 4\.x function.*one signature}i) end it 'includes links to tasks' do - expect(output).to match(/\[`backup`\]\(#.*\).*backup your database/i) + expect(output).to match(%r{\[`backup`\]\(#.*\).*backup your database}i) end end describe 'resource types' do it 'includes checks in parameter list for the database type' do - expect(output).to match(/check to see if the database already exists/i) + expect(output).to match(%r{check to see if the database already exists}i) end end - describe 'with Puppet Plans', :if => TEST_PUPPET_PLANS do + describe 'with Puppet Plans', if: TEST_PUPPET_PLANS do before(:each) do parse_plan_content end include_examples 'markdown lint checker' - describe "table of contents" do + describe 'table of contents' do it 'includes links to plans' do - expect(output).to match(/\[`plann`\]\(#.*\).*simple plan/i) + expect(output).to match(%r{\[`plann`\]\(#.*\).*simple plan}i) end end end - describe 'with Puppet Data Types', :if => TEST_PUPPET_DATATYPES do + describe 'with Puppet Data Types', if: TEST_PUPPET_DATATYPES do before(:each) do parse_data_type_content end @@ -117,45 +115,45 @@ def parse_data_type_content describe 'table of contents' do it 'includes links to data types' do - expect(output).to match(/\[`Amodule::ComplexAlias`\]\(#.*\).*Amodule::ComplexAlias/i) - expect(output).to match(/\[`Amodule::SimpleAlias`\]\(#.*\).*Amodule::SimpleAlias/i) - expect(output).to match(/\[`UnitDataType`\]\(#.*\).*data type in ruby/i) + expect(output).to match(%r{\[`Amodule::ComplexAlias`\]\(#.*\).*Amodule::ComplexAlias}i) + expect(output).to match(%r{\[`Amodule::SimpleAlias`\]\(#.*\).*Amodule::SimpleAlias}i) + expect(output).to match(%r{\[`UnitDataType`\]\(#.*\).*data type in ruby}i) end end describe 'parameter docs' do it 'includes param name' do - expect(output).to match(/#+ `param1`/) + expect(output).to match(%r{#+ `param1`}) end it 'includes param type' do - expect(output).to match(/Data type: `Variant\[Numeric, String\[1,2\]\]`/) + expect(output).to match(%r{Data type: `Variant\[Numeric, String\[1,2\]\]`}) end it 'includes param description' do - expect(output).to match(/a variant parameter/i) + expect(output).to match(%r{a variant parameter}i) end it 'includes param default' do - expect(output).to match(/default value: `param2`/i) + expect(output).to match(%r{default value: `param2`}i) end end describe 'function docs' do it 'includes signature' do - expect(output).to match(/UnitDataType\.func1\(param1, param2\)/) + expect(output).to match(%r{UnitDataType\.func1\(param1, param2\)}) end it 'includes summary' do - expect(output).to match(/func1 documentation/i) + expect(output).to match(%r{func1 documentation}i) end it 'includes parameter docs' do - expect(output).to match(/param1 documentation/i) + expect(output).to match(%r{param1 documentation}i) end it 'includes return value' do - expect(output).to match(/returns: `optional\[string\]`/i) + expect(output).to match(%r{returns: `optional\[string\]`}i) end end end From d5a3fb3f4a530ff8517f811ae1675d2f12305c06 Mon Sep 17 00:00:00 2001 From: Craig Gumbley Date: Wed, 28 Sep 2022 09:55:16 +0100 Subject: [PATCH 08/16] (MAINT) Rubocop - (spec) fixes for spec helpers --- spec/markdownlint_style.rb | 2 +- spec/spec_helper.rb | 12 ++++++------ spec/spec_helper_acceptance_local.rb | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/spec/markdownlint_style.rb b/spec/markdownlint_style.rb index 54cf1cce8..f18022334 100644 --- a/spec/markdownlint_style.rb +++ b/spec/markdownlint_style.rb @@ -12,4 +12,4 @@ exclude_rule 'MD026' # Allow html tags -exclude_rule 'MD033' \ No newline at end of file +exclude_rule 'MD033' diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 708e68a3c..9fce165c4 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -32,16 +32,16 @@ PuppetStrings::Yard.setup! # Enable testing of Puppet functions if running against 4.1+ -TEST_PUPPET_FUNCTIONS = Puppet::Util::Package.versioncmp(Puppet.version, "4.1.0") >= 0 +TEST_PUPPET_FUNCTIONS = Puppet::Util::Package.versioncmp(Puppet.version, '4.1.0') >= 0 # Enable testing of Puppet language functions declared with return type if running against 4.8+ -TEST_FUNCTION_RETURN_TYPE = Puppet::Util::Package.versioncmp(Puppet.version, "4.8.0") >= 0 +TEST_FUNCTION_RETURN_TYPE = Puppet::Util::Package.versioncmp(Puppet.version, '4.8.0') >= 0 # Enable testing of Plans if Puppet version is greater than 5.0.0 -TEST_PUPPET_PLANS = Puppet::Util::Package.versioncmp(Puppet.version, "5.0.0") >= 0 +TEST_PUPPET_PLANS = Puppet::Util::Package.versioncmp(Puppet.version, '5.0.0') >= 0 # Enable testing of Data Types if Puppet version is greater than 4.1.0 -TEST_PUPPET_DATATYPES = Puppet::Util::Package.versioncmp(Puppet.version, "4.1.0") >= 0 +TEST_PUPPET_DATATYPES = Puppet::Util::Package.versioncmp(Puppet.version, '4.1.0') >= 0 RSpec.configure do |config| config.mock_with :mocha @@ -66,7 +66,7 @@ def lint_markdown(content) violations = [] ruleset.rules.each do |id, rule| error_lines = rule.check.call(doc) - next if error_lines.nil? or error_lines.empty? + next if error_lines.nil? || error_lines.empty? # record the error error_lines.each do |line| @@ -84,6 +84,6 @@ def lint_markdown(content) end failure_message do |actual| - "expected that #{actual.length > 80 ? actual.slice(0,80).inspect + '...' : actual.inspect} would have no markdown lint errors but got #{@violations.join("\n")}" + "expected that #{actual.length > 80 ? actual.slice(0, 80).inspect + '...' : actual.inspect} would have no markdown lint errors but got #{@violations.join("\n")}" end end diff --git a/spec/spec_helper_acceptance_local.rb b/spec/spec_helper_acceptance_local.rb index 1f1702269..7234e6974 100644 --- a/spec/spec_helper_acceptance_local.rb +++ b/spec/spec_helper_acceptance_local.rb @@ -3,7 +3,7 @@ def sut_module_path(module_regex) modules = JSON.parse(run_shell('puppet module list --render-as json').stdout) test_module_info = modules['modules_by_path'].values.flatten.find { |mod_info| mod_info =~ module_regex } - test_module_info.match(/\(([^)]*)\)/)[1] + test_module_info.match(%r{\(([^)]*)\)})[1] end def sut_tmp_path From d2e993713b79c2c5d410fa74f1e87b9c95341dfb Mon Sep 17 00:00:00 2001 From: Craig Gumbley Date: Wed, 28 Sep 2022 09:40:27 +0100 Subject: [PATCH 09/16] (MAINT) Rubocop - (spec) improve output capture --- spec/unit/puppet-strings/json_spec.rb | 76 ++++++++++++++++----------- 1 file changed, 45 insertions(+), 31 deletions(-) diff --git a/spec/unit/puppet-strings/json_spec.rb b/spec/unit/puppet-strings/json_spec.rb index a22feb6b1..614bdaec6 100644 --- a/spec/unit/puppet-strings/json_spec.rb +++ b/spec/unit/puppet-strings/json_spec.rb @@ -228,50 +228,59 @@ class klass(Integer $param1, $param2, String $param3 = hi) inherits foo::bar { RSpec.shared_examples 'correct JSON' do it 'includes data for Puppet Classes' do - puppet_class_json = YARD::Registry.all(:puppet_class).sort_by!(&:name).map!(&:to_hash).to_json + expected = YARD::Registry.all(:puppet_class).sort_by!(&:name).map!(&:to_hash).to_json - expect(json_output).to include_json(puppet_class_json) + actual = capture_output { described_class.render(nil) } + expect(actual[:stdout]).to include_json(expected) end it 'includes data for Puppet Data Types' do - data_types_json = YARD::Registry.all(:puppet_data_type).sort_by!(&:name).map!(&:to_hash).to_json - expect(json_output).to include_json(data_types_json) + expected = YARD::Registry.all(:puppet_data_type).sort_by!(&:name).map!(&:to_hash).to_json + + actual = capture_output { described_class.render(nil) } + expect(actual[:stdout]).to include_json(expected) end it 'includes data for Puppet Defined Types' do - defined_types_json = YARD::Registry.all(:puppet_defined_type).sort_by!(&:name).map!(&:to_hash).to_json + expected = YARD::Registry.all(:puppet_defined_type).sort_by!(&:name).map!(&:to_hash).to_json - expect(json_output).to include_json(defined_types_json) + actual = capture_output { described_class.render(nil) } + expect(actual[:stdout]).to include_json(expected) end it 'includes data for Puppet Resource Types' do - resource_types_json = YARD::Registry.all(:puppet_type).sort_by!(&:name).map!(&:to_hash).to_json + expected = YARD::Registry.all(:puppet_type).sort_by!(&:name).map!(&:to_hash).to_json - expect(json_output).to include_json(resource_types_json) + actual = capture_output { described_class.render(nil) } + expect(actual[:stdout]).to include_json(expected) end it 'includes data for Puppet Providers' do - providers_json = YARD::Registry.all(:puppet_provider).sort_by!(&:name).map!(&:to_hash).to_json + expected = YARD::Registry.all(:puppet_provider).sort_by!(&:name).map!(&:to_hash).to_json - expect(json_output).to include_json(providers_json) + actual = capture_output { described_class.render(nil) } + expect(actual[:stdout]).to include_json(expected) end it 'includes data for Puppet Functions', if: TEST_PUPPET_FUNCTIONS do - puppet_functions_json = YARD::Registry.all(:puppet_function).sort_by!(&:name).map!(&:to_hash).to_json + expected = YARD::Registry.all(:puppet_function).sort_by!(&:name).map!(&:to_hash).to_json - expect(json_output).to include_json(puppet_functions_json) + actual = capture_output { described_class.render(nil) } + expect(actual[:stdout]).to include_json(expected) end it 'includes data for Puppet Tasks' do - puppet_tasks_json = YARD::Registry.all(:puppet_task).sort_by!(&:name).map!(&:to_hash).to_json + expected = YARD::Registry.all(:puppet_task).sort_by!(&:name).map!(&:to_hash).to_json - expect(json_output).to include_json(puppet_tasks_json) + actual = capture_output { described_class.render(nil) } + expect(actual[:stdout]).to include_json(expected) end it 'includes data for Puppet Plans', if: TEST_PUPPET_PLANS do - puppet_plans_json = YARD::Registry.all(:puppet_plan).sort_by!(&:name).map!(&:to_hash).to_json + expected = YARD::Registry.all(:puppet_plan).sort_by!(&:name).map!(&:to_hash).to_json - expect(json_output).to include_json(puppet_plans_json) + actual = capture_output { described_class.render(nil) } + expect(actual[:stdout]).to include_json(expected) end end @@ -292,21 +301,26 @@ class klass(Integer $param1, $param2, String $param3 = hi) inherits foo::bar { end describe 'rendering JSON to stdout' do - let(:json_output) { @json_output } - - before(:each) do - output = StringIO.new - - old_stdout = $stdout - $stdout = output - - described_class.render(nil) - - $stdout = old_stdout - - @json_output = output.string - end - include_examples 'correct JSON' end end + +# Helper method to capture stdout and stderr from a block +# Source: https://gist.github.com/herrphon/2d2ebbf23c86a10aa955 +# +# @param [Proc] block The block to capture output from +# @return [Hash] A hash containing the captured output +def capture_output(&_block) + begin + $stdout = StringIO.new + $stderr = StringIO.new + yield + result = {} + result[:stdout] = $stdout.string + result[:stderr] = $stderr.string + ensure + $stdout = STDOUT + $stderr = STDERR + end + result +end From 5b932b64082c3125f84ac8cfd86731d1ca235f03 Mon Sep 17 00:00:00 2001 From: Craig Gumbley Date: Wed, 28 Sep 2022 09:20:37 +0100 Subject: [PATCH 10/16] (MAINT) Rubocop - (lib) fixes for features --- lib/puppet/feature/rgen.rb | 2 +- lib/puppet/feature/yard.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/puppet/feature/rgen.rb b/lib/puppet/feature/rgen.rb index d932a9f28..159e8a007 100644 --- a/lib/puppet/feature/rgen.rb +++ b/lib/puppet/feature/rgen.rb @@ -2,4 +2,4 @@ require 'puppet/util/feature' -Puppet.features.add(:rgen, :libs => ['rgen/metamodel_builder', 'rgen/ecore/ecore']) +Puppet.features.add(:rgen, libs: ['rgen/metamodel_builder', 'rgen/ecore/ecore']) diff --git a/lib/puppet/feature/yard.rb b/lib/puppet/feature/yard.rb index 5b709f380..e6366a9c7 100644 --- a/lib/puppet/feature/yard.rb +++ b/lib/puppet/feature/yard.rb @@ -2,4 +2,4 @@ require 'puppet/util/feature' -Puppet.features.add(:yard, :libs => ['yard']) +Puppet.features.add(:yard, libs: ['yard']) From 5bec15bc5b65bbe1e39bd5227924139c288906cf Mon Sep 17 00:00:00 2001 From: Craig Gumbley Date: Wed, 28 Sep 2022 09:20:52 +0100 Subject: [PATCH 11/16] (MAINT) Rubocop - (lib) fixes for face --- lib/puppet/face/strings.rb | 62 ++++++++++++++++++-------------------- 1 file changed, 29 insertions(+), 33 deletions(-) diff --git a/lib/puppet/face/strings.rb b/lib/puppet/face/strings.rb index 001a46899..23b757fab 100644 --- a/lib/puppet/face/strings.rb +++ b/lib/puppet/face/strings.rb @@ -32,9 +32,9 @@ check_required_features require 'puppet-strings' - PuppetStrings::generate( + PuppetStrings.generate( args.count > 1 ? args[0..-2] : PuppetStrings::DEFAULT_SEARCH_PATTERNS, - build_generate_options(args.last) + build_generate_options(args.last), ) nil end @@ -79,35 +79,34 @@ return end puts 'Starting YARD documentation server.' - PuppetStrings::run_server('-m', *module_docs) + PuppetStrings.run_server('-m', *module_docs) nil end end - action(:describe) do #This is Kris' experiment with string based describe - option "--list" do - summary "list types" + action(:describe) do # This is Kris' experiment with string based describe + option '--list' do + summary 'list types' end - option "--providers" do - summary "provide details on providers" + option '--providers' do + summary 'provide details on providers' end -#TODO: Implement the rest of describe behavior -# * --help: -# Print this help text + # TODO: Implement the rest of describe behavior + # * --help: + # Print this help text -# * --providers: -# Describe providers in detail for each type + # * --providers: + # Describe providers in detail for each type -# * --list: -# List all types + # * --list: + # List all types -# * --meta: -# List all metaparameters - -# * --short: -# List only parameters without detail + # * --meta: + # List all metaparameters + # * --short: + # List only parameters without detail when_invoked do |*args| check_required_features @@ -117,27 +116,24 @@ options[:describe] = true options[:stdout] = true options[:format] = 'json' - + if args.length > 1 if options[:list] - warn "WARNING: ignoring types when listing all types." + warn 'WARNING: ignoring types when listing all types.' else options[:describe_types] = args[0..-2] end end - #TODO: Set up search_patterns and whatever else needed to collect data for describe - currently missing some + # TODO: Set up search_patterns and whatever else needed to collect data for describe - currently missing some # manifests/**/*.pp # functions/**/*.pp # tasks/*.json # plans/*.pp - search_patterns = %w( - types/**/*.pp - lib/**/*.rb - ) - PuppetStrings::generate( + search_patterns = ['types/**/*.pp', 'lib/**/*.rb'] + PuppetStrings.generate( search_patterns, - build_generate_options(options) + build_generate_options(options), ) nil end @@ -146,9 +142,9 @@ # Checks that the required features are installed. # @return [void] def check_required_features - raise RuntimeError, "The 'yard' gem must be installed in order to use this face." unless Puppet.features.yard? - raise RuntimeError, "The 'rgen' gem must be installed in order to use this face." unless Puppet.features.rgen? - raise RuntimeError, 'This face requires Ruby 1.9 or greater.' if RUBY_VERSION.match?(/^1\.8/) + raise "The 'yard' gem must be installed in order to use this face." unless Puppet.features.yard? + raise "The 'rgen' gem must be installed in order to use this face." unless Puppet.features.rgen? + raise 'This face requires Ruby 1.9 or greater.' if RUBY_VERSION.match?(%r{^1\.8}) end # Builds the options to PuppetStrings.generate. @@ -186,7 +182,7 @@ def build_generate_options(options = nil, *yard_args) generate_options[:json] = true generate_options[:path] ||= options[:emit_json] if options[:emit_json] else - raise RuntimeError, "Invalid format #{options[:format]}. Please select 'json' or 'markdown'." + raise "Invalid format #{options[:format]}. Please select 'json' or 'markdown'." end elsif options[:emit_json] || options[:emit_json_stdout] generate_options[:json] = true From 5af8db8cd51f61695a39d3192fb88e680e795bbd Mon Sep 17 00:00:00 2001 From: Craig Gumbley Date: Wed, 28 Sep 2022 09:21:17 +0100 Subject: [PATCH 12/16] (MAINT) Rubocop - (lib) fixes for yard --- lib/puppet-strings/yard/code_objects/class.rb | 4 +- .../yard/code_objects/data_type.rb | 8 +- .../yard/code_objects/data_type_alias.rb | 2 +- .../yard/code_objects/defined_type.rb | 4 +- .../yard/code_objects/function.rb | 22 ++-- lib/puppet-strings/yard/code_objects/group.rb | 2 +- lib/puppet-strings/yard/code_objects/plan.rb | 6 +- .../yard/code_objects/provider.rb | 4 +- lib/puppet-strings/yard/code_objects/task.rb | 13 +- lib/puppet-strings/yard/code_objects/type.rb | 12 +- lib/puppet-strings/yard/handlers/helpers.rb | 7 +- lib/puppet-strings/yard/handlers/json/base.rb | 3 +- .../yard/handlers/json/task_handler.rb | 8 +- .../yard/handlers/puppet/base.rb | 9 +- .../yard/handlers/puppet/function_handler.rb | 5 +- lib/puppet-strings/yard/handlers/ruby/base.rb | 5 +- .../yard/handlers/ruby/data_type_handler.rb | 31 +++-- .../yard/handlers/ruby/function_handler.rb | 120 ++++++++++-------- .../yard/handlers/ruby/provider_handler.rb | 3 +- .../yard/handlers/ruby/rsapi_handler.rb | 21 +-- .../yard/handlers/ruby/type_base.rb | 54 ++++---- .../yard/handlers/ruby/type_extras_handler.rb | 5 +- .../yard/handlers/ruby/type_handler.rb | 3 +- lib/puppet-strings/yard/parsers.rb | 1 + .../yard/parsers/json/parser.rb | 5 +- .../yard/parsers/json/task_statement.rb | 6 +- .../yard/parsers/puppet/parser.rb | 8 +- .../yard/parsers/puppet/statement.rb | 26 ++-- lib/puppet-strings/yard/tags/enum_tag.rb | 3 +- lib/puppet-strings/yard/tags/factory.rb | 2 +- lib/puppet-strings/yard/tags/overload_tag.rb | 14 +- .../yard/tags/parameter_directive.rb | 4 +- .../yard/tags/property_directive.rb | 4 +- lib/puppet-strings/yard/tags/summary_tag.rb | 3 +- lib/puppet-strings/yard/util.rb | 8 +- 35 files changed, 235 insertions(+), 200 deletions(-) diff --git a/lib/puppet-strings/yard/code_objects/class.rb b/lib/puppet-strings/yard/code_objects/class.rb index 2a3c9b1c7..5346d6bd5 100644 --- a/lib/puppet-strings/yard/code_objects/class.rb +++ b/lib/puppet-strings/yard/code_objects/class.rb @@ -13,7 +13,7 @@ def self.instance # Gets the display name of the group. # @param [Boolean] prefix whether to show a prefix. Ignored for Puppet group namespaces. # @return [String] Returns the display name of the group. - def name(prefix = false) + def name(_prefix = false) 'Puppet Classes' end end @@ -53,7 +53,7 @@ def to_hash hash[:line] = line hash[:inherits] = statement.parent_class if statement.parent_class hash[:docstring] = PuppetStrings::Yard::Util.docstring_to_hash(docstring) - defaults = Hash[*parameters.reject{ |p| p[1].nil? }.flatten] + defaults = Hash[*parameters.reject { |p| p[1].nil? }.flatten] hash[:defaults] = defaults unless defaults.nil? || defaults.empty? hash[:source] = source unless source.nil? || source.empty? hash diff --git a/lib/puppet-strings/yard/code_objects/data_type.rb b/lib/puppet-strings/yard/code_objects/data_type.rb index 264c004b3..39f343f3a 100644 --- a/lib/puppet-strings/yard/code_objects/data_type.rb +++ b/lib/puppet-strings/yard/code_objects/data_type.rb @@ -14,7 +14,7 @@ def self.instance # Gets the display name of the group. # @param [Boolean] prefix whether to show a prefix. Ignored for Puppet group namespaces. # @return [String] Returns the display name of the group. - def name(prefix = false) + def name(_prefix = false) 'Puppet Data Types' end end @@ -73,7 +73,7 @@ def add_function(name, return_type, parameter_types) meth_obj.add_tag(YARD::Tags::Tag.new(:param, '', [param_type], "param#{index + 1}")) end - self.meths << meth_obj + meths << meth_obj end def functions @@ -87,14 +87,14 @@ def to_hash hash[:name] = name hash[:file] = file hash[:line] = line - hash[:docstring] = PuppetStrings::Yard::Util.docstring_to_hash(docstring, %i[param option enum return example]) + hash[:docstring] = PuppetStrings::Yard::Util.docstring_to_hash(docstring, [:param, :option, :enum, :return, :example]) hash[:defaults] = defaults unless defaults.nil? || defaults.empty? hash[:source] = source unless source.nil? || source.empty? hash[:functions] = functions.map do |func| { name: func.name, signature: func.signature, - docstring: PuppetStrings::Yard::Util.docstring_to_hash(func.docstring, %i[param option enum return example]) + docstring: PuppetStrings::Yard::Util.docstring_to_hash(func.docstring, [:param, :option, :enum, :return, :example]) } end hash diff --git a/lib/puppet-strings/yard/code_objects/data_type_alias.rb b/lib/puppet-strings/yard/code_objects/data_type_alias.rb index 24b2d9145..5ea304bdb 100644 --- a/lib/puppet-strings/yard/code_objects/data_type_alias.rb +++ b/lib/puppet-strings/yard/code_objects/data_type_alias.rb @@ -14,7 +14,7 @@ def self.instance # Gets the display name of the group. # @param [Boolean] prefix whether to show a prefix. Ignored for Puppet group namespaces. # @return [String] Returns the display name of the group. - def name(prefix = false) + def name(_prefix = false) 'Puppet Data Type Aliases' end end diff --git a/lib/puppet-strings/yard/code_objects/defined_type.rb b/lib/puppet-strings/yard/code_objects/defined_type.rb index a77e8100c..2e5cb1c01 100644 --- a/lib/puppet-strings/yard/code_objects/defined_type.rb +++ b/lib/puppet-strings/yard/code_objects/defined_type.rb @@ -13,7 +13,7 @@ def self.instance # Gets the display name of the group. # @param [Boolean] prefix whether to show a prefix. Ignored for Puppet group namespaces. # @return [String] Returns the display name of the group. - def name(prefix = false) + def name(_prefix = false) 'Defined Types' end end @@ -52,7 +52,7 @@ def to_hash hash[:file] = file hash[:line] = line hash[:docstring] = PuppetStrings::Yard::Util.docstring_to_hash(docstring) - defaults = Hash[*parameters.reject{ |p| p[1].nil? }.flatten] + defaults = Hash[*parameters.reject { |p| p[1].nil? }.flatten] hash[:defaults] = defaults unless defaults.nil? || defaults.empty? hash[:source] = source unless source.nil? || source.empty? hash diff --git a/lib/puppet-strings/yard/code_objects/function.rb b/lib/puppet-strings/yard/code_objects/function.rb index d31574bae..59a79380d 100644 --- a/lib/puppet-strings/yard/code_objects/function.rb +++ b/lib/puppet-strings/yard/code_objects/function.rb @@ -8,13 +8,13 @@ class PuppetStrings::Yard::CodeObjects::Functions < PuppetStrings::Yard::CodeObj # @param [Symbol] type The function type to get the group for. # @return Returns the singleton instance of the group. def self.instance(type) - super("puppet_functions_#{type}".intern) + super("puppet_functions_#{type}".to_sym) end # Gets the display name of the group. # @param [Boolean] prefix whether to show a prefix. Ignored for Puppet group namespaces. # @return [String] Returns the display name of the group. - def name(prefix = false) + def name(_prefix = false) 'Puppet Functions' end end @@ -62,18 +62,18 @@ def function_type # Gets the Puppet signature of the function (single overload only). # @return [String] Returns the Puppet signature of the function. def signature - return '' if self.has_tag? :overload + return '' if has_tag? :overload tags = self.tags(:param) - args = @parameters.map do |parameter| + args = @parameters.map { |parameter| name, default = parameter tag = tags.find { |t| t.name == name } if tags type = tag&.types ? "#{tag.type} " : 'Any ' - prefix = "#{name[0]}" if name.start_with?('*', '&') + prefix = (name[0]).to_s if name.start_with?('*', '&') name = name[1..-1] if prefix default = " = #{default}" if default "#{type}#{prefix}$#{name}#{default}" - end.join(', ') + }.join(', ') @name.to_s + '(' + args + ')' end @@ -88,17 +88,17 @@ def to_hash hash[:type] = @function_type.to_s hash[:signatures] = [] - if self.has_tag? :overload + if has_tag? :overload # loop over overloads and append onto the signatures array - self.tags(:overload).each do |o| - hash[:signatures] << { :signature => o.signature, :docstring => PuppetStrings::Yard::Util.docstring_to_hash(o.docstring, %i[param option enum return example]) } + tags(:overload).each do |o| + hash[:signatures] << { signature: o.signature, docstring: PuppetStrings::Yard::Util.docstring_to_hash(o.docstring, [:param, :option, :enum, :return, :example]) } end else - hash[:signatures] << { :signature => self.signature, :docstring => PuppetStrings::Yard::Util.docstring_to_hash(docstring, %i[param option enum return example]) } + hash[:signatures] << { signature: signature, docstring: PuppetStrings::Yard::Util.docstring_to_hash(docstring, [:param, :option, :enum, :return, :example]) } end hash[:docstring] = PuppetStrings::Yard::Util.docstring_to_hash(docstring) - defaults = Hash[*parameters.reject{ |p| p[1].nil? }.flatten] + defaults = Hash[*parameters.reject { |p| p[1].nil? }.flatten] hash[:defaults] = defaults unless defaults.nil? || defaults.empty? hash[:source] = source unless source.nil? || source.empty? hash diff --git a/lib/puppet-strings/yard/code_objects/group.rb b/lib/puppet-strings/yard/code_objects/group.rb index c4f69924e..35a741818 100644 --- a/lib/puppet-strings/yard/code_objects/group.rb +++ b/lib/puppet-strings/yard/code_objects/group.rb @@ -13,7 +13,7 @@ def self.instance(key) instance = P(:root, key) return instance unless instance.is_a?(YARD::CodeObjects::Proxy) - instance = self.new(:root, key) + instance = new(:root, key) instance.visibility = :hidden P(:root).children << instance instance diff --git a/lib/puppet-strings/yard/code_objects/plan.rb b/lib/puppet-strings/yard/code_objects/plan.rb index 0eb483c3b..6bec1fb3c 100644 --- a/lib/puppet-strings/yard/code_objects/plan.rb +++ b/lib/puppet-strings/yard/code_objects/plan.rb @@ -2,6 +2,7 @@ require 'puppet-strings/yard/code_objects/group' +# Implements the group for Puppet plans. class PuppetStrings::Yard::CodeObjects::Plans < PuppetStrings::Yard::CodeObjects::Group # Gets the singleton instance of the group. # @return Returns the singleton instance of the group. @@ -12,11 +13,12 @@ def self.instance # Gets the display name of the group. # @param [Boolean] prefix whether to show a prefix. Ignored for Puppet group namespaces. # @return [String] Returns the display name of the group. - def name(prefix = false) + def name(_prefix = false) 'Puppet Plans' end end +# Implements the Puppet plan code object. class PuppetStrings::Yard::CodeObjects::Plan < PuppetStrings::Yard::CodeObjects::Base attr_reader :statement attr_reader :parameters @@ -50,7 +52,7 @@ def to_hash hash[:file] = file hash[:line] = line hash[:docstring] = PuppetStrings::Yard::Util.docstring_to_hash(docstring) - defaults = Hash[*parameters.reject{ |p| p[1].nil? }.flatten] + defaults = Hash[*parameters.reject { |p| p[1].nil? }.flatten] hash[:defaults] = defaults unless defaults.nil? || defaults.empty? hash[:source] = source unless source.nil? || source.empty? hash diff --git a/lib/puppet-strings/yard/code_objects/provider.rb b/lib/puppet-strings/yard/code_objects/provider.rb index d312ef122..47e6ad5b6 100644 --- a/lib/puppet-strings/yard/code_objects/provider.rb +++ b/lib/puppet-strings/yard/code_objects/provider.rb @@ -8,13 +8,13 @@ class PuppetStrings::Yard::CodeObjects::Providers < PuppetStrings::Yard::CodeObj # @param [String] type The resource type name for the provider. # @return Returns the singleton instance of the group. def self.instance(type) - super("puppet_providers_#{type}".intern) + super("puppet_providers_#{type}".to_sym) end # Gets the display name of the group. # @param [Boolean] prefix whether to show a prefix. Ignored for Puppet group namespaces. # @return [String] Returns the display name of the group. - def name(prefix = false) + def name(_prefix = false) 'Providers' end end diff --git a/lib/puppet-strings/yard/code_objects/task.rb b/lib/puppet-strings/yard/code_objects/task.rb index 7d0f50069..a94ff8d6b 100644 --- a/lib/puppet-strings/yard/code_objects/task.rb +++ b/lib/puppet-strings/yard/code_objects/task.rb @@ -11,9 +11,9 @@ def self.instance end # Gets the display name of the group. - # @param [Boolean] prefix whether to show a prefix. + # @param [Boolean] prefix whether to show a prefix. Ignored for Puppet group namespaces. # @return [String] Returns the display name of the group. - def name(prefix = false) + def name(_prefix = false) 'Puppet Tasks' end end @@ -45,11 +45,11 @@ def source def parameters parameters = [] - statement.parameters.each do |name,props| + statement.parameters.each do |name, props| parameters.push({ name: name.to_s, tag_name: 'param', - text: props['description'] || "", - types: [props['type']] || "" }) + text: props['description'] || '', + types: [props['type']] || '' }) end parameters end @@ -66,7 +66,6 @@ def to_hash }, source: statement.source, supports_noop: statement.json['supports_noop'] || false, - input_method: statement.json['input_method'] - } + input_method: statement.json['input_method'] } end end diff --git a/lib/puppet-strings/yard/code_objects/type.rb b/lib/puppet-strings/yard/code_objects/type.rb index 1535523d3..1240fba87 100644 --- a/lib/puppet-strings/yard/code_objects/type.rb +++ b/lib/puppet-strings/yard/code_objects/type.rb @@ -14,7 +14,7 @@ def self.instance # Gets the display name of the group. # @param [Boolean] prefix whether to show a prefix. Ignored for Puppet group namespaces. # @return [String] Returns the display name of the group. - def name(prefix = false) + def name(_prefix = false) 'Resource Types' end end @@ -87,7 +87,7 @@ class Feature # @param [String] docstring The docstring of the feature. def initialize(name, docstring) @name = name - @docstring = PuppetStrings::Yard::Util.scrub_string(docstring).gsub("\n", ' ') + @docstring = PuppetStrings::Yard::Util.scrub_string(docstring).tr("\n", ' ') end # Converts the feature to a hash representation. @@ -148,7 +148,7 @@ def add_check(check) end def parameters - @parameters ||= [] # guard against not filled parameters + @parameters ||= [] # guard against not filled parameters # just return params if there are no providers return @parameters if providers.empty? @@ -157,8 +157,8 @@ def parameters provider_param = Parameter.new( 'provider', - "The specific backend to use for this `#{self.name.to_s}` resource. You will seldom need " + \ - "to specify this --- Puppet will usually discover the appropriate provider for your platform." + "The specific backend to use for this `#{name}` resource. You will seldom need " \ + 'to specify this --- Puppet will usually discover the appropriate provider for your platform.', ) @parameters ||= [] @@ -169,7 +169,7 @@ def parameters # render-time. For now, this should re-resolve on every call. # may be able to memoize this def providers - providers = YARD::Registry.all("puppet_providers_#{name}".intern) + providers = YARD::Registry.all("puppet_providers_#{name}".to_sym) return providers if providers.empty? providers.first.children diff --git a/lib/puppet-strings/yard/handlers/helpers.rb b/lib/puppet-strings/yard/handlers/helpers.rb index 2968571d4..358282602 100644 --- a/lib/puppet-strings/yard/handlers/helpers.rb +++ b/lib/puppet-strings/yard/handlers/helpers.rb @@ -1,10 +1,9 @@ # frozen_string_literal: true +# Implements a helper that logs a warning if a summary tag has more than 140 characters module PuppetStrings::Yard::Handlers::Helpers - # Logs a warning if a summary tag has more than 140 characters def self.validate_summary_tag(object) - if object.has_tag?(:summary) && object.tag(:summary).text.length > 140 - log.warn "The length of the summary for #{object.type} '#{object.name}' exceeds the recommended limit of 140 characters." - end + return unless object.has_tag?(:summary) && object.tag(:summary).text.length > 140 + log.warn "The length of the summary for #{object.type} '#{object.name}' exceeds the recommended limit of 140 characters." end end diff --git a/lib/puppet-strings/yard/handlers/json/base.rb b/lib/puppet-strings/yard/handlers/json/base.rb index 13eece9ae..c13941109 100644 --- a/lib/puppet-strings/yard/handlers/json/base.rb +++ b/lib/puppet-strings/yard/handlers/json/base.rb @@ -1,7 +1,8 @@ # frozen_string_literal: true +# Implements the base class for all JSON handlers. class PuppetStrings::Yard::Handlers::JSON::Base < YARD::Handlers::Base def self.handles?(statement) - handlers.any? {|handler| statement.is_a?(handler)} + handlers.any? { |handler| statement.is_a?(handler) } end end diff --git a/lib/puppet-strings/yard/handlers/json/task_handler.rb b/lib/puppet-strings/yard/handlers/json/task_handler.rb index ee9fad4ef..6ce505f79 100644 --- a/lib/puppet-strings/yard/handlers/json/task_handler.rb +++ b/lib/puppet-strings/yard/handlers/json/task_handler.rb @@ -4,6 +4,7 @@ require 'puppet-strings/yard/parsers' require 'puppet-strings/yard/parsers/json/parser' +# Implements the handler for JSON task metadata. class PuppetStrings::Yard::Handlers::JSON::TaskHandler < PuppetStrings::Yard::Handlers::JSON::Base handles PuppetStrings::Yard::Parsers::JSON::TaskStatement namespace_only @@ -24,10 +25,9 @@ def validate_description end def validate_params - unless @statement.parameters.empty? - @statement.parameters.each do |param, val| - log.warn "Missing description for param '#{param}' in #{@kind}" if val['description'].nil? - end + return if @statement.parameters.empty? + @statement.parameters.each do |param, val| + log.warn "Missing description for param '#{param}' in #{@kind}" if val['description'].nil? end end end diff --git a/lib/puppet-strings/yard/handlers/puppet/base.rb b/lib/puppet-strings/yard/handlers/puppet/base.rb index 5ad2062a4..bbc713149 100644 --- a/lib/puppet-strings/yard/handlers/puppet/base.rb +++ b/lib/puppet-strings/yard/handlers/puppet/base.rb @@ -6,10 +6,11 @@ class PuppetStrings::Yard::Handlers::Puppet::Base < YARD::Handlers::Base # @param statement The statement that was parsed. # @return [Boolean] Returns true if the statement is handled by this handler or false if not. def self.handles?(statement) - handlers.any? {|handler| statement.is_a?(handler)} + handlers.any? { |handler| statement.is_a?(handler) } end protected + # Sets the parameter tag types for the given code object. # This also performs some validation on the parameter tags. # @param object The code object to set the parameter tag types for. @@ -35,7 +36,11 @@ def set_parameter_types(object) end # Warn if the parameter type and tag types don't match - log.warn "The type of the @param tag for parameter '#{parameter.name}' does not match the parameter type specification near #{statement.file}:#{statement.line}: ignoring in favor of parameter type information." if parameter.type && tag.types && !tag.types.empty? && parameter.type != tag.types[0] + if parameter.type && tag.types && !tag.types.empty? && parameter.type != tag.types[0] + log.warn "The type of the @param tag for parameter '#{parameter.name}' "\ + "does not match the parameter type specification near #{statement.file}:#{statement.line}: "\ + 'ignoring in favor of parameter type information.' + end if parameter.type tag.types = [parameter.type] diff --git a/lib/puppet-strings/yard/handlers/puppet/function_handler.rb b/lib/puppet-strings/yard/handlers/puppet/function_handler.rb index 121199519..bed168293 100644 --- a/lib/puppet-strings/yard/handlers/puppet/function_handler.rb +++ b/lib/puppet-strings/yard/handlers/puppet/function_handler.rb @@ -36,7 +36,8 @@ class PuppetStrings::Yard::Handlers::Puppet::FunctionHandler < PuppetStrings::Ya end private - def add_return_tag(object, type=nil) + + def add_return_tag(object, type = nil) tag = object.tag(:return) if tag if (type && tag.types && tag.types.first) && (type != tag.types.first) @@ -47,7 +48,7 @@ def add_return_tag(object, type=nil) return end log.warn "Missing @return tag near #{statement.file}:#{statement.line}." - type = type || 'Any' + type ||= 'Any' object.add_tag YARD::Tags::Tag.new(:return, '', type) end end diff --git a/lib/puppet-strings/yard/handlers/ruby/base.rb b/lib/puppet-strings/yard/handlers/ruby/base.rb index 39da8232e..7b263b524 100644 --- a/lib/puppet-strings/yard/handlers/ruby/base.rb +++ b/lib/puppet-strings/yard/handlers/ruby/base.rb @@ -6,9 +6,10 @@ class PuppetStrings::Yard::Handlers::Ruby::Base < YARD::Handlers::Ruby::Base # A regular expression for detecting the start of a Ruby heredoc. # Note: the first character of the heredoc start may have been cut off by YARD. - HEREDOC_START = /^ 1 + source = lines[1..(lines.last.include?(Regexp.last_match(1)[0..-2]) ? -2 : -1)].join("\n") if lines.size > 1 end source diff --git a/lib/puppet-strings/yard/handlers/ruby/data_type_handler.rb b/lib/puppet-strings/yard/handlers/ruby/data_type_handler.rb index 54f85e33e..b15a6939c 100644 --- a/lib/puppet-strings/yard/handlers/ruby/data_type_handler.rb +++ b/lib/puppet-strings/yard/handlers/ruby/data_type_handler.rb @@ -1,5 +1,7 @@ # frozen_string_literal: true +# rubocop:disable Naming/MethodName + require 'puppet-strings/yard/handlers/helpers' require 'puppet-strings/yard/handlers/ruby/base' require 'puppet-strings/yard/code_objects' @@ -65,7 +67,7 @@ def extract_data_type_interface parsed_interface = nil # Recursively traverse the block looking for the first valid 'interface' call - interface_node = find_ruby_ast_node(block, true) do |node| + find_ruby_ast_node(block, true) do |node| next false unless node.is_a?(YARD::Parser::Ruby::MethodCallNode) && node.method_name && node.method_name.source == 'interface' @@ -102,7 +104,7 @@ def extract_data_type_interface # @yieldreturn [Boolean] Whether the node was what was searched for # @return [YARD::Parser::Ruby::AstNode, nil] def find_ruby_ast_node(ast_node, recurse = false, &block) - raise ArgumentError, 'find_ruby_ast_node requires a block' unless block_given? + raise ArgumentError, 'find_ruby_ast_node requires a block' unless block is_found = yield ast_node return ast_node if is_found @@ -136,7 +138,7 @@ def find_ruby_ast_node(ast_node, recurse = false, &block) # Anything else is ignored class LazyLiteralEvaluator def initialize - @literal_visitor = ::Puppet::Pops::Visitor.new(self, "literal", 0, 0) + @literal_visitor = ::Puppet::Pops::Visitor.new(self, 'literal', 0, 0) end def literal(ast) @@ -187,11 +189,11 @@ def literal_LiteralBoolean(o) o.value end - def literal_LiteralUndef(o) + def literal_LiteralUndef(_o) nil end - def literal_LiteralDefault(o) + def literal_LiteralDefault(_o) :default end @@ -210,9 +212,8 @@ def literal_LiteralList(o) end def literal_LiteralHash(o) - o.entries.reduce({}) do |result, entry| + o.entries.each_with_object({}) do |entry, result| result[literal(entry.key)] = literal(entry.value) - result end end end @@ -235,7 +236,7 @@ def extract_params(hash) default = value['value'] unless value['value'].nil? end data_type = [data_type] unless data_type.nil? || data_type.is_a?(Array) - params_hash[key] = { :types => data_type, :default => default } + params_hash[key] = { types: data_type, default: default } end params_hash @@ -250,7 +251,7 @@ def extract_functions(object, hash) return funcs_hash if hash.nil? || hash['functions'].nil? || hash['functions'].empty? hash['functions'].each do |key, func_type| - func_hash = { :param_types => [], :return_type => nil } + func_hash = { param_types: [], return_type: nil } begin callable_type = Puppet::Pops::Types::TypeParser.singleton.parse(func_type) if callable_type.is_a?(Puppet::Pops::Types::PCallableType) @@ -378,7 +379,9 @@ def validate_function_method!(object, meth, actual_function) if tag.tag_name == 'param' index += 1 if index > actual_function[:param_types].count - log.warn "The @param tag for '#{tag.name}' should not exist for function '#{meth.name}' that is defined near #{object.file}:#{object.line}. Expected only #{actual_function[:param_types].count} parameter/s" + log.warn "The @param tag for '#{tag.name}' should not exist for function "\ + "'#{meth.name}' that is defined near #{object.file}:#{object.line}. "\ + "Expected only #{actual_function[:param_types].count} parameter/s" true else false @@ -392,14 +395,14 @@ def validate_function_method!(object, meth, actual_function) # Add missing params if meth.docstring.tags(:param).count < actual_function[:param_types].count start = meth.docstring.tags(:param).count + 1 - (start..actual_function[:param_types].count).each do |index| # Using 1-based index here instead of usual zero - meth.add_tag(YARD::Tags::Tag.new(:param, '', actual_function[:param_types][index - 1], "param#{index}")) + (start..actual_function[:param_types].count).each do |param_type_index| # Using 1-based index here instead of usual zero + meth.add_tag(YARD::Tags::Tag.new(:param, '', actual_function[:param_types][param_type_index - 1], "param#{param_type_index}")) end end # Ensure the parameter types are correct - meth.docstring.tags(:param).each_with_index do |tag, index| - actual_types = [actual_function[:param_types][index]] + meth.docstring.tags(:param).each_with_index do |tag, actual_type_index| + actual_types = [actual_function[:param_types][actual_type_index]] if tag.types != actual_types log.warn "The @param tag for '#{tag.name}' for function '#{meth.name}' has a different type definition than the actual function near #{object.file}:#{object.line}. Expected #{actual_types}" tag.types = actual_types diff --git a/lib/puppet-strings/yard/handlers/ruby/function_handler.rb b/lib/puppet-strings/yard/handlers/ruby/function_handler.rb index 07b4fd37b..dbf067d56 100644 --- a/lib/puppet-strings/yard/handlers/ruby/function_handler.rb +++ b/lib/puppet-strings/yard/handlers/ruby/function_handler.rb @@ -8,18 +8,18 @@ # Implements the handler for Puppet functions written in Ruby. class PuppetStrings::Yard::Handlers::Ruby::FunctionHandler < PuppetStrings::Yard::Handlers::Ruby::Base # Represents the list of Puppet 4.x function API methods to support. - DISPATCH_METHOD_NAMES = %w( - param - required_param - optional_param - repeated_param - optional_repeated_param - required_repeated_param - block_param - required_block_param - optional_block_param - return_type - ).freeze + DISPATCH_METHOD_NAMES = [ + 'param', + 'required_param', + 'optional_param', + 'repeated_param', + 'optional_repeated_param', + 'required_repeated_param', + 'block_param', + 'required_block_param', + 'optional_block_param', + 'return_type', + ].freeze namespace_only handles method_call(:create_function) @@ -33,13 +33,13 @@ class PuppetStrings::Yard::Handlers::Ruby::FunctionHandler < PuppetStrings::Yard return unless statement.count > 1 module_name = statement[0].source - return unless module_name == 'Puppet::Functions' || module_name == 'Puppet::Parser::Functions' || module_name == 'newfunction' + return unless ['Puppet::Functions', 'Puppet::Parser::Functions', 'newfunction'].include?(module_name) # Create and register the function object - is_3x = module_name == 'Puppet::Parser::Functions' || module_name == 'newfunction' + is_3x = ['Puppet::Parser::Functions', 'newfunction'].include?(module_name) object = PuppetStrings::Yard::CodeObjects::Function.new( get_name(statement, 'Puppet::Functions.create_function'), - is_3x ? PuppetStrings::Yard::CodeObjects::Function::RUBY_3X : PuppetStrings::Yard::CodeObjects::Function::RUBY_4X + is_3x ? PuppetStrings::Yard::CodeObjects::Function::RUBY_3X : PuppetStrings::Yard::CodeObjects::Function::RUBY_4X, ) object.source = statement register object @@ -56,7 +56,7 @@ class PuppetStrings::Yard::Handlers::Ruby::FunctionHandler < PuppetStrings::Yard end # Populate the parameters and the return tag - object.parameters = object.tags(:param).map{ |p| [p.name, nil] } + object.parameters = object.tags(:param).map { |p| [p.name, nil] } add_return_tag(object, statement.file, statement.line) else # For 4x, auto generate tags based on dispatch docstrings @@ -71,11 +71,27 @@ class PuppetStrings::Yard::Handlers::Ruby::FunctionHandler < PuppetStrings::Yard end private + def add_tags(object) log.warn "Missing documentation for Puppet function '#{object.name}' at #{statement.file}:#{statement.line}." if object.docstring.empty? && object.tags.empty? - log.warn "The docstring for Puppet 4.x function '#{object.name}' contains @param tags near #{object.file}:#{object.line}: parameter documentation should be made on the dispatch call." unless object.tags(:param).empty? - log.warn "The docstring for Puppet 4.x function '#{object.name}' contains @return tags near #{object.file}:#{object.line}: return value documentation should be made on the dispatch call." unless object.tags(:return).empty? - log.warn "The docstring for Puppet 4.x function '#{object.name}' contains @overload tags near #{object.file}:#{object.line}: overload tags are automatically generated from the dispatch calls." unless object.tags(:overload).empty? + + unless object.tags(:param).empty? + log.warn "The docstring for Puppet 4.x function '#{object.name}' "\ + "contains @param tags near #{object.file}:#{object.line}: parameter "\ + 'documentation should be made on the dispatch call.' + end + + unless object.tags(:return).empty? + log.warn "The docstring for Puppet 4.x function '#{object.name}' "\ + "contains @return tags near #{object.file}:#{object.line}: return "\ + 'value documentation should be made on the dispatch call.' + end + + unless object.tags(:overload).empty? + log.warn "The docstring for Puppet 4.x function '#{object.name}' "\ + "contains @overload tags near #{object.file}:#{object.line}: overload "\ + 'tags are automatically generated from the dispatch calls.' + end # Delete any existing param/return/overload tags object.docstring.delete_tags(:param) @@ -106,12 +122,11 @@ def add_tags(object) end # If there's only one overload, move the tags to the object itself - if overloads.count == 1 - overload = overloads.first - object.parameters = overload.parameters - object.add_tag(*overload.tags) - object.docstring.delete_tags(:overload) - end + return unless overloads.length == 1 + overload = overloads.first + object.parameters = overload.parameters + object.add_tag(*overload.tags) + object.docstring.delete_tags(:overload) end def add_overload_tag(object, node) @@ -169,7 +184,7 @@ def add_overload_tag(object, node) node_as_string(parameters[0]), nil, # TODO: determine default from corresponding Ruby method signature? method_name.include?('optional'), - method_name.include?('repeated') + method_name.include?('repeated'), ) end @@ -200,7 +215,7 @@ def add_overload_tag(object, node) nil, # TODO: determine default from corresponding Ruby method signature? block.method_name.source.include?('optional'), false, # Not repeated - true # Is block + true, # Is block ) end end @@ -223,29 +238,29 @@ def add_method_overload(object, node) # Populate the required parameters params = parameters.unnamed_required_params params&.each do |parameter| - add_param_tag( - overload_tag, - param_tags, - parameter.source, - parameter.file, - parameter.line - ) - end + add_param_tag( + overload_tag, + param_tags, + parameter.source, + parameter.file, + parameter.line, + ) + end # Populate the optional parameters params = parameters.unnamed_optional_params params&.each do |parameter| - add_param_tag( - overload_tag, - param_tags, - parameter[0].source, - parameter.file, - parameter.line, - nil, - parameter[1].source, - true - ) - end + add_param_tag( + overload_tag, + param_tags, + parameter[0].source, + parameter.file, + parameter.line, + nil, + parameter[1].source, + true, + ) + end # Populate the splat parameter param = parameters.splat_param @@ -259,7 +274,7 @@ def add_method_overload(object, node) nil, nil, false, - true + true, ) end @@ -276,7 +291,7 @@ def add_method_overload(object, node) nil, false, false, - true + true, ) end @@ -290,9 +305,14 @@ def add_method_overload(object, node) end def add_param_tag(object, tags, name, file, line, type = nil, default = nil, optional = false, repeated = false, block = false) - tag = tags.find { |tag| tag.name == name } if tags + tag = tags.find { |t| t.name == name } if tags log.warn "Missing @param tag for parameter '#{name}' near #{file}:#{line}." unless tag || object.docstring.all.empty? - log.warn "The @param tag for parameter '#{name}' should not contain a type specification near #{file}:#{line}: ignoring in favor of dispatch type information." if type && tag && tag.types && !tag.types.empty? + + if type && tag && tag.types && !tag.types.empty? + log.warn "The @param tag for parameter '#{name}' should not contain a "\ + "type specification near #{file}:#{line}: ignoring in favor of "\ + 'dispatch type information.' + end if repeated name = '*' + name diff --git a/lib/puppet-strings/yard/handlers/ruby/provider_handler.rb b/lib/puppet-strings/yard/handlers/ruby/provider_handler.rb index c12b159f1..1a199a347 100644 --- a/lib/puppet-strings/yard/handlers/ruby/provider_handler.rb +++ b/lib/puppet-strings/yard/handlers/ruby/provider_handler.rb @@ -44,6 +44,7 @@ class PuppetStrings::Yard::Handlers::Ruby::ProviderHandler < PuppetStrings::Yard end private + def register_provider_docstring(object) # Walk the tree searching for assignments or calls to desc/doc= statement.traverse do |child| @@ -93,7 +94,7 @@ def populate_provider_data(object) object.add_confine(node_as_string(kvp[0]) || kvp[0].source, node_as_string(kvp[1]) || kvp[1].source) end - elsif method_name == 'has_feature' || method_name == 'has_features' + elsif ['has_feature', 'has_features'].include?(method_name) # Add the features to the object parameters.each do |parameter| object.add_feature(node_as_string(parameter) || parameter.source) diff --git a/lib/puppet-strings/yard/handlers/ruby/rsapi_handler.rb b/lib/puppet-strings/yard/handlers/ruby/rsapi_handler.rb index 19f50b209..c9c36f526 100644 --- a/lib/puppet-strings/yard/handlers/ruby/rsapi_handler.rb +++ b/lib/puppet-strings/yard/handlers/ruby/rsapi_handler.rb @@ -52,11 +52,15 @@ def raise_parse_error(msg, location = statement) # check that the params of the register_type call are key/value pairs. def kv_arg_list?(params) - params.type == :list && params.children.count > 0 && params.children.first.type == :list && params.children.first.children.count > 0 && statement.parameters.children.first.children.first.type == :assoc + params.type == :list && + params.children.count > 0 && + params.children.first.type == :list && + params.children.first.children.count > 0 && + statement.parameters.children.first.children.first.type == :assoc end def extract_schema - raise_parse_error("Expected list of key/value pairs as argument") unless kv_arg_list?(statement.parameters) + raise_parse_error('Expected list of key/value pairs as argument') unless kv_arg_list?(statement.parameters) hash_from_node(statement.parameters.children.first) end @@ -84,7 +88,7 @@ def value_from_node(node) def array_from_node(node) return nil unless node - arr = node.children.collect do |assoc| + node.children.map do |assoc| value_from_node(assoc.children[0]) end end @@ -94,7 +98,7 @@ def hash_from_node(node) # puts "hash from #{node.inspect}" - kv_pairs = node.children.collect do |assoc| + kv_pairs = node.children.map do |assoc| [value_from_node(assoc.children[0]), value_from_node(assoc.children[1])] end Hash[kv_pairs] @@ -107,20 +111,19 @@ def var_ref_from_node(node) if node.children.first.type == :kw case node.children.first.source - when "false" + when 'false' return false - when "true" + when 'true' return true - when "nil" + when 'nil' return nil else raise_parse_error("unexpected keyword '#{node.children.first.source}'") end end - raise_parse_error("unexpected variable") + raise_parse_error('unexpected variable') end - def populate_type_data(object, schema) return if schema['attributes'].nil? diff --git a/lib/puppet-strings/yard/handlers/ruby/type_base.rb b/lib/puppet-strings/yard/handlers/ruby/type_base.rb index 09da6e86f..ea681f88e 100644 --- a/lib/puppet-strings/yard/handlers/ruby/type_base.rb +++ b/lib/puppet-strings/yard/handlers/ruby/type_base.rb @@ -2,17 +2,19 @@ require 'puppet-strings/yard/handlers/ruby/base' +# Base class for all Puppet resource type handlers. class PuppetStrings::Yard::Handlers::Ruby::TypeBase < PuppetStrings::Yard::Handlers::Ruby::Base protected + def get_type_yard_object(name) - #Have to guess the path - if we create the object to get the true path from the code, - #it also shows up in the .at call - self registering? + # Have to guess the path - if we create the object to get the true path from the code, + # it also shows up in the .at call - self registering? guess_path = "puppet_types::#{name}" object = YARD::Registry.at(guess_path) return object unless object.nil? - #Didn't find, create instead + # Didn't find, create instead object = PuppetStrings::Yard::CodeObjects::Type.new(name) register object object @@ -32,8 +34,8 @@ def find_docstring(node, kind) elsif child.is_a?(YARD::Parser::Ruby::MethodCallNode) # Look for a call to a dispatch method with a block next unless child.method_name && - (child.method_name.source == 'desc' || child.method_name.source == 'doc=') && - child.parameters(false).count == 1 + (child.method_name.source == 'desc' || child.method_name.source == 'doc=') && + child.parameters(false).count == 1 docstring = node_as_string(child.parameters[0]) log.error "Failed to parse docstring for #{kind} near #{child.file}:#{child.line}." and return nil unless docstring @@ -100,27 +102,25 @@ def set_values(node, object) parameters = node.parameters(false) if parameters.count >= 2 - kvps = parameters[1].find_all { |kvp| kvp.count == 2 } + kvps = parameters[1].select { |kvp| kvp.count == 2 } required_features_kvp = kvps.find { |kvp| node_as_string(kvp[0]) == 'required_features' } object.required_features = node_as_string(required_features_kvp[1]) unless required_features_kvp.nil? end - if object.is_a? PuppetStrings::Yard::CodeObjects::Type::Parameter - # Process the options for parameter base types - if parameters.count >= 2 - parameters[1].each do |kvp| - next unless kvp.count == 2 - next unless node_as_string(kvp[0]) == 'parent' - - if kvp[1].source == 'Puppet::Parameter::Boolean' - object.add('true') unless object.values.include? 'true' # rubocop:disable Performance/InefficientHashSearch Not supported on Ruby 2.1 - object.add('false') unless object.values.include? 'false' # rubocop:disable Performance/InefficientHashSearch Not supported on Ruby 2.1 - object.add('yes') unless object.values.include? 'yes' # rubocop:disable Performance/InefficientHashSearch Not supported on Ruby 2.1 - object.add('no') unless object.values.include? 'no' # rubocop:disable Performance/InefficientHashSearch Not supported on Ruby 2.1 - end - break - end + return unless object.is_a? PuppetStrings::Yard::CodeObjects::Type::Parameter + # Process the options for parameter base types + return unless parameters.count >= 2 + parameters[1].each do |kvp| + next unless kvp.count == 2 + next unless node_as_string(kvp[0]) == 'parent' + + if kvp[1].source == 'Puppet::Parameter::Boolean' + object.add('true') unless object.values.include? 'true' + object.add('false') unless object.values.include? 'false' + object.add('yes') unless object.values.include? 'yes' + object.add('no') unless object.values.include? 'no' end + break end end @@ -129,15 +129,15 @@ def set_default_namevar(object) default = nil object.properties&.each do |property| - return nil if property.isnamevar + return nil if property.isnamevar - default = property if property.name == 'name' - end + default = property if property.name == 'name' + end object.parameters&.each do |parameter| - return nil if parameter.isnamevar + return nil if parameter.isnamevar - default ||= parameter if parameter.name == 'name' - end + default ||= parameter if parameter.name == 'name' + end default.isnamevar = true if default end end diff --git a/lib/puppet-strings/yard/handlers/ruby/type_extras_handler.rb b/lib/puppet-strings/yard/handlers/ruby/type_extras_handler.rb index aa49fcae0..2aa09d044 100644 --- a/lib/puppet-strings/yard/handlers/ruby/type_extras_handler.rb +++ b/lib/puppet-strings/yard/handlers/ruby/type_extras_handler.rb @@ -16,7 +16,6 @@ class PuppetStrings::Yard::Handlers::Ruby::TypeExtrasHandler < PuppetStrings::Ya handles method_call(:ensurable) process do - # Our entry point is a type newproperty/newparam compound statement like this: # "Puppet::Type.type(:file).newparam(:content) do" # We want to @@ -36,7 +35,7 @@ class PuppetStrings::Yard::Handlers::Ruby::TypeExtrasHandler < PuppetStrings::Ya return unless (statement.count > 1) && (statement[0].children.count > 2) module_name = statement[0].children[0].source - method1_name = statement[0].children.drop(1).find{ |c| c.type == :ident }.source + method1_name = statement[0].children.drop(1).find { |c| c.type == :ident }.source return unless ['Type', 'Puppet::Type'].include?(module_name) && method1_name == 'type' # ensurable is syntatic sugar for newproperty @@ -52,7 +51,7 @@ class PuppetStrings::Yard::Handlers::Ruby::TypeExtrasHandler < PuppetStrings::Ya typeobject = get_type_yard_object(typename) # node - what should it be here? - node = statement #?? not sure... test... + node = statement # ?? not sure... test... if method2_name == 'newproperty' typeobject.add_property(create_property(propertyname, node)) diff --git a/lib/puppet-strings/yard/handlers/ruby/type_handler.rb b/lib/puppet-strings/yard/handlers/ruby/type_handler.rb index 084dfbc25..a5eeba5c1 100644 --- a/lib/puppet-strings/yard/handlers/ruby/type_handler.rb +++ b/lib/puppet-strings/yard/handlers/ruby/type_handler.rb @@ -18,7 +18,7 @@ class PuppetStrings::Yard::Handlers::Ruby::TypeHandler < PuppetStrings::Yard::Ha return unless statement.count > 1 module_name = statement[0].source - return unless module_name == 'Puppet::Type' || module_name == 'Type' + return unless ['Puppet::Type', 'Type'].include?(module_name) object = get_type_yard_object(get_name(statement, 'Puppet::Type.newtype')) @@ -39,6 +39,7 @@ class PuppetStrings::Yard::Handlers::Ruby::TypeHandler < PuppetStrings::Yard::Ha end private + def populate_type_data(object) # Traverse the block looking for properties/parameters/features block = statement.block diff --git a/lib/puppet-strings/yard/parsers.rb b/lib/puppet-strings/yard/parsers.rb index 47b37dedf..c18f43fbd 100644 --- a/lib/puppet-strings/yard/parsers.rb +++ b/lib/puppet-strings/yard/parsers.rb @@ -6,6 +6,7 @@ module PuppetStrings::Yard::Parsers module JSON require 'puppet-strings/yard/parsers/json/parser' end + # The module for custom YARD parsers for the Puppet language. module Puppet require 'puppet-strings/yard/parsers/puppet/parser' diff --git a/lib/puppet-strings/yard/parsers/json/parser.rb b/lib/puppet-strings/yard/parsers/json/parser.rb index c9199dcfa..3fcfcc534 100644 --- a/lib/puppet-strings/yard/parsers/json/parser.rb +++ b/lib/puppet-strings/yard/parsers/json/parser.rb @@ -2,6 +2,7 @@ require 'puppet-strings/yard/parsers/json/task_statement' +# Implementas a JSON parser. class PuppetStrings::Yard::Parsers::JSON::Parser < YARD::Parser::Base attr_reader :file, :source @@ -9,7 +10,7 @@ class PuppetStrings::Yard::Parsers::JSON::Parser < YARD::Parser::Base # @param [String] source The source being parsed. # @param [String] filename The file name of the file being parsed. # @return [void] - def initialize(source, filename) + def initialize(source, filename) # rubocop:disable Lint/MissingSuper @file = filename @source = source @statements = [] @@ -27,7 +28,7 @@ def parse # TODO: this should compare json to a Task metadata json-schema or perform some other hueristics # to determine what type of statement it represents @statements.push(PuppetStrings::Yard::Parsers::JSON::TaskStatement.new(json, @source, @file)) unless json.empty? - rescue # rubocop:disable Style/RescueStandardError Just catch everything + rescue log.error "Failed to parse #{@file}: " @statements = [] end diff --git a/lib/puppet-strings/yard/parsers/json/task_statement.rb b/lib/puppet-strings/yard/parsers/json/task_statement.rb index 9cead548f..a083b350d 100644 --- a/lib/puppet-strings/yard/parsers/json/task_statement.rb +++ b/lib/puppet-strings/yard/parsers/json/task_statement.rb @@ -3,7 +3,7 @@ module PuppetStrings::Yard::Parsers::JSON # Represents the Puppet Task statement. class TaskStatement - attr_reader :line, :comments, :comments_range, :json, :file, :source, :docstring + attr_reader :line, :comments_range, :json, :file, :source, :docstring def initialize(json, source, file) @file = file @@ -23,7 +23,7 @@ def comments_hash_flag end def show - "" + '' end def comments @@ -31,7 +31,7 @@ def comments end def name - File.basename(@file).gsub('.json','') || "" + File.basename(@file).gsub('.json', '') || '' end end end diff --git a/lib/puppet-strings/yard/parsers/puppet/parser.rb b/lib/puppet-strings/yard/parsers/puppet/parser.rb index 4c34e4007..745fd26ed 100644 --- a/lib/puppet-strings/yard/parsers/puppet/parser.rb +++ b/lib/puppet-strings/yard/parsers/puppet/parser.rb @@ -1,5 +1,7 @@ # frozen_string_literal: true +# rubocop:disable Naming/MethodName + require 'puppet' require 'puppet/pops' require 'puppet-strings/yard/parsers/puppet/statement' @@ -12,7 +14,7 @@ class PuppetStrings::Yard::Parsers::Puppet::Parser < YARD::Parser::Base # @param [String] source The source being parsed. # @param [String] filename The file name of the file being parsed. # @return [void] - def initialize(source, filename) + def initialize(source, filename) # rubocop:disable Lint/MissingSuper @source = source @file = filename @visitor = ::Puppet::Pops::Visitor.new(self, 'transform') @@ -22,8 +24,8 @@ def initialize(source, filename) # @return [void] def parse begin - if @file.to_s.match(/^plans|\/plans\//) - if Puppet::Util::Package.versioncmp(Puppet.version, "5.0.0") < 0 + if @file.to_s.match?(%r{^plans|/plans/}) + if Puppet::Util::Package.versioncmp(Puppet.version, '5.0.0') < 0 log.warn "Skipping #{@file}: Puppet Plans require Puppet 5 or greater." return end diff --git a/lib/puppet-strings/yard/parsers/puppet/statement.rb b/lib/puppet-strings/yard/parsers/puppet/statement.rb index 01d8a16ca..54cf7f625 100644 --- a/lib/puppet-strings/yard/parsers/puppet/statement.rb +++ b/lib/puppet-strings/yard/parsers/puppet/statement.rb @@ -7,7 +7,7 @@ module PuppetStrings::Yard::Parsers::Puppet # Represents the base Puppet language statement. class Statement # The pattern for parsing docstring comments. - COMMENT_REGEX = /^\s*#+\s?/ + COMMENT_REGEX = %r{^\s*#+\s?}.freeze attr_reader :source attr_reader :file @@ -32,7 +32,7 @@ def initialize(object, file) # @return [void] def extract_docstring(lines) comment = [] - (0..@line-2).reverse_each do |index| + (0..@line - 2).reverse_each do |index| break unless index <= lines.count line = lines[index].strip @@ -66,8 +66,9 @@ def comments_hash_flag end private + def first_line - @source.split(/\r?\n/).first.strip + @source.split(%r{\r?\n}).first.strip end end @@ -89,10 +90,9 @@ def initialize(parameter) @type = adapter.extract_text end # Take the exact text for the default value expression - if parameter.value - adapter = ::Puppet::Pops::Adapters::SourcePosAdapter.adapt(parameter.value) - @value = adapter.extract_text - end + return unless parameter.value + adapter = ::Puppet::Pops::Adapters::SourcePosAdapter.adapt(parameter.value) + @value = adapter.extract_text end end @@ -146,13 +146,11 @@ class FunctionStatement < ParameterizedStatement def initialize(object, file) super(object, file) @name = object.name - if object.respond_to? :return_type - type = object.return_type - if type - adapter = ::Puppet::Pops::Adapters::SourcePosAdapter.adapt(type) - @type = adapter.extract_text.gsub('>> ', '') - end - end + return unless object.respond_to? :return_type + type = object.return_type + return unless type + adapter = ::Puppet::Pops::Adapters::SourcePosAdapter.adapt(type) + @type = adapter.extract_text.gsub('>> ', '') end end diff --git a/lib/puppet-strings/yard/tags/enum_tag.rb b/lib/puppet-strings/yard/tags/enum_tag.rb index 2ce82c75b..b8b757204 100644 --- a/lib/puppet-strings/yard/tags/enum_tag.rb +++ b/lib/puppet-strings/yard/tags/enum_tag.rb @@ -3,12 +3,11 @@ require 'yard/tags/option_tag' # Implements an enum tag for describing enumerated value data types - class PuppetStrings::Yard::Tags::EnumTag < YARD::Tags::OptionTag # Registers the tag with YARD. # @return [void] def self.register! - YARD::Tags::Library.define_tag("puppet.enum", :enum, :with_enums) + YARD::Tags::Library.define_tag('puppet.enum', :enum, :with_enums) YARD::Tags::Library.visible_tags.place(:enum).after(:option) end end diff --git a/lib/puppet-strings/yard/tags/factory.rb b/lib/puppet-strings/yard/tags/factory.rb index b2d5a6c23..763d78190 100644 --- a/lib/puppet-strings/yard/tags/factory.rb +++ b/lib/puppet-strings/yard/tags/factory.rb @@ -3,8 +3,8 @@ require 'yard/tags/default_factory' require 'puppet-strings/yard/tags/enum_tag' +# Factory for creating tags. class PuppetStrings::Yard::Tags::Factory < YARD::Tags::DefaultFactory - # Parses tag text and creates a new enum tag type. Modeled after # the parse_tag_with_options method in YARD::Tags::DefaultFactory. # diff --git a/lib/puppet-strings/yard/tags/overload_tag.rb b/lib/puppet-strings/yard/tags/overload_tag.rb index 3b358cbca..e474dbc01 100644 --- a/lib/puppet-strings/yard/tags/overload_tag.rb +++ b/lib/puppet-strings/yard/tags/overload_tag.rb @@ -21,15 +21,15 @@ def initialize(name, docstring) # @return [String] Returns the signature of the overload. def signature tags = self.tags(:param) - args = @parameters.map do |parameter| + args = @parameters.map { |parameter| name, default = parameter tag = tags.find { |t| t.name == name } if tags type = tag&.types ? "#{tag.type} " : 'Any ' - prefix = "#{name[0]}" if name.start_with?('*', '&') + prefix = (name[0]).to_s if name.start_with?('*', '&') name = name[1..-1] if prefix default = " = #{default}" if default "#{type}#{prefix}$#{name}#{default}" - end.join(', ') + }.join(', ') @name + '(' + args + ')' end @@ -57,7 +57,7 @@ def tags(name = nil) # Determines if a tag with the given name is present. # @param [String, Symbol] name The tag name. # @return [Boolean] Returns true if there is at least one tag with the given name or false if not. - def has_tag?(name) + def has_tag?(name) # rubocop:disable Naming/PredicateName @docstring.has_tag?(name) end @@ -67,7 +67,7 @@ def has_tag?(name) def object=(value) super(value) @docstring.object = value - @docstring.tags.each {|tag| tag.object = value } + @docstring.tags.each { |tag| tag.object = value } end # Responsible for forwarding method calls to the associated object. @@ -102,8 +102,8 @@ def to_hash hash[:tag_name] = tag_name hash[:text] = text if text hash[:signature] = signature - hash[:docstring] = PuppetStrings::Yard::Util.docstring_to_hash(docstring) if !docstring.blank? - defaults = Hash[*parameters.reject{ |p| p[1].nil? }.flatten] + hash[:docstring] = PuppetStrings::Yard::Util.docstring_to_hash(docstring) unless docstring.blank? + defaults = Hash[*parameters.reject { |p| p[1].nil? }.flatten] hash[:defaults] = defaults unless defaults.empty? hash[:types] = types if types hash[:name] = name if name diff --git a/lib/puppet-strings/yard/tags/parameter_directive.rb b/lib/puppet-strings/yard/tags/parameter_directive.rb index d84b537c9..da9023192 100644 --- a/lib/puppet-strings/yard/tags/parameter_directive.rb +++ b/lib/puppet-strings/yard/tags/parameter_directive.rb @@ -12,8 +12,8 @@ def call # Add a parameter to the resource parameter = PuppetStrings::Yard::CodeObjects::Type::Parameter.new(tag.name, tag.text) tag.types&.each do |value| - parameter.add(value) - end + parameter.add(value) + end object.add_parameter parameter end diff --git a/lib/puppet-strings/yard/tags/property_directive.rb b/lib/puppet-strings/yard/tags/property_directive.rb index db2c41296..9cf25b43e 100644 --- a/lib/puppet-strings/yard/tags/property_directive.rb +++ b/lib/puppet-strings/yard/tags/property_directive.rb @@ -12,8 +12,8 @@ def call # Add a property to the resource property = PuppetStrings::Yard::CodeObjects::Type::Property.new(tag.name, tag.text) tag.types&.each do |value| - property.add(value) - end + property.add(value) + end object.add_property property end diff --git a/lib/puppet-strings/yard/tags/summary_tag.rb b/lib/puppet-strings/yard/tags/summary_tag.rb index 44e9dd541..b3168673b 100644 --- a/lib/puppet-strings/yard/tags/summary_tag.rb +++ b/lib/puppet-strings/yard/tags/summary_tag.rb @@ -1,11 +1,10 @@ # frozen_string_literal: true # Implements a summary tag for general purpose short descriptions - class PuppetStrings::Yard::Tags::SummaryTag < YARD::Tags::Tag # Registers the tag with YARD. # @return [void] def self.register! - YARD::Tags::Library.define_tag("puppet.summary", :summary) + YARD::Tags::Library.define_tag('puppet.summary', :summary) end end diff --git a/lib/puppet-strings/yard/util.rb b/lib/puppet-strings/yard/util.rb index c2a5a82bd..d51b4f4ee 100644 --- a/lib/puppet-strings/yard/util.rb +++ b/lib/puppet-strings/yard/util.rb @@ -9,7 +9,7 @@ module PuppetStrings::Yard::Util # @param [String] str The string to scrub. # @return [String] A scrubbed string. def self.scrub_string(str) - match = str.match(/^%[Qq]{(.*)}$/m) + match = str.match(%r{^%[Qq]{(.*)}$}m) if match return Puppet::Util::Docs.scrub(match[1]) end @@ -25,8 +25,8 @@ def self.scrub_string(str) # @param [String] data HTML document to convert # @return [String] HTML document with links converted def self.github_to_yard_links(data) - data.scan(/href\=\"\#(.+)\"/).each do |bad_link| - data = data.gsub("=\"##{bad_link.first}\"", "=\"#label-#{bad_link.first.capitalize.gsub('-', '+')}\"") + data.scan(%r{href\=\"\#(.+)\"}).each do |bad_link| + data = data.gsub("=\"##{bad_link.first}\"", "=\"#label-#{bad_link.first.capitalize.tr('-', '+')}\"") end data @@ -59,7 +59,7 @@ def self.tags_to_hashes(tags) # @param [YARD::Docstring, String] docstring The docstring to convert to a hash. # @param [Array] select_tags List of tags to select. Other tags will be filtered out. # @return [Hash] Returns a hash representation of the given docstring. - def self.docstring_to_hash(docstring, select_tags=nil) + def self.docstring_to_hash(docstring, select_tags = nil) hash = {} hash[:text] = docstring From 223ef05bcf31e4f3f3ee385633ef5afb58276d56 Mon Sep 17 00:00:00 2001 From: Craig Gumbley Date: Wed, 28 Sep 2022 09:21:37 +0100 Subject: [PATCH 13/16] (MAINT) Rubocop - (lib) fixes for tasks --- lib/puppet-strings/tasks/generate.rb | 18 ++++++++---------- lib/puppet-strings/tasks/gh_pages.rb | 11 ++++++----- lib/puppet-strings/tasks/validate.rb | 2 +- 3 files changed, 15 insertions(+), 16 deletions(-) diff --git a/lib/puppet-strings/tasks/generate.rb b/lib/puppet-strings/tasks/generate.rb index d5e98c15f..57b8d9934 100644 --- a/lib/puppet-strings/tasks/generate.rb +++ b/lib/puppet-strings/tasks/generate.rb @@ -5,7 +5,7 @@ # Implements the strings:generate task. namespace :strings do desc 'Generate Puppet documentation with YARD.' - task :generate, [:patterns, :debug, :backtrace, :markup, :json, :markdown, :yard_args] do |t, args| + task :generate, [:patterns, :debug, :backtrace, :markup, :json, :markdown, :yard_args] do |_t, args| patterns = args[:patterns] patterns = patterns.split if patterns patterns ||= PuppetStrings::DEFAULT_SEARCH_PATTERNS @@ -16,7 +16,7 @@ markup: args[:markup] || 'markdown', } - raise("Error: Both JSON and Markdown output have been selected. Please select one.") if args[:json] == 'true' && args[:markdown] == 'true' + raise('Error: Both JSON and Markdown output have been selected. Please select one.') if args[:json] == 'true' && args[:markdown] == 'true' # rubocop:disable Style/PreferredHashMethods # Because of Ruby, true and false from the args are both strings and both true. Here, @@ -28,16 +28,14 @@ # @param [Symbol] possible format option # @return nil def parse_format_option(args, options, format) - if args.has_key? format - options[format] = args[format] == 'false' || args[format].empty? ? false : true - if options[format] - options[:path] = args[format] == 'true' ? nil : args[format] - end - end + return unless args.has_key? format + options[format] = args[format] == 'false' || args[format].empty? ? false : true + return unless options[format] + options[:path] = args[format] == 'true' ? nil : args[format] end # rubocop:enable Style/PreferredHashMethods - %i[json markdown].each { |format| parse_format_option(args, options, format) } + [:json, :markdown].each { |format| parse_format_option(args, options, format) } warn('yard_args behavior is a little dodgy, use at your own risk') if args[:yard_args] options[:yard_args] = args[:yard_args].split if args.key? :yard_args @@ -47,7 +45,7 @@ def parse_format_option(args, options, format) namespace :generate do desc 'Generate Puppet Reference documentation.' - task :reference, [:patterns, :debug, :backtrace] do |t, args| + task :reference, [:patterns, :debug, :backtrace] do |_t, args| Rake::Task['strings:generate'].invoke(args[:patterns], args[:debug], args[:backtrace], nil, 'false', 'true') end end diff --git a/lib/puppet-strings/tasks/gh_pages.rb b/lib/puppet-strings/tasks/gh_pages.rb index 857c84fc0..576d5da4f 100644 --- a/lib/puppet-strings/tasks/gh_pages.rb +++ b/lib/puppet-strings/tasks/gh_pages.rb @@ -1,12 +1,13 @@ # frozen_string_literal: true +require 'English' require 'puppet-strings/tasks' namespace :strings do namespace :gh_pages do task :checkout do if Dir.exist?('doc') - fail "The 'doc' directory (#{File.expand_path('doc')}) is not a Git repository! Remove it and run the Rake task again." unless Dir.exist?('doc/.git') + raise "The 'doc' directory (#{File.expand_path('doc')}) is not a Git repository! Remove it and run the Rake task again." unless Dir.exist?('doc/.git') Dir.chdir('doc') do system 'git checkout gh-pages' @@ -14,7 +15,7 @@ end else git_uri = `git config --get remote.origin.url`.strip - fail "Could not determine the remote URL for origin: ensure the current directory is a Git repro with a remote named 'origin'." unless $?.success? + raise "Could not determine the remote URL for origin: ensure the current directory is a Git repro with a remote named 'origin'." unless $CHILD_STATUS.success? Dir.mkdir('doc') Dir.chdir('doc') do @@ -29,7 +30,7 @@ task :configure do unless File.exist?(File.join('doc', '_config.yml')) Dir.chdir('doc') do - File.open('_config.yml', 'w+') {|f| f.write("include: _index.html") } + File.open('_config.yml', 'w+') { |f| f.write('include: _index.html') } end end end @@ -37,7 +38,7 @@ task :push do output = `git describe --long 2>/dev/null` # If a project has never been tagged, fall back to latest SHA - output.empty? ? git_sha = `git log --pretty=format:'%H' -n 1` : git_sha = output + git_sha = output.empty? ? `git log --pretty=format:'%H' -n 1` : output Dir.chdir('doc') do system 'git add .' @@ -47,7 +48,7 @@ end desc 'Update docs on the gh-pages branch and push to GitHub.' - task :update => [ + task update: [ :checkout, :'strings:generate', :configure, diff --git a/lib/puppet-strings/tasks/validate.rb b/lib/puppet-strings/tasks/validate.rb index e945f1b6c..7b475061f 100644 --- a/lib/puppet-strings/tasks/validate.rb +++ b/lib/puppet-strings/tasks/validate.rb @@ -6,7 +6,7 @@ namespace :strings do namespace :validate do desc 'Validate the reference is up to date' - task :reference, [:patterns, :debug, :backtrace] do |t, args| + task :reference, [:patterns, :debug, :backtrace] do |_t, args| filename = 'REFERENCE.md' unless File.exist?(filename) From 28ace22ba132a8839fbb721d3bbb244ddcbc9abd Mon Sep 17 00:00:00 2001 From: Craig Gumbley Date: Wed, 28 Sep 2022 09:21:57 +0100 Subject: [PATCH 14/16] (MAINT) Rubocop - (lib) fixes for monkey_patches --- lib/puppet-strings/monkey_patches/display_object_command.rb | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lib/puppet-strings/monkey_patches/display_object_command.rb b/lib/puppet-strings/monkey_patches/display_object_command.rb index f82d52bc9..171be2b01 100644 --- a/lib/puppet-strings/monkey_patches/display_object_command.rb +++ b/lib/puppet-strings/monkey_patches/display_object_command.rb @@ -4,9 +4,12 @@ # namespace, but this is disabled in our base object, and so instead gets # URL-encoded. require 'yard/server/commands/display_object_command' + +# Monkey patch YARD::Server::Commands::DisplayObjectCommand object_path. class YARD::Server::Commands::DisplayObjectCommand private - alias_method :object_path_yard, :object_path + + alias object_path_yard object_path def object_path object_path_yard.gsub('_3A', ':') end From e45c4d6f97c7c1f47df6839b183903eea30429ea Mon Sep 17 00:00:00 2001 From: Craig Gumbley Date: Wed, 28 Sep 2022 09:22:25 +0100 Subject: [PATCH 15/16] (MAINT) Rubocop - (lib) fixes for markdown --- lib/puppet-strings/markdown/base.rb | 23 ++++++++++--------- lib/puppet-strings/markdown/data_type.rb | 1 + lib/puppet-strings/markdown/data_types.rb | 15 +++++------- lib/puppet-strings/markdown/defined_type.rb | 1 + lib/puppet-strings/markdown/defined_types.rb | 12 ++++------ lib/puppet-strings/markdown/function.rb | 18 ++++++++------- lib/puppet-strings/markdown/functions.rb | 13 ++++------- lib/puppet-strings/markdown/puppet_class.rb | 1 + lib/puppet-strings/markdown/puppet_classes.rb | 12 ++++------ lib/puppet-strings/markdown/puppet_plan.rb | 1 + lib/puppet-strings/markdown/puppet_plans.rb | 12 ++++------ lib/puppet-strings/markdown/puppet_task.rb | 2 +- lib/puppet-strings/markdown/puppet_tasks.rb | 6 ++--- lib/puppet-strings/markdown/resource_type.rb | 3 ++- lib/puppet-strings/markdown/resource_types.rb | 12 ++++------ .../markdown/table_of_contents.rb | 13 ++++++----- 16 files changed, 70 insertions(+), 75 deletions(-) diff --git a/lib/puppet-strings/markdown/base.rb b/lib/puppet-strings/markdown/base.rb index 2a40cf515..b0e58a6d9 100644 --- a/lib/puppet-strings/markdown/base.rb +++ b/lib/puppet-strings/markdown/base.rb @@ -4,11 +4,12 @@ require 'puppet-strings/json' require 'puppet-strings/yard' +# Implements classes that make elements in a YARD::Registry hash easily accessible for template. module PuppetStrings::Markdown # This class makes elements in a YARD::Registry hash easily accessible for templates. # # Here's an example hash: - #{:name=>:klass, + # {:name=>:klass, # :file=>"(stdin)", # :line=>16, # :inherits=>"foo::bar", @@ -57,11 +58,11 @@ def initialize(registry, component_type) # generate 1:1 tag methods # e.g. {:tag_name=>"author", :text=>"eputnam"} - { :return_val => 'return', - :since => 'since', - :summary => 'summary', - :note => 'note', - :todo => 'todo' }.each do |method_name, tag_name| + { return_val: 'return', + since: 'since', + summary: 'summary', + note: 'note', + todo: 'todo' }.each do |method_name, tag_name| # @return [String] unless the tag is nil or the string.empty? define_method method_name do @tags.find { |tag| tag[:tag_name] == tag_name && !tag[:text].empty? }[:text] if @tags.any? { |tag| tag[:tag_name] == tag_name && !tag[:text].empty? } @@ -148,7 +149,7 @@ def toc_info { name: name.to_s, link: link, - desc: summary || @registry[:docstring][:text][0..140].gsub("\n",' '), + desc: summary || @registry[:docstring][:text][0..140].tr("\n", ' '), private: private? } end @@ -165,9 +166,9 @@ def private? def word_wrap(text, line_width: 120, break_sequence: "\n") return unless text - text.split("\n").collect! do |line| - line.length > line_width ? line.gsub(/(.{1,#{line_width}})(\s+|$)/, "\\1#{break_sequence}").strip : line - end * break_sequence + text.split("\n").map! { |line| + line.length > line_width ? line.gsub(%r{(.{1,#{line_width}})(\s+|$)}, "\\1#{break_sequence}").strip : line + } * break_sequence end # @return [String] full markdown rendering of a component @@ -176,7 +177,7 @@ def render(template) begin PuppetStrings::Markdown.erb(file).result(binding) rescue StandardError => e - fail "Processing #{@registry[:file]}:#{@registry[:line]} with #{file} => #{e}" + raise "Processing #{@registry[:file]}:#{@registry[:line]} with #{file} => #{e}" end end diff --git a/lib/puppet-strings/markdown/data_type.rb b/lib/puppet-strings/markdown/data_type.rb index c4363bba4..61fa5debb 100644 --- a/lib/puppet-strings/markdown/data_type.rb +++ b/lib/puppet-strings/markdown/data_type.rb @@ -20,6 +20,7 @@ def render end end + # Generates Markdown for a Puppet Function. class DataType::Function < Base def initialize(registry) super(registry, 'data_type_function') diff --git a/lib/puppet-strings/markdown/data_types.rb b/lib/puppet-strings/markdown/data_types.rb index 0fb1bd02c..15c842232 100644 --- a/lib/puppet-strings/markdown/data_types.rb +++ b/lib/puppet-strings/markdown/data_types.rb @@ -3,35 +3,32 @@ require_relative 'data_type' module PuppetStrings::Markdown + # Generates Markdown for Puppet Data Types. module DataTypes - # @return [Array] list of data types def self.in_dtypes arr = YARD::Registry.all(:puppet_data_type).map!(&:to_hash) arr.concat(YARD::Registry.all(:puppet_data_type_alias).map!(&:to_hash)) - arr.sort! { |a,b| a[:name] <=> b[:name] } + arr.sort! { |a, b| a[:name] <=> b[:name] } arr.map! { |a| PuppetStrings::Markdown::DataType.new(a) } end def self.contains_private? - result = false - unless in_dtypes.nil? - in_dtypes.find { |type| type.private? }.nil? ? false : true - end + return if in_dtypes.nil? + in_dtypes.find { |type| type.private? }.nil? ? false : true end def self.render - final = in_dtypes.length > 0 ? "## Data types\n\n" : "" + final = !in_dtypes.empty? ? "## Data types\n\n" : '' in_dtypes.each do |type| final += type.render unless type.private? end final end - def self.toc_info - final = ["Data types"] + final = ['Data types'] in_dtypes.each do |type| final.push(type.toc_info) diff --git a/lib/puppet-strings/markdown/defined_type.rb b/lib/puppet-strings/markdown/defined_type.rb index 37ff07f65..4353d98b2 100644 --- a/lib/puppet-strings/markdown/defined_type.rb +++ b/lib/puppet-strings/markdown/defined_type.rb @@ -3,6 +3,7 @@ require 'puppet-strings/markdown/base' module PuppetStrings::Markdown + # Generates Markdown for a Puppet Defined Type. class DefinedType < Base def initialize(registry) @template = 'classes_and_defines.erb' diff --git a/lib/puppet-strings/markdown/defined_types.rb b/lib/puppet-strings/markdown/defined_types.rb index a4c281a1c..1ec19cad3 100644 --- a/lib/puppet-strings/markdown/defined_types.rb +++ b/lib/puppet-strings/markdown/defined_types.rb @@ -3,8 +3,8 @@ require_relative 'defined_type' module PuppetStrings::Markdown + # Generates Markdown for Puppet Defined Types. module DefinedTypes - # @return [Array] list of defined types def self.in_dtypes arr = YARD::Registry.all(:puppet_defined_type).sort_by!(&:name).map!(&:to_hash) @@ -12,14 +12,12 @@ def self.in_dtypes end def self.contains_private? - result = false - unless in_dtypes.nil? - in_dtypes.find { |type| type.private? }.nil? ? false : true - end + return if in_dtypes.nil? + in_dtypes.find { |type| type.private? }.nil? ? false : true end def self.render - final = in_dtypes.length > 0 ? "## Defined types\n\n" : "" + final = !in_dtypes.empty? ? "## Defined types\n\n" : '' in_dtypes.each do |type| final += type.render unless type.private? end @@ -27,7 +25,7 @@ def self.render end def self.toc_info - final = ["Defined types"] + final = ['Defined types'] in_dtypes.each do |type| final.push(type.toc_info) diff --git a/lib/puppet-strings/markdown/function.rb b/lib/puppet-strings/markdown/function.rb index e2449925f..ba0575f7d 100644 --- a/lib/puppet-strings/markdown/function.rb +++ b/lib/puppet-strings/markdown/function.rb @@ -3,6 +3,7 @@ require 'puppet-strings/markdown/base' module PuppetStrings::Markdown + # Generates Markdown for a Puppet Function. class Function < Base attr_reader :signatures @@ -21,14 +22,14 @@ def render def type t = @registry[:type] - if /ruby4x/.match?(t) - "Ruby 4.x API" - elsif /ruby3/.match?(t) - "Ruby 3.x API" - elsif /ruby/.match?(t) - "Ruby" + if %r{ruby4x}.match?(t) + 'Ruby 4.x API' + elsif %r{ruby3}.match?(t) + 'Ruby 3.x API' + elsif %r{ruby}.match?(t) + 'Ruby' else - "Puppet Language" + 'Puppet Language' end end @@ -37,10 +38,11 @@ def error_type(type) end def error_text(text) - "#{text.split(' ').drop(1).join(' ')}" + text.split(' ').drop(1).join(' ').to_s end end + # Implements methods to retrieve information about a function signature. class Function::Signature < Base def initialize(registry) @registry = registry diff --git a/lib/puppet-strings/markdown/functions.rb b/lib/puppet-strings/markdown/functions.rb index c111478c5..d4361a7e9 100644 --- a/lib/puppet-strings/markdown/functions.rb +++ b/lib/puppet-strings/markdown/functions.rb @@ -3,8 +3,8 @@ require_relative 'function' module PuppetStrings::Markdown + # Generates Markdown for Puppet Functions. module Functions - # @return [Array] list of functions def self.in_functions arr = YARD::Registry.all(:puppet_function).sort_by!(&:name).map!(&:to_hash) @@ -12,14 +12,12 @@ def self.in_functions end def self.contains_private? - result = false - unless in_functions.nil? - in_functions.find { |func| func.private? }.nil? ? false : true - end + return if in_functions.nil? + in_functions.find { |func| func.private? }.nil? ? false : true end def self.render - final = in_functions.length > 0 ? "## Functions\n\n" : "" + final = !in_functions.empty? ? "## Functions\n\n" : '' in_functions.each do |func| final += func.render unless func.private? end @@ -27,7 +25,7 @@ def self.render end def self.toc_info - final = ["Functions"] + final = ['Functions'] in_functions.each do |func| final.push(func.toc_info) @@ -37,4 +35,3 @@ def self.toc_info end end end - diff --git a/lib/puppet-strings/markdown/puppet_class.rb b/lib/puppet-strings/markdown/puppet_class.rb index 4eda6c57e..37ea1698b 100644 --- a/lib/puppet-strings/markdown/puppet_class.rb +++ b/lib/puppet-strings/markdown/puppet_class.rb @@ -3,6 +3,7 @@ require 'puppet-strings/markdown/base' module PuppetStrings::Markdown + # Generates Markdown for a Puppet Class. class PuppetClass < Base def initialize(registry) @template = 'classes_and_defines.erb' diff --git a/lib/puppet-strings/markdown/puppet_classes.rb b/lib/puppet-strings/markdown/puppet_classes.rb index f22dd5789..ef7b4ce8c 100644 --- a/lib/puppet-strings/markdown/puppet_classes.rb +++ b/lib/puppet-strings/markdown/puppet_classes.rb @@ -3,8 +3,8 @@ require_relative 'puppet_class' module PuppetStrings::Markdown + # Generates Markdown for Puppet Classes. module PuppetClasses - # @return [Array] list of classes def self.in_classes arr = YARD::Registry.all(:puppet_class).sort_by!(&:name).map!(&:to_hash) @@ -12,14 +12,12 @@ def self.in_classes end def self.contains_private? - result = false - unless in_classes.nil? - in_classes.find { |klass| klass.private? }.nil? ? false : true - end + return if in_classes.nil? + in_classes.find { |klass| klass.private? }.nil? ? false : true end def self.render - final = in_classes.length > 0 ? "## Classes\n\n" : "" + final = !in_classes.empty? ? "## Classes\n\n" : '' in_classes.each do |klass| final += klass.render unless klass.private? end @@ -27,7 +25,7 @@ def self.render end def self.toc_info - final = ["Classes"] + final = ['Classes'] in_classes.each do |klass| final.push(klass.toc_info) diff --git a/lib/puppet-strings/markdown/puppet_plan.rb b/lib/puppet-strings/markdown/puppet_plan.rb index 56601dacf..310fc505a 100644 --- a/lib/puppet-strings/markdown/puppet_plan.rb +++ b/lib/puppet-strings/markdown/puppet_plan.rb @@ -3,6 +3,7 @@ require 'puppet-strings/markdown/base' module PuppetStrings::Markdown + # Generates Markdown for a Puppet Plan. class PuppetPlan < Base def initialize(registry) @template = 'classes_and_defines.erb' diff --git a/lib/puppet-strings/markdown/puppet_plans.rb b/lib/puppet-strings/markdown/puppet_plans.rb index 7586eab01..4c9406a4b 100644 --- a/lib/puppet-strings/markdown/puppet_plans.rb +++ b/lib/puppet-strings/markdown/puppet_plans.rb @@ -3,8 +3,8 @@ require_relative 'puppet_plan' module PuppetStrings::Markdown + # Generates Markdown for Puppet Plans. module PuppetPlans - # @return [Array] list of classes def self.in_plans arr = YARD::Registry.all(:puppet_plan).sort_by!(&:name).map!(&:to_hash) @@ -12,14 +12,12 @@ def self.in_plans end def self.contains_private? - result = false - unless in_plans.nil? - in_plans.find { |plan| plan.private? }.nil? ? false : true - end + return if in_plans.nil? + in_plans.find { |plan| plan.private? }.nil? ? false : true end def self.render - final = in_plans.length > 0 ? "## Plans\n\n" : "" + final = !in_plans.empty? ? "## Plans\n\n" : '' in_plans.each do |plan| final += plan.render unless plan.private? end @@ -27,7 +25,7 @@ def self.render end def self.toc_info - final = ["Plans"] + final = ['Plans'] in_plans.each do |plan| final.push(plan.toc_info) diff --git a/lib/puppet-strings/markdown/puppet_task.rb b/lib/puppet-strings/markdown/puppet_task.rb index d00e5bdb0..7da80ed23 100644 --- a/lib/puppet-strings/markdown/puppet_task.rb +++ b/lib/puppet-strings/markdown/puppet_task.rb @@ -3,6 +3,7 @@ require 'puppet-strings/markdown/base' module PuppetStrings::Markdown + # Generates Markdown for a Puppet Task. class PuppetTask < Base def initialize(registry) @template = 'puppet_task.erb' @@ -21,6 +22,5 @@ def supports_noop def input_method @registry[:input_method] end - end end diff --git a/lib/puppet-strings/markdown/puppet_tasks.rb b/lib/puppet-strings/markdown/puppet_tasks.rb index 9d394f3fc..835cb1f98 100644 --- a/lib/puppet-strings/markdown/puppet_tasks.rb +++ b/lib/puppet-strings/markdown/puppet_tasks.rb @@ -3,8 +3,8 @@ require_relative 'puppet_task' module PuppetStrings::Markdown + # Generates Markdown for Puppet Tasks. module PuppetTasks - # @return [Array] list of classes def self.in_tasks arr = YARD::Registry.all(:puppet_task).sort_by!(&:name).map!(&:to_hash) @@ -16,7 +16,7 @@ def self.contains_private? end def self.render - final = in_tasks.length > 0 ? "## Tasks\n\n" : "" + final = !in_tasks.empty? ? "## Tasks\n\n" : '' in_tasks.each do |task| final += task.render unless task.private? end @@ -24,7 +24,7 @@ def self.render end def self.toc_info - final = ["Tasks"] + final = ['Tasks'] in_tasks.each do |task| final.push(task.toc_info) diff --git a/lib/puppet-strings/markdown/resource_type.rb b/lib/puppet-strings/markdown/resource_type.rb index 1d959cb67..424cb98e8 100644 --- a/lib/puppet-strings/markdown/resource_type.rb +++ b/lib/puppet-strings/markdown/resource_type.rb @@ -3,6 +3,7 @@ require 'puppet-strings/markdown/base' module PuppetStrings::Markdown + # Generates Markdown for a Puppet Resource Type. class ResourceType < Base def initialize(registry) @template = 'resource_type.erb' @@ -45,7 +46,7 @@ def parameters end def regex_in_data_type?(data_type) - m = data_type.match(/\w+\[\/.*\/\]/) + m = data_type.match(%r{\w+\[/.*/\]}) m unless m.nil? || m.length.zero? end end diff --git a/lib/puppet-strings/markdown/resource_types.rb b/lib/puppet-strings/markdown/resource_types.rb index 01abe1c65..e4c87a816 100644 --- a/lib/puppet-strings/markdown/resource_types.rb +++ b/lib/puppet-strings/markdown/resource_types.rb @@ -3,8 +3,8 @@ require_relative 'resource_type' module PuppetStrings::Markdown + # Generates Markdown for Puppet Resource Types. module ResourceTypes - # @return [Array] list of resource types def self.in_rtypes arr = YARD::Registry.all(:puppet_type).sort_by!(&:name).map!(&:to_hash) @@ -12,14 +12,12 @@ def self.in_rtypes end def self.contains_private? - result = false - unless in_rtypes.nil? - in_rtypes.find { |type| type.private? }.nil? ? false : true - end + return if in_rtypes.nil? + in_rtypes.find { |type| type.private? }.nil? ? false : true end def self.render - final = in_rtypes.length > 0 ? "## Resource types\n\n" : "" + final = !in_rtypes.empty? ? "## Resource types\n\n" : '' in_rtypes.each do |type| final += type.render unless type.private? end @@ -27,7 +25,7 @@ def self.render end def self.toc_info - final = ["Resource types"] + final = ['Resource types'] in_rtypes.each do |type| final.push(type.toc_info) diff --git a/lib/puppet-strings/markdown/table_of_contents.rb b/lib/puppet-strings/markdown/table_of_contents.rb index 5f7e15382..eaf2bf856 100644 --- a/lib/puppet-strings/markdown/table_of_contents.rb +++ b/lib/puppet-strings/markdown/table_of_contents.rb @@ -1,17 +1,18 @@ # frozen_string_literal: true module PuppetStrings::Markdown + # Generates a table of contents. module TableOfContents def self.render final = "## Table of Contents\n\n" [PuppetStrings::Markdown::PuppetClasses, - PuppetStrings::Markdown::DefinedTypes, - PuppetStrings::Markdown::ResourceTypes, - PuppetStrings::Markdown::Functions, - PuppetStrings::Markdown::DataTypes, - PuppetStrings::Markdown::PuppetTasks, - PuppetStrings::Markdown::PuppetPlans].each do |r| + PuppetStrings::Markdown::DefinedTypes, + PuppetStrings::Markdown::ResourceTypes, + PuppetStrings::Markdown::Functions, + PuppetStrings::Markdown::DataTypes, + PuppetStrings::Markdown::PuppetTasks, + PuppetStrings::Markdown::PuppetPlans].each do |r| toc = r.toc_info group_name = toc.shift group = toc From f68b2be91cc77bcd092818f345e558566146840c Mon Sep 17 00:00:00 2001 From: Craig Gumbley Date: Wed, 28 Sep 2022 09:22:50 +0100 Subject: [PATCH 16/16] (MAINT) Rubocop - (lib) fixes for puppet-strings --- lib/puppet-strings.rb | 20 +++++++------------ lib/puppet-strings/describe.rb | 36 +++++++++++++++++----------------- lib/puppet-strings/tasks.rb | 12 +++++------- lib/puppet-strings/yard.rb | 12 ++++++------ 4 files changed, 36 insertions(+), 44 deletions(-) diff --git a/lib/puppet-strings.rb b/lib/puppet-strings.rb index 29ead460e..db65123e4 100644 --- a/lib/puppet-strings.rb +++ b/lib/puppet-strings.rb @@ -1,16 +1,11 @@ +# rubocop:disable Naming/FileName + # frozen_string_literal: true # The root module for Puppet Strings. module PuppetStrings # The glob patterns used to search for files to document. - DEFAULT_SEARCH_PATTERNS = %w( - manifests/**/*.pp - functions/**/*.pp - types/**/*.pp - lib/**/*.rb - tasks/*.json - plans/**/*.pp - ).freeze + DEFAULT_SEARCH_PATTERNS = ['manifests/**/*.pp', 'functions/**/*.pp', 'types/**/*.pp', 'lib/**/*.rb', 'tasks/*.json', 'plans/**/*.pp'].freeze # Generates documentation. # @param [Array] search_patterns The search patterns (e.g. manifests/**/*.pp) to look for files. @@ -39,7 +34,7 @@ def self.generate(search_patterns = DEFAULT_SEARCH_PATTERNS, options = {}) file = if options[:json] options[:path] elsif options[:markdown] - options[:path] || "REFERENCE.md" + options[:path] || 'REFERENCE.md' end # Disable output and prevent stats/progress when writing to STDOUT args << '-n' @@ -64,13 +59,12 @@ def self.generate(search_patterns = DEFAULT_SEARCH_PATTERNS, options = {}) render_markdown(file) end - if options[:describe] - render_describe(options[:describe_types], options[:describe_list], options[:providers]) - end + return unless options[:describe] + render_describe(options[:describe_types], options[:describe_list], options[:providers]) end def self.puppet_5? - Puppet::Util::Package.versioncmp(Puppet.version, "5.0.0") >= 0 + Puppet::Util::Package.versioncmp(Puppet.version, '5.0.0') >= 0 end def self.render_json(path) diff --git a/lib/puppet-strings/describe.rb b/lib/puppet-strings/describe.rb index 982851730..2583008d5 100644 --- a/lib/puppet-strings/describe.rb +++ b/lib/puppet-strings/describe.rb @@ -8,16 +8,16 @@ module PuppetStrings::Describe # Renders requested types or a summarized list in the current YARD registry to STDOUT. # @param [Array] describe_types The list of names of the types to be displayed. # @param [bool] list Create the summarized list instead of describing each type. - # @param [bool] providers Show details of the providers. + # @param [bool] _providers Show details of the providers. # @return [void] - def self.render(describe_types = [], list = false, providers = false) + def self.render(describe_types = [], list = false, _providers = false) document = { defined_types: YARD::Registry.all(:puppet_defined_type).sort_by!(&:name).map!(&:to_hash), - resource_types: YARD::Registry.all(:puppet_type).sort_by!(&:name).map!(&:to_hash), + resource_types: YARD::Registry.all(:puppet_type).sort_by!(&:name).map!(&:to_hash), } if list - puts "These are the types known to puppet:" + puts 'These are the types known to puppet:' document[:resource_types].each { |t| list_one_type(t) } else document[:providers] = YARD::Registry.all(:puppet_provider).sort_by!(&:name).map!(&:to_hash) @@ -26,31 +26,31 @@ def self.render(describe_types = [], list = false, providers = false) describe_types.each { |name| type_names[name] = true } document[:resource_types].each do |t| - show_one_type(t, providers) if type_names[t[:name].to_s] + show_one_type(t) if type_names[t[:name].to_s] end end end - def self.show_one_type(resource_type, providers = false) - puts "\n%{name}\n%{underscore}" % { name: resource_type[:name], underscore: "=" * resource_type[:name].length } + def self.show_one_type(resource_type) + puts "\n%{name}\n%{underscore}" % { name: resource_type[:name], underscore: '=' * resource_type[:name].length } puts resource_type[:docstring][:text] combined_list = (resource_type[:parameters].nil? ? [] : resource_type[:parameters]) + (resource_type[:properties].nil? ? [] : resource_type[:properties]) - if combined_list.any? - puts "\nParameters\n----------" - combined_list.sort_by { |p| p[:name] }.each { |p| show_one_parameter(p) } - puts "\nProviders\n---------" - end - #Show providers here - list or provide details + return unless combined_list.any? + + puts "\nParameters\n----------" + combined_list.sort_by { |p| p[:name] }.each { |p| show_one_parameter(p) } + puts "\nProviders\n---------" + # Show providers here - list or provide details end def self.show_one_parameter(parameter) puts "\n- **%{name}**\n" % { name: parameter[:name] } puts parameter[:description] - puts "Valid values are `%{values}`." % { values: parameter[:values].join("`, `") } unless parameter[:values].nil? - puts "Requires features %{required_features}." % { required_features: parameter[:required_features] } unless parameter[:required_features].nil? + puts 'Valid values are `%{values}`.' % { values: parameter[:values].join('`, `') } unless parameter[:values].nil? + puts 'Requires features %{required_features}.' % { required_features: parameter[:required_features] } unless parameter[:required_features].nil? end def self.list_one_type(type) @@ -58,13 +58,13 @@ def self.list_one_type(type) shortento = targetlength - 4 contentstring = type[:docstring][:text] end_of_line = contentstring.index("\n") # "." gives closer results to old describeb, but breaks for '.k5login' - if !end_of_line.nil? + unless end_of_line.nil? contentstring = contentstring[0..end_of_line] end if contentstring.length > targetlength contentstring = contentstring[0..shortento] + ' ...' end - - puts "%-15s - %-s" % [type[:name], contentstring] + + puts "#{type[:name].to_s.ljust(15)} - #{contentstring}" end end diff --git a/lib/puppet-strings/tasks.rb b/lib/puppet-strings/tasks.rb index 60f906aae..8d68600a4 100644 --- a/lib/puppet-strings/tasks.rb +++ b/lib/puppet-strings/tasks.rb @@ -3,11 +3,9 @@ require 'rake' require 'rake/tasklib' -module PuppetStrings - # The module for Puppet Strings rake tasks. - module Tasks - require 'puppet-strings/tasks/generate.rb' - require 'puppet-strings/tasks/gh_pages.rb' - require 'puppet-strings/tasks/validate.rb' - end +# The module for Puppet Strings rake tasks. +module PuppetStrings::Tasks + require 'puppet-strings/tasks/generate.rb' + require 'puppet-strings/tasks/gh_pages.rb' + require 'puppet-strings/tasks/validate.rb' end diff --git a/lib/puppet-strings/yard.rb b/lib/puppet-strings/yard.rb index 0d6111737..fe9912980 100644 --- a/lib/puppet-strings/yard.rb +++ b/lib/puppet-strings/yard.rb @@ -61,7 +61,7 @@ def all_objects :puppet_provider, :puppet_function, :puppet_task, - :puppet_plan + :puppet_plan, ) end end @@ -114,18 +114,18 @@ def output(name, data, undoc = nil) @undocumented += undoc if undoc.is_a?(Integer) data = if undoc - ('%5s (% 5d undocumented)' % [data, undoc]) + "#{data} (#{undoc} undocumented)" else - '%5s' % data + data.to_s end - log.puts('%-21s %s' % [name + ':', data]) + log.puts("#{name.ljust(25)} #{data}") end # This differs from the YARD implementation in that it considers # a docstring without text but with tags to be undocumented. def type_statistics_all(type) - objs = all_objects.select {|m| m.type == type } - undoc = objs.find_all {|m| m.docstring.all.empty? } + objs = all_objects.select { |m| m.type == type } + undoc = objs.select { |m| m.docstring.all.empty? } @undoc_list |= undoc if @undoc_list [objs.size, undoc.size] end