我正在开发一个工具来分析如何在代码库的某些区域使用(启用/禁用)和修复(不包括在待办事项列表中)RuboCop.考虑到大量的配置选项,我正在寻找一种方法,以编程方式询问RuboCop是否给定了文件或文件夹,是否启用了特定规则,以及是否通过TODO排除了该文件.有针对这一点的API吗?

到目前为止,我已经在https://github.com/rubocop/rubocop个地方探索过了,看看我是否能找到一个API...通过SO和谷歌搜索,什么也找不到.

推荐答案

我不认为你想要什么就有什么公共接口.This mobilize_team method in the RunnerRuboCop::Cop::Team的实例化.Team对象确定在this roundup_relevant_cops method中使用的警察.这两种方法都是私有的,但您可以使用send来解决这一问题.

例如,假设我们有一个项目,其中包含名为test_one.rbtest_two.rb的两个文件.

.rubocop_todo.yml表示,其中一个文件仍需处理:

# .rubocop_todo.yml
Style/FrozenStringLiteralComment:
  Exclude:
    - 'test_two.rb'

.rubocop.yml配置说明我们只关心Style/FrozenStringLiteralComment:

# .rubocop.yml
inherit_from: .rubocop_todo.yml

AllCops:
  DisabledByDefault: true

Style/FrozenStringLiteralComment:
  Enabled: true

我们可以看到,如果我们这样做,RuboCop将应用于每个文件:

require 'rubocop'

# Set up the Runner. Assumes no special command line options are involved.
options, _paths = RuboCop::Options.new.parse([])
config_store = RuboCop::ConfigStore.new
runner = RuboCop::Runner.new(options, config_store)

# For each file, figure out which cops are enabled for that file
['test_one.rb', 'test_two.rb'].each do |filename|
  full_path = File.join(Dir.pwd, filename)
  config = config_store.for_file(full_path)
  source = RuboCop::ProcessedSource.from_file(full_path, config.target_ruby_version)
  team = runner.send(:mobilize_team, source)
  cops = team.send(:roundup_relevant_cops, source)
  puts "#{filename}: #{cops.map(&:name).join(', ')}"
end

这将显示以下输出:

test_one.rb: Lint/Syntax, Style/FrozenStringLiteralComment
test_two.rb: Lint/Syntax

由于this special condition in enable_cop?,Lint/Syntax COP始终处于启用状态.由于test_one.rb不包括在TODO列表中,它是唯一符合第Style/FrozenStringLiteralComment个COP的文件.

Ruby相关问答推荐

MongoDB通过Brew Services";未定义的方法`plist_starting';";

如何使用Ruby range?

Ruby 扁平化 JSON 对象或哈希

PDFNet:Ubuntu 16.04 和 Ubuntu 20.04 上 PDF 输出文本的词序不同

类似于模块的 attr_accessor 和 attr_reader 的东西?

从整数中 Select 重复数字的字符串

无法解析音频文件 track1.m4a

使用 Drive API 创建空文件

如果 Java 人go Scala,C# go F#,那么 Ruby 人go 哪里寻求函数式?

bundler 可以告诉我 Gemfile 中的哪些 gem 有更新的版本

如何在 ruby​​ 中列出当前范围内的当前可用对象?

Ruby on Rails 中是否有简写 if(没有 else)语句?

出于调试目的,如何打印有关 NET:HTTPRequest 的信息?

有效的Electron邮件地址正则表达式?

我如何 expect期望在 RSpec 中引发异常的东西?

如何在不按 Enter 的情况下获取单个字符?

获取Ruby中数组的差异

判断散列的键是否包含所有键集

为什么在安装 gem 时出现权限被拒绝错误?

何时在 Ruby 中使用 Struct 而不是 Hash?