Converted to use Configurable instead of Toggleable.

This commit is contained in:
Jeremy Fincher 2003-11-08 08:01:34 +00:00
parent 367d561d10
commit 64e664e0bc
3 changed files with 62 additions and 57 deletions

View File

@ -78,9 +78,7 @@ def makeDb(filename):
class BugError(Exception): class BugError(Exception):
"""A bugzilla error""" """A bugzilla error"""
def __init__(self, args = None): pass
Exception.__init__(self)
self.args = args
def configure(onStart, afterConnect, advanced): def configure(onStart, afterConnect, advanced):
from questions import expect, anything, yn from questions import expect, anything, yn
@ -91,17 +89,20 @@ def configure(onStart, afterConnect, advanced):
print 'supybot sees such a URL, he will parse the web page for' print 'supybot sees such a URL, he will parse the web page for'
print 'information and reply with the results.\n' print 'information and reply with the results.\n'
if yn('Do you want the Bugzilla snarfer enabled by default?') == 'n': if yn('Do you want the Bugzilla snarfer enabled by default?') == 'n':
onStart.append('Bugzilla toggle bug off') onStart.append('Bugzilla config bug-snarfer off')
class Bugzilla(callbacks.PrivmsgCommandAndRegexp, plugins.Toggleable): class Bugzilla(callbacks.PrivmsgCommandAndRegexp, plugins.Configurable):
"""Show a link to a bug report with a brief description""" """Show a link to a bug report with a brief description"""
threaded = True threaded = True
regexps = ['bzSnarfer'] regexps = ['bzSnarfer']
toggles = plugins.ToggleDictionary({'bug' : True}) configurables = plugins.ConfigurableDictionary(
[('bug-snarfer', plugins.ConfigurableTypes.bool, True,
"""Determines whether the bug snarfer will be enabled, such that any
Bugzilla URLs seen in the channel will have their information reported
into the channel.""")]
)
def __init__(self): def __init__(self):
callbacks.PrivmsgCommandAndRegexp.__init__(self) callbacks.PrivmsgCommandAndRegexp.__init__(self)
plugins.Toggleable.__init__(self)
self.entre = re.compile('&(\S*?);') self.entre = re.compile('&(\S*?);')
self.db = makeDb(dbfilename) self.db = makeDb(dbfilename)
@ -116,7 +117,7 @@ class Bugzilla(callbacks.PrivmsgCommandAndRegexp, plugins.Toggleable):
is the name that will be used to reference the zilla in all other is the name that will be used to reference the zilla in all other
commands. <description> is the common name for the bugzilla and will commands. <description> is the common name for the bugzilla and will
be listed with the bugzilla query. be listed with the bugzilla query.
E.g.: add rh http://bugzilla.redhat.com/bugzilla Red Hat Zilla""" """
(shorthand, url, description) = privmsgs.getArgs(args, needed=3) (shorthand, url, description) = privmsgs.getArgs(args, needed=3)
cursor = self.db.cursor() cursor = self.db.cursor()
cursor.execute("""INSERT INTO bugzillas VALUES (%s, %s, %s)""", cursor.execute("""INSERT INTO bugzillas VALUES (%s, %s, %s)""",
@ -131,7 +132,7 @@ class Bugzilla(callbacks.PrivmsgCommandAndRegexp, plugins.Toggleable):
Remove the bugzilla associated with <abbreviation> from the list of Remove the bugzilla associated with <abbreviation> from the list of
defined bugzillae. defined bugzillae.
E.g.: remove rh""" """
shorthand = privmsgs.getArgs(args) shorthand = privmsgs.getArgs(args)
cursor = self.db.cursor() cursor = self.db.cursor()
cursor.execute("""SELECT * from bugzillas where shorthand = %s""", cursor.execute("""SELECT * from bugzillas where shorthand = %s""",
@ -151,7 +152,7 @@ class Bugzilla(callbacks.PrivmsgCommandAndRegexp, plugins.Toggleable):
List defined bugzillae. If <abbreviation> is specified, list the List defined bugzillae. If <abbreviation> is specified, list the
information for that bugzilla. information for that bugzilla.
E.g.: list rh; or just list""" """
shorthand = privmsgs.getArgs(args, needed=0, optional=1) shorthand = privmsgs.getArgs(args, needed=0, optional=1)
if shorthand: if shorthand:
cursor = self.db.cursor() cursor = self.db.cursor()
@ -175,7 +176,7 @@ class Bugzilla(callbacks.PrivmsgCommandAndRegexp, plugins.Toggleable):
def bzSnarfer(self, irc, msg, match): def bzSnarfer(self, irc, msg, match):
r"(http://\S+)/show_bug.cgi\?id=([0-9]+)" r"(http://\S+)/show_bug.cgi\?id=([0-9]+)"
if not self.toggles.get('bug', channel=msg.args[0]): if not self.configurables.get('bug-snarfer', channel=msg.args[0]):
return return
queryurl = '%s/xml.cgi?id=%s' % (match.group(1), match.group(2)) queryurl = '%s/xml.cgi?id=%s' % (match.group(1), match.group(2))
try: try:
@ -195,14 +196,15 @@ class Bugzilla(callbacks.PrivmsgCommandAndRegexp, plugins.Toggleable):
report['title'] = str(summary['title']) report['title'] = str(summary['title'])
report['summary'] = str(self._mk_summary_string(summary)) report['summary'] = str(self._mk_summary_string(summary))
report['product'] = str(summary['product']) report['product'] = str(summary['product'])
irc.reply(msg, '%(product)s bug #%(id)s: %(title)s %(summary)s' s = '%(product)s bug #%(id)s: %(title)s %(summary)s' % report
% report, prefixName = False) irc.reply(msg, s, prefixName=False)
bzSnarfer = privmsgs.urlSnarfer(bzSnarfer)
def bug(self, irc, msg, args): def bug(self, irc, msg, args):
"""<abbreviation> <number> """<abbreviation> <number>
Look up bug <number> in the bugzilla associated with <abbreviation>. Look up bug <number> in the bugzilla associated with <abbreviation>.
E.g.: bug rh 10301""" """
(shorthand, num) = privmsgs.getArgs(args, needed=2) (shorthand, num) = privmsgs.getArgs(args, needed=2)
cursor = self.db.cursor() cursor = self.db.cursor()
cursor.execute("""SELECT url,description from bugzillas where cursor.execute("""SELECT url,description from bugzillas where
@ -231,38 +233,38 @@ class Bugzilla(callbacks.PrivmsgCommandAndRegexp, plugins.Toggleable):
report['url'] = str('%s/show_bug.cgi?id=%s' % (url, num)) report['url'] = str('%s/show_bug.cgi?id=%s' % (url, num))
report['title'] = str(summary['title']) report['title'] = str(summary['title'])
report['summary'] = str(self._mk_summary_string(summary)) report['summary'] = str(self._mk_summary_string(summary))
irc.reply(msg, '%(zilla)s bug #%(id)s: %(title)s %(summary)s %(url)s' s = '%(zilla)s bug #%(id)s: %(title)s %(summary)s %(url)s' % report
% report) irc.reply(msg, s)
return
def _mk_summary_string(self, summary): def _mk_summary_string(self, summary):
ary = [] L = []
if 'product' in summary: if 'product' in summary:
ary.append(ircutils.bold('Product: ') + summary['product']) L.append(ircutils.bold('Product: ') + summary['product'])
if 'component' in summary: if 'component' in summary:
ary.append(ircutils.bold('Component: ') + summary['component']) L.append(ircutils.bold('Component: ') + summary['component'])
if 'severity' in summary: if 'severity' in summary:
ary.append(ircutils.bold('Severity: ') + summary['severity']) L.append(ircutils.bold('Severity: ') + summary['severity'])
if 'assigned to' in summary: if 'assigned to' in summary:
ary.append(ircutils.bold('Assigned to: ') + summary['assigned to']) L.append(ircutils.bold('Assigned to: ') + summary['assigned to'])
if 'status' in summary: if 'status' in summary:
ary.append(ircutils.bold('Status: ') + summary['status']) L.append(ircutils.bold('Status: ') + summary['status'])
if 'resolution' in summary: if 'resolution' in summary:
ary.append(ircutils.bold('Resolution: ') + summary['resolution']) L.append(ircutils.bold('Resolution: ') + summary['resolution'])
out = string.join(ary, ', ') return ', '.join(L)
return out
def _is_bug_number(self, bug): def _is_bug_number(self, bug):
try: int(bug) try:
except: return 0 int(bug)
else: return 1 return True
except ValueError:
return False
def _get_short_bug_summary(self, url, desc, num): def _get_short_bug_summary(self, url, desc, num):
bugxml = self._getbugxml(url, desc) bugxml = self._getbugxml(url, desc)
try: zilladom = minidom.parseString(bugxml) try: zilladom = minidom.parseString(bugxml)
except Exception, e: except Exception, e:
msg = 'Could not parse XML returned by %s bugzilla: %s' msg = 'Could not parse XML returned by %s bugzilla: %s'
raise BugError(str(msg % (desc, e))) raise BugError, msg % (desc, e)
bug_n = zilladom.getElementsByTagName('bug')[0] bug_n = zilladom.getElementsByTagName('bug')[0]
if bug_n.hasAttribute('error'): if bug_n.hasAttribute('error'):
errtxt = bug_n.getAttribute('error') errtxt = bug_n.getAttribute('error')
@ -296,41 +298,38 @@ class Bugzilla(callbacks.PrivmsgCommandAndRegexp, plugins.Toggleable):
return summary return summary
def _getbugxml(self, url, desc): def _getbugxml(self, url, desc):
try: fh = urllib.urlopen(url) try:
except: raise IOError('Connection to %s bugzilla failed' % desc) fh = urllib.urlopen(url)
bugxml = '' except:
while 1: raise IOError('Connection to %s bugzilla failed' % desc)
chunk = fh.read(8192) bugxml = fh.read()
if chunk == '':
break
bugxml = bugxml + chunk
fh.close() fh.close()
if not len(bugxml): if not bugxml:
msg = 'Error getting bug content from %s' % desc raise IOError, 'Error getting bug content from %s' % desc
raise IOError(msg)
return bugxml return bugxml
def _getnodetxt(self, node): def _getnodetxt(self, node):
val = '' L = []
for childnode in node.childNodes: for childnode in node.childNodes:
if childnode.nodeType == childnode.TEXT_NODE: if childnode.nodeType == childnode.TEXT_NODE:
val = val + childnode.data L.append(childnode.data)
val = ''.join(L)
if node.hasAttribute('encoding'): if node.hasAttribute('encoding'):
encoding = node.getAttribute('encoding') encoding = node.getAttribute('encoding')
if encoding == 'base64': if encoding == 'base64':
try: try:
val = base64.decodestring(val) val = val.decode('base64')
except: except:
val = 'Cannot convert bug data from base64!' val = 'Cannot convert bug data from base64.'
entre = self.entre while self.entre.search(val):
while entre.search(val): entity = self.entre.search(val).group(1)
entity = entre.search(val).group(1) if entity in entities:
if entities.has_key(entity): val = re.sub(self.entre, entities[entity], val)
val = re.sub(entre, entities[entity], val)
else: else:
val = re.sub(entre, '_', val) val = re.sub(self.entre, '_', val)
return val return val
Class = Bugzilla Class = Bugzilla
# vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78: # vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78:

View File

@ -59,11 +59,17 @@ frowns = (':|', ':-/', ':-\\', ':\\', ':/', ':(', ':-(', ':\'(')
smileyre = re.compile('|'.join(map(re.escape, smileys))) smileyre = re.compile('|'.join(map(re.escape, smileys)))
frownre = re.compile('|'.join(map(re.escape, frowns))) frownre = re.compile('|'.join(map(re.escape, frowns)))
class ChannelDB(callbacks.Privmsg,plugins.Toggleable,plugins.ChannelDBHandler): class ChannelDB(callbacks.Privmsg,
toggles = plugins.ToggleDictionary({'selfstats': True}) plugins.Configurable,
plugins.ChannelDBHandler):
configurables = plugins.ConfigurableDictionary(
[('self-stats', plugins.ConfigurableTypes.bool, True,
"""Determines whether the bot will keep channel statistics on itself,
possibly skewing the channel stats (especially in cases where he's
relaying between channels on a network.""")]
)
def __init__(self): def __init__(self):
callbacks.Privmsg.__init__(self) callbacks.Privmsg.__init__(self)
plugins.Toggleable.__init__(self)
plugins.ChannelDBHandler.__init__(self) plugins.ChannelDBHandler.__init__(self)
self.lastmsg = None self.lastmsg = None
self.laststate = None self.laststate = None
@ -224,7 +230,7 @@ class ChannelDB(callbacks.Privmsg,plugins.Toggleable,plugins.ChannelDBHandler):
def outFilter(self, irc, msg): def outFilter(self, irc, msg):
if msg.command == 'PRIVMSG': if msg.command == 'PRIVMSG':
if ircutils.isChannel(msg.args[0]): if ircutils.isChannel(msg.args[0]):
if self.toggles.get('selfstats', msg.args[0]): if self.configurables.get('self-stats', msg.args[0]):
db = self.getDb(msg.args[0]) db = self.getDb(msg.args[0])
cursor = db.cursor() cursor = db.cursor()
try: try:

View File

@ -70,7 +70,7 @@ if sqlite is not None:
u = ircdb.users.getUser(id) u = ircdb.users.getUser(id)
u.addCapability(ircdb.makeChannelCapability(self.channel, 'op')) u.addCapability(ircdb.makeChannelCapability(self.channel, 'op'))
ircdb.users.setUser(id, u) ircdb.users.setUser(id, u)
self.assertNotError('channeldb toggle selfstats off') self.assertNotError('channeldb config self-stats off')
m1 = self.getMsg('channeldb stats %s' % self.irc.nick) m1 = self.getMsg('channeldb stats %s' % self.irc.nick)
m2 = self.getMsg('channeldb stats %s' % self.irc.nick) m2 = self.getMsg('channeldb stats %s' % self.irc.nick)
self.assertEqual(m1.args[1], m2.args[1]) self.assertEqual(m1.args[1], m2.args[1])