【发布时间】:2016-09-21 18:18:56
【问题描述】:
我正在编写一个自定义 RuboCop 插件来强制执行 Berksfile 中的特定 URL。我目前可能已经超出了我有限的 Ruby 知识所能支持的范围。
这是一些伪代码。我什至接近吗?
config/default.yml:
ACME/ApprovedSupermarkets:
Description: 'Enforce the use of only authorized Chef Supermarkets.'
Enabled: true
Include:
- '**/Berksfile'
Severity: error
Sources:
- 'https://supermarket.acme.com'
- 'https://supermarket.trusted.com'
lib/rubocop/cop/acme/approved_supermarkets.rb
# encoding: utf-8
# frozen_string_literal: true
require 'uri'
module RuboCop
module Cop
module ACME
# This cop checks that only allowed supermarkets are used within Berksfiles.
class ApprovedSupermarkets < Cop
MSG = 'Only the use of authorized Chef Supermarkets are allowed.'.freeze
def investigate(processed_source)
processed_source.lines.each_with_index do |line, index|
check_line(line, index)
end
end
def check_line(line, index)
return if match_uris(line)
add_offense(nil, index, MSG)
end
def match_uris(string)
matches = []
string.scan(uri_regexp) do
matches << $LAST_MATCH_INFO if valid_uri?($LAST_MATCH_INFO[0])
end
matches
end
def valid_uri?(uri_ish_string)
URI.parse(uri_ish_string)
true
rescue
false
end
def uri_regexp
@regexp ||= URI.regexp(cop_config['Sources'])
end
end
end
end
end
spec/rubocop/cop/acme/approved_supermarkets_spec.rb:
# encoding: utf-8
require 'spec_helper'
describe Rubocop::Cop::ACME::ApprovedSupermarkets do
subject(:cop) { described_class.new }
let(:cop_config) { cop_config }
cop_config['Sources'].each do |source|
it 'accepts #{source} as an authorized supermarket' do
inspect_source(cop, "source '#{source}'")
expect(cop.offenses).to be_empty
end
end
end
Berksfile(应该会失败)
source 'https://supermarket.untrusted.com'
metadata
我们想写几个其他的内部警察,这就是为什么我选择开发一个 RuboCop 插件而不是向 RuboCop 项目添加一个问题。任何帮助表示赞赏。
【问题讨论】:
标签: ruby chef-infra rubocop