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.4 with the 2.6 json library installed.
8 # usage: irkerhook.py [-V] [-n]
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.
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, the channel list includes the freenode #commits list
34 default_channels = "irc://chat.freenode.net/%(project)s,irc://chat.freenode.net/#commits"
37 # No user-serviceable parts below this line:
40 import os, sys, commands, socket, urllib, json
45 return "'" + s.replace("'","'\\''") + "'"
48 return commands.getstatusoutput(command)[1]
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
58 # These aren't really repo data but they belong here anyway...
60 self.tinyifier = default_tinyifier
66 self.host = socket.getfqdn()
67 # Per-commit data begins
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):
84 def load_preferences(self, conf):
85 "Load preferences from a file in the repository root."
86 if not os.path.exists(conf):
89 for line in open(conf):
91 if line.startswith("#") or not line.strip():
93 elif line.count('=') != 1:
94 sys.stderr.write('"%s", line %d: missing = in config line\n' \
97 fields = line.split('=')
99 sys.stderr.write('"%s", line %d: too many fields in config line\n' \
102 variable = fields[0].strip()
103 value = fields[1].strip()
104 if value.lower() == "true":
106 elif value.lower() == "false":
108 # User cannot set maxchannels - only a command-line arg can do that.
109 if variable == "maxchannels":
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))
128 sys.stderr.write("irkerhook.py: no project name set!\n")
131 self.repo = self.project.lower()
132 if not self.channels:
133 self.channels = default_channels % self.__dict__
134 if self.urlprefix.lower() == "none":
137 self.urlprefix = urlprefixmap.get(self.urlprefix, self.urlprefix)
138 prefix = self.urlprefix % self.__dict__
140 webview = prefix + self.commit
141 if urllib.urlopen(webview).getcode() == 404:
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()
152 self.activate_color()
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.
171 bare = do("git config --bool --get core.bare")
172 if bare.lower() == "true":
175 keyfile = ".git/HEAD"
178 if os.path.exists(os.path.join(here, keyfile)):
179 self.project = os.path.basename(here)
182 sys.stderr.write("irkerhook.py: no git repo below root!\n")
184 here = os.path.dirname(here)
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':
194 else: # self.revformat == 'describe'
195 self.rev = do("git describe %s 2>/dev/null" % shellquote(self.commit))
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]
214 class SvnExtractor(GenericExtractor):
215 "Metadata extraction for the svn version control system."
216 def __init__(self, arguments):
217 GenericExtractor.__init__(self, arguments)
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.")
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"))
237 def svnlook(self, info):
238 return do("svnlook %s %s --revision %s" % (shellquote(info), shellquote(self.repository), shellquote(self.commit)))
240 if __name__ == "__main__":
244 (options, arguments) = getopt.getopt(sys.argv[1:], "nV")
245 except getopt.GetoptError, msg:
246 print "irkerhook.py: " + str(msg)
253 for (switch, val) in options:
257 print "irkerhook.py: version", version
260 # Gather info for repo type discrimination
261 for tok in arguments:
262 if tok.startswith("repository="):
263 repository = tok[11:]
265 # Determine the repository type. Default to git unless user has pointed
266 # us at a repo with identifiable internals.
268 if os.path.exists(os.path.join(repository, "format")):
271 # Someday we'll have extractors for several version-control systems
273 extractor = SvnExtractor(arguments)
275 extractor = GitExtractor(arguments)
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:
286 privmsg = extractor.template % extractor.__dict__
288 # Anti-spamming guard.
289 channel_list = extractor.channels.split(",")
290 if extractor.maxchannels != 0:
291 channel_list = channel_list[:extractor.maxchannels]
294 message = json.dumps({"to":channel_list, "privmsg":privmsg})
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")
308 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
309 sock.sendto(message + "\n", (extractor.server or default_server, IRKER_PORT))
312 except socket.error, e:
313 sys.stderr.write("%s\n" % e)