Class: RuboCop::Cop::Chef::ChefStyle::CommentFormat

Inherits:
RuboCop::Cop
  • Object
show all
Defined in:
lib/rubocop/cop/chef/style/comments_format.rb

Overview

Checks for incorrectly formatted headers

Examples:


# bad
Copyright 2013-2016 Chef Software, Inc.
Recipe default.rb
Attributes default.rb
License Apache2
Cookbook tomcat
Cookbook Name:: Tomcat
Attributes File:: default

# good
Copyright:: 2013-2016 Chef Software, Inc.
Recipe:: default.rb
Attributes:: default.rb
License:: Apache License, Version 2.0
Cookbook:: Tomcat

Constant Summary collapse

MSG =
'Properly format header comments'.freeze

Instance Method Summary collapse

Instance Method Details

#autocorrect(comment) ⇒ Object



58
59
60
61
62
63
64
65
66
67
# File 'lib/rubocop/cop/chef/style/comments_format.rb', line 58

def autocorrect(comment)
  # Extract the type and the actual value. Strip out "Name" or "File"
  # 'Cookbook Name' should be 'Cookbook'. Also skip a :: if present
  # https://rubular.com/r/Do9fpLWXlCmvdJ
  match = /^#\s*([A-Za-z]+)\s?(?:Name|File)?(?:::)?\s(.*)/.match(comment.text)
  comment_type, value = match.captures
  correct_comment = "# #{comment_type}:: #{value}"

  ->(corrector) { corrector.replace(comment.loc.expression, correct_comment) }
end

#investigate(processed_source) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/rubocop/cop/chef/style/comments_format.rb', line 45

def investigate(processed_source)
  return unless processed_source.ast

  processed_source.comments.each do |comment|
    next if comment.loc.first_line > 10 # avoid false positives when we were checking further down the file
    next unless comment.inline? # headers aren't in blocks

    if invalid_comment?(comment)
      add_offense(comment, location: comment.loc.expression, message: MSG, severity: :refactor)
    end
  end
end