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