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