-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpre-commit.rb
111 lines (87 loc) · 1.69 KB
/
pre-commit.rb
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#!/usr/bin/env ruby
class GitDiff
attr_reader :filenames
def initialize
@filenames = `git diff --cached --name-only --diff-filter=ACM`.split("\n")
end
end
class Check
attr_reader :diff, :exit_status, :files
def initialize(diff)
@diff = diff
end
def check
before_run
puts "Running \033[1;34m#{self.class}#check\e[0m: #{command}"
report_error unless run
after_run
end
def before_run
end
def after_run
end
def files
@files ||= Array(diff.filenames)
end
def run
if files.empty?
puts "Diff does not contain relevant files. \033[0;33m [SKIPPED]\e[0m"
true
else
run_command
end
end
def run_command
system(command)
end
def command
raise NotImplementedError
end
def report_error
raise NotImplementedError
end
private
def select_files(extension:)
@files = diff.filenames.select { |filename| File.extname(filename) == ".#{extension}" }
end
end
class Keywords < Check
BAD = %w(
binding.pry
throw
console.log
debugger
)
def run_command
result = `#{command}`
puts result
report_error unless result.empty?
result.empty?
end
def command
%(git diff --cached -G"#{BAD.join('|')}" #{files.join(' ')})
end
def report_error
puts "There are files that contain this keywords: #{BAD.join(', ')}.\n"
exit 1
end
end
class Rubocop < Check
def before_run
@files = select_files(extension: :rb)
end
def command
"rubocop #{files.join(' ')}"
end
def report_error
puts "Rubocop reported some offenses. Aborting commit"
exit 1
end
end
diff = GitDiff.new
[
Keywords,
Rubocop
].each do |klass|
klass.new(diff).check
end