Skip to content

Commit

Permalink
Add command-line switch -S/--display-style-guide
Browse files Browse the repository at this point in the history
When enabled style guide URLs are added to offence messages. Setting
DisplayStyleGuide to true in the config has the same effect.
  • Loading branch information
marxarelli committed Feb 24, 2015
1 parent 7c1c28e commit e8fe222
Show file tree
Hide file tree
Showing 7 changed files with 125 additions and 51 deletions.
2 changes: 1 addition & 1 deletion .rubocop_todo.yml
Expand Up @@ -12,7 +12,7 @@ Metrics/AbcSize:
# Offense count: 9
# Configuration parameters: CountComments.
Metrics/ClassLength:
Max: 138
Max: 148

# Offense count: 28
Metrics/CyclomaticComplexity:
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -4,6 +4,7 @@

### New features

* [#1669](https://github.com/bbatsov/rubocop/pull/1669): Add command-line switch `--display-style-guide`. ([@marxarelli][])
* [#1641](https://github.com/bbatsov/rubocop/pull/1641): Add ruby19_no_mixed_keys style to `HashStyle` cop. ([@iainbeeston][])
* [#1604](https://github.com/bbatsov/rubocop/issues/1604): Add `IgnoreClassMethods` option to `TrivialAccessors` cop. ([@bbatsov][])
* [#1651](https://github.com/bbatsov/rubocop/issues/1651): The `Style/SpaceAroundOperators` cop now also detects extra spaces around operators. A list of operators that *may* be surrounded by multiple spaces is configurable. ([@bquorning][])
Expand Down
4 changes: 4 additions & 0 deletions config/default.yml
Expand Up @@ -33,6 +33,10 @@ AllCops:
# by overriding DisplayCopNames, or by giving the -D/--display-cop-names
# option.
DisplayCopNames: false
# Style guide URLs are not displayed in offense messages by default. Change
# behavior by overriding DisplayStyleGuide, or by giving the
# -S/--display-style-guide option.
DisplayStyleGuide: false
# Additional cops that do not reference a style guide rule may be enabled by
# default. Change behavior by overriding StyleGuideCopsOnly, or by giving
# the --only-guide-cops option.
Expand Down
19 changes: 18 additions & 1 deletion lib/rubocop/cop/cop.rb
Expand Up @@ -132,6 +132,12 @@ def display_cop_names?
config['AllCops'] && config['AllCops']['DisplayCopNames']
end

def display_style_guide?
style_guide_url &&
(@options[:display_style_guide] ||
config['AllCops'] && config['AllCops']['DisplayStyleGuide'])
end

def message(_node = nil)
self.class::MSG
end
Expand All @@ -151,7 +157,7 @@ def add_offense(node, loc, message = nil, severity = nil)
severity = custom_severity || severity || default_severity

message ||= message(node)
message = display_cop_names? ? "#{name}: #{message}" : message
message = annotate_message(message)

corrected = begin
autocorrect(node) if autocorrect?
Expand Down Expand Up @@ -183,8 +189,19 @@ def relevant_file?(file)
!file_name_matches_any?(file, 'Exclude', false)
end

def style_guide_url
url = cop_config && cop_config['StyleGuide']
(url.nil? || url.empty?) ? nil : url
end

private

def annotate_message(message)
message = "#{name}: #{message}" if display_cop_names?
message = "#{message} (#{style_guide_url})" if display_style_guide?
message
end

def file_name_matches_any?(file, parameter, default_result)
patterns = cop_config && cop_config[parameter]
return default_result unless patterns
Expand Down
92 changes: 47 additions & 45 deletions lib/rubocop/options.rb
Expand Up @@ -6,51 +6,52 @@ module RuboCop
# This module contains help texts for command line options.
module OptionsHelp
TEXT = {
only: 'Run only the given cop(s).',
only_guide_cops: ['Run only cops for rules that link to a',
'style guide.'],
except: 'Disable the given cop(s).',
require: 'Require Ruby file.',
config: 'Specify configuration file.',
auto_gen_config: ['Generate a configuration file acting as a',
'TODO list.'],
force_exclusion: ['Force excluding files specified in the',
'configuration `Exclude` even if they are',
'explicitly passed as arguments.'],
format: ['Choose an output formatter. This option',
'can be specified multiple times to enable',
'multiple formatters at the same time.',
' [p]rogress (default)',
' [s]imple',
' [c]lang',
' [d]isabled cops via inline comments',
' [fu]ubar',
' [e]macs',
' [j]son',
' [h]tml',
' [fi]les',
' [o]ffenses',
' custom formatter class name'],
out: ['Write output to a file instead of STDOUT.',
'This option applies to the previously',
'specified --format, or the default format',
'if no format is specified.'],
fail_level: ['Minimum severity (A/R/C/W/E/F) for exit',
'with error code.'],
show_cops: ['Shows the given cops, or all cops by',
'default, and their configurations for the',
'current directory.'],
fail_fast: ['Inspect files in order of modification',
'time and stop after the first file',
'containing offenses.'],
debug: 'Display debug info.',
display_cop_names: 'Display cop names in offense messages.',
rails: 'Run extra Rails cops.',
lint: 'Run only lint cops.',
auto_correct: 'Auto-correct offenses.',
no_color: 'Disable color output.',
version: 'Display version.',
verbose_version: 'Display verbose version.'
only: 'Run only the given cop(s).',
only_guide_cops: ['Run only cops for rules that link to a',
'style guide.'],
except: 'Disable the given cop(s).',
require: 'Require Ruby file.',
config: 'Specify configuration file.',
auto_gen_config: ['Generate a configuration file acting as a',
'TODO list.'],
force_exclusion: ['Force excluding files specified in the',
'configuration `Exclude` even if they are',
'explicitly passed as arguments.'],
format: ['Choose an output formatter. This option',
'can be specified multiple times to enable',
'multiple formatters at the same time.',
' [p]rogress (default)',
' [s]imple',
' [c]lang',
' [d]isabled cops via inline comments',
' [fu]ubar',
' [e]macs',
' [j]son',
' [h]tml',
' [fi]les',
' [o]ffenses',
' custom formatter class name'],
out: ['Write output to a file instead of STDOUT.',
'This option applies to the previously',
'specified --format, or the default format',
'if no format is specified.'],
fail_level: ['Minimum severity (A/R/C/W/E/F) for exit',
'with error code.'],
show_cops: ['Shows the given cops, or all cops by',
'default, and their configurations for the',
'current directory.'],
fail_fast: ['Inspect files in order of modification',
'time and stop after the first file',
'containing offenses.'],
debug: 'Display debug info.',
display_cop_names: 'Display cop names in offense messages.',
display_style_guide: 'Display style guide URLs in offense messages.',
rails: 'Run extra Rails cops.',
lint: 'Run only lint cops.',
auto_correct: 'Auto-correct offenses.',
no_color: 'Disable color output.',
version: 'Display version.',
verbose_version: 'Display verbose version.'
}
end

Expand Down Expand Up @@ -165,6 +166,7 @@ def add_boolean_flags(opts)
option(opts, '-F', '--fail-fast')
option(opts, '-d', '--debug')
option(opts, '-D', '--display-cop-names')
option(opts, '-S', '--display-style-guide')
option(opts, '-R', '--rails')
option(opts, '-l', '--lint')
option(opts, '-a', '--auto-correct')
Expand Down
53 changes: 50 additions & 3 deletions spec/rubocop/cli_spec.rb
Expand Up @@ -1183,25 +1183,45 @@ def abs(path)

it 'shows cop names' do
create_file('example1.rb', "\tputs 0")
file = abs('example1.rb')

expect(cli.run(['--format',
'emacs',
'--debug',
'example1.rb'])).to eq(1)
expect($stdout.string.lines.to_a[-1])
.to eq(["#{abs('example1.rb')}:1:1: C: Style/Tab: Tab detected.",
.to eq(["#{file}:1:1: C: Style/Tab: Tab detected.",
''].join("\n"))
end
end

describe '-D/--display-cop-names' do
it 'shows cop names' do
create_file('example1.rb', "\tputs 0")
file = abs('example1.rb')

expect(cli.run(['--format',
'emacs',
'--debug',
'--display-cop-names',
'example1.rb'])).to eq(1)
expect($stdout.string.lines.to_a[-1])
.to eq(["#{file}:1:1: C: Style/Tab: Tab detected.",
''].join("\n"))
end
end

describe '-S/--display-style-guide' do
it 'shows style guide entry' do
create_file('example1.rb', "\tputs 0")
file = abs('example1.rb')
url = 'https://github.com/bbatsov/ruby-style-guide#spaces-indentation'

expect(cli.run(['--format',
'emacs',
'--display-style-guide',
'example1.rb'])).to eq(1)
expect($stdout.string.lines.to_a[-1])
.to eq(["#{abs('example1.rb')}:1:1: C: Style/Tab: Tab detected.",
.to eq(["#{file}:1:1: C: Tab detected. (#{url})",
''].join("\n"))
end
end
Expand Down Expand Up @@ -2159,6 +2179,33 @@ def interrupt
''].join("\n"))
end

it 'displays style guide URLs if DisplayStyleGuide is true' do
source = ['# encoding: utf-8',
'x = 0 ',
'puts x']
create_file('example1.rb', source)

# DisplayCopNames: false inherited from config/default.yml
create_file('.rubocop.yml', [])

create_file('dir/example2.rb', source)
create_file('dir/.rubocop.yml', ['AllCops:',
' DisplayStyleGuide: true'])

url = 'https://github.com/bbatsov/ruby-style-guide#no-trailing-whitespace'

expect(cli.run(%w(--format simple))).to eq(1)
expect($stdout.string)
.to eq(['== example1.rb ==',
'C: 2: 6: Trailing whitespace detected.',
'== dir/example2.rb ==',
'C: 2: 6: Trailing whitespace' \
" detected. (#{url})",
'',
'2 files inspected, 2 offenses detected',
''].join("\n"))
end

it 'finds included files' do
create_file('file.rb', 'x=0') # Included by default
create_file('example', 'x=0')
Expand Down
5 changes: 4 additions & 1 deletion spec/rubocop/options_spec.rb
Expand Up @@ -34,6 +34,7 @@ def abs(path)
rescue SystemExit # rubocop:disable Lint/HandleExceptions
end

# rubocop:disable Metrics/LineLength
expected_help = <<-END
Usage: rubocop [options] [file1, file2, ...]
--except [COP1,COP2,...] Disable the given cop(s).
Expand Down Expand Up @@ -75,13 +76,15 @@ def abs(path)
containing offenses.
-d, --debug Display debug info.
-D, --display-cop-names Display cop names in offense messages.
-S, --display-style-guide Display style guide URLs in offense messages.
-R, --rails Run extra Rails cops.
-l, --lint Run only lint cops.
-a, --auto-correct Auto-correct offenses.
-n, --no-color Disable color output.
-v, --version Display version.
-V, --verbose-version Display verbose version.
END
END
# rubocop:enable Metrics/LineLength

expect($stdout.string).to eq(expected_help)
end
Expand Down

0 comments on commit e8fe222

Please sign in to comment.