02cd212f796fe8e3ba6d39ce88f6218cdd8fcdaa
[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.4 with the 2.6 json library installed.
7 #
8 # usage: irkerhook.py [-V] [-n]
9 #
10 # This script is meant to be run in a post-commit hook.  Try it with
11 # -n to see the notification dumped to stdout and verify that it looks
12 # 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 import os, sys, commands, socket, urllib, json
41
42 version = "1.2"
43
44 def shellquote(s):
45     return "'" + s.replace("'","'\\''") + "'"
46
47 def do(command):
48     return commands.getstatusoutput(command)[1]
49
50 class GenericExtractor:
51     "Generic class for encapsulating data from a VCS."
52     booleans = ["tcp", "color"]
53     numerics = ["maxchannels"]
54     def __init__(self, arguments):
55         self.arguments = arguments
56         self.project = None
57         self.repo = None
58         # These aren't really repo data but they belong here anyway...
59         self.tcp = True
60         self.tinyifier = default_tinyifier
61         self.server = None
62         self.channels = None
63         self.maxchannels = 0
64         self.template = None
65         self.urlprefix = None
66         self.host = socket.getfqdn()
67         # Per-commit data begins
68         self.author = None
69         self.files = None
70         self.logmsg = None
71         self.rev = None
72         self.color = False
73         # Color highlighting is disabled by default.
74         self.bold = self.green = self.blue = ""
75         self.yellow = self.brown = self.reset = ""
76     def activate_color(self):
77         "IRC color codes."
78         self.bold = '\x02'
79         self.green = '\x033'
80         self.blue = '\x032'
81         self.yellow = '\x037'
82         self.brown = '\x035'
83         self.reset = '\x0F'
84     def load_preferences(self, conf):
85         "Load preferences from a file in the repository root."
86         if not os.path.exists(conf):
87             return
88         ln = 0
89         for line in open(conf):
90             ln += 1
91             if line.startswith("#") or not line.strip():
92                 continue
93             elif line.count('=') != 1:
94                 sys.stderr.write('"%s", line %d: missing = in config line\n' \
95                                  % (conf, ln))
96                 continue
97             fields = line.split('=')
98             if len(fields) != 2:
99                 sys.stderr.write('"%s", line %d: too many fields in config line\n' \
100                                  % (conf, ln))
101                 continue
102             variable = fields[0].strip()
103             value = fields[1].strip()
104             if value.lower() == "true":
105                 value = True
106             elif value.lower() == "false":
107                 value = False
108             # User cannot set maxchannels - only a command-line arg can do that.
109             if variable == "maxchannels":
110                 return
111             setattr(self, variable, value)
112     def do_overrides(self):
113         "Make command-line overrides possible."
114         for tok in self.arguments:
115             for key in self.__dict__:
116                 if tok.startswith(key + "="):
117                     val = tok[len(key)+1:]
118                     setattr(self, key, val)
119         for (key, val) in self.__dict__.items():
120             if key in GenericExtractor.booleans:
121                 if val.lower() == "true":
122                     setattr(self, key, True)
123                 elif val.lower() == "false":
124                     setattr(self, key, False)
125                 elif key in GenericExtractor.numerics:
126                     setattr(self, key, int(val))
127         if not self.project:
128             sys.stderr.write("irkerhook.py: no project name set!\n")
129             raise SystemExit, 1
130         if not self.repo:
131             self.repo = self.project.lower()
132         if not self.channels:
133             self.channels = default_channels % self.__dict__
134         if self.urlprefix.lower() == "none":
135             self.url = ""
136         else:
137             self.urlprefix = urlprefixmap.get(self.urlprefix, self.urlprefix) 
138             prefix = self.urlprefix % self.__dict__
139             try:
140                 webview = prefix + self.commit
141                 if urllib.urlopen(webview).getcode() == 404:
142                     raise IOError
143                 try:
144                     # Didn't get a retrieval error or 404 on the web
145                     # view, so try to tinyify a reference to it.
146                     self.url = open(urllib.urlretrieve(self.tinyifier + webview)[0]).read()
147                 except IOError:
148                     self.url = webview
149             except IOError:
150                 self.url = ""
151         if self.color:
152             self.activate_color()
153
154 class GitExtractor(GenericExtractor):
155     "Metadata extraction for the git version control system."
156     def __init__(self, arguments):
157         GenericExtractor.__init__(self, arguments)
158         # Get all global config variables
159         self.project = do("git config --get irker.project")
160         self.repo = do("git config --get irker.repo")
161         self.server = do("git config --get irker.server")
162         self.channels = do("git config --get irker.channels")
163         self.tcp = do("git config --bool --get irker.tcp")
164         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'
165         self.color = do("git config --bool --get irker.color")
166         self.urlprefix = do("git config --get irker.urlprefix") or "gitweb"
167         # This one is git-specific
168         self.revformat = do("git config --get irker.revformat")
169         # The project variable defaults to the name of the repository toplevel.
170         if not self.project:
171             bare = do("git config --bool --get core.bare")
172             if bare.lower() == "true":
173                 keyfile = "HEAD"
174             else:
175                 keyfile = ".git/HEAD"
176             here = os.getcwd()
177             while True:
178                 if os.path.exists(os.path.join(here, keyfile)):
179                     self.project = os.path.basename(here)
180                     break
181                 elif here == '/':
182                     sys.stderr.write("irkerhook.py: no git repo below root!\n")
183                     sys.exit(1)
184                 here = os.path.dirname(here)
185         # Revision level
186         self.refname = do("git symbolic-ref HEAD 2>/dev/null")
187         self.commit = do("git rev-parse HEAD")
188         self.branch = os.path.basename(self.refname)
189         # Compute a description for the revision
190         if self.revformat == 'raw':
191             self.rev = self.commit
192         elif self.revformat == 'short':
193             self.rev = ''
194         else: # self.revformat == 'describe'
195             self.rev = do("git describe %s 2>/dev/null" % shellquote(self.commit))
196         if not self.rev:
197             self.rev = self.commit[:12]
198         # Extract the meta-information for the commit
199         self.files = do("git diff-tree -r --name-only " + shellquote(self.commit))
200         self.files = " ".join(self.files.strip().split("\n")[1:])
201         # Design choice: for git we ship only the first line, which is
202         # conventionally supposed to be a summary of the commit.  Under
203         # other VCSes a different choice may be appropriate.
204         metainfo = do("git log -1 '--pretty=format:%an <%ae>|%s' " + shellquote(self.commit))
205         (self.author, self.logmsg) = metainfo.split("|")
206         # This discards the part of the author's address after @.
207         # Might be be nice to ship the full email address, if not
208         # for spammers' address harvesters - getting this wrong
209         # would make the freenode #commits channel into harvester heaven.
210         self.author = self.author.replace("<", "").split("@")[0].split()[-1]
211         # Get overrides
212         self.do_overrides()
213
214 class SvnExtractor(GenericExtractor):
215     "Metadata extraction for the svn version control system."
216     def __init__(self, arguments):
217         GenericExtractor.__init__(self, arguments)
218         self.commit = None
219         # Some things we need to have before metadata queries will work
220         for tok in arguments:
221             if tok.startswith("repository="):
222                 self.repository = tok[11:]
223             elif tok.startswith("commit="):
224                 self.commit = tok[7:]
225         if self.commit is None or self.repository is None:
226             sys.stderr.write("irkerhook: svn requires 'repository' and 'commit' variables.")
227             sys.exit(1)
228         self.project = os.path.basename(self.repository)
229         self.author = self.svnlook("author")
230         self.files = self.svnlook("dirs-changed").strip().replace("\n", " ")
231         self.logmsg = self.svnlook("log")
232         self.rev = "r%s" % self.commit
233         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'
234         self.urlprefix = "viewcvs"
235         self.load_preferences(os.path.join(self.repository, "irker.conf"))
236         self.do_overrides()
237     def svnlook(self, info):
238         return do("svnlook %s %s --revision %s" % (shellquote(info), shellquote(self.repository), shellquote(self.commit)))
239
240 if __name__ == "__main__":
241     import getopt
242
243     try:
244         (options, arguments) = getopt.getopt(sys.argv[1:], "nV")
245     except getopt.GetoptError, msg:
246         print "irkerhook.py: " + str(msg)
247         raise SystemExit, 1
248
249     notify = True
250     channels = ""
251     commit = ""
252     repository = ""
253     for (switch, val) in options:
254         if switch == '-n':
255             notify = False
256         elif switch == '-V':
257             print "irkerhook.py: version", version
258             sys.exit(0)
259
260     # Gather info for repo type discrimination
261     for tok in arguments:
262         if tok.startswith("repository="):
263             repository = tok[11:]
264
265     # Determine the repository type. Default to git unless user has pointed
266     # us at a repo with identifiable internals.
267     vcs = "git"
268     if os.path.exists(os.path.join(repository, "format")):
269         vcs = "svn"
270
271     # Someday we'll have extractors for several version-control systems
272     if vcs == "svn":
273         extractor = SvnExtractor(arguments)
274     else:
275         extractor = GitExtractor(arguments)
276
277     # Message reduction.  The assumption here is that IRC can't handle
278     # lines more than 510 characters long. If we exceed that length, we
279     # try knocking out the file list, on the theory that for notification
280     # purposes the commit text is more important.  If it's still too long
281     # there's nothing much can be done other than ship it expecting the IRC
282     # server to truncate.
283     privmsg = extractor.template % extractor.__dict__
284     if len(privmsg) > 510:
285         extractor.files = ""
286         privmsg = extractor.template % extractor.__dict__
287
288     # Anti-spamming guard.
289     channel_list = extractor.channels.split(",")
290     if extractor.maxchannels != 0:
291         channel_list = channel_list[:extractor.maxchannels]
292
293     # Ready to ship.
294     message = json.dumps({"to":channel_list, "privmsg":privmsg})
295     if not notify:
296         print message
297     else:
298         try:
299             if extractor.tcp:
300                 try:
301                     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
302                     sock.connect((extractor.server or default_server, IRKER_PORT))
303                     sock.sendall(message + "\n")
304                 finally:
305                     sock.close()
306             else:
307                 try:
308                     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
309                     sock.sendto(message + "\n", (extractor.server or default_server, IRKER_PORT))
310                 finally:
311                     sock.close()
312         except socket.error, e:
313             sys.stderr.write("%s\n" % e)
314
315 #End