3 # This script expects one line for each new revision on the form
4 # <oldrev> <newrev> <refname>
7 # aa453216d1b3e49e7f6f98441fa56946ddcd6a20
8 # 68f7abf4e6f922807889f52bc043ecd31b79f814 refs/heads/master
10 # Each of these changes will be passed to the buildbot server along
11 # with any other change information we manage to extract from the
14 # This script is meant to be run from hooks/post-receive in the git
15 # repository. It can also be run at client side with hooks/post-merge
16 # after using this wrapper:
19 # PRE=$(git rev-parse 'HEAD@{1}')
20 # POST=$(git rev-parse HEAD)
21 # SYMNAME=$(git rev-parse --symbolic-full-name HEAD)
22 # echo "$PRE $POST $SYMNAME" | git_buildbot.py
24 # Largely based on contrib/hooks/post-receive-email from git.
32 from twisted.spread import pb
33 from twisted.cred import credentials
34 from twisted.internet import reactor
36 from buildbot.scripts import runner
37 from optparse import OptionParser
39 # Modify this to fit your setup, or pass in --master server:host on the
42 master = "localhost:9989"
44 # When sending the notification, send this category iff
45 # it's set (via --category)
50 # The GIT_DIR environment variable must have been set up so that any
51 # git commands that are executed will operate on the repository we're
57 def connectFailed(error):
58 logging.error("Could not connect to %s: %s"
59 % (master, error.getErrorMessage()))
63 def addChange(remote, changei):
64 logging.debug("addChange %s, %s" % (repr(remote), repr(changei)))
68 remote.broker.transport.loseConnection()
71 logging.info("New revision: %s" % c['revision'][:8])
72 for key, value in c.iteritems():
73 logging.debug(" %s: %s" % (key, value))
75 d = remote.callRemote('addChange', c)
77 # tail recursion in Twisted can blow out the stack, so we
78 # insert a callLater to delay things
80 reactor.callLater(0, addChange, remote, changei)
81 d.addCallback(recurseLater)
85 def connected(remote):
86 return addChange(remote, changes.__iter__())
89 def grab_commit_info(c, rev):
90 # Extract information about committer and files using git show
91 f = os.popen("git show --raw --pretty=full %s" % rev, 'r')
100 m = re.match(r"^:.*[MAD]\s+(.+)$", line)
102 logging.debug("Got file: %s" % m.group(1))
103 files.append(m.group(1))
106 m = re.match(r"^Author:\s+(.+)$", line)
108 logging.debug("Got author: %s" % m.group(1))
109 c['who'] = m.group(1)
111 if re.match(r"^Merge: .*$", line):
112 files.append('merge')
117 logging.warning("git show exited with status %d" % status)
120 def gen_changes(input, branch):
122 line = input.readline()
126 logging.debug("Change: %s" % line)
128 m = re.match(r"^([0-9a-f]+) (.*)$", line.strip())
129 c = {'revision': m.group(1),
130 'comments': m.group(2),
134 c['category'] = category
135 grab_commit_info(c, m.group(1))
139 def gen_create_branch_changes(newrev, refname, branch):
140 # A new branch has been created. Generate changes for everything
141 # up to `newrev' which does not exist in any branch but `refname'.
143 # Note that this may be inaccurate if two new branches are created
144 # at the same time, pointing to the same commit, or if there are
145 # commits that only exists in a common subset of the new branches.
147 logging.info("Branch `%s' created" % branch)
149 f = os.popen("git rev-parse --not --branches"
150 + "| grep -v $(git rev-parse %s)" % refname
151 + "| git rev-list --reverse --pretty=oneline --stdin %s" % newrev,
154 gen_changes(f, branch)
158 logging.warning("git rev-list exited with status %d" % status)
161 def gen_update_branch_changes(oldrev, newrev, refname, branch):
162 # A branch has been updated. If it was a fast-forward update,
163 # generate Change events for everything between oldrev and newrev.
165 # In case of a forced update, first generate a "fake" Change event
166 # rewinding the branch to the common ancestor of oldrev and
167 # newrev. Then, generate Change events for each commit between the
168 # common ancestor and newrev.
170 logging.info("Branch `%s' updated %s .. %s"
171 % (branch, oldrev[:8], newrev[:8]))
173 baserev = commands.getoutput("git merge-base %s %s" % (oldrev, newrev))
174 logging.debug("oldrev=%s newrev=%s baserev=%s" % (oldrev, newrev, baserev))
175 if baserev != oldrev:
176 c = {'revision': baserev,
177 'comments': "Rewind branch",
181 logging.info("Branch %s was rewound to %s" % (branch, baserev[:8]))
183 f = os.popen("git diff --raw %s..%s" % (oldrev, baserev), 'r')
189 file = re.match(r"^:.*[MAD]\s*(.+)$", line).group(1)
190 logging.debug(" Rewound file: %s" % file)
195 logging.warning("git diff exited with status %d" % status)
198 c['category'] = category
204 if newrev != baserev:
206 f = os.popen("git rev-list --reverse --pretty=oneline %s..%s"
207 % (baserev, newrev), 'r')
208 gen_changes(f, branch)
212 logging.warning("git rev-list exited with status %d" % status)
219 def process_changes():
220 # Read branch updates from stdin and generate Change events
222 line = sys.stdin.readline()
226 [oldrev, newrev, refname] = line.split(None, 2)
228 # We only care about regular heads, i.e. branches
229 m = re.match(r"^refs\/heads\/(.+)$", refname)
231 logging.info("Ignoring refname `%s': Not a branch" % refname)
236 # Find out if the branch was created, deleted or updated. Branches
237 # being deleted aren't really interesting.
238 if re.match(r"^0*$", newrev):
239 logging.info("Branch `%s' deleted, ignoring" % branch)
241 elif re.match(r"^0*$", oldrev):
242 gen_create_branch_changes(newrev, refname, branch)
244 gen_update_branch_changes(oldrev, newrev, refname, branch)
246 # Submit the changes, if any
248 logging.warning("No changes found")
251 host, port = master.split(':')
254 f = pb.PBClientFactory()
255 d = f.login(credentials.UsernamePassword("change", "changepw"))
256 reactor.connectTCP(host, port, f)
258 d.addErrback(connectFailed)
259 d.addCallback(connected)
266 parser = OptionParser()
267 parser.add_option("-l", "--logfile", action="store", type="string",
268 help="Log to the specified file")
269 parser.add_option("-v", "--verbose", action="count",
270 help="Be more verbose. Ignored if -l is not specified.")
271 master_help = ("Build master to push to. Default is %(master)s" %
272 { 'master' : master })
273 parser.add_option("-m", "--master", action="store", type="string",
275 parser.add_option("-c", "--category", action="store",
276 type="string", help="Scheduler category to notify.")
277 options, args = parser.parse_args()
281 # Log errors and critical messages to stderr. Optionally log
282 # information to a file as well (we'll set that up later.)
283 stderr = logging.StreamHandler(sys.stderr)
284 fmt = logging.Formatter("git_buildbot: %(levelname)s: %(message)s")
285 stderr.setLevel(logging.ERROR)
286 stderr.setFormatter(fmt)
287 logging.getLogger().addHandler(stderr)
288 logging.getLogger().setLevel(logging.DEBUG)
291 options = parse_options()
292 level = logging.WARNING
294 level -= 10 * options.verbose
299 logfile = logging.FileHandler(options.logfile)
300 logfile.setLevel(level)
301 fmt = logging.Formatter("%(asctime)s %(levelname)s: %(message)s")
302 logfile.setFormatter(fmt)
303 logging.getLogger().addHandler(logfile)
306 master=options.master
309 category = options.category
315 logging.exception("Unhandled exception")