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]
51 def __init__(self, extractor, commit):
60 self.__dict__.update(extractor.__dict__)
62 "Produce a notification string from this commit."
63 if self.urlprefix.lower() == "none":
66 urlprefix = urlprefixmap.get(self.urlprefix, self.urlprefix)
67 webview = (urlprefix % self.__dict__) + self.commit
69 if urllib.urlopen(webview).getcode() == 404:
72 # Didn't get a retrieval error or 404 on the web
73 # view, so try to tinyify a reference to it.
74 self.url = open(urllib.urlretrieve(self.tinyifier + webview)[0]).read()
79 return self.template % self.__dict__
81 class GenericExtractor:
82 "Generic class for encapsulating data from a VCS."
84 numerics = ["maxchannels"]
85 def __init__(self, arguments):
86 self.arguments = arguments
89 # These aren't really repo data but they belong here anyway...
91 self.tinyifier = default_tinyifier
97 self.host = socket.getfqdn()
98 # Color highlighting is disabled by default.
100 self.bold = self.green = self.blue = ""
101 self.yellow = self.brown = self.reset = ""
102 def activate_color(self, style):
108 self.yellow = '\x037'
112 self.bold = '\x1b[1m;'
113 self.green = '\x1b[1;2m;'
114 self.blue = '\x1b[1;4m;'
115 self.yellow = '\x1b[1;3m;'
116 self.brown = '\x1b[3m;'
117 self.reset = '\x1b[0m;'
118 def load_preferences(self, conf):
119 "Load preferences from a file in the repository root."
120 if not os.path.exists(conf):
123 for line in open(conf):
125 if line.startswith("#") or not line.strip():
127 elif line.count('=') != 1:
128 sys.stderr.write('"%s", line %d: missing = in config line\n' \
131 fields = line.split('=')
133 sys.stderr.write('"%s", line %d: too many fields in config line\n' \
136 variable = fields[0].strip()
137 value = fields[1].strip()
138 if value.lower() == "true":
140 elif value.lower() == "false":
142 # User cannot set maxchannels - only a command-line arg can do that.
143 if variable == "maxchannels":
145 setattr(self, variable, value)
146 def do_overrides(self):
147 "Make command-line overrides possible."
148 for tok in self.arguments:
149 for key in self.__dict__:
150 if tok.startswith("--" + key + "="):
151 val = tok[len(key)+3:]
152 setattr(self, key, val)
153 for (key, val) in self.__dict__.items():
154 if key in GenericExtractor.booleans:
155 if type(val) == type("") and val.lower() == "true":
156 setattr(self, key, True)
157 elif type(val) == type("") and val.lower() == "false":
158 setattr(self, key, False)
159 elif key in GenericExtractor.numerics:
160 setattr(self, key, int(val))
162 sys.stderr.write("irkerhook.py: no project name set!\n")
165 self.repo = self.project.lower()
166 if not self.channels:
167 self.channels = default_channels % self.__dict__
168 if self.color and self.color.lower() != "none":
169 self.activate_color(self.color)
171 class GitExtractor(GenericExtractor):
172 "Metadata extraction for the git version control system."
173 def __init__(self, arguments):
174 GenericExtractor.__init__(self, arguments)
175 # Get all global config variables
176 self.project = do("git config --get irker.project")
177 self.repo = do("git config --get irker.repo")
178 self.server = do("git config --get irker.server")
179 self.channels = do("git config --get irker.channels")
180 self.tcp = do("git config --bool --get irker.tcp")
181 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'
182 self.color = do("git config --get irker.color")
183 self.urlprefix = do("git config --get irker.urlprefix") or "gitweb"
184 # These are git-specific
185 self.refname = do("git symbolic-ref HEAD 2>/dev/null")
186 self.revformat = do("git config --get irker.revformat")
187 # The project variable defaults to the name of the repository toplevel.
189 bare = do("git config --bool --get core.bare")
190 if bare.lower() == "true":
193 keyfile = ".git/HEAD"
196 if os.path.exists(os.path.join(here, keyfile)):
197 self.project = os.path.basename(here)
200 sys.stderr.write("irkerhook.py: no git repo below root!\n")
202 here = os.path.dirname(here)
205 def commit_factory(self, commit_id):
206 "Make a Commit object holding data for a specified commit ID."
207 commit = Commit(self, commit_id)
208 commit.branch = os.path.basename(self.refname)
209 # Compute a description for the revision
210 if self.revformat == 'raw':
211 commit.rev = commit.commit
212 elif self.revformat == 'short':
214 else: # self.revformat == 'describe'
215 commit.rev = do("git describe %s 2>/dev/null" % shellquote(commit.commit))
217 commit.rev = commit.commit[:12]
218 # Extract the meta-information for the commit
219 commit.files = do("git diff-tree -r --name-only " + shellquote(commit.commit))
220 commit.files = " ".join(commit.files.strip().split("\n")[1:])
221 # Design choice: for git we ship only the first line, which is
222 # conventionally supposed to be a summary of the commit. Under
223 # other VCSes a different choice may be appropriate.
224 metainfo = do("git log -1 '--pretty=format:%an <%ae>|%s' " + shellquote(commit.commit))
225 (commit.author, commit.logmsg) = metainfo.split("|")
226 # This discards the part of the author's address after @.
227 # Might be be nice to ship the full email address, if not
228 # for spammers' address harvesters - getting this wrong
229 # would make the freenode #commits channel into harvester heaven.
230 commit.author = commit.author.replace("<", "").split("@")[0].split()[-1]
233 class SvnExtractor(GenericExtractor):
234 "Metadata extraction for the svn version control system."
235 def __init__(self, arguments):
236 GenericExtractor.__init__(self, arguments)
237 # Some things we need to have before metadata queries will work
238 self.repository = None
239 for tok in arguments:
240 if tok.startswith("--repository="):
241 self.repository = tok[13:]
242 self.project = os.path.basename(self.repository)
243 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'
244 self.urlprefix = "viewcvs"
245 self.load_preferences(os.path.join(self.repository, "irker.conf"))
247 def commit_factory(self, commit_id):
249 commit = Commit(self, commit_id)
251 commit.rev = "r%s" % self.id
252 commit.author = self.svnlook("author")
253 commit.files = self.svnlook("dirs-changed").strip().replace("\n", " ")
254 commit.logmsg = self.svnlook("log")
256 def svnlook(self, info):
257 return do("svnlook %s %s --revision %s" % (shellquote(info), shellquote(self.repository), shellquote(self.id)))
259 if __name__ == "__main__":
264 for arg in sys.argv[1:]:
268 print "irkerhook.py: version", version
270 elif arg.startswith("--refname="):
272 elif arg.startswith("--repository="):
273 repository = arg[13:]
274 elif not arg.startswith("--"):
277 # Determine the repository type. Default to git unless user has pointed
278 # us at a repo with identifiable internals.
280 if repository and os.path.exists(os.path.join(repository, "format")):
283 # Someday we'll have extractors for several version-control systems
285 if repository is None or not commits:
286 sys.stderr.write("irkerhook: svn requires a repository and a commit.")
288 extractor = SvnExtractor(sys.argv[1:])
290 extractor = GitExtractor(sys.argv[1:])
292 commits = [do("git rev-parse HEAD")]
294 for commit in commits:
295 metadata = extractor.commit_factory(commit)
297 # Message reduction. The assumption here is that IRC can't handle
298 # lines more than 510 characters long. If we exceed that length, we
299 # try knocking out the file list, on the theory that for notification
300 # purposes the commit text is more important. If it's still too long
301 # there's nothing much can be done other than ship it expecting the IRC
302 # server to truncate.
303 privmsg = str(metadata)
304 if len(privmsg) > 510:
306 privmsg = str(metadata)
308 # Anti-spamming guard.
309 channel_list = extractor.channels.split(",")
310 if extractor.maxchannels != 0:
311 channel_list = channel_list[:extractor.maxchannels]
314 message = json.dumps({"to":channel_list, "privmsg":privmsg})
321 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
322 sock.connect((extractor.server or default_server, IRKER_PORT))
323 sock.sendall(message + "\n")
328 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
329 sock.sendto(message + "\n", (extractor.server or default_server, IRKER_PORT))
332 except socket.error, e:
333 sys.stderr.write("%s\n" % e)