rubocop-rspec-extra 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: b6d37e0a9b8e12b308c8f45612176fd83edd6a6ce1852746dc0140efba3efb6b
4
+ data.tar.gz: ef9b88f0c670940a7f79b8c4ae6e73f1f8b492b630cceb540dab1c6a85ec003e
5
+ SHA512:
6
+ metadata.gz: 6ba9025e60e671873a082672d0677fc2eacd07c60f1d1fca1d9ac6068fdd9d1894faf6336e37d63f86bfbc9bcb482477bd246176e23967cd9f36df316107a323
7
+ data.tar.gz: e6b5eda765dd616f7ba4d9e24c93462b0440986b00098f11c21993c45e93e8391723e6301db74f2a53beae6745caf7e51cee045f4696a03b8f44d1808669aa37
data/.codespellignore ADDED
File without changes
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,35 @@
1
+ inherit_from: .rubocop_todo.yml
2
+
3
+ require:
4
+ - rubocop/cop/internal_affairs
5
+ - rubocop-performance
6
+ - rubocop-rake
7
+ - rubocop-rspec
8
+ - rubocop-rspec-extra
9
+
10
+ AllCops:
11
+ NewCops: enable
12
+ TargetRubyVersion: 2.6
13
+ SuggestExtensions: false
14
+
15
+ Layout/LineLength:
16
+ Enabled: false
17
+
18
+ Metrics:
19
+ Enabled: false
20
+
21
+ Naming/FileName:
22
+ Exclude:
23
+ - lib/rubocop-rspec-extra.rb
24
+
25
+ Style/Documentation:
26
+ Enabled: false
27
+
28
+ Style/StringLiterals:
29
+ EnforcedStyle: double_quotes
30
+
31
+ Style/StringLiteralsInInterpolation:
32
+ EnforcedStyle: double_quotes
33
+
34
+ RSpec/ExampleLength:
35
+ Enabled: false
data/.rubocop_todo.yml ADDED
@@ -0,0 +1,12 @@
1
+ # This configuration was generated by
2
+ # `rubocop --auto-gen-config --auto-gen-only-exclude --no-exclude-limit --no-auto-gen-timestamp`
3
+ # using RuboCop version 1.47.0.
4
+ # The point is for the user to remove these configuration records
5
+ # one by one as the offenses are removed from the code base.
6
+ # Note that changes in the inspected code, or installation of new
7
+ # versions of RuboCop, may require this file to be generated again.
8
+
9
+ # Offense count: 10
10
+ Rake/MethodDefinitionInTask:
11
+ Exclude:
12
+ - 'tasks/cut_release.rake'
data/.yamllint.yml ADDED
@@ -0,0 +1,9 @@
1
+ extends: default
2
+
3
+ rules:
4
+ comments:
5
+ min-spaces-from-content: 1
6
+ document-start: disable
7
+ line-length: disable
8
+ truthy:
9
+ check-keys: false
data/.yardopts ADDED
@@ -0,0 +1,2 @@
1
+ --markup markdown
2
+ --hide-void-return
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## Unreleased
2
+
3
+ ## 0.1.0 - 2023-04-18
4
+
5
+ - 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 t.yudai92@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
+ For answers to common questions about this code of conduct, see the FAQ at
82
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
83
+
84
+ [homepage]: https://www.contributor-covenant.org
data/Gemfile ADDED
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ gemspec
6
+
7
+ gem "bump", require: false
8
+ gem "rake"
9
+ gem "rspec", "~> 3.11"
10
+ gem "rubocop-performance", "~> 1.7"
11
+ gem "rubocop-rake", "~> 0.6"
12
+ gem "rubocop-rspec", "~> 2.18"
13
+ gem "yard"
data/MIT-LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 Yudai Takada
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,81 @@
1
+ # Rubocop::Rspec::Extra
2
+
3
+ ![GitHub top language](https://img.shields.io/github/languages/top/ydah/rubocop-rspec-extra) ![GitHub](https://img.shields.io/github/license/ydah/rubocop-rspec-extra) ![Ruby Style Guide](https://img.shields.io/badge/code_style-rubocop-brightgreen.svg) [![CI](https://github.com/ydah/rubocop-rspec-extra/actions/workflows/ci.yml/badge.svg)](https://github.com/ydah/rubocop-rspec-extra/actions/workflows/ci.yml) [![Maintainability](https://api.codeclimate.com/v1/badges/6b1f27edd867a4b64661/maintainability)](https://codeclimate.com/github/ydah/rubocop-rspec-extra/maintainability)
4
+
5
+ A [RuboCop](https://github.com/rubocop/rubocop) extension focused on enforcing RSpec. A place where no one is officially employed, but where useful cops can gather.
6
+
7
+ ## Installation
8
+
9
+ Just install the `rubocop-rspec-extra` gem
10
+
11
+ ```bash
12
+ gem install rubocop-rspec-extra
13
+ ```
14
+
15
+ or if you use bundler put this in your `Gemfile`
16
+
17
+ ```bash
18
+ gem 'rubocop-rspec-extra', require: false
19
+ ```
20
+
21
+ ## Usage
22
+
23
+ You need to tell RuboCop to load the RSpec Extra extension. There are two
24
+ ways to do this:
25
+
26
+ ### RuboCop configuration file
27
+
28
+ Put this into your `.rubocop.yml`.
29
+
30
+ ```yaml
31
+ require: rubocop-rspec-extra
32
+ ```
33
+
34
+ Alternatively, use the following array notation when specifying multiple extensions.
35
+
36
+ ```yaml
37
+ require:
38
+ - rubocop-rspec
39
+ - rubocop-rspec-extra
40
+ ```
41
+
42
+ Now you can run `rubocop` and it will automatically load the RuboCop RSpec Extra
43
+ cops together with the standard cops.
44
+
45
+ ### Command line
46
+
47
+ ```bash
48
+ rubocop --require rubocop-rspec-extra
49
+ ```
50
+
51
+ ### Rake task
52
+
53
+ ```ruby
54
+ RuboCop::RakeTask.new do |task|
55
+ task.requires << 'rubocop-rspec-extra'
56
+ end
57
+ ```
58
+
59
+ ## The Cops
60
+
61
+ All cops are located under
62
+ [`lib/rubocop/cop/rspec/extra`](lib/rubocop/cop/rspec/extra), and contain
63
+ examples/documentation.
64
+
65
+ In your `.rubocop.yml`, you may treat the Committee cops just like any other
66
+ cop. For example:
67
+
68
+ ```yaml
69
+ RSpec/Extra/RestrictBlockTag:
70
+ Exclude:
71
+ - spec/my_poorly_named_spec_file.rb
72
+ ```
73
+
74
+ ## Contributing
75
+
76
+ Checkout the [contribution guidelines](.github/CONTRIBUTING.md).
77
+
78
+ ## License
79
+
80
+ `rubocop-committee` is MIT licensed. [See the accompanying file](MIT-LICENSE.md) for
81
+ the full text.
data/Rakefile ADDED
@@ -0,0 +1,14 @@
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
+ Dir["tasks/**/*.rake"].each { |t| load t }
11
+
12
+ RuboCop::RakeTask.new
13
+
14
+ task default: %i[spec rubocop]
@@ -0,0 +1,21 @@
1
+ ---
2
+ RSpec/Extra:
3
+ Enabled: true
4
+
5
+ RSpec/Extra/BeEmpty:
6
+ Description: Prefer using `be_empty` when checking for an empty array.
7
+ Enabled: pending
8
+ VersionAdded: '<<next>>'
9
+ Reference: https://www.rubydoc.info/gems/rubocop-rspec-extra/RuboCop/Cop/RSpec/Extra/BeEmpty
10
+
11
+ RSpec/Extra/RestrictBlockTag:
12
+ Description: 'Restrict to only allowed block tags.'
13
+ Enabled: false
14
+ VersionAdded: '<<next>>'
15
+ AllowTags: []
16
+
17
+ RSpec/Extra/RestrictBlockTagValue:
18
+ Description: 'Restrict to only allowed block tag value.'
19
+ Enabled: pending
20
+ VersionAdded: '<<next>>'
21
+ AllowTagValues: {}
data/docs/antora.yml ADDED
@@ -0,0 +1,5 @@
1
+ name: rubocop-rspec-extra
2
+ title: RuboCop RSpec Extra
3
+ version: ~
4
+ nav:
5
+ - modules/ROOT/nav.adoc
@@ -0,0 +1,6 @@
1
+ * xref:index.adoc[Home]
2
+ * xref:installation.adoc[Installation]
3
+ * xref:usage.adoc[Usage]
4
+ * xref:cops.adoc[Cops]
5
+ * Cops Documentation
6
+ ** xref:cops_rspec_extra.adoc[Extra]
@@ -0,0 +1,9 @@
1
+ // START_COP_LIST
2
+
3
+ === Department xref:cops_rspec_extra.adoc[RSpec/Extra]
4
+
5
+ * xref:cops_rspec_extra.adoc#rspecextra/beempty[RSpec/Extra/BeEmpty]
6
+ * xref:cops_rspec_extra.adoc#rspecextra/restrictblocktag[RSpec/Extra/RestrictBlockTag]
7
+ * xref:cops_rspec_extra.adoc#rspecextra/restrictblocktagvalue[RSpec/Extra/RestrictBlockTagValue]
8
+
9
+ // END_COP_LIST
@@ -0,0 +1,127 @@
1
+ = RSpec/Extra
2
+
3
+ == RSpec/Extra/BeEmpty
4
+
5
+ |===
6
+ | Enabled by default | Safe | Supports autocorrection | Version Added | Version Changed
7
+
8
+ | Pending
9
+ | Yes
10
+ | Yes
11
+ | <<next>>
12
+ | -
13
+ |===
14
+
15
+ Prefer using `be_empty` when checking for an empty array.
16
+
17
+ === Examples
18
+
19
+ [source,ruby]
20
+ ----
21
+ # bad
22
+ expect(array.empty?).to be true
23
+ expect(array.empty?).to be_truthy
24
+ expect(array.size).to eq(0)
25
+ expect(array.length).to eq(0)
26
+ expect(array.count).to eq(0)
27
+ expect(array).to eql([])
28
+ expect(array).to contain_exactly
29
+ expect(array).to match_array([])
30
+
31
+ # good
32
+ expect(array).to be_empty
33
+ ----
34
+
35
+ === References
36
+
37
+ * https://www.rubydoc.info/gems/rubocop-rspec-extra/RuboCop/Cop/RSpec/Extra/BeEmpty
38
+
39
+ == RSpec/Extra/RestrictBlockTag
40
+
41
+ |===
42
+ | Enabled by default | Safe | Supports autocorrection | Version Added | Version Changed
43
+
44
+ | Disabled
45
+ | Yes
46
+ | No
47
+ | <<next>>
48
+ | -
49
+ |===
50
+
51
+ Restrict to only allowed block tags.
52
+
53
+ === Examples
54
+
55
+ ==== AllowTags: ['foo', 'bar']
56
+
57
+ [source,ruby]
58
+ ----
59
+ # bad
60
+ RSpec.describe 'Something', :baz do
61
+ end
62
+
63
+ # bad
64
+ RSpec.describe 'Something' do
65
+ context 'when something', baz: :foo do
66
+ end
67
+ end
68
+
69
+ # good
70
+ RSpec.describe 'Something', :foo do
71
+ end
72
+
73
+ # good
74
+ RSpec.describe 'Something' do
75
+ context 'when something', bar: :foo do
76
+ end
77
+ end
78
+ ----
79
+
80
+ === Configurable attributes
81
+
82
+ |===
83
+ | Name | Default value | Configurable values
84
+
85
+ | AllowTags
86
+ | `[]`
87
+ | Array
88
+ |===
89
+
90
+ == RSpec/Extra/RestrictBlockTagValue
91
+
92
+ |===
93
+ | Enabled by default | Safe | Supports autocorrection | Version Added | Version Changed
94
+
95
+ | Pending
96
+ | Yes
97
+ | No
98
+ | <<next>>
99
+ | -
100
+ |===
101
+
102
+ Restrict to only allowed block tag value.
103
+
104
+ === Examples
105
+
106
+ ==== AllowTagValues: { foo: 'baz' }
107
+
108
+ [source,ruby]
109
+ ----
110
+ # bad
111
+ RSpec.describe 'Something', foo: :bar do
112
+ end
113
+
114
+ # good
115
+ RSpec.describe 'Something', foo: :baz do
116
+ end
117
+ ----
118
+
119
+ === Configurable attributes
120
+
121
+ |===
122
+ | Name | Default value | Configurable values
123
+
124
+ | AllowTagValues
125
+ | `{}`
126
+ |
127
+ |===
@@ -0,0 +1,17 @@
1
+ = RuboCop RSpec Extra
2
+
3
+ RSpec-specific analysis for your projects, as an extension to
4
+ https://github.com/rubocop/rubocop[RuboCop].
5
+ A place where no one is officially employed, but where useful cops can gather.
6
+
7
+ RuboCop RSpec Extra follows the https://docs.rubocop.org/rubocop/versioning.html[RuboCop versioning guide].
8
+ In a nutshell, between major versions new cops are introduced in a special `pending` status.
9
+ That means that they won’t be run unless explicitly told otherwise.
10
+ RuboCop will warn on start that certain cops are neither explicitly enabled and disabled.
11
+ On a major version release, all `pending` cops are enabled.
12
+
13
+ == Project Goals
14
+
15
+
16
+ * Simplify the process of adopting new RSpec functionality
17
+ * A collection of cops who are not hired by RuboCop RSpec but are useful when writing test code in RSpec
@@ -0,0 +1,15 @@
1
+ = Installation
2
+
3
+ Just install the `rubocop-rspec` gem
4
+
5
+ [source,bash]
6
+ ----
7
+ gem install rubocop-rspec-extra
8
+ ----
9
+
10
+ or if you use bundler put this in your `Gemfile`
11
+
12
+ [source,ruby]
13
+ ----
14
+ gem 'rubocop-rspec-extra'
15
+ ----
@@ -0,0 +1,37 @@
1
+ = Usage
2
+
3
+ You need to tell RuboCop to load the RuboCop RSpec Extra extension.
4
+ There are some ways to do this:
5
+
6
+ == RuboCop configuration file
7
+
8
+ Put this into your `.rubocop.yml`:
9
+
10
+ ----
11
+ require: rubocop-rspec-extra
12
+ ----
13
+
14
+ or, if you are using several extensions:
15
+
16
+ ----
17
+ require:
18
+ - rubocop-rspec
19
+ - rubocop-rspec-extra
20
+ ----
21
+
22
+ Now you can run `rubocop` and it will automatically load the RuboCop RSpec Extra
23
+ cops together with the standard cops.
24
+
25
+ [source,bash]
26
+ ----
27
+ $ rubocop --require rubocop-rspec-extra
28
+ ----
29
+
30
+ == Rake task
31
+
32
+ [source,ruby]
33
+ ----
34
+ RuboCop::RakeTask.new do |task|
35
+ task.requires << 'rubocop-rspec-extra'
36
+ end
37
+ ----
@@ -0,0 +1,84 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RuboCop
4
+ module Cop
5
+ module RSpec
6
+ module Extra
7
+ # Prefer using `be_empty` when checking for an empty array.
8
+ #
9
+ # @example
10
+ # # bad
11
+ # expect(array.empty?).to be true
12
+ # expect(array.empty?).to be_truthy
13
+ # expect(array.size).to eq(0)
14
+ # expect(array.length).to eq(0)
15
+ # expect(array.count).to eq(0)
16
+ # expect(array).to eql([])
17
+ # expect(array).to contain_exactly
18
+ # expect(array).to match_array([])
19
+ #
20
+ # # good
21
+ # expect(array).to be_empty
22
+ #
23
+ class BeEmpty < Base
24
+ extend AutoCorrector
25
+
26
+ MSG = "Use `be_empty` matchers for checking an empty array."
27
+ RESTRICT_ON_SEND =
28
+ %i[be be_truthy eq eql contain_exactly match_array].freeze
29
+
30
+ # @!method expect_array_empty_true?(node)
31
+ def_node_matcher :expect_array_empty_true?, <<~PATTERN
32
+ (send
33
+ (send nil? :expect $(send _ :empty?))
34
+ #Runners.all
35
+ ${(send nil? :be true) (send nil? :be_truthy)}
36
+ )
37
+ PATTERN
38
+
39
+ # @!method expect_array_size_zero?(node)
40
+ def_node_matcher :expect_array_size_zero?, <<~PATTERN
41
+ (send
42
+ (send nil? :expect $(send _ {:size :length :count}))
43
+ #Runners.all
44
+ $(send nil? {:eq :eql} (int 0))
45
+ )
46
+ PATTERN
47
+
48
+ # @!method expect_array_matcher?(node)
49
+ def_node_matcher :expect_array_matcher?, <<~PATTERN
50
+ (send
51
+ (send nil? :expect _)
52
+ #Runners.all
53
+ ${
54
+ (send nil? {:eq :eql :match_array} (array))
55
+ (send nil? :contain_exactly)
56
+ }
57
+ )
58
+ PATTERN
59
+
60
+ def on_send(node)
61
+ expect_array_empty_true?(node.parent) do |actual, expect|
62
+ register_offense(actual, expect)
63
+ end
64
+ expect_array_size_zero?(node.parent) do |actual, expect|
65
+ register_offense(actual, expect)
66
+ end
67
+ expect_array_matcher?(node.parent) do |expect|
68
+ register_offense(nil, expect)
69
+ end
70
+ end
71
+
72
+ private
73
+
74
+ def register_offense(actual, expect)
75
+ add_offense(expect) do |corrector|
76
+ corrector.replace(actual, actual.receiver.source) if actual
77
+ corrector.replace(expect, "be_empty")
78
+ end
79
+ end
80
+ end
81
+ end
82
+ end
83
+ end
84
+ end
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RuboCop
4
+ module Cop
5
+ module RSpec
6
+ module Extra
7
+ # Restrict to only allowed block tags.
8
+ #
9
+ # @example AllowTags: ['foo', 'bar']
10
+ # # bad
11
+ # RSpec.describe 'Something', :baz do
12
+ # end
13
+ #
14
+ # # bad
15
+ # RSpec.describe 'Something' do
16
+ # context 'when something', baz: :foo do
17
+ # end
18
+ # end
19
+ #
20
+ # # good
21
+ # RSpec.describe 'Something', :foo do
22
+ # end
23
+ #
24
+ # # good
25
+ # RSpec.describe 'Something' do
26
+ # context 'when something', bar: :foo do
27
+ # end
28
+ # end
29
+ #
30
+ class RestrictBlockTag < Base
31
+ include Metadata
32
+
33
+ def on_metadata(symbols, pairs)
34
+ offenses = (symbols + pairs.map(&:key)).filter do |symbol|
35
+ !allow_tags.include?(symbol.value.to_s)
36
+ end
37
+
38
+ return unless offenses.any?
39
+
40
+ offenses.each do |offense|
41
+ add_offense(offense, message: offense_message)
42
+ end
43
+ end
44
+
45
+ private
46
+
47
+ def offense_message
48
+ if allow_tags.any?
49
+ format("This tag is not allowed. Allowed tags: %<allow_tags>s.", allow_tags: allow_tags.join(", "))
50
+ else
51
+ "Tags are not allowed."
52
+ end
53
+ end
54
+
55
+ def allow_tags
56
+ cop_config.fetch("AllowTags", [])
57
+ end
58
+ end
59
+ end
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RuboCop
4
+ module Cop
5
+ module RSpec
6
+ module Extra
7
+ # Restrict to only allowed block tag value.
8
+ #
9
+ # @example AllowTagValues: { foo: 'baz' }
10
+ # # bad
11
+ # RSpec.describe 'Something', foo: :bar do
12
+ # end
13
+ #
14
+ # # good
15
+ # RSpec.describe 'Something', foo: :baz do
16
+ # end
17
+ #
18
+ class RestrictBlockTagValue < Base
19
+ include Metadata
20
+ MSG = "This value is not allowed in this tag. Allowed tag value: %<allow_tag_value>s."
21
+
22
+ def on_metadata(_symbols, pairs)
23
+ offenses = pairs.filter do |pair|
24
+ allow_tag_values.any? do |k, v|
25
+ pair.key.value.to_s == k &&
26
+ pair.value.value.to_s != v
27
+ end
28
+ end
29
+
30
+ return unless offenses.any?
31
+
32
+ offenses.each do |offense|
33
+ add_offense(offense, message: format(MSG, allow_tag_value: allow_tag_values[offense.key.value.to_s]))
34
+ end
35
+ end
36
+
37
+ private
38
+
39
+ def allow_tag_values
40
+ cop_config.fetch("AllowTagValues", {})
41
+ end
42
+ end
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RuboCop
4
+ module RSpec
5
+ module Extra
6
+ module Inject
7
+ def self.defaults!
8
+ path = CONFIG_DEFAULT.to_s
9
+ hash = ::RuboCop::ConfigLoader.send(:load_yaml_configuration, path)
10
+ config = ::RuboCop::Config.new(hash, path).tap(&:make_excludes_absolute)
11
+ puts "configuration from #{path}" if ::RuboCop::ConfigLoader.debug?
12
+ config = ::RuboCop::ConfigLoader.merge_with_default(config, path)
13
+ ::RuboCop::ConfigLoader.instance_variable_set(:@default_configuration, config)
14
+ end
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rubocop
4
+ module Rspec
5
+ module Extra
6
+ VERSION = "0.1.0"
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rubocop-rspec"
4
+
5
+ require_relative "rubocop/rspec/extra/inject"
6
+ require_relative "rubocop/rspec/extra/version"
7
+
8
+ require_relative "rubocop/cop/rspec/extra/be_empty"
9
+ require_relative "rubocop/cop/rspec/extra/restrict_block_tag"
10
+ require_relative "rubocop/cop/rspec/extra/restrict_block_tag_value"
11
+
12
+ module RuboCop
13
+ module RSpec
14
+ module Extra
15
+ PROJECT_ROOT = ::Pathname.new(__dir__).parent.expand_path.freeze
16
+ CONFIG_DEFAULT = PROJECT_ROOT.join("config", "default.yml").freeze
17
+ CONFIG = ::YAML.safe_load(CONFIG_DEFAULT.read).freeze
18
+ private_constant(:CONFIG_DEFAULT, :PROJECT_ROOT)
19
+ end
20
+ end
21
+ end
22
+
23
+ RuboCop::RSpec::Extra::Inject.defaults!
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ autoload :Changelog, "#{__dir__}/changelog"
4
+
5
+ namespace :changelog do
6
+ %i[new fix change].each do |type|
7
+ desc "Create a Changelog entry (#{type})"
8
+ task type, [:id] do |_task, args|
9
+ ref_type = :pull if args[:id]
10
+ path = Changelog::Entry.new(type: type, ref_id: args[:id], ref_type: ref_type).write
11
+ cmd = "git add #{path}"
12
+ system cmd
13
+ puts "Entry '#{path}' created and added to git index"
14
+ end
15
+ end
16
+
17
+ desc "Merge entries and delete them"
18
+ task :merge do
19
+ raise "No entries!" unless Changelog.pending?
20
+
21
+ Changelog.new.merge!.and_delete!
22
+ cmd = "git commit -a -m 'Update Changelog'"
23
+ puts cmd
24
+ system cmd
25
+ end
26
+
27
+ desc "Check to see if there are any entries left"
28
+ task :check_clean do
29
+ next unless Changelog.pending?
30
+
31
+ puts "*** Pending changelog entries!"
32
+ puts "Do `bundle exec rake changelog:merge`"
33
+ exit(1)
34
+ end
35
+ end
@@ -0,0 +1,193 @@
1
+ # frozen_string_literal: true
2
+
3
+ if RUBY_VERSION < "2.6"
4
+ puts "Changelog utilities available only for Ruby 2.6+"
5
+ exit(1)
6
+ end
7
+
8
+ # Changelog utility
9
+ class Changelog
10
+ ENTRIES_PATH = "changelog/"
11
+ FIRST_HEADER = /#{Regexp.escape("## Master (Unreleased)\n")}/m.freeze
12
+ CONTRIBUTORS_HEADER = /#{Regexp.escape("<!-- Contributors (alphabetically) -->\n\n")}/m.freeze
13
+ ENTRIES_PATH_TEMPLATE = "#{ENTRIES_PATH}%<type>s_%<name>s.md"
14
+ TYPE_REGEXP = /#{Regexp.escape(ENTRIES_PATH)}([a-z]+)_/.freeze
15
+ TYPE_TO_HEADER = { new: "New features", fix: "Bug fixes", change: "Changes" }.freeze
16
+ HEADER = /### (.*)/.freeze
17
+ PATH = "CHANGELOG.md"
18
+ REF_URL = "https://github.com/rubocop/rubocop-rspec-extra"
19
+ MAX_LENGTH = 40
20
+ CONTRIBUTOR = "[@%<link>s]: https://github.com/%<user>s"
21
+ SIGNATURE = Regexp.new(format(Regexp.escape("[@%<user>s]"), user: '([\w-]+)'))
22
+ EOF = "\n"
23
+
24
+ # New entry
25
+ Entry = Struct.new(:type, :body, :ref_type, :ref_id, :user, keyword_init: true) do
26
+ def initialize(type:, body: last_commit_title, ref_type: nil, ref_id: nil, user: github_user)
27
+ id, body = extract_id(body)
28
+ ref_id ||= id || "x"
29
+ ref_type ||= id ? :issues : :pull
30
+ super
31
+ end
32
+
33
+ def write
34
+ FileUtils.mkdir_p(ENTRIES_PATH)
35
+ File.write(path, content)
36
+ path
37
+ end
38
+
39
+ def path
40
+ format(ENTRIES_PATH_TEMPLATE, type: type, name: str_to_filename(body))
41
+ end
42
+
43
+ def content
44
+ period = "." unless body.end_with? "."
45
+ "- #{ref}: #{body}#{period} ([@#{user}])\n"
46
+ end
47
+
48
+ def ref
49
+ "[##{ref_id}](#{REF_URL}/#{ref_type}/#{ref_id})"
50
+ end
51
+
52
+ def last_commit_title
53
+ `git log -1 --pretty=%B`.lines.first.chomp
54
+ end
55
+
56
+ def extract_id(body)
57
+ /^\[Fix(?:es)? #(\d+)\] (.*)/.match(body)&.captures || [nil, body]
58
+ end
59
+
60
+ def str_to_filename(str)
61
+ str
62
+ .split
63
+ .reject(&:empty?)
64
+ .map { |s| prettify(s) }
65
+ .inject do |result, word|
66
+ s = "#{result}_#{word}"
67
+ return result if s.length > MAX_LENGTH
68
+
69
+ s
70
+ end
71
+ end
72
+
73
+ def github_user
74
+ user = `git config --global credential.username`.chomp
75
+ warn 'Set your username with `git config --global credential.username "myusernamehere"`' if user.empty?
76
+
77
+ user
78
+ end
79
+
80
+ private
81
+
82
+ def prettify(str)
83
+ str.gsub!(/\W/, "_")
84
+
85
+ # Separate word boundaries by `_`.
86
+ str.gsub!(/([A-Z]+)(?=[A-Z][a-z])|([a-z\d])(?=[A-Z])/) do
87
+ (Regexp.last_match(1) || Regexp.last_match(2)) << "_"
88
+ end
89
+
90
+ str.gsub!(/\A_+|_+\z/, "")
91
+ str.downcase!
92
+ str
93
+ end
94
+ end
95
+
96
+ def self.pending?
97
+ entry_paths.any?
98
+ end
99
+
100
+ def self.entry_paths
101
+ Dir["#{ENTRIES_PATH}*"]
102
+ end
103
+
104
+ def self.read_entries
105
+ entry_paths.to_h { |path| [path, File.read(path)] }
106
+ end
107
+
108
+ attr_reader :header, :rest
109
+
110
+ def initialize(content: File.read(PATH), entries: Changelog.read_entries)
111
+ require "strscan"
112
+
113
+ parse(content)
114
+ @entries = entries
115
+ end
116
+
117
+ def and_delete!
118
+ @entries.each_key { |path| File.delete(path) }
119
+ end
120
+
121
+ def merge!
122
+ File.write(PATH, merge_content)
123
+ self
124
+ end
125
+
126
+ def unreleased_content
127
+ entry_map = parse_entries(@entries)
128
+ merged_map = merge_entries(entry_map)
129
+ merged_map.flat_map do |header, things|
130
+ ["### #{header}\n", *things, ""]
131
+ end.join("\n")
132
+ end
133
+
134
+ def merge_content
135
+ merged_content = [@header, unreleased_content, @changes.chomp, *all_contributors].join("\n")
136
+
137
+ merged_content << EOF
138
+ end
139
+
140
+ def all_contributors
141
+ (@contributors.split(/\R/) + new_contributors).uniq.sort
142
+ end
143
+
144
+ def new_contributors
145
+ contributors
146
+ .map { |user| format(CONTRIBUTOR, link: user.downcase, user: user) }
147
+ end
148
+
149
+ def contributors
150
+ contributors = @entries.values.flat_map do |entry|
151
+ entry.match(/\. \((?<contributors>.+)\)\n/)[:contributors].split(",")
152
+ end
153
+
154
+ contributors.join.scan(SIGNATURE).flatten
155
+ end
156
+
157
+ private
158
+
159
+ def merge_entries(entry_map)
160
+ all = @unreleased.merge(entry_map) { |_k, v1, v2| v1.concat(v2) }
161
+ canonical = TYPE_TO_HEADER.values.to_h { |v| [v, nil] }
162
+ canonical.merge(all).compact
163
+ end
164
+
165
+ def parse(content)
166
+ ss = StringScanner.new(content)
167
+ @header = ss.scan_until(FIRST_HEADER)
168
+ @unreleased = parse_release(ss.scan_until(/\n(?=## )/m))
169
+ @changes = ss.scan_until(CONTRIBUTORS_HEADER)
170
+ @contributors = ss.rest
171
+ end
172
+
173
+ # @return [Hash<type, Array<String>]]
174
+ def parse_release(unreleased)
175
+ unreleased
176
+ .lines
177
+ .map(&:chomp)
178
+ .reject(&:empty?)
179
+ .slice_before(HEADER)
180
+ .to_h do |header, *entries|
181
+ [HEADER.match(header)[1], entries]
182
+ end
183
+ end
184
+
185
+ def parse_entries(path_content_map)
186
+ changes = Hash.new { |h, k| h[k] = [] }
187
+ path_content_map.each do |path, content|
188
+ header = TYPE_TO_HEADER.fetch(TYPE_REGEXP.match(path)[1].to_sym)
189
+ changes[header].concat(content.lines.map(&:chomp))
190
+ end
191
+ changes
192
+ end
193
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rubocop"
4
+ require "rubocop-rspec-extra"
5
+ require "rubocop/cops_documentation_generator"
6
+ require "yard"
7
+
8
+ YARD::Rake::YardocTask.new(:yard_for_generate_documentation) do |task|
9
+ task.files = ["lib/rubocop/cop/**/*.rb"]
10
+ task.options = ["--no-output"]
11
+ end
12
+
13
+ desc "Generate docs of all cops departments"
14
+ task generate_cops_documentation: :yard_for_generate_documentation do
15
+ generator = CopsDocumentationGenerator.new(
16
+ departments: %w[RSpec/Extra]
17
+ )
18
+ generator.call
19
+ end
20
+
21
+ desc "Syntax check for the documentation comments"
22
+ task documentation_syntax_check: :yard_for_generate_documentation do
23
+ require "parser/ruby25"
24
+
25
+ ok = true
26
+ YARD::Registry.load!
27
+ cops = RuboCop::Cop::Registry.global
28
+ cops.each do |cop|
29
+ examples = YARD::Registry.all(:class).find do |code_object|
30
+ next unless RuboCop::Cop::Badge.for(code_object.to_s) == cop.badge
31
+
32
+ break code_object.tags("example")
33
+ end
34
+
35
+ examples.to_a.each do |example|
36
+ buffer = Parser::Source::Buffer.new("<code>", 1)
37
+ buffer.source = example.text
38
+ parser = Parser::Ruby25.new(RuboCop::AST::Builder.new)
39
+ parser.diagnostics.all_errors_are_fatal = true
40
+ parser.parse(buffer)
41
+ rescue Parser::SyntaxError => e
42
+ path = example.object.file
43
+ puts "#{path}: Syntax Error in an example. #{e}"
44
+ ok = false
45
+ end
46
+ end
47
+ abort unless ok
48
+ end
@@ -0,0 +1,91 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bump"
4
+
5
+ namespace :cut_release do
6
+ %w[major minor patch pre].each do |release_type|
7
+ desc "Cut a new #{release_type} release and create release notes."
8
+ task release_type => "changelog:check_clean" do
9
+ run(release_type)
10
+ end
11
+ end
12
+
13
+ def add_header_to_changelog(version)
14
+ update_file("CHANGELOG.md") do |changelog|
15
+ changelog.sub("## Master (Unreleased)\n\n",
16
+ '\0' "## #{version} (#{Time.now.strftime("%F")})\n\n")
17
+ end
18
+ end
19
+
20
+ def create_release_notes(version)
21
+ release_notes = new_version_changes.strip
22
+ contributor_links = user_links(release_notes)
23
+
24
+ File.open("relnotes/v#{version}.md", "w") do |file|
25
+ file << release_notes
26
+ file << "\n\n"
27
+ file << contributor_links
28
+ file << "\n"
29
+ end
30
+ end
31
+
32
+ def update_antora_yml(new_version)
33
+ antora_metadata = File.read("docs/antora.yml")
34
+
35
+ File.open("docs/antora.yml", "w") do |f|
36
+ f << antora_metadata.sub("version: ~", "version: '#{version_sans_patch(new_version)}'")
37
+ end
38
+ end
39
+
40
+ def version_sans_patch(version)
41
+ version.split(".").take(2).join(".")
42
+ end
43
+
44
+ # Replace `<<next>>` (and variations) with version being cut.
45
+ def update_cop_versions(version)
46
+ update_file("config/default.yml") do |default|
47
+ default.gsub(/['"]?<<\s*next\s*>>['"]?/i,
48
+ "'#{version_sans_patch(version)}'")
49
+ end
50
+ RuboCop::ConfigLoader.default_configuration = nil # invalidate loaded conf
51
+ end
52
+
53
+ def new_version_changes
54
+ changelog = File.read("CHANGELOG.md")
55
+ _, _, new_changes, _older_changes = changelog.split(/^## .*$/, 4)
56
+ new_changes
57
+ end
58
+
59
+ def update_file(path)
60
+ content = File.read(path)
61
+ File.write(path, yield(content))
62
+ end
63
+
64
+ def user_links(text)
65
+ names = text.scan(/\[@(\S+)\]/).map(&:first).uniq
66
+ names.map { |name| "[@#{name}]: https://github.com/#{name}" }.join("\n")
67
+ end
68
+
69
+ def update_docs(version)
70
+ update_file("docs/antora.yml") do |antora_metadata|
71
+ antora_metadata.sub("version: ~",
72
+ "version: '#{version_sans_patch(version)}'")
73
+ end
74
+ end
75
+
76
+ def run(release_type)
77
+ old_version = Bump::Bump.current
78
+ Bump::Bump.run(release_type, commit: false, bundle: false, tag: false)
79
+ new_version = Bump::Bump.current
80
+
81
+ update_cop_versions(new_version)
82
+ `bundle exec rake generate_cops_documentation`
83
+ update_docs(new_version) if %w[major minor].include?(release_type)
84
+
85
+ add_header_to_changelog(new_version)
86
+ create_release_notes(new_version)
87
+ update_antora_yml(new_version)
88
+
89
+ puts "Changed version from #{old_version} to #{new_version}."
90
+ end
91
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ desc "Generate a new cop with a template"
4
+ task :new_cop, [:cop] do |_task, args|
5
+ require "rubocop"
6
+
7
+ cop_name = args.fetch(:cop) do
8
+ warn "usage: bundle exec rake 'new_cop[RSpec/Extra/Name]'"
9
+ exit!
10
+ end
11
+
12
+ generator = RuboCop::Cop::Generator.new(cop_name)
13
+
14
+ generator.write_source
15
+ generator.write_spec
16
+ generator.inject_require(root_file_path: "lib/rubocop-rspec-extra.rb")
17
+ generator.inject_config(config_file_path: "config/default.yml")
18
+
19
+ puts generator.todo
20
+ end
metadata ADDED
@@ -0,0 +1,95 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rubocop-rspec-extra
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - ydah
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-04-17 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rubocop
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
+ description: |
28
+ Automatic committee code style checking tool.
29
+ A RuboCop extension focused on enforcing RSpec.
30
+ A place where no one is officially employed, but where useful cops can gather.
31
+ email:
32
+ - t.yudai92@gmail.com
33
+ executables: []
34
+ extensions: []
35
+ extra_rdoc_files: []
36
+ files:
37
+ - ".codespellignore"
38
+ - ".rspec"
39
+ - ".rubocop.yml"
40
+ - ".rubocop_todo.yml"
41
+ - ".yamllint.yml"
42
+ - ".yardopts"
43
+ - CHANGELOG.md
44
+ - CODE_OF_CONDUCT.md
45
+ - Gemfile
46
+ - MIT-LICENSE.md
47
+ - README.md
48
+ - Rakefile
49
+ - config/default.yml
50
+ - docs/antora.yml
51
+ - docs/modules/ROOT/nav.adoc
52
+ - docs/modules/ROOT/pages/cops.adoc
53
+ - docs/modules/ROOT/pages/cops_rspec_extra.adoc
54
+ - docs/modules/ROOT/pages/index.adoc
55
+ - docs/modules/ROOT/pages/installation.adoc
56
+ - docs/modules/ROOT/pages/usage.adoc
57
+ - lib/rubocop-rspec-extra.rb
58
+ - lib/rubocop/cop/rspec/extra/be_empty.rb
59
+ - lib/rubocop/cop/rspec/extra/restrict_block_tag.rb
60
+ - lib/rubocop/cop/rspec/extra/restrict_block_tag_value.rb
61
+ - lib/rubocop/rspec/extra/inject.rb
62
+ - lib/rubocop/rspec/extra/version.rb
63
+ - tasks/changelog.rake
64
+ - tasks/changelog.rb
65
+ - tasks/cops_documentation.rake
66
+ - tasks/cut_release.rake
67
+ - tasks/new_cop.rake
68
+ homepage: https://github.com/ydah/rubocop-rspec-extra
69
+ licenses:
70
+ - MIT
71
+ metadata:
72
+ homepage_uri: https://github.com/ydah/rubocop-rspec-extra
73
+ source_code_uri: https://github.com/ydah/rubocop-rspec-extra
74
+ changelog_uri: https://github.com/ydah/rubocop-rspec-extra/blob/master/CHANGELOG.md
75
+ rubygems_mfa_required: 'true'
76
+ post_install_message:
77
+ rdoc_options: []
78
+ require_paths:
79
+ - lib
80
+ required_ruby_version: !ruby/object:Gem::Requirement
81
+ requirements:
82
+ - - ">="
83
+ - !ruby/object:Gem::Version
84
+ version: 2.6.0
85
+ required_rubygems_version: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ requirements: []
91
+ rubygems_version: 3.4.5
92
+ signing_key:
93
+ specification_version: 4
94
+ summary: Automatic committee code style checking tool.
95
+ test_files: []