Replace sys.version_info[0] usages with minisix.PY{2,3}.

This commit is contained in:
Valentin Lorentz 2015-08-09 00:23:03 +02:00
parent 078eb9bad8
commit 216c5d213f
40 changed files with 144 additions and 116 deletions

View File

@ -38,6 +38,7 @@ import supybot.utils as utils
import supybot.ircdb as ircdb import supybot.ircdb as ircdb
from supybot.commands import * from supybot.commands import *
import supybot.plugins as plugins import supybot.plugins as plugins
import supybot.minisix as minisix
import supybot.ircutils as ircutils import supybot.ircutils as ircutils
import supybot.callbacks as callbacks import supybot.callbacks as callbacks
from supybot.i18n import PluginInternationalization from supybot.i18n import PluginInternationalization
@ -106,7 +107,7 @@ if sqlite3:
def has_aka(self, channel, name): def has_aka(self, channel, name):
name = callbacks.canonicalName(name, preserve_spaces=True) name = callbacks.canonicalName(name, preserve_spaces=True)
if sys.version_info[0] < 3 and isinstance(name, str): if minisix.PY2 and isinstance(name, str):
name = name.decode('utf8') name = name.decode('utf8')
db = self.get_db(channel) db = self.get_db(channel)
return self.get_db(channel).cursor() \ return self.get_db(channel).cursor() \
@ -122,7 +123,7 @@ if sqlite3:
def get_alias(self, channel, name): def get_alias(self, channel, name):
name = callbacks.canonicalName(name, preserve_spaces=True) name = callbacks.canonicalName(name, preserve_spaces=True)
if sys.version_info[0] < 3 and isinstance(name, str): if minisix.PY2 and isinstance(name, str):
name = name.decode('utf8') name = name.decode('utf8')
cursor = self.get_db(channel).cursor() cursor = self.get_db(channel).cursor()
cursor.execute("""SELECT alias FROM aliases cursor.execute("""SELECT alias FROM aliases
@ -137,7 +138,7 @@ if sqlite3:
name = callbacks.canonicalName(name, preserve_spaces=True) name = callbacks.canonicalName(name, preserve_spaces=True)
if self.has_aka(channel, name): if self.has_aka(channel, name):
raise AkaError(_('This Aka already exists.')) raise AkaError(_('This Aka already exists.'))
if sys.version_info[0] < 3: if minisix.PY2:
if isinstance(name, str): if isinstance(name, str):
name = name.decode('utf8') name = name.decode('utf8')
if isinstance(alias, str): if isinstance(alias, str):
@ -150,7 +151,7 @@ if sqlite3:
def remove_aka(self, channel, name): def remove_aka(self, channel, name):
name = callbacks.canonicalName(name, preserve_spaces=True) name = callbacks.canonicalName(name, preserve_spaces=True)
if sys.version_info[0] < 3 and isinstance(name, str): if minisix.PY2 and isinstance(name, str):
name = name.decode('utf8') name = name.decode('utf8')
db = self.get_db(channel) db = self.get_db(channel)
db.cursor().execute('DELETE FROM aliases WHERE name = ?', (name,)) db.cursor().execute('DELETE FROM aliases WHERE name = ?', (name,))
@ -158,7 +159,7 @@ if sqlite3:
def lock_aka(self, channel, name, by): def lock_aka(self, channel, name, by):
name = callbacks.canonicalName(name, preserve_spaces=True) name = callbacks.canonicalName(name, preserve_spaces=True)
if sys.version_info[0] < 3 and isinstance(name, str): if minisix.PY2 and isinstance(name, str):
name = name.decode('utf8') name = name.decode('utf8')
db = self.get_db(channel) db = self.get_db(channel)
cursor = db.cursor().execute("""UPDATE aliases cursor = db.cursor().execute("""UPDATE aliases
@ -170,7 +171,7 @@ if sqlite3:
def unlock_aka(self, channel, name, by): def unlock_aka(self, channel, name, by):
name = callbacks.canonicalName(name, preserve_spaces=True) name = callbacks.canonicalName(name, preserve_spaces=True)
if sys.version_info[0] < 3 and isinstance(name, str): if minisix.PY2 and isinstance(name, str):
name = name.decode('utf8') name = name.decode('utf8')
db = self.get_db(channel) db = self.get_db(channel)
cursor = db.cursor() cursor = db.cursor()
@ -182,7 +183,7 @@ if sqlite3:
def get_aka_lock(self, channel, name): def get_aka_lock(self, channel, name):
name = callbacks.canonicalName(name, preserve_spaces=True) name = callbacks.canonicalName(name, preserve_spaces=True)
if sys.version_info[0] < 3 and isinstance(name, str): if minisix.PY2 and isinstance(name, str):
name = name.decode('utf8') name = name.decode('utf8')
cursor = self.get_db(channel).cursor() cursor = self.get_db(channel).cursor()
cursor.execute("""SELECT locked, locked_by, locked_at cursor.execute("""SELECT locked, locked_by, locked_at
@ -237,7 +238,7 @@ elif sqlalchemy:
def has_aka(self, channel, name): def has_aka(self, channel, name):
name = callbacks.canonicalName(name, preserve_spaces=True) name = callbacks.canonicalName(name, preserve_spaces=True)
if sys.version_info[0] < 3 and isinstance(name, str): if minisix.PY2 and isinstance(name, str):
name = name.decode('utf8') name = name.decode('utf8')
count = self.get_db(channel).query(SQLAlchemyAlias) \ count = self.get_db(channel).query(SQLAlchemyAlias) \
.filter(SQLAlchemyAlias.name == name) \ .filter(SQLAlchemyAlias.name == name) \
@ -249,7 +250,7 @@ elif sqlalchemy:
def get_alias(self, channel, name): def get_alias(self, channel, name):
name = callbacks.canonicalName(name, preserve_spaces=True) name = callbacks.canonicalName(name, preserve_spaces=True)
if sys.version_info[0] < 3 and isinstance(name, str): if minisix.PY2 and isinstance(name, str):
name = name.decode('utf8') name = name.decode('utf8')
try: try:
return self.get_db(channel).query(SQLAlchemyAlias.alias) \ return self.get_db(channel).query(SQLAlchemyAlias.alias) \
@ -261,7 +262,7 @@ elif sqlalchemy:
name = callbacks.canonicalName(name, preserve_spaces=True) name = callbacks.canonicalName(name, preserve_spaces=True)
if self.has_aka(channel, name): if self.has_aka(channel, name):
raise AkaError(_('This Aka already exists.')) raise AkaError(_('This Aka already exists.'))
if sys.version_info[0] < 3: if minisix.PY2:
if isinstance(name, str): if isinstance(name, str):
name = name.decode('utf8') name = name.decode('utf8')
if isinstance(alias, str): if isinstance(alias, str):
@ -272,7 +273,7 @@ elif sqlalchemy:
def remove_aka(self, channel, name): def remove_aka(self, channel, name):
name = callbacks.canonicalName(name, preserve_spaces=True) name = callbacks.canonicalName(name, preserve_spaces=True)
if sys.version_info[0] < 3 and isinstance(name, str): if minisix.PY2 and isinstance(name, str):
name = name.decode('utf8') name = name.decode('utf8')
db = self.get_db(channel) db = self.get_db(channel)
db.query(SQLAlchemyAlias).filter(SQLAlchemyAlias.name == name).delete() db.query(SQLAlchemyAlias).filter(SQLAlchemyAlias.name == name).delete()
@ -280,7 +281,7 @@ elif sqlalchemy:
def lock_aka(self, channel, name, by): def lock_aka(self, channel, name, by):
name = callbacks.canonicalName(name, preserve_spaces=True) name = callbacks.canonicalName(name, preserve_spaces=True)
if sys.version_info[0] < 3 and isinstance(name, str): if minisix.PY2 and isinstance(name, str):
name = name.decode('utf8') name = name.decode('utf8')
db = self.get_db(channel) db = self.get_db(channel)
try: try:
@ -297,7 +298,7 @@ elif sqlalchemy:
def unlock_aka(self, channel, name, by): def unlock_aka(self, channel, name, by):
name = callbacks.canonicalName(name, preserve_spaces=True) name = callbacks.canonicalName(name, preserve_spaces=True)
if sys.version_info[0] < 3 and isinstance(name, str): if minisix.PY2 and isinstance(name, str):
name = name.decode('utf8') name = name.decode('utf8')
db = self.get_db(channel) db = self.get_db(channel)
try: try:
@ -314,7 +315,7 @@ elif sqlalchemy:
def get_aka_lock(self, channel, name): def get_aka_lock(self, channel, name):
name = callbacks.canonicalName(name, preserve_spaces=True) name = callbacks.canonicalName(name, preserve_spaces=True)
if sys.version_info[0] < 3 and isinstance(name, str): if minisix.PY2 and isinstance(name, str):
name = name.decode('utf8') name = name.decode('utf8')
try: try:
return self.get_db(channel) \ return self.get_db(channel) \
@ -387,7 +388,7 @@ class Aka(callbacks.Plugin):
for cb in dynamic.irc.callbacks: # including this plugin for cb in dynamic.irc.callbacks: # including this plugin
if cb.isCommandMethod(' '.join(args[0:-1])): if cb.isCommandMethod(' '.join(args[0:-1])):
return False return False
if sys.version_info[0] < 3 and isinstance(name, str): if minisix.PY2 and isinstance(name, str):
name = name.decode('utf8') name = name.decode('utf8')
channel = dynamic.channel or 'global' channel = dynamic.channel or 'global'
return self._db.has_aka(channel, name) or \ return self._db.has_aka(channel, name) or \

View File

@ -35,6 +35,7 @@ import types
import supybot.conf as conf import supybot.conf as conf
import supybot.utils as utils import supybot.utils as utils
from supybot.commands import * from supybot.commands import *
import supybot.minisix as minisix
import supybot.ircutils as ircutils import supybot.ircutils as ircutils
import supybot.registry as registry import supybot.registry as registry
import supybot.callbacks as callbacks import supybot.callbacks as callbacks
@ -223,7 +224,7 @@ def makeNewAlias(name, alias):
doc = format(_('<an alias,%s %n>\n\nAlias for %q.'), doc = format(_('<an alias,%s %n>\n\nAlias for %q.'),
flexargs, (biggestDollar, _('argument')), alias) flexargs, (biggestDollar, _('argument')), alias)
except UnicodeDecodeError: except UnicodeDecodeError:
if sys.version_info[0] == 2: if minisix.PY2:
alias = alias.decode('utf8') alias = alias.decode('utf8')
doc = format(_('<an alias,%s %n>\n\nAlias for %q.'), doc = format(_('<an alias,%s %n>\n\nAlias for %q.'),
flexargs, (biggestDollar, _('argument')), alias) flexargs, (biggestDollar, _('argument')), alias)

View File

@ -31,14 +31,13 @@
import os import os
import sys import sys
import time import time
if sys.version_info[0] < 3:
from io import open
from cStringIO import StringIO from cStringIO import StringIO
import supybot.conf as conf import supybot.conf as conf
import supybot.world as world import supybot.world as world
import supybot.ircdb as ircdb import supybot.ircdb as ircdb
import supybot.irclib as irclib import supybot.irclib as irclib
import supybot.minisix as minisix
import supybot.ircmsgs as ircmsgs import supybot.ircmsgs as ircmsgs
import supybot.ircutils as ircutils import supybot.ircutils as ircutils
import supybot.registry as registry import supybot.registry as registry
@ -46,6 +45,9 @@ import supybot.callbacks as callbacks
from supybot.i18n import PluginInternationalization, internationalizeDocstring from supybot.i18n import PluginInternationalization, internationalizeDocstring
_ = PluginInternationalization('ChannelLogger') _ = PluginInternationalization('ChannelLogger')
if minisix.PY2:
from io import open
class FakeLog(object): class FakeLog(object):
def flush(self): def flush(self):
return return
@ -164,7 +166,7 @@ class ChannelLogger(callbacks.Plugin):
format = conf.supybot.log.timestampFormat() format = conf.supybot.log.timestampFormat()
if format: if format:
string = time.strftime(format) + ' ' string = time.strftime(format) + ' '
if sys.version_info[0] < 3: if minisix.PY2:
string = string.decode('utf8', 'ignore') string = string.decode('utf8', 'ignore')
log.write(string) log.write(string)
@ -181,7 +183,7 @@ class ChannelLogger(callbacks.Plugin):
self.timestamp(log) self.timestamp(log)
if self.registryValue('stripFormatting', channel): if self.registryValue('stripFormatting', channel):
s = ircutils.stripFormatting(s) s = ircutils.stripFormatting(s)
if sys.version_info[0] < 3: if minisix.PY2:
s = s.decode('utf8', 'ignore') s = s.decode('utf8', 'ignore')
log.write(s) log.write(s)
if self.registryValue('flushImmediately'): if self.registryValue('flushImmediately'):

View File

@ -39,6 +39,7 @@ import supybot.ircdb as ircdb
import supybot.utils as utils import supybot.utils as utils
from supybot.commands import * from supybot.commands import *
import supybot.plugins as plugins import supybot.plugins as plugins
import supybot.minisix as minisix
import supybot.ircutils as ircutils import supybot.ircutils as ircutils
import supybot.callbacks as callbacks import supybot.callbacks as callbacks
import supybot.httpserver as httpserver import supybot.httpserver as httpserver
@ -219,11 +220,11 @@ class Factoids(callbacks.Plugin, plugins.ChannelDBHandler):
def makeDb(self, filename): def makeDb(self, filename):
if os.path.exists(filename): if os.path.exists(filename):
db = sqlite3.connect(filename) db = sqlite3.connect(filename)
if sys.version_info[0] < 3: if minisix.PY2:
db.text_factory = str db.text_factory = str
return db return db
db = sqlite3.connect(filename) db = sqlite3.connect(filename)
if sys.version_info[0] < 3: if minisix.PY2:
db.text_factory = str db.text_factory = str
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""CREATE TABLE keys ( cursor.execute("""CREATE TABLE keys (

View File

@ -38,6 +38,7 @@ from cStringIO import StringIO
import supybot.conf as conf import supybot.conf as conf
import supybot.utils as utils import supybot.utils as utils
from supybot.commands import * from supybot.commands import *
import supybot.minisix as minisix
import supybot.ircmsgs as ircmsgs import supybot.ircmsgs as ircmsgs
import supybot.ircutils as ircutils import supybot.ircutils as ircutils
import supybot.callbacks as callbacks import supybot.callbacks as callbacks
@ -146,7 +147,7 @@ class Filter(callbacks.Plugin):
Returns the binary representation of <text>. Returns the binary representation of <text>.
""" """
L = [] L = []
if sys.version_info[0] >= 3: if minisix.PY3:
if isinstance(text, str): if isinstance(text, str):
bytes_ = text.encode() bytes_ = text.encode()
else: else:
@ -221,7 +222,7 @@ class Filter(callbacks.Plugin):
commonly used for text that simply needs to be hidden from inadvertent commonly used for text that simply needs to be hidden from inadvertent
reading by roaming eyes, since it's easily reversible. reading by roaming eyes, since it's easily reversible.
""" """
if sys.version_info[0] < 3: if minisix.PY2:
text = text.decode('utf8') text = text.decode('utf8')
irc.reply(self._rot13_encoder(text)[0]) irc.reply(self._rot13_encoder(text)[0])
rot13 = wrap(rot13, ['text']) rot13 = wrap(rot13, ['text'])
@ -398,12 +399,12 @@ class Filter(callbacks.Plugin):
Returns <text> colorized like a rainbow. Returns <text> colorized like a rainbow.
""" """
if sys.version_info[0] < 3: if minisix.PY2:
text = text.decode('utf-8') text = text.decode('utf-8')
colors = utils.iter.cycle(['05', '04', '07', '08', '09', '03', '11', colors = utils.iter.cycle(['05', '04', '07', '08', '09', '03', '11',
'10', '12', '02', '06', '13']) '10', '12', '02', '06', '13'])
L = [self._color(c, fg=next(colors)) for c in text] L = [self._color(c, fg=next(colors)) for c in text]
if sys.version_info[0] < 3: if minisix.PY2:
L = [c.encode('utf-8') for c in L] L = [c.encode('utf-8') for c in L]
irc.reply(''.join(L) + '\x03') irc.reply(''.join(L) + '\x03')
rainbow = wrap(rainbow, ['text']) rainbow = wrap(rainbow, ['text'])

View File

@ -38,6 +38,7 @@ import supybot.conf as conf
import supybot.utils as utils import supybot.utils as utils
import supybot.ircdb as ircdb import supybot.ircdb as ircdb
from supybot.commands import * from supybot.commands import *
import supybot.minisix as minisix
import supybot.plugins as plugins import supybot.plugins as plugins
import supybot.ircutils as ircutils import supybot.ircutils as ircutils
import supybot.callbacks as callbacks import supybot.callbacks as callbacks
@ -147,7 +148,7 @@ class GPG(callbacks.Plugin):
the key used is associated to a user.""" the key used is associated to a user."""
self._expire_tokens() self._expire_tokens()
content = utils.web.getUrl(url) content = utils.web.getUrl(url)
if sys.version_info[0] >= 3 and isinstance(content, bytes): if minisix.PY3 and isinstance(content, bytes):
content = content.decode() content = content.decode()
match = self._auth_re.search(content) match = self._auth_re.search(content)
if not match: if not match:

View File

@ -40,6 +40,7 @@ import supybot.conf as conf
import supybot.utils as utils import supybot.utils as utils
import supybot.world as world import supybot.world as world
from supybot.commands import * from supybot.commands import *
import supybot.minisix as minisix
import supybot.ircmsgs as ircmsgs import supybot.ircmsgs as ircmsgs
import supybot.ircutils as ircutils import supybot.ircutils as ircutils
import supybot.callbacks as callbacks import supybot.callbacks as callbacks
@ -136,7 +137,7 @@ class Google(callbacks.PluginRegexp):
title = utils.web.htmlToText(result['titleNoFormatting']\ title = utils.web.htmlToText(result['titleNoFormatting']\
.encode('utf-8')) .encode('utf-8'))
url = result['unescapedUrl'] url = result['unescapedUrl']
if sys.version_info[0] < 3: if minisix.PY2:
url = url.encode('utf-8') url = url.encode('utf-8')
if title: if title:
if bold: if bold:
@ -144,7 +145,7 @@ class Google(callbacks.PluginRegexp):
results.append(format('%s: %u', title, url)) results.append(format('%s: %u', title, url))
else: else:
results.append(url) results.append(url)
if sys.version_info[0] < 3: if minisix.PY2:
repl = lambda x:x if isinstance(x, unicode) else unicode(x, 'utf8') repl = lambda x:x if isinstance(x, unicode) else unicode(x, 'utf8')
results = list(map(repl, results)) results = list(map(repl, results))
if not results: if not results:

View File

@ -35,6 +35,7 @@ import csv
import supybot.conf as conf import supybot.conf as conf
import supybot.utils as utils import supybot.utils as utils
from supybot.commands import * from supybot.commands import *
import supybot.minisix as minisix
import supybot.plugins as plugins import supybot.plugins as plugins
import supybot.ircmsgs as ircmsgs import supybot.ircmsgs as ircmsgs
import supybot.ircutils as ircutils import supybot.ircutils as ircutils
@ -59,12 +60,12 @@ class SqliteKarmaDB(object):
return self.dbs[filename] return self.dbs[filename]
if os.path.exists(filename): if os.path.exists(filename):
db = sqlite3.connect(filename, check_same_thread=False) db = sqlite3.connect(filename, check_same_thread=False)
if sys.version_info[0] < 3: if minisix.PY2:
db.text_factory = str db.text_factory = str
self.dbs[filename] = db self.dbs[filename] = db
return db return db
db = sqlite3.connect(filename, check_same_thread=False) db = sqlite3.connect(filename, check_same_thread=False)
if sys.version_info[0] < 3: if minisix.PY2:
db.text_factory = str db.text_factory = str
self.dbs[filename] = db self.dbs[filename] = db
cursor = db.cursor() cursor = db.cursor()

View File

@ -101,7 +101,7 @@ class MathTestCase(PluginTestCase):
self.assertResponse('calc 5*0.06', str(5*0.06)) self.assertResponse('calc 5*0.06', str(5*0.06))
self.assertResponse('calc 2.0-7.0', str(2-7)) self.assertResponse('calc 2.0-7.0', str(2-7))
self.assertResponse('calc e**(i*pi)+1', '0') self.assertResponse('calc e**(i*pi)+1', '0')
if sys.version_info[0] >= 3: if minisix.PY3:
# Python 2 has bad handling of exponentiation of negative numbers # Python 2 has bad handling of exponentiation of negative numbers
self.assertResponse('calc (-1)**.5', 'i') self.assertResponse('calc (-1)**.5', 'i')
self.assertRegexp('calc (-5)**.5', '2.236067977[0-9]+i') self.assertRegexp('calc (-5)**.5', '2.236067977[0-9]+i')

View File

@ -30,6 +30,7 @@
import supybot.utils as utils import supybot.utils as utils
from supybot.commands import * from supybot.commands import *
import supybot.minisix as minisix
import supybot.plugins as plugins import supybot.plugins as plugins
import supybot.ircutils as ircutils import supybot.ircutils as ircutils
import supybot.callbacks as callbacks import supybot.callbacks as callbacks
@ -81,11 +82,11 @@ class MessageParser(callbacks.Plugin, plugins.ChannelDBHandler):
"""Create the database and connect to it.""" """Create the database and connect to it."""
if os.path.exists(filename): if os.path.exists(filename):
db = sqlite3.connect(filename) db = sqlite3.connect(filename)
if sys.version_info[0] < 3: if minisix.PY2:
db.text_factory = str db.text_factory = str
return db return db
db = sqlite3.connect(filename) db = sqlite3.connect(filename)
if sys.version_info[0] < 3: if minisix.PY2:
db.text_factory = str db.text_factory = str
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""CREATE TABLE triggers ( cursor.execute("""CREATE TABLE triggers (

View File

@ -44,6 +44,7 @@ import supybot.utils as utils
from supybot.commands import * from supybot.commands import *
import supybot.ircdb as ircdb import supybot.ircdb as ircdb
import supybot.irclib as irclib import supybot.irclib as irclib
import supybot.minisix as minisix
import supybot.ircmsgs as ircmsgs import supybot.ircmsgs as ircmsgs
import supybot.ircutils as ircutils import supybot.ircutils as ircutils
import supybot.callbacks as callbacks import supybot.callbacks as callbacks
@ -53,7 +54,7 @@ from supybot import commands
from supybot.i18n import PluginInternationalization, internationalizeDocstring from supybot.i18n import PluginInternationalization, internationalizeDocstring
_ = PluginInternationalization('Misc') _ = PluginInternationalization('Misc')
if sys.version_info[0] < 3: if minisix.PY2:
from itertools import ifilter as filter from itertools import ifilter as filter
def get_suffix(file): def get_suffix(file):
@ -336,7 +337,7 @@ class Misc(callbacks.Plugin):
version = data['commit']['committer']['date'] version = data['commit']['committer']['date']
# Strip the last 'Z': # Strip the last 'Z':
version = version.rsplit('T', 1)[0].replace('-', '.') version = version.rsplit('T', 1)[0].replace('-', '.')
if sys.version_info[0] < 3 and isinstance(version, unicode): if minisix.PY2 and isinstance(version, unicode):
version = version.encode('utf8') version = version.encode('utf8')
versions[branch] = version versions[branch] = version
newest = _('The newest versions available online are %s.') % \ newest = _('The newest versions available online are %s.') % \

View File

@ -39,6 +39,7 @@ import supybot.ircdb as ircdb
import supybot.utils as utils import supybot.utils as utils
import supybot.shlex as shlex import supybot.shlex as shlex
from supybot.commands import * from supybot.commands import *
import supybot.minisix as minisix
import supybot.plugins as plugins import supybot.plugins as plugins
import supybot.ircutils as ircutils import supybot.ircutils as ircutils
import supybot.callbacks as callbacks import supybot.callbacks as callbacks
@ -107,12 +108,12 @@ class SqliteMoobotDB(object):
if os.path.exists(filename): if os.path.exists(filename):
db = sqlite3.connect(filename, check_same_thread=False) db = sqlite3.connect(filename, check_same_thread=False)
if sys.version_info[0] < 3: if minisix.PY2:
db.text_factory = str db.text_factory = str
self.dbs[channel] = db self.dbs[channel] = db
return db return db
db = sqlite3.connect(filename, check_same_thread=False) db = sqlite3.connect(filename, check_same_thread=False)
if sys.version_info[0] < 3: if minisix.PY2:
db.text_factory = str db.text_factory = str
self.dbs[channel] = db self.dbs[channel] = db
cursor = db.cursor() cursor = db.cursor()

View File

@ -47,6 +47,7 @@ from supybot.commands import *
import supybot.irclib as irclib import supybot.irclib as irclib
import supybot.plugin as plugin import supybot.plugin as plugin
import supybot.plugins as plugins import supybot.plugins as plugins
import supybot.minisix as minisix
import supybot.drivers as drivers import supybot.drivers as drivers
import supybot.ircmsgs as ircmsgs import supybot.ircmsgs as ircmsgs
import supybot.ircutils as ircutils import supybot.ircutils as ircutils
@ -398,7 +399,7 @@ class Owner(callbacks.Plugin):
L.append(format('linecache line cache flushed: %n cleared.', L.append(format('linecache line cache flushed: %n cleared.',
(len(linecache.cache), 'line'))) (len(linecache.cache), 'line')))
linecache.clearcache() linecache.clearcache()
if sys.version_info[0] < 3: if minisix.PY2:
sys.exc_clear() sys.exc_clear()
collected = world.upkeep() collected = world.upkeep()
if gc.garbage: if gc.garbage:

View File

@ -37,17 +37,18 @@ import urllib
import tarfile import tarfile
from cStringIO import StringIO from cStringIO import StringIO
BytesIO = StringIO if sys.version_info[0] < 3 else io.BytesIO
import supybot.log as log import supybot.log as log
import supybot.conf as conf import supybot.conf as conf
import supybot.utils as utils import supybot.utils as utils
from supybot.commands import * from supybot.commands import *
import supybot.minisix as minisix
import supybot.plugins as plugins import supybot.plugins as plugins
import supybot.ircutils as ircutils import supybot.ircutils as ircutils
import supybot.callbacks as callbacks import supybot.callbacks as callbacks
from supybot.i18n import PluginInternationalization, internationalizeDocstring from supybot.i18n import PluginInternationalization, internationalizeDocstring
BytesIO = StringIO if minisix.PY2 else io.BytesIO
_ = PluginInternationalization('PluginDownloader') _ = PluginInternationalization('PluginDownloader')
class Repository: class Repository:
@ -104,7 +105,7 @@ class GithubRepository(GitRepository):
def _download(self, plugin): def _download(self, plugin):
try: try:
response = utils.web.getUrlFd(self._downloadUrl) response = utils.web.getUrlFd(self._downloadUrl)
if sys.version_info[0] < 3: if minisix.PY2:
assert response.getcode() == 200, response.getcode() assert response.getcode() == 200, response.getcode()
else: else:
assert response.status == 200, response.status assert response.status == 200, response.status
@ -127,7 +128,7 @@ class GithubRepository(GitRepository):
assert archive.getmember(prefix + dirname).isdir(), \ assert archive.getmember(prefix + dirname).isdir(), \
'This is not a valid plugin (it is a file, not a directory).' 'This is not a valid plugin (it is a file, not a directory).'
run_2to3 = sys.version_info[0] >= 3 run_2to3 = minisix.PY3
for file in archive.getmembers(): for file in archive.getmembers():
if file.name.startswith(prefix + dirname): if file.name.startswith(prefix + dirname):
extractedFile = archive.extractfile(file) extractedFile = archive.extractfile(file)
@ -144,7 +145,7 @@ class GithubRepository(GitRepository):
with open(newFileName, 'ab') as fd: with open(newFileName, 'ab') as fd:
reload_imported = False reload_imported = False
for line in extractedFile.readlines(): for line in extractedFile.readlines():
if sys.version_info[0] >= 3: if minisix.PY3:
if 'import reload' in line.decode(): if 'import reload' in line.decode():
reload_imported = True reload_imported = True
elif not reload_imported and \ elif not reload_imported and \
@ -188,7 +189,7 @@ class GithubRepository(GitRepository):
if file.name.startswith(prefix + dirname + '/README'): if file.name.startswith(prefix + dirname + '/README'):
extractedFile = archive.extractfile(file) extractedFile = archive.extractfile(file)
content = extractedFile.read() content = extractedFile.read()
if sys.version_info[0] >= 3: if minisix.PY3:
content = content.decode() content = content.decode()
return content return content

View File

@ -33,6 +33,7 @@ import sys
import shutil import shutil
from supybot.test import * from supybot.test import *
import supybot.minisix as minisix
pluginsPath = '%s/test-plugins' % os.getcwd() pluginsPath = '%s/test-plugins' % os.getcwd()
@ -98,7 +99,7 @@ class PluginDownloaderTestCase(PluginTestCase):
'Advanced Twitter plugin for Supybot, with capabilities ' 'Advanced Twitter plugin for Supybot, with capabilities '
'handling, and per-channel user account.') 'handling, and per-channel user account.')
if sys.version_info[0] >= 3: if minisix.PY3:
def test_2to3(self): def test_2to3(self):
self.assertRegexp('plugindownloader install SpiderDave Pastebin', self.assertRegexp('plugindownloader install SpiderDave Pastebin',
'convert') 'convert')

View File

@ -37,6 +37,7 @@ import supybot.dbi as dbi
import supybot.conf as conf import supybot.conf as conf
import supybot.utils as utils import supybot.utils as utils
from supybot.commands import * from supybot.commands import *
import supybot.minisix as minisix
import supybot.ircmsgs as ircmsgs import supybot.ircmsgs as ircmsgs
import supybot.plugins as plugins import supybot.plugins as plugins
import supybot.ircutils as ircutils import supybot.ircutils as ircutils
@ -86,13 +87,13 @@ class SqliteQuoteGrabsDB(object):
return self.dbs[filename] return self.dbs[filename]
if os.path.exists(filename): if os.path.exists(filename):
db = sqlite3.connect(filename) db = sqlite3.connect(filename)
if sys.version_info[0] < 3: if minisix.PY2:
db.text_factory = str db.text_factory = str
db.create_function('nickeq', 2, p) db.create_function('nickeq', 2, p)
self.dbs[filename] = db self.dbs[filename] = db
return db return db
db = sqlite3.connect(filename) db = sqlite3.connect(filename)
if sys.version_info[0] < 3: if minisix.PY2:
db.text_factory = str db.text_factory = str
db.create_function('nickeq', 2, p) db.create_function('nickeq', 2, p)
self.dbs[filename] = db self.dbs[filename] = db

View File

@ -44,6 +44,7 @@ import supybot.conf as conf
import supybot.utils as utils import supybot.utils as utils
import supybot.world as world import supybot.world as world
from supybot.commands import * from supybot.commands import *
import supybot.minisix as minisix
import supybot.ircmsgs as ircmsgs import supybot.ircmsgs as ircmsgs
import supybot.ircutils as ircutils import supybot.ircutils as ircutils
import supybot.registry as registry import supybot.registry as registry

View File

@ -32,7 +32,8 @@ import sys
import feedparser import feedparser
from supybot.test import * from supybot.test import *
import supybot.conf as conf import supybot.conf as conf
if sys.version_info[0] >= 3: import supybot.minisix as minisix
if minisix.PY3:
from io import BytesIO from io import BytesIO
else: else:
from cStringIO import StringIO as BytesIO from cStringIO import StringIO as BytesIO
@ -47,7 +48,7 @@ xkcd_new = """<?xml version="1.0" encoding="utf-8"?>
def constant(content): def constant(content):
if sys.version_info[0] >= 3: if minisix.PY3:
content = content.encode() content = content.encode()
def f(*args, **kwargs): def f(*args, **kwargs):
return BytesIO(content) return BytesIO(content)

View File

@ -39,6 +39,7 @@ import supybot.world as world
import supybot.ircdb as ircdb import supybot.ircdb as ircdb
from supybot.commands import * from supybot.commands import *
import supybot.irclib as irclib import supybot.irclib as irclib
import supybot.minisix as minisix
import supybot.ircmsgs as ircmsgs import supybot.ircmsgs as ircmsgs
import supybot.plugins as plugins import supybot.plugins as plugins
import supybot.ircutils as ircutils import supybot.ircutils as ircutils
@ -209,7 +210,7 @@ class Seen(callbacks.Plugin):
nick, channel, nick, channel,
utils.timeElapsed(time.time()-when)) utils.timeElapsed(time.time()-when))
if self.registryValue('showLastMessage', channel): if self.registryValue('showLastMessage', channel):
if sys.version_info[0] < 3: if minisix.PY2:
said = said.decode('utf8') said = said.decode('utf8')
reply = _('%s: %s') % (reply, said) reply = _('%s: %s') % (reply, said)
irc.reply(reply) irc.reply(reply)

View File

@ -37,7 +37,7 @@ import binascii
import supybot.utils as utils import supybot.utils as utils
from supybot.commands import * from supybot.commands import *
import supybot.commands as commands import supybot.minisix as minisix
import supybot.plugins as plugins import supybot.plugins as plugins
import supybot.commands as commands import supybot.commands as commands
import supybot.ircutils as ircutils import supybot.ircutils as ircutils
@ -96,9 +96,9 @@ class String(callbacks.Plugin):
text = codecs.getencoder('base64_codec')(text)[0].decode() text = codecs.getencoder('base64_codec')(text)[0].decode()
# Change result into a string # Change result into a string
if sys.version_info[0] < 3 and isinstance(text, unicode): if minisix.PY2 and isinstance(text, unicode):
text = text.encode('utf-8') text = text.encode('utf-8')
elif sys.version_info[0] >= 3 and isinstance(text, bytes): elif minisix.PY3 and isinstance(text, bytes):
text = text.decode() text = text.decode()
if encoding in ('base64', 'base64_codec'): if encoding in ('base64', 'base64_codec'):
@ -129,7 +129,7 @@ class String(callbacks.Plugin):
decoder = codecs.getdecoder(encoding) decoder = codecs.getdecoder(encoding)
except LookupError: except LookupError:
irc.errorInvalid(_('encoding'), encoding) irc.errorInvalid(_('encoding'), encoding)
if sys.version_info[0] >= 3 and not isinstance(text, bytes): if minisix.PY3 and not isinstance(text, bytes):
text = text.encode() text = text.encode()
try: try:
text = decoder(text)[0] text = decoder(text)[0]
@ -140,9 +140,9 @@ class String(callbacks.Plugin):
return return
# Change result into a string # Change result into a string
if sys.version_info[0] < 3 and isinstance(text, unicode): if minisix.PY2 and isinstance(text, unicode):
text = text.encode('utf-8') text = text.encode('utf-8')
elif sys.version_info[0] >= 3 and isinstance(text, bytes): elif minisix.PY3 and isinstance(text, bytes):
try: try:
text = text.decode() text = text.decode()
except UnicodeDecodeError: except UnicodeDecodeError:

View File

@ -42,6 +42,7 @@ import shlex
import supybot.utils as utils import supybot.utils as utils
from supybot.commands import * from supybot.commands import *
import supybot.minisix as minisix
import supybot.plugins as plugins import supybot.plugins as plugins
import supybot.ircutils as ircutils import supybot.ircutils as ircutils
import supybot.registry as registry import supybot.registry as registry
@ -222,7 +223,7 @@ class Unix(callbacks.Plugin):
'not available.'), Raise=True) 'not available.'), Raise=True)
(out, err) = inst.communicate() (out, err) = inst.communicate()
inst.wait() inst.wait()
if sys.version_info[0] > 2: if minisix.PY3:
lines = [i.decode('utf-8').rstrip() for i in out.splitlines()] lines = [i.decode('utf-8').rstrip() for i in out.splitlines()]
lines = list(map(str, lines)) lines = list(map(str, lines))
else: else:

View File

@ -37,6 +37,7 @@ import htmlentitydefs
import supybot.conf as conf import supybot.conf as conf
import supybot.utils as utils import supybot.utils as utils
from supybot.commands import * from supybot.commands import *
import supybot.minisix as minisix
import supybot.plugins as plugins import supybot.plugins as plugins
import supybot.commands as commands import supybot.commands as commands
import supybot.ircutils as ircutils import supybot.ircutils as ircutils
@ -163,7 +164,7 @@ class Web(callbacks.PluginRegexp):
if self.registryValue('snarferShowTargetDomain', channel) if self.registryValue('snarferShowTargetDomain', channel)
else url) else url)
title = utils.web.htmlToText(parser.title.strip()) title = utils.web.htmlToText(parser.title.strip())
if sys.version_info[0] < 3: if minisix.PY2:
if isinstance(title, unicode): if isinstance(title, unicode):
title = title.encode('utf8', 'replace') title = title.encode('utf8', 'replace')
s = format(_('Title: %s (at %s)'), title, domain) s = format(_('Title: %s (at %s)'), title, domain)
@ -280,7 +281,7 @@ class Web(callbacks.PluginRegexp):
except UnicodeDecodeError: except UnicodeDecodeError:
pass pass
parser = Title() parser = Title()
if sys.version_info[0] >= 3 and isinstance(text, bytes): if minisix.PY3 and isinstance(text, bytes):
irc.error(_('Could not guess the page\'s encoding. (Try ' irc.error(_('Could not guess the page\'s encoding. (Try '
'installing python-charade.)'), Raise=True) 'installing python-charade.)'), Raise=True)
try: try:

View File

@ -51,7 +51,7 @@ try:
proc = subprocess.Popen('git show HEAD --format=%ci', shell=True, proc = subprocess.Popen('git show HEAD --format=%ci', shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout=subprocess.PIPE, stderr=subprocess.PIPE)
date = proc.stdout.readline() date = proc.stdout.readline()
if sys.version_info[0] >= 3: if minisix.PY3:
date = date.decode() date = date.decode()
date = time.strptime(date.strip(), '%Y-%m-%d %H:%M:%S %z') date = time.strptime(date.strip(), '%Y-%m-%d %H:%M:%S %z')
utc_date = time.gmtime(time.mktime(date)) utc_date = time.gmtime(time.mktime(date))

View File

@ -42,7 +42,13 @@ import codecs
import getopt import getopt
import inspect import inspect
if sys.version_info[0] < 3: from . import (conf, ircdb, irclib, ircmsgs, ircutils, log, minisix, registry,
utils, world)
from .utils.iter import any, all
from .i18n import PluginInternationalization, internationalizeDocstring
_ = PluginInternationalization()
if minisix.PY2:
# cStringIO is buggy with Python 2.6 ( # cStringIO is buggy with Python 2.6 (
# see http://paste.progval.net/show/227/ ) # see http://paste.progval.net/show/227/ )
# and it does not handle unicode objects in Python 2.x # and it does not handle unicode objects in Python 2.x
@ -50,12 +56,6 @@ if sys.version_info[0] < 3:
else: else:
from cStringIO import StringIO from cStringIO import StringIO
from . import (conf, ircdb, irclib, ircmsgs, ircutils, log, registry, utils,
world)
from .utils.iter import any, all
from .i18n import PluginInternationalization, internationalizeDocstring
_ = PluginInternationalization()
def _addressed(nick, msg, prefixChars=None, nicks=None, def _addressed(nick, msg, prefixChars=None, nicks=None,
prefixStrings=None, whenAddressedByNick=None, prefixStrings=None, whenAddressedByNick=None,
whenAddressedByNickAtEnd=None): whenAddressedByNickAtEnd=None):
@ -151,9 +151,9 @@ def canonicalName(command, preserve_spaces=False):
Currently, this makes everything lowercase and removes all dashes and Currently, this makes everything lowercase and removes all dashes and
underscores. underscores.
""" """
if sys.version_info[0] < 3 and isinstance(command, unicode): if minisix.PY2 and isinstance(command, unicode):
command = command.encode('utf-8') command = command.encode('utf-8')
elif sys.version_info[0] >= 3 and isinstance(command, bytes): elif minisix.PY3 and isinstance(command, bytes):
command = command.decode() command = command.decode()
special = '\t-_' special = '\t-_'
if not preserve_spaces: if not preserve_spaces:
@ -294,7 +294,7 @@ class Tokenizer(object):
# Whoever you are, if you make a single modification to this # Whoever you are, if you make a single modification to this
# code, TEST the code with Python 2 & 3, both with the unit # code, TEST the code with Python 2 & 3, both with the unit
# tests and on IRC with this: @echo "好" # tests and on IRC with this: @echo "好"
if sys.version_info[0] < 3: if minisix.PY2:
try: try:
token = token.encode('utf8').decode('string_escape') token = token.encode('utf8').decode('string_escape')
token = token.decode('utf8') token = token.decode('utf8')
@ -925,7 +925,7 @@ class NestedCommandsIrcProxy(ReplyIrcProxy):
# In case we're truncating, we add 20 to allowedLength, # In case we're truncating, we add 20 to allowedLength,
# because our allowedLength is shortened for the # because our allowedLength is shortened for the
# "(XX more messages)" trailer. # "(XX more messages)" trailer.
if sys.version_info[0] >= 3: if minisix.PY3:
appended = _('(XX more messages)').encode() appended = _('(XX more messages)').encode()
s = s.encode()[:allowedLength+len(appended)] s = s.encode()[:allowedLength+len(appended)]
s = s.decode('utf8', 'ignore') s = s.decode('utf8', 'ignore')

View File

@ -41,7 +41,7 @@ import errno
import select import select
import socket import socket
from .. import (conf, drivers, log, schedule, utils, world) from .. import (conf, drivers, log, minisix, schedule, utils, world)
from ..utils.iter import imap from ..utils.iter import imap
from ..utils.str import decode_raw_line from ..utils.str import decode_raw_line
@ -127,7 +127,7 @@ class SocketDriver(drivers.IrcDriver, drivers.ServersMixin):
self.outbuffer += ''.join(map(str, msgs)) self.outbuffer += ''.join(map(str, msgs))
if self.outbuffer: if self.outbuffer:
try: try:
if sys.version_info[0] < 3: if minisix.PY2:
sent = self.conn.send(self.outbuffer) sent = self.conn.send(self.outbuffer)
else: else:
sent = self.conn.send(self.outbuffer.encode()) sent = self.conn.send(self.outbuffer.encode())
@ -148,8 +148,8 @@ class SocketDriver(drivers.IrcDriver, drivers.ServersMixin):
# Do not use a list comprehension here, we have to edit the list # Do not use a list comprehension here, we have to edit the list
# and not to reassign it. # and not to reassign it.
if not inst.connected or \ if not inst.connected or \
(sys.version_info[0] == 3 and inst.conn._closed) or \ (minisix.PY3 and inst.conn._closed) or \
(sys.version_info[0] == 2 and (minisix.PY2 and
inst.conn._sock.__class__ is socket._closedsocket): inst.conn._sock.__class__ is socket._closedsocket):
cls._instances.remove(inst) cls._instances.remove(inst)
elif inst.conn.fileno() == -1: elif inst.conn.fileno() == -1:

View File

@ -41,6 +41,7 @@ from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import supybot.log as log import supybot.log as log
import supybot.conf as conf import supybot.conf as conf
import supybot.world as world import supybot.world as world
import supybot.minisix as minisix
from supybot.i18n import PluginInternationalization from supybot.i18n import PluginInternationalization
_ = PluginInternationalization() _ = PluginInternationalization()
@ -276,7 +277,7 @@ class SupyHTTPServerCallback(object):
message, it probably means you are developing a plugin, and you have message, it probably means you are developing a plugin, and you have
neither overriden this message or defined an handler for this query.""") neither overriden this message or defined an handler for this query.""")
if sys.version_info[0] >= 3: if minisix.PY3:
def write(self, b): def write(self, b):
if isinstance(b, str): if isinstance(b, str):
b = b.encode() b = b.encode()
@ -316,7 +317,7 @@ class Supy404(SupyHTTPServerCallback):
self.send_header('Content-Length', len(self.response)) self.send_header('Content-Length', len(self.response))
self.end_headers() self.end_headers()
response = self.response response = self.response
if sys.version_info[0] >= 3: if minisix.PY3:
response = response.encode() response = response.encode()
self.wfile.write(response) self.wfile.write(response)
@ -339,7 +340,7 @@ class SupyIndex(SupyHTTPServerCallback):
self.send_header('Content-Type', 'text/html; charset=utf-8') self.send_header('Content-Type', 'text/html; charset=utf-8')
self.send_header('Content-Length', len(response)) self.send_header('Content-Length', len(response))
self.end_headers() self.end_headers()
if sys.version_info[0] >= 3: if minisix.PY3:
response = response.encode() response = response.encode()
self.wfile.write(response) self.wfile.write(response)
@ -357,7 +358,7 @@ class Static(SupyHTTPServerCallback):
self.send_header('Content-type', self._mimetype) self.send_header('Content-type', self._mimetype)
self.send_header('Content-Length', len(response)) self.send_header('Content-Length', len(response))
self.end_headers() self.end_headers()
if sys.version_info[0] >= 3: if minisix.PY3:
response = response.encode() response = response.encode()
self.wfile.write(response) self.wfile.write(response)
@ -394,7 +395,7 @@ class Favicon(SupyHTTPServerCallback):
self.send_header('Content-type', 'text/plain; charset=utf-8') self.send_header('Content-type', 'text/plain; charset=utf-8')
self.send_header('Content-Length', len(response)) self.send_header('Content-Length', len(response))
self.end_headers() self.end_headers()
if sys.version_info[0] >= 3: if minisix.PY3:
response = response.encode() response = response.encode()
self.wfile.write(response) self.wfile.write(response)

View File

@ -40,7 +40,7 @@ import sys
import time import time
import functools import functools
from . import conf, ircutils, utils from . import conf, ircutils, minisix, utils
from .utils.iter import all from .utils.iter import all
### ###
@ -582,7 +582,7 @@ def kick(channel, nick, s='', prefix='', msg=None):
assert isNick(nick), repr(nick) assert isNick(nick), repr(nick)
if msg and not prefix: if msg and not prefix:
prefix = msg.prefix prefix = msg.prefix
if sys.version_info[0] < 3 and isinstance(s, unicode): if minisix.PY2 and isinstance(s, unicode):
s = s.encode('utf8') s = s.encode('utf8')
assert isinstance(s, str) assert isinstance(s, str)
if s: if s:
@ -602,7 +602,7 @@ def kicks(channels, nicks, s='', prefix='', msg=None):
assert areNicks(nicks), repr(nicks) assert areNicks(nicks), repr(nicks)
if msg and not prefix: if msg and not prefix:
prefix = msg.prefix prefix = msg.prefix
if sys.version_info[0] < 3 and isinstance(s, unicode): if minisix.PY2 and isinstance(s, unicode):
s = s.encode('utf8') s = s.encode('utf8')
assert isinstance(s, str) assert isinstance(s, str)
if s: if s:
@ -619,7 +619,7 @@ def privmsg(recipient, s, prefix='', msg=None):
if conf.supybot.protocols.irc.strictRfc(): if conf.supybot.protocols.irc.strictRfc():
assert (areReceivers(recipient)), repr(recipient) assert (areReceivers(recipient)), repr(recipient)
assert s, 's must not be empty.' assert s, 's must not be empty.'
if sys.version_info[0] < 3 and isinstance(s, unicode): if minisix.PY2 and isinstance(s, unicode):
s = s.encode('utf8') s = s.encode('utf8')
assert isinstance(s, str) assert isinstance(s, str)
if msg and not prefix: if msg and not prefix:
@ -651,7 +651,7 @@ def notice(recipient, s, prefix='', msg=None):
if conf.supybot.protocols.irc.strictRfc(): if conf.supybot.protocols.irc.strictRfc():
assert areReceivers(recipient), repr(recipient) assert areReceivers(recipient), repr(recipient)
assert s, 'msg must not be empty.' assert s, 'msg must not be empty.'
if sys.version_info[0] < 3 and isinstance(s, unicode): if minisix.PY2 and isinstance(s, unicode):
s = s.encode('utf8') s = s.encode('utf8')
assert isinstance(s, str) assert isinstance(s, str)
if msg and not prefix: if msg and not prefix:
@ -701,7 +701,7 @@ def part(channel, s='', prefix='', msg=None):
assert isChannel(channel), repr(channel) assert isChannel(channel), repr(channel)
if msg and not prefix: if msg and not prefix:
prefix = msg.prefix prefix = msg.prefix
if sys.version_info[0] < 3 and isinstance(s, unicode): if minisix.PY2 and isinstance(s, unicode):
s = s.encode('utf8') s = s.encode('utf8')
assert isinstance(s, str) assert isinstance(s, str)
if s: if s:
@ -717,7 +717,7 @@ def parts(channels, s='', prefix='', msg=None):
assert all(isChannel, channels), channels assert all(isChannel, channels), channels
if msg and not prefix: if msg and not prefix:
prefix = msg.prefix prefix = msg.prefix
if sys.version_info[0] < 3 and isinstance(s, unicode): if minisix.PY2 and isinstance(s, unicode):
s = s.encode('utf8') s = s.encode('utf8')
assert isinstance(s, str) assert isinstance(s, str)
if s: if s:
@ -746,7 +746,7 @@ def topic(channel, topic=None, prefix='', msg=None):
return IrcMsg(prefix=prefix, command='TOPIC', return IrcMsg(prefix=prefix, command='TOPIC',
args=(channel,), msg=msg) args=(channel,), msg=msg)
else: else:
if sys.version_info[0] < 3 and isinstance(topic, unicode): if minisix.PY2 and isinstance(topic, unicode):
topic = topic.encode('utf8') topic = topic.encode('utf8')
assert isinstance(topic, str) assert isinstance(topic, str)
return IrcMsg(prefix=prefix, command='TOPIC', return IrcMsg(prefix=prefix, command='TOPIC',

View File

@ -608,10 +608,10 @@ def isValidArgument(s):
def safeArgument(s): def safeArgument(s):
"""If s is unsafe for IRC, returns a safe version.""" """If s is unsafe for IRC, returns a safe version."""
if sys.version_info[0] < 3 and isinstance(s, unicode): if minisix.PY2 and isinstance(s, unicode):
s = s.encode('utf-8') s = s.encode('utf-8')
elif (sys.version_info[0] < 3 and not isinstance(s, basestring)) or \ elif (minisix.PY2 and not isinstance(s, basestring)) or \
(sys.version_info[0] >= 3 and not isinstance(s, str)): (minisix.PY3 and not isinstance(s, str)):
debug('Got a non-string in safeArgument: %r', s) debug('Got a non-string in safeArgument: %r', s)
s = str(s) s = str(s)
if isValidArgument(s): if isValidArgument(s):

View File

@ -65,7 +65,7 @@ def loadPluginModule(name, ignoreDeprecation=False):
module = imp.load_module(name, *moduleInfo) module = imp.load_module(name, *moduleInfo)
except: except:
sys.modules.pop(name, None) sys.modules.pop(name, None)
keys = sys.modules.keys() keys = list(sys.modules.keys())
for key in keys: for key in keys:
if key.startswith(name + '.'): if key.startswith(name + '.'):
sys.modules.pop(key) sys.modules.pop(key)

View File

@ -35,7 +35,7 @@ import sys
import textwrap import textwrap
from getpass import getpass as getPass from getpass import getpass as getPass
from . import ansi, utils from . import ansi, minisix, utils
from supybot.i18n import PluginInternationalization, internationalizeDocstring from supybot.i18n import PluginInternationalization, internationalizeDocstring
_ = PluginInternationalization() _ = PluginInternationalization()
@ -76,7 +76,7 @@ def expect(prompt, possibilities, recursed=False, default=None,
if useBold: if useBold:
prompt += ansi.RESET prompt += ansi.RESET
print(ansi.BOLD, end=' ', file=fd) print(ansi.BOLD, end=' ', file=fd)
if sys.version_info[0] >= 3: if minisix.PY3:
s = input(prompt) s = input(prompt)
else: else:
s = raw_input(prompt) s = raw_input(prompt)

View File

@ -37,7 +37,7 @@ import codecs
import string import string
import textwrap import textwrap
from . import utils, i18n from . import utils, i18n, minisix
_ = i18n.PluginInternationalization() _ = i18n.PluginInternationalization()
def error(s): def error(s):
@ -66,7 +66,7 @@ class NonExistentRegistryEntry(RegistryException, AttributeError):
# raise an AttributeError if a registry entry does not exist. # raise an AttributeError if a registry entry does not exist.
pass pass
ENCODING = 'string_escape' if sys.version_info[0] < 3 else 'unicode_escape' ENCODING = 'string_escape' if minisix.PY2 else 'unicode_escape'
decoder = codecs.getdecoder(ENCODING) decoder = codecs.getdecoder(ENCODING)
encoder = codecs.getencoder(ENCODING) encoder = codecs.getencoder(ENCODING)

View File

@ -40,7 +40,7 @@ import unittest
import threading import threading
from . import (callbacks, conf, drivers, httpserver, i18n, ircdb, irclib, from . import (callbacks, conf, drivers, httpserver, i18n, ircdb, irclib,
ircmsgs, ircutils, log, plugin, registry, utils, world) ircmsgs, ircutils, log, minisix, plugin, registry, utils, world)
i18n.import_conf() i18n.import_conf()
network = True network = True
@ -242,7 +242,7 @@ class PluginTestCase(SupyTestCase):
prefixChars = conf.supybot.reply.whenAddressedBy.chars() prefixChars = conf.supybot.reply.whenAddressedBy.chars()
if not usePrefixChar and query[0] in prefixChars: if not usePrefixChar and query[0] in prefixChars:
query = query[1:] query = query[1:]
if sys.version_info[0] < 3: if minisix.PY2:
query = query.encode('utf8') # unicode->str query = query.encode('utf8') # unicode->str
msg = ircmsgs.privmsg(to, query, prefix=frm) msg = ircmsgs.privmsg(to, query, prefix=frm)
if self.myVerbose: if self.myVerbose:
@ -437,7 +437,7 @@ class ChannelPluginTestCase(PluginTestCase):
prefixChars = conf.supybot.reply.whenAddressedBy.chars() prefixChars = conf.supybot.reply.whenAddressedBy.chars()
if query[0] not in prefixChars and usePrefixChar: if query[0] not in prefixChars and usePrefixChar:
query = prefixChars[0] + query query = prefixChars[0] + query
if sys.version_info[0] < 3 and isinstance(query, unicode): if minisix.PY2 and isinstance(query, unicode):
query = query.encode('utf8') # unicode->str query = query.encode('utf8') # unicode->str
msg = ircmsgs.privmsg(to, query, prefix=frm) msg = ircmsgs.privmsg(to, query, prefix=frm)
if self.myVerbose: if self.myVerbose:

View File

@ -46,6 +46,7 @@ from . import crypt
from .str import format from .str import format
from .file import mktemp from .file import mktemp
from .iter import imap from .iter import imap
from .. import minisix
from supybot.i18n import PluginInternationalization from supybot.i18n import PluginInternationalization
_ = PluginInternationalization() _ = PluginInternationalization()
@ -168,7 +169,7 @@ def saltHash(password, salt=None, hash='sha'):
hasher = crypt.md5 hasher = crypt.md5
return '|'.join([salt, hasher((salt + password).encode('utf8')).hexdigest()]) return '|'.join([salt, hasher((salt + password).encode('utf8')).hexdigest()])
_astStr2 = ast.Str if sys.version_info[0] < 3 else ast.Bytes _astStr2 = ast.Str if minisix.PY2 else ast.Bytes
def safeEval(s, namespace={'True': True, 'False': False, 'None': None}): def safeEval(s, namespace={'True': True, 'False': False, 'None': None}):
"""Evaluates s, safely. Useful for turning strings into tuples/lists/etc. """Evaluates s, safely. Useful for turning strings into tuples/lists/etc.
without unsafely using eval().""" without unsafely using eval()."""
@ -223,7 +224,7 @@ class IterableMap(object):
"""Define .items() in a class and subclass this to get the other iters. """Define .items() in a class and subclass this to get the other iters.
""" """
def items(self): def items(self):
if sys.version_info[0] >= 3 and hasattr(self, 'items'): if minisix.PY3 and hasattr(self, 'items'):
# For old plugins # For old plugins
return getattr(self, 'items')() # avoid 2to3 return getattr(self, 'items')() # avoid 2to3
else: else:

View File

@ -53,7 +53,7 @@ try:
except ImportError: except ImportError:
charadeLoaded = False charadeLoaded = False
if sys.version_info[0] >= 3: if minisix.PY3:
def decode_raw_line(line): def decode_raw_line(line):
#first, try to decode using utf-8 #first, try to decode using utf-8
try: try:
@ -182,8 +182,8 @@ def dqrepr(s):
"""Returns a repr() of s guaranteed to be in double quotes.""" """Returns a repr() of s guaranteed to be in double quotes."""
# The wankers-that-be decided not to use double-quotes anymore in 2.3. # The wankers-that-be decided not to use double-quotes anymore in 2.3.
# return '"' + repr("'\x00" + s)[6:] # return '"' + repr("'\x00" + s)[6:]
encoding = 'string_escape' if sys.version_info[0] < 3 else 'unicode_escape' encoding = 'string_escape' if minisix.PY2 else 'unicode_escape'
if sys.version_info[0] < 3 and isinstance(s, unicode): if minisix.PY2 and isinstance(s, unicode):
s = s.encode('utf8', 'replace') s = s.encode('utf8', 'replace')
return '"%s"' % s.encode(encoding).decode().replace('"', '\\"') return '"%s"' % s.encode(encoding).decode().replace('"', '\\"')
@ -506,7 +506,7 @@ def format(s, *args, **kwargs):
# to add the character to the _formatRe regexp or it will be ignored # to add the character to the _formatRe regexp or it will be ignored
# (and hard to debug if you don't know the trick). # (and hard to debug if you don't know the trick).
# Of course, you should also document it in the docstring above. # Of course, you should also document it in the docstring above.
if sys.version_info[0] < 3: if minisix.PY2:
def pred(s): def pred(s):
if isinstance(s, unicode): if isinstance(s, unicode):
return s.encode('utf8') return s.encode('utf8')
@ -521,7 +521,7 @@ def format(s, *args, **kwargs):
token = args.pop() token = args.pop()
if isinstance(token, str): if isinstance(token, str):
return token return token
elif sys.version_info[0] < 3 and isinstance(token, unicode): elif minisix.PY2 and isinstance(token, unicode):
return token.encode('utf8', 'replace') return token.encode('utf8', 'replace')
else: else:
return str(token) return str(token)

View File

@ -46,6 +46,7 @@ except AttributeError:
pass pass
from .str import normalizeWhitespace from .str import normalizeWhitespace
from .. import minisix
Request = urllib2.Request Request = urllib2.Request
urlquote = urllib.quote urlquote = urllib.quote
@ -108,7 +109,7 @@ def getUrlFd(url, headers=None, data=None, timeout=None):
a dict and string, respectively, as per urllib2.Request's arguments.""" a dict and string, respectively, as per urllib2.Request's arguments."""
if headers is None: if headers is None:
headers = defaultHeaders headers = defaultHeaders
if sys.version_info[0] >= 3 and isinstance(data, str): if minisix.PY3 and isinstance(data, str):
data = data.encode() data = data.encode()
try: try:
if not isinstance(url, urllib2.Request): if not isinstance(url, urllib2.Request):
@ -203,9 +204,9 @@ class HtmlToText(HTMLParser, object):
def handle_entityref(self, data): def handle_entityref(self, data):
if data in htmlentitydefs.name2codepoint: if data in htmlentitydefs.name2codepoint:
self.data.append(unichr(htmlentitydefs.name2codepoint[data])) self.data.append(unichr(htmlentitydefs.name2codepoint[data]))
elif sys.version_info[0] >= 3 and isinstance(data, bytes): elif minisix.PY3 and isinstance(data, bytes):
self.data.append(data.decode()) self.data.append(data.decode())
elif sys.version_info[0] < 3 and isinstance(data, str): elif minisix.PY2 and isinstance(data, str):
self.data.append(data.decode('utf8', errors='replace')) self.data.append(data.decode('utf8', errors='replace'))
else: else:
self.data.append(data) self.data.append(data)
@ -222,7 +223,7 @@ def htmlToText(s, tagReplace=' '):
s = s.decode(encoding) s = s.decode(encoding)
else: else:
try: try:
if sys.version_info[0] < 3 or isinstance(s, bytes): if minisix.PY2 or isinstance(s, bytes):
s = s.decode('utf8') s = s.decode('utf8')
except: except:
pass pass

View File

@ -173,7 +173,7 @@ def upkeep():
#if registryFilename is not None: #if registryFilename is not None:
# registry.open(registryFilename) # registry.open(registryFilename)
if not dying: if not dying:
if sys.version_info[0] < 3: if minisix.PY2:
log.debug('Regexp cache size: %s', len(re._cache)) log.debug('Regexp cache size: %s', len(re._cache))
log.debug('Pattern cache size: %s', len(ircutils._patternCache)) log.debug('Pattern cache size: %s', len(ircutils._patternCache))
log.debug('HostmaskPatternEqual cache size: %s', log.debug('HostmaskPatternEqual cache size: %s',

View File

@ -33,6 +33,7 @@ from supybot.test import *
import supybot.conf as conf import supybot.conf as conf
import supybot.utils as utils import supybot.utils as utils
import supybot.ircmsgs as ircmsgs import supybot.ircmsgs as ircmsgs
import supybot.minisix as minisix
import supybot.callbacks as callbacks import supybot.callbacks as callbacks
tokenize = callbacks.tokenize tokenize = callbacks.tokenize
@ -76,7 +77,7 @@ class TokenizerTestCase(SupyTestCase):
def testUnicode(self): def testUnicode(self):
self.assertEqual(tokenize(u''), [u'']) self.assertEqual(tokenize(u''), [u''])
self.assertEqual(tokenize(u'""'), [u''])""" self.assertEqual(tokenize(u'""'), [u''])"""
if sys.version_info[0] >= 3: if minisix.PY3:
_testUnicode = _testUnicode.replace("u'", "'") _testUnicode = _testUnicode.replace("u'", "'")
exec(_testUnicode) exec(_testUnicode)

View File

@ -37,6 +37,7 @@ from supybot.commands import *
import supybot.conf as conf import supybot.conf as conf
import supybot.irclib as irclib import supybot.irclib as irclib
import supybot.ircmsgs as ircmsgs import supybot.ircmsgs as ircmsgs
import supybot.minisix as minisix
import supybot.callbacks as callbacks import supybot.callbacks as callbacks
@ -88,7 +89,7 @@ class GeneralContextTestCase(CommandsTestCase):
finally: finally:
conf.supybot.protocols.irc.strictRfc.setValue(strict) conf.supybot.protocols.irc.strictRfc.setValue(strict)
if sys.version_info[0] < 3: if minisix.PY2:
def testSpecLong(self): def testSpecLong(self):
self.assertState(['long'], ['1'], [long(1)]) self.assertState(['long'], ['1'], [long(1)])
self.assertState(['long', 'long', 'long'], ['1', '2', '3'], self.assertState(['long', 'long', 'long'], ['1', '2', '3'],

View File

@ -29,6 +29,7 @@
from supybot.test import * from supybot.test import *
from supybot import log from supybot import log
import supybot.minisix as minisix
class FirewallTestCase(SupyTestCase): class FirewallTestCase(SupyTestCase):
def setUp(self): def setUp(self):
@ -46,7 +47,7 @@ class C(%s
pass pass
def foo(self): def foo(self):
raise self.MyException()""" % raise self.MyException()""" %
('metaclass=log.MetaFirewall):\n' if sys.version_info[0] >= 3 else ('metaclass=log.MetaFirewall):\n' if minisix.PY3 else
'object):\n __metaclass__ = log.MetaFirewall')) 'object):\n __metaclass__ = log.MetaFirewall'))
def testCFooDoesNotRaise(self): def testCFooDoesNotRaise(self):

View File

@ -35,6 +35,7 @@ import time
import pickle import pickle
import supybot.utils as utils import supybot.utils as utils
from supybot.utils.structures import * from supybot.utils.structures import *
import supybot.minisix as minisix
if sys.version_info[0] >= 0: if sys.version_info[0] >= 0:
xrange = range xrange = range
@ -130,7 +131,7 @@ class GenTest(SupyTestCase):
self.assertEqual(list(AL.items()), [(1, 2), (2, 3), (3, 4)]) self.assertEqual(list(AL.items()), [(1, 2), (2, 3), (3, 4)])
self.assertEqual(list(AL.items()), [(1, 2), (2, 3), (3, 4)]) self.assertEqual(list(AL.items()), [(1, 2), (2, 3), (3, 4)])
self.assertEqual(list(AL.keys()), [1, 2, 3]) self.assertEqual(list(AL.keys()), [1, 2, 3])
if sys.version_info[0] < 3: if minisix.PY2:
self.assertEqual(list(AL.keys()), [1, 2, 3]) self.assertEqual(list(AL.keys()), [1, 2, 3])
self.assertEqual(AL.values(), [2, 3, 4]) self.assertEqual(AL.values(), [2, 3, 4])
self.assertEqual(list(AL.values()), [2, 3, 4]) self.assertEqual(list(AL.values()), [2, 3, 4])