-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.rb
147 lines (115 loc) · 2.57 KB
/
server.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
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
require 'sinatra'
require 'json'
require 'logger'
require 'pp'
webhook_url_prefix=ENV.fetch('WEBHOOK_URL_PREFIX', '')
LOGGER = Logger.new(STDOUT)
set :bind, "0.0.0.0"
set :port, 8000
set :logger, LOGGER
class GitCommit
attr_reader :webhook, :git_type
def initialize(user_agent:, webhook:)
@webhook = webhook
@git_type = if user_agent =~ /^Bitbucket-Webhooks\/2.0/
:bitbucket
elsif user_agent =~ /^GitHub-Hookshot/
:github
end
LOGGER.info "ready to go"
build if git_type
end
def bitbucket?
git_type == :bitbucket
end
def github?
git_type == :github
end
# should return latest commit id in git push
def commit_id
return @commit_id if @commit_id
@commit_id = if bitbucket?
webhook['push']['changes'].first['commits'].first['hash']
elsif github?
webhook['commits'].last['id']
end
end
def url
return @url if @url
@url = if bitbucket?
webhook['push']['changes'].first['commits'].first['links']['html']['href']
elsif github?
webhook['commits'].last['url']
end
end
def repository
url.gsub(/^https:\/\/(github.com|bitbucket.org)\//,'').gsub(/\/commit.+$/, '')
end
def builder
@@builder ||= {}
end
def build
return unless repository == 'andyk74/webhook-test'
if builder[repository].status
LOGGER.info "Still building #{repository}"
return
end
LOGGER.info "Start building #{repository}"
builder[repository] = Thread.start do
begin
log = `
cd /Development/docker/docker-build2 \
&& git fetch \
&& git checkout #{commit_id} \
&& docker-compose stop \
&& docker-compose rm -f \
&& docker-compose build --force-rm --pull \
&& docker-compose up -d
`
LOGGER.info "Build log: #{log.split}"
rescue => e
LOGGER.error "build error #{e}"
end
end
end
end
before do
begin
request.body.rewind
@params = JSON.parse(request.body.read)
rescue
logger.error "Can't parse JSON body"
@params
end
end
post "/#{webhook_url_prefix}" do
# logger.info "POST, params: #{params.inspect}"
ua = request.env['HTTP_USER_AGENT']
commit = GitCommit.new user_agent: ua, webhook: params
logger.info "User agent: #{ua}, commit id: #{commit.commit_id}, url: #{commit.url}, repository: #{commit.repository}"
nil
end
get /\S*/ do
nil
end
post /\S*/ do
nil
end
put /\S*/ do
nil
end
patch /\S*/ do
nil
end
delete /\S*/ do
nil
end
options /\S*/ do
nil
end
link /\S*/ do
nil
end
unlink /\S*/ do
nil
end