summaryrefslogtreecommitdiff
path: root/gitnoti.py
blob: 7817182bade248cdb95343c600194fe1a38e73d8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
#!/usr/bin/env python

import git, os, sys, time, pyinotify, netrc
from optparse import OptionParser
from twisted.words.protocols import irc
from twisted.internet import reactor, protocol
from twisted.internet.task import LoopingCall

have_bitly = False
try:
	import bitly
	have_bitly = True
except:
	pass

parser = OptionParser()
parser.add_option('-s', '--host')
parser.add_option('-n', '--nick', default = 'git')
parser.add_option('-d', '--dir')
parser.add_option('-c', '--channel')
parser.add_option('-i', '--interval', type = 'int', default = 10)
parser.add_option('-u', '--url')

(options, args) = parser.parse_args()

if not options.host or not options.dir or not options.channel or not options.nick:
	parser.print_help()
	sys.exit(1)

if have_bitly and not netrc.netrc().authenticators('bitly'):
	have_bitly = False

root = options.dir

if root[-1] == '/':
	root = root[:-1]

repos = None

def repo_commit_msg(repo, commit):
	reponame = os.path.splitext(os.path.basename(repo.path))[0]

	stat = '%d files,' % commit.stats.total['files']
	stat += ' \00305--%d\017' % commit.stats.total['deletions']
	stat += ' \00303++%d\017' % commit.stats.total['insertions']
	msg = '\002%s\002 pushed to \002%s\002 by \002%s\002 (%s) %s' % (
		reponame,
		commit.id_abbrev,
		commit.committer.name if commit.author.name == commit.committer.name else '%s/%s' % (commit.committer.name, commit.author.name),
		stat,
		commit.summary
	)

	if options.url:
		msg += ' | '
		url = options.url % {'repo': reponame, 'commit': commit.id}
		if have_bitly:
			short_url = None
			try:
				bitly_auth = netrc.netrc().authenticators('bitly')
				bitly_api = bitly.Api(login = bitly_auth[0], apikey = bitly_auth[2])
				short_url = bitly_api.shorten(url)
			except:
				short_url = None

			if short_url:
				url = short_url
		msg += url

	return msg

class ReposNotifyEvent(pyinotify.ProcessEvent):
	def new_repo(self, event):
		flags = pyinotify.EventsCodes.ALL_FLAGS
		heads = '%s/refs/heads' % event.pathname

		i = 0
		# Wait max 10 seconds for refs/heads/ to appear.
		while not os.access(heads, os.F_OK) and i < 10:
			time.sleep(1)
			i += 1
		if not os.access(heads, os.F_OK):
			self.bot.gitmsg('Repo %s was found but couldn''t locate refs/heads/ (repo NOT added).' % os.path.splitext(event.name)[0])
			return

		wdd = self.bot.wm.add_watch(heads, flags['IN_MODIFY'] | flags['IN_CREATE'])
		repos[event.pathname] = [None, None, wdd]
		self.bot.gitmsg('New repo: %s' % os.path.splitext(event.name)[0])

	def updated_repo(self, event):
		pathname = event.pathname
		while len(pathname) > 1 and not pathname in repos:
			pathname = os.path.dirname(pathname)
		if len(pathname) == 1 or not pathname in repos:
			return
		l = repos[pathname]
		if not l[0]:
			l[0] = git.Repo(pathname)
		repo = l[0]
		if not repo.heads: # No commits
			return
		last = l[1]
		nlast = repo.heads[0].commit
		if nlast.id != last:
			msg = repo_commit_msg(repo, nlast)
			self.bot.gitmsg(msg)
			l[1] = nlast.id

	def process_IN_CREATE(self, event):
		if os.path.dirname(event.pathname) == root:
			self.new_repo(event)
		else:
			self.updated_repo(event)

	def process_IN_DELETE(self, event):
		if event.pathname in repos:
			self.bot.wm.rm_watch(repos[event.pathname][2].values())
			del repos[event.pathname]
			self.bot.gitmsg('Removed repo: %s' % os.path.splitext(event.name)[0])

	def process_IN_MODIFY(self, event):
		self.updated_repo(event)

def check_notifies(bot):
	bot.notifier.process_events()
	while bot.notifier.check_events():
		bot.notifier.read_events()
		bot.notifier.process_events()

class Bot(irc.IRCClient):
	nickname = options.nick

	def initial_add(self):
		global repos
		if not repos:
			repos = {}
			for path in (x for x in os.listdir(root) if x.endswith('.git')):
				try:
					r = git.Repo('%s/%s' % (root, path))
				except:
					continue
				flags = pyinotify.EventsCodes.ALL_FLAGS
				wdd = self.wm.add_watch('%s/%s/refs/heads' % (root, path), flags['IN_MODIFY'] | flags['IN_CREATE'])
				repos['%s/%s' % (root, path)] = [r, r.heads[0].commit.id, wdd]

	def gitmsg(self, msg):
		self.say(options.channel, msg)

	def signedOn(self):
		self.join(options.channel)
		self.wm = pyinotify.WatchManager()
		flags = pyinotify.EventsCodes.ALL_FLAGS
		self.wm.add_watch(root, flags['IN_DELETE'] | flags['IN_CREATE'] | flags['IN_ONLYDIR'])
		self.rne = ReposNotifyEvent()
		self.rne.bot = self
		self.notifier = pyinotify.Notifier(self.wm, self.rne, timeout = options.interval)

		self.initial_add()

		self.repeater = LoopingCall(check_notifies, self)
		self.repeater.start(options.interval)

	def privmsg(self, user, channel, message):
		private = channel == self.nickname
		nick = user.split('!')[0]
		target = nick if private else channel
		messagelist = message.split()
		if len(messagelist) < 2:
			return
		if messagelist[0].startswith(self.nickname):
			cmd = messagelist[1].lower()
			if cmd == 'list':
				s = 'Repos: %s' % ', '.join([os.path.splitext(os.path.basename(x))[0] for x in repos.keys()])
				self.msg(target, s)
			elif cmd == 'last':
				repo = messagelist[2].lower() if len(messagelist) > 2 else None
				if not repo:
					self.msg(target, 'Which repo?')
					return
				repo = [(k, v) for k, v in repos.iteritems() if os.path.basename(k).startswith(repo)]
				if len(repo) == 1:
					path = repo[0][0]
					repo = repo[0][1]
					r = repo[0] or git.Repo(path)
					msg = repo_commit_msg(r, r.heads[0].commit)
					self.msg(target, msg)
				elif len(repo) == 0:
					self.msg(target, 'No repo found.')
				else:
					self.msg(target, 'Ambiguous name: %s' % (', '.join([os.path.basename(x[0].path) for x in repos])))

class BotFactory(protocol.ReconnectingClientFactory):
	protocol = Bot

if __name__ == '__main__':
	f = BotFactory()
	reactor.connectTCP(options.host, 6667, f)
	reactor.run()