Python 2.5 compatibility
[irker.git] / irkerhook.py
1 #!/usr/bin/env python
2 # Copyright (c) 2012 Eric S. Raymond <esr@thyrsus.com>
3 # Distributed under BSD terms.
4 #
5 # This script contains git porcelain and porcelain byproducts.
6 # Requires Python 2.6, or 2.5 with the simplejson library installed.
7 #
8 # usage: irkerhook.py [-V] [-n] [--variable=value...] [commit_id...]
9 #
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.
13 #
14 # See the irkerhook manual page in the distribution for a detailed
15 # explanation of how to configure this hook.
16
17 # The default location of the irker proxy, if the project configuration
18 # does not override it.
19 default_server = "localhost"
20 IRKER_PORT = 6659
21
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="
25
26 # Map magic urlprefix values to actual URL prefixes.
27 urlprefixmap = {
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=",
31     }
32
33 # By default, ship to the freenode #commits list 
34 default_channels = "irc://chat.freenode.net/#commits"
35
36 #
37 # No user-serviceable parts below this line:
38 #
39
40 version = "1.17"
41
42 import os, sys, commands, socket, urllib, subprocess, locale, datetime
43 from pipes import quote as shellquote
44 try:
45     import simplejson as json   # Faster, also makes us Python-2.5-compatible
46 except ImportError:
47     import json
48
49 def do(command):
50     return unicode(commands.getstatusoutput(command)[1], locale.getlocale()[1] or 'UTF-8').encode(locale.getlocale()[1] or 'UTF-8')
51
52 class Commit:
53     def __init__(self, extractor, commit):
54         "Per-commit data."
55         self.commit = commit
56         self.branch = None
57         self.rev = None
58         self.mail = None
59         self.author = None
60         self.files = None
61         self.logmsg = None
62         self.url = None
63         self.author_date = None
64         self.commit_date = None
65         self.__dict__.update(extractor.__dict__)
66     def __unicode__(self):
67         "Produce a notification string from this commit."
68         if self.urlprefix.lower() == "none":
69             self.url = ""
70         else:
71             urlprefix = urlprefixmap.get(self.urlprefix, self.urlprefix) 
72             webview = (urlprefix % self.__dict__) + self.commit
73             try:
74                 if urllib.urlopen(webview).getcode() == 404:
75                     raise IOError
76                 if self.tinyifier and self.tinyifier.lower() != "none":
77                     try:
78                         # Didn't get a retrieval error or 404 on the web
79                         # view, so try to tinyify a reference to it.
80                         self.url = open(urllib.urlretrieve(self.tinyifier + webview)[0]).read()
81                         try:
82                             self.url = self.url.decode('UTF-8')
83                         except UnicodeError:
84                             pass
85                     except IOError:
86                         self.url = webview
87                 else:
88                     self.url = webview
89             except IOError:
90                 self.url = ""
91         return self.template % self.__dict__
92
93 class GenericExtractor:
94     "Generic class for encapsulating data from a VCS."
95     booleans = ["tcp"]
96     numerics = ["maxchannels"]
97     def __init__(self, arguments):
98         self.arguments = arguments
99         self.project = None
100         self.repo = None
101         # These aren't really repo data but they belong here anyway...
102         self.tcp = True
103         self.tinyifier = default_tinyifier
104         self.server = None
105         self.channels = None
106         self.maxchannels = 0
107         self.template = None
108         self.urlprefix = None
109         self.host = socket.getfqdn()
110         self.cialike = None
111         self.filtercmd = None
112         # Color highlighting is disabled by default.
113         self.color = None
114         self.bold = self.green = self.blue = self.yellow = ""
115         self.brown = self.magenta = self.cyan = self.reset = ""
116     def activate_color(self, style):
117         "IRC color codes."
118         if style == 'mIRC':
119             # mIRC colors are mapped as closely to the ANSI colors as
120             # possible.  However, bright colors (green, blue, red,
121             # yellow) have been made their dark counterparts since
122             # ChatZilla does not properly darken mIRC colors in the
123             # Light Motif color scheme.
124             self.bold = '\x02'
125             self.green = '\x0303'
126             self.blue = '\x0302'
127             self.red = '\x0305'
128             self.yellow = '\x0307'
129             self.brown = '\x0305'
130             self.magenta = '\x0306'
131             self.cyan = '\x0310'
132             self.reset = '\x0F'
133         if style == 'ANSI':
134             self.bold = '\x1b[1m'
135             self.green = '\x1b[1;32m'
136             self.blue = '\x1b[1;34m'
137             self.red =  '\x1b[1;31m'
138             self.yellow = '\x1b[1;33m'
139             self.brown = '\x1b[33m'
140             self.magenta = '\x1b[35m'
141             self.cyan = '\x1b[36m'
142             self.reset = '\x1b[0m'
143     def load_preferences(self, conf):
144         "Load preferences from a file in the repository root."
145         if not os.path.exists(conf):
146             return
147         ln = 0
148         for line in open(conf):
149             ln += 1
150             if line.startswith("#") or not line.strip():
151                 continue
152             elif line.count('=') != 1:
153                 sys.stderr.write('"%s", line %d: missing = in config line\n' \
154                                  % (conf, ln))
155                 continue
156             fields = line.split('=')
157             if len(fields) != 2:
158                 sys.stderr.write('"%s", line %d: too many fields in config line\n' \
159                                  % (conf, ln))
160                 continue
161             variable = fields[0].strip()
162             value = fields[1].strip()
163             if value.lower() == "true":
164                 value = True
165             elif value.lower() == "false":
166                 value = False
167             # User cannot set maxchannels - only a command-line arg can do that.
168             if variable == "maxchannels":
169                 return
170             setattr(self, variable, value)
171     def do_overrides(self):
172         "Make command-line overrides possible."
173         for tok in self.arguments:
174             for key in self.__dict__:
175                 if tok.startswith("--" + key + "="):
176                     val = tok[len(key)+3:]
177                     setattr(self, key, val)
178         for (key, val) in self.__dict__.items():
179             if key in GenericExtractor.booleans:
180                 if type(val) == type("") and val.lower() == "true":
181                     setattr(self, key, True)
182                 elif type(val) == type("") and val.lower() == "false":
183                     setattr(self, key, False)
184             elif key in GenericExtractor.numerics:
185                 setattr(self, key, int(val))
186         if not self.project:
187             sys.stderr.write("irkerhook.py: no project name set!\n")
188             raise SystemExit(1)
189         if not self.repo:
190             self.repo = self.project.lower()
191         if not self.channels:
192             self.channels = default_channels % self.__dict__
193         if self.color and self.color.lower() != "none":
194             self.activate_color(self.color)
195
196 def has(dirname, paths):
197     "Test for existence of a list of paths."
198     return all([os.path.exists(os.path.join(dirname, x)) for x in paths])
199
200 # VCS-dependent code begins here
201
202 class GitExtractor(GenericExtractor):
203     "Metadata extraction for the git version control system."
204     @staticmethod
205     def is_repository(dirname):
206         # Must detect both ordinary and bare repositories
207         return has(dirname, [".git"]) or \
208                has(dirname, ["HEAD", "refs", "objects"])
209     def __init__(self, arguments):
210         GenericExtractor.__init__(self, arguments)
211         # Get all global config variables
212         self.project = do("git config --get irker.project")
213         self.repo = do("git config --get irker.repo")
214         self.server = do("git config --get irker.server")
215         self.channels = do("git config --get irker.channels")
216         self.tcp = do("git config --bool --get irker.tcp")
217         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'
218         self.tinyifier = do("git config --get irker.tinyifier") or default_tinyifier
219         self.color = do("git config --get irker.color")
220         self.urlprefix = do("git config --get irker.urlprefix") or "gitweb"
221         self.cialike = do("git config --get irker.cialike")
222         self.filtercmd = do("git config --get irker.filtercmd")
223         # These are git-specific
224         self.refname = do("git symbolic-ref HEAD 2>/dev/null")
225         self.revformat = do("git config --get irker.revformat")
226         # The project variable defaults to the name of the repository toplevel.
227         if not self.project:
228             bare = do("git config --bool --get core.bare")
229             if bare.lower() == "true":
230                 keyfile = "HEAD"
231             else:
232                 keyfile = ".git/HEAD"
233             here = os.getcwd()
234             while True:
235                 if os.path.exists(os.path.join(here, keyfile)):
236                     self.project = os.path.basename(here)
237                     if self.project.endswith('.git'):
238                         self.project = self.project[0:-4]
239                     break
240                 elif here == '/':
241                     sys.stderr.write("irkerhook.py: no git repo below root!\n")
242                     sys.exit(1)
243                 here = os.path.dirname(here)
244         # Get overrides
245         self.do_overrides()
246     def head(self):
247         "Return a symbolic reference to the tip commit of the current branch."
248         return "HEAD"
249     def commit_factory(self, commit_id):
250         "Make a Commit object holding data for a specified commit ID."
251         commit = Commit(self, commit_id)
252         commit.branch = os.path.basename(self.refname)
253         # Compute a description for the revision
254         if self.revformat == 'raw':
255             commit.rev = commit.commit
256         elif self.revformat == 'short':
257             commit.rev = ''
258         else: # self.revformat == 'describe'
259             commit.rev = do("git describe %s 2>/dev/null" % shellquote(commit.commit))
260         if not commit.rev:
261             commit.rev = commit.commit[:12]
262         # Extract the meta-information for the commit
263         commit.files = do("git diff-tree -r --name-only " + shellquote(commit.commit))
264         commit.files = " ".join(commit.files.strip().split("\n")[1:])
265         # Design choice: for git we ship only the first line, which is
266         # conventionally supposed to be a summary of the commit.  Under
267         # other VCSes a different choice may be appropriate.
268         metainfo = do("git log -1 '--pretty=format:%an <%ae>|%s' " + shellquote(commit.commit))
269         (commit.author, _, commit.logmsg) = metainfo.partition("|")
270         commit.mail = commit.author.split()[-1].strip("<>")
271         # This discards the part of the author's address after @.
272         # Might be be nice to ship the full email address, if not
273         # for spammers' address harvesters - getting this wrong
274         # would make the freenode #commits channel into harvester heaven.
275         commit.author = commit.mail.split("@")[0]
276         commit.author_date, commit.commit_date = \
277             do("git log -1 '--pretty=format:%ai|%ci' " + shellquote(commit.commit)).split("|")
278         return commit
279
280 class SvnExtractor(GenericExtractor):
281     "Metadata extraction for the svn version control system."
282     @staticmethod
283     def is_repository(dirname):
284         return has(dirname, ["format", "hooks", "locks"])
285     def __init__(self, arguments):
286         GenericExtractor.__init__(self, arguments)
287         # Some things we need to have before metadata queries will work
288         self.repository = '.'
289         for tok in arguments:
290             if tok.startswith("--repository="):
291                 self.repository = tok[13:]
292         self.project = os.path.basename(self.repository)
293         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'
294         self.urlprefix = "viewcvs"
295         self.load_preferences(os.path.join(self.repository, "irker.conf"))
296         self.do_overrides()
297     def head(self):
298         sys.stderr.write("irker: under svn, hook requires a commit argument.\n")
299         raise SystemExit(1)
300     def commit_factory(self, commit_id):
301         self.id = commit_id
302         commit = Commit(self, commit_id)
303         commit.branch = ""
304         commit.rev = "r%s" % self.id
305         commit.author = self.svnlook("author")
306         commit.commit_date = self.svnlook("date").partition('(')[0]
307         commit.files = self.svnlook("dirs-changed").strip().replace("\n", " ")
308         commit.logmsg = self.svnlook("log").strip()
309         return commit
310     def svnlook(self, info):
311         return do("svnlook %s %s --revision %s" % (shellquote(info), shellquote(self.repository), shellquote(self.id)))
312
313 class HgExtractor(GenericExtractor):
314     "Metadata extraction for the Mercurial version control system."
315     @staticmethod
316     def is_repository(directory):
317         return has(directory, [".hg"])
318     def __init__(self, arguments):
319         # This fiddling with arguments is necessary since the Mercurial hook can
320         # be run in two different ways: either directly via Python (in which
321         # case hg should be pointed to the hg_hook function below) or as a
322         # script (in which case the normal __main__ block at the end of this
323         # file is exercised).  In the first case, we already get repository and
324         # ui objects from Mercurial, in the second case, we have to create them
325         # from the root path.
326         self.repository = None
327         if arguments and type(arguments[0]) == type(()):
328             # Called from hg_hook function
329             ui, self.repository = arguments[0]
330             arguments = []  # Should not be processed further by do_overrides
331         else:
332             # Called from command line: create repo/ui objects
333             from mercurial import hg, ui as uimod
334
335             repopath = '.'
336             for tok in arguments:
337                 if tok.startswith('--repository='):
338                     repopath = tok[13:]
339             ui = uimod.ui()
340             ui.readconfig(os.path.join(repopath, '.hg', 'hgrc'), repopath)
341             self.repository = hg.repository(ui, repopath)
342
343         GenericExtractor.__init__(self, arguments)
344         # Extract global values from the hg configuration file(s)
345         self.project = ui.config('irker', 'project')
346         self.repo = ui.config('irker', 'repo')
347         self.server = ui.config('irker', 'server')
348         self.channels = ui.config('irker', 'channels')
349         self.tcp = str(ui.configbool('irker', 'tcp'))  # converted to bool again in do_overrides
350         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'
351         self.tinyifier = ui.config('irker', 'tinyifier') or default_tinyifier
352         self.color = ui.config('irker', 'color')
353         self.urlprefix = (ui.config('irker', 'urlprefix') or
354                           ui.config('web', 'baseurl') or '')
355         if self.urlprefix:
356             # self.commit is appended to this by do_overrides
357             self.urlprefix = self.urlprefix.rstrip('/') + '/rev/'
358         self.cialike = ui.config('irker', 'cialike')
359         self.filtercmd = ui.config('irker', 'filtercmd')
360         if not self.project:
361             self.project = os.path.basename(self.repository.root.rstrip('/'))
362         self.do_overrides()
363     def head(self):
364         "Return a symbolic reference to the tip commit of the current branch."
365         return "-1"
366     def commit_factory(self, commit_id):
367         "Make a Commit object holding data for a specified commit ID."
368         from mercurial.node import short
369         from mercurial.templatefilters import person
370         node = self.repository.lookup(commit_id)
371         commit = Commit(self, short(node))
372         # Extract commit-specific values from a "context" object
373         ctx = self.repository.changectx(node)
374         commit.rev = '%d:%s' % (ctx.rev(), commit.commit)
375         commit.branch = ctx.branch()
376         commit.author = person(ctx.user())
377         commit.author_date = \
378             datetime.datetime.fromtimestamp(ctx.date()[0]).strftime('%Y-%m-%d %H:%M:%S')
379         commit.logmsg = ctx.description()
380         # Extract changed files from status against first parent
381         st = self.repository.status(ctx.p1().node(), ctx.node())
382         commit.files = ' '.join(st[0] + st[1] + st[2])
383         return commit
384
385 def hg_hook(ui, repo, **kwds):
386     # To be called from a Mercurial "commit" or "incoming" hook.  Example
387     # configuration:
388     # [hooks]
389     # incoming.irker = python:/path/to/irkerhook.py:hg_hook
390     extractor = HgExtractor([(ui, repo)])
391     ship(extractor, kwds['node'], False)
392
393 # The files we use to identify a Subversion repo might occur as content
394 # in a git or hg repo, but the special subdirectories for those are more
395 # reliable indicators.  So test for Subversion last.
396 extractors = [GitExtractor, HgExtractor, SvnExtractor]
397
398 # VCS-dependent code ends here
399
400 def ship(extractor, commit, debug):
401     "Ship a notification for the specified commit."
402     metadata = extractor.commit_factory(commit)
403
404     # This is where we apply filtering
405     if extractor.filtercmd:
406         cmd = '%s %s' % (shellquote(extractor.filtercmd),
407                          shellquote(json.dumps(metadata.__dict__)))
408         data = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read()
409         try:
410             metadata.__dict__.update(json.loads(data))
411         except ValueError:
412             sys.stderr.write("irkerhook.py: could not decode JSON: %s\n" % data)
413             raise SystemExit, 1
414
415     # Rewrite the file list if too long. The objective here is only
416     # to be easier on the eyes.
417     if extractor.cialike \
418            and extractor.cialike.lower() != "none" \
419            and len(metadata.files) > int(extractor.cialike):
420         files = metadata.files.split()
421         dirs = set([d.rpartition('/')[0] for d in files])
422         if len(dirs) == 1:
423             metadata.files = "(%s files)" % (len(files),)
424         else:
425             metadata.files = "(%s files in %s dirs)" % (len(files), len(dirs))
426     # Message reduction.  The assumption here is that IRC can't handle
427     # lines more than 510 characters long. If we exceed that length, we
428     # try knocking out the file list, on the theory that for notification
429     # purposes the commit text is more important.  If it's still too long
430     # there's nothing much can be done other than ship it expecting the IRC
431     # server to truncate.
432     privmsg = unicode(metadata)
433     if len(privmsg) > 510:
434         metadata.files = ""
435         privmsg = unicode(metadata)
436
437     # Anti-spamming guard.  It's deliberate that we get maxchannels not from
438     # the user-filtered metadata but from the extractor data - means repo
439     # administrators can lock in that setting.
440     channels = metadata.channels.split(",")
441     if extractor.maxchannels != 0:
442         channels = channels[:extractor.maxchannels]
443
444     # Ready to ship.
445     message = json.dumps({"to": channels, "privmsg": privmsg})
446     if debug:
447         print message
448     elif channels:
449         try:
450             if extractor.tcp:
451                 try:
452                     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
453                     sock.connect((extractor.server or default_server, IRKER_PORT))
454                     sock.sendall(message + "\n")
455                 finally:
456                     sock.close()
457             else:
458                 try:
459                     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
460                     sock.sendto(message + "\n", (extractor.server or default_server, IRKER_PORT))
461                 finally:
462                     sock.close()
463         except socket.error, e:
464             sys.stderr.write("%s\n" % e)
465
466 if __name__ == "__main__":
467     notify = True
468     repository = os.getcwd()
469     commits = []
470     for arg in sys.argv[1:]:
471         if arg == '-n':
472             notify = False
473         elif arg == '-V':
474             print "irkerhook.py: version", version
475             sys.exit(0)
476         elif arg.startswith("--repository="):
477             repository = arg[13:]
478         elif not arg.startswith("--"):
479             commits.append(arg)
480
481     # Figure out which extractor we should be using
482     for candidate in extractors:
483         if candidate.is_repository(repository):
484             cls = candidate
485             break
486     else:
487         sys.stderr.write("irkerhook: cannot identify a repository type.\n")
488         raise SystemExit(1)
489     extractor = cls(sys.argv[1:])
490
491     # And apply it.
492     if not commits:
493         commits = [extractor.head()]
494     for commit in commits:
495         ship(extractor, commit, not notify)
496
497 #End