blob: eff0d45fe191aa9f464a41c82c8ccde4b4495398 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
# frozen_string_literal: true
module RuboCop
module Cop
module Rake
# Flag global `require`s or `require_relative`s in rake files.
#
# Load dependencies lazily in `task` definitions if possible.
#
# @example
# # bad
#
# require_relative 'gitlab/json'
# require 'json'
#
# task :parse_json do
# Gitlab::Json.parse(...)
# end
#
# # good
#
# task :parse_json do
# require_relative 'gitlab/json'
# require 'json'
#
# Gitlab::Json.parse(...)
# end
#
# RSpec::Core::RakeTask.new(:parse_json) do |t, args|
# require_relative 'gitlab/json'
# require 'json'
#
# Gitlab::Json.parse(...)
# end
#
# # Requiring files which contain the word `task` is allowed.
# require 'some_gem/rake_task'
# require 'some_gem/rake_tasks'
#
# SomeGem.define_tasks
#
# # Loading in method definition as well.
# def load_deps
# require 'json'
# end
#
# task :parse_json
# load_deps
# end
#
class Require < RuboCop::Cop::Base
MSG = 'Load dependencies inside `task` definitions if possible.'
METHODS = %i[require require_relative].freeze
RESTRICT_ON_SEND = METHODS
def_node_matcher :require_method, <<~PATTERN
(send nil? ${#{METHODS.map(&:inspect).join(' ')}} $_)
PATTERN
def on_send(node)
return unless in_rake_file?(node)
method, file = require_method(node)
return unless method
return if requires_task?(file)
return if inside_block_or_method?(node)
add_offense(node)
end
private
def in_rake_file?(node)
File.extname(filepath(node)) == '.rake'
end
def filepath(node)
node.location.expression.source_buffer.name
end
# Allow `require "foo/rake_task"`
def requires_task?(file)
file.source.include?('task')
end
def inside_block_or_method?(node)
node.each_ancestor(:block, :def).any?
end
end
end
end
end
|