forked from sds/overcommit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
protected_branches.rb
74 lines (60 loc) · 1.75 KB
/
protected_branches.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
# frozen_string_literal: true
module Overcommit::Hook::PrePush
# Prevents updates to specified branches.
# Accepts a 'destructive_only' option globally or per branch
# to only prevent destructive updates.
class ProtectedBranches < Base
def run
return :pass unless illegal_pushes.any?
messages = illegal_pushes.map do |pushed_ref|
"Deleting or force-pushing to #{pushed_ref.remote_ref} is not allowed."
end
[:fail, messages.join("\n")]
end
private
def illegal_pushes
@illegal_pushes ||= pushed_refs.select do |pushed_ref|
protected?(pushed_ref)
end
end
def protected?(ref)
find_pattern(ref.remote_ref)&.destructive?(ref)
end
def find_pattern(remote_ref)
ref_name = remote_ref[%r{refs/heads/(.*)}, 1]
return if ref_name.nil?
patterns.find do |pattern|
File.fnmatch(pattern.to_s, ref_name)
end
end
def patterns
@patterns ||= fetch_patterns
end
def fetch_patterns
branch_configurations.map do |pattern|
if pattern.is_a?(Hash)
Pattern.new(pattern.keys.first, pattern['destructive_only'])
else
Pattern.new(pattern, global_destructive_only?)
end
end
end
def branch_configurations
config['branches'].to_a + config['branch_patterns'].to_a
end
def global_destructive_only?
config['destructive_only'].nil? || config['destructive_only']
end
Pattern = Struct.new('Pattern', :name, :destructive_only) do
alias_method :to_s, :name
alias_method :destructive_only?, :destructive_only
def destructive?(ref)
if destructive_only?
ref.destructive?
else
true
end
end
end
end
end