Class: RuboCop::Cop::Chef::Style::CommentFormat

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/chef/style/comments_format.rb

Overview

Checks for incorrectly formatted headers

Examples:


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

### correct
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'
VERBOSE_COMMENT_REGEX =
/^#\s*([A-Za-z]+)\s?(?:Name|File)?(?:::)?\s(.*)/.freeze
CHEF_LIKE_COMMENT_REGEX =
/^#\s*(Author|Cookbook|Library|Attribute|Copyright|Recipe|Resource|Definition|License)\s+/.freeze

Instance Method Summary collapse

Methods inherited from Base

#target_chef_version

Instance Method Details

#on_new_investigationObject



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/rubocop/cop/chef/style/comments_format.rb', line 49

def on_new_investigation
  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? && CHEF_LIKE_COMMENT_REGEX.match?(comment.text) # headers aren't in blocks

    add_offense(comment, severity: :refactor) do |corrector|
      # 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 = VERBOSE_COMMENT_REGEX.match(comment.text)
      comment_type, value = match.captures
      correct_comment = "# #{comment_type}:: #{value}"
      corrector.replace(comment, correct_comment)
    end
  end
end