mirror of
https://github.com/progval/Limnoria.git
synced 2025-05-06 11:33:39 -05:00
Continue accelerating the 2to3 step (remove fix_raise).
This commit is contained in:
parent
c1c23f66f4
commit
2fda69b4d6
@ -57,13 +57,13 @@ def getChannel(msg, args=()):
|
|||||||
'variable ' \
|
'variable ' \
|
||||||
'supybot.reply.requireChannelCommandsToBeSentInChannel ' \
|
'supybot.reply.requireChannelCommandsToBeSentInChannel ' \
|
||||||
'to False.'
|
'to False.'
|
||||||
raise callbacks.Error, s
|
raise callbacks.Error(s)
|
||||||
return args.pop(0)
|
return args.pop(0)
|
||||||
elif ircutils.isChannel(msg.args[0]):
|
elif ircutils.isChannel(msg.args[0]):
|
||||||
return msg.args[0]
|
return msg.args[0]
|
||||||
else:
|
else:
|
||||||
raise callbacks.Error, 'Command must be sent in a channel or ' \
|
raise callbacks.Error('Command must be sent in a channel or ' \
|
||||||
'include a channel in its arguments.'
|
'include a channel in its arguments.')
|
||||||
|
|
||||||
def getArgs(args, required=1, optional=0, wildcard=0):
|
def getArgs(args, required=1, optional=0, wildcard=0):
|
||||||
if len(args) < required:
|
if len(args) < required:
|
||||||
@ -163,12 +163,12 @@ def makeNewAlias(name, alias):
|
|||||||
biggestAt = findBiggestAt(original)
|
biggestAt = findBiggestAt(original)
|
||||||
wildcard = '$*' in original
|
wildcard = '$*' in original
|
||||||
if biggestAt and wildcard:
|
if biggestAt and wildcard:
|
||||||
raise AliasError, 'Can\'t mix $* and optional args (@1, etc.)'
|
raise AliasError('Can\'t mix $* and optional args (@1, etc.)')
|
||||||
if original.count('$*') > 1:
|
if original.count('$*') > 1:
|
||||||
raise AliasError, 'There can be only one $* in an alias.'
|
raise AliasError('There can be only one $* in an alias.')
|
||||||
testTokens = callbacks.tokenize(original)
|
testTokens = callbacks.tokenize(original)
|
||||||
if testTokens and isinstance(testTokens[0], list):
|
if testTokens and isinstance(testTokens[0], list):
|
||||||
raise AliasError, 'Commands may not be the result of nesting.'
|
raise AliasError('Commands may not be the result of nesting.')
|
||||||
def f(self, irc, msg, args):
|
def f(self, irc, msg, args):
|
||||||
alias = original.replace('$nick', msg.nick)
|
alias = original.replace('$nick', msg.nick)
|
||||||
if '$channel' in original:
|
if '$channel' in original:
|
||||||
@ -333,21 +333,21 @@ class Alias(callbacks.Plugin):
|
|||||||
realName = callbacks.canonicalName(name)
|
realName = callbacks.canonicalName(name)
|
||||||
if name != realName:
|
if name != realName:
|
||||||
s = format(_('That name isn\'t valid. Try %q instead.'), realName)
|
s = format(_('That name isn\'t valid. Try %q instead.'), realName)
|
||||||
raise AliasError, s
|
raise AliasError(s)
|
||||||
name = realName
|
name = realName
|
||||||
if self.isCommandMethod(name):
|
if self.isCommandMethod(name):
|
||||||
if realName not in self.aliases:
|
if realName not in self.aliases:
|
||||||
s = 'You can\'t overwrite commands in this plugin.'
|
s = 'You can\'t overwrite commands in this plugin.'
|
||||||
raise AliasError, s
|
raise AliasError(s)
|
||||||
if name in self.aliases:
|
if name in self.aliases:
|
||||||
(currentAlias, locked, _) = self.aliases[name]
|
(currentAlias, locked, _) = self.aliases[name]
|
||||||
if locked and currentAlias != alias:
|
if locked and currentAlias != alias:
|
||||||
raise AliasError, format('Alias %q is locked.', name)
|
raise AliasError(format('Alias %q is locked.', name))
|
||||||
try:
|
try:
|
||||||
f = makeNewAlias(name, alias)
|
f = makeNewAlias(name, alias)
|
||||||
f = types.MethodType(f, self)
|
f = types.MethodType(f, self)
|
||||||
except RecursiveAlias:
|
except RecursiveAlias:
|
||||||
raise AliasError, 'You can\'t define a recursive alias.'
|
raise AliasError('You can\'t define a recursive alias.')
|
||||||
if '.' in name or '|' in name:
|
if '.' in name or '|' in name:
|
||||||
aliasGroup = self.registryValue('escapedaliases', value=False)
|
aliasGroup = self.registryValue('escapedaliases', value=False)
|
||||||
confname = escapeAlias(name)
|
confname = escapeAlias(name)
|
||||||
@ -374,9 +374,9 @@ class Alias(callbacks.Plugin):
|
|||||||
else:
|
else:
|
||||||
conf.supybot.plugins.Alias.aliases.unregister(name)
|
conf.supybot.plugins.Alias.aliases.unregister(name)
|
||||||
else:
|
else:
|
||||||
raise AliasError, 'That alias is locked.'
|
raise AliasError('That alias is locked.')
|
||||||
else:
|
else:
|
||||||
raise AliasError, 'There is no such alias.'
|
raise AliasError('There is no such alias.')
|
||||||
|
|
||||||
@internationalizeDocstring
|
@internationalizeDocstring
|
||||||
def add(self, irc, msg, args, name, alias):
|
def add(self, irc, msg, args, name, alias):
|
||||||
|
@ -51,7 +51,7 @@ _ = PluginInternationalization('Config')
|
|||||||
def getWrapper(name):
|
def getWrapper(name):
|
||||||
parts = registry.split(name)
|
parts = registry.split(name)
|
||||||
if not parts or parts[0] not in ('supybot', 'users'):
|
if not parts or parts[0] not in ('supybot', 'users'):
|
||||||
raise InvalidRegistryName, name
|
raise InvalidRegistryName(name)
|
||||||
group = getattr(conf, parts.pop(0))
|
group = getattr(conf, parts.pop(0))
|
||||||
while parts:
|
while parts:
|
||||||
try:
|
try:
|
||||||
@ -60,7 +60,7 @@ def getWrapper(name):
|
|||||||
# that we have a useful error message for the user.
|
# that we have a useful error message for the user.
|
||||||
except (registry.NonExistentRegistryEntry,
|
except (registry.NonExistentRegistryEntry,
|
||||||
registry.InvalidRegistryName):
|
registry.InvalidRegistryName):
|
||||||
raise registry.InvalidRegistryName, name
|
raise registry.InvalidRegistryName(name)
|
||||||
return group
|
return group
|
||||||
|
|
||||||
def getCapability(name):
|
def getCapability(name):
|
||||||
|
@ -65,8 +65,8 @@ class Connection:
|
|||||||
|
|
||||||
code, text = self.getresultcode()
|
code, text = self.getresultcode()
|
||||||
if code < 200 or code >= 300:
|
if code < 200 or code >= 300:
|
||||||
raise Exception, "Got '%s' when 200-class response expected" % \
|
raise Exception("Got '%s' when 200-class response expected" % \
|
||||||
line
|
line)
|
||||||
return [code, text]
|
return [code, text]
|
||||||
|
|
||||||
def get100block(self):
|
def get100block(self):
|
||||||
@ -86,8 +86,8 @@ class Connection:
|
|||||||
finalcode]"""
|
finalcode]"""
|
||||||
code, text = self.getresultcode()
|
code, text = self.getresultcode()
|
||||||
if code < 100 or code >= 200:
|
if code < 100 or code >= 200:
|
||||||
raise Exception, "Got '%s' when 100-class response expected" % \
|
raise Exception("Got '%s' when 100-class response expected" % \
|
||||||
code
|
code)
|
||||||
|
|
||||||
bodylines = self.get100block().split("\n")
|
bodylines = self.get100block().split("\n")
|
||||||
|
|
||||||
@ -157,7 +157,7 @@ class Connection:
|
|||||||
|
|
||||||
if dbname != '*' and dbname != '!' and \
|
if dbname != '*' and dbname != '!' and \
|
||||||
not dbname in self.dbdescs.keys():
|
not dbname in self.dbdescs.keys():
|
||||||
raise Exception, "Invalid database name '%s'" % dbname
|
raise Exception("Invalid database name '%s'" % dbname)
|
||||||
|
|
||||||
self.dbobjs[dbname] = Database(self, dbname)
|
self.dbobjs[dbname] = Database(self, dbname)
|
||||||
return self.dbobjs[dbname]
|
return self.dbobjs[dbname]
|
||||||
@ -181,7 +181,7 @@ class Connection:
|
|||||||
|
|
||||||
if database != '*' and database != '!' and \
|
if database != '*' and database != '!' and \
|
||||||
not database in self.getdbdescs():
|
not database in self.getdbdescs():
|
||||||
raise Exception, "Invalid database '%s' specified" % database
|
raise Exception("Invalid database '%s' specified" % database)
|
||||||
|
|
||||||
self.sendcommand("DEFINE " + enquote(database) + " " + enquote(word))
|
self.sendcommand("DEFINE " + enquote(database) + " " + enquote(word))
|
||||||
code = self.getresultcode()[0]
|
code = self.getresultcode()[0]
|
||||||
@ -192,7 +192,7 @@ class Connection:
|
|||||||
# No definitions.
|
# No definitions.
|
||||||
return []
|
return []
|
||||||
if code != 150:
|
if code != 150:
|
||||||
raise Exception, "Unknown code %d" % code
|
raise Exception("Unknown code %d" % code)
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
code, text = self.getresultcode()
|
code, text = self.getresultcode()
|
||||||
@ -217,10 +217,10 @@ class Connection:
|
|||||||
self.getstratdescs() # Prime the cache
|
self.getstratdescs() # Prime the cache
|
||||||
self.getdbdescs() # Prime the cache
|
self.getdbdescs() # Prime the cache
|
||||||
if not strategy in self.getstratdescs().keys():
|
if not strategy in self.getstratdescs().keys():
|
||||||
raise Exception, "Invalid strategy '%s'" % strategy
|
raise Exception("Invalid strategy '%s'" % strategy)
|
||||||
if database != '*' and database != '!' and \
|
if database != '*' and database != '!' and \
|
||||||
not database in self.getdbdescs().keys():
|
not database in self.getdbdescs().keys():
|
||||||
raise Exception, "Invalid database name '%s'" % database
|
raise Exception("Invalid database name '%s'" % database)
|
||||||
|
|
||||||
self.sendcommand("MATCH %s %s %s" % (enquote(database),
|
self.sendcommand("MATCH %s %s %s" % (enquote(database),
|
||||||
enquote(strategy),
|
enquote(strategy),
|
||||||
@ -230,7 +230,7 @@ class Connection:
|
|||||||
# No Matches
|
# No Matches
|
||||||
return []
|
return []
|
||||||
if code != 152:
|
if code != 152:
|
||||||
raise Exception, "Unexpected code %d" % code
|
raise Exception("Unexpected code %d" % code)
|
||||||
|
|
||||||
retval = []
|
retval = []
|
||||||
|
|
||||||
@ -239,7 +239,7 @@ class Connection:
|
|||||||
retval.append(Definition(self, self.getdbobj(matchdict),
|
retval.append(Definition(self, self.getdbobj(matchdict),
|
||||||
dequote(matchword)))
|
dequote(matchword)))
|
||||||
if self.getresultcode()[0] != 250:
|
if self.getresultcode()[0] != 250:
|
||||||
raise Exception, "Unexpected end-of-list code %d" % code
|
raise Exception("Unexpected end-of-list code %d" % code)
|
||||||
return retval
|
return retval
|
||||||
|
|
||||||
class Database:
|
class Database:
|
||||||
|
@ -120,7 +120,7 @@ class Google(callbacks.PluginRegexp):
|
|||||||
headers=headers).decode('utf8')
|
headers=headers).decode('utf8')
|
||||||
data = json.loads(text)
|
data = json.loads(text)
|
||||||
if data['responseStatus'] != 200:
|
if data['responseStatus'] != 200:
|
||||||
raise callbacks.Error, _('We broke The Google!')
|
raise callbacks.Error(_('We broke The Google!'))
|
||||||
return data
|
return data
|
||||||
|
|
||||||
def formatData(self, data, bold=True, max=0, onetoone=False):
|
def formatData(self, data, bold=True, max=0, onetoone=False):
|
||||||
|
@ -167,7 +167,7 @@ class SqliteKarmaDB(object):
|
|||||||
elif kind == 'active':
|
elif kind == 'active':
|
||||||
orderby = 'added+subtracted'
|
orderby = 'added+subtracted'
|
||||||
else:
|
else:
|
||||||
raise ValueError, 'invalid kind'
|
raise ValueError('invalid kind')
|
||||||
sql = """SELECT name, %s FROM karma ORDER BY %s DESC LIMIT %s""" % \
|
sql = """SELECT name, %s FROM karma ORDER BY %s DESC LIMIT %s""" % \
|
||||||
(orderby, orderby, limit)
|
(orderby, orderby, limit)
|
||||||
db = self._getDb(channel)
|
db = self._getDb(channel)
|
||||||
|
@ -937,12 +937,12 @@ class UnitGroup:
|
|||||||
while tmpList:
|
while tmpList:
|
||||||
count += 1
|
count += 1
|
||||||
if count > 5000:
|
if count > 5000:
|
||||||
raise UnitDataError, 'Circular unit definition'
|
raise UnitDataError('Circular unit definition')
|
||||||
unit = tmpList.pop(0)
|
unit = tmpList.pop(0)
|
||||||
if unit.equiv == '!':
|
if unit.equiv == '!':
|
||||||
self.reducedList.append(copy.copy(unit))
|
self.reducedList.append(copy.copy(unit))
|
||||||
elif not unit.equiv:
|
elif not unit.equiv:
|
||||||
raise UnitDataError, 'Invalid conversion for "%s"' % unit.name
|
raise UnitDataError('Invalid conversion for "%s"' % unit.name)
|
||||||
else:
|
else:
|
||||||
if unit.fromEqn:
|
if unit.fromEqn:
|
||||||
self.linear = 0
|
self.linear = 0
|
||||||
@ -1029,7 +1029,7 @@ class UnitGroup:
|
|||||||
except OverflowError:
|
except OverflowError:
|
||||||
return 1e9999
|
return 1e9999
|
||||||
except:
|
except:
|
||||||
raise UnitDataError, 'Bad equation for %s' % self.unitList[0].name
|
raise UnitDataError('Bad equation for %s' % self.unitList[0].name)
|
||||||
|
|
||||||
def convertStr(self, num, toGroup):
|
def convertStr(self, num, toGroup):
|
||||||
"Return formatted string of converted number"
|
"Return formatted string of converted number"
|
||||||
@ -1063,7 +1063,7 @@ class UnitData(dict):
|
|||||||
lines = f.readlines()
|
lines = f.readlines()
|
||||||
f.close()
|
f.close()
|
||||||
except IOError:
|
except IOError:
|
||||||
raise UnitDataError, 'Can not read "units.dat" file'
|
raise UnitDataError('Can not read "units.dat" file')
|
||||||
for i in range(len(lines)): # join continuation lines
|
for i in range(len(lines)): # join continuation lines
|
||||||
delta = 1
|
delta = 1
|
||||||
while lines[i].rstrip().endswith('\\'):
|
while lines[i].rstrip().endswith('\\'):
|
||||||
@ -1087,7 +1087,7 @@ class UnitData(dict):
|
|||||||
self.sortedKeys.sort()
|
self.sortedKeys.sort()
|
||||||
|
|
||||||
if len(self.sortedKeys) < len(units):
|
if len(self.sortedKeys) < len(units):
|
||||||
raise UnitDataError, 'Duplicate unit names found'
|
raise UnitDataError('Duplicate unit names found')
|
||||||
|
|
||||||
return (types, typeUnits)
|
return (types, typeUnits)
|
||||||
|
|
||||||
@ -1132,7 +1132,7 @@ class Unit:
|
|||||||
self.toEqn = self.toEqn.strip()
|
self.toEqn = self.toEqn.strip()
|
||||||
self.fromEqn = self.fromEqn.strip()
|
self.fromEqn = self.fromEqn.strip()
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
raise UnitDataError, 'Bad equation for "%s"' % self.name
|
raise UnitDataError('Bad equation for "%s"' % self.name)
|
||||||
else: # split factor and equiv unit for linear
|
else: # split factor and equiv unit for linear
|
||||||
parts = self.equiv.split(None, 1)
|
parts = self.equiv.split(None, 1)
|
||||||
if len(parts) > 1 and re.search('[^\d\.eE\+\-\*/]', parts[0]) \
|
if len(parts) > 1 and re.search('[^\d\.eE\+\-\*/]', parts[0]) \
|
||||||
|
@ -376,7 +376,7 @@ class MoobotFactoids(callbacks.Plugin):
|
|||||||
self.log.debug('Invalid tokens for {add,replace}Factoid: %s.',
|
self.log.debug('Invalid tokens for {add,replace}Factoid: %s.',
|
||||||
tokens)
|
tokens)
|
||||||
s = _('Missing an \'is\' or \'_is_\'.')
|
s = _('Missing an \'is\' or \'_is_\'.')
|
||||||
raise ValueError, s
|
raise ValueError(s)
|
||||||
(key, newfact) = map(' '.join, utils.iter.split(p, tokens, maxsplit=1))
|
(key, newfact) = map(' '.join, utils.iter.split(p, tokens, maxsplit=1))
|
||||||
key = self._sanitizeKey(key)
|
key = self._sanitizeKey(key)
|
||||||
return (key, newfact)
|
return (key, newfact)
|
||||||
|
@ -50,8 +50,7 @@ class Network(callbacks.Plugin):
|
|||||||
if irc:
|
if irc:
|
||||||
return irc
|
return irc
|
||||||
else:
|
else:
|
||||||
raise callbacks.Error, \
|
raise callbacks.Error('I\'m not currently connected to %s.' % network)
|
||||||
'I\'m not currently connected to %s.' % network
|
|
||||||
|
|
||||||
@internationalizeDocstring
|
@internationalizeDocstring
|
||||||
def connect(self, irc, msg, args, opts, network, server, password):
|
def connect(self, irc, msg, args, opts, network, server, password):
|
||||||
|
@ -169,8 +169,8 @@ class Owner(callbacks.Plugin):
|
|||||||
(server, port) = group.servers()[0]
|
(server, port) = group.servers()[0]
|
||||||
except (registry.NonExistentRegistryEntry, IndexError):
|
except (registry.NonExistentRegistryEntry, IndexError):
|
||||||
if serverPort is None:
|
if serverPort is None:
|
||||||
raise ValueError, 'connect requires a (server, port) ' \
|
raise ValueError('connect requires a (server, port) ' \
|
||||||
'if the network is not registered.'
|
'if the network is not registered.')
|
||||||
conf.registerNetwork(network, password, ssl)
|
conf.registerNetwork(network, password, ssl)
|
||||||
serverS = '%s:%s' % serverPort
|
serverS = '%s:%s' % serverPort
|
||||||
conf.supybot.networks.get(network).servers.append(serverS)
|
conf.supybot.networks.get(network).servers.append(serverS)
|
||||||
|
@ -286,7 +286,7 @@ class RSS(callbacks.Plugin):
|
|||||||
raise results['bozo_exception']
|
raise results['bozo_exception']
|
||||||
except feedparser.sgmllib.SGMLParseError:
|
except feedparser.sgmllib.SGMLParseError:
|
||||||
self.log.exception('Uncaught exception from feedparser:')
|
self.log.exception('Uncaught exception from feedparser:')
|
||||||
raise callbacks.Error, 'Invalid (unparsable) RSS feed.'
|
raise callbacks.Error('Invalid (unparsable) RSS feed.')
|
||||||
except socket.timeout:
|
except socket.timeout:
|
||||||
return error('Timeout downloading feed.')
|
return error('Timeout downloading feed.')
|
||||||
except Exception, e:
|
except Exception, e:
|
||||||
@ -366,7 +366,7 @@ class RSS(callbacks.Plugin):
|
|||||||
self.locks[url] = threading.RLock()
|
self.locks[url] = threading.RLock()
|
||||||
if self.isCommandMethod(name):
|
if self.isCommandMethod(name):
|
||||||
s = format('I already have a command in this plugin named %s.',name)
|
s = format('I already have a command in this plugin named %s.',name)
|
||||||
raise callbacks.Error, s
|
raise callbacks.Error(s)
|
||||||
def f(self, irc, msg, args):
|
def f(self, irc, msg, args):
|
||||||
args.insert(0, url)
|
args.insert(0, url)
|
||||||
self.rss(irc, msg, args)
|
self.rss(irc, msg, args)
|
||||||
|
@ -58,8 +58,7 @@ def configure(advanced):
|
|||||||
class ValidNickOrEmptyString(registry.String):
|
class ValidNickOrEmptyString(registry.String):
|
||||||
def setValue(self, v):
|
def setValue(self, v):
|
||||||
if v and not ircutils.isNick(v):
|
if v and not ircutils.isNick(v):
|
||||||
raise registry.InvalidRegistryValue, \
|
raise registry.InvalidRegistryValue('Value must be a valid nick or the empty string.')
|
||||||
'Value must be a valid nick or the empty string.'
|
|
||||||
registry.String.setValue(self, v)
|
registry.String.setValue(self, v)
|
||||||
|
|
||||||
class ValidNickSet(conf.ValidNicks):
|
class ValidNickSet(conf.ValidNicks):
|
||||||
|
@ -62,9 +62,8 @@ class ShrinkCycle(registry.SpaceSeparatedListOfStrings):
|
|||||||
if L:
|
if L:
|
||||||
self.lastIndex = (self.lastIndex + 1) % len(L)
|
self.lastIndex = (self.lastIndex + 1) % len(L)
|
||||||
return L[self.lastIndex]
|
return L[self.lastIndex]
|
||||||
raise ValueError, \
|
raise ValueError('No services have been configured for rotation. ' \
|
||||||
'No services have been configured for rotation. ' \
|
'See conf.supybot.plugins.ShrinkUrl.serviceRotation.')
|
||||||
'See conf.supybot.plugins.ShrinkUrl.serviceRotation.'
|
|
||||||
|
|
||||||
ShrinkUrl = conf.registerPlugin('ShrinkUrl')
|
ShrinkUrl = conf.registerPlugin('ShrinkUrl')
|
||||||
conf.registerChannelValue(ShrinkUrl, 'shrinkSnarfer',
|
conf.registerChannelValue(ShrinkUrl, 'shrinkSnarfer',
|
||||||
|
@ -182,7 +182,7 @@ class ShrinkUrl(callbacks.PluginRegexp):
|
|||||||
self.db.set('ln', url, text)
|
self.db.set('ln', url, text)
|
||||||
return text
|
return text
|
||||||
else:
|
else:
|
||||||
raise ShrinkError, text
|
raise ShrinkError(text)
|
||||||
|
|
||||||
@internationalizeDocstring
|
@internationalizeDocstring
|
||||||
def ln(self, irc, msg, args, url):
|
def ln(self, irc, msg, args, url):
|
||||||
@ -207,7 +207,7 @@ class ShrinkUrl(callbacks.PluginRegexp):
|
|||||||
text = utils.web.getUrl('http://tinyurl.com/api-create.php?url=' + url)
|
text = utils.web.getUrl('http://tinyurl.com/api-create.php?url=' + url)
|
||||||
text = text.decode()
|
text = text.decode()
|
||||||
if text.startswith('Error'):
|
if text.startswith('Error'):
|
||||||
raise ShrinkError, text[5:]
|
raise ShrinkError(text[5:])
|
||||||
self.db.set('tiny', url, text)
|
self.db.set('tiny', url, text)
|
||||||
return text
|
return text
|
||||||
|
|
||||||
@ -236,7 +236,7 @@ class ShrinkUrl(callbacks.PluginRegexp):
|
|||||||
data = utils.web.urlencode({'long_url': url})
|
data = utils.web.urlencode({'long_url': url})
|
||||||
text = utils.web.getUrl(self._xrlApi, data=data).decode()
|
text = utils.web.getUrl(self._xrlApi, data=data).decode()
|
||||||
if text.startswith('ERROR:'):
|
if text.startswith('ERROR:'):
|
||||||
raise ShrinkError, text[6:]
|
raise ShrinkError(text[6:])
|
||||||
self.db.set('xrl', quotedurl, text)
|
self.db.set('xrl', quotedurl, text)
|
||||||
return text
|
return text
|
||||||
|
|
||||||
@ -271,7 +271,7 @@ class ShrinkUrl(callbacks.PluginRegexp):
|
|||||||
self.db.set('goo', url, googl)
|
self.db.set('goo', url, googl)
|
||||||
return googl
|
return googl
|
||||||
else:
|
else:
|
||||||
raise ShrinkError, text
|
raise ShrinkError(text)
|
||||||
|
|
||||||
def goo(self, irc, msg, args, url):
|
def goo(self, irc, msg, args, url):
|
||||||
"""<url>
|
"""<url>
|
||||||
@ -301,7 +301,7 @@ class ShrinkUrl(callbacks.PluginRegexp):
|
|||||||
self.db.set('ur1', url, ur1ca)
|
self.db.set('ur1', url, ur1ca)
|
||||||
return ur1ca
|
return ur1ca
|
||||||
else:
|
else:
|
||||||
raise ShrinkError, text
|
raise ShrinkError(text)
|
||||||
|
|
||||||
def ur1(self, irc, msg, args, url):
|
def ur1(self, irc, msg, args, url):
|
||||||
"""<url>
|
"""<url>
|
||||||
@ -325,7 +325,7 @@ class ShrinkUrl(callbacks.PluginRegexp):
|
|||||||
except KeyError:
|
except KeyError:
|
||||||
text = utils.web.getUrl(self._x0Api % url).decode()
|
text = utils.web.getUrl(self._x0Api % url).decode()
|
||||||
if text.startswith('ERROR:'):
|
if text.startswith('ERROR:'):
|
||||||
raise ShrinkError, text[6:]
|
raise ShrinkError(text[6:])
|
||||||
self.db.set('x0', url, text)
|
self.db.set('x0', url, text)
|
||||||
return text
|
return text
|
||||||
|
|
||||||
|
@ -45,7 +45,7 @@ _ = PluginInternationalization('User')
|
|||||||
class User(callbacks.Plugin):
|
class User(callbacks.Plugin):
|
||||||
def _checkNotChannel(self, irc, msg, password=' '):
|
def _checkNotChannel(self, irc, msg, password=' '):
|
||||||
if password and irc.isChannel(msg.args[0]):
|
if password and irc.isChannel(msg.args[0]):
|
||||||
raise callbacks.Error, conf.supybot.replies.requiresPrivacy()
|
raise callbacks.Error(conf.supybot.replies.requiresPrivacy())
|
||||||
|
|
||||||
@internationalizeDocstring
|
@internationalizeDocstring
|
||||||
def list(self, irc, msg, args, optlist, glob):
|
def list(self, irc, msg, args, optlist, glob):
|
||||||
|
@ -83,7 +83,7 @@ def DB(filename, types):
|
|||||||
return types[type](fn, *args, **kwargs)
|
return types[type](fn, *args, **kwargs)
|
||||||
except KeyError:
|
except KeyError:
|
||||||
continue
|
continue
|
||||||
raise NoSuitableDatabase, types.keys()
|
raise NoSuitableDatabase(types.keys())
|
||||||
return MakeDB
|
return MakeDB
|
||||||
|
|
||||||
def makeChannelFilename(filename, channel=None, dirname=None):
|
def makeChannelFilename(filename, channel=None, dirname=None):
|
||||||
@ -503,7 +503,7 @@ class PeriodicFileDownloader(object):
|
|||||||
periodicFiles = None
|
periodicFiles = None
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
if self.periodicFiles is None:
|
if self.periodicFiles is None:
|
||||||
raise ValueError, 'You must provide files to download'
|
raise ValueError('You must provide files to download')
|
||||||
self.lastDownloaded = {}
|
self.lastDownloaded = {}
|
||||||
self.downloadedCounter = {}
|
self.downloadedCounter = {}
|
||||||
for filename in self.periodicFiles:
|
for filename in self.periodicFiles:
|
||||||
|
1
setup.py
1
setup.py
@ -155,7 +155,6 @@ try:
|
|||||||
'fix_itertools', 'fix_itertools_imports', 'fix_long',
|
'fix_itertools', 'fix_itertools_imports', 'fix_long',
|
||||||
'fix_map', 'fix_metaclass', 'fix_methodattrs',
|
'fix_map', 'fix_metaclass', 'fix_methodattrs',
|
||||||
'fix_numliterals',
|
'fix_numliterals',
|
||||||
'fix_raise',
|
|
||||||
'fix_reduce', 'fix_renames', 'fix_repr',
|
'fix_reduce', 'fix_renames', 'fix_repr',
|
||||||
'fix_set_literal', 'fix_standarderror', 'fix_sys_exc',
|
'fix_set_literal', 'fix_standarderror', 'fix_sys_exc',
|
||||||
'fix_throw', 'fix_tuple_params', 'fix_types',
|
'fix_throw', 'fix_tuple_params', 'fix_types',
|
||||||
|
@ -315,11 +315,11 @@ class Tokenizer(object):
|
|||||||
while True:
|
while True:
|
||||||
token = lexer.get_token()
|
token = lexer.get_token()
|
||||||
if not token:
|
if not token:
|
||||||
raise SyntaxError, _('Missing "%s". You may want to '
|
raise SyntaxError(_('Missing "%s". You may want to '
|
||||||
'quote your arguments with double '
|
'quote your arguments with double '
|
||||||
'quotes in order to prevent extra '
|
'quotes in order to prevent extra '
|
||||||
'brackets from being evaluated '
|
'brackets from being evaluated '
|
||||||
'as nested commands.') % self.right
|
'as nested commands.') % self.right)
|
||||||
elif token == self.right:
|
elif token == self.right:
|
||||||
return ret
|
return ret
|
||||||
elif token == self.left:
|
elif token == self.left:
|
||||||
@ -345,26 +345,26 @@ class Tokenizer(object):
|
|||||||
# for strings like 'foo | bar', where a pipe stands alone as a
|
# for strings like 'foo | bar', where a pipe stands alone as a
|
||||||
# token, but shouldn't be treated specially.
|
# token, but shouldn't be treated specially.
|
||||||
if not args:
|
if not args:
|
||||||
raise SyntaxError, _('"|" with nothing preceding. I '
|
raise SyntaxError(_('"|" with nothing preceding. I '
|
||||||
'obviously can\'t do a pipe with '
|
'obviously can\'t do a pipe with '
|
||||||
'nothing before the |.')
|
'nothing before the |.'))
|
||||||
ends.append(args)
|
ends.append(args)
|
||||||
args = []
|
args = []
|
||||||
elif token == self.left:
|
elif token == self.left:
|
||||||
args.append(self._insideBrackets(lexer))
|
args.append(self._insideBrackets(lexer))
|
||||||
elif token == self.right:
|
elif token == self.right:
|
||||||
raise SyntaxError, _('Spurious "%s". You may want to '
|
raise SyntaxError(_('Spurious "%s". You may want to '
|
||||||
'quote your arguments with double '
|
'quote your arguments with double '
|
||||||
'quotes in order to prevent extra '
|
'quotes in order to prevent extra '
|
||||||
'brackets from being evaluated '
|
'brackets from being evaluated '
|
||||||
'as nested commands.') % self.right
|
'as nested commands.') % self.right)
|
||||||
else:
|
else:
|
||||||
args.append(self._handleToken(token))
|
args.append(self._handleToken(token))
|
||||||
if ends:
|
if ends:
|
||||||
if not args:
|
if not args:
|
||||||
raise SyntaxError, _('"|" with nothing following. I '
|
raise SyntaxError(_('"|" with nothing following. I '
|
||||||
'obviously can\'t do a pipe with '
|
'obviously can\'t do a pipe with '
|
||||||
'nothing after the |.')
|
'nothing after the |.'))
|
||||||
args.append(ends.pop())
|
args.append(ends.pop())
|
||||||
while ends:
|
while ends:
|
||||||
args[-1].append(ends.pop())
|
args[-1].append(ends.pop())
|
||||||
@ -385,7 +385,7 @@ def tokenize(s, channel=None):
|
|||||||
ret = Tokenizer(brackets=brackets,pipe=pipe,quotes=quotes).tokenize(s)
|
ret = Tokenizer(brackets=brackets,pipe=pipe,quotes=quotes).tokenize(s)
|
||||||
return ret
|
return ret
|
||||||
except ValueError, e:
|
except ValueError, e:
|
||||||
raise SyntaxError, str(e)
|
raise SyntaxError(str(e))
|
||||||
|
|
||||||
def formatCommand(command):
|
def formatCommand(command):
|
||||||
return ' '.join(command)
|
return ' '.join(command)
|
||||||
@ -399,7 +399,7 @@ def checkCommandCapability(msg, cb, commandName):
|
|||||||
if ircdb.checkCapability(msg.prefix, capability):
|
if ircdb.checkCapability(msg.prefix, capability):
|
||||||
log.info('Preventing %s from calling %s because of %s.',
|
log.info('Preventing %s from calling %s because of %s.',
|
||||||
msg.prefix, pluginCommand, capability)
|
msg.prefix, pluginCommand, capability)
|
||||||
raise RuntimeError, capability
|
raise RuntimeError(capability)
|
||||||
try:
|
try:
|
||||||
antiPlugin = ircdb.makeAntiCapability(plugin)
|
antiPlugin = ircdb.makeAntiCapability(plugin)
|
||||||
antiCommand = ircdb.makeAntiCapability(commandName)
|
antiCommand = ircdb.makeAntiCapability(commandName)
|
||||||
@ -497,7 +497,7 @@ class RichReplyMethods(object):
|
|||||||
|
|
||||||
def _error(self, s, Raise=False, **kwargs):
|
def _error(self, s, Raise=False, **kwargs):
|
||||||
if Raise:
|
if Raise:
|
||||||
raise Error, s
|
raise Error(s)
|
||||||
else:
|
else:
|
||||||
return self.error(s, **kwargs)
|
return self.error(s, **kwargs)
|
||||||
|
|
||||||
@ -598,7 +598,7 @@ class ReplyIrcProxy(RichReplyMethods):
|
|||||||
def error(self, s, msg=None, **kwargs):
|
def error(self, s, msg=None, **kwargs):
|
||||||
if 'Raise' in kwargs and kwargs['Raise']:
|
if 'Raise' in kwargs and kwargs['Raise']:
|
||||||
if s:
|
if s:
|
||||||
raise Error, s
|
raise Error(s)
|
||||||
else:
|
else:
|
||||||
raise ArgumentError
|
raise ArgumentError
|
||||||
if msg is None:
|
if msg is None:
|
||||||
@ -992,7 +992,7 @@ class NestedCommandsIrcProxy(ReplyIrcProxy):
|
|||||||
self.repliedTo = True
|
self.repliedTo = True
|
||||||
if Raise:
|
if Raise:
|
||||||
if s:
|
if s:
|
||||||
raise Error, s
|
raise Error(s)
|
||||||
else:
|
else:
|
||||||
raise ArgumentError
|
raise ArgumentError
|
||||||
if s:
|
if s:
|
||||||
|
10
src/cdb.py
10
src/cdb.py
@ -80,7 +80,7 @@ def open_db(filename, mode='r', **kwargs):
|
|||||||
maker.finish()
|
maker.finish()
|
||||||
return ReaderWriter(filename, **kwargs)
|
return ReaderWriter(filename, **kwargs)
|
||||||
else:
|
else:
|
||||||
raise ValueError, 'Invalid flag: %s' % mode
|
raise ValueError('Invalid flag: %s' % mode)
|
||||||
|
|
||||||
def shelf(filename, *args, **kwargs):
|
def shelf(filename, *args, **kwargs):
|
||||||
"""Opens a new shelf database object."""
|
"""Opens a new shelf database object."""
|
||||||
@ -257,7 +257,7 @@ class Reader(utils.IterableMap):
|
|||||||
try:
|
try:
|
||||||
return self.default
|
return self.default
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
raise KeyError, key
|
raise KeyError(key)
|
||||||
|
|
||||||
def findall(self, key):
|
def findall(self, key):
|
||||||
ret = []
|
ret = []
|
||||||
@ -377,7 +377,7 @@ class ReaderWriter(utils.IterableMap):
|
|||||||
|
|
||||||
def __getitem__(self, key):
|
def __getitem__(self, key):
|
||||||
if key in self.removals:
|
if key in self.removals:
|
||||||
raise KeyError, key
|
raise KeyError(key)
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
return self.adds[key]
|
return self.adds[key]
|
||||||
@ -386,7 +386,7 @@ class ReaderWriter(utils.IterableMap):
|
|||||||
|
|
||||||
def __delitem__(self, key):
|
def __delitem__(self, key):
|
||||||
if key in self.removals:
|
if key in self.removals:
|
||||||
raise KeyError, key
|
raise KeyError(key)
|
||||||
else:
|
else:
|
||||||
if key in self.adds and key in self.cdb:
|
if key in self.adds and key in self.cdb:
|
||||||
self._journalRemoveKey(key)
|
self._journalRemoveKey(key)
|
||||||
@ -398,7 +398,7 @@ class ReaderWriter(utils.IterableMap):
|
|||||||
elif key in self.cdb:
|
elif key in self.cdb:
|
||||||
self._journalRemoveKey(key)
|
self._journalRemoveKey(key)
|
||||||
else:
|
else:
|
||||||
raise KeyError, key
|
raise KeyError(key)
|
||||||
self.mods += 1
|
self.mods += 1
|
||||||
self._flushIfOverLimit()
|
self._flushIfOverLimit()
|
||||||
|
|
||||||
|
@ -121,7 +121,7 @@ def process(f, *args, **kwargs):
|
|||||||
p.join(timeout)
|
p.join(timeout)
|
||||||
if p.is_alive():
|
if p.is_alive():
|
||||||
p.terminate()
|
p.terminate()
|
||||||
raise ProcessTimeoutError, "%s aborted due to timeout." % (p.name,)
|
raise ProcessTimeoutError("%s aborted due to timeout." % (p.name,))
|
||||||
try:
|
try:
|
||||||
v = q.get(block=False)
|
v = q.get(block=False)
|
||||||
except Queue.Empty:
|
except Queue.Empty:
|
||||||
@ -799,7 +799,7 @@ def getConverter(name):
|
|||||||
try:
|
try:
|
||||||
return wrappers[name]
|
return wrappers[name]
|
||||||
except KeyError, e:
|
except KeyError, e:
|
||||||
raise UnknownConverter, str(e)
|
raise UnknownConverter(str(e))
|
||||||
|
|
||||||
def callConverter(name, irc, msg, args, state, *L):
|
def callConverter(name, irc, msg, args, state, *L):
|
||||||
getConverter(name)(irc, msg, args, state, *L)
|
getConverter(name)(irc, msg, args, state, *L)
|
||||||
@ -1024,7 +1024,7 @@ class State(object):
|
|||||||
self.errored = True
|
self.errored = True
|
||||||
return getattr(dynamic.irc, attr)
|
return getattr(dynamic.irc, attr)
|
||||||
else:
|
else:
|
||||||
raise AttributeError, attr
|
raise AttributeError(attr)
|
||||||
|
|
||||||
def essence(self):
|
def essence(self):
|
||||||
st = State(self.types)
|
st = State(self.types)
|
||||||
|
@ -142,7 +142,7 @@ class DirMapping(MappingInterface):
|
|||||||
try:
|
try:
|
||||||
os.remove(self._makeFilename(id))
|
os.remove(self._makeFilename(id))
|
||||||
except EnvironmentError, e:
|
except EnvironmentError, e:
|
||||||
raise NoRecordError, id
|
raise NoRecordError(id)
|
||||||
|
|
||||||
class FlatfileMapping(MappingInterface):
|
class FlatfileMapping(MappingInterface):
|
||||||
def __init__(self, filename, maxSize=10**6):
|
def __init__(self, filename, maxSize=10**6):
|
||||||
@ -154,7 +154,7 @@ class FlatfileMapping(MappingInterface):
|
|||||||
try:
|
try:
|
||||||
self.currentId = int(strId)
|
self.currentId = int(strId)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
raise Error, 'Invalid file for FlatfileMapping: %s' % filename
|
raise Error('Invalid file for FlatfileMapping: %s' % filename)
|
||||||
except EnvironmentError, e:
|
except EnvironmentError, e:
|
||||||
# File couldn't be opened.
|
# File couldn't be opened.
|
||||||
self.maxSize = int(math.log10(maxSize))
|
self.maxSize = int(math.log10(maxSize))
|
||||||
@ -209,7 +209,7 @@ class FlatfileMapping(MappingInterface):
|
|||||||
(lineId, s) = self._splitLine(line)
|
(lineId, s) = self._splitLine(line)
|
||||||
if lineId == strId:
|
if lineId == strId:
|
||||||
return s
|
return s
|
||||||
raise NoRecordError, id
|
raise NoRecordError(id)
|
||||||
finally:
|
finally:
|
||||||
fd.close()
|
fd.close()
|
||||||
|
|
||||||
@ -295,7 +295,7 @@ class CdbMapping(MappingInterface):
|
|||||||
try:
|
try:
|
||||||
return self.db[str(id)]
|
return self.db[str(id)]
|
||||||
except KeyError:
|
except KeyError:
|
||||||
raise NoRecordError, id
|
raise NoRecordError(id)
|
||||||
|
|
||||||
# XXX Same as above.
|
# XXX Same as above.
|
||||||
def set(self, id, s):
|
def set(self, id, s):
|
||||||
|
@ -36,7 +36,7 @@ class DynamicScope(object):
|
|||||||
if name in f.f_locals:
|
if name in f.f_locals:
|
||||||
return f.f_locals
|
return f.f_locals
|
||||||
f = f.f_back
|
f = f.f_back
|
||||||
raise NameError, name
|
raise NameError(name)
|
||||||
|
|
||||||
def __getattr__(self, name):
|
def __getattr__(self, name):
|
||||||
try:
|
try:
|
||||||
|
29
src/ircdb.py
29
src/ircdb.py
@ -80,7 +80,7 @@ def unAntiCapability(capability):
|
|||||||
"""Takes an anticapability and returns the non-anti form."""
|
"""Takes an anticapability and returns the non-anti form."""
|
||||||
assert isCapability(capability), 'got %s' % capability
|
assert isCapability(capability), 'got %s' % capability
|
||||||
if not isAntiCapability(capability):
|
if not isAntiCapability(capability):
|
||||||
raise ValueError, '%s is not an anti capability' % capability
|
raise ValueError('%s is not an anti capability' % capability)
|
||||||
if isChannelCapability(capability):
|
if isChannelCapability(capability):
|
||||||
(channel, capability) = fromChannelCapability(capability)
|
(channel, capability) = fromChannelCapability(capability)
|
||||||
return ','.join((channel, capability[1:]))
|
return ','.join((channel, capability[1:]))
|
||||||
@ -290,8 +290,7 @@ class IrcUser(object):
|
|||||||
"""Adds a hostmask to the user's hostmasks."""
|
"""Adds a hostmask to the user's hostmasks."""
|
||||||
assert ircutils.isUserHostmask(hostmask), 'got %s' % hostmask
|
assert ircutils.isUserHostmask(hostmask), 'got %s' % hostmask
|
||||||
if len(unWildcardHostmask(hostmask)) < 3:
|
if len(unWildcardHostmask(hostmask)) < 3:
|
||||||
raise ValueError, \
|
raise ValueError('Hostmask must contain at least 3 non-wildcard characters.')
|
||||||
'Hostmask must contain at least 3 non-wildcard characters.'
|
|
||||||
self.hostmasks.add(hostmask)
|
self.hostmasks.add(hostmask)
|
||||||
|
|
||||||
def removeHostmask(self, hostmask):
|
def removeHostmask(self, hostmask):
|
||||||
@ -337,7 +336,7 @@ class IrcUser(object):
|
|||||||
uniqued = list(filter(uniqueHostmask, reversed(self.auth)))
|
uniqued = list(filter(uniqueHostmask, reversed(self.auth)))
|
||||||
self.auth = list(reversed(uniqued))
|
self.auth = list(reversed(uniqued))
|
||||||
else:
|
else:
|
||||||
raise ValueError, 'secure flag set, unmatched hostmask'
|
raise ValueError('secure flag set, unmatched hostmask')
|
||||||
|
|
||||||
def clearAuth(self):
|
def clearAuth(self):
|
||||||
"""Unsets a user's authenticated hostmask."""
|
"""Unsets a user's authenticated hostmask."""
|
||||||
@ -492,7 +491,7 @@ class IrcChannel(object):
|
|||||||
|
|
||||||
class Creator(object):
|
class Creator(object):
|
||||||
def badCommand(self, command, rest, lineno):
|
def badCommand(self, command, rest, lineno):
|
||||||
raise ValueError, 'Invalid command on line %s: %s' % (lineno, command)
|
raise ValueError('Invalid command on line %s: %s' % (lineno, command))
|
||||||
|
|
||||||
class IrcUserCreator(Creator):
|
class IrcUserCreator(Creator):
|
||||||
u = None
|
u = None
|
||||||
@ -503,12 +502,12 @@ class IrcUserCreator(Creator):
|
|||||||
|
|
||||||
def user(self, rest, lineno):
|
def user(self, rest, lineno):
|
||||||
if self.u.id is not None:
|
if self.u.id is not None:
|
||||||
raise ValueError, 'Unexpected user command on line %s.' % lineno
|
raise ValueError('Unexpected user command on line %s.' % lineno)
|
||||||
self.u.id = int(rest)
|
self.u.id = int(rest)
|
||||||
|
|
||||||
def _checkId(self):
|
def _checkId(self):
|
||||||
if self.u.id is None:
|
if self.u.id is None:
|
||||||
raise ValueError, 'Unexpected user description without user.'
|
raise ValueError('Unexpected user description without user.')
|
||||||
|
|
||||||
def name(self, rest, lineno):
|
def name(self, rest, lineno):
|
||||||
self._checkId()
|
self._checkId()
|
||||||
@ -571,12 +570,12 @@ class IrcChannelCreator(Creator):
|
|||||||
|
|
||||||
def channel(self, rest, lineno):
|
def channel(self, rest, lineno):
|
||||||
if self.name is not None:
|
if self.name is not None:
|
||||||
raise ValueError, 'Unexpected channel command on line %s' % lineno
|
raise ValueError('Unexpected channel command on line %s' % lineno)
|
||||||
IrcChannelCreator.name = rest
|
IrcChannelCreator.name = rest
|
||||||
|
|
||||||
def _checkId(self):
|
def _checkId(self):
|
||||||
if self.name is None:
|
if self.name is None:
|
||||||
raise ValueError, 'Unexpected channel description without channel.'
|
raise ValueError('Unexpected channel description without channel.')
|
||||||
|
|
||||||
def lobotomized(self, rest, lineno):
|
def lobotomized(self, rest, lineno):
|
||||||
self._checkId()
|
self._checkId()
|
||||||
@ -697,14 +696,14 @@ class UsersDictionary(utils.IterableMap):
|
|||||||
self._hostmaskCache[id] = set([s])
|
self._hostmaskCache[id] = set([s])
|
||||||
return id
|
return id
|
||||||
elif len(ids) == 0:
|
elif len(ids) == 0:
|
||||||
raise KeyError, s
|
raise KeyError(s)
|
||||||
else:
|
else:
|
||||||
log.error('Multiple matches found in user database. '
|
log.error('Multiple matches found in user database. '
|
||||||
'Removing the offending hostmasks.')
|
'Removing the offending hostmasks.')
|
||||||
for (id, hostmask) in ids.iteritems():
|
for (id, hostmask) in ids.iteritems():
|
||||||
log.error('Removing %q from user %s.', hostmask, id)
|
log.error('Removing %q from user %s.', hostmask, id)
|
||||||
self.users[id].removeHostmask(hostmask)
|
self.users[id].removeHostmask(hostmask)
|
||||||
raise DuplicateHostmask, 'Ids %r matched.' % ids
|
raise DuplicateHostmask('Ids %r matched.' % ids)
|
||||||
else: # Not a hostmask, must be a name.
|
else: # Not a hostmask, must be a name.
|
||||||
s = s.lower()
|
s = s.lower()
|
||||||
try:
|
try:
|
||||||
@ -716,7 +715,7 @@ class UsersDictionary(utils.IterableMap):
|
|||||||
self._nameCache[id] = s
|
self._nameCache[id] = s
|
||||||
return id
|
return id
|
||||||
else:
|
else:
|
||||||
raise KeyError, s
|
raise KeyError(s)
|
||||||
|
|
||||||
def getUser(self, id):
|
def getUser(self, id):
|
||||||
"""Returns a user given its id, name, or hostmask."""
|
"""Returns a user given its id, name, or hostmask."""
|
||||||
@ -775,7 +774,7 @@ class UsersDictionary(utils.IterableMap):
|
|||||||
self.nextId = max(self.nextId, user.id)
|
self.nextId = max(self.nextId, user.id)
|
||||||
try:
|
try:
|
||||||
if self.getUserId(user.name) != user.id:
|
if self.getUserId(user.name) != user.id:
|
||||||
raise DuplicateHostmask, hostmask
|
raise DuplicateHostmask(hostmask)
|
||||||
except KeyError:
|
except KeyError:
|
||||||
pass
|
pass
|
||||||
for hostmask in user.hostmasks:
|
for hostmask in user.hostmasks:
|
||||||
@ -788,10 +787,10 @@ class UsersDictionary(utils.IterableMap):
|
|||||||
# raise an exception. So instead, we'll raise an
|
# raise an exception. So instead, we'll raise an
|
||||||
# exception, but be nice and give the offending hostmask
|
# exception, but be nice and give the offending hostmask
|
||||||
# back at the same time.
|
# back at the same time.
|
||||||
raise DuplicateHostmask, hostmask
|
raise DuplicateHostmask(hostmask)
|
||||||
for otherHostmask in u.hostmasks:
|
for otherHostmask in u.hostmasks:
|
||||||
if ircutils.hostmaskPatternEqual(hostmask, otherHostmask):
|
if ircutils.hostmaskPatternEqual(hostmask, otherHostmask):
|
||||||
raise DuplicateHostmask, hostmask
|
raise DuplicateHostmask(hostmask)
|
||||||
self.invalidateCache(user.id)
|
self.invalidateCache(user.id)
|
||||||
self.users[user.id] = user
|
self.users[user.id] = user
|
||||||
if flush:
|
if flush:
|
||||||
|
@ -85,7 +85,7 @@ class IrcMsg(object):
|
|||||||
def __init__(self, s='', command='', args=(), prefix='', msg=None):
|
def __init__(self, s='', command='', args=(), prefix='', msg=None):
|
||||||
assert not (msg and s), 'IrcMsg.__init__ cannot accept both s and msg'
|
assert not (msg and s), 'IrcMsg.__init__ cannot accept both s and msg'
|
||||||
if not s and not command and not msg:
|
if not s and not command and not msg:
|
||||||
raise MalformedIrcMsg, 'IRC messages require a command.'
|
raise MalformedIrcMsg('IRC messages require a command.')
|
||||||
self._str = None
|
self._str = None
|
||||||
self._repr = None
|
self._repr = None
|
||||||
self._hash = None
|
self._hash = None
|
||||||
@ -109,7 +109,7 @@ class IrcMsg(object):
|
|||||||
self.args = s.split()
|
self.args = s.split()
|
||||||
self.command = self.args.pop(0)
|
self.command = self.args.pop(0)
|
||||||
except (IndexError, ValueError):
|
except (IndexError, ValueError):
|
||||||
raise MalformedIrcMsg, repr(originalString)
|
raise MalformedIrcMsg(repr(originalString))
|
||||||
else:
|
else:
|
||||||
if msg is not None:
|
if msg is not None:
|
||||||
if prefix:
|
if prefix:
|
||||||
|
@ -48,6 +48,7 @@ import functools
|
|||||||
from cStringIO import StringIO as sio
|
from cStringIO import StringIO as sio
|
||||||
|
|
||||||
from . import utils
|
from . import utils
|
||||||
|
from . import minisix
|
||||||
from itertools import imap
|
from itertools import imap
|
||||||
|
|
||||||
def debug(s, *args):
|
def debug(s, *args):
|
||||||
@ -88,13 +89,13 @@ def splitHostmask(hostmask):
|
|||||||
assert isUserHostmask(hostmask)
|
assert isUserHostmask(hostmask)
|
||||||
nick, rest = hostmask.split('!', 1)
|
nick, rest = hostmask.split('!', 1)
|
||||||
user, host = rest.split('@', 1)
|
user, host = rest.split('@', 1)
|
||||||
return (sys.intern(nick), sys.intern(user), sys.intern(host))
|
return (minisix.intern(nick), minisix.intern(user), minisix.intern(host))
|
||||||
|
|
||||||
def joinHostmask(nick, ident, host):
|
def joinHostmask(nick, ident, host):
|
||||||
"""nick, user, host => hostmask
|
"""nick, user, host => hostmask
|
||||||
Joins the nick, ident, host into a user hostmask."""
|
Joins the nick, ident, host into a user hostmask."""
|
||||||
assert nick and ident and host
|
assert nick and ident and host
|
||||||
return sys.intern('%s!%s@%s' % (nick, ident, host))
|
return minisix.intern('%s!%s@%s' % (nick, ident, host))
|
||||||
|
|
||||||
_rfc1459trans = utils.str.MultipleReplacer(dict(zip(
|
_rfc1459trans = utils.str.MultipleReplacer(dict(zip(
|
||||||
string.ascii_uppercase + r'\[]~',
|
string.ascii_uppercase + r'\[]~',
|
||||||
@ -107,7 +108,7 @@ def toLower(s, casemapping=None):
|
|||||||
elif casemapping == 'ascii': # freenode
|
elif casemapping == 'ascii': # freenode
|
||||||
return s.lower()
|
return s.lower()
|
||||||
else:
|
else:
|
||||||
raise ValueError, 'Invalid casemapping: %r' % casemapping
|
raise ValueError('Invalid casemapping: %r' % casemapping)
|
||||||
|
|
||||||
def strEqual(nick1, nick2):
|
def strEqual(nick1, nick2):
|
||||||
"""s1, s2 => bool
|
"""s1, s2 => bool
|
||||||
|
@ -185,12 +185,11 @@ try:
|
|||||||
messagesLogFilename = os.path.join(_logDir, 'messages.log')
|
messagesLogFilename = os.path.join(_logDir, 'messages.log')
|
||||||
_handler = BetterFileHandler(messagesLogFilename)
|
_handler = BetterFileHandler(messagesLogFilename)
|
||||||
except EnvironmentError, e:
|
except EnvironmentError, e:
|
||||||
raise SystemExit, \
|
raise SystemExit('Error opening messages logfile (%s). ' \
|
||||||
'Error opening messages logfile (%s). ' \
|
|
||||||
'Generally, this is because you are running Supybot in a directory ' \
|
'Generally, this is because you are running Supybot in a directory ' \
|
||||||
'you don\'t have permissions to add files in, or you\'re running ' \
|
'you don\'t have permissions to add files in, or you\'re running ' \
|
||||||
'Supybot as a different user than you normal do. The original ' \
|
'Supybot as a different user than you normal do. The original ' \
|
||||||
'error was: %s' % (messagesLogFilename, utils.gen.exnToString(e))
|
'error was: %s' % (messagesLogFilename, utils.gen.exnToString(e)))
|
||||||
|
|
||||||
# These are public.
|
# These are public.
|
||||||
formatter = Formatter('NEVER SEEN; IF YOU SEE THIS, FILE A BUG!')
|
formatter = Formatter('NEVER SEEN; IF YOU SEE THIS, FILE A BUG!')
|
||||||
|
@ -59,7 +59,7 @@ def loadPluginModule(name, ignoreDeprecation=False):
|
|||||||
if len(matched_names) == 1:
|
if len(matched_names) == 1:
|
||||||
name = matched_names[0]
|
name = matched_names[0]
|
||||||
else:
|
else:
|
||||||
raise ImportError, name
|
raise ImportError(name)
|
||||||
moduleInfo = imp.find_module(name, pluginDirs)
|
moduleInfo = imp.find_module(name, pluginDirs)
|
||||||
try:
|
try:
|
||||||
module = imp.load_module(name, *moduleInfo)
|
module = imp.load_module(name, *moduleInfo)
|
||||||
@ -74,8 +74,8 @@ def loadPluginModule(name, ignoreDeprecation=False):
|
|||||||
if ignoreDeprecation:
|
if ignoreDeprecation:
|
||||||
log.warning('Deprecated plugin loaded: %s', name)
|
log.warning('Deprecated plugin loaded: %s', name)
|
||||||
else:
|
else:
|
||||||
raise Deprecated, format('Attempted to load deprecated plugin %s',
|
raise Deprecated(format('Attempted to load deprecated plugin %s',
|
||||||
name)
|
name))
|
||||||
if module.__name__ in sys.modules:
|
if module.__name__ in sys.modules:
|
||||||
sys.modules[module.__name__] = module
|
sys.modules[module.__name__] = module
|
||||||
linecache.checkcache()
|
linecache.checkcache()
|
||||||
@ -88,8 +88,7 @@ def loadPluginClass(irc, module, register=None):
|
|||||||
except TypeError, e:
|
except TypeError, e:
|
||||||
s = str(e)
|
s = str(e)
|
||||||
if '2 given' in s and '__init__' in s:
|
if '2 given' in s and '__init__' in s:
|
||||||
raise callbacks.Error, \
|
raise callbacks.Error('In our switch from CVS to Darcs (after 0.80.1), we ' \
|
||||||
'In our switch from CVS to Darcs (after 0.80.1), we ' \
|
|
||||||
'changed the __init__ for callbacks.Privmsg* to also ' \
|
'changed the __init__ for callbacks.Privmsg* to also ' \
|
||||||
'accept an irc argument. This plugin (%s) is overriding ' \
|
'accept an irc argument. This plugin (%s) is overriding ' \
|
||||||
'its __init__ method and needs to update its prototype ' \
|
'its __init__ method and needs to update its prototype ' \
|
||||||
@ -98,17 +97,16 @@ def loadPluginClass(irc, module, register=None):
|
|||||||
'parent\'s __init__. Another possible cause: the code in ' \
|
'parent\'s __init__. Another possible cause: the code in ' \
|
||||||
'your __init__ raised a TypeError when calling a function ' \
|
'your __init__ raised a TypeError when calling a function ' \
|
||||||
'or creating an object, which doesn\'t take 2 arguments.' %\
|
'or creating an object, which doesn\'t take 2 arguments.' %\
|
||||||
module.__name__
|
module.__name__)
|
||||||
else:
|
else:
|
||||||
raise
|
raise
|
||||||
except AttributeError, e:
|
except AttributeError, e:
|
||||||
if 'Class' in str(e):
|
if 'Class' in str(e):
|
||||||
raise callbacks.Error, \
|
raise callbacks.Error('This plugin module doesn\'t have a "Class" ' \
|
||||||
'This plugin module doesn\'t have a "Class" ' \
|
|
||||||
'attribute to specify which plugin should be ' \
|
'attribute to specify which plugin should be ' \
|
||||||
'instantiated. If you didn\'t write this ' \
|
'instantiated. If you didn\'t write this ' \
|
||||||
'plugin, but received it with Supybot, file ' \
|
'plugin, but received it with Supybot, file ' \
|
||||||
'a bug with us about this error.'
|
'a bug with us about this error.')
|
||||||
else:
|
else:
|
||||||
raise
|
raise
|
||||||
cb.classModule = module
|
cb.classModule = module
|
||||||
|
@ -103,7 +103,7 @@ def open_registry(filename, clear=False):
|
|||||||
value = decoder(value)[0]
|
value = decoder(value)[0]
|
||||||
acc = ''
|
acc = ''
|
||||||
except ValueError:
|
except ValueError:
|
||||||
raise InvalidRegistryFile, 'Error unpacking line %r' % acc
|
raise InvalidRegistryFile('Error unpacking line %r' % acc)
|
||||||
_cache[key] = value
|
_cache[key] = value
|
||||||
_lastModified = time.time()
|
_lastModified = time.time()
|
||||||
_fd.close()
|
_fd.close()
|
||||||
@ -199,11 +199,11 @@ class Group(object):
|
|||||||
self.X = X
|
self.X = X
|
||||||
|
|
||||||
def __call__(self):
|
def __call__(self):
|
||||||
raise ValueError, 'Groups have no value.'
|
raise ValueError('Groups have no value.')
|
||||||
|
|
||||||
def __nonExistentEntry(self, attr):
|
def __nonExistentEntry(self, attr):
|
||||||
s = '%r is not a valid entry in %r' % (attr, self._name)
|
s = '%r is not a valid entry in %r' % (attr, self._name)
|
||||||
raise NonExistentRegistryEntry, s
|
raise NonExistentRegistryEntry(s)
|
||||||
|
|
||||||
def __makeChild(self, attr, s):
|
def __makeChild(self, attr, s):
|
||||||
v = self.__class__(self._default, self._help)
|
v = self.__class__(self._default, self._help)
|
||||||
@ -250,7 +250,7 @@ class Group(object):
|
|||||||
|
|
||||||
def register(self, name, node=None):
|
def register(self, name, node=None):
|
||||||
if not isValidRegistryName(name):
|
if not isValidRegistryName(name):
|
||||||
raise InvalidRegistryName, name
|
raise InvalidRegistryName(name)
|
||||||
if node is None:
|
if node is None:
|
||||||
node = Group(private=self._private)
|
node = Group(private=self._private)
|
||||||
else:
|
else:
|
||||||
@ -626,9 +626,8 @@ class Regexp(Value):
|
|||||||
self.sr = sr
|
self.sr = sr
|
||||||
self.__parent.setValue(v)
|
self.__parent.setValue(v)
|
||||||
else:
|
else:
|
||||||
raise InvalidRegistryValue, \
|
raise InvalidRegistryValue('Can\'t setValue a regexp, there would be an inconsistency '\
|
||||||
'Can\'t setValue a regexp, there would be an inconsistency '\
|
'between the regexp and the recorded string value.')
|
||||||
'between the regexp and the recorded string value.'
|
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
self() # Gotta update if we've been reloaded.
|
self() # Gotta update if we've been reloaded.
|
||||||
|
@ -149,7 +149,7 @@ class shlex:
|
|||||||
if self.debug >= 2:
|
if self.debug >= 2:
|
||||||
print("shlex: I see EOF in quotes state")
|
print("shlex: I see EOF in quotes state")
|
||||||
# XXX what error should be raised here?
|
# XXX what error should be raised here?
|
||||||
raise ValueError, "No closing quotation"
|
raise ValueError("No closing quotation")
|
||||||
elif self.state == 'a':
|
elif self.state == 'a':
|
||||||
if not nextchar:
|
if not nextchar:
|
||||||
self.state = None # end of file
|
self.state = None # end of file
|
||||||
|
20
src/test.py
20
src/test.py
@ -187,7 +187,7 @@ class PluginTestCase(SupyTestCase):
|
|||||||
ircdb.ignores.reload()
|
ircdb.ignores.reload()
|
||||||
ircdb.channels.reload()
|
ircdb.channels.reload()
|
||||||
if self.plugins is None:
|
if self.plugins is None:
|
||||||
raise ValueError, 'PluginTestCase must have a "plugins" attribute.'
|
raise ValueError('PluginTestCase must have a "plugins" attribute.')
|
||||||
self.nick = nick
|
self.nick = nick
|
||||||
self.prefix = ircutils.joinHostmask(nick, 'user', 'host.domain.tld')
|
self.prefix = ircutils.joinHostmask(nick, 'user', 'host.domain.tld')
|
||||||
self.irc = getTestIrc()
|
self.irc = getTestIrc()
|
||||||
@ -276,7 +276,7 @@ class PluginTestCase(SupyTestCase):
|
|||||||
def assertError(self, query, **kwargs):
|
def assertError(self, query, **kwargs):
|
||||||
m = self._feedMsg(query, **kwargs)
|
m = self._feedMsg(query, **kwargs)
|
||||||
if m is None:
|
if m is None:
|
||||||
raise TimeoutError, query
|
raise TimeoutError(query)
|
||||||
if lastGetHelp not in m.args[1]:
|
if lastGetHelp not in m.args[1]:
|
||||||
self.failUnless(m.args[1].startswith('Error:'),
|
self.failUnless(m.args[1].startswith('Error:'),
|
||||||
'%r did not error: %s' % (query, m.args[1]))
|
'%r did not error: %s' % (query, m.args[1]))
|
||||||
@ -288,7 +288,7 @@ class PluginTestCase(SupyTestCase):
|
|||||||
def assertNotError(self, query, **kwargs):
|
def assertNotError(self, query, **kwargs):
|
||||||
m = self._feedMsg(query, **kwargs)
|
m = self._feedMsg(query, **kwargs)
|
||||||
if m is None:
|
if m is None:
|
||||||
raise TimeoutError, query
|
raise TimeoutError(query)
|
||||||
self.failIf(m.args[1].startswith('Error:'),
|
self.failIf(m.args[1].startswith('Error:'),
|
||||||
'%r errored: %s' % (query, m.args[1]))
|
'%r errored: %s' % (query, m.args[1]))
|
||||||
self.failIf(lastGetHelp in m.args[1],
|
self.failIf(lastGetHelp in m.args[1],
|
||||||
@ -301,7 +301,7 @@ class PluginTestCase(SupyTestCase):
|
|||||||
def assertHelp(self, query, **kwargs):
|
def assertHelp(self, query, **kwargs):
|
||||||
m = self._feedMsg(query, **kwargs)
|
m = self._feedMsg(query, **kwargs)
|
||||||
if m is None:
|
if m is None:
|
||||||
raise TimeoutError, query
|
raise TimeoutError(query)
|
||||||
msg = m.args[1]
|
msg = m.args[1]
|
||||||
if 'more message' in msg:
|
if 'more message' in msg:
|
||||||
msg = msg[0:-27] # Strip (XXX more messages)
|
msg = msg[0:-27] # Strip (XXX more messages)
|
||||||
@ -321,7 +321,7 @@ class PluginTestCase(SupyTestCase):
|
|||||||
def assertResponse(self, query, expectedResponse, **kwargs):
|
def assertResponse(self, query, expectedResponse, **kwargs):
|
||||||
m = self._feedMsg(query, **kwargs)
|
m = self._feedMsg(query, **kwargs)
|
||||||
if m is None:
|
if m is None:
|
||||||
raise TimeoutError, query
|
raise TimeoutError(query)
|
||||||
self.assertEqual(m.args[1], expectedResponse,
|
self.assertEqual(m.args[1], expectedResponse,
|
||||||
'%r != %r' % (expectedResponse, m.args[1]))
|
'%r != %r' % (expectedResponse, m.args[1]))
|
||||||
return m
|
return m
|
||||||
@ -333,7 +333,7 @@ class PluginTestCase(SupyTestCase):
|
|||||||
def assertRegexp(self, query, regexp, flags=re.I, **kwargs):
|
def assertRegexp(self, query, regexp, flags=re.I, **kwargs):
|
||||||
m = self._feedMsg(query, **kwargs)
|
m = self._feedMsg(query, **kwargs)
|
||||||
if m is None:
|
if m is None:
|
||||||
raise TimeoutError, query
|
raise TimeoutError(query)
|
||||||
self.failUnless(re.search(regexp, m.args[1], flags),
|
self.failUnless(re.search(regexp, m.args[1], flags),
|
||||||
'%r does not match %r' % (m.args[1], regexp))
|
'%r does not match %r' % (m.args[1], regexp))
|
||||||
return m
|
return m
|
||||||
@ -345,7 +345,7 @@ class PluginTestCase(SupyTestCase):
|
|||||||
def assertNotRegexp(self, query, regexp, flags=re.I, **kwargs):
|
def assertNotRegexp(self, query, regexp, flags=re.I, **kwargs):
|
||||||
m = self._feedMsg(query, **kwargs)
|
m = self._feedMsg(query, **kwargs)
|
||||||
if m is None:
|
if m is None:
|
||||||
raise TimeoutError, query
|
raise TimeoutError(query)
|
||||||
self.failUnless(re.search(regexp, m.args[1], flags) is None,
|
self.failUnless(re.search(regexp, m.args[1], flags) is None,
|
||||||
'%r matched %r' % (m.args[1], regexp))
|
'%r matched %r' % (m.args[1], regexp))
|
||||||
return m
|
return m
|
||||||
@ -357,7 +357,7 @@ class PluginTestCase(SupyTestCase):
|
|||||||
def assertAction(self, query, expectedResponse=None, **kwargs):
|
def assertAction(self, query, expectedResponse=None, **kwargs):
|
||||||
m = self._feedMsg(query, **kwargs)
|
m = self._feedMsg(query, **kwargs)
|
||||||
if m is None:
|
if m is None:
|
||||||
raise TimeoutError, query
|
raise TimeoutError(query)
|
||||||
self.failUnless(ircmsgs.isAction(m), '%r is not an action.' % m)
|
self.failUnless(ircmsgs.isAction(m), '%r is not an action.' % m)
|
||||||
if expectedResponse is not None:
|
if expectedResponse is not None:
|
||||||
s = ircmsgs.unAction(m)
|
s = ircmsgs.unAction(m)
|
||||||
@ -372,7 +372,7 @@ class PluginTestCase(SupyTestCase):
|
|||||||
def assertActionRegexp(self, query, regexp, flags=re.I, **kwargs):
|
def assertActionRegexp(self, query, regexp, flags=re.I, **kwargs):
|
||||||
m = self._feedMsg(query, **kwargs)
|
m = self._feedMsg(query, **kwargs)
|
||||||
if m is None:
|
if m is None:
|
||||||
raise TimeoutError, query
|
raise TimeoutError(query)
|
||||||
self.failUnless(ircmsgs.isAction(m))
|
self.failUnless(ircmsgs.isAction(m))
|
||||||
s = ircmsgs.unAction(m)
|
s = ircmsgs.unAction(m)
|
||||||
self.failUnless(re.search(regexp, s, flags),
|
self.failUnless(re.search(regexp, s, flags),
|
||||||
@ -537,7 +537,7 @@ def open_http(url, data=None):
|
|||||||
host = realhost
|
host = realhost
|
||||||
|
|
||||||
#print "proxy via http:", host, selector
|
#print "proxy via http:", host, selector
|
||||||
if not host: raise IOError, ('http error', 'no host given')
|
if not host: raise IOError('http error', 'no host given')
|
||||||
|
|
||||||
if proxy_passwd:
|
if proxy_passwd:
|
||||||
import base64
|
import base64
|
||||||
|
@ -50,7 +50,7 @@ def open_mkdir(filename, mode='wb', *args, **kwargs):
|
|||||||
baz in it.
|
baz in it.
|
||||||
"""
|
"""
|
||||||
if mode not in ('w', 'wb'):
|
if mode not in ('w', 'wb'):
|
||||||
raise ValueError, 'utils.file.open expects to write.'
|
raise ValueError('utils.file.open expects to write.')
|
||||||
(dirname, basename) = os.path.split(filename)
|
(dirname, basename) = os.path.split(filename)
|
||||||
os.makedirs(dirname)
|
os.makedirs(dirname)
|
||||||
return open(filename, mode, *args, **kwargs)
|
return open(filename, mode, *args, **kwargs)
|
||||||
@ -137,7 +137,7 @@ class AtomicFile(object):
|
|||||||
if allowEmptyOverwrite is None:
|
if allowEmptyOverwrite is None:
|
||||||
allowEmptyOverwrite = force(self.default.allowEmptyOverwrite)
|
allowEmptyOverwrite = force(self.default.allowEmptyOverwrite)
|
||||||
if mode not in ('w', 'wb'):
|
if mode not in ('w', 'wb'):
|
||||||
raise ValueError, format('Invalid mode: %q', mode)
|
raise ValueError(format('Invalid mode: %q', mode))
|
||||||
self.rolledback = False
|
self.rolledback = False
|
||||||
self.allowEmptyOverwrite = allowEmptyOverwrite
|
self.allowEmptyOverwrite = allowEmptyOverwrite
|
||||||
self.makeBackupIfSmaller = makeBackupIfSmaller
|
self.makeBackupIfSmaller = makeBackupIfSmaller
|
||||||
@ -219,7 +219,7 @@ class AtomicFile(object):
|
|||||||
shutil.move(self.tempFilename, self.filename)
|
shutil.move(self.tempFilename, self.filename)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
raise ValueError, 'AtomicFile.close called after rollback.'
|
raise ValueError('AtomicFile.close called after rollback.')
|
||||||
|
|
||||||
def __del__(self):
|
def __del__(self):
|
||||||
# We rollback because if we're deleted without being explicitly closed,
|
# We rollback because if we're deleted without being explicitly closed,
|
||||||
|
@ -117,7 +117,7 @@ def timeElapsed(elapsed, short=False, leadingZeroes=False, years=True,
|
|||||||
leadingZeroes = True
|
leadingZeroes = True
|
||||||
Format(_('second'), secs)
|
Format(_('second'), secs)
|
||||||
if not ret:
|
if not ret:
|
||||||
raise ValueError, 'Time difference not great enough to be noted.'
|
raise ValueError('Time difference not great enough to be noted.')
|
||||||
result = ''
|
result = ''
|
||||||
if short:
|
if short:
|
||||||
result = ' '.join(ret)
|
result = ' '.join(ret)
|
||||||
@ -161,13 +161,13 @@ def safeEval(s, namespace={'True': True, 'False': False, 'None': None}):
|
|||||||
try:
|
try:
|
||||||
node = ast.parse(s)
|
node = ast.parse(s)
|
||||||
except SyntaxError, e:
|
except SyntaxError, e:
|
||||||
raise ValueError, 'Invalid string: %s.' % e
|
raise ValueError('Invalid string: %s.' % e)
|
||||||
nodes = ast.parse(s).body
|
nodes = ast.parse(s).body
|
||||||
if not nodes:
|
if not nodes:
|
||||||
if node.__class__ is ast.Module:
|
if node.__class__ is ast.Module:
|
||||||
return node.doc
|
return node.doc
|
||||||
else:
|
else:
|
||||||
raise ValueError, format('Unsafe string: %q', s)
|
raise ValueError(format('Unsafe string: %q', s))
|
||||||
node = nodes[0]
|
node = nodes[0]
|
||||||
def checkNode(node):
|
def checkNode(node):
|
||||||
if node.__class__ is ast.Expr:
|
if node.__class__ is ast.Expr:
|
||||||
@ -192,7 +192,7 @@ def safeEval(s, namespace={'True': True, 'False': False, 'None': None}):
|
|||||||
if checkNode(node):
|
if checkNode(node):
|
||||||
return eval(s, namespace, namespace)
|
return eval(s, namespace, namespace)
|
||||||
else:
|
else:
|
||||||
raise ValueError, format('Unsafe string: %q', s)
|
raise ValueError(format('Unsafe string: %q', s))
|
||||||
|
|
||||||
def exnToString(e):
|
def exnToString(e):
|
||||||
"""Turns a simple exception instance into a string (better than str(e))"""
|
"""Turns a simple exception instance into a string (better than str(e))"""
|
||||||
|
@ -154,7 +154,7 @@ def limited(iterable, limit):
|
|||||||
yield next(iterable)
|
yield next(iterable)
|
||||||
i -= 1
|
i -= 1
|
||||||
except StopIteration:
|
except StopIteration:
|
||||||
raise ValueError, 'Expected %s elements in iterable (%r), got %s.' % \
|
raise ValueError('Expected %s elements in iterable (%r), got %s.' % \
|
||||||
(limit, iterable, limit-i)
|
(limit, iterable, limit-i))
|
||||||
|
|
||||||
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
|
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
|
||||||
|
@ -67,7 +67,7 @@ def getSocket(host, socks_proxy=None):
|
|||||||
elif isIPV6(host):
|
elif isIPV6(host):
|
||||||
return socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
|
return socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
|
||||||
else:
|
else:
|
||||||
raise socket.error, 'Something wonky happened.'
|
raise socket.error('Something wonky happened.')
|
||||||
|
|
||||||
def isIP(s):
|
def isIP(s):
|
||||||
"""Returns whether or not a given string is an IP address.
|
"""Returns whether or not a given string is an IP address.
|
||||||
|
@ -53,7 +53,7 @@ def universalImport(*names):
|
|||||||
ret = getattr(ret, parts[0])
|
ret = getattr(ret, parts[0])
|
||||||
del parts[0]
|
del parts[0]
|
||||||
return ret
|
return ret
|
||||||
raise ImportError, ','.join(names)
|
raise ImportError(','.join(names))
|
||||||
|
|
||||||
def changeFunctionName(f, name, doc=None):
|
def changeFunctionName(f, name, doc=None):
|
||||||
if doc is None:
|
if doc is None:
|
||||||
|
@ -33,7 +33,7 @@ def window(L, size):
|
|||||||
Returns a sliding 'window' through the list L of size size."""
|
Returns a sliding 'window' through the list L of size size."""
|
||||||
assert not isinstance(L, int), 'Argument order swapped: window(L, size)'
|
assert not isinstance(L, int), 'Argument order swapped: window(L, size)'
|
||||||
if size < 1:
|
if size < 1:
|
||||||
raise ValueError, 'size <= 0 disallowed.'
|
raise ValueError('size <= 0 disallowed.')
|
||||||
for i in xrange(len(L) - (size-1)):
|
for i in xrange(len(L) - (size-1)):
|
||||||
yield L[i:i+size]
|
yield L[i:i+size]
|
||||||
|
|
||||||
|
@ -124,7 +124,7 @@ def soundex(s, length=4):
|
|||||||
s = s.upper() # Make everything uppercase.
|
s = s.upper() # Make everything uppercase.
|
||||||
s = ''.join([x for x in s if x in string.ascii_uppercase])
|
s = ''.join([x for x in s if x in string.ascii_uppercase])
|
||||||
if not s:
|
if not s:
|
||||||
raise ValueError, 'Invalid string for soundex: %s'
|
raise ValueError('Invalid string for soundex: %s')
|
||||||
firstChar = s[0] # Save the first character.
|
firstChar = s[0] # Save the first character.
|
||||||
s = _soundextrans(s) # Convert to soundex numbers.
|
s = _soundextrans(s) # Convert to soundex numbers.
|
||||||
s = s.lstrip(s[0]) # Remove all repeated first characters.
|
s = s.lstrip(s[0]) # Remove all repeated first characters.
|
||||||
@ -155,7 +155,7 @@ _openers = '{[(<'
|
|||||||
_closers = '}])>'
|
_closers = '}])>'
|
||||||
def _getSep(s, allowBraces=False):
|
def _getSep(s, allowBraces=False):
|
||||||
if len(s) < 2:
|
if len(s) < 2:
|
||||||
raise ValueError, 'string given to _getSep is too short: %r' % s
|
raise ValueError('string given to _getSep is too short: %r' % s)
|
||||||
if allowBraces:
|
if allowBraces:
|
||||||
braces = _closers
|
braces = _closers
|
||||||
else:
|
else:
|
||||||
@ -165,9 +165,8 @@ def _getSep(s, allowBraces=False):
|
|||||||
else:
|
else:
|
||||||
separator = s[0]
|
separator = s[0]
|
||||||
if separator.isalnum() or separator in braces:
|
if separator.isalnum() or separator in braces:
|
||||||
raise ValueError, \
|
raise ValueError('Invalid separator: separator must not be alphanumeric or in ' \
|
||||||
'Invalid separator: separator must not be alphanumeric or in ' \
|
'"%s"' % braces)
|
||||||
'"%s"' % braces
|
|
||||||
return separator
|
return separator
|
||||||
|
|
||||||
def perlReToPythonRe(s):
|
def perlReToPythonRe(s):
|
||||||
@ -183,7 +182,7 @@ def perlReToPythonRe(s):
|
|||||||
try:
|
try:
|
||||||
(regexp, flags) = matcher.match(s).groups()
|
(regexp, flags) = matcher.match(s).groups()
|
||||||
except AttributeError: # Unpack list of wrong size.
|
except AttributeError: # Unpack list of wrong size.
|
||||||
raise ValueError, 'Must be of the form m/.../ or /.../'
|
raise ValueError('Must be of the form m/.../ or /.../')
|
||||||
regexp = regexp.replace('\\'+opener, opener)
|
regexp = regexp.replace('\\'+opener, opener)
|
||||||
if opener != closer:
|
if opener != closer:
|
||||||
regexp = regexp.replace('\\'+closer, closer)
|
regexp = regexp.replace('\\'+closer, closer)
|
||||||
@ -192,11 +191,11 @@ def perlReToPythonRe(s):
|
|||||||
for c in flags.upper():
|
for c in flags.upper():
|
||||||
flag |= getattr(re, c)
|
flag |= getattr(re, c)
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
raise ValueError, 'Invalid flag: %s' % c
|
raise ValueError('Invalid flag: %s' % c)
|
||||||
try:
|
try:
|
||||||
return re.compile(regexp, flag)
|
return re.compile(regexp, flag)
|
||||||
except re.error, e:
|
except re.error, e:
|
||||||
raise ValueError, str(e)
|
raise ValueError(str(e))
|
||||||
|
|
||||||
def perlReToReplacer(s):
|
def perlReToReplacer(s):
|
||||||
"""Converts a string representation of a Perl regular expression (i.e.,
|
"""Converts a string representation of a Perl regular expression (i.e.,
|
||||||
@ -210,7 +209,7 @@ def perlReToReplacer(s):
|
|||||||
try:
|
try:
|
||||||
(regexp, replace, flags) = matcher.match(s).groups()
|
(regexp, replace, flags) = matcher.match(s).groups()
|
||||||
except AttributeError: # Unpack list of wrong size.
|
except AttributeError: # Unpack list of wrong size.
|
||||||
raise ValueError, 'Must be of the form s/.../.../'
|
raise ValueError('Must be of the form s/.../.../')
|
||||||
regexp = regexp.replace('\x08', r'\b')
|
regexp = regexp.replace('\x08', r'\b')
|
||||||
replace = replace.replace('\\'+sep, sep)
|
replace = replace.replace('\\'+sep, sep)
|
||||||
for i in xrange(10):
|
for i in xrange(10):
|
||||||
@ -414,7 +413,7 @@ def toBool(s):
|
|||||||
elif s in ('false', 'off', 'disable', 'disabled', '0'):
|
elif s in ('false', 'off', 'disable', 'disabled', '0'):
|
||||||
return False
|
return False
|
||||||
else:
|
else:
|
||||||
raise ValueError, 'Invalid string for toBool: %s' % quoted(s)
|
raise ValueError('Invalid string for toBool: %s' % quoted(s))
|
||||||
|
|
||||||
# When used with Supybot, this is overriden when supybot.conf is loaded
|
# When used with Supybot, this is overriden when supybot.conf is loaded
|
||||||
def timestamp(t):
|
def timestamp(t):
|
||||||
@ -476,14 +475,12 @@ def format(s, *args, **kwargs):
|
|||||||
return commaAndify(t)
|
return commaAndify(t)
|
||||||
elif isinstance(t, tuple) and len(t) == 2:
|
elif isinstance(t, tuple) and len(t) == 2:
|
||||||
if not isinstance(t[0], list):
|
if not isinstance(t[0], list):
|
||||||
raise ValueError, \
|
raise ValueError('Invalid list for %%L in format: %s' % t)
|
||||||
'Invalid list for %%L in format: %s' % t
|
|
||||||
if not isinstance(t[1], basestring):
|
if not isinstance(t[1], basestring):
|
||||||
raise ValueError, \
|
raise ValueError('Invalid string for %%L in format: %s' % t)
|
||||||
'Invalid string for %%L in format: %s' % t
|
|
||||||
return commaAndify(t[0], And=t[1])
|
return commaAndify(t[0], And=t[1])
|
||||||
else:
|
else:
|
||||||
raise ValueError, 'Invalid value for %%L in format: %s' % t
|
raise ValueError('Invalid value for %%L in format: %s' % t)
|
||||||
elif char == 'p':
|
elif char == 'p':
|
||||||
return pluralize(args.pop())
|
return pluralize(args.pop())
|
||||||
elif char == 'q':
|
elif char == 'q':
|
||||||
@ -493,17 +490,17 @@ def format(s, *args, **kwargs):
|
|||||||
elif char == 'n':
|
elif char == 'n':
|
||||||
t = args.pop()
|
t = args.pop()
|
||||||
if not isinstance(t, (tuple, list)):
|
if not isinstance(t, (tuple, list)):
|
||||||
raise ValueError, 'Invalid value for %%n in format: %s' % t
|
raise ValueError('Invalid value for %%n in format: %s' % t)
|
||||||
if len(t) == 2:
|
if len(t) == 2:
|
||||||
return nItems(*t)
|
return nItems(*t)
|
||||||
elif len(t) == 3:
|
elif len(t) == 3:
|
||||||
return nItems(t[0], t[2], between=t[1])
|
return nItems(t[0], t[2], between=t[1])
|
||||||
else:
|
else:
|
||||||
raise ValueError, 'Invalid value for %%n in format: %s' % t
|
raise ValueError('Invalid value for %%n in format: %s' % t)
|
||||||
elif char == 'S':
|
elif char == 'S':
|
||||||
t = args.pop()
|
t = args.pop()
|
||||||
if not isinstance(t, (int, long)):
|
if not isinstance(t, (int, long)):
|
||||||
raise ValueError, 'Invalid value for %%S in format: %s' % t
|
raise ValueError('Invalid value for %%S in format: %s' % t)
|
||||||
for suffix in ['B','KB','MB','GB','TB']:
|
for suffix in ['B','KB','MB','GB','TB']:
|
||||||
if t < 1024:
|
if t < 1024:
|
||||||
return "%i%s" % (t, suffix)
|
return "%i%s" % (t, suffix)
|
||||||
@ -527,10 +524,10 @@ def format(s, *args, **kwargs):
|
|||||||
elif char == '%':
|
elif char == '%':
|
||||||
return '%'
|
return '%'
|
||||||
else:
|
else:
|
||||||
raise ValueError, 'Invalid char in sub (in format).'
|
raise ValueError('Invalid char in sub (in format).')
|
||||||
try:
|
try:
|
||||||
return _formatRe.sub(sub, s)
|
return _formatRe.sub(sub, s)
|
||||||
except IndexError:
|
except IndexError:
|
||||||
raise ValueError, 'Extra format chars in format spec: %r' % s
|
raise ValueError('Extra format chars in format spec: %r' % s)
|
||||||
|
|
||||||
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
|
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
|
||||||
|
@ -41,7 +41,7 @@ class RingBuffer(object):
|
|||||||
__slots__ = ('L', 'i', 'full', 'maxSize')
|
__slots__ = ('L', 'i', 'full', 'maxSize')
|
||||||
def __init__(self, maxSize, seq=()):
|
def __init__(self, maxSize, seq=()):
|
||||||
if maxSize <= 0:
|
if maxSize <= 0:
|
||||||
raise ValueError, 'maxSize must be > 0.'
|
raise ValueError('maxSize must be > 0.')
|
||||||
self.maxSize = maxSize
|
self.maxSize = maxSize
|
||||||
self.reset()
|
self.reset()
|
||||||
for elt in seq:
|
for elt in seq:
|
||||||
@ -109,7 +109,7 @@ class RingBuffer(object):
|
|||||||
else:
|
else:
|
||||||
(m, idx) = divmod(oidx, len(self.L))
|
(m, idx) = divmod(oidx, len(self.L))
|
||||||
if m and m != -1:
|
if m and m != -1:
|
||||||
raise IndexError, oidx
|
raise IndexError(oidx)
|
||||||
idx = (idx + self.i) % len(self.L)
|
idx = (idx + self.i) % len(self.L)
|
||||||
return self.L[idx]
|
return self.L[idx]
|
||||||
else:
|
else:
|
||||||
@ -127,21 +127,21 @@ class RingBuffer(object):
|
|||||||
if isinstance(oidx, types.SliceType):
|
if isinstance(oidx, types.SliceType):
|
||||||
range_ = xrange(*slice.indices(oidx, len(self)))
|
range_ = xrange(*slice.indices(oidx, len(self)))
|
||||||
if len(range_) != len(elt):
|
if len(range_) != len(elt):
|
||||||
raise ValueError, 'seq must be the same length as slice.'
|
raise ValueError('seq must be the same length as slice.')
|
||||||
else:
|
else:
|
||||||
for (i, x) in zip(range_, elt):
|
for (i, x) in zip(range_, elt):
|
||||||
self[i] = x
|
self[i] = x
|
||||||
else:
|
else:
|
||||||
(m, idx) = divmod(oidx, len(self.L))
|
(m, idx) = divmod(oidx, len(self.L))
|
||||||
if m and m != -1:
|
if m and m != -1:
|
||||||
raise IndexError, oidx
|
raise IndexError(oidx)
|
||||||
idx = (idx + self.i) % len(self.L)
|
idx = (idx + self.i) % len(self.L)
|
||||||
self.L[idx] = elt
|
self.L[idx] = elt
|
||||||
else:
|
else:
|
||||||
if isinstance(idx, types.SliceType):
|
if isinstance(idx, types.SliceType):
|
||||||
range_ = xrange(*slice.indices(idx, len(self)))
|
range_ = xrange(*slice.indices(idx, len(self)))
|
||||||
if len(range_) != len(elt):
|
if len(range_) != len(elt):
|
||||||
raise ValueError, 'seq must be the same length as slice.'
|
raise ValueError('seq must be the same length as slice.')
|
||||||
else:
|
else:
|
||||||
for (i, x) in zip(range_, elt):
|
for (i, x) in zip(range_, elt):
|
||||||
self[i] = x
|
self[i] = x
|
||||||
@ -226,7 +226,7 @@ class queue(object):
|
|||||||
|
|
||||||
def __getitem__(self, oidx):
|
def __getitem__(self, oidx):
|
||||||
if len(self) == 0:
|
if len(self) == 0:
|
||||||
raise IndexError, 'queue index out of range'
|
raise IndexError('queue index out of range')
|
||||||
if isinstance(oidx, types.SliceType):
|
if isinstance(oidx, types.SliceType):
|
||||||
L = []
|
L = []
|
||||||
for i in xrange(*slice.indices(oidx, len(self))):
|
for i in xrange(*slice.indices(oidx, len(self))):
|
||||||
@ -235,7 +235,7 @@ class queue(object):
|
|||||||
else:
|
else:
|
||||||
(m, idx) = divmod(oidx, len(self))
|
(m, idx) = divmod(oidx, len(self))
|
||||||
if m and m != -1:
|
if m and m != -1:
|
||||||
raise IndexError, oidx
|
raise IndexError(oidx)
|
||||||
if len(self.front) > idx:
|
if len(self.front) > idx:
|
||||||
return self.front[-(idx+1)]
|
return self.front[-(idx+1)]
|
||||||
else:
|
else:
|
||||||
@ -243,22 +243,22 @@ class queue(object):
|
|||||||
|
|
||||||
def __setitem__(self, oidx, value):
|
def __setitem__(self, oidx, value):
|
||||||
if len(self) == 0:
|
if len(self) == 0:
|
||||||
raise IndexError, 'queue index out of range'
|
raise IndexError('queue index out of range')
|
||||||
if isinstance(oidx, types.SliceType):
|
if isinstance(oidx, types.SliceType):
|
||||||
range_ = xrange(*slice.indices(oidx, len(self)))
|
range_ = xrange(*slice.indices(oidx, len(self)))
|
||||||
if len(range_) != len(value):
|
if len(range_) != len(value):
|
||||||
raise ValueError, 'seq must be the same length as slice.'
|
raise ValueError('seq must be the same length as slice.')
|
||||||
else:
|
else:
|
||||||
for i in range_:
|
for i in range_:
|
||||||
(m, idx) = divmod(oidx, len(self))
|
(m, idx) = divmod(oidx, len(self))
|
||||||
if m and m != -1:
|
if m and m != -1:
|
||||||
raise IndexError, oidx
|
raise IndexError(oidx)
|
||||||
for (i, x) in zip(range_, value):
|
for (i, x) in zip(range_, value):
|
||||||
self[i] = x
|
self[i] = x
|
||||||
else:
|
else:
|
||||||
(m, idx) = divmod(oidx, len(self))
|
(m, idx) = divmod(oidx, len(self))
|
||||||
if m and m != -1:
|
if m and m != -1:
|
||||||
raise IndexError, oidx
|
raise IndexError(oidx)
|
||||||
if len(self.front) > idx:
|
if len(self.front) > idx:
|
||||||
self.front[-(idx+1)] = value
|
self.front[-(idx+1)] = value
|
||||||
else:
|
else:
|
||||||
@ -272,7 +272,7 @@ class queue(object):
|
|||||||
else:
|
else:
|
||||||
(m, idx) = divmod(oidx, len(self))
|
(m, idx) = divmod(oidx, len(self))
|
||||||
if m and m != -1:
|
if m and m != -1:
|
||||||
raise IndexError, oidx
|
raise IndexError(oidx)
|
||||||
if len(self.front) > idx:
|
if len(self.front) > idx:
|
||||||
del self.front[-(idx+1)]
|
del self.front[-(idx+1)]
|
||||||
else:
|
else:
|
||||||
|
@ -126,18 +126,18 @@ def getUrlFd(url, headers=None, data=None, timeout=None):
|
|||||||
fd = urllib2.urlopen(request, timeout=timeout)
|
fd = urllib2.urlopen(request, timeout=timeout)
|
||||||
return fd
|
return fd
|
||||||
except socket.timeout, e:
|
except socket.timeout, e:
|
||||||
raise Error, TIMED_OUT
|
raise Error(TIMED_OUT)
|
||||||
except sockerrors, e:
|
except sockerrors, e:
|
||||||
raise Error, strError(e)
|
raise Error(strError(e))
|
||||||
except httplib.InvalidURL, e:
|
except httplib.InvalidURL, e:
|
||||||
raise Error, 'Invalid URL: %s' % e
|
raise Error('Invalid URL: %s' % e)
|
||||||
except urllib2.HTTPError, e:
|
except urllib2.HTTPError, e:
|
||||||
raise Error, strError(e)
|
raise Error(strError(e))
|
||||||
except urllib2.URLError, e:
|
except urllib2.URLError, e:
|
||||||
raise Error, strError(e.reason)
|
raise Error(strError(e.reason))
|
||||||
# Raised when urllib doesn't recognize the url type
|
# Raised when urllib doesn't recognize the url type
|
||||||
except ValueError, e:
|
except ValueError, e:
|
||||||
raise Error, strError(e)
|
raise Error(strError(e))
|
||||||
|
|
||||||
def getUrl(url, size=None, headers=None, data=None):
|
def getUrl(url, size=None, headers=None, data=None):
|
||||||
"""getUrl(url, size=None, headers=None, data=None)
|
"""getUrl(url, size=None, headers=None, data=None)
|
||||||
@ -152,7 +152,7 @@ def getUrl(url, size=None, headers=None, data=None):
|
|||||||
else:
|
else:
|
||||||
text = fd.read(size)
|
text = fd.read(size)
|
||||||
except socket.timeout, e:
|
except socket.timeout, e:
|
||||||
raise Error, TIMED_OUT
|
raise Error(TIMED_OUT)
|
||||||
fd.close()
|
fd.close()
|
||||||
return text
|
return text
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user