Home > Net >  Exclude all except one subfolder for Rubocop
Exclude all except one subfolder for Rubocop

Time:06-27

Let's say we have a folder called bin and it includes another subfolder bin/scripts besides other folders and top-level files.

We are looking to scan only the bin/scripts/**/* files and ignore everything else in the bin folder.

This pattern bellow excludes everything in that folder

AllCops:
  TargetRubyVersion: 3.1.2
  NewCops: enable
  Exclude:
    - "bin/**/*"

CodePudding user response:

Use ERB to Template Your Exclusions

This is covered by the RuboCop documentation on including/excluding files when used in conjunction with the section on pre-processing using ERB. There might be a more elegant way to do this, but using ERB to add excluded items based on an inverted regular expression using Enumerable#grep_v on a Dir#glob just seems easiest to me.

This was tested with Ruby 3.1.2 and RuboCop v1.30.1, and "just works." Your mileage may vary with other versions or approaches.

AllCops:
  TargetRubyVersion: 3.1.2
  NewCops: enable
  Exclude:
    <% Dir.glob('bin/**/*').grep_v(%r{bin/scripts/}).each do |path| %>
    - <%= path %>
    <% end %>

With the template above in .rubocop.yml and a tree structure of:

.
├── bin
│   ├── bar.rb
│   ├── baz
│   │   └── quux.rb
│   └── scripts
│       └── wuuble
│           └── zub.rb
└── lib
    └── foo.rb

RuboCop only checks:

  • lib/foo.rb
  • bin/scripts/wuuble/zub.rb
  • Related