templatecop 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: 7b3638b72df80a798b42389125fa1b67085a6c1ddbae87ac431b9fa2f4088ab7
4
+ data.tar.gz: d6c5635d979fe7734f412259fc0dc2761e048de9afe76c271b6ac79452af6ff4
5
+ SHA512:
6
+ metadata.gz: e4616cc878daf91433567903956aab4f6a96f5a3f33e38284ec1f4d9754632a59a841011eec804e88abb5281a16ac6651cf84cad91e9d33f2d0ff0195120bcbf
7
+ data.tar.gz: 8624e290b2f2f42304210ef0a71cf5d15ed57bf01ee1e17a4e131012d52d40f8078f56080d074ebbc668827a91d9095844de42d9be434289bd8a46d34db500dd
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,7 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ ## 0.1.0 - 2022-01-15
6
+
7
+ - Initial release.
@@ -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 templatecop.gemspec
6
+ gemspec
7
+
8
+ gem 'rake'
9
+ gem 'rspec'
10
+ gem 'rubocop'
11
+ gem 'rubocop-rspec'
data/Gemfile.lock ADDED
@@ -0,0 +1,60 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ templatecop (0.1.0)
5
+ parser
6
+ rubocop (>= 0.87)
7
+
8
+ GEM
9
+ remote: https://rubygems.org/
10
+ specs:
11
+ ast (2.4.2)
12
+ diff-lcs (1.5.0)
13
+ parallel (1.21.0)
14
+ parser (3.1.0.0)
15
+ ast (~> 2.4.1)
16
+ rainbow (3.1.1)
17
+ rake (13.0.6)
18
+ regexp_parser (2.2.0)
19
+ rexml (3.2.5)
20
+ rspec (3.10.0)
21
+ rspec-core (~> 3.10.0)
22
+ rspec-expectations (~> 3.10.0)
23
+ rspec-mocks (~> 3.10.0)
24
+ rspec-core (3.10.1)
25
+ rspec-support (~> 3.10.0)
26
+ rspec-expectations (3.10.2)
27
+ diff-lcs (>= 1.2.0, < 2.0)
28
+ rspec-support (~> 3.10.0)
29
+ rspec-mocks (3.10.2)
30
+ diff-lcs (>= 1.2.0, < 2.0)
31
+ rspec-support (~> 3.10.0)
32
+ rspec-support (3.10.3)
33
+ rubocop (1.24.1)
34
+ parallel (~> 1.10)
35
+ parser (>= 3.0.0.0)
36
+ rainbow (>= 2.2.2, < 4.0)
37
+ regexp_parser (>= 1.8, < 3.0)
38
+ rexml
39
+ rubocop-ast (>= 1.15.1, < 2.0)
40
+ ruby-progressbar (~> 1.7)
41
+ unicode-display_width (>= 1.4.0, < 3.0)
42
+ rubocop-ast (1.15.1)
43
+ parser (>= 3.0.1.1)
44
+ rubocop-rspec (2.7.0)
45
+ rubocop (~> 1.19)
46
+ ruby-progressbar (1.11.0)
47
+ unicode-display_width (2.1.0)
48
+
49
+ PLATFORMS
50
+ x86_64-linux
51
+
52
+ DEPENDENCIES
53
+ rake
54
+ rspec
55
+ rubocop
56
+ rubocop-rspec
57
+ templatecop!
58
+
59
+ BUNDLED WITH
60
+ 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,27 @@
1
+ # Templatecop
2
+
3
+ [RuboCop](https://github.com/rubocop/rubocop) runner framework for template language.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'templatecop'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ ```
16
+ bundle install
17
+ ```
18
+
19
+ Or install it yourself as:
20
+
21
+ ```
22
+ gem install templatecop
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ TBD.
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]
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'optparse'
4
+ require 'rubocop'
5
+
6
+ module Templatecop
7
+ # Call this from your executable.
8
+ # @example
9
+ # Templatecop.call(
10
+ # default_configuration_path: File.expand_path('../default.yml', __dir__),
11
+ # implicit_configuration_paths: %w[.slimcop.yml .rubocop.yml],
12
+ # executable_name: 'slimcop',
13
+ # ruby_extractor: Slimcop::RubyExtractor.new
14
+ # )
15
+ class Cli
16
+ class << self
17
+ # @param [Array<String>] argv
18
+ # @param [String] default_configuration_path (e.g. "default.yml")
19
+ # @param [Array<String>] default_path_patterns
20
+ # @param [String] executable_name (e.g. "slimcop")
21
+ # @param [Array<String>] implicit_configuration_paths
22
+ # @param [#call] ruby_extractor An object that converts template code into Ruby codes.
23
+ def call(
24
+ executable_name:,
25
+ ruby_extractor:,
26
+ implicit_configuration_paths:,
27
+ argv: ::ARGV.dup,
28
+ default_configuration_path: nil,
29
+ default_path_patterns: []
30
+ )
31
+ new(
32
+ argv: argv,
33
+ default_configuration_path: default_configuration_path,
34
+ default_path_patterns: default_path_patterns,
35
+ executable_name: executable_name,
36
+ implicit_configuration_paths: implicit_configuration_paths,
37
+ ruby_extractor: ruby_extractor
38
+ ).call
39
+ end
40
+ end
41
+
42
+ def initialize(
43
+ argv:,
44
+ default_configuration_path:,
45
+ default_path_patterns:,
46
+ executable_name:,
47
+ implicit_configuration_paths:,
48
+ ruby_extractor:
49
+ )
50
+ @argv = argv
51
+ @default_configuration_path = default_configuration_path
52
+ @default_path_patterns = default_path_patterns
53
+ @executable_name = executable_name
54
+ @ruby_extractor = ruby_extractor
55
+ @implicit_configuration_paths = implicit_configuration_paths
56
+ end
57
+
58
+ def call
59
+ options = parse_options!
60
+ formatter = ::RuboCop::Formatter::ProgressFormatter.new($stdout, color: options[:color])
61
+ rubocop_config = RuboCopConfigGenerator.new(
62
+ default_configuration_path: @default_configuration_path,
63
+ forced_configuration_path: options[:forced_configuration_path],
64
+ implicit_configuration_paths: @implicit_configuration_paths
65
+ ).call
66
+ file_paths = PathFinder.new(
67
+ default_patterns: @default_path_patterns,
68
+ patterns: @argv
69
+ ).call
70
+
71
+ offenses = Runner.new(
72
+ auto_correct: options[:auto_correct],
73
+ file_paths: file_paths,
74
+ formatter: formatter,
75
+ rubocop_config: rubocop_config,
76
+ ruby_extractor: @ruby_extractor
77
+ ).call
78
+
79
+ exit(offenses.empty? ? 0 : 1)
80
+ end
81
+
82
+ private
83
+
84
+ # @return [Hash]
85
+ def parse_options!
86
+ options = {}
87
+ parser = ::OptionParser.new
88
+ parser.banner = "Usage: #{@executable_name} [options] [file1, file2, ...]"
89
+ parser.version = VERSION
90
+ parser.on('-a', '--auto-correct', 'Auto-correct offenses.') do
91
+ options[:auto_correct] = true
92
+ end
93
+ parser.on('-c', '--config=', "Specify configuration file. (default: #{@default_configuration_path} or .rubocop.yml)") do |file_path|
94
+ options[:forced_configuration_path] = file_path
95
+ end
96
+ parser.on('--[no-]color', 'Force color output on or off.') do |value|
97
+ options[:color] = value
98
+ end
99
+ parser.parse!(@argv)
100
+ options
101
+ end
102
+ end
103
+ end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'forwardable'
4
+
5
+ require 'parser'
6
+ require 'rubocop'
7
+
8
+ module Templatecop
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 Template 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,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'pathname'
4
+
5
+ module Templatecop
6
+ # Collect file paths from given path patterns.
7
+ class PathFinder
8
+ # @param [Array<String>] default_patterns
9
+ # @param [Array<String>] patterns Patterns normally given as CLI arguments (e.g. `["app/views/**/*.html.template"]`).
10
+ def initialize(
11
+ default_patterns:,
12
+ patterns:
13
+ )
14
+ @default_patterns = default_patterns
15
+ @patterns = patterns
16
+ end
17
+
18
+ # @return [Array<String>]
19
+ def call
20
+ patterns.flat_map do |pattern|
21
+ ::Pathname.glob(pattern).select(&:file?).map(&:to_s)
22
+ end.uniq.sort
23
+ end
24
+
25
+ private
26
+
27
+ # @return [Array<String>]
28
+ def patterns
29
+ if @patterns.empty?
30
+ @default_patterns
31
+ else
32
+ @patterns
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rubocop'
4
+
5
+ module Templatecop
6
+ # Generate RuboCop::Config.
7
+ class RuboCopConfigGenerator
8
+ # @param [String] default_configuration_path
9
+ # @param [String, nil] forced_configuration_path
10
+ # @param [Array<String>] implicit_configuration_paths
11
+ def initialize(
12
+ default_configuration_path:,
13
+ forced_configuration_path:,
14
+ implicit_configuration_paths:
15
+ )
16
+ @default_configuration_path = default_configuration_path
17
+ @forced_configuration_path = forced_configuration_path
18
+ @implicit_configuration_paths = implicit_configuration_paths
19
+ end
20
+
21
+ # @return [RuboCop::Config]
22
+ def call
23
+ ::RuboCop::ConfigLoader.merge_with_default(merged_config, loaded_path)
24
+ end
25
+
26
+ private
27
+
28
+ # @return [String]
29
+ def loaded_path
30
+ @forced_configuration_path || implicit_configuration_path || @default_configuration_path
31
+ end
32
+
33
+ # @return [RuboCop::Config]
34
+ def merged_config
35
+ ::RuboCop::Config.create(merged_config_hash, loaded_path)
36
+ end
37
+
38
+ # @return [Hash]
39
+ def merged_config_hash
40
+ result = default_config
41
+ result = ::RuboCop::ConfigLoader.merge(result, user_config) if user_config
42
+ result
43
+ end
44
+
45
+ # @return [RuboCop::Config, nil]
46
+ def user_config
47
+ if instance_variable_defined?(:@user_config)
48
+ @user_config
49
+ else
50
+ @user_config = \
51
+ if @forced_configuration_path
52
+ ::RuboCop::ConfigLoader.load_file(@forced_configuration_path)
53
+ elsif (path = implicit_configuration_path)
54
+ ::RuboCop::ConfigLoader.load_file(path)
55
+ end
56
+ end
57
+ end
58
+
59
+ # @return [RuboCop::Config]
60
+ def default_config
61
+ ::RuboCop::ConfigLoader.load_file(@default_configuration_path)
62
+ end
63
+
64
+ # @return [String, nil]
65
+ def implicit_configuration_path
66
+ if instance_variable_defined?(:@implicit_configuration_path)
67
+ @implicit_configuration_path
68
+ else
69
+ @implicit_configuration_path = @implicit_configuration_paths.find do |path|
70
+ ::File.exist?(path)
71
+ end
72
+ end
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,93 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Templatecop
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,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rubocop'
4
+
5
+ module Templatecop
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,119 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Templatecop
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
+ # @param [#call] ruby_extractor
11
+ def initialize(
12
+ auto_correct:,
13
+ file_paths:,
14
+ formatter:,
15
+ rubocop_config:,
16
+ ruby_extractor:
17
+ )
18
+ @auto_correct = auto_correct
19
+ @file_paths = file_paths
20
+ @formatter = formatter
21
+ @rubocop_config = rubocop_config
22
+ @ruby_extractor = ruby_extractor
23
+ end
24
+
25
+ # @return [Array<RuboCop::Cop::Offense>]
26
+ def call
27
+ on_started
28
+ offenses = investigate_and_correct
29
+ on_finished
30
+ offenses
31
+ end
32
+
33
+ private
34
+
35
+ # @param [String] file_path
36
+ # @param [Array<Templatecop::Offense>] offenses
37
+ # @param [String] source
38
+ def correct(file_path:, offenses:, source:)
39
+ rewritten_source = TemplateCorrector.new(
40
+ file_path: file_path,
41
+ offenses: offenses,
42
+ source: source
43
+ ).call
44
+ ::File.write(file_path, rewritten_source)
45
+ end
46
+
47
+ # @param [Boolean] auto_correct
48
+ # @param [String] file_path
49
+ # @param [String] rubocop_config
50
+ # @param [String] source
51
+ # @return [Array<Templatecop::Offense>]
52
+ def investigate(auto_correct:, file_path:, rubocop_config:, source:)
53
+ TemplateOffenseCollector.new(
54
+ auto_correct: auto_correct,
55
+ file_path: file_path,
56
+ rubocop_config: rubocop_config,
57
+ ruby_extractor: @ruby_extractor,
58
+ source: source
59
+ ).call
60
+ end
61
+
62
+ # @return [Array<RuboCop::Cop::Offense>]
63
+ def investigate_and_correct
64
+ @file_paths.flat_map do |file_path|
65
+ offenses_per_file = []
66
+ max_trials_count.times do
67
+ on_file_started(file_path)
68
+ source = ::File.read(file_path)
69
+ offenses = investigate(
70
+ auto_correct: @auto_correct,
71
+ file_path: file_path,
72
+ rubocop_config: @rubocop_config,
73
+ source: source
74
+ )
75
+ offenses_per_file += offenses
76
+ break if offenses.empty?
77
+
78
+ next unless @auto_correct
79
+
80
+ correct(
81
+ file_path: file_path,
82
+ offenses: offenses,
83
+ source: source
84
+ )
85
+ end
86
+ on_file_finished(file_path, offenses_per_file)
87
+ offenses_per_file
88
+ end
89
+ end
90
+
91
+ # @return [Integer]
92
+ def max_trials_count
93
+ if @auto_correct
94
+ 7 # What a heuristic number.
95
+ else
96
+ 1
97
+ end
98
+ end
99
+
100
+ def on_started
101
+ @formatter.started(@file_paths)
102
+ end
103
+
104
+ # @param [String] file_path
105
+ def on_file_started(file_path)
106
+ @formatter.file_started(file_path, {})
107
+ end
108
+
109
+ # @param [String] file_path
110
+ # @param [Array<RuboCop::Cop::Offenses]
111
+ def on_file_finished(file_path, offenses)
112
+ @formatter.file_finished(file_path, offenses)
113
+ end
114
+
115
+ def on_finished
116
+ @formatter.finished(@file_paths)
117
+ end
118
+ end
119
+ end
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'parser'
4
+ require 'rubocop/cop/legacy/corrector'
5
+
6
+ module Templatecop
7
+ # Apply auto-corrections to Template file.
8
+ class TemplateCorrector
9
+ # @param [String] file_path
10
+ # @param [Array<Templatecop::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 Template 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,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Templatecop
4
+ # Collect RuboCop offenses from Template code.
5
+ class TemplateOffenseCollector
6
+ # @param [Boolean] auto_correct
7
+ # @param [String] file_path Template file path
8
+ # @param [RuboCop::Config] rubocop_config
9
+ # @param [#call] ruby_extractor
10
+ # @param [String] source Template code
11
+ def initialize(
12
+ auto_correct:,
13
+ file_path:,
14
+ rubocop_config:,
15
+ ruby_extractor:,
16
+ source:
17
+ )
18
+ @auto_correct = auto_correct
19
+ @file_path = file_path
20
+ @rubocop_config = rubocop_config
21
+ @ruby_extractor = ruby_extractor
22
+ @source = source
23
+ end
24
+
25
+ # @return [Array<Templatecop::Offense>]
26
+ def call
27
+ snippets.flat_map do |snippet|
28
+ RubyOffenseCollector.new(
29
+ auto_correct: @auto_correct,
30
+ file_path: @file_path,
31
+ rubocop_config: @rubocop_config,
32
+ source: snippet[:code]
33
+ ).call.map do |rubocop_offense|
34
+ Offense.new(
35
+ file_path: @file_path,
36
+ offset: snippet[:offset],
37
+ rubocop_offense: rubocop_offense,
38
+ source: @source
39
+ )
40
+ end
41
+ end
42
+ end
43
+
44
+ private
45
+
46
+ # @return [Array<Hash>]
47
+ def snippets
48
+ @ruby_extractor.call(
49
+ file_path: @file_path,
50
+ source: @source
51
+ )
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Templatecop
4
+ VERSION = '0.1.0'
5
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'templatecop/version'
4
+
5
+ module Templatecop
6
+ autoload :Cli, 'templatecop/cli'
7
+ autoload :Offense, 'templatecop/offense'
8
+ autoload :PathFinder, 'templatecop/path_finder'
9
+ autoload :RuboCopConfigGenerator, 'templatecop/rubo_cop_config_generator'
10
+ autoload :RubyClipper, 'templatecop/ruby_clipper'
11
+ autoload :RubyExtractor, 'templatecop/ruby_extractor'
12
+ autoload :RubyOffenseCollector, 'templatecop/ruby_offense_collector'
13
+ autoload :Runner, 'templatecop/runner'
14
+ autoload :TemplateCorrector, 'templatecop/template_corrector'
15
+ autoload :TemplateOffenseCollector, 'templatecop/template_offense_collector'
16
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/templatecop/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'templatecop'
7
+ spec.version = Templatecop::VERSION
8
+ spec.authors = ['Ryo Nakamura']
9
+ spec.email = ['r7kamura@gmail.com']
10
+
11
+ spec.summary = 'RuboCop runner framework for template language.'
12
+ spec.homepage = 'https://github.com/r7kamura/templatecop'
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/mainCHANGELOG.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 'parser'
33
+ spec.add_dependency 'rubocop', '>= 0.87'
34
+ end
metadata ADDED
@@ -0,0 +1,96 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: templatecop
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-15 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: parser
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: rubocop
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0.87'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0.87'
41
+ description:
42
+ email:
43
+ - r7kamura@gmail.com
44
+ executables: []
45
+ extensions: []
46
+ extra_rdoc_files: []
47
+ files:
48
+ - ".rspec"
49
+ - ".rubocop.yml"
50
+ - CHANGELOG.md
51
+ - CODE_OF_CONDUCT.md
52
+ - Gemfile
53
+ - Gemfile.lock
54
+ - LICENSE.txt
55
+ - README.md
56
+ - Rakefile
57
+ - lib/templatecop.rb
58
+ - lib/templatecop/cli.rb
59
+ - lib/templatecop/offense.rb
60
+ - lib/templatecop/path_finder.rb
61
+ - lib/templatecop/rubo_cop_config_generator.rb
62
+ - lib/templatecop/ruby_clipper.rb
63
+ - lib/templatecop/ruby_offense_collector.rb
64
+ - lib/templatecop/runner.rb
65
+ - lib/templatecop/template_corrector.rb
66
+ - lib/templatecop/template_offense_collector.rb
67
+ - lib/templatecop/version.rb
68
+ - templatecop.gemspec
69
+ homepage: https://github.com/r7kamura/templatecop
70
+ licenses:
71
+ - MIT
72
+ metadata:
73
+ homepage_uri: https://github.com/r7kamura/templatecop
74
+ source_code_uri: https://github.com/r7kamura/templatecop
75
+ changelog_uri: https://github.com/r7kamura/templatecop/blob/mainCHANGELOG.md
76
+ rubygems_mfa_required: 'true'
77
+ post_install_message:
78
+ rdoc_options: []
79
+ require_paths:
80
+ - lib
81
+ required_ruby_version: !ruby/object:Gem::Requirement
82
+ requirements:
83
+ - - ">="
84
+ - !ruby/object:Gem::Version
85
+ version: 2.6.0
86
+ required_rubygems_version: !ruby/object:Gem::Requirement
87
+ requirements:
88
+ - - ">="
89
+ - !ruby/object:Gem::Version
90
+ version: '0'
91
+ requirements: []
92
+ rubygems_version: 3.1.4
93
+ signing_key:
94
+ specification_version: 4
95
+ summary: RuboCop runner framework for template language.
96
+ test_files: []