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