-
Notifications
You must be signed in to change notification settings - Fork 0
/
gitmdf
executable file
·317 lines (276 loc) · 9.67 KB
/
gitmdf
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
#!/usr/bin/env ruby
require 'fileutils'
require 'json'
require 'logger'
require 'sinatra/base'
require 'yaml'
class GitNotifier
STATE_FILE = '.git-notifier.dat'
private
MAPPINGS = {
'from' => 'sender',
'to' => 'mailinglist',
'subject' => 'emailprefix',
'uri' => 'repouri'
}
public
def self.run(path, opts)
args = Hash[opts.map { |k, v| [MAPPINGS[k] || k, v] }]
success = execute(path, args)
$logger.error('git-notifier failed') unless success
success
end
private
def self.execute(path, args = [])
args = args.map do |k, v|
v = v * ',' if k == 'mailinglist'
next unless v
["--#{k}"] + (!!v == v ? [] : ["#{v}"]) # Ignore non-boolean values.
end
current = Dir.pwd()
success = true
Dir.chdir(path)
begin
$logger.debug('> git fetch origin +refs/heads/*:refs/heads/*')
success = system('git', 'fetch', 'origin', '+refs/heads/*:refs/heads/*')
raise "git fetch failed in #{path}" unless success
args = args.flatten.delete_if { |x| x.nil? }
$logger.debug("> git-notifier #{args}")
success = system('git-notifier', *args)
raise "git-notifier failed in #{path} with args: #{args}" unless success
rescue Exception => e
$logger.error(e)
end
Dir.chdir(current)
success
end
end
class GitMdf
def initialize(config)
@notifier = config['notifier']
@github = config['github']
@bitbucket = config['bitbucket']
@silent_init = config['gitmdf']['silent_init']
dir = config['gitmdf']['directory']
if dir != '.'
$logger.info("switching into working directory #{dir}")
Dir.mkdir(dir) unless Dir.exists?(dir)
Dir.chdir(dir)
end
end
def process_github(push)
opts = @notifier.clone
url = push['repository']['url']
user = push['repository']['owner']['name']
repo = push['repository']['name']
opts['link'] = "#{url}/compare/#{push['before']}...#{push['after']}"
$logger.info("received push from #{user}/#{repo} for commits "\
"#{push['before'][0..5]}...#{push['after'][0..5]}")
@github.each do |entry|
if "#{user}\/#{repo}" =~ Regexp.new(entry['id'])
opts.merge!(entry.reject { |k, v| k == 'id' || k == 'protocol'})
opts['uri'] ||= url
entry['protocol'] ||= 'git'
remote = case entry['protocol']
when /git/
"git://github.com/#{user}/#{repo}.git"
when /ssh/
"git@github.com:#{user}/#{repo}.git"
when /https/
"https://github.com/#{user}/#{repo}.git"
else
$logger.error("invalid protocol: #{entry['protocol']}")
next
end
dir = File.join(user, repo)
if not Dir.exists?(dir)
$logger.debug("> git clone --bare #{remote} #{dir}")
if not system('git', 'clone', '--bare', remote, dir)
$logger.error("git failed to clone repository #{user}/#{repo}")
FileUtils.rm_rf(dir) if File.exists?(dir)
return
end
# Do not keep empty user directories.
if Dir[File.join(user, '*')].empty?
Dir.rmdir(user)
end
end
state_file = File.join(dir, GitNotifier::STATE_FILE)
if @silent_init and not File.exists?(state_file)
$logger.info("configuring git-notifer for silent update")
opts['updateonly'] = true unless File.exists?(state_file)
end
return GitNotifier.run(dir, opts)
end
end
$logger.warn("no matching repository found for #{user}/#{repo}")
end
def process_bitbucket(push)
opts = @notifier.clone
url = push['repository']['links']['html']['href']
user = push['repository']['owner']['username']
repo = push['repository']['name']
push_before = push['push']['changes'][0]['old']['target']['hash']
push_after = push['push']['changes'][0]['new']['target']['hash']
opts['link'] = "#{url}/compare/#{push_before}...#{push_after}"
$logger.info("received push from #{user}/#{repo} for commits "\
"#{push_before[0..5]}...#{push_after[0..5]}")
@bitbucket.each do |entry|
if "#{user}\/#{repo}" =~ Regexp.new(entry['id'])
opts.merge!(entry.reject { |k, v| k == 'id' || k == 'protocol'})
opts['uri'] ||= url
entry['protocol'] ||= 'git'
remote = case entry['protocol']
when /git/
"git://bitbucket.org/#{user}/#{repo}.git"
when /ssh/
"git@bitbucket.org:#{user}/#{repo}.git"
when /https/
"https://bitbucket.org/#{user}/#{repo}.git"
else
$logger.error("invalid protocol: #{entry['protocol']}")
next
end
dir = File.join(user, repo)
if not Dir.exists?(dir)
$logger.debug("> git clone --bare #{remote} #{dir}")
if not system('git', 'clone', '--bare', remote, dir)
$logger.error("git failed to clone repository #{user}/#{repo}")
FileUtils.rm_rf(dir) if File.exists?(dir)
return
end
# Do not keep empty user directories.
if Dir[File.join(user, '*')].empty?
Dir.rmdir(user)
end
end
state_file = File.join(dir, GitNotifier::STATE_FILE)
if @silent_init and not File.exists?(state_file)
$logger.info("configuring git-notifer for silent update")
opts['updateonly'] = true unless File.exists?(state_file)
end
return GitNotifier.run(dir, opts)
end
end
$logger.warn("no matching repository found for #{user}/#{repo}")
end
end
class GitMdfServer < Sinatra::Base
configure do
set(:environment, :production)
set(:bind, settings.bind)
set(:port, settings.port)
end
get '/' do
"Use #{request.url} as WebHook URL in your GitHub or BitBucket repository settings."
end
post '/' do
sources = settings.allowed_sources
if not sources.empty? and not sources.include?(request.ip)
$logger.info("discarding request from disallowed address #{request.ip}")
return
end
if not params[:payload]
$logger.error('received POST request with empty payload; will try parsing request body')
else
json = JSON.parse(params[:payload])
if not json
$log.error('received invalid JSON:')
STDERR.puts(params[:payload])
else
STDERR.puts(JSON.pretty_generate(json)) if settings.debug_post
# Ideally we'd use the X-Github-Event header to distinguish a ping from
# an ordinary push. However, the 'headers' variable in Sinatra only
# contains Content-Type, so we introspect the JSON instead.
if json['zen']
$logger.debug('got ping from github')
else
settings.gitmdf.process_github(json)
end
end
end
# BitBucket WebHook API issue:
# https://bitbucket.org/site/master/issues/11537/webhooks-payload-empty
if not params[:payload]
request.body.rewind
request_payload = request.body.read
json = JSON.parse(request_payload)
if not json
$log.error('received invalid JSON:')
STDERR.puts(request_payload)
else
STDERR.puts(JSON.pretty_generate(json)) if settings.debug_post
settings.gitmdf.process_bitbucket(json)
end
end
end
end
def which(cmd)
ENV['PATH'].split(File::PATH_SEPARATOR).each do |path|
exe = "#{path}/#{cmd}"
return exe if File.executable?(exe)
end
nil
end
def run(config)
GitMdfServer.set(:gitmdf, GitMdf.new(config))
GitMdfServer.set(:bind, config['gitmdf']['bind'])
GitMdfServer.set(:port, config['gitmdf']['port'])
GitMdfServer.set(:debug_post, config['gitmdf']['debug'])
GitMdfServer.set(:allowed_sources, config['gitmdf']['allowed_sources'])
if not config['gitmdf']['ssl']['enable']
Sinatra.new(GitMdfServer).run!
else
require 'webrick/https'
require 'openssl'
cert = File.open(config['gitmdf']['ssl']['cert']).read
key = File.open(config['gitmdf']['ssl']['key']).read
webrick_options = {
app: GitMdfServer,
BindAddress: config['gitmdf']['bind'],
Port: config['gitmdf']['port'],
Logger: $logger,
SSLEnable: true,
SSLCertificate: OpenSSL::X509::Certificate.new(cert),
SSLPrivateKey: OpenSSL::PKey::RSA.new(key),
SSLCertName: [['CN', WEBrick::Utils::getservername]]
}
Rack::Server.start(webrick_options)
end
end
if __FILE__ == $0
$logger = Logger.new(STDERR)
$logger.formatter = proc do |severity, datetime, progname, msg|
time = datetime.strftime('%Y-%m-%d %H:%M:%S')
"[#{time}] #{severity}#{' ' * (5 - severity.size + 1)} | #{msg}\n"
end
unless which('git-notifier')
$logger.error('could not find git-notifier in $PATH')
exit 1
end
if ARGV.size() != 1
STDERR.puts "usage: #{$0} <config.yml>"
exit 1
end
file = File.absolute_path(ARGV[0])
config = YAML.load_file(file)
sinatra = Thread.new { run(config) }
if config['gitmdf']['monitor'] > 0
last_modified = Time.at(0)
loop do
mtime = File.mtime(file)
if mtime > last_modified
last_modified = mtime
$logger.info("re-reading configuration file")
config = YAML.load_file(file)
GitMdfServer.set(:gitmdf, GitMdf.new(config))
GitMdfServer.set(:debug_post, config['gitmdf']['debug'])
GitMdfServer.set(:allowed_sources, config['gitmdf']['allowed_sources'])
break if config['gitmdf']['monitor'] == 0
end
break unless sinatra.alive?
sleep(config['gitmdf']['monitor'])
end
end
sinatra.join
end