erbcop 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 83b12a5974c220329d0f7e7afd819ccb684393822e42afb1c313a7222b101ddc
4
+ data.tar.gz: 395fb3c1ed1b1d3e06fd5fba735528092825adb6b6152d3de8564d95d90733ed
5
+ SHA512:
6
+ metadata.gz: 02f26eb4e0dc4db0047aa0e75bff070073f099b7e7f2f1ce463e27852769bac04af383dea0864985586639f189d848174d3b17bc85d9cf0bbdb91442dfdc0bce
7
+ data.tar.gz: ac2022f7afea7cf9b1338bcf61c4b8bd2c14f970ac6eba26be4839ec45b9b96a71e5a71f4f4051013fef1fff354f3cc8723ecbc8bee5c8d552d6f4884156ed1a
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,31 @@
1
+ require:
2
+ - rubocop-rspec
3
+
4
+ AllCops:
5
+ NewCops: enable
6
+ SuggestExtensions: false
7
+ TargetRubyVersion: 2.6
8
+
9
+ Layout/LineLength:
10
+ Enabled: false
11
+
12
+ Metrics:
13
+ Enabled: false
14
+
15
+ RSpec/AnyInstance:
16
+ Enabled: false
17
+
18
+ RSpec/ExampleLength:
19
+ Enabled: false
20
+
21
+ RSpec/ImplicitSubject:
22
+ Enabled: false
23
+
24
+ RSpec/MultipleExpectations:
25
+ Enabled: false
26
+
27
+ RSpec/NamedSubject:
28
+ Enabled: false
29
+
30
+ Style/Documentation:
31
+ Enabled: false
data/CHANGELOG.md ADDED
@@ -0,0 +1,10 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ ## 0.1.0 - 2022-01-15
6
+
7
+ ### Added
8
+
9
+ - Initial release.
10
+ - Add almost the same features as slimcop 0.11.0.
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at r7kamura@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ # Specify your gem's dependencies in erbcop.gemspec
6
+ gemspec
7
+
8
+ gem 'rake'
9
+ gem 'rspec'
10
+ gem 'rubocop'
11
+ gem 'rubocop-rspec'
data/Gemfile.lock ADDED
@@ -0,0 +1,102 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ erbcop (0.1.0)
5
+ better_html
6
+ rainbow
7
+ rubocop (>= 0.87)
8
+
9
+ GEM
10
+ remote: https://rubygems.org/
11
+ specs:
12
+ actionview (7.0.1)
13
+ activesupport (= 7.0.1)
14
+ builder (~> 3.1)
15
+ erubi (~> 1.4)
16
+ rails-dom-testing (~> 2.0)
17
+ rails-html-sanitizer (~> 1.1, >= 1.2.0)
18
+ activesupport (7.0.1)
19
+ concurrent-ruby (~> 1.0, >= 1.0.2)
20
+ i18n (>= 1.6, < 2)
21
+ minitest (>= 5.1)
22
+ tzinfo (~> 2.0)
23
+ ast (2.4.2)
24
+ better_html (1.0.16)
25
+ actionview (>= 4.0)
26
+ activesupport (>= 4.0)
27
+ ast (~> 2.0)
28
+ erubi (~> 1.4)
29
+ html_tokenizer (~> 0.0.6)
30
+ parser (>= 2.4)
31
+ smart_properties
32
+ builder (3.2.4)
33
+ concurrent-ruby (1.1.9)
34
+ crass (1.0.6)
35
+ diff-lcs (1.5.0)
36
+ erubi (1.10.0)
37
+ html_tokenizer (0.0.7)
38
+ i18n (1.8.11)
39
+ concurrent-ruby (~> 1.0)
40
+ loofah (2.13.0)
41
+ crass (~> 1.0.2)
42
+ nokogiri (>= 1.5.9)
43
+ minitest (5.15.0)
44
+ nokogiri (1.13.1-x86_64-linux)
45
+ racc (~> 1.4)
46
+ parallel (1.21.0)
47
+ parser (3.1.0.0)
48
+ ast (~> 2.4.1)
49
+ racc (1.6.0)
50
+ rails-dom-testing (2.0.3)
51
+ activesupport (>= 4.2.0)
52
+ nokogiri (>= 1.6)
53
+ rails-html-sanitizer (1.4.2)
54
+ loofah (~> 2.3)
55
+ rainbow (3.1.1)
56
+ rake (13.0.6)
57
+ regexp_parser (2.2.0)
58
+ rexml (3.2.5)
59
+ rspec (3.10.0)
60
+ rspec-core (~> 3.10.0)
61
+ rspec-expectations (~> 3.10.0)
62
+ rspec-mocks (~> 3.10.0)
63
+ rspec-core (3.10.1)
64
+ rspec-support (~> 3.10.0)
65
+ rspec-expectations (3.10.2)
66
+ diff-lcs (>= 1.2.0, < 2.0)
67
+ rspec-support (~> 3.10.0)
68
+ rspec-mocks (3.10.2)
69
+ diff-lcs (>= 1.2.0, < 2.0)
70
+ rspec-support (~> 3.10.0)
71
+ rspec-support (3.10.3)
72
+ rubocop (1.24.1)
73
+ parallel (~> 1.10)
74
+ parser (>= 3.0.0.0)
75
+ rainbow (>= 2.2.2, < 4.0)
76
+ regexp_parser (>= 1.8, < 3.0)
77
+ rexml
78
+ rubocop-ast (>= 1.15.1, < 2.0)
79
+ ruby-progressbar (~> 1.7)
80
+ unicode-display_width (>= 1.4.0, < 3.0)
81
+ rubocop-ast (1.15.1)
82
+ parser (>= 3.0.1.1)
83
+ rubocop-rspec (2.7.0)
84
+ rubocop (~> 1.19)
85
+ ruby-progressbar (1.11.0)
86
+ smart_properties (1.17.0)
87
+ tzinfo (2.0.4)
88
+ concurrent-ruby (~> 1.0)
89
+ unicode-display_width (2.1.0)
90
+
91
+ PLATFORMS
92
+ x86_64-linux
93
+
94
+ DEPENDENCIES
95
+ erbcop!
96
+ rake
97
+ rspec
98
+ rubocop
99
+ rubocop-rspec
100
+
101
+ BUNDLED WITH
102
+ 2.3.5
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Ryo Nakamura
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,64 @@
1
+ # Erbcop
2
+
3
+ [![test](https://github.com/r7kamura/erbcop/actions/workflows/test.yml/badge.svg)](https://github.com/r7kamura/erbcop/actions/workflows/test.yml)
4
+
5
+ [RuboCop](https://github.com/rubocop/rubocop) runner for ERB template.
6
+
7
+ This is the ERB version of [Slimcop](https://github.com/r7kamura/slimcop).
8
+
9
+ ## Installation
10
+
11
+ Add this line to your application's Gemfile:
12
+
13
+ ```ruby
14
+ gem 'erbcop'
15
+ ```
16
+
17
+ And then execute:
18
+
19
+ ```
20
+ bundle install
21
+ ```
22
+
23
+ Or install it yourself as:
24
+
25
+ ```
26
+ gem install erbcop
27
+ ```
28
+
29
+ ## Usage
30
+
31
+ Use `erbcop` executable to check offenses and auto-correct them.
32
+
33
+ ```console
34
+ $ erbcop --help
35
+ Usage: erbcop [options] [file1, file2, ...]
36
+ -a, --auto-correct Auto-correct offenses.
37
+ -c, --config= Specify configuration file. (default: .erbcop.yml or .rubocop.yml)
38
+ --[no-]color Force color output on or off.
39
+ ```
40
+
41
+ ### Example
42
+
43
+ ```console
44
+ $ erbcop 'spec/fixtures/**/*.erb'
45
+ Inspecting 1 file
46
+ C
47
+
48
+ Offenses:
49
+
50
+ spec/fixtures/dummy.erb:1:4: C: [Correctable] Style/StringLiterals: Prefer single-quoted strings when you don't need string interpolation or special symbols.
51
+ <% "a" %>
52
+ ^^^
53
+ spec/fixtures/dummy.erb:4:9: C: [Correctable] Style/NumericPredicate: Use array.size.positive? instead of array.size > 0.
54
+ <% a if array.size > 0 %>
55
+ ^^^^^^^^^^^^^^
56
+ spec/fixtures/dummy.erb:4:9: C: [Correctable] Style/ZeroLengthPredicate: Use !empty? instead of size > 0.
57
+ <% a if array.size > 0 %>
58
+ ^^^^^^^^^^^^^^
59
+ spec/fixtures/dummy.erb:5:4: C: [Correctable] Style/NegatedIf: Favor unless over if for negative conditions.
60
+ <% a if !b %>
61
+ ^^^^^^^
62
+
63
+ 1 file inspected, 4 offenses detected, 4 offenses auto-correctable
64
+ ```
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require 'rubocop/rake_task'
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/default.yml ADDED
@@ -0,0 +1,116 @@
1
+ Layout/ArgumentAlignment:
2
+ Enabled: false
3
+
4
+ Layout/ArrayAlignment:
5
+ Enabled: false
6
+
7
+ Layout/BlockAlignment:
8
+ Enabled: false
9
+
10
+ Layout/ClosingParenthesisIndentation:
11
+ Enabled: false
12
+
13
+ Lint/EmptyFile:
14
+ Enabled: false
15
+
16
+ Layout/EmptyLineAfterGuardClause:
17
+ Enabled: false
18
+
19
+ Layout/EndAlignment:
20
+ Enabled: false
21
+
22
+ Layout/FirstArgumentIndentation:
23
+ Enabled: false
24
+
25
+ Layout/FirstArrayElementIndentation:
26
+ Enabled: false
27
+
28
+ Layout/FirstHashElementIndentation:
29
+ Enabled: false
30
+
31
+ Layout/FirstParameterIndentation:
32
+ Enabled: false
33
+
34
+ Layout/HashAlignment:
35
+ Enabled: false
36
+
37
+ Layout/IndentationConsistency:
38
+ Enabled: false
39
+
40
+ Layout/IndentationWidth:
41
+ Enabled: false
42
+
43
+ Layout/InitialIndentation:
44
+ Enabled: false
45
+
46
+ Layout/LineEndStringConcatenationIndentation:
47
+ Enabled: false
48
+
49
+ Layout/LineLength:
50
+ Enabled: false
51
+
52
+ Layout/MultilineArrayBraceLayout:
53
+ Enabled: false
54
+
55
+ Layout/MultilineAssignmentLayout:
56
+ Enabled: false
57
+
58
+ Layout/MultilineHashBraceLayout:
59
+ Enabled: false
60
+
61
+ Layout/MultilineMethodCallBraceLayout:
62
+ Enabled: false
63
+
64
+ Layout/MultilineMethodCallIndentation:
65
+ Enabled: false
66
+
67
+ Layout/MultilineMethodDefinitionBraceLayout:
68
+ Enabled: false
69
+
70
+ Layout/MultilineOperationIndentation:
71
+ Enabled: false
72
+
73
+ Layout/ParameterAlignment:
74
+ Enabled: false
75
+
76
+ Layout/TrailingEmptyLines:
77
+ Enabled: false
78
+
79
+ Layout/TrailingWhitespace:
80
+ Enabled: false
81
+
82
+ Lint/UselessAssignment:
83
+ Enabled: false
84
+
85
+ Lint/Void:
86
+ Enabled: false
87
+
88
+ Metrics/BlockLength:
89
+ Enabled: false
90
+
91
+ Metrics/BlockNesting:
92
+ Enabled: false
93
+
94
+ Naming/FileName:
95
+ Enabled: false
96
+
97
+ Style/FrozenStringLiteralComment:
98
+ Enabled: false
99
+
100
+ Style/IdenticalConditionalBranches:
101
+ Enabled: false
102
+
103
+ Style/IfUnlessModifier:
104
+ Enabled: false
105
+
106
+ Style/Next:
107
+ Enabled: false
108
+
109
+ Style/RescueModifier:
110
+ Enabled: false
111
+
112
+ Style/WhileUntilDo:
113
+ Enabled: false
114
+
115
+ Style/WhileUntilModifier:
116
+ Enabled: false
data/erbcop.gemspec ADDED
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/erbcop/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'erbcop'
7
+ spec.version = Erbcop::VERSION
8
+ spec.authors = ['Ryo Nakamura']
9
+ spec.email = ['r7kamura@gmail.com']
10
+
11
+ spec.summary = 'RuboCop runner for ERB template.'
12
+ spec.homepage = 'https://github.com/r7kamura/erbcop'
13
+ spec.license = 'MIT'
14
+ spec.required_ruby_version = '>= 2.6.0'
15
+
16
+ spec.metadata['homepage_uri'] = spec.homepage
17
+ spec.metadata['source_code_uri'] = spec.homepage
18
+ spec.metadata['changelog_uri'] = "#{spec.homepage}/blob/main/CHANGELOG.md"
19
+
20
+ # Specify which files should be added to the gem when it is released.
21
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
22
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
23
+ `git ls-files -z`.split("\x0").reject do |f|
24
+ (f == __FILE__) || f.match(%r{\A(?:(?:bin|test|spec|features)/|\.(?:git|travis|circleci)|appveyor)})
25
+ end
26
+ end
27
+ spec.bindir = 'exe'
28
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
29
+ spec.require_paths = ['lib']
30
+ spec.metadata['rubygems_mfa_required'] = 'true'
31
+
32
+ spec.add_dependency 'better_html'
33
+ spec.add_dependency 'rainbow'
34
+ spec.add_dependency 'rubocop', '>= 0.87'
35
+ end
data/exe/erbcop ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ $LOAD_PATH.unshift File.expand_path('../lib', __dir__)
5
+ require 'erbcop'
6
+
7
+ Erbcop::Cli.new(ARGV).call
data/lib/erbcop/cli.rb ADDED
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rainbow'
4
+ require 'rubocop'
5
+
6
+ module Erbcop
7
+ class Cli
8
+ def initialize(argv)
9
+ @argv = argv.dup
10
+ end
11
+
12
+ def call
13
+ options = parse!
14
+ formatter = ::RuboCop::Formatter::ProgressFormatter.new($stdout, color: options[:color])
15
+ rubocop_config = RuboCopConfigGenerator.new(additional_config_file_path: options[:additional_config_file_path]).call
16
+ file_paths = PathFinder.new(patterns: @argv).call
17
+
18
+ offenses = Runner.new(
19
+ auto_correct: options[:auto_correct],
20
+ file_paths: file_paths,
21
+ formatter: formatter,
22
+ rubocop_config: rubocop_config
23
+ ).call
24
+
25
+ exit(offenses.empty? ? 0 : 1)
26
+ end
27
+
28
+ private
29
+
30
+ # @return [Hash]
31
+ def parse!
32
+ options = {}
33
+ parser = ::OptionParser.new
34
+ parser.banner = 'Usage: erbcop [options] [file1, file2, ...]'
35
+ parser.version = VERSION
36
+ parser.on('-a', '--auto-correct', 'Auto-correct offenses.') do
37
+ options[:auto_correct] = true
38
+ end
39
+ parser.on('-c', '--config=', 'Specify configuration file. (default: .erbcop.yml or .rubocop.yml)') do |file_path|
40
+ options[:additional_config_file_path] = file_path
41
+ end
42
+ parser.on('--[no-]color', 'Force color output on or off.') do |value|
43
+ options[:color] = value
44
+ end
45
+ parser.parse!(@argv)
46
+ options
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'parser'
4
+ require 'rubocop/cop/legacy/corrector'
5
+
6
+ module Erbcop
7
+ # Apply auto-corrections to Erb file.
8
+ class ErbCorrector
9
+ # @param [String] file_path
10
+ # @param [Array<Erbcop::Offense>] offenses
11
+ # @param [String] source
12
+ def initialize(file_path:, offenses:, source:)
13
+ @file_path = file_path
14
+ @offenses = offenses
15
+ @source = source
16
+ end
17
+
18
+ # @return [String] Rewritten Erb code.
19
+ def call
20
+ ::RuboCop::Cop::Legacy::Corrector.new(source_buffer, corrections).rewrite
21
+ end
22
+
23
+ private
24
+
25
+ # @return [Array<Proc>]
26
+ def corrections
27
+ @offenses.select(&:corrector).map do |offense|
28
+ lambda do |corrector|
29
+ corrector.import!(offense.corrector, offset: offense.offset)
30
+ end
31
+ end
32
+ end
33
+
34
+ # @return [Parser::Source::Buffer]
35
+ def source_buffer
36
+ ::Parser::Source::Buffer.new(
37
+ @file_path,
38
+ source: @source
39
+ )
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Erbcop
4
+ # Collect RuboCop offenses from Erb code.
5
+ class ErbOffenseCollector
6
+ # @param [Boolean] auto_correct
7
+ # @param [String] file_path Erb file path
8
+ # @param [RuboCop::Config] rubocop_config
9
+ # @param [String] source Erb code
10
+ def initialize(auto_correct:, file_path:, rubocop_config:, source:)
11
+ @auto_correct = auto_correct
12
+ @file_path = file_path
13
+ @rubocop_config = rubocop_config
14
+ @source = source
15
+ end
16
+
17
+ # @return [Array<Erbcop::Offense>]
18
+ def call
19
+ snippets.flat_map do |snippet|
20
+ RubyOffenseCollector.new(
21
+ auto_correct: @auto_correct,
22
+ file_path: @file_path,
23
+ rubocop_config: @rubocop_config,
24
+ source: snippet[:code]
25
+ ).call.map do |rubocop_offense|
26
+ Offense.new(
27
+ file_path: @file_path,
28
+ offset: snippet[:offset],
29
+ rubocop_offense: rubocop_offense,
30
+ source: @source
31
+ )
32
+ end
33
+ end
34
+ end
35
+
36
+ private
37
+
38
+ # @return [Array<Hash>]
39
+ def snippets
40
+ RubyExtractor.new(
41
+ file_path: @file_path,
42
+ source: @source
43
+ ).call
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'forwardable'
4
+
5
+ require 'parser'
6
+ require 'rubocop'
7
+
8
+ module Erbcop
9
+ class Offense
10
+ extend ::Forwardable
11
+
12
+ # @return [String]
13
+ attr_reader :file_path
14
+
15
+ # @return [Integer]
16
+ attr_reader :offset
17
+
18
+ delegate(
19
+ %i[
20
+ column
21
+ column_length
22
+ correctable?
23
+ corrected_with_todo?
24
+ corrected?
25
+ corrector
26
+ highlighted_area
27
+ line
28
+ message
29
+ real_column
30
+ severity
31
+ ] => :rubocop_offense_with_real_location
32
+ )
33
+
34
+ # @param [Integer] offset
35
+ # @param [RuboCop::Cop::Offense] rubocop_offense
36
+ # @param [String] source Erb code.
37
+ def initialize(file_path:, offset:, rubocop_offense:, source:)
38
+ @file_path = file_path
39
+ @offset = offset
40
+ @rubocop_offense = rubocop_offense
41
+ @source = source
42
+ end
43
+
44
+ # @return [Parser::Source::Range]
45
+ def location
46
+ @location ||= ::Parser::Source::Range.new(
47
+ buffer,
48
+ @rubocop_offense.location.begin_pos + @offset,
49
+ @rubocop_offense.location.end_pos + @offset
50
+ )
51
+ end
52
+
53
+ private
54
+
55
+ # @return [Parser::Source::Buffer]
56
+ def buffer
57
+ ::Parser::Source::Buffer.new(
58
+ file_path,
59
+ source: @source
60
+ )
61
+ end
62
+
63
+ # @return [RuboCop::Cop::Offense]
64
+ def rubocop_offense_with_real_location
65
+ ::RuboCop::Cop::Offense.new(
66
+ @rubocop_offense.severity.name,
67
+ location,
68
+ @rubocop_offense.message,
69
+ @rubocop_offense.cop_name,
70
+ @rubocop_offense.status,
71
+ @rubocop_offense.corrector
72
+ )
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'pathname'
4
+
5
+ module Erbcop
6
+ # Collect file paths from given path patterns.
7
+ class PathFinder
8
+ DEFAULT_PATH_PATTERNS = %w[
9
+ **/*.erb
10
+ ].freeze
11
+
12
+ # @param [Array<String>] patterns Patterns normally given as CLI arguments (e.g. `["app/views/**/*.html.erb"]`).
13
+ def initialize(patterns:)
14
+ @patterns = patterns
15
+ end
16
+
17
+ # @return [Array<String>]
18
+ def call
19
+ patterns.flat_map do |pattern|
20
+ ::Pathname.glob(pattern).select(&:file?).map(&:to_s)
21
+ end.uniq.sort
22
+ end
23
+
24
+ private
25
+
26
+ # @return [Array<String>]
27
+ def patterns
28
+ if @patterns.empty?
29
+ DEFAULT_PATH_PATTERNS
30
+ else
31
+ @patterns
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rubocop'
4
+
5
+ module Erbcop
6
+ class RuboCopConfigGenerator
7
+ DEFAULT_ADDITIONAL_CONFIG_PATH1 = '.erbcop.yml'
8
+ DEFAULT_ADDITIONAL_CONFIG_PATH2 = '.rubocop.yml'
9
+
10
+ # @param [String] additional_config_file_path
11
+ def initialize(additional_config_file_path: nil)
12
+ @additional_config_file_path = additional_config_file_path
13
+ end
14
+
15
+ # @return [RuboCop::Config]
16
+ def call
17
+ ::RuboCop::ConfigLoader.merge_with_default(merged_config, loaded_path)
18
+ end
19
+
20
+ private
21
+
22
+ # @return [String]
23
+ def loaded_path
24
+ @additional_config_file_path || erbcop_default_config_file_path
25
+ end
26
+
27
+ # @return [RuboCop::Config]
28
+ def merged_config
29
+ ::RuboCop::Config.create(merged_config_hash, loaded_path)
30
+ end
31
+
32
+ # @return [Hash]
33
+ def merged_config_hash
34
+ result = erbcop_default_config
35
+ result = ::RuboCop::ConfigLoader.merge(result, additional_config) if additional_config
36
+ result
37
+ end
38
+
39
+ # @return [RuboCop::Config, nil]
40
+ def additional_config
41
+ if instance_variable_defined?(:@additional_config)
42
+ @additional_config
43
+ else
44
+ @additional_config = \
45
+ if @additional_config_file_path
46
+ ::RuboCop::ConfigLoader.load_file(@additional_config_file_path)
47
+ elsif ::File.exist?(DEFAULT_ADDITIONAL_CONFIG_PATH1)
48
+ ::RuboCop::ConfigLoader.load_file(DEFAULT_ADDITIONAL_CONFIG_PATH1)
49
+ elsif ::File.exist?(DEFAULT_ADDITIONAL_CONFIG_PATH2)
50
+ ::RuboCop::ConfigLoader.load_file(DEFAULT_ADDITIONAL_CONFIG_PATH2)
51
+ end
52
+ end
53
+ end
54
+
55
+ # @return [RuboCop::Config]
56
+ def erbcop_default_config
57
+ ::RuboCop::ConfigLoader.load_file(erbcop_default_config_file_path)
58
+ end
59
+
60
+ # @return [String]
61
+ def erbcop_default_config_file_path
62
+ @erbcop_default_config_file_path ||= ::File.expand_path('../../default.yml', __dir__)
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,93 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Erbcop
4
+ # Remove unnecessary part (e.g. `if`, `unless`, `do`, ...) from Ruby code.
5
+ class RubyClipper
6
+ # @param [String] code
7
+ def initialize(code)
8
+ @code = code
9
+ end
10
+
11
+ # @return [Hash]
12
+ def call
13
+ [
14
+ PrecedingKeywordRemover,
15
+ TrailingDoRemover
16
+ ].each_with_object(
17
+ code: @code,
18
+ offset: 0
19
+ ) do |klass, object|
20
+ result = klass.new(object[:code]).call
21
+ object[:code] = result[:code]
22
+ object[:offset] += result[:offset]
23
+ end
24
+ end
25
+
26
+ class PrecedingKeywordRemover
27
+ REGEXP = /
28
+ \A
29
+ (?:
30
+ begin
31
+ | case
32
+ | else
33
+ | elsif
34
+ | ensure
35
+ | if
36
+ | rescue
37
+ | unless
38
+ | until
39
+ | when
40
+ | while
41
+ | for[ \t]+\w+[ \t]+in
42
+ )
43
+ [ \t]
44
+ /x.freeze
45
+
46
+ # @param [String] code
47
+ def initialize(code)
48
+ @code = code
49
+ end
50
+
51
+ # @return [Hash]
52
+ def call
53
+ data = @code.match(REGEXP)
54
+ if data
55
+ offset = data[0].length
56
+ {
57
+ code: @code[offset..],
58
+ offset: offset
59
+ }
60
+ else
61
+ {
62
+ code: @code,
63
+ offset: 0
64
+ }
65
+ end
66
+ end
67
+ end
68
+
69
+ class TrailingDoRemover
70
+ REGEXP = /
71
+ [ \t]
72
+ do
73
+ [ \t]*
74
+ (\|[^|]*\|)?
75
+ [ \t]*
76
+ \Z
77
+ /x.freeze
78
+
79
+ # @param [String] code
80
+ def initialize(code)
81
+ @code = code
82
+ end
83
+
84
+ # @return [Hash]
85
+ def call
86
+ {
87
+ code: @code.sub(REGEXP, ''),
88
+ offset: 0
89
+ }
90
+ end
91
+ end
92
+ end
93
+ end
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'better_html'
4
+ require 'better_html/parser'
5
+
6
+ module Erbcop
7
+ # Extract Ruby codes from Erb source.
8
+ class RubyExtractor
9
+ # @param [String, nil] file_path
10
+ # @param [String] source
11
+ def initialize(file_path:, source:)
12
+ @file_path = file_path
13
+ @source = source
14
+ end
15
+
16
+ # @return [Array<Hash>]
17
+ def call
18
+ nodes.map do |node|
19
+ snippet = node.children.first
20
+ clipped = RubyClipper.new(snippet).call
21
+ {
22
+ code: clipped[:code],
23
+ offset: node.location.begin_pos + clipped[:offset]
24
+ }
25
+ end
26
+ end
27
+
28
+ private
29
+
30
+ # @return [Enumerator<BetterHtml::AST::Node>]
31
+ def nodes
32
+ ::BetterHtml::Parser.new(
33
+ ::Parser::Source::Buffer.new(
34
+ @file_path,
35
+ source: @source
36
+ ),
37
+ template_language: :html
38
+ ).ast.descendants(:code)
39
+ end
40
+
41
+ # @return [Array<Array<Integer>>]
42
+ def ranges
43
+ result = []
44
+ traverse(ast) do |begin_, end_|
45
+ result << [begin_, end_]
46
+ end
47
+ result
48
+ end
49
+
50
+ def traverse(node, &block)
51
+ return unless node.instance_of?(::Array)
52
+
53
+ if node[0] == :erbi && node[1] == :position
54
+ block.call(node[2], node[3])
55
+ else
56
+ node.each do |element|
57
+ traverse(element, &block)
58
+ end
59
+ end
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rubocop'
4
+
5
+ module Erbcop
6
+ # Collect RuboCop offenses from Ruby code.
7
+ class RubyOffenseCollector
8
+ # @param [Boolean] auto_correct
9
+ # @param [String] file_path
10
+ # @param [RuboCop::Config] rubocop_config
11
+ # @param [String] source
12
+ def initialize(auto_correct:, file_path:, rubocop_config:, source:)
13
+ @auto_correct = auto_correct
14
+ @file_path = file_path
15
+ @rubocop_config = rubocop_config
16
+ @source = source
17
+ end
18
+
19
+ # @return [Array<RuboCop::Cop::Offense>]
20
+ def call
21
+ # Skip if invalid syntax Ruby code is given. (e.g. "- if a?")
22
+ return [] unless rubocop_processed_source.valid_syntax?
23
+
24
+ rubocop_team.investigate(rubocop_processed_source).offenses.reject(&:disabled?)
25
+ end
26
+
27
+ private
28
+
29
+ # @return [RuboCop::ProcessedSource]
30
+ def rubocop_processed_source
31
+ @rubocop_processed_source ||= ::RuboCop::ProcessedSource.new(
32
+ @source,
33
+ @rubocop_config.target_ruby_version,
34
+ @file_path
35
+ )
36
+ end
37
+
38
+ # @return [RuboCop::Cop::Team]
39
+ def rubocop_team
40
+ ::RuboCop::Cop::Team.new(
41
+ ::RuboCop::Cop::Registry.new(::RuboCop::Cop::Cop.all),
42
+ @rubocop_config,
43
+ auto_correct: @auto_correct,
44
+ display_cop_names: true,
45
+ extra_details: true,
46
+ stdin: ''
47
+ )
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,115 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Erbcop
4
+ # Run investigation and auto-correcttion.
5
+ class Runner
6
+ # @param [Boolean] auto_correct
7
+ # @param [Array<String>] file_paths
8
+ # @param [Object] formatter
9
+ # @param [RuboCop::Config] rubocop_config
10
+ def initialize(
11
+ auto_correct:,
12
+ file_paths:,
13
+ formatter:,
14
+ rubocop_config:
15
+ )
16
+ @auto_correct = auto_correct
17
+ @file_paths = file_paths
18
+ @formatter = formatter
19
+ @rubocop_config = rubocop_config
20
+ end
21
+
22
+ # @return [Array<RuboCop::Cop::Offense>]
23
+ def call
24
+ on_started
25
+ offenses = investigate_and_correct
26
+ on_finished
27
+ offenses
28
+ end
29
+
30
+ private
31
+
32
+ # @param [String] file_path
33
+ # @param [Array<Erbcop::Offense>] offenses
34
+ # @param [String] source
35
+ def correct(file_path:, offenses:, source:)
36
+ rewritten_source = ErbCorrector.new(
37
+ file_path: file_path,
38
+ offenses: offenses,
39
+ source: source
40
+ ).call
41
+ ::File.write(file_path, rewritten_source)
42
+ end
43
+
44
+ # @param [Boolean] auto_correct
45
+ # @param [String] file_path
46
+ # @param [String] rubocop_config
47
+ # @param [String] source
48
+ # @return [Array<Erbcop::Offense>]
49
+ def investigate(auto_correct:, file_path:, rubocop_config:, source:)
50
+ ErbOffenseCollector.new(
51
+ auto_correct: auto_correct,
52
+ file_path: file_path,
53
+ rubocop_config: rubocop_config,
54
+ source: source
55
+ ).call
56
+ end
57
+
58
+ # @return [Array<RuboCop::Cop::Offense>]
59
+ def investigate_and_correct
60
+ @file_paths.flat_map do |file_path|
61
+ offenses_per_file = []
62
+ max_trials_count.times do
63
+ on_file_started(file_path)
64
+ source = ::File.read(file_path)
65
+ offenses = investigate(
66
+ auto_correct: @auto_correct,
67
+ file_path: file_path,
68
+ rubocop_config: @rubocop_config,
69
+ source: source
70
+ )
71
+ offenses_per_file += offenses
72
+ break if offenses.empty?
73
+
74
+ next unless @auto_correct
75
+
76
+ correct(
77
+ file_path: file_path,
78
+ offenses: offenses,
79
+ source: source
80
+ )
81
+ end
82
+ on_file_finished(file_path, offenses_per_file)
83
+ offenses_per_file
84
+ end
85
+ end
86
+
87
+ # @return [Integer]
88
+ def max_trials_count
89
+ if @auto_correct
90
+ 7 # What a heuristic number.
91
+ else
92
+ 1
93
+ end
94
+ end
95
+
96
+ def on_started
97
+ @formatter.started(@file_paths)
98
+ end
99
+
100
+ # @param [String] file_path
101
+ def on_file_started(file_path)
102
+ @formatter.file_started(file_path, {})
103
+ end
104
+
105
+ # @param [String] file_path
106
+ # @param [Array<RuboCop::Cop::Offenses]
107
+ def on_file_finished(file_path, offenses)
108
+ @formatter.file_finished(file_path, offenses)
109
+ end
110
+
111
+ def on_finished
112
+ @formatter.finished(@file_paths)
113
+ end
114
+ end
115
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Erbcop
4
+ VERSION = '0.1.0'
5
+ end
data/lib/erbcop.rb ADDED
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'erbcop/version'
4
+
5
+ module Erbcop
6
+ autoload :Cli, 'erbcop/cli'
7
+ autoload :Offense, 'erbcop/offense'
8
+ autoload :PathFinder, 'erbcop/path_finder'
9
+ autoload :RuboCopConfigGenerator, 'erbcop/rubo_cop_config_generator'
10
+ autoload :RubyClipper, 'erbcop/ruby_clipper'
11
+ autoload :RubyExtractor, 'erbcop/ruby_extractor'
12
+ autoload :RubyOffenseCollector, 'erbcop/ruby_offense_collector'
13
+ autoload :Runner, 'erbcop/runner'
14
+ autoload :ErbCorrector, 'erbcop/erb_corrector'
15
+ autoload :ErbOffenseCollector, 'erbcop/erb_offense_collector'
16
+ end
metadata ADDED
@@ -0,0 +1,114 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: erbcop
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Ryo Nakamura
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2022-01-14 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: better_html
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rainbow
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rubocop
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0.87'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0.87'
55
+ description:
56
+ email:
57
+ - r7kamura@gmail.com
58
+ executables:
59
+ - erbcop
60
+ extensions: []
61
+ extra_rdoc_files: []
62
+ files:
63
+ - ".rspec"
64
+ - ".rubocop.yml"
65
+ - CHANGELOG.md
66
+ - CODE_OF_CONDUCT.md
67
+ - Gemfile
68
+ - Gemfile.lock
69
+ - LICENSE.txt
70
+ - README.md
71
+ - Rakefile
72
+ - default.yml
73
+ - erbcop.gemspec
74
+ - exe/erbcop
75
+ - lib/erbcop.rb
76
+ - lib/erbcop/cli.rb
77
+ - lib/erbcop/erb_corrector.rb
78
+ - lib/erbcop/erb_offense_collector.rb
79
+ - lib/erbcop/offense.rb
80
+ - lib/erbcop/path_finder.rb
81
+ - lib/erbcop/rubo_cop_config_generator.rb
82
+ - lib/erbcop/ruby_clipper.rb
83
+ - lib/erbcop/ruby_extractor.rb
84
+ - lib/erbcop/ruby_offense_collector.rb
85
+ - lib/erbcop/runner.rb
86
+ - lib/erbcop/version.rb
87
+ homepage: https://github.com/r7kamura/erbcop
88
+ licenses:
89
+ - MIT
90
+ metadata:
91
+ homepage_uri: https://github.com/r7kamura/erbcop
92
+ source_code_uri: https://github.com/r7kamura/erbcop
93
+ changelog_uri: https://github.com/r7kamura/erbcop/blob/main/CHANGELOG.md
94
+ rubygems_mfa_required: 'true'
95
+ post_install_message:
96
+ rdoc_options: []
97
+ require_paths:
98
+ - lib
99
+ required_ruby_version: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: 2.6.0
104
+ required_rubygems_version: !ruby/object:Gem::Requirement
105
+ requirements:
106
+ - - ">="
107
+ - !ruby/object:Gem::Version
108
+ version: '0'
109
+ requirements: []
110
+ rubygems_version: 3.1.4
111
+ signing_key:
112
+ specification_version: 4
113
+ summary: RuboCop runner for ERB template.
114
+ test_files: []