-
Notifications
You must be signed in to change notification settings - Fork 4
/
post-commit
executable file
·113 lines (89 loc) · 2.62 KB
/
post-commit
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
#!/usr/bin/env ruby
# encoding: UTF-8
require 'net/https'
require 'json'
class GitLogs
attr_accessor :raw_log, :commit_data
def initialize
self.raw_log = `git log --no-color --format='Commit: %h%nAuthor: %aN <%aE>%nMessage: %s%nRefs: %d' -1`.force_encoding('utf-8')
# Example git formatted log output:
#
# Commit: 8872e8fe03a10238d7be84d78813874d79ce0c3d
# Author: John Doe <john.doe@unknown.com>
# Message: [#90743834] test new v5 hook addition
# Refs: (HEAD, feature/hook-test)
parse!
self
end
def parse!
regexp = /Commit:\ (.*)\nAuthor:\ (.*)\nMessage:\ (.*)\nRefs:\ \ \((.*)\)/i
match = raw_log.scan(regexp).flatten
self.commit_data = GitLog.new(match[0], match[1], match[2], match[3])
end
def pivotal_sync!
Pivotal.new(commit_data).send! if commit_has_story_id?
end
def commit_has_story_id?
# somewhere between square brackets there has to be a hash followed by multiple digits
!commit_data.message.scan(/\[*+\#(\d+)\D?(.*)\]/).empty?
end
end
class GitLog
attr_accessor :hash, :author, :message, :refs
def initialize hash, author, message, refs
self.hash = hash
self.author = author
self.refs = refs
self.message = message
updated_message
end
def updated_message
return message if ids_from_refs.empty?
ids = ids_from_refs.join(' ')
self.message = if message.scan(/\[(.+)\]/).empty?
"[#{ids}] #{message}"
else
index = message.index('[') + 1
message.insert index, "#{ids} "
end
end
def ids_from_refs
ref_array = refs.split(',')
ref_array.each_with_object([]) do |result, ref|
id = ref.scan(/\#(\d+)/).flatten
result << "##{id.first}" unless id.empty?
result
end.flatten.uniq
end
def to_json
{ source_commit:
{ commit_id: self.hash,
author: self.author,
message: self.message,
}
}.to_json
end
end
class Pivotal
attr_accessor :git_log, :tracker_token
BASE_URI = URI('https://www.pivotaltracker.com/')
def initialize git_log
self.git_log = git_log
self.tracker_token = get_token
end
def get_token
`git config --get pivotal.token`.strip
end
def send!
https = Net::HTTP.start(BASE_URI.host, 443, {
use_ssl: true,
verify_mode: OpenSSL::SSL::VERIFY_NONE
})
request = Net::HTTP::Post.new('/services/v5/source_commits')
request['X-TrackerToken'] = tracker_token
request['Content-type'] = 'application/json'
request.body = git_log.to_json
response = https.request(request)
end
end
GitLogs.new().pivotal_sync!