2 # Copyright (c) 2012 Eric S. Raymond <esr@thyrsus.com>
3 # Distributed under BSD terms.
5 # This script contains git porcelain and porcelain byproducts.
6 # Requires Python 2.6, or 2.5 with the simplejson library installed.
8 # usage: irkerhook.py [-V] [-n] [--variable=value...] [commit_id...]
10 # This script is meant to be run in an update or post-commit hook.
11 # Try it with -n to see the notification dumped to stdout and verify
12 # that it looks sane. With -V this script dumps its version and exits.
14 # See the irkerhook manual page in the distribution for a detailed
15 # explanation of how to configure this hook.
17 # The default location of the irker proxy, if the project configuration
18 # does not override it.
19 default_server = "localhost"
22 # The default service used to turn your web-view URL into a tinyurl so it
23 # will take up less space on the IRC notification line.
24 default_tinyifier = "http://tinyurl.com/api-create.php?url="
26 # Map magic urlprefix values to actual URL prefixes.
28 "viewcvs": "http://%(host)s/viewcvs/%(repo)s?view=revision&revision=",
29 "gitweb": "http://%(host)s/cgi-bin/gitweb.cgi?p=%(repo)s;a=commit;h=",
30 "cgit": "http://%(host)s/cgi-bin/cgit.cgi/%(repo)s/commit/?id=",
33 # By default, ship to the freenode #commits list
34 default_channels = "irc://chat.freenode.net/#commits"
37 # No user-serviceable parts below this line:
42 import os, sys, commands, socket, urllib, subprocess, locale
43 from pipes import quote as shellquote
45 import simplejson as json # Faster, also makes us Python-2.5-compatible
50 return unicode(commands.getstatusoutput(command)[1], locale.getpreferredencoding() or 'UTF-8')
53 def __init__(self, extractor, commit):
63 self.__dict__.update(extractor.__dict__)
64 def __unicode__(self):
65 "Produce a notification string from this commit."
66 if self.urlprefix.lower() == "none":
69 urlprefix = urlprefixmap.get(self.urlprefix, self.urlprefix)
70 webview = (urlprefix % self.__dict__) + self.commit
72 if urllib.urlopen(webview).getcode() == 404:
74 if self.tinyifier and self.tinyifier.lower() != "none":
76 # Didn't get a retrieval error or 404 on the web
77 # view, so try to tinyify a reference to it.
78 self.url = open(urllib.urlretrieve(self.tinyifier + webview)[0]).read()
85 return self.template % self.__dict__
87 class GenericExtractor:
88 "Generic class for encapsulating data from a VCS."
90 numerics = ["maxchannels"]
91 def __init__(self, arguments):
92 self.arguments = arguments
95 # These aren't really repo data but they belong here anyway...
97 self.tinyifier = default_tinyifier
102 self.urlprefix = None
103 self.host = socket.getfqdn()
105 self.filtercmd = None
106 # Color highlighting is disabled by default.
108 self.bold = self.green = self.blue = self.yellow = ""
109 self.brown = self.magenta = self.cyan = self.reset = ""
110 def activate_color(self, style):
113 # mIRC colors are mapped as closely to the ANSI colors as
114 # possible. However, bright colors (green, blue, red,
115 # yellow) have been made their dark counterparts since
116 # ChatZilla does not properly darken mIRC colors in the
117 # Light Motif color scheme.
119 self.green = '\x0303'
122 self.yellow = '\x0307'
123 self.brown = '\x0305'
124 self.magenta = '\x0306'
128 self.bold = '\x1b[1m'
129 self.green = '\x1b[1;32m'
130 self.blue = '\x1b[1;34m'
131 self.red = '\x1b[1;31m'
132 self.yellow = '\x1b[1;33m'
133 self.brown = '\x1b[33m'
134 self.magenta = '\x1b[35m'
135 self.cyan = '\x1b[36m'
136 self.reset = '\x1b[0m'
137 def load_preferences(self, conf):
138 "Load preferences from a file in the repository root."
139 if not os.path.exists(conf):
142 for line in open(conf):
144 if line.startswith("#") or not line.strip():
146 elif line.count('=') != 1:
147 sys.stderr.write('"%s", line %d: missing = in config line\n' \
150 fields = line.split('=')
152 sys.stderr.write('"%s", line %d: too many fields in config line\n' \
155 variable = fields[0].strip()
156 value = fields[1].strip()
157 if value.lower() == "true":
159 elif value.lower() == "false":
161 # User cannot set maxchannels - only a command-line arg can do that.
162 if variable == "maxchannels":
164 setattr(self, variable, value)
165 def do_overrides(self):
166 "Make command-line overrides possible."
167 for tok in self.arguments:
168 for key in self.__dict__:
169 if tok.startswith("--" + key + "="):
170 val = tok[len(key)+3:]
171 setattr(self, key, val)
172 for (key, val) in self.__dict__.items():
173 if key in GenericExtractor.booleans:
174 if type(val) == type("") and val.lower() == "true":
175 setattr(self, key, True)
176 elif type(val) == type("") and val.lower() == "false":
177 setattr(self, key, False)
178 elif key in GenericExtractor.numerics:
179 setattr(self, key, int(val))
181 sys.stderr.write("irkerhook.py: no project name set!\n")
184 self.repo = self.project.lower()
185 if not self.channels:
186 self.channels = default_channels % self.__dict__
187 if self.color and self.color.lower() != "none":
188 self.activate_color(self.color)
190 def has(dirname, paths):
191 "Test for existence of a list of paths."
192 return all([os.path.exists(os.path.join(dirname, x)) for x in paths])
194 # VCS-dependent code begins here
196 class GitExtractor(GenericExtractor):
197 "Metadata extraction for the git version control system."
199 def is_repository(dirname):
200 # Must detect both ordinary and bare repositories
201 return has(dirname, [".git"]) or \
202 has(dirname, ["HEAD", "refs", "objects"])
203 def __init__(self, arguments):
204 GenericExtractor.__init__(self, arguments)
205 # Get all global config variables
206 self.project = do("git config --get irker.project")
207 self.repo = do("git config --get irker.repo")
208 self.server = do("git config --get irker.server")
209 self.channels = do("git config --get irker.channels")
210 self.tcp = do("git config --bool --get irker.tcp")
211 self.template = '%(bold)s%(project)s:%(reset)s %(green)s%(author)s%(reset)s %(repo)s:%(yellow)s%(branch)s%(reset)s * %(bold)s%(rev)s%(reset)s / %(bold)s%(files)s%(reset)s: %(logmsg)s %(brown)s%(url)s%(reset)s'
212 self.tinyifier = do("git config --get irker.tinyifier") or default_tinyifier
213 self.color = do("git config --get irker.color")
214 self.urlprefix = do("git config --get irker.urlprefix") or "gitweb"
215 self.cialike = do("git config --get irker.cialike")
216 self.filtercmd = do("git config --get irker.filtercmd")
217 # These are git-specific
218 self.refname = do("git symbolic-ref HEAD 2>/dev/null")
219 self.revformat = do("git config --get irker.revformat")
220 # The project variable defaults to the name of the repository toplevel.
222 bare = do("git config --bool --get core.bare")
223 if bare.lower() == "true":
226 keyfile = ".git/HEAD"
229 if os.path.exists(os.path.join(here, keyfile)):
230 self.project = os.path.basename(here)
231 if self.project.endswith('.git'):
232 self.project = self.project[0:-4]
235 sys.stderr.write("irkerhook.py: no git repo below root!\n")
237 here = os.path.dirname(here)
241 "Return a symbolic reference to the tip commit of the current branch."
243 def commit_factory(self, commit_id):
244 "Make a Commit object holding data for a specified commit ID."
245 commit = Commit(self, commit_id)
246 commit.branch = os.path.basename(self.refname)
247 # Compute a description for the revision
248 if self.revformat == 'raw':
249 commit.rev = commit.commit
250 elif self.revformat == 'short':
252 else: # self.revformat == 'describe'
253 commit.rev = do("git describe %s 2>/dev/null" % shellquote(commit.commit))
255 commit.rev = commit.commit[:12]
256 # Extract the meta-information for the commit
257 commit.files = do("git diff-tree -r --name-only " + shellquote(commit.commit))
258 commit.files = " ".join(commit.files.strip().split("\n")[1:])
259 # Design choice: for git we ship only the first line, which is
260 # conventionally supposed to be a summary of the commit. Under
261 # other VCSes a different choice may be appropriate.
262 metainfo = do("git log -1 '--pretty=format:%an <%ae>|%s' " + shellquote(commit.commit))
263 (commit.author, commit.logmsg) = metainfo.split("|")
264 commit.mail = commit.author.split()[-1].strip("<>")
265 # This discards the part of the author's address after @.
266 # Might be be nice to ship the full email address, if not
267 # for spammers' address harvesters - getting this wrong
268 # would make the freenode #commits channel into harvester heaven.
269 commit.author = commit.mail.split("@")[0]
272 class SvnExtractor(GenericExtractor):
273 "Metadata extraction for the svn version control system."
275 def is_repository(dirname):
276 return has(dirname, ["format", "hooks", "locks"])
277 def __init__(self, arguments):
278 GenericExtractor.__init__(self, arguments)
279 # Some things we need to have before metadata queries will work
280 self.repository = '.'
281 for tok in arguments:
282 if tok.startswith("--repository="):
283 self.repository = tok[13:]
284 self.project = os.path.basename(self.repository)
285 self.template = '%(bold)s%(project)s%(reset)s: %(green)s%(author)s%(reset)s %(repo)s * %(bold)s%(rev)s%(reset)s / %(bold)s%(files)s%(reset)s: %(logmsg)s %(brown)s%(url)s%(reset)s'
286 self.urlprefix = "viewcvs"
287 self.load_preferences(os.path.join(self.repository, "irker.conf"))
290 sys.stderr.write("irker: under svn, hook requires a commit argument.\n")
292 def commit_factory(self, commit_id):
294 commit = Commit(self, commit_id)
296 commit.rev = "r%s" % self.id
297 commit.author = self.svnlook("author")
298 commit.files = self.svnlook("dirs-changed").strip().replace("\n", " ")
299 commit.logmsg = self.svnlook("log")
301 def svnlook(self, info):
302 return do("svnlook %s %s --revision %s" % (shellquote(info), shellquote(self.repository), shellquote(self.id)))
304 class HgExtractor(GenericExtractor):
305 "Metadata extraction for the Mercurial version control system."
307 def is_repository(directory):
308 return has(directory, [".hg"])
309 def __init__(self, arguments):
310 # This fiddling with arguments is necessary since the Mercurial hook can
311 # be run in two different ways: either directly via Python (in which
312 # case hg should be pointed to the hg_hook function below) or as a
313 # script (in which case the normal __main__ block at the end of this
314 # file is exercised). In the first case, we already get repository and
315 # ui objects from Mercurial, in the second case, we have to create them
316 # from the root path.
317 self.repository = None
318 if arguments and type(arguments[0]) == type(()):
319 # Called from hg_hook function
320 ui, self.repository = arguments[0]
321 arguments = [] # Should not be processed further by do_overrides
323 # Called from command line: create repo/ui objects
324 from mercurial import hg, ui as uimod
327 for tok in arguments:
328 if tok.startswith('--repository='):
331 ui.readconfig(os.path.join(repopath, '.hg', 'hgrc'), repopath)
332 self.repository = hg.repository(ui, repopath)
334 GenericExtractor.__init__(self, arguments)
335 # Extract global values from the hg configuration file(s)
336 self.project = ui.config('irker', 'project')
337 self.repo = ui.config('irker', 'repo')
338 self.server = ui.config('irker', 'server')
339 self.channels = ui.config('irker', 'channels')
340 self.tcp = str(ui.configbool('irker', 'tcp')) # converted to bool again in do_overrides
341 self.template = '%(bold)s%(project)s:%(reset)s %(green)s%(author)s%(reset)s %(repo)s:%(yellow)s%(branch)s%(reset)s * %(bold)s%(rev)s%(reset)s / %(bold)s%(files)s%(reset)s: %(logmsg)s %(brown)s%(url)s%(reset)s'
342 self.tinyifier = ui.config('irker', 'tinyifier') or default_tinyifier
343 self.color = ui.config('irker', 'color')
344 self.urlprefix = (ui.config('irker', 'urlprefix') or
345 ui.config('web', 'baseurl') or '')
347 # self.commit is appended to this by do_overrides
348 self.urlprefix = self.urlprefix.rstrip('/') + '/rev'
349 self.cialike = ui.config('irker', 'cialike')
350 self.filtercmd = ui.config('irker', 'filtercmd')
352 self.project = os.path.basename(self.repository.root.rstrip('/'))
355 "Return a symbolic reference to the tip commit of the current branch."
357 def commit_factory(self, commit_id):
358 "Make a Commit object holding data for a specified commit ID."
359 from mercurial.node import short
360 from mercurial.templatefilters import person
361 node = self.repository.lookup(commit_id)
362 commit = Commit(self, short(node))
363 # Extract commit-specific values from a "context" object
364 ctx = self.repository.changectx(node)
365 commit.rev = '%d:%s' % (ctx.rev(), commit.commit)
366 commit.branch = ctx.branch()
367 commit.author = person(ctx.user())
368 commit.logmsg = ctx.description()
369 # Extract changed files from status against first parent
370 st = self.repository.status(ctx.p1().node(), ctx.node())
371 commit.files = ' '.join(st[0] + st[1] + st[2])
374 def hg_hook(ui, repo, **kwds):
375 # To be called from a Mercurial "commit" or "incoming" hook. Example
378 # incoming.irker = python:/path/to/irkerhook.py:hg_hook
379 extractor = HgExtractor([(ui, repo)])
380 ship(extractor, kwds['node'], False)
382 # The files we use to identify a Subversion repo might occur as content
383 # in a git or hg repo, but the special subdirectories for those are more
384 # reliable indicators. So test for Subversion last.
385 extractors = [GitExtractor, HgExtractor, SvnExtractor]
387 # VCS-dependent code ends here
389 def ship(extractor, commit, debug):
390 "Ship a notification for the specified commit."
391 metadata = extractor.commit_factory(commit)
393 # This is where we apply filtering
394 if extractor.filtercmd:
395 cmd = '%s %s' % (shellquote(extractor.filtercmd),
396 shellquote(json.dumps(metadata.__dict__)))
397 data = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read()
399 metadata.__dict__.update(json.loads(data))
401 sys.stderr.write("irkerhook.py: could not decode JSON: %s\n" % data)
404 # Rewrite the file list if too long. The objective here is only
405 # to be easier on the eyes.
406 if extractor.cialike \
407 and extractor.cialike.lower() != "none" \
408 and len(metadata.files) > int(extractor.cialike):
409 files = metadata.files.split()
410 dirs = set([d.rpartition('/')[0] for d in files])
412 metadata.files = "(%s files)" % (len(files),)
414 metadata.files = "(%s files in %s dirs)" % (len(files), len(dirs))
415 # Message reduction. The assumption here is that IRC can't handle
416 # lines more than 510 characters long. If we exceed that length, we
417 # try knocking out the file list, on the theory that for notification
418 # purposes the commit text is more important. If it's still too long
419 # there's nothing much can be done other than ship it expecting the IRC
420 # server to truncate.
421 privmsg = unicode(metadata)
422 if len(privmsg) > 510:
424 privmsg = unicode(metadata)
426 # Anti-spamming guard. It's deliberate that we get maxchannels not from
427 # the user-filtered metadata but from the extractor data - means repo
428 # administrators can lock in that setting.
429 channels = metadata.channels.split(",")
430 if extractor.maxchannels != 0:
431 channels = channels[:extractor.maxchannels]
434 message = json.dumps({"to": channels, "privmsg": privmsg})
441 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
442 sock.connect((extractor.server or default_server, IRKER_PORT))
443 sock.sendall(message + "\n")
448 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
449 sock.sendto(message + "\n", (extractor.server or default_server, IRKER_PORT))
452 except socket.error, e:
453 sys.stderr.write("%s\n" % e)
455 if __name__ == "__main__":
457 repository = os.getcwd()
459 for arg in sys.argv[1:]:
463 print "irkerhook.py: version", version
465 elif arg.startswith("--repository="):
466 repository = arg[13:]
467 elif not arg.startswith("--"):
470 # Figure out which extractor we should be using
471 for candidate in extractors:
472 if candidate.is_repository(repository):
476 sys.stderr.write("irkerhook: cannot identify a repository type.\n")
478 extractor = cls(sys.argv[1:])
482 commits = [extractor.head()]
483 for commit in commits:
484 ship(extractor, commit, not notify)