'):
- content = u'
' + content + u'
'
+ content = '
' + content + '
'
try:
from lxml import etree
except ImportError:
- self.disp(_(u"You need lxml to edit pretty XHTML"))
+ self.disp(_("You need lxml to edit pretty XHTML"))
else:
parser = etree.XMLParser(remove_blank_text=True)
root = etree.fromstring(content, parser)
- content = etree.tostring(root, encoding=unicode, pretty_print=True)
+ content = etree.tostring(root, encoding=str, pretty_print=True)
return content, mb_data, mb_data["id"]
@@ -599,11 +596,11 @@ class Edit(base.CommandBase, BlogPublishCommon, common.BaseEdit):
self.current_syntax
)
except Exception as e:
- if "NotFound" in unicode(
+ if "NotFound" in str(
e
): # FIXME: there is not good way to check bridge errors
self.parser.error(
- _(u"unknown syntax requested ({syntax})").format(
+ _("unknown syntax requested ({syntax})").format(
syntax=self.args.syntax
)
)
@@ -627,7 +624,7 @@ class Preview(base.CommandBase, common.BaseEdit):
def __init__(self, host):
base.CommandBase.__init__(
- self, host, "preview", use_verbose=True, help=_(u"preview a blog content")
+ self, host, "preview", use_verbose=True, help=_("preview a blog content")
)
common.BaseEdit.__init__(self, self.host, BLOG_TMP_DIR, use_metadata=True)
@@ -636,15 +633,14 @@ class Preview(base.CommandBase, common.BaseEdit):
"--inotify",
type=str,
choices=("auto", "true", "false"),
- default=u"auto",
- help=_(u"use inotify to handle preview"),
+ default="auto",
+ help=_("use inotify to handle preview"),
)
self.parser.add_argument(
"file",
- type=base.unicode_decoder,
nargs="?",
- default=u"current",
- help=_(u"path to the content file"),
+ default="current",
+ help=_("path to the content file"),
)
def showPreview(self):
@@ -660,7 +656,7 @@ class Preview(base.CommandBase, common.BaseEdit):
)
if not args:
self.disp(
- u'Couln\'t find command in "{name}", abording'.format(name=opt_name),
+ 'Couln\'t find command in "{name}", abording'.format(name=opt_name),
error=True,
)
self.host.quit(1)
@@ -683,11 +679,11 @@ class Preview(base.CommandBase, common.BaseEdit):
)
xhtml = (
- u''
- u'
'
- u""
- u"{}"
- u""
+ ''
+ '
'
+ ""
+ "{}"
+ ""
).format(content)
with open(self.preview_file_path, "wb") as f:
@@ -695,7 +691,7 @@ class Preview(base.CommandBase, common.BaseEdit):
def start(self):
import webbrowser
- import urllib
+ import urllib.request, urllib.parse, urllib.error
self.webbrowser, self.urllib = webbrowser, urllib
@@ -708,13 +704,13 @@ class Preview(base.CommandBase, common.BaseEdit):
if self.args.inotify == "auto":
inotify = None
self.disp(
- u"inotify module not found, deactivating feature. You can install"
- u" it with {install}".format(install=INOTIFY_INSTALL)
+ "inotify module not found, deactivating feature. You can install"
+ " it with {install}".format(install=INOTIFY_INSTALL)
)
else:
self.disp(
- u"inotify not found, can't activate the feature! Please install "
- u"it with {install}".format(install=INOTIFY_INSTALL),
+ "inotify not found, can't activate the feature! Please install "
+ "it with {install}".format(install=INOTIFY_INSTALL),
error=True,
)
self.host.quit(1)
@@ -724,7 +720,7 @@ class Preview(base.CommandBase, common.BaseEdit):
inotify.adapters._LOGGER.setLevel(40)
except AttributeError:
self.disp(
- u"Logger doesn't exists, inotify may have chanded", error=True
+ "Logger doesn't exists, inotify may have chanded", error=True
)
else:
inotify = None
@@ -768,8 +764,8 @@ class Preview(base.CommandBase, common.BaseEdit):
# XXX: we don't delete file automatically because browser need it
# (and webbrowser.open can return before it is read)
self.disp(
- u"temporary file created at {}\nthis file will NOT BE DELETED "
- u"AUTOMATICALLY, please delete it yourself when you have finished".format(
+ "temporary file created at {}\nthis file will NOT BE DELETED "
+ "AUTOMATICALLY, please delete it yourself when you have finished".format(
self.preview_file_path
)
)
@@ -793,10 +789,10 @@ class Preview(base.CommandBase, common.BaseEdit):
try:
for event in i.event_gen():
if event is not None:
- self.disp(u"Content updated", 1)
+ self.disp("Content updated", 1)
if {"IN_DELETE_SELF", "IN_MOVE_SELF"}.intersection(event[1]):
self.disp(
- u"{} event catched, changing the watch".format(
+ "{} event catched, changing the watch".format(
", ".join(event[1])
),
2,
@@ -813,7 +809,7 @@ class Preview(base.CommandBase, common.BaseEdit):
update_cb()
except InotifyError:
self.disp(
- u"Can't catch inotify events, as the file been deleted?", error=True
+ "Can't catch inotify events, as the file been deleted?", error=True
)
finally:
os.unlink(self.preview_file_path)
@@ -830,28 +826,27 @@ class Import(base.CommandAnswering):
"import",
use_pubsub=True,
use_progress=True,
- help=_(u"import an external blog"),
+ help=_("import an external blog"),
)
self.need_loop = True
def add_parser_options(self):
self.parser.add_argument(
"importer",
- type=base.unicode_decoder,
nargs="?",
- help=_(u"importer name, nothing to display importers list"),
+ help=_("importer name, nothing to display importers list"),
)
self.parser.add_argument(
- "--host", type=base.unicode_decoder, help=_(u"original blog host")
+ "--host", help=_("original blog host")
)
self.parser.add_argument(
"--no-images-upload",
action="store_true",
- help=_(u"do *NOT* upload images (default: do upload images)"),
+ help=_("do *NOT* upload images (default: do upload images)"),
)
self.parser.add_argument(
"--upload-ignore-host",
- help=_(u"do not upload images from this host (default: upload all images)"),
+ help=_("do not upload images from this host (default: upload all images)"),
)
self.parser.add_argument(
"--ignore-tls-errors",
@@ -864,52 +859,51 @@ class Import(base.CommandAnswering):
action="append",
nargs=2,
default=[],
- metavar=(u"NAME", u"VALUE"),
- help=_(u"importer specific options (see importer description)"),
+ metavar=("NAME", "VALUE"),
+ help=_("importer specific options (see importer description)"),
)
self.parser.add_argument(
"location",
- type=base.unicode_decoder,
nargs="?",
help=_(
- u"importer data location (see importer description), nothing to show "
- u"importer description"
+ "importer data location (see importer description), nothing to show "
+ "importer description"
),
)
def onProgressStarted(self, metadata):
- self.disp(_(u"Blog upload started"), 2)
+ self.disp(_("Blog upload started"), 2)
def onProgressFinished(self, metadata):
- self.disp(_(u"Blog uploaded successfully"), 2)
+ self.disp(_("Blog uploaded successfully"), 2)
redirections = {
k[len(URL_REDIRECT_PREFIX) :]: v
- for k, v in metadata.iteritems()
+ for k, v in metadata.items()
if k.startswith(URL_REDIRECT_PREFIX)
}
if redirections:
- conf = u"\n".join(
+ conf = "\n".join(
[
- u"url_redirections_dict = {}".format(
+ "url_redirections_dict = {}".format(
# we need to add ' ' before each new line
# and to double each '%' for ConfigParser
- u"\n ".join(
+ "\n ".join(
json.dumps(redirections, indent=1, separators=(",", ": "))
- .replace(u"%", u"%%")
- .split(u"\n")
+ .replace("%", "%%")
+ .split("\n")
)
),
]
)
self.disp(
_(
- u"\nTo redirect old URLs to new ones, put the following lines in your"
- u" sat.conf file, in [libervia] section:\n\n{conf}".format(conf=conf)
+ "\nTo redirect old URLs to new ones, put the following lines in your"
+ " sat.conf file, in [libervia] section:\n\n{conf}".format(conf=conf)
)
)
def onProgressError(self, error_msg):
- self.disp(_(u"Error while uploading blog: {}").format(error_msg), error=True)
+ self.disp(_("Error while uploading blog: {}").format(error_msg), error=True)
def error(self, failure):
self.disp(
@@ -924,14 +918,14 @@ class Import(base.CommandAnswering):
if getattr(self.args, name):
self.parser.error(
_(
- u"{name} argument can't be used without location argument"
+ "{name} argument can't be used without location argument"
).format(name=name)
)
if self.args.importer is None:
self.disp(
- u"\n".join(
+ "\n".join(
[
- u"{}: {}".format(name, desc)
+ "{}: {}".format(name, desc)
for name, desc in self.host.bridge.blogImportList()
]
)
@@ -942,14 +936,14 @@ class Import(base.CommandAnswering):
self.args.importer
)
except Exception as e:
- msg = [l for l in unicode(e).split("\n") if l][
+ msg = [l for l in str(e).split("\n") if l][
-1
] # we only keep the last line
self.disp(msg)
self.host.quit(1)
else:
self.disp(
- u"{name}: {short_desc}\n\n{long_desc}".format(
+ "{name}: {short_desc}\n\n{long_desc}".format(
name=self.args.importer,
short_desc=short_desc,
long_desc=long_desc,
@@ -967,8 +961,8 @@ class Import(base.CommandAnswering):
options["upload_images"] = C.BOOL_FALSE
if self.args.upload_ignore_host:
self.parser.error(
- u"upload-ignore-host option can't be used when no-images-upload "
- u"is set"
+ "upload-ignore-host option can't be used when no-images-upload "
+ "is set"
)
elif self.args.upload_ignore_host:
options["upload_ignore_host"] = self.args.upload_ignore_host
diff --git a/sat_frontends/jp/cmd_bookmarks.py b/sat_frontends/jp/cmd_bookmarks.py
index 278f3cf0..701c90be 100644
--- a/sat_frontends/jp/cmd_bookmarks.py
+++ b/sat_frontends/jp/cmd_bookmarks.py
@@ -17,7 +17,7 @@
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see
.
-import base
+from . import base
from sat.core.i18n import _
__commands__ = ["Bookmarks"]
@@ -33,7 +33,7 @@ class BookmarksCommon(base.CommandBase):
self.parser.add_argument('-t', '--type', type=str, choices=TYPES, default=TYPES[0], help=_("bookmarks type (default: %(default)s)"))
def _errback(self, failure):
- print (("Something went wrong: [%s]") % failure)
+ print((("Something went wrong: [%s]") % failure))
self.host.quit(1)
class BookmarksList(BookmarksCommon):
@@ -48,20 +48,20 @@ class BookmarksList(BookmarksCommon):
if not data[location]:
continue
loc_mess = []
- loc_mess.append(u"%s:" % location)
+ loc_mess.append("%s:" % location)
book_mess = []
- for book_link, book_data in data[location].items():
+ for book_link, book_data in list(data[location].items()):
name = book_data.get('name')
autojoin = book_data.get('autojoin', 'false') == 'true'
nick = book_data.get('nick')
- book_mess.append(u"\t%s[%s%s]%s" % ((name+' ') if name else '',
+ book_mess.append("\t%s[%s%s]%s" % ((name+' ') if name else '',
book_link,
- u' (%s)' % nick if nick else '',
- u' (*)' if autojoin else ''))
- loc_mess.append(u'\n'.join(book_mess))
- mess.append(u'\n'.join(loc_mess))
+ ' (%s)' % nick if nick else '',
+ ' (*)' if autojoin else ''))
+ loc_mess.append('\n'.join(book_mess))
+ mess.append('\n'.join(loc_mess))
- print u'\n\n'.join(mess)
+ print('\n\n'.join(mess))
class BookmarksRemove(BookmarksCommon):
@@ -72,7 +72,7 @@ class BookmarksRemove(BookmarksCommon):
def add_parser_options(self):
super(BookmarksRemove, self).add_parser_options()
- self.parser.add_argument('bookmark', type=base.unicode_decoder, help=_('jid (for muc bookmark) or url of to remove'))
+ self.parser.add_argument('bookmark', help=_('jid (for muc bookmark) or url of to remove'))
def start(self):
self.host.bridge.bookmarksRemove(self.args.type, self.args.bookmark, self.args.location, self.host.profile, callback = lambda: self.host.quit(), errback=self._errback)
@@ -86,16 +86,16 @@ class BookmarksAdd(BookmarksCommon):
def add_parser_options(self):
super(BookmarksAdd, self).add_parser_options(location_default='auto')
- self.parser.add_argument('bookmark', type=base.unicode_decoder, help=_('jid (for muc bookmark) or url of to remove'))
- self.parser.add_argument('-n', '--name', type=base.unicode_decoder, help=_("bookmark name"))
+ self.parser.add_argument('bookmark', help=_('jid (for muc bookmark) or url of to remove'))
+ self.parser.add_argument('-n', '--name', help=_("bookmark name"))
muc_group = self.parser.add_argument_group(_('MUC specific options'))
- muc_group.add_argument('-N', '--nick', type=base.unicode_decoder, help=_('nickname'))
+ muc_group.add_argument('-N', '--nick', help=_('nickname'))
muc_group.add_argument('-a', '--autojoin', action='store_true', help=_('join room on profile connection'))
def start(self):
if self.args.type == 'url' and (self.args.autojoin or self.args.nick is not None):
# XXX: Argparse doesn't seem to manage this case, any better way ?
- print _(u"You can't use --autojoin or --nick with --type url")
+ print(_("You can't use --autojoin or --nick with --type url"))
self.host.quit(1)
data = {}
if self.args.autojoin:
diff --git a/sat_frontends/jp/cmd_debug.py b/sat_frontends/jp/cmd_debug.py
index 4879fa3c..84684ac8 100644
--- a/sat_frontends/jp/cmd_debug.py
+++ b/sat_frontends/jp/cmd_debug.py
@@ -18,7 +18,7 @@
# along with this program. If not, see
.
-import base
+from . import base
from sat.core.i18n import _
from sat_frontends.jp.constants import Const as C
from sat.tools.common.ansi import ANSI as A
@@ -31,11 +31,11 @@ class BridgeCommon(object):
def evalArgs(self):
if self.args.arg:
try:
- return eval(u"[{}]".format(u",".join(self.args.arg)))
+ return eval("[{}]".format(",".join(self.args.arg)))
except SyntaxError as e:
self.disp(
- u"Can't evaluate arguments: {mess}\n{text}\n{offset}^".format(
- mess=e, text=e.text.decode("utf-8"), offset=u" " * (e.offset - 1)
+ "Can't evaluate arguments: {mess}\n{text}\n{offset}^".format(
+ mess=e, text=e.text, offset=" " * (e.offset - 1)
),
error=True,
)
@@ -46,26 +46,26 @@ class BridgeCommon(object):
class Method(base.CommandBase, BridgeCommon):
def __init__(self, host):
- base.CommandBase.__init__(self, host, "method", help=_(u"call a bridge method"))
+ base.CommandBase.__init__(self, host, "method", help=_("call a bridge method"))
BridgeCommon.__init__(self)
self.need_loop = True
def add_parser_options(self):
self.parser.add_argument(
- "method", type=str, help=_(u"name of the method to execute")
+ "method", type=str, help=_("name of the method to execute")
)
self.parser.add_argument(
- "arg", type=base.unicode_decoder, nargs="*", help=_(u"argument of the method")
+ "arg", nargs="*", help=_("argument of the method")
)
def method_cb(self, ret=None):
if ret is not None:
- self.disp(unicode(ret))
+ self.disp(str(ret))
self.host.quit()
def method_eb(self, failure):
self.disp(
- _(u"Error while executing {}: {}".format(self.args.method, failure)),
+ _("Error while executing {}: {}".format(self.args.method, failure)),
error=True,
)
self.host.quit(C.EXIT_ERROR)
@@ -85,22 +85,22 @@ class Method(base.CommandBase, BridgeCommon):
try:
method(*args, callback=self.method_cb, errback=self.method_eb)
except TypeError:
- self.method_eb(_(u"bad arguments"))
+ self.method_eb(_("bad arguments"))
class Signal(base.CommandBase, BridgeCommon):
def __init__(self, host):
base.CommandBase.__init__(
- self, host, "signal", help=_(u"send a fake signal from backend")
+ self, host, "signal", help=_("send a fake signal from backend")
)
BridgeCommon.__init__(self)
def add_parser_options(self):
self.parser.add_argument(
- "signal", type=str, help=_(u"name of the signal to send")
+ "signal", type=str, help=_("name of the signal to send")
)
self.parser.add_argument(
- "arg", type=base.unicode_decoder, nargs="*", help=_(u"argument of the signal")
+ "arg", nargs="*", help=_("argument of the signal")
)
def start(self):
@@ -138,7 +138,7 @@ class Monitor(base.CommandBase):
"--direction",
choices=("in", "out", "both"),
default="both",
- help=_(u"stream direction filter"),
+ help=_("stream direction filter"),
)
def printXML(self, direction, xml_data, profile):
@@ -155,7 +155,7 @@ class Monitor(base.CommandBase):
whiteping = False
if verbosity:
- profile_disp = u" ({})".format(profile) if verbosity > 1 else u""
+ profile_disp = " ({})".format(profile) if verbosity > 1 else ""
if direction == "IN":
self.disp(
A.color(
@@ -180,7 +180,7 @@ class Monitor(base.CommandBase):
# but importing lxml directly here is not clean
# should be wrapped in a custom Exception
self.disp(xml_data)
- self.disp(u"")
+ self.disp("")
def start(self):
self.host.bridge.register_signal("xmlLog", self.printXML, "plugin")
diff --git a/sat_frontends/jp/cmd_encryption.py b/sat_frontends/jp/cmd_encryption.py
index 08db2248..ab21b007 100644
--- a/sat_frontends/jp/cmd_encryption.py
+++ b/sat_frontends/jp/cmd_encryption.py
@@ -48,10 +48,10 @@ class EncryptionAlgorithms(base.CommandBase):
def default_output(self, plugins):
if not plugins:
- self.disp(_(u"No encryption plugin registered!"))
+ self.disp(_("No encryption plugin registered!"))
self.host.quit(C.EXIT_NOT_FOUND)
else:
- self.disp(_(u"Following encryption algorithms are available: {algos}").format(
+ self.disp(_("Following encryption algorithms are available: {algos}").format(
algos=', '.join([p['name'] for p in plugins])))
self.host.quit()
@@ -60,7 +60,7 @@ class EncryptionAlgorithms(base.CommandBase):
callback=self.encryptionPluginsGetCb,
errback=partial(
self.errback,
- msg=_(u"can't retrieve plugins: {}"),
+ msg=_("can't retrieve plugins: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -72,20 +72,20 @@ class EncryptionGet(base.CommandBase):
super(EncryptionGet, self).__init__(
host, "get",
use_output=C.OUTPUT_DICT,
- help=_(u"get encryption session data"))
+ help=_("get encryption session data"))
self.need_loop = True
def add_parser_options(self):
self.parser.add_argument(
- "jid", type=base.unicode_decoder,
- help=_(u"jid of the entity to check")
+ "jid",
+ help=_("jid of the entity to check")
)
def messageEncryptionGetCb(self, serialised):
session_data = data_format.deserialise(serialised)
if session_data is None:
self.disp(
- u"No encryption session found, the messages are sent in plain text.")
+ "No encryption session found, the messages are sent in plain text.")
self.host.quit(C.EXIT_NOT_FOUND)
self.output(session_data)
self.host.quit()
@@ -98,7 +98,7 @@ class EncryptionGet(base.CommandBase):
callback=self.messageEncryptionGetCb,
errback=partial(
self.errback,
- msg=_(u"can't get session: {}"),
+ msg=_("can't get session: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -109,23 +109,23 @@ class EncryptionStart(base.CommandBase):
def __init__(self, host):
super(EncryptionStart, self).__init__(
host, "start",
- help=_(u"start encrypted session with an entity"))
+ help=_("start encrypted session with an entity"))
self.need_loop = True
def add_parser_options(self):
self.parser.add_argument(
"--encrypt-noreplace",
action="store_true",
- help=_(u"don't replace encryption algorithm if an other one is already used"))
+ help=_("don't replace encryption algorithm if an other one is already used"))
algorithm = self.parser.add_mutually_exclusive_group()
algorithm.add_argument(
- "-n", "--name", help=_(u"algorithm name (DEFAULT: choose automatically)"))
+ "-n", "--name", help=_("algorithm name (DEFAULT: choose automatically)"))
algorithm.add_argument(
"-N", "--namespace",
- help=_(u"algorithm namespace (DEFAULT: choose automatically)"))
+ help=_("algorithm namespace (DEFAULT: choose automatically)"))
self.parser.add_argument(
- "jid", type=base.unicode_decoder,
- help=_(u"jid of the entity to stop encrypted session with")
+ "jid",
+ help=_("jid of the entity to stop encrypted session with")
)
def encryptionNamespaceGetCb(self, namespace):
@@ -136,7 +136,7 @@ class EncryptionStart(base.CommandBase):
self.profile,
callback=self.host.quit,
errback=partial(self.errback,
- msg=_(u"Can't start encryption session: {}"),
+ msg=_("Can't start encryption session: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
))
@@ -145,13 +145,13 @@ class EncryptionStart(base.CommandBase):
self.host.bridge.encryptionNamespaceGet(self.args.name,
callback=self.encryptionNamespaceGetCb,
errback=partial(self.errback,
- msg=_(u"Can't get encryption namespace: {}"),
+ msg=_("Can't get encryption namespace: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
))
elif self.args.namespace is not None:
self.encryptionNamespaceGetCb(self.args.namespace)
else:
- self.encryptionNamespaceGetCb(u"")
+ self.encryptionNamespaceGetCb("")
class EncryptionStop(base.CommandBase):
@@ -159,13 +159,13 @@ class EncryptionStop(base.CommandBase):
def __init__(self, host):
super(EncryptionStop, self).__init__(
host, "stop",
- help=_(u"stop encrypted session with an entity"))
+ help=_("stop encrypted session with an entity"))
self.need_loop = True
def add_parser_options(self):
self.parser.add_argument(
- "jid", type=base.unicode_decoder,
- help=_(u"jid of the entity to stop encrypted session with")
+ "jid",
+ help=_("jid of the entity to stop encrypted session with")
)
def start(self):
@@ -176,7 +176,7 @@ class EncryptionStop(base.CommandBase):
callback=self.host.quit,
errback=partial(
self.errback,
- msg=_(u"can't end encrypted session: {}"),
+ msg=_("can't end encrypted session: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -187,20 +187,20 @@ class TrustUI(base.CommandBase):
def __init__(self, host):
super(TrustUI, self).__init__(
host, "ui",
- help=_(u"get UI to manage trust"))
+ help=_("get UI to manage trust"))
self.need_loop = True
def add_parser_options(self):
self.parser.add_argument(
- "jid", type=base.unicode_decoder,
- help=_(u"jid of the entity to stop encrypted session with")
+ "jid",
+ help=_("jid of the entity to stop encrypted session with")
)
algorithm = self.parser.add_mutually_exclusive_group()
algorithm.add_argument(
- "-n", "--name", help=_(u"algorithm name (DEFAULT: current algorithm)"))
+ "-n", "--name", help=_("algorithm name (DEFAULT: current algorithm)"))
algorithm.add_argument(
"-N", "--namespace",
- help=_(u"algorithm namespace (DEFAULT: current algorithm)"))
+ help=_("algorithm namespace (DEFAULT: current algorithm)"))
def encryptionTrustUIGetCb(self, xmlui_raw):
xmlui = xmlui_manager.create(self.host, xmlui_raw)
@@ -215,7 +215,7 @@ class TrustUI(base.CommandBase):
callback=self.encryptionTrustUIGetCb,
errback=partial(
self.errback,
- msg=_(u"can't end encrypted session: {}"),
+ msg=_("can't end encrypted session: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -225,13 +225,13 @@ class TrustUI(base.CommandBase):
self.host.bridge.encryptionNamespaceGet(self.args.name,
callback=self.encryptionNamespaceGetCb,
errback=partial(self.errback,
- msg=_(u"Can't get encryption namespace: {}"),
+ msg=_("Can't get encryption namespace: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
))
elif self.args.namespace is not None:
self.encryptionNamespaceGetCb(self.args.namespace)
else:
- self.encryptionNamespaceGetCb(u"")
+ self.encryptionNamespaceGetCb("")
class EncryptionTrust(base.CommandBase):
@@ -239,7 +239,7 @@ class EncryptionTrust(base.CommandBase):
def __init__(self, host):
super(EncryptionTrust, self).__init__(
- host, "trust", use_profile=False, help=_(u"trust manangement")
+ host, "trust", use_profile=False, help=_("trust manangement")
)
@@ -249,5 +249,5 @@ class Encryption(base.CommandBase):
def __init__(self, host):
super(Encryption, self).__init__(
- host, "encryption", use_profile=False, help=_(u"encryption sessions handling")
+ host, "encryption", use_profile=False, help=_("encryption sessions handling")
)
diff --git a/sat_frontends/jp/cmd_event.py b/sat_frontends/jp/cmd_event.py
index 8e2728c2..7b6f4c4c 100644
--- a/sat_frontends/jp/cmd_event.py
+++ b/sat_frontends/jp/cmd_event.py
@@ -18,7 +18,7 @@
# along with this program. If not, see
.
-import base
+from . import base
from sat.core.i18n import _
from sat.tools.common.ansi import ANSI as A
from sat_frontends.jp.constants import Const as C
@@ -30,7 +30,7 @@ import time
__commands__ = ["Event"]
-OUTPUT_OPT_TABLE = u"table"
+OUTPUT_OPT_TABLE = "table"
# TODO: move date parsing to base, it may be useful for other commands
@@ -45,7 +45,7 @@ class Get(base.CommandBase):
use_pubsub=True,
pubsub_flags={C.SINGLE_ITEM},
use_verbose=True,
- help=_(u"get event data"),
+ help=_("get event data"),
)
self.need_loop = True
@@ -67,7 +67,7 @@ class Get(base.CommandBase):
callback=self.eventInviteeGetCb,
errback=partial(
self.errback,
- msg=_(u"can't get event data: {}"),
+ msg=_("can't get event data: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -78,22 +78,20 @@ class EventBase(object):
self.parser.add_argument(
"-i",
"--id",
- type=base.unicode_decoder,
- default=u"",
- help=_(u"ID of the PubSub Item"),
+ default="",
+ help=_("ID of the PubSub Item"),
)
self.parser.add_argument(
- "-d", "--date", type=unicode, help=_(u"date of the event")
+ "-d", "--date", type=str, help=_("date of the event")
)
self.parser.add_argument(
"-f",
"--field",
- type=base.unicode_decoder,
action="append",
nargs=2,
dest="fields",
- metavar=(u"KEY", u"VALUE"),
- help=_(u"configuration field to set"),
+ metavar=("KEY", "VALUE"),
+ help=_("configuration field to set"),
)
def parseFields(self):
@@ -106,10 +104,10 @@ class EventBase(object):
except ValueError:
try:
date_time = du_parser.parse(
- self.args.date, dayfirst=not (u"-" in self.args.date)
+ self.args.date, dayfirst=not ("-" in self.args.date)
)
except ValueError as e:
- self.parser.error(_(u"Can't parse date: {msg}").format(msg=e))
+ self.parser.error(_("Can't parse date: {msg}").format(msg=e))
if date_time.tzinfo is None:
date = calendar.timegm(date_time.timetuple())
else:
@@ -131,7 +129,7 @@ class Create(EventBase, base.CommandBase):
self.need_loop = True
def eventCreateCb(self, node):
- self.disp(_(u"Event created successfuly on node {node}").format(node=node))
+ self.disp(_("Event created successfuly on node {node}").format(node=node))
self.host.quit()
def start(self):
@@ -147,7 +145,7 @@ class Create(EventBase, base.CommandBase):
callback=self.eventCreateCb,
errback=partial(
self.errback,
- msg=_(u"can't create event: {}"),
+ msg=_("can't create event: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -178,7 +176,7 @@ class Modify(EventBase, base.CommandBase):
callback=self.host.quit,
errback=partial(
self.errback,
- msg=_(u"can't update event data: {}"),
+ msg=_("can't update event data: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -194,7 +192,7 @@ class InviteeGet(base.CommandBase):
use_pubsub=True,
pubsub_flags={C.NODE, C.ITEM, C.SINGLE_ITEM},
use_verbose=True,
- help=_(u"get event attendance"),
+ help=_("get event attendance"),
)
self.need_loop = True
@@ -213,7 +211,7 @@ class InviteeGet(base.CommandBase):
callback=self.eventInviteeGetCb,
errback=partial(
self.errback,
- msg=_(u"can't get event data: {}"),
+ msg=_("can't get event data: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -235,12 +233,11 @@ class InviteeSet(base.CommandBase):
self.parser.add_argument(
"-f",
"--field",
- type=base.unicode_decoder,
action="append",
nargs=2,
dest="fields",
- metavar=(u"KEY", u"VALUE"),
- help=_(u"configuration field to set"),
+ metavar=("KEY", "VALUE"),
+ help=_("configuration field to set"),
)
def start(self):
@@ -253,7 +250,7 @@ class InviteeSet(base.CommandBase):
callback=self.host.quit,
errback=partial(
self.errback,
- msg=_(u"can't set event data: {}"),
+ msg=_("can't set event data: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -271,7 +268,7 @@ class InviteesList(base.CommandBase):
use_pubsub=True,
pubsub_flags={C.NODE},
use_verbose=True,
- help=_(u"get event attendance"),
+ help=_("get event attendance"),
)
self.need_loop = True
@@ -280,26 +277,26 @@ class InviteesList(base.CommandBase):
"-m",
"--missing",
action="store_true",
- help=_(u"show missing people (invited but no R.S.V.P. so far)"),
+ help=_("show missing people (invited but no R.S.V.P. so far)"),
)
self.parser.add_argument(
"-R",
"--no-rsvp",
action="store_true",
- help=_(u"don't show people which gave R.S.V.P."),
+ help=_("don't show people which gave R.S.V.P."),
)
def _attend_filter(self, attend, row):
- if attend == u"yes":
+ if attend == "yes":
attend_color = C.A_SUCCESS
- elif attend == u"no":
+ elif attend == "no":
attend_color = C.A_FAILURE
else:
attend_color = A.FG_WHITE
return A.color(attend_color, attend)
def _guests_filter(self, guests):
- return u"(" + unicode(guests) + ")" if guests else u""
+ return "(" + str(guests) + ")" if guests else ""
def default_output(self, event_data):
data = []
@@ -309,13 +306,13 @@ class InviteesList(base.CommandBase):
attendees_missing = 0
guests = 0
guests_maybe = 0
- for jid_, jid_data in event_data.iteritems():
- jid_data[u"jid"] = jid_
+ for jid_, jid_data in event_data.items():
+ jid_data["jid"] = jid_
try:
guests_int = int(jid_data["guests"])
except (ValueError, KeyError):
pass
- attend = jid_data.get(u"attend", u"")
+ attend = jid_data.get("attend", "")
if attend == "yes":
attendees_yes += 1
guests += guests_int
@@ -324,10 +321,10 @@ class InviteesList(base.CommandBase):
guests_maybe += guests_int
elif attend == "no":
attendees_no += 1
- jid_data[u"guests"] = ""
+ jid_data["guests"] = ""
else:
attendees_missing += 1
- jid_data[u"guests"] = ""
+ jid_data["guests"] = ""
data.append(jid_data)
show_table = OUTPUT_OPT_TABLE in self.args.output_opts
@@ -335,60 +332,60 @@ class InviteesList(base.CommandBase):
table = common.Table.fromDict(
self.host,
data,
- (u"nick",)
- + ((u"jid",) if self.host.verbosity else ())
- + (u"attend", "guests"),
+ ("nick",)
+ + (("jid",) if self.host.verbosity else ())
+ + ("attend", "guests"),
headers=None,
filters={
- u"nick": A.color(C.A_HEADER, u"{}" if show_table else u"{} "),
- u"jid": u"{}" if show_table else u"{} ",
- u"attend": self._attend_filter,
- u"guests": u"{}" if show_table else self._guests_filter,
+ "nick": A.color(C.A_HEADER, "{}" if show_table else "{} "),
+ "jid": "{}" if show_table else "{} ",
+ "attend": self._attend_filter,
+ "guests": "{}" if show_table else self._guests_filter,
},
- defaults={u"nick": u"", u"attend": u"", u"guests": 1},
+ defaults={"nick": "", "attend": "", "guests": 1},
)
if show_table:
table.display()
else:
- table.display_blank(show_header=False, col_sep=u"")
+ table.display_blank(show_header=False, col_sep="")
if not self.args.no_rsvp:
- self.disp(u"")
+ self.disp("")
self.disp(
A.color(
C.A_SUBHEADER,
- _(u"Attendees: "),
+ _("Attendees: "),
A.RESET,
- unicode(len(data)),
- _(u" ("),
+ str(len(data)),
+ _(" ("),
C.A_SUCCESS,
- _(u"yes: "),
- unicode(attendees_yes),
+ _("yes: "),
+ str(attendees_yes),
A.FG_WHITE,
- _(u", maybe: "),
- unicode(attendees_maybe),
- u", ",
+ _(", maybe: "),
+ str(attendees_maybe),
+ ", ",
C.A_FAILURE,
- _(u"no: "),
- unicode(attendees_no),
+ _("no: "),
+ str(attendees_no),
A.RESET,
- u")",
+ ")",
)
)
self.disp(
- A.color(C.A_SUBHEADER, _(u"confirmed guests: "), A.RESET, unicode(guests))
+ A.color(C.A_SUBHEADER, _("confirmed guests: "), A.RESET, str(guests))
)
self.disp(
A.color(
C.A_SUBHEADER,
- _(u"unconfirmed guests: "),
+ _("unconfirmed guests: "),
A.RESET,
- unicode(guests_maybe),
+ str(guests_maybe),
)
)
self.disp(
A.color(
- C.A_SUBHEADER, _(u"total: "), A.RESET, unicode(guests + guests_maybe)
+ C.A_SUBHEADER, _("total: "), A.RESET, str(guests + guests_maybe)
)
)
if attendees_missing:
@@ -396,9 +393,9 @@ class InviteesList(base.CommandBase):
self.disp(
A.color(
C.A_SUBHEADER,
- _(u"missing people (no reply): "),
+ _("missing people (no reply): "),
A.RESET,
- unicode(attendees_missing),
+ str(attendees_missing),
)
)
@@ -420,9 +417,9 @@ class InviteesList(base.CommandBase):
prefilled_data.update(event_data)
# we get nicknames for everybody, make it easier for organisers
- for jid_, data in prefilled_data.iteritems():
+ for jid_, data in prefilled_data.items():
id_data = self.host.bridge.identityGet(jid_, self.profile)
- data[u"nick"] = id_data.get(u"nick", u"")
+ data["nick"] = id_data.get("nick", "")
self.output(prefilled_data)
self.host.quit()
@@ -435,7 +432,7 @@ class InviteesList(base.CommandBase):
callback=partial(self.eventInviteesListCb, prefilled_data=prefilled_data),
errback=partial(
self.errback,
- msg=_(u"can't get event data: {}"),
+ msg=_("can't get event data: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -446,14 +443,14 @@ class InviteesList(base.CommandBase):
# we only consider people with "publisher" affiliation as invited, creators are not, and members can just observe
prefilled = {
jid_: {}
- for jid_, affiliation in affiliations.iteritems()
- if affiliation in (u"publisher",)
+ for jid_, affiliation in affiliations.items()
+ if affiliation in ("publisher",)
}
self.getList(prefilled)
def start(self):
if self.args.no_rsvp and not self.args.missing:
- self.parser.error(_(u"you need to use --missing if you use --no-rsvp"))
+ self.parser.error(_("you need to use --missing if you use --no-rsvp"))
if self.args.missing:
self.host.bridge.psNodeAffiliationsGet(
self.args.service,
@@ -462,7 +459,7 @@ class InviteesList(base.CommandBase):
callback=self.psNodeAffiliationsGetCb,
errback=partial(
self.errback,
- msg=_(u"can't get event data: {}"),
+ msg=_("can't get event data: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -478,7 +475,7 @@ class InviteeInvite(base.CommandBase):
"invite",
use_pubsub=True,
pubsub_flags={C.NODE, C.SINGLE_ITEM},
- help=_(u"invite someone to the event through email"),
+ help=_("invite someone to the event through email"),
)
self.need_loop = True
@@ -487,49 +484,42 @@ class InviteeInvite(base.CommandBase):
"-e",
"--email",
action="append",
- type=base.unicode_decoder,
default=[],
help="email(s) to send the invitation to",
)
self.parser.add_argument(
"-N",
"--name",
- type=base.unicode_decoder,
default="",
help="name of the invitee",
)
self.parser.add_argument(
"-H",
"--host-name",
- type=base.unicode_decoder,
default="",
help="name of the host",
)
self.parser.add_argument(
"-l",
"--lang",
- type=base.unicode_decoder,
default="",
help="main language spoken by the invitee",
)
self.parser.add_argument(
"-U",
"--url-template",
- type=base.unicode_decoder,
default="",
help="template to construct the URL",
)
self.parser.add_argument(
"-S",
"--subject",
- type=base.unicode_decoder,
default="",
help="subject of the invitation email (default: generic subject)",
)
self.parser.add_argument(
"-b",
"--body",
- type=base.unicode_decoder,
default="",
help="body of the invitation email (default: generic body)",
)
@@ -554,7 +544,7 @@ class InviteeInvite(base.CommandBase):
callback=self.host.quit,
errback=partial(
self.errback,
- msg=_(u"can't create invitation: {}"),
+ msg=_("can't create invitation: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -565,7 +555,7 @@ class Invitee(base.CommandBase):
def __init__(self, host):
super(Invitee, self).__init__(
- host, "invitee", use_profile=False, help=_(u"manage invities")
+ host, "invitee", use_profile=False, help=_("manage invities")
)
diff --git a/sat_frontends/jp/cmd_file.py b/sat_frontends/jp/cmd_file.py
index 64225c6c..9441f5b5 100644
--- a/sat_frontends/jp/cmd_file.py
+++ b/sat_frontends/jp/cmd_file.py
@@ -18,7 +18,7 @@
# along with this program. If not, see
.
-import base
+from . import base
import sys
import os
import os.path
@@ -50,32 +50,29 @@ class Send(base.CommandBase):
def add_parser_options(self):
self.parser.add_argument(
- "files", type=str, nargs="+", metavar="file", help=_(u"a list of file")
+ "files", type=str, nargs="+", metavar="file", help=_("a list of file")
)
self.parser.add_argument(
- "jid", type=base.unicode_decoder, help=_(u"the destination jid")
+ "jid", help=_("the destination jid")
)
self.parser.add_argument(
- "-b", "--bz2", action="store_true", help=_(u"make a bzip2 tarball")
+ "-b", "--bz2", action="store_true", help=_("make a bzip2 tarball")
)
self.parser.add_argument(
"-d",
"--path",
- type=base.unicode_decoder,
- help=(u"path to the directory where the file must be stored"),
+ help=("path to the directory where the file must be stored"),
)
self.parser.add_argument(
"-N",
"--namespace",
- type=base.unicode_decoder,
- help=(u"namespace of the file"),
+ help=("namespace of the file"),
)
self.parser.add_argument(
"-n",
"--name",
- type=base.unicode_decoder,
- default=u"",
- help=(u"name to use (DEFAULT: use source file name)"),
+ default="",
+ help=("name to use (DEFAULT: use source file name)"),
)
def start(self):
@@ -83,16 +80,16 @@ class Send(base.CommandBase):
self.send_files()
def onProgressStarted(self, metadata):
- self.disp(_(u"File copy started"), 2)
+ self.disp(_("File copy started"), 2)
def onProgressFinished(self, metadata):
- self.disp(_(u"File sent successfully"), 2)
+ self.disp(_("File sent successfully"), 2)
def onProgressError(self, error_msg):
if error_msg == C.PROGRESS_ERROR_DECLINED:
- self.disp(_(u"The file has been refused by your contact"))
+ self.disp(_("The file has been refused by your contact"))
else:
- self.disp(_(u"Error while sending file: {}").format(error_msg), error=True)
+ self.disp(_("Error while sending file: {}").format(error_msg), error=True)
def gotId(self, data, file_):
"""Called when a progress id has been received
@@ -101,13 +98,13 @@ class Send(base.CommandBase):
@param file_(str): file path
"""
# FIXME: this show progress only for last progress_id
- self.disp(_(u"File request sent to {jid}".format(jid=self.full_dest_jid)), 1)
+ self.disp(_("File request sent to {jid}".format(jid=self.full_dest_jid)), 1)
try:
self.progress_id = data["progress"]
except KeyError:
# TODO: if 'xmlui' key is present, manage xmlui message display
self.disp(
- _(u"Can't send file to {jid}".format(jid=self.full_dest_jid)), error=True
+ _("Can't send file to {jid}".format(jid=self.full_dest_jid)), error=True
)
self.host.quit(2)
@@ -121,12 +118,12 @@ class Send(base.CommandBase):
def send_files(self):
for file_ in self.args.files:
if not os.path.exists(file_):
- self.disp(_(u"file [{}] doesn't exist !").format(file_), error=True)
+ self.disp(_("file [{}] doesn't exist !").format(file_), error=True)
self.host.quit(1)
if not self.args.bz2 and os.path.isdir(file_):
self.disp(
_(
- u"[{}] is a dir ! Please send files inside or use compression"
+ "[{}] is a dir ! Please send files inside or use compression"
).format(file_)
)
self.host.quit(1)
@@ -134,26 +131,26 @@ class Send(base.CommandBase):
self.full_dest_jid = self.host.get_full_jid(self.args.jid)
extra = {}
if self.args.path:
- extra[u"path"] = self.args.path
+ extra["path"] = self.args.path
if self.args.namespace:
- extra[u"namespace"] = self.args.namespace
+ extra["namespace"] = self.args.namespace
if self.args.bz2:
with tempfile.NamedTemporaryFile("wb", delete=False) as buf:
self.host.addOnQuitCallback(os.unlink, buf.name)
- self.disp(_(u"bz2 is an experimental option, use with caution"))
+ self.disp(_("bz2 is an experimental option, use with caution"))
# FIXME: check free space
- self.disp(_(u"Starting compression, please wait..."))
+ self.disp(_("Starting compression, please wait..."))
sys.stdout.flush()
bz2 = tarfile.open(mode="w:bz2", fileobj=buf)
- archive_name = u"{}.tar.bz2".format(
- os.path.basename(self.args.files[0]) or u"compressed_files"
+ archive_name = "{}.tar.bz2".format(
+ os.path.basename(self.args.files[0]) or "compressed_files"
)
for file_ in self.args.files:
- self.disp(_(u"Adding {}").format(file_), 1)
+ self.disp(_("Adding {}").format(file_), 1)
bz2.add(file_)
bz2.close()
- self.disp(_(u"Done !"), 1)
+ self.disp(_("Done !"), 1)
self.host.bridge.fileSend(
self.full_dest_jid,
@@ -193,71 +190,65 @@ class Request(base.CommandBase):
@property
def filename(self):
- return self.args.name or self.args.hash or u"output"
+ return self.args.name or self.args.hash or "output"
def add_parser_options(self):
self.parser.add_argument(
- "jid", type=base.unicode_decoder, help=_(u"the destination jid")
+ "jid", help=_("the destination jid")
)
self.parser.add_argument(
"-D",
"--dest",
- type=base.unicode_decoder,
help=_(
- u"destination path where the file will be saved (default: [current_dir]/[name|hash])"
+ "destination path where the file will be saved (default: [current_dir]/[name|hash])"
),
)
self.parser.add_argument(
"-n",
"--name",
- type=base.unicode_decoder,
- default=u"",
- help=_(u"name of the file"),
+ default="",
+ help=_("name of the file"),
)
self.parser.add_argument(
"-H",
"--hash",
- type=base.unicode_decoder,
- default=u"",
- help=_(u"hash of the file"),
+ default="",
+ help=_("hash of the file"),
)
self.parser.add_argument(
"-a",
"--hash-algo",
- type=base.unicode_decoder,
- default=u"sha-256",
- help=_(u"hash algorithm use for --hash (default: sha-256)"),
+ default="sha-256",
+ help=_("hash algorithm use for --hash (default: sha-256)"),
)
self.parser.add_argument(
"-d",
"--path",
- type=base.unicode_decoder,
- help=(u"path to the directory containing the file"),
+ help=("path to the directory containing the file"),
)
self.parser.add_argument(
"-N",
"--namespace",
- type=base.unicode_decoder,
- help=(u"namespace of the file"),
+ help=("namespace of the file"),
)
self.parser.add_argument(
"-f",
"--force",
action="store_true",
- help=_(u"overwrite existing file without confirmation"),
+ help=_("overwrite existing file without confirmation"),
)
def onProgressStarted(self, metadata):
- self.disp(_(u"File copy started"), 2)
+ self.disp(_("File copy started"), 2)
def onProgressFinished(self, metadata):
- self.disp(_(u"File received successfully"), 2)
+ self.disp(_("File received successfully"), 2)
def onProgressError(self, error_msg):
if error_msg == C.PROGRESS_ERROR_DECLINED:
- self.disp(_(u"The file request has been refused"))
+ self.disp(_("The file request has been refused"))
else:
- self.disp(_(u"Error while requesting file: {}").format(error_msg), error=True)
+ self.disp(_("Error while requesting file: {}").format(error_msg), error=True)
def gotId(self, progress_id):
"""Called when a progress id has been received
@@ -275,7 +266,7 @@ class Request(base.CommandBase):
def start(self):
if not self.args.name and not self.args.hash:
- self.parser.error(_(u"at least one of --name or --hash must be provided"))
+ self.parser.error(_("at least one of --name or --hash must be provided"))
# extra = dict(self.args.extra)
if self.args.dest:
path = os.path.abspath(os.path.expanduser(self.args.dest))
@@ -285,32 +276,32 @@ class Request(base.CommandBase):
path = os.path.abspath(self.filename)
if os.path.exists(path) and not self.args.force:
- message = _(u"File {path} already exists! Do you want to overwrite?").format(
+ message = _("File {path} already exists! Do you want to overwrite?").format(
path=path
)
- confirm = raw_input(u"{} (y/N) ".format(message).encode("utf-8"))
- if confirm not in (u"y", u"Y"):
- self.disp(_(u"file request cancelled"))
+ confirm = input("{} (y/N) ".format(message).encode("utf-8"))
+ if confirm not in ("y", "Y"):
+ self.disp(_("file request cancelled"))
self.host.quit(2)
self.full_dest_jid = self.host.get_full_jid(self.args.jid)
extra = {}
if self.args.path:
- extra[u"path"] = self.args.path
+ extra["path"] = self.args.path
if self.args.namespace:
- extra[u"namespace"] = self.args.namespace
+ extra["namespace"] = self.args.namespace
self.host.bridge.fileJingleRequest(
self.full_dest_jid,
path,
self.args.name,
self.args.hash,
- self.args.hash_algo if self.args.hash else u"",
+ self.args.hash_algo if self.args.hash else "",
extra,
self.profile,
callback=self.gotId,
errback=partial(
self.errback,
- msg=_(u"can't request file: {}"),
+ msg=_("can't request file: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -332,25 +323,25 @@ class Receive(base.CommandAnswering):
}
def onProgressStarted(self, metadata):
- self.disp(_(u"File copy started"), 2)
+ self.disp(_("File copy started"), 2)
def onProgressFinished(self, metadata):
- self.disp(_(u"File received successfully"), 2)
+ self.disp(_("File received successfully"), 2)
if metadata.get("hash_verified", False):
try:
self.disp(
- _(u"hash checked: {algo}:{checksum}").format(
+ _("hash checked: {algo}:{checksum}").format(
algo=metadata["hash_algo"], checksum=metadata["hash"]
),
1,
)
except KeyError:
- self.disp(_(u"hash is checked but hash value is missing", 1), error=True)
+ self.disp(_("hash is checked but hash value is missing", 1), error=True)
else:
- self.disp(_(u"hash can't be verified"), 1)
+ self.disp(_("hash can't be verified"), 1)
def onProgressError(self, error_msg):
- self.disp(_(u"Error while receiving file: {}").format(error_msg), error=True)
+ self.disp(_("Error while receiving file: {}").format(error_msg), error=True)
def getXmluiId(self, action_data):
# FIXME: we temporarily use ElementTree, but a real XMLUI managing module
@@ -359,12 +350,12 @@ class Receive(base.CommandAnswering):
try:
xml_ui = action_data["xmlui"]
except KeyError:
- self.disp(_(u"Action has no XMLUI"), 1)
+ self.disp(_("Action has no XMLUI"), 1)
else:
ui = ET.fromstring(xml_ui.encode("utf-8"))
xmlui_id = ui.get("submit")
if not xmlui_id:
- self.disp(_(u"Invalid XMLUI received"), error=True)
+ self.disp(_("Invalid XMLUI received"), error=True)
return xmlui_id
def onFileAction(self, action_data, action_id, security_limit, profile):
@@ -374,17 +365,17 @@ class Receive(base.CommandAnswering):
try:
from_jid = jid.JID(action_data["meta_from_jid"])
except KeyError:
- self.disp(_(u"Ignoring action without from_jid data"), 1)
+ self.disp(_("Ignoring action without from_jid data"), 1)
return
try:
progress_id = action_data["meta_progress_id"]
except KeyError:
- self.disp(_(u"ignoring action without progress id"), 1)
+ self.disp(_("ignoring action without progress id"), 1)
return
if not self.bare_jids or from_jid.bare in self.bare_jids:
if self._overwrite_refused:
- self.disp(_(u"File refused because overwrite is needed"), error=True)
+ self.disp(_("File refused because overwrite is needed"), error=True)
self.host.bridge.launchAction(
xmlui_id, {"cancelled": C.BOOL_TRUE}, profile_key=profile
)
@@ -400,15 +391,15 @@ class Receive(base.CommandAnswering):
try:
progress_id = action_data["meta_progress_id"]
except KeyError:
- self.disp(_(u"ignoring action without progress id"), 1)
+ self.disp(_("ignoring action without progress id"), 1)
return
- self.disp(_(u"Overwriting needed"), 1)
+ self.disp(_("Overwriting needed"), 1)
if progress_id == self.progress_id:
if self.args.force:
- self.disp(_(u"Overwrite accepted"), 2)
+ self.disp(_("Overwrite accepted"), 2)
else:
- self.disp(_(u"Refused to overwrite"), 2)
+ self.disp(_("Refused to overwrite"), 2)
self._overwrite_refused = True
xmlui_data = {"answer": C.boolConst(self.args.force)}
@@ -417,40 +408,39 @@ class Receive(base.CommandAnswering):
def add_parser_options(self):
self.parser.add_argument(
"jids",
- type=base.unicode_decoder,
nargs="*",
- help=_(u"jids accepted (accept everything if none is specified)"),
+ help=_("jids accepted (accept everything if none is specified)"),
)
self.parser.add_argument(
"-m",
"--multiple",
action="store_true",
- help=_(u"accept multiple files (you'll have to stop manually)"),
+ help=_("accept multiple files (you'll have to stop manually)"),
)
self.parser.add_argument(
"-f",
"--force",
action="store_true",
help=_(
- u"force overwritting of existing files (/!\\ name is choosed by sender)"
+ "force overwritting of existing files (/!\\ name is choosed by sender)"
),
)
self.parser.add_argument(
"--path",
default=".",
metavar="DIR",
- help=_(u"destination path (default: working directory)"),
+ help=_("destination path (default: working directory)"),
)
def start(self):
self.bare_jids = [jid.JID(jid_).bare for jid_ in self.args.jids]
self.path = os.path.abspath(self.args.path)
if not os.path.isdir(self.path):
- self.disp(_(u"Given path is not a directory !", error=True))
+ self.disp(_("Given path is not a directory !", error=True))
self.host.quit(2)
if self.args.multiple:
self.host.quit_on_progress_end = False
- self.disp(_(u"waiting for incoming file request"), 2)
+ self.disp(_("waiting for incoming file request"), 2)
class Upload(base.CommandBase):
@@ -464,7 +454,6 @@ class Upload(base.CommandBase):
self.parser.add_argument("file", type=str, help=_("file to upload"))
self.parser.add_argument(
"jid",
- type=base.unicode_decoder,
nargs="?",
help=_("jid of upload component (nothing to autodetect)"),
)
@@ -475,21 +464,21 @@ class Upload(base.CommandBase):
)
def onProgressStarted(self, metadata):
- self.disp(_(u"File upload started"), 2)
+ self.disp(_("File upload started"), 2)
def onProgressFinished(self, metadata):
- self.disp(_(u"File uploaded successfully"), 2)
+ self.disp(_("File uploaded successfully"), 2)
try:
url = metadata["url"]
except KeyError:
- self.disp(u"download URL not found in metadata")
+ self.disp("download URL not found in metadata")
else:
- self.disp(_(u"URL to retrieve the file:"), 1)
+ self.disp(_("URL to retrieve the file:"), 1)
# XXX: url is display alone on a line to make parsing easier
self.disp(url)
def onProgressError(self, error_msg):
- self.disp(_(u"Error while uploading file: {}").format(error_msg), error=True)
+ self.disp(_("Error while uploading file: {}").format(error_msg), error=True)
def gotId(self, data, file_):
"""Called when a progress id has been received
@@ -501,7 +490,7 @@ class Upload(base.CommandBase):
self.progress_id = data["progress"]
except KeyError:
# TODO: if 'xmlui' key is present, manage xmlui message display
- self.disp(_(u"Can't upload file"), error=True)
+ self.disp(_("Can't upload file"), error=True)
self.host.quit(2)
def error(self, failure):
@@ -514,10 +503,10 @@ class Upload(base.CommandBase):
def start(self):
file_ = self.args.file
if not os.path.exists(file_):
- self.disp(_(u"file [{}] doesn't exist !").format(file_), error=True)
+ self.disp(_("file [{}] doesn't exist !").format(file_), error=True)
self.host.quit(1)
if os.path.isdir(file_):
- self.disp(_(u"[{}] is a dir! Can't upload a dir").format(file_))
+ self.disp(_("[{}] is a dir! Can't upload a dir").format(file_))
self.host.quit(1)
self.full_dest_jid = (
@@ -547,7 +536,7 @@ class ShareList(base.CommandBase):
"list",
use_output=C.OUTPUT_LIST_DICT,
extra_outputs=extra_outputs,
- help=_(u"retrieve files shared by an entity"),
+ help=_("retrieve files shared by an entity"),
use_verbose=True,
)
self.need_loop = True
@@ -556,12 +545,11 @@ class ShareList(base.CommandBase):
self.parser.add_argument(
"-d",
"--path",
- default=u"",
- help=_(u"path to the directory containing the files"),
+ default="",
+ help=_("path to the directory containing the files"),
)
self.parser.add_argument(
"jid",
- type=base.unicode_decoder,
nargs="?",
default="",
help=_("jid of sharing entity (nothing to check our own jid)"),
@@ -569,9 +557,9 @@ class ShareList(base.CommandBase):
def file_gen(self, files_data):
for file_data in files_data:
- yield file_data[u"name"]
- yield file_data.get(u"size", "")
- yield file_data.get(u"hash", "")
+ yield file_data["name"]
+ yield file_data.get("size", "")
+ yield file_data.get("hash", "")
def _name_filter(self, name, row):
if row.type == C.FILE_TYPE_DIRECTORY:
@@ -579,39 +567,39 @@ class ShareList(base.CommandBase):
elif row.type == C.FILE_TYPE_FILE:
return A.color(C.A_FILE, name)
else:
- self.disp(_(u"unknown file type: {type}").format(type=row.type), error=True)
+ self.disp(_("unknown file type: {type}").format(type=row.type), error=True)
return name
def _size_filter(self, size, row):
if not size:
- return u""
+ return ""
size = int(size)
# cf. https://stackoverflow.com/a/1094933 (thanks)
- suffix = u"o"
- for unit in [u"", u"Ki", u"Mi", u"Gi", u"Ti", u"Pi", u"Ei", u"Zi"]:
+ suffix = "o"
+ for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]:
if abs(size) < 1024.0:
- return A.color(A.BOLD, u"{:.2f}".format(size), unit, suffix)
+ return A.color(A.BOLD, "{:.2f}".format(size), unit, suffix)
size /= 1024.0
- return A.color(A.BOLD, u"{:.2f}".format(size), u"Yi", suffix)
+ return A.color(A.BOLD, "{:.2f}".format(size), "Yi", suffix)
def default_output(self, files_data):
"""display files a way similar to ls"""
files_data.sort(key=lambda d: d["name"].lower())
show_header = False
if self.verbosity == 0:
- headers = (u"name", u"type")
+ headers = ("name", "type")
elif self.verbosity == 1:
- headers = (u"name", u"type", u"size")
+ headers = ("name", "type", "size")
elif self.verbosity > 1:
show_header = True
- headers = (u"name", u"type", u"size", u"hash")
+ headers = ("name", "type", "size", "hash")
table = common.Table.fromDict(
self.host,
files_data,
headers,
- filters={u"name": self._name_filter, u"size": self._size_filter},
- defaults={u"size": u"", u"hash": u""},
+ filters={"name": self._name_filter, "size": self._size_filter},
+ defaults={"size": "", "hash": ""},
)
table.display_blank(show_header=show_header, hide_cols=["type"])
@@ -628,7 +616,7 @@ class ShareList(base.CommandBase):
callback=self._FISListCb,
errback=partial(
self.errback,
- msg=_(u"can't retrieve shared files: {}"),
+ msg=_("can't retrieve shared files: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -637,7 +625,7 @@ class ShareList(base.CommandBase):
class SharePath(base.CommandBase):
def __init__(self, host):
super(SharePath, self).__init__(
- host, "path", help=_(u"share a file or directory"), use_verbose=True
+ host, "path", help=_("share a file or directory"), use_verbose=True
)
self.need_loop = True
@@ -645,47 +633,44 @@ class SharePath(base.CommandBase):
self.parser.add_argument(
"-n",
"--name",
- type=base.unicode_decoder,
- default=u"",
- help=_(u"virtual name to use (default: use directory/file name)"),
+ default="",
+ help=_("virtual name to use (default: use directory/file name)"),
)
perm_group = self.parser.add_mutually_exclusive_group()
perm_group.add_argument(
"-j",
"--jid",
- type=base.unicode_decoder,
action="append",
dest="jids",
default=[],
- help=_(u"jid of contacts allowed to retrieve the files"),
+ help=_("jid of contacts allowed to retrieve the files"),
)
perm_group.add_argument(
"--public",
action="store_true",
help=_(
- u"share publicly the file(s) (/!\\ *everybody* will be able to access them)"
+ "share publicly the file(s) (/!\\ *everybody* will be able to access them)"
),
)
self.parser.add_argument(
"path",
- type=base.unicode_decoder,
- help=_(u"path to a file or directory to share"),
+ help=_("path to a file or directory to share"),
)
def _FISSharePathCb(self, name):
self.disp(
- _(u'{path} shared under the name "{name}"').format(path=self.path, name=name)
+ _('{path} shared under the name "{name}"').format(path=self.path, name=name)
)
self.host.quit()
def start(self):
self.path = os.path.abspath(self.args.path)
if self.args.public:
- access = {u"read": {u"type": u"public"}}
+ access = {"read": {"type": "public"}}
else:
jids = self.args.jids
if jids:
- access = {u"read": {u"type": "whitelist", u"jids": jids}}
+ access = {"read": {"type": "whitelist", "jids": jids}}
else:
access = {}
self.host.bridge.FISSharePath(
@@ -696,7 +681,7 @@ class SharePath(base.CommandBase):
callback=self._FISSharePathCb,
errback=partial(
self.errback,
- msg=_(u"can't share path: {}"),
+ msg=_("can't share path: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -705,7 +690,7 @@ class SharePath(base.CommandBase):
class ShareInvite(base.CommandBase):
def __init__(self, host):
super(ShareInvite, self).__init__(
- host, "invite", help=_(u"send invitation for a shared repository")
+ host, "invite", help=_("send invitation for a shared repository")
)
self.need_loop = True
@@ -713,61 +698,55 @@ class ShareInvite(base.CommandBase):
self.parser.add_argument(
"-n",
"--name",
- type=base.unicode_decoder,
- default=u"",
- help=_(u"name of the repository"),
+ default="",
+ help=_("name of the repository"),
)
self.parser.add_argument(
"-N",
"--namespace",
- type=base.unicode_decoder,
- default=u"",
- help=_(u"namespace of the repository"),
+ default="",
+ help=_("namespace of the repository"),
)
self.parser.add_argument(
"-P",
"--path",
- type=base.unicode_decoder,
- help=_(u"path to the repository"),
+ help=_("path to the repository"),
)
self.parser.add_argument(
"-t",
"--type",
- choices=[u"files", u"photos"],
- default=u"files",
- help=_(u"type of the repository"),
+ choices=["files", "photos"],
+ default="files",
+ help=_("type of the repository"),
)
self.parser.add_argument(
"-T",
"--thumbnail",
- type=base.unicode_decoder,
- help=_(u"https URL of a image to use as thumbnail"),
+ help=_("https URL of a image to use as thumbnail"),
)
self.parser.add_argument(
"service",
- type=base.unicode_decoder,
- help=_(u"jid of the file sharing service hosting the repository"),
+ help=_("jid of the file sharing service hosting the repository"),
)
self.parser.add_argument(
"jid",
- type=base.unicode_decoder,
- help=_(u"jid of the person to invite"),
+ help=_("jid of the person to invite"),
)
def _FISInviteCb(self):
self.disp(
- _(u'invitation sent to {entity}').format(entity=self.args.jid)
+ _('invitation sent to {entity}').format(entity=self.args.jid)
)
self.host.quit()
def start(self):
- self.path = os.path.normpath(self.args.path) if self.args.path else u""
+ self.path = os.path.normpath(self.args.path) if self.args.path else ""
extra = {}
if self.args.thumbnail is not None:
- if not self.args.thumbnail.startswith(u'http'):
- self.parser.error(_(u"only http(s) links are allowed with --thumbnail"))
+ if not self.args.thumbnail.startswith('http'):
+ self.parser.error(_("only http(s) links are allowed with --thumbnail"))
else:
- extra[u'thumb_url'] = self.args.thumbnail
+ extra['thumb_url'] = self.args.thumbnail
self.host.bridge.FISInvite(
self.args.jid,
self.args.service,
@@ -780,7 +759,7 @@ class ShareInvite(base.CommandBase):
callback=self._FISInviteCb,
errback=partial(
self.errback,
- msg=_(u"can't send invitation: {}"),
+ msg=_("can't send invitation: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -791,7 +770,7 @@ class Share(base.CommandBase):
def __init__(self, host):
super(Share, self).__init__(
- host, "share", use_profile=False, help=_(u"files sharing management")
+ host, "share", use_profile=False, help=_("files sharing management")
)
@@ -800,5 +779,5 @@ class File(base.CommandBase):
def __init__(self, host):
super(File, self).__init__(
- host, "file", use_profile=False, help=_(u"files sending/receiving/management")
+ host, "file", use_profile=False, help=_("files sending/receiving/management")
)
diff --git a/sat_frontends/jp/cmd_forums.py b/sat_frontends/jp/cmd_forums.py
index ea477962..02fc806b 100644
--- a/sat_frontends/jp/cmd_forums.py
+++ b/sat_frontends/jp/cmd_forums.py
@@ -18,7 +18,7 @@
# along with this program. If not, see
.
-import base
+from . import base
from sat.core.i18n import _
from sat_frontends.jp.constants import Const as C
from sat_frontends.jp import common
@@ -29,7 +29,7 @@ import json
__commands__ = ["Forums"]
-FORUMS_TMP_DIR = u"forums"
+FORUMS_TMP_DIR = "forums"
class Edit(base.CommandBase, common.BaseEdit):
@@ -43,7 +43,7 @@ class Edit(base.CommandBase, common.BaseEdit):
use_pubsub=True,
use_draft=True,
use_verbose=True,
- help=_(u"edit forums"),
+ help=_("edit forums"),
)
common.BaseEdit.__init__(self, self.host, FORUMS_TMP_DIR)
self.need_loop = True
@@ -52,17 +52,16 @@ class Edit(base.CommandBase, common.BaseEdit):
self.parser.add_argument(
"-k",
"--key",
- type=base.unicode_decoder,
- default=u"",
- help=_(u"forum key (DEFAULT: default forums)"),
+ default="",
+ help=_("forum key (DEFAULT: default forums)"),
)
def getTmpSuff(self):
"""return suffix used for content file"""
- return u"json"
+ return "json"
def forumsSetCb(self):
- self.disp(_(u"forums have been edited"), 1)
+ self.disp(_("forums have been edited"), 1)
self.host.quit()
def publish(self, forums_raw):
@@ -75,7 +74,7 @@ class Edit(base.CommandBase, common.BaseEdit):
callback=self.forumsSetCb,
errback=partial(
self.errback,
- msg=_(u"can't set forums: {}"),
+ msg=_("can't set forums: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -94,12 +93,12 @@ class Edit(base.CommandBase, common.BaseEdit):
def forumsGetEb(self, failure_):
# FIXME: error handling with bridge is broken, need to be properly fixed
- if failure_.condition == u"item-not-found":
- self.forumsGetCb(u"")
+ if failure_.condition == "item-not-found":
+ self.forumsGetCb("")
else:
self.errback(
failure_,
- msg=_(u"can't get forums structure: {}"),
+ msg=_("can't get forums structure: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
)
@@ -125,7 +124,7 @@ class Get(base.CommandBase):
extra_outputs=extra_outputs,
use_pubsub=True,
use_verbose=True,
- help=_(u"get forums structure"),
+ help=_("get forums structure"),
)
self.need_loop = True
@@ -133,9 +132,8 @@ class Get(base.CommandBase):
self.parser.add_argument(
"-k",
"--key",
- type=base.unicode_decoder,
- default=u"",
- help=_(u"forum key (DEFAULT: default forums)"),
+ default="",
+ help=_("forum key (DEFAULT: default forums)"),
)
def default_output(self, forums, level=0):
@@ -143,33 +141,33 @@ class Get(base.CommandBase):
keys = list(forum.keys())
keys.sort()
try:
- keys.remove(u"title")
+ keys.remove("title")
except ValueError:
pass
else:
- keys.insert(0, u"title")
+ keys.insert(0, "title")
try:
- keys.remove(u"sub-forums")
+ keys.remove("sub-forums")
except ValueError:
pass
else:
- keys.append(u"sub-forums")
+ keys.append("sub-forums")
for key in keys:
value = forum[key]
if key == "sub-forums":
self.default_output(value, level + 1)
else:
- if self.host.verbosity < 1 and key != u"title":
+ if self.host.verbosity < 1 and key != "title":
continue
head_color = C.A_LEVEL_COLORS[level % len(C.A_LEVEL_COLORS)]
self.disp(
- A.color(level * 4 * u" ", head_color, key, A.RESET, u": ", value)
+ A.color(level * 4 * " ", head_color, key, A.RESET, ": ", value)
)
def forumsGetCb(self, forums_raw):
if not forums_raw:
- self.disp(_(u"no schema found"), 1)
+ self.disp(_("no schema found"), 1)
self.host.quit(1)
forums = json.loads(forums_raw)
self.output(forums)
@@ -184,7 +182,7 @@ class Get(base.CommandBase):
callback=self.forumsGetCb,
errback=partial(
self.errback,
- msg=_(u"can't get forums: {}"),
+ msg=_("can't get forums: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -195,5 +193,5 @@ class Forums(base.CommandBase):
def __init__(self, host):
super(Forums, self).__init__(
- host, "forums", use_profile=False, help=_(u"Forums structure edition")
+ host, "forums", use_profile=False, help=_("Forums structure edition")
)
diff --git a/sat_frontends/jp/cmd_identity.py b/sat_frontends/jp/cmd_identity.py
index 5bd59f48..f624c78d 100644
--- a/sat_frontends/jp/cmd_identity.py
+++ b/sat_frontends/jp/cmd_identity.py
@@ -18,7 +18,7 @@
# along with this program. If not, see
.
-import base
+from . import base
from sat.core.i18n import _
from sat_frontends.jp.constants import Const as C
from functools import partial
@@ -36,13 +36,13 @@ class Get(base.CommandBase):
"get",
use_output=C.OUTPUT_DICT,
use_verbose=True,
- help=_(u"get identity data"),
+ help=_("get identity data"),
)
self.need_loop = True
def add_parser_options(self):
self.parser.add_argument(
- "jid", type=base.unicode_decoder, help=_(u"entity to check")
+ "jid", help=_("entity to check")
)
def identityGetCb(self, data):
@@ -57,7 +57,7 @@ class Get(base.CommandBase):
callback=self.identityGetCb,
errback=partial(
self.errback,
- msg=_(u"can't get identity data: {}"),
+ msg=_("can't get identity data: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -71,13 +71,12 @@ class Set(base.CommandBase):
self.parser.add_argument(
"-f",
"--field",
- type=base.unicode_decoder,
action="append",
nargs=2,
dest="fields",
- metavar=(u"KEY", u"VALUE"),
+ metavar=("KEY", "VALUE"),
required=True,
- help=_(u"identity field(s) to set"),
+ help=_("identity field(s) to set"),
)
self.need_loop = True
@@ -89,7 +88,7 @@ class Set(base.CommandBase):
callback=self.host.quit,
errback=partial(
self.errback,
- msg=_(u"can't set identity data data: {}"),
+ msg=_("can't set identity data data: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
diff --git a/sat_frontends/jp/cmd_info.py b/sat_frontends/jp/cmd_info.py
index e08b6db3..65541219 100644
--- a/sat_frontends/jp/cmd_info.py
+++ b/sat_frontends/jp/cmd_info.py
@@ -17,7 +17,7 @@
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see
.
-import base
+from . import base
from sat.core.i18n import _
from sat.tools.common.ansi import ANSI as A
from sat.tools.common import date_utils
@@ -35,10 +35,10 @@ class Disco(base.CommandBase):
self.need_loop=True
def add_parser_options(self):
- self.parser.add_argument(u"jid", type=base.unicode_decoder, help=_(u"entity to discover"))
- self.parser.add_argument(u"-t", u"--type", type=str, choices=('infos', 'items', 'both'), default='both', help=_(u"type of data to discover"))
- self.parser.add_argument(u"-n", u"--node", type=base.unicode_decoder, default=u'', help=_(u"node to use"))
- self.parser.add_argument(u"-C", u"--no-cache", dest='use_cache', action="store_false", help=_(u"ignore cache"))
+ self.parser.add_argument("jid", help=_("entity to discover"))
+ self.parser.add_argument("-t", "--type", type=str, choices=('infos', 'items', 'both'), default='both', help=_("type of data to discover"))
+ self.parser.add_argument("-n", "--node", default='', help=_("node to use"))
+ self.parser.add_argument("-C", "--no-cache", dest='use_cache', action="store_false", help=_("ignore cache"))
def start(self):
self.get_infos = self.args.type in ('infos', 'both')
@@ -51,7 +51,7 @@ class Disco(base.CommandBase):
self.host.bridge.discoInfos(jid, node=self.args.node, use_cache=self.args.use_cache, profile_key=self.host.profile, callback=lambda infos: self.gotInfos(infos, jid), errback=self.error)
def error(self, failure):
- print (_("Error while doing discovery [%s]") % failure)
+ print((_("Error while doing discovery [%s]") % failure))
self.host.quit(1)
def gotInfos(self, infos, jid):
@@ -68,78 +68,78 @@ class Disco(base.CommandBase):
features.sort()
identities.sort(key=lambda identity: identity[2])
data.update({
- u'features': features,
- u'identities': identities,
- u'extensions': extensions})
+ 'features': features,
+ 'identities': identities,
+ 'extensions': extensions})
if self.get_items:
items.sort(key=lambda item: item[2])
- data[u'items'] = items
+ data['items'] = items
self.output(data)
self.host.quit()
def default_output(self, data):
- features = data.get(u'features', [])
- identities = data.get(u'identities', [])
- extensions = data.get(u'extensions', {})
- items = data.get(u'items', [])
+ features = data.get('features', [])
+ identities = data.get('identities', [])
+ extensions = data.get('extensions', {})
+ items = data.get('items', [])
identities_table = common.Table(self.host,
identities,
- headers=(_(u'category'),
- _(u'type'),
- _(u'name')),
+ headers=(_('category'),
+ _('type'),
+ _('name')),
use_buffer=True)
extensions_tpl = []
- extensions_types = extensions.keys()
+ extensions_types = list(extensions.keys())
extensions_types.sort()
for type_ in extensions_types:
fields = []
for field in extensions[type_]:
field_lines = []
data, values = field
- data_keys = data.keys()
+ data_keys = list(data.keys())
data_keys.sort()
for key in data_keys:
- field_lines.append(A.color(u'\t', C.A_SUBHEADER, key, A.RESET, u': ',
+ field_lines.append(A.color('\t', C.A_SUBHEADER, key, A.RESET, ': ',
data[key]))
if len(values) == 1:
- field_lines.append(A.color(u'\t', C.A_SUBHEADER, u"value", A.RESET,
- u': ', values[0] or (A.BOLD + u"UNSET")))
+ field_lines.append(A.color('\t', C.A_SUBHEADER, "value", A.RESET,
+ ': ', values[0] or (A.BOLD + "UNSET")))
elif len(values) > 1:
- field_lines.append(A.color(u'\t', C.A_SUBHEADER, u"values", A.RESET,
- u': '))
+ field_lines.append(A.color('\t', C.A_SUBHEADER, "values", A.RESET,
+ ': '))
for value in values:
- field_lines.append(A.color(u'\t - ', A.BOLD, value))
- fields.append(u'\n'.join(field_lines))
- extensions_tpl.append(u'{type_}\n{fields}'.format(type_=type_,
+ field_lines.append(A.color('\t - ', A.BOLD, value))
+ fields.append('\n'.join(field_lines))
+ extensions_tpl.append('{type_}\n{fields}'.format(type_=type_,
fields='\n\n'.join(fields)))
items_table = common.Table(self.host,
items,
- headers=(_(u'entity'),
- _(u'node'),
- _(u'name')),
+ headers=(_('entity'),
+ _('node'),
+ _('name')),
use_buffer=True)
template = []
if features:
- template.append(A.color(C.A_HEADER, _(u"Features")) + u"\n\n{features}")
+ template.append(A.color(C.A_HEADER, _("Features")) + "\n\n{features}")
if identities:
- template.append(A.color(C.A_HEADER, _(u"Identities")) + u"\n\n{identities}")
+ template.append(A.color(C.A_HEADER, _("Identities")) + "\n\n{identities}")
if extensions:
- template.append(A.color(C.A_HEADER, _(u"Extensions")) + u"\n\n{extensions}")
+ template.append(A.color(C.A_HEADER, _("Extensions")) + "\n\n{extensions}")
if items:
- template.append(A.color(C.A_HEADER, _(u"Items")) + u"\n\n{items}")
+ template.append(A.color(C.A_HEADER, _("Items")) + "\n\n{items}")
- print u"\n\n".join(template).format(features = u'\n'.join(features),
+ print("\n\n".join(template).format(features = '\n'.join(features),
identities = identities_table.display().string,
- extensions = u'\n'.join(extensions_tpl),
+ extensions = '\n'.join(extensions_tpl),
items = items_table.display().string,
- )
+ ))
class Version(base.CommandBase):
@@ -157,7 +157,7 @@ class Version(base.CommandBase):
self.host.bridge.getSoftwareVersion(jid, self.host.profile, callback=self.gotVersion, errback=self.error)
def error(self, failure):
- print (_("Error while trying to get version [%s]") % failure)
+ print((_("Error while trying to get version [%s]") % failure))
self.host.quit(1)
def gotVersion(self, data):
@@ -170,7 +170,7 @@ class Version(base.CommandBase):
if os:
infos.append(_("Operating System: %s") % os)
- print "\n".join(infos)
+ print("\n".join(infos))
self.host.quit()
@@ -183,7 +183,7 @@ class Session(base.CommandBase):
def default_output(self, data):
started = data['started']
- data['started'] = u'{short} (UTC, {relative})'.format(
+ data['started'] = '{short} (UTC, {relative})'.format(
short=date_utils.date_fmt(started),
relative=date_utils.date_fmt(started, 'relative'))
self.host.output(C.OUTPUT_DICT, 'simple', {}, data)
@@ -199,7 +199,7 @@ class Session(base.CommandBase):
self.host.quit()
def _sessionInfoGetEb(self, error_data):
- self.disp(_(u'Error getting session infos: {}').format(error_data), error=True)
+ self.disp(_('Error getting session infos: {}').format(error_data), error=True)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
diff --git a/sat_frontends/jp/cmd_input.py b/sat_frontends/jp/cmd_input.py
index ec71e275..5f5cc0bb 100644
--- a/sat_frontends/jp/cmd_input.py
+++ b/sat_frontends/jp/cmd_input.py
@@ -18,7 +18,7 @@
# along with this program. If not, see
.
-import base
+from . import base
from sat.core.i18n import _
from sat.core import exceptions
from sat_frontends.jp.constants import Const as C
@@ -56,7 +56,7 @@ class InputCommon(base.CommandBase):
def add_parser_options(self):
self.parser.add_argument(
- "--encoding", default="utf-8", help=_(u"encoding of the input data")
+ "--encoding", default="utf-8", help=_("encoding of the input data")
)
self.parser.add_argument(
"-i",
@@ -64,7 +64,7 @@ class InputCommon(base.CommandBase):
action="append_const",
const=(OPT_STDIN, None),
dest="arguments",
- help=_(u"standard input"),
+ help=_("standard input"),
)
self.parser.add_argument(
"-s",
@@ -72,7 +72,7 @@ class InputCommon(base.CommandBase):
type=self.opt(OPT_SHORT),
action="append",
dest="arguments",
- help=_(u"short option"),
+ help=_("short option"),
)
self.parser.add_argument(
"-l",
@@ -80,7 +80,7 @@ class InputCommon(base.CommandBase):
type=self.opt(OPT_LONG),
action="append",
dest="arguments",
- help=_(u"long option"),
+ help=_("long option"),
)
self.parser.add_argument(
"-p",
@@ -88,7 +88,7 @@ class InputCommon(base.CommandBase):
type=self.opt(OPT_POS),
action="append",
dest="arguments",
- help=_(u"positional argument"),
+ help=_("positional argument"),
)
self.parser.add_argument(
"-x",
@@ -96,19 +96,19 @@ class InputCommon(base.CommandBase):
action="append_const",
const=(OPT_IGNORE, None),
dest="arguments",
- help=_(u"ignore value"),
+ help=_("ignore value"),
)
self.parser.add_argument(
"-D",
"--debug",
action="store_true",
- help=_(u"don't actually run commands but echo what would be launched"),
+ help=_("don't actually run commands but echo what would be launched"),
)
self.parser.add_argument(
- "--log", type=argparse.FileType("wb"), help=_(u"log stdout to FILE")
+ "--log", type=argparse.FileType("wb"), help=_("log stdout to FILE")
)
self.parser.add_argument(
- "--log-err", type=argparse.FileType("wb"), help=_(u"log stderr to FILE")
+ "--log-err", type=argparse.FileType("wb"), help=_("log stderr to FILE")
)
self.parser.add_argument("command", nargs=argparse.REMAINDER)
@@ -123,7 +123,7 @@ class InputCommon(base.CommandBase):
arg_type, arg_name = arguments[self.args_idx]
except IndexError:
self.disp(
- _(u"arguments in input data and in arguments sequence don't match"),
+ _("arguments in input data and in arguments sequence don't match"),
error=True,
)
self.host.quit(C.EXIT_DATA_ERROR)
@@ -150,13 +150,13 @@ class InputCommon(base.CommandBase):
self.disp(
A.color(
C.A_SUBHEADER,
- _(u"values: "),
+ _("values: "),
A.RESET,
- u", ".join(self._values_ori),
+ ", ".join(self._values_ori),
),
2,
)
- self.disp(A.color(A.BOLD, _(u"**SKIPPING**\n")))
+ self.disp(A.color(A.BOLD, _("**SKIPPING**\n")))
self.reset()
self.idx += 1
raise exceptions.CancelError
@@ -180,7 +180,7 @@ class InputCommon(base.CommandBase):
else:
self.parser.error(
_(
- u"Invalid argument, an option type is expected, got {type_}:{name}"
+ "Invalid argument, an option type is expected, got {type_}:{name}"
).format(type_=arg_type, name=arg_name)
)
@@ -188,39 +188,39 @@ class InputCommon(base.CommandBase):
"""run requested command with parsed arguments"""
if self.args_idx != len(self.args.arguments):
self.disp(
- _(u"arguments in input data and in arguments sequence don't match"),
+ _("arguments in input data and in arguments sequence don't match"),
error=True,
)
self.host.quit(C.EXIT_DATA_ERROR)
self.disp(
- A.color(C.A_HEADER, _(u"command {idx}").format(idx=self.idx)),
+ A.color(C.A_HEADER, _("command {idx}").format(idx=self.idx)),
no_lf=not self.args.debug,
)
stdin = "".join(self._stdin)
if self.args.debug:
self.disp(
A.color(
- C.A_SUBHEADER, _(u"values: "), A.RESET, u", ".join(self._values_ori)
+ C.A_SUBHEADER, _("values: "), A.RESET, ", ".join(self._values_ori)
),
2,
)
if stdin:
- self.disp(A.color(C.A_SUBHEADER, u"--- STDIN ---"))
- self.disp(stdin.decode("utf-8"))
- self.disp(A.color(C.A_SUBHEADER, u"-------------"))
+ self.disp(A.color(C.A_SUBHEADER, "--- STDIN ---"))
+ self.disp(stdin)
+ self.disp(A.color(C.A_SUBHEADER, "-------------"))
self.disp(
- u"{indent}{prog} {static} {options} {positionals}".format(
- indent=4 * u" ",
+ "{indent}{prog} {static} {options} {positionals}".format(
+ indent=4 * " ",
prog=sys.argv[0],
- static=" ".join(self.args.command).decode("utf-8"),
- options=u" ".join([o.decode("utf-8") for o in self._opts]),
- positionals=u" ".join([p.decode("utf-8") for p in self._pos]),
+ static=" ".join(self.args.command),
+ options=" ".join([o for o in self._opts]),
+ positionals=" ".join([p for p in self._pos]),
)
)
- self.disp(u"\n")
+ self.disp("\n")
else:
- self.disp(u" (" + u", ".join(self._values_ori) + u")", 2, no_lf=True)
+ self.disp(" (" + ", ".join(self._values_ori) + ")", 2, no_lf=True)
args = [sys.argv[0]] + self.args.command + self._opts + self._pos
p = subprocess.Popen(
args,
@@ -238,9 +238,9 @@ class InputCommon(base.CommandBase):
log_err.write(log_tpl.format(command=" ".join(args), buff=stderr))
ret = p.wait()
if ret == 0:
- self.disp(A.color(C.A_SUCCESS, _(u"OK")))
+ self.disp(A.color(C.A_SUCCESS, _("OK")))
else:
- self.disp(A.color(C.A_FAILURE, _(u"FAILED")))
+ self.disp(A.color(C.A_FAILURE, _("FAILED")))
self.reset()
self.idx += 1
@@ -260,7 +260,7 @@ class InputCommon(base.CommandBase):
class Csv(InputCommon):
def __init__(self, host):
- super(Csv, self).__init__(host, "csv", _(u"comma-separated values"))
+ super(Csv, self).__init__(host, "csv", _("comma-separated values"))
def add_parser_options(self):
InputCommon.add_parser_options(self)
@@ -269,7 +269,7 @@ class Csv(InputCommon):
"--row",
type=int,
default=0,
- help=_(u"starting row (previous ones will be ignored)"),
+ help=_("starting row (previous ones will be ignored)"),
)
self.parser.add_argument(
"-S",
@@ -277,7 +277,7 @@ class Csv(InputCommon):
action="append_const",
const=("split", None),
dest="arguments",
- help=_(u"split value in several options"),
+ help=_("split value in several options"),
)
self.parser.add_argument(
"-E",
@@ -285,8 +285,8 @@ class Csv(InputCommon):
action="append",
type=self.opt("empty"),
dest="arguments",
- help=_(u"action to do on empty value ({choices})").format(
- choices=u", ".join(OPT_EMPTY_CHOICES)
+ help=_("action to do on empty value ({choices})").format(
+ choices=", ".join(OPT_EMPTY_CHOICES)
),
)
@@ -300,8 +300,8 @@ class Csv(InputCommon):
return value if value else False
else:
self.parser.error(
- _(u"--empty value must be one of {choices}").format(
- choices=u", ".join(OPT_EMPTY_CHOICES)
+ _("--empty value must be one of {choices}").format(
+ choices=", ".join(OPT_EMPTY_CHOICES)
)
)
@@ -331,5 +331,5 @@ class Input(base.CommandBase):
host,
"input",
use_profile=False,
- help=_(u"launch command with external input"),
+ help=_("launch command with external input"),
)
diff --git a/sat_frontends/jp/cmd_invitation.py b/sat_frontends/jp/cmd_invitation.py
index 9147e5e7..e312ae00 100644
--- a/sat_frontends/jp/cmd_invitation.py
+++ b/sat_frontends/jp/cmd_invitation.py
@@ -18,7 +18,7 @@
# along with this program. If not, see
.
-import base
+from . import base
from sat.core.i18n import _
from sat_frontends.jp.constants import Const as C
from sat.tools.common.ansi import ANSI as A
@@ -36,7 +36,7 @@ class Create(base.CommandBase):
"create",
use_profile=False,
use_output=C.OUTPUT_DICT,
- help=_(u"create and send an invitation"),
+ help=_("create and send an invitation"),
)
self.need_loop = True
@@ -44,28 +44,24 @@ class Create(base.CommandBase):
self.parser.add_argument(
"-j",
"--jid",
- type=base.unicode_decoder,
default="",
help="jid of the invitee (default: generate one)",
)
self.parser.add_argument(
"-P",
"--password",
- type=base.unicode_decoder,
default="",
help="password of the invitee profile/XMPP account (default: generate one)",
)
self.parser.add_argument(
"-n",
"--name",
- type=base.unicode_decoder,
default="",
help="name of the invitee",
)
self.parser.add_argument(
"-N",
"--host-name",
- type=base.unicode_decoder,
default="",
help="name of the host",
)
@@ -73,7 +69,6 @@ class Create(base.CommandBase):
"-e",
"--email",
action="append",
- type=base.unicode_decoder,
default=[],
help="email(s) to send the invitation to (if --no-email is set, email will just be saved)",
)
@@ -83,28 +78,24 @@ class Create(base.CommandBase):
self.parser.add_argument(
"-l",
"--lang",
- type=base.unicode_decoder,
default="",
help="main language spoken by the invitee",
)
self.parser.add_argument(
"-u",
"--url",
- type=base.unicode_decoder,
default="",
help="template to construct the URL",
)
self.parser.add_argument(
"-s",
"--subject",
- type=base.unicode_decoder,
default="",
help="subject of the invitation email (default: generic subject)",
)
self.parser.add_argument(
"-b",
"--body",
- type=base.unicode_decoder,
default="",
help="body of the invitation email (default: generic body)",
)
@@ -112,7 +103,6 @@ class Create(base.CommandBase):
"-x",
"--extra",
metavar=("KEY", "VALUE"),
- type=base.unicode_decoder,
action="append",
nargs=2,
default=[],
@@ -121,7 +111,6 @@ class Create(base.CommandBase):
self.parser.add_argument(
"-p",
"--profile",
- type=base.unicode_decoder,
default="",
help="profile doing the invitation (default: don't associate profile)",
)
@@ -132,7 +121,7 @@ class Create(base.CommandBase):
def invitationCreateEb(self, failure_):
self.disp(
- u"can't create invitation: {reason}".format(reason=failure_), error=True
+ "can't create invitation: {reason}".format(reason=failure_), error=True
)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
@@ -143,11 +132,11 @@ class Create(base.CommandBase):
if self.args.no_email:
if email:
extra["email"] = email
- data_format.iter2dict(u"emails_extra", emails_extra)
+ data_format.iter2dict("emails_extra", emails_extra)
else:
if not email:
self.parser.error(
- _(u"you need to specify an email address to send email invitation")
+ _("you need to specify an email address to send email invitation")
)
self.host.bridge.invitationCreate(
@@ -176,19 +165,19 @@ class Get(base.CommandBase):
"get",
use_profile=False,
use_output=C.OUTPUT_DICT,
- help=_(u"get invitation data"),
+ help=_("get invitation data"),
)
self.need_loop = True
def add_parser_options(self):
self.parser.add_argument(
- "id", type=base.unicode_decoder, help=_(u"invitation UUID")
+ "id", help=_("invitation UUID")
)
self.parser.add_argument(
"-j",
"--with-jid",
action="store_true",
- help=_(u"start profile session and retrieve jid"),
+ help=_("start profile session and retrieve jid"),
)
def output_data(self, data, jid_=None):
@@ -199,28 +188,28 @@ class Get(base.CommandBase):
def invitationGetCb(self, invitation_data):
if self.args.with_jid:
- profile = invitation_data[u"guest_profile"]
+ profile = invitation_data["guest_profile"]
def session_started(__):
self.host.bridge.asyncGetParamA(
- u"JabberID",
- u"Connection",
+ "JabberID",
+ "Connection",
profile_key=profile,
callback=lambda jid_: self.output_data(invitation_data, jid_),
errback=partial(
self.errback,
- msg=_(u"can't retrieve jid: {}"),
+ msg=_("can't retrieve jid: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
self.host.bridge.profileStartSession(
- invitation_data[u"password"],
+ invitation_data["password"],
profile,
callback=session_started,
errback=partial(
self.errback,
- msg=_(u"can't start session: {}"),
+ msg=_("can't start session: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -233,7 +222,7 @@ class Get(base.CommandBase):
callback=self.invitationGetCb,
errback=partial(
self.errback,
- msg=_(u"can't get invitation data: {}"),
+ msg=_("can't get invitation data: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -242,7 +231,7 @@ class Get(base.CommandBase):
class Modify(base.CommandBase):
def __init__(self, host):
base.CommandBase.__init__(
- self, host, "modify", use_profile=False, help=_(u"modify existing invitation")
+ self, host, "modify", use_profile=False, help=_("modify existing invitation")
)
self.need_loop = True
@@ -253,21 +242,18 @@ class Modify(base.CommandBase):
self.parser.add_argument(
"-n",
"--name",
- type=base.unicode_decoder,
default="",
help="name of the invitee",
)
self.parser.add_argument(
"-N",
"--host-name",
- type=base.unicode_decoder,
default="",
help="name of the host",
)
self.parser.add_argument(
"-e",
"--email",
- type=base.unicode_decoder,
default="",
help="email to send the invitation to (if --no-email is set, email will just be saved)",
)
@@ -275,7 +261,6 @@ class Modify(base.CommandBase):
"-l",
"--lang",
dest="language",
- type=base.unicode_decoder,
default="",
help="main language spoken by the invitee",
)
@@ -283,7 +268,6 @@ class Modify(base.CommandBase):
"-x",
"--extra",
metavar=("KEY", "VALUE"),
- type=base.unicode_decoder,
action="append",
nargs=2,
default=[],
@@ -292,21 +276,20 @@ class Modify(base.CommandBase):
self.parser.add_argument(
"-p",
"--profile",
- type=base.unicode_decoder,
default="",
help="profile doing the invitation (default: don't associate profile",
)
self.parser.add_argument(
- "id", type=base.unicode_decoder, help=_(u"invitation UUID")
+ "id", help=_("invitation UUID")
)
def invitationModifyCb(self):
- self.disp(_(u"invitations have been modified correctly"))
+ self.disp(_("invitations have been modified correctly"))
self.host.quit(C.EXIT_OK)
def invitationModifyEb(self, failure_):
self.disp(
- u"can't create invitation: {reason}".format(reason=failure_), error=True
+ "can't create invitation: {reason}".format(reason=failure_), error=True
)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
@@ -319,7 +302,7 @@ class Modify(base.CommandBase):
if arg_name in extra:
self.parser.error(
_(
- u"you can't set {arg_name} in both optional argument and extra"
+ "you can't set {arg_name} in both optional argument and extra"
).format(arg_name=arg_name)
)
extra[arg_name] = value
@@ -342,26 +325,26 @@ class List(base.CommandBase):
use_profile=False,
use_output=C.OUTPUT_COMPLEX,
extra_outputs=extra_outputs,
- help=_(u"list invitations data"),
+ help=_("list invitations data"),
)
self.need_loop = True
def default_output(self, data):
- for idx, datum in enumerate(data.iteritems()):
+ for idx, datum in enumerate(data.items()):
if idx:
- self.disp(u"\n")
+ self.disp("\n")
key, invitation_data = datum
self.disp(A.color(C.A_HEADER, key))
- indent = u" "
- for k, v in invitation_data.iteritems():
- self.disp(indent + A.color(C.A_SUBHEADER, k + u":") + u" " + unicode(v))
+ indent = " "
+ for k, v in invitation_data.items():
+ self.disp(indent + A.color(C.A_SUBHEADER, k + ":") + " " + str(v))
def add_parser_options(self):
self.parser.add_argument(
"-p",
"--profile",
default=C.PROF_KEY_NONE,
- help=_(u"return only invitations linked to this profile"),
+ help=_("return only invitations linked to this profile"),
)
def invitationListCb(self, data):
@@ -374,7 +357,7 @@ class List(base.CommandBase):
callback=self.invitationListCb,
errback=partial(
self.errback,
- msg=_(u"can't list invitations: {}"),
+ msg=_("can't list invitations: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -388,5 +371,5 @@ class Invitation(base.CommandBase):
host,
"invitation",
use_profile=False,
- help=_(u"invitation of user(s) without XMPP account"),
+ help=_("invitation of user(s) without XMPP account"),
)
diff --git a/sat_frontends/jp/cmd_merge_request.py b/sat_frontends/jp/cmd_merge_request.py
index db8e9edd..98f5195e 100644
--- a/sat_frontends/jp/cmd_merge_request.py
+++ b/sat_frontends/jp/cmd_merge_request.py
@@ -18,7 +18,7 @@
# along with this program. If not, see
.
-import base
+from . import base
from sat.core.i18n import _
from sat.tools.common import data_format
from sat_frontends.jp.constants import Const as C
@@ -37,8 +37,8 @@ class Set(base.CommandBase):
host,
"set",
use_pubsub=True,
- pubsub_defaults={u"service": _(u"auto"), u"node": _(u"auto")},
- help=_(u"publish or update a merge request"),
+ pubsub_defaults={"service": _("auto"), "node": _("auto")},
+ help=_("publish or update a merge request"),
)
self.need_loop = True
@@ -46,59 +46,56 @@ class Set(base.CommandBase):
self.parser.add_argument(
"-i",
"--item",
- type=base.unicode_decoder,
- default=u"",
- help=_(u"id or URL of the request to update, or nothing for a new one"),
+ default="",
+ help=_("id or URL of the request to update, or nothing for a new one"),
)
self.parser.add_argument(
"-r",
"--repository",
metavar="PATH",
- type=base.unicode_decoder,
- default=u".",
- help=_(u"path of the repository (DEFAULT: current directory)"),
+ default=".",
+ help=_("path of the repository (DEFAULT: current directory)"),
)
self.parser.add_argument(
"-f",
"--force",
action="store_true",
- help=_(u"publish merge request without confirmation"),
+ help=_("publish merge request without confirmation"),
)
self.parser.add_argument(
"-l",
"--label",
dest="labels",
- type=base.unicode_decoder,
action="append",
- help=_(u"labels to categorize your request"),
+ help=_("labels to categorize your request"),
)
def mergeRequestSetCb(self, published_id):
if published_id:
- self.disp(u"Merge request published at {pub_id}".format(pub_id=published_id))
+ self.disp("Merge request published at {pub_id}".format(pub_id=published_id))
else:
- self.disp(u"Merge request published")
+ self.disp("Merge request published")
self.host.quit(C.EXIT_OK)
def sendRequest(self):
extra = {"update": True} if self.args.item else {}
values = {}
if self.args.labels is not None:
- values[u"labels"] = self.args.labels
+ values["labels"] = self.args.labels
self.host.bridge.mergeRequestSet(
self.args.service,
self.args.node,
self.repository,
- u"auto",
+ "auto",
values,
- u"",
+ "",
self.args.item,
data_format.serialise(extra),
self.profile,
callback=self.mergeRequestSetCb,
errback=partial(
self.errback,
- msg=_(u"can't create merge request: {}"),
+ msg=_("can't create merge request: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -106,9 +103,9 @@ class Set(base.CommandBase):
def askConfirmation(self):
if not self.args.force:
message = _(
- u"You are going to publish your changes to service [{service}], are you sure ?"
+ "You are going to publish your changes to service [{service}], are you sure ?"
).format(service=self.args.service)
- self.host.confirmOrQuit(message, _(u"merge request publication cancelled"))
+ self.host.confirmOrQuit(message, _("merge request publication cancelled"))
self.sendRequest()
def start(self):
@@ -125,8 +122,8 @@ class Get(base.CommandBase):
use_verbose=True,
use_pubsub=True,
pubsub_flags={C.MULTI_ITEMS},
- pubsub_defaults={u"service": _(u"auto"), u"node": _(u"auto")},
- help=_(u"get a merge request"),
+ pubsub_defaults={"service": _("auto"), "node": _("auto")},
+ help=_("get a merge request"),
)
self.need_loop = True
@@ -141,7 +138,7 @@ class Get(base.CommandBase):
for request_xmlui in requests_data[0]:
xmlui = xmlui_manager.create(self.host, request_xmlui, whitelist=whitelist)
xmlui.show(values_only=True)
- self.disp(u"")
+ self.disp("")
self.host.quit(C.EXIT_OK)
def getRequests(self):
@@ -151,13 +148,13 @@ class Get(base.CommandBase):
self.args.node,
self.args.max,
self.args.items,
- u"",
+ "",
extra,
self.profile,
callback=self.mergeRequestGetCb,
errback=partial(
self.errback,
- msg=_(u"can't get merge request: {}"),
+ msg=_("can't get merge request: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -176,8 +173,8 @@ class Import(base.CommandBase):
"import",
use_pubsub=True,
pubsub_flags={C.SINGLE_ITEM, C.ITEM},
- pubsub_defaults={u"service": _(u"auto"), u"node": _(u"auto")},
- help=_(u"import a merge request"),
+ pubsub_defaults={"service": _("auto"), "node": _("auto")},
+ help=_("import a merge request"),
)
self.need_loop = True
@@ -186,9 +183,8 @@ class Import(base.CommandBase):
"-r",
"--repository",
metavar="PATH",
- type=base.unicode_decoder,
- default=u".",
- help=_(u"path of the repository (DEFAULT: current directory)"),
+ default=".",
+ help=_("path of the repository (DEFAULT: current directory)"),
)
def mergeRequestImportCb(self):
@@ -206,7 +202,7 @@ class Import(base.CommandBase):
callback=self.mergeRequestImportCb,
errback=partial(
self.errback,
- msg=_(u"can't import merge request: {}"),
+ msg=_("can't import merge request: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
diff --git a/sat_frontends/jp/cmd_message.py b/sat_frontends/jp/cmd_message.py
index a764d216..a7bb5b28 100644
--- a/sat_frontends/jp/cmd_message.py
+++ b/sat_frontends/jp/cmd_message.py
@@ -37,15 +37,15 @@ class Send(base.CommandBase):
def add_parser_options(self):
self.parser.add_argument(
- "-l", "--lang", type=str, default="", help=_(u"language of the message")
+ "-l", "--lang", type=str, default="", help=_("language of the message")
)
self.parser.add_argument(
"-s",
"--separate",
action="store_true",
help=_(
- u"separate xmpp messages: send one message per line instead of one "
- u"message alone."
+ "separate xmpp messages: send one message per line instead of one "
+ "message alone."
),
)
self.parser.add_argument(
@@ -53,17 +53,16 @@ class Send(base.CommandBase):
"--new-line",
action="store_true",
help=_(
- u"add a new line at the beginning of the input (usefull for ascii art ;))"
+ "add a new line at the beginning of the input (usefull for ascii art ;))"
),
)
self.parser.add_argument(
"-S",
"--subject",
- type=base.unicode_decoder,
- help=_(u"subject of the message"),
+ help=_("subject of the message"),
)
self.parser.add_argument(
- "-L", "--subject_lang", type=str, default="", help=_(u"language of subject")
+ "-L", "--subject_lang", type=str, default="", help=_("language of subject")
)
self.parser.add_argument(
"-t",
@@ -73,16 +72,16 @@ class Send(base.CommandBase):
help=_("type of the message"),
)
self.parser.add_argument("-e", "--encrypt", metavar="ALGORITHM",
- help=_(u"encrypt message using given algorithm"))
+ help=_("encrypt message using given algorithm"))
self.parser.add_argument(
"--encrypt-noreplace",
action="store_true",
- help=_(u"don't replace encryption algorithm if an other one is already used"))
+ help=_("don't replace encryption algorithm if an other one is already used"))
syntax = self.parser.add_mutually_exclusive_group()
- syntax.add_argument("-x", "--xhtml", action="store_true", help=_(u"XHTML body"))
- syntax.add_argument("-r", "--rich", action="store_true", help=_(u"rich body"))
+ syntax.add_argument("-x", "--xhtml", action="store_true", help=_("XHTML body"))
+ syntax.add_argument("-r", "--rich", action="store_true", help=_("rich body"))
self.parser.add_argument(
- "jid", type=base.unicode_decoder, help=_(u"the destination jid")
+ "jid", help=_("the destination jid")
)
def multi_send_cb(self):
@@ -91,7 +90,7 @@ class Send(base.CommandBase):
self.host.quit(self.errcode)
def multi_send_eb(self, failure_, msg):
- self.disp(_(u"Can't send message [{msg}]: {reason}").format(
+ self.disp(_("Can't send message [{msg}]: {reason}").format(
msg=msg, reason=failure_))
self.errcode = C.EXIT_BRIDGE_ERRBACK
self.multi_send_cb()
@@ -112,10 +111,10 @@ class Send(base.CommandBase):
subject = {self.args.subject_lang: self.args.subject}
if self.args.xhtml or self.args.rich:
- key = u"xhtml" if self.args.xhtml else u"rich"
+ key = "xhtml" if self.args.xhtml else "rich"
if self.args.lang:
- key = u"{}_{}".format(key, self.args.lang)
- extra[key] = clean_ustr(u"".join(stdin_lines))
+ key = "{}_{}".format(key, self.args.lang)
+ extra[key] = clean_ustr("".join(stdin_lines))
stdin_lines = []
if self.args.separate: # we send stdin in several messages
@@ -150,7 +149,7 @@ class Send(base.CommandBase):
else:
msg = (
- {self.args.lang: header + clean_ustr(u"".join(stdin_lines))}
+ {self.args.lang: header + clean_ustr("".join(stdin_lines))}
if not (self.args.xhtml or self.args.rich)
else {}
)
@@ -163,7 +162,7 @@ class Send(base.CommandBase):
profile_key=self.host.profile,
callback=self.host.quit,
errback=partial(self.errback,
- msg=_(u"Can't send message: {}")))
+ msg=_("Can't send message: {}")))
def encryptionNamespaceGetCb(self, namespace, jid_):
self.host.bridge.messageEncryptionStart(
@@ -171,7 +170,7 @@ class Send(base.CommandBase):
self.profile,
callback=lambda: self.sendStdin(jid_),
errback=partial(self.errback,
- msg=_(u"Can't start encryption session: {}"),
+ msg=_("Can't start encryption session: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
))
@@ -179,7 +178,7 @@ class Send(base.CommandBase):
def start(self):
if self.args.xhtml and self.args.separate:
self.disp(
- u"argument -s/--separate is not compatible yet with argument -x/--xhtml",
+ "argument -s/--separate is not compatible yet with argument -x/--xhtml",
error=True,
)
self.host.quit(2)
@@ -194,7 +193,7 @@ class Send(base.CommandBase):
self.host.bridge.encryptionNamespaceGet(self.args.encrypt,
callback=partial(self.encryptionNamespaceGetCb, jid_=jid_),
errback=partial(self.errback,
- msg=_(u"Can't get encryption namespace: {}"),
+ msg=_("Can't get encryption namespace: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
))
else:
@@ -205,49 +204,49 @@ class MAM(base.CommandBase):
def __init__(self, host):
super(MAM, self).__init__(
- host, "mam", use_output=C.OUTPUT_MESS, use_verbose=True, help=_(u"query archives using MAM"))
+ host, "mam", use_output=C.OUTPUT_MESS, use_verbose=True, help=_("query archives using MAM"))
self.need_loop=True
def add_parser_options(self):
self.parser.add_argument(
- "-s", "--service", type=base.unicode_decoder, default=u"",
- help=_(u"jid of the service (default: profile's server"))
+ "-s", "--service", default="",
+ help=_("jid of the service (default: profile's server"))
self.parser.add_argument(
"-S", "--start", dest="mam_start", type=base.date_decoder,
help=_(
- u"start fetching archive from this date (default: from the beginning)"))
+ "start fetching archive from this date (default: from the beginning)"))
self.parser.add_argument(
"-E", "--end", dest="mam_end", type=base.date_decoder,
- help=_(u"end fetching archive after this date (default: no limit)"))
+ help=_("end fetching archive after this date (default: no limit)"))
self.parser.add_argument(
- "-W", "--with", dest="mam_with", type=base.unicode_decoder,
- help=_(u"retrieve only archives with this jid"))
+ "-W", "--with", dest="mam_with",
+ help=_("retrieve only archives with this jid"))
self.parser.add_argument(
"-m", "--max", dest="rsm_max", type=int, default=20,
- help=_(u"maximum number of items to retrieve, using RSM (default: 20))"))
+ help=_("maximum number of items to retrieve, using RSM (default: 20))"))
rsm_page_group = self.parser.add_mutually_exclusive_group()
rsm_page_group.add_argument(
- "-a", "--after", dest="rsm_after", type=base.unicode_decoder,
- help=_(u"find page after this item"), metavar='ITEM_ID')
+ "-a", "--after", dest="rsm_after",
+ help=_("find page after this item"), metavar='ITEM_ID')
rsm_page_group.add_argument(
- "-b", "--before", dest="rsm_before", type=base.unicode_decoder,
- help=_(u"find page before this item"), metavar='ITEM_ID')
+ "-b", "--before", dest="rsm_before",
+ help=_("find page before this item"), metavar='ITEM_ID')
rsm_page_group.add_argument(
"--index", dest="rsm_index", type=int,
- help=_(u"index of the page to retrieve"))
+ help=_("index of the page to retrieve"))
def _sessionInfosGetCb(self, session_info, data, metadata):
- self.host.own_jid = jid.JID(session_info[u"jid"])
+ self.host.own_jid = jid.JID(session_info["jid"])
self.output(data)
# FIXME: metadata are not displayed correctly and don't play nice with output
# they should be added to output data somehow
if self.verbosity:
- for value in (u"rsm_first", u"rsm_last", u"rsm_index", u"rsm_count",
- u"mam_complete", u"mam_stable"):
+ for value in ("rsm_first", "rsm_last", "rsm_index", "rsm_count",
+ "mam_complete", "mam_stable"):
if value in metadata:
- label = value.split(u"_")[1]
+ label = value.split("_")[1]
self.disp(A.color(
- C.A_HEADER, label, u': ' , A.RESET, metadata[value]))
+ C.A_HEADER, label, ': ' , A.RESET, metadata[value]))
self.host.quit()
@@ -260,16 +259,16 @@ class MAM(base.CommandBase):
def start(self):
extra = {}
if self.args.mam_start is not None:
- extra[u"mam_start"] = float(self.args.mam_start)
+ extra["mam_start"] = float(self.args.mam_start)
if self.args.mam_end is not None:
- extra[u"mam_end"] = float(self.args.mam_end)
+ extra["mam_end"] = float(self.args.mam_end)
if self.args.mam_with is not None:
- extra[u"mam_with"] = self.args.mam_with
+ extra["mam_with"] = self.args.mam_with
for suff in ('max', 'after', 'before', 'index'):
- key = u'rsm_' + suff
+ key = 'rsm_' + suff
value = getattr(self.args,key)
if value is not None:
- extra[key] = unicode(value)
+ extra[key] = str(value)
self.host.bridge.MAMGet(
self.args.service, data_format.serialise(extra), self.profile,
callback=self._MAMGetCb, errback=self.errback)
diff --git a/sat_frontends/jp/cmd_param.py b/sat_frontends/jp/cmd_param.py
index 70563dc7..8557165b 100644
--- a/sat_frontends/jp/cmd_param.py
+++ b/sat_frontends/jp/cmd_param.py
@@ -19,7 +19,7 @@
# along with this program. If not, see
.
-import base
+from . import base
from sat.core.i18n import _
__commands__ = ["Param"]
@@ -29,31 +29,31 @@ class Get(base.CommandBase):
super(Get, self).__init__(host, 'get', need_connect=False, help=_('Get a parameter value'))
def add_parser_options(self):
- self.parser.add_argument("category", nargs='?', type=base.unicode_decoder, help=_(u"Category of the parameter"))
- self.parser.add_argument("name", nargs='?', type=base.unicode_decoder, help=_(u"Name of the parameter"))
- self.parser.add_argument("-a", "--attribute", type=str, default="value", help=_(u"Name of the attribute to get"))
- self.parser.add_argument("--security-limit", type=int, default=-1, help=_(u"Security limit"))
+ self.parser.add_argument("category", nargs='?', help=_("Category of the parameter"))
+ self.parser.add_argument("name", nargs='?', help=_("Name of the parameter"))
+ self.parser.add_argument("-a", "--attribute", type=str, default="value", help=_("Name of the attribute to get"))
+ self.parser.add_argument("--security-limit", type=int, default=-1, help=_("Security limit"))
def start(self):
if self.args.category is None:
categories = self.host.bridge.getParamsCategories()
- print u"\n".join(categories)
+ print("\n".join(categories))
elif self.args.name is None:
try:
values_dict = self.host.bridge.asyncGetParamsValuesFromCategory(self.args.category, self.args.security_limit, self.profile)
except Exception as e:
- print u"Can't find requested parameters: {}".format(e)
+ print("Can't find requested parameters: {}".format(e))
self.host.quit(1)
- for name, value in values_dict.iteritems():
- print u"{}\t{}".format(name, value)
+ for name, value in values_dict.items():
+ print("{}\t{}".format(name, value))
else:
try:
value = self.host.bridge.asyncGetParamA(self.args.name, self.args.category, self.args.attribute,
self.args.security_limit, self.profile)
except Exception as e:
- print u"Can't find requested parameter: {}".format(e)
+ print("Can't find requested parameter: {}".format(e))
self.host.quit(1)
- print value
+ print(value)
class Set(base.CommandBase):
@@ -61,16 +61,16 @@ class Set(base.CommandBase):
super(Set, self).__init__(host, 'set', need_connect=False, help=_('Set a parameter value'))
def add_parser_options(self):
- self.parser.add_argument("category", type=base.unicode_decoder, help=_(u"Category of the parameter"))
- self.parser.add_argument("name", type=base.unicode_decoder, help=_(u"Name of the parameter"))
- self.parser.add_argument("value", type=base.unicode_decoder, help=_(u"Name of the parameter"))
- self.parser.add_argument("--security-limit", type=int, default=-1, help=_(u"Security limit"))
+ self.parser.add_argument("category", help=_("Category of the parameter"))
+ self.parser.add_argument("name", help=_("Name of the parameter"))
+ self.parser.add_argument("value", help=_("Name of the parameter"))
+ self.parser.add_argument("--security-limit", type=int, default=-1, help=_("Security limit"))
def start(self):
try:
self.host.bridge.setParam(self.args.name, self.args.value, self.args.category, self.args.security_limit, self.profile)
except Exception as e:
- print u"Can set requested parameter: {}".format(e)
+ print("Can set requested parameter: {}".format(e))
class SaveTemplate(base.CommandBase):
@@ -83,9 +83,9 @@ class SaveTemplate(base.CommandBase):
def start(self):
"""Save parameters template to xml file"""
if self.host.bridge.saveParamsTemplate(self.args.filename):
- print _("Parameters saved to file %s") % self.args.filename
+ print(_("Parameters saved to file %s") % self.args.filename)
else:
- print _("Can't save parameters to file %s") % self.args.filename
+ print(_("Can't save parameters to file %s") % self.args.filename)
class LoadTemplate(base.CommandBase):
@@ -99,9 +99,9 @@ class LoadTemplate(base.CommandBase):
def start(self):
"""Load parameters template from xml file"""
if self.host.bridge.loadParamsTemplate(self.args.filename):
- print _("Parameters loaded from file %s") % self.args.filename
+ print(_("Parameters loaded from file %s") % self.args.filename)
else:
- print _("Can't load parameters from file %s") % self.args.filename
+ print(_("Can't load parameters from file %s") % self.args.filename)
class Param(base.CommandBase):
diff --git a/sat_frontends/jp/cmd_ping.py b/sat_frontends/jp/cmd_ping.py
index 310a1ee0..4ac2c652 100644
--- a/sat_frontends/jp/cmd_ping.py
+++ b/sat_frontends/jp/cmd_ping.py
@@ -17,7 +17,7 @@
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see
.
-import base
+from . import base
from sat.core.i18n import _
__commands__ = ["Ping"]
@@ -31,14 +31,14 @@ class Ping(base.CommandBase):
def add_parser_options(self):
self.parser.add_argument(
- "jid", type=base.unicode_decoder, help=_(u"jid to ping")
+ "jid", help=_("jid to ping")
)
self.parser.add_argument(
- "-d", "--delay-only", action="store_true", help=_(u"output delay only (in s)")
+ "-d", "--delay-only", action="store_true", help=_("output delay only (in s)")
)
def _pingCb(self, pong_time):
- fmt = u"{time}" if self.args.delay_only else u"PONG ({time} s)"
+ fmt = "{time}" if self.args.delay_only else "PONG ({time} s)"
self.disp(fmt.format(time=pong_time))
self.host.quit()
diff --git a/sat_frontends/jp/cmd_pipe.py b/sat_frontends/jp/cmd_pipe.py
index 78ad07c6..8e977ed7 100644
--- a/sat_frontends/jp/cmd_pipe.py
+++ b/sat_frontends/jp/cmd_pipe.py
@@ -26,7 +26,7 @@ from sat_frontends.tools import jid
import xml.etree.ElementTree as ET # FIXME: used temporarily to manage XMLUI
from functools import partial
import socket
-import SocketServer
+import socketserver
import errno
__commands__ = ["Pipe"]
@@ -41,7 +41,7 @@ class PipeOut(base.CommandBase):
def add_parser_options(self):
self.parser.add_argument(
- "jid", type=base.unicode_decoder, help=_("the destination jid")
+ "jid", help=_("the destination jid")
)
def streamOutCb(self, port):
@@ -69,13 +69,13 @@ class PipeOut(base.CommandBase):
callback=self.streamOutCb,
errback=partial(
self.errback,
- msg=_(u"can't start stream: {}"),
+ msg=_("can't start stream: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
-class StreamServer(SocketServer.BaseRequestHandler):
+class StreamServer(socketserver.BaseRequestHandler):
def handle(self):
while True:
data = self.request.recv(4096)
@@ -100,7 +100,6 @@ class PipeIn(base.CommandAnswering):
def add_parser_options(self):
self.parser.add_argument(
"jids",
- type=base.unicode_decoder,
nargs="*",
help=_('Jids accepted (none means "accept everything")'),
)
@@ -112,12 +111,12 @@ class PipeIn(base.CommandAnswering):
try:
xml_ui = action_data["xmlui"]
except KeyError:
- self.disp(_(u"Action has no XMLUI"), 1)
+ self.disp(_("Action has no XMLUI"), 1)
else:
ui = ET.fromstring(xml_ui.encode("utf-8"))
xmlui_id = ui.get("submit")
if not xmlui_id:
- self.disp(_(u"Invalid XMLUI received"), error=True)
+ self.disp(_("Invalid XMLUI received"), error=True)
return xmlui_id
def onStreamAction(self, action_data, action_id, security_limit, profile):
@@ -127,14 +126,14 @@ class PipeIn(base.CommandAnswering):
try:
from_jid = jid.JID(action_data["meta_from_jid"])
except KeyError:
- self.disp(_(u"Ignoring action without from_jid data"), 1)
+ self.disp(_("Ignoring action without from_jid data"), 1)
return
if not self.bare_jids or from_jid.bare in self.bare_jids:
host, port = "localhost", START_PORT
while True:
try:
- server = SocketServer.TCPServer((host, port), StreamServer)
+ server = socketserver.TCPServer((host, port), StreamServer)
except socket.error as e:
if e.errno == errno.EADDRINUSE:
port += 1
@@ -142,7 +141,7 @@ class PipeIn(base.CommandAnswering):
raise e
else:
break
- xmlui_data = {"answer": C.BOOL_TRUE, "port": unicode(port)}
+ xmlui_data = {"answer": C.BOOL_TRUE, "port": str(port)}
self.host.bridge.launchAction(xmlui_id, xmlui_data, profile_key=profile)
server.serve_forever()
self.host.quitFromSignal()
diff --git a/sat_frontends/jp/cmd_profile.py b/sat_frontends/jp/cmd_profile.py
index 9c4b086f..eeeb3065 100644
--- a/sat_frontends/jp/cmd_profile.py
+++ b/sat_frontends/jp/cmd_profile.py
@@ -38,7 +38,7 @@ class ProfileConnect(base.CommandBase):
def __init__(self, host):
# it's weird to have a command named "connect" with need_connect=False, but it can be handy to be able
# to launch just the session, so some paradoxes don't hurt
- super(ProfileConnect, self).__init__(host, 'connect', need_connect=False, help=(u'connect a profile'))
+ super(ProfileConnect, self).__init__(host, 'connect', need_connect=False, help=('connect a profile'))
def add_parser_options(self):
pass
@@ -47,7 +47,7 @@ class ProfileConnect(base.CommandBase):
class ProfileDisconnect(base.CommandBase):
def __init__(self, host):
- super(ProfileDisconnect, self).__init__(host, 'disconnect', need_connect=False, help=(u'disconnect a profile'))
+ super(ProfileDisconnect, self).__init__(host, 'disconnect', need_connect=False, help=('disconnect a profile'))
self.need_loop = True
def add_parser_options(self):
@@ -59,32 +59,32 @@ class ProfileDisconnect(base.CommandBase):
class ProfileDefault(base.CommandBase):
def __init__(self, host):
- super(ProfileDefault, self).__init__(host, 'default', use_profile=False, help=(u'print default profile'))
+ super(ProfileDefault, self).__init__(host, 'default', use_profile=False, help=('print default profile'))
def add_parser_options(self):
pass
def start(self):
- print self.host.bridge.profileNameGet('@DEFAULT@')
+ print(self.host.bridge.profileNameGet('@DEFAULT@'))
class ProfileDelete(base.CommandBase):
def __init__(self, host):
- super(ProfileDelete, self).__init__(host, 'delete', use_profile=False, help=(u'delete a profile'))
+ super(ProfileDelete, self).__init__(host, 'delete', use_profile=False, help=('delete a profile'))
def add_parser_options(self):
self.parser.add_argument('profile', type=str, help=PROFILE_HELP)
- self.parser.add_argument('-f', '--force', action='store_true', help=_(u'delete profile without confirmation'))
+ self.parser.add_argument('-f', '--force', action='store_true', help=_('delete profile without confirmation'))
def start(self):
if self.args.profile not in self.host.bridge.profilesListGet():
log.error("Profile %s doesn't exist." % self.args.profile)
self.host.quit(1)
if not self.args.force:
- message = u"Are you sure to delete profile [{}] ?".format(self.args.profile)
- res = raw_input("{} (y/N)? ".format(message))
+ message = "Are you sure to delete profile [{}] ?".format(self.args.profile)
+ res = input("{} (y/N)? ".format(message))
if res not in ("y", "Y"):
- self.disp(_(u"Profile deletion cancelled"))
+ self.disp(_("Profile deletion cancelled"))
self.host.quit(2)
self.host.bridge.asyncDeleteProfile(self.args.profile, callback=lambda __: None)
@@ -92,19 +92,19 @@ class ProfileDelete(base.CommandBase):
class ProfileInfo(base.CommandBase):
def __init__(self, host):
- super(ProfileInfo, self).__init__(host, 'info', need_connect=False, help=_(u'get information about a profile'))
+ super(ProfileInfo, self).__init__(host, 'info', need_connect=False, help=_('get information about a profile'))
self.need_loop = True
- self.to_show = [(_(u"jid"), "Connection", "JabberID"),]
+ self.to_show = [(_("jid"), "Connection", "JabberID"),]
self.largest = max([len(item[0]) for item in self.to_show])
def add_parser_options(self):
- self.parser.add_argument('--show-password', action='store_true', help=_(u'show the XMPP password IN CLEAR TEXT'))
+ self.parser.add_argument('--show-password', action='store_true', help=_('show the XMPP password IN CLEAR TEXT'))
def showNextValue(self, label=None, category=None, value=None):
"""Show next value from self.to_show and quit on last one"""
if label is not None:
- print((u"{label:<"+unicode(self.largest+2)+"}{value}").format(label=label+": ", value=value))
+ print((("{label:<"+str(self.largest+2)+"}{value}").format(label=label+": ", value=value)))
try:
label, category, name = self.to_show.pop(0)
except IndexError:
@@ -115,18 +115,18 @@ class ProfileInfo(base.CommandBase):
def start(self):
if self.args.show_password:
- self.to_show.append((_(u"XMPP password"), "Connection", "Password"))
+ self.to_show.append((_("XMPP password"), "Connection", "Password"))
self.showNextValue()
class ProfileList(base.CommandBase):
def __init__(self, host):
- super(ProfileList, self).__init__(host, 'list', use_profile=False, use_output='list', help=(u'list profiles'))
+ super(ProfileList, self).__init__(host, 'list', use_profile=False, use_output='list', help=('list profiles'))
def add_parser_options(self):
group = self.parser.add_mutually_exclusive_group()
- group.add_argument('-c', '--clients', action='store_true', help=_(u'get clients profiles only'))
- group.add_argument('-C', '--components', action='store_true', help=(u'get components profiles only'))
+ group.add_argument('-c', '--clients', action='store_true', help=_('get clients profiles only'))
+ group.add_argument('-C', '--components', action='store_true', help=('get components profiles only'))
def start(self):
@@ -141,17 +141,17 @@ class ProfileList(base.CommandBase):
class ProfileCreate(base.CommandBase):
def __init__(self, host):
- super(ProfileCreate, self).__init__(host, 'create', use_profile=False, help=(u'create a new profile'))
+ super(ProfileCreate, self).__init__(host, 'create', use_profile=False, help=('create a new profile'))
self.need_loop = True
def add_parser_options(self):
- self.parser.add_argument('profile', type=str, help=_(u'the name of the profile'))
- self.parser.add_argument('-p', '--password', type=str, default='', help=_(u'the password of the profile'))
- self.parser.add_argument('-j', '--jid', type=str, help=_(u'the jid of the profile'))
- self.parser.add_argument('-x', '--xmpp-password', type=str, help=_(u'the password of the XMPP account (use profile password if not specified)'),
+ self.parser.add_argument('profile', type=str, help=_('the name of the profile'))
+ self.parser.add_argument('-p', '--password', type=str, default='', help=_('the password of the profile'))
+ self.parser.add_argument('-j', '--jid', type=str, help=_('the jid of the profile'))
+ self.parser.add_argument('-x', '--xmpp-password', type=str, help=_('the password of the XMPP account (use profile password if not specified)'),
metavar='PASSWORD')
- self.parser.add_argument('-C', '--component', type=base.unicode_decoder, default='',
- help=_(u'set to component import name (entry point) if this is a component'))
+ self.parser.add_argument('-C', '--component', default='',
+ help=_('set to component import name (entry point) if this is a component'))
def _session_started(self, __):
if self.args.jid:
@@ -172,22 +172,22 @@ class ProfileCreate(base.CommandBase):
self.host.bridge.profileCreate(self.args.profile, self.args.password, self.args.component,
callback=self._profile_created,
errback=partial(self.errback,
- msg=_(u"can't create profile: {}"),
+ msg=_("can't create profile: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK))
class ProfileModify(base.CommandBase):
def __init__(self, host):
- super(ProfileModify, self).__init__(host, 'modify', need_connect=False, help=_(u'modify an existing profile'))
+ super(ProfileModify, self).__init__(host, 'modify', need_connect=False, help=_('modify an existing profile'))
def add_parser_options(self):
profile_pwd_group = self.parser.add_mutually_exclusive_group()
- profile_pwd_group.add_argument('-w', '--password', type=base.unicode_decoder, help=_(u'change the password of the profile'))
- profile_pwd_group.add_argument('--disable-password', action='store_true', help=_(u'disable profile password (dangerous!)'))
- self.parser.add_argument('-j', '--jid', type=base.unicode_decoder, help=_(u'the jid of the profile'))
- self.parser.add_argument('-x', '--xmpp-password', type=base.unicode_decoder, help=_(u'change the password of the XMPP account'),
+ profile_pwd_group.add_argument('-w', '--password', help=_('change the password of the profile'))
+ profile_pwd_group.add_argument('--disable-password', action='store_true', help=_('disable profile password (dangerous!)'))
+ self.parser.add_argument('-j', '--jid', help=_('the jid of the profile'))
+ self.parser.add_argument('-x', '--xmpp-password', help=_('change the password of the XMPP account'),
metavar='PASSWORD')
- self.parser.add_argument('-D', '--default', action='store_true', help=_(u'set as default profile'))
+ self.parser.add_argument('-D', '--default', action='store_true', help=_('set as default profile'))
def start(self):
if self.args.disable_password:
@@ -206,4 +206,4 @@ class Profile(base.CommandBase):
subcommands = (ProfileConnect, ProfileDisconnect, ProfileCreate, ProfileDefault, ProfileDelete, ProfileInfo, ProfileList, ProfileModify)
def __init__(self, host):
- super(Profile, self).__init__(host, 'profile', use_profile=False, help=_(u'profile commands'))
+ super(Profile, self).__init__(host, 'profile', use_profile=False, help=_('profile commands'))
diff --git a/sat_frontends/jp/cmd_pubsub.py b/sat_frontends/jp/cmd_pubsub.py
index dba84388..f9e63a91 100644
--- a/sat_frontends/jp/cmd_pubsub.py
+++ b/sat_frontends/jp/cmd_pubsub.py
@@ -18,7 +18,7 @@
# along with this program. If not, see
.
-import base
+from . import base
from sat.core.i18n import _
from sat.core import exceptions
from sat_frontends.jp.constants import Const as C
@@ -37,7 +37,7 @@ import sys
__commands__ = ["Pubsub"]
-PUBSUB_TMP_DIR = u"pubsub"
+PUBSUB_TMP_DIR = "pubsub"
PUBSUB_SCHEMA_TMP_DIR = PUBSUB_TMP_DIR + "_schema"
ALLOWED_SUBSCRIPTIONS_OWNER = ("subscribed", "pending", "none")
@@ -53,7 +53,7 @@ class NodeInfo(base.CommandBase):
use_output=C.OUTPUT_DICT,
use_pubsub=True,
pubsub_flags={C.NODE},
- help=_(u"retrieve node configuration"),
+ help=_("retrieve node configuration"),
)
self.need_loop = True
@@ -61,29 +61,28 @@ class NodeInfo(base.CommandBase):
self.parser.add_argument(
"-k",
"--key",
- type=base.unicode_decoder,
action="append",
dest="keys",
- help=_(u"data key to filter"),
+ help=_("data key to filter"),
)
def removePrefix(self, key):
- return key[7:] if key.startswith(u"pubsub#") else key
+ return key[7:] if key.startswith("pubsub#") else key
def filterKey(self, key):
- return any((key == k or key == u"pubsub#" + k) for k in self.args.keys)
+ return any((key == k or key == "pubsub#" + k) for k in self.args.keys)
def psNodeConfigurationGetCb(self, config_dict):
key_filter = (lambda k: True) if not self.args.keys else self.filterKey
config_dict = {
- self.removePrefix(k): v for k, v in config_dict.iteritems() if key_filter(k)
+ self.removePrefix(k): v for k, v in config_dict.items() if key_filter(k)
}
self.output(config_dict)
self.host.quit()
def psNodeConfigurationGetEb(self, failure_):
self.disp(
- u"can't get node configuration: {reason}".format(reason=failure_), error=True
+ "can't get node configuration: {reason}".format(reason=failure_), error=True
)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
@@ -107,7 +106,7 @@ class NodeCreate(base.CommandBase):
use_pubsub=True,
pubsub_flags={C.NODE},
use_verbose=True,
- help=_(u"create a node"),
+ help=_("create a node"),
)
self.need_loop = True
@@ -115,36 +114,35 @@ class NodeCreate(base.CommandBase):
self.parser.add_argument(
"-f",
"--field",
- type=base.unicode_decoder,
action="append",
nargs=2,
dest="fields",
default=[],
- metavar=(u"KEY", u"VALUE"),
- help=_(u"configuration field to set"),
+ metavar=("KEY", "VALUE"),
+ help=_("configuration field to set"),
)
self.parser.add_argument(
"-F",
"--full-prefix",
action="store_true",
- help=_(u'don\'t prepend "pubsub#" prefix to field names'),
+ help=_('don\'t prepend "pubsub#" prefix to field names'),
)
def psNodeCreateCb(self, node_id):
if self.host.verbosity:
- announce = _(u"node created successfully: ")
+ announce = _("node created successfully: ")
else:
- announce = u""
+ announce = ""
self.disp(announce + node_id)
self.host.quit()
def psNodeCreateEb(self, failure_):
- self.disp(u"can't create: {reason}".format(reason=failure_), error=True)
+ self.disp("can't create: {reason}".format(reason=failure_), error=True)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
def start(self):
if not self.args.full_prefix:
- options = {u"pubsub#" + k: v for k, v in self.args.fields}
+ options = {"pubsub#" + k: v for k, v in self.args.fields}
else:
options = dict(self.args.fields)
self.host.bridge.psNodeCreate(
@@ -155,7 +153,7 @@ class NodeCreate(base.CommandBase):
callback=self.psNodeCreateCb,
errback=partial(
self.errback,
- msg=_(u"can't create node: {}"),
+ msg=_("can't create node: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -169,7 +167,7 @@ class NodePurge(base.CommandBase):
"purge",
use_pubsub=True,
pubsub_flags={C.NODE},
- help=_(u"purge a node (i.e. remove all items from it)"),
+ help=_("purge a node (i.e. remove all items from it)"),
)
self.need_loop = True
@@ -178,26 +176,26 @@ class NodePurge(base.CommandBase):
"-f",
"--force",
action="store_true",
- help=_(u"purge node without confirmation"),
+ help=_("purge node without confirmation"),
)
def psNodePurgeCb(self):
- self.disp(_(u"node [{node}] purged successfully").format(node=self.args.node))
+ self.disp(_("node [{node}] purged successfully").format(node=self.args.node))
self.host.quit()
def start(self):
if not self.args.force:
if not self.args.service:
- message = _(u"Are you sure to purge PEP node [{node_id}]? "
- u"This will delete ALL items from it!").format(
+ message = _("Are you sure to purge PEP node [{node_id}]? "
+ "This will delete ALL items from it!").format(
node_id=self.args.node
)
else:
message = _(
- u"Are you sure to delete node [{node_id}] on service [{service}]? "
- u"This will delete ALL items from it!"
+ "Are you sure to delete node [{node_id}] on service [{service}]? "
+ "This will delete ALL items from it!"
).format(node_id=self.args.node, service=self.args.service)
- self.host.confirmOrQuit(message, _(u"node purge cancelled"))
+ self.host.confirmOrQuit(message, _("node purge cancelled"))
self.host.bridge.psNodePurge(
self.args.service,
@@ -206,7 +204,7 @@ class NodePurge(base.CommandBase):
callback=self.psNodePurgeCb,
errback=partial(
self.errback,
- msg=_(u"can't purge node: {}"),
+ msg=_("can't purge node: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -220,7 +218,7 @@ class NodeDelete(base.CommandBase):
"delete",
use_pubsub=True,
pubsub_flags={C.NODE},
- help=_(u"delete a node"),
+ help=_("delete a node"),
)
self.need_loop = True
@@ -229,24 +227,24 @@ class NodeDelete(base.CommandBase):
"-f",
"--force",
action="store_true",
- help=_(u"delete node without confirmation"),
+ help=_("delete node without confirmation"),
)
def psNodeDeleteCb(self):
- self.disp(_(u"node [{node}] deleted successfully").format(node=self.args.node))
+ self.disp(_("node [{node}] deleted successfully").format(node=self.args.node))
self.host.quit()
def start(self):
if not self.args.force:
if not self.args.service:
- message = _(u"Are you sure to delete PEP node [{node_id}] ?").format(
+ message = _("Are you sure to delete PEP node [{node_id}] ?").format(
node_id=self.args.node
)
else:
message = _(
- u"Are you sure to delete node [{node_id}] on service [{service}] ?"
+ "Are you sure to delete node [{node_id}] on service [{service}] ?"
).format(node_id=self.args.node, service=self.args.service)
- self.host.confirmOrQuit(message, _(u"node deletion cancelled"))
+ self.host.confirmOrQuit(message, _("node deletion cancelled"))
self.host.bridge.psNodeDelete(
self.args.service,
@@ -255,7 +253,7 @@ class NodeDelete(base.CommandBase):
callback=self.psNodeDeleteCb,
errback=partial(
self.errback,
- msg=_(u"can't delete node: {}"),
+ msg=_("can't delete node: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -271,7 +269,7 @@ class NodeSet(base.CommandBase):
use_pubsub=True,
pubsub_flags={C.NODE},
use_verbose=True,
- help=_(u"set node configuration"),
+ help=_("set node configuration"),
)
self.need_loop = True
@@ -279,28 +277,27 @@ class NodeSet(base.CommandBase):
self.parser.add_argument(
"-f",
"--field",
- type=base.unicode_decoder,
action="append",
nargs=2,
dest="fields",
required=True,
- metavar=(u"KEY", u"VALUE"),
- help=_(u"configuration field to set (required)"),
+ metavar=("KEY", "VALUE"),
+ help=_("configuration field to set (required)"),
)
def psNodeConfigurationSetCb(self):
- self.disp(_(u"node configuration successful"), 1)
+ self.disp(_("node configuration successful"), 1)
self.host.quit()
def psNodeConfigurationSetEb(self, failure_):
self.disp(
- u"can't set node configuration: {reason}".format(reason=failure_), error=True
+ "can't set node configuration: {reason}".format(reason=failure_), error=True
)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
def getKeyName(self, k):
- if not k.startswith(u"pubsub#"):
- return u"pubsub#" + k
+ if not k.startswith("pubsub#"):
+ return "pubsub#" + k
else:
return k
@@ -323,7 +320,7 @@ class NodeImport(base.CommandBase):
"import",
use_pubsub=True,
pubsub_flags={C.NODE},
- help=_(u"import raw XML to a node"),
+ help=_("import raw XML to a node"),
)
self.need_loop = True
@@ -331,18 +328,18 @@ class NodeImport(base.CommandBase):
self.parser.add_argument(
"--admin",
action="store_true",
- help=_(u"do a pubsub admin request, needed to change publisher"),
+ help=_("do a pubsub admin request, needed to change publisher"),
)
self.parser.add_argument(
"import_file",
- type=file,
- help=_(u"path to the XML file with data to import. The file must contain "
- u"whole XML of each item to import."),
+ type=argparse.FileType(),
+ help=_("path to the XML file with data to import. The file must contain "
+ "whole XML of each item to import."),
)
def psItemsSendCb(self, item_ids):
- self.disp(_(u'items published with id(s) {item_ids}').format(
- item_ids=u', '.join(item_ids)))
+ self.disp(_('items published with id(s) {item_ids}').format(
+ item_ids=', '.join(item_ids)))
self.host.quit()
def start(self):
@@ -364,7 +361,7 @@ class NodeImport(base.CommandBase):
if not all([i.tag == '{http://jabber.org/protocol/pubsub}item' for i in element]):
self.disp(
- _(u"You are not using list of pubsub items, we can't import this file"),
+ _("You are not using list of pubsub items, we can't import this file"),
error=True)
self.host.quit(C.EXIT_DATA_ERROR)
@@ -374,28 +371,28 @@ class NodeImport(base.CommandBase):
self.args.service,
self.args.node,
items,
- u"",
+ "",
self.profile,
callback=partial(self.psItemsSendCb),
errback=partial(
self.errback,
- msg=_(u"can't send item: {}"),
+ msg=_("can't send item: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
else:
- self.disp(_(u"Items are imported without using admin mode, publisher can't "
- u"be changed"))
+ self.disp(_("Items are imported without using admin mode, publisher can't "
+ "be changed"))
self.host.bridge.psItemsSend(
self.args.service,
self.args.node,
items,
- u"",
+ "",
self.profile,
callback=partial(self.psItemsSendCb),
errback=partial(
self.errback,
- msg=_(u"can't send item: {}"),
+ msg=_("can't send item: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -410,7 +407,7 @@ class NodeAffiliationsGet(base.CommandBase):
use_output=C.OUTPUT_DICT,
use_pubsub=True,
pubsub_flags={C.NODE},
- help=_(u"retrieve node affiliations (for node owner)"),
+ help=_("retrieve node affiliations (for node owner)"),
)
self.need_loop = True
@@ -423,7 +420,7 @@ class NodeAffiliationsGet(base.CommandBase):
def psNodeAffiliationsGetEb(self, failure_):
self.disp(
- u"can't get node affiliations: {reason}".format(reason=failure_), error=True
+ "can't get node affiliations: {reason}".format(reason=failure_), error=True
)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
@@ -446,7 +443,7 @@ class NodeAffiliationsSet(base.CommandBase):
use_pubsub=True,
pubsub_flags={C.NODE},
use_verbose=True,
- help=_(u"set affiliations (for node owner)"),
+ help=_("set affiliations (for node owner)"),
)
self.need_loop = True
@@ -459,19 +456,18 @@ class NodeAffiliationsSet(base.CommandBase):
dest="affiliations",
metavar=("JID", "AFFILIATION"),
required=True,
- type=base.unicode_decoder,
action="append",
nargs=2,
- help=_(u"entity/affiliation couple(s)"),
+ help=_("entity/affiliation couple(s)"),
)
def psNodeAffiliationsSetCb(self):
- self.disp(_(u"affiliations have been set"), 1)
+ self.disp(_("affiliations have been set"), 1)
self.host.quit()
def psNodeAffiliationsSetEb(self, failure_):
self.disp(
- u"can't set node affiliations: {reason}".format(reason=failure_), error=True
+ "can't set node affiliations: {reason}".format(reason=failure_), error=True
)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
@@ -495,7 +491,7 @@ class NodeAffiliations(base.CommandBase):
host,
"affiliations",
use_profile=False,
- help=_(u"set or retrieve node affiliations"),
+ help=_("set or retrieve node affiliations"),
)
@@ -508,7 +504,7 @@ class NodeSubscriptionsGet(base.CommandBase):
use_output=C.OUTPUT_DICT,
use_pubsub=True,
pubsub_flags={C.NODE},
- help=_(u"retrieve node subscriptions (for node owner)"),
+ help=_("retrieve node subscriptions (for node owner)"),
)
self.need_loop = True
@@ -521,7 +517,7 @@ class NodeSubscriptionsGet(base.CommandBase):
def psNodeSubscriptionsGetEb(self, failure_):
self.disp(
- u"can't get node subscriptions: {reason}".format(reason=failure_), error=True
+ "can't get node subscriptions: {reason}".format(reason=failure_), error=True
)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
@@ -552,8 +548,8 @@ class StoreSubscriptionAction(argparse.Action):
subscription = "subscribed"
if subscription not in ALLOWED_SUBSCRIPTIONS_OWNER:
parser.error(
- _(u"subscription must be one of {}").format(
- u", ".join(ALLOWED_SUBSCRIPTIONS_OWNER)
+ _("subscription must be one of {}").format(
+ ", ".join(ALLOWED_SUBSCRIPTIONS_OWNER)
)
)
dest_dict[jid_s] = subscription
@@ -568,7 +564,7 @@ class NodeSubscriptionsSet(base.CommandBase):
use_pubsub=True,
pubsub_flags={C.NODE},
use_verbose=True,
- help=_(u"set/modify subscriptions (for node owner)"),
+ help=_("set/modify subscriptions (for node owner)"),
)
self.need_loop = True
@@ -583,18 +579,17 @@ class NodeSubscriptionsSet(base.CommandBase):
nargs="+",
metavar=("JID [SUSBSCRIPTION]"),
required=True,
- type=base.unicode_decoder,
action=StoreSubscriptionAction,
- help=_(u"entity/subscription couple(s)"),
+ help=_("entity/subscription couple(s)"),
)
def psNodeSubscriptionsSetCb(self):
- self.disp(_(u"subscriptions have been set"), 1)
+ self.disp(_("subscriptions have been set"), 1)
self.host.quit()
def psNodeSubscriptionsSetEb(self, failure_):
self.disp(
- u"can't set node subscriptions: {reason}".format(reason=failure_), error=True
+ "can't set node subscriptions: {reason}".format(reason=failure_), error=True
)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
@@ -617,7 +612,7 @@ class NodeSubscriptions(base.CommandBase):
host,
"subscriptions",
use_profile=False,
- help=_(u"get or modify node subscriptions"),
+ help=_("get or modify node subscriptions"),
)
@@ -630,15 +625,15 @@ class NodeSchemaSet(base.CommandBase):
use_pubsub=True,
pubsub_flags={C.NODE},
use_verbose=True,
- help=_(u"set/replace a schema"),
+ help=_("set/replace a schema"),
)
self.need_loop = True
def add_parser_options(self):
- self.parser.add_argument("schema", help=_(u"schema to set (must be XML)"))
+ self.parser.add_argument("schema", help=_("schema to set (must be XML)"))
def psSchemaSetCb(self):
- self.disp(_(u"schema has been set"), 1)
+ self.disp(_("schema has been set"), 1)
self.host.quit()
def start(self):
@@ -650,7 +645,7 @@ class NodeSchemaSet(base.CommandBase):
callback=self.psSchemaSetCb,
errback=partial(
self.errback,
- msg=_(u"can't set schema: {}"),
+ msg=_("can't set schema: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -668,7 +663,7 @@ class NodeSchemaEdit(base.CommandBase, common.BaseEdit):
pubsub_flags={C.NODE},
use_draft=True,
use_verbose=True,
- help=_(u"edit a schema"),
+ help=_("edit a schema"),
)
common.BaseEdit.__init__(self, self.host, PUBSUB_SCHEMA_TMP_DIR)
self.need_loop = True
@@ -677,7 +672,7 @@ class NodeSchemaEdit(base.CommandBase, common.BaseEdit):
pass
def psSchemaSetCb(self):
- self.disp(_(u"schema has been set"), 1)
+ self.disp(_("schema has been set"), 1)
self.host.quit()
def publish(self, schema):
@@ -689,7 +684,7 @@ class NodeSchemaEdit(base.CommandBase, common.BaseEdit):
callback=self.psSchemaSetCb,
errback=partial(
self.errback,
- msg=_(u"can't set schema: {}"),
+ msg=_("can't set schema: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -698,8 +693,8 @@ class NodeSchemaEdit(base.CommandBase, common.BaseEdit):
try:
from lxml import etree
except ImportError:
- self.disp(u'lxml module must be installed to use edit, please install it '
- u'with "pip install lxml"',
+ self.disp('lxml module must be installed to use edit, please install it '
+ 'with "pip install lxml"',
error=True,
)
self.host.quit(1)
@@ -722,7 +717,7 @@ class NodeSchemaEdit(base.CommandBase, common.BaseEdit):
callback=self.psSchemaGetCb,
errback=partial(
self.errback,
- msg=_(u"can't edit schema: {}"),
+ msg=_("can't edit schema: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -738,7 +733,7 @@ class NodeSchemaGet(base.CommandBase):
use_pubsub=True,
pubsub_flags={C.NODE},
use_verbose=True,
- help=_(u"get schema"),
+ help=_("get schema"),
)
self.need_loop = True
@@ -747,7 +742,7 @@ class NodeSchemaGet(base.CommandBase):
def psSchemaGetCb(self, schema):
if not schema:
- self.disp(_(u"no schema found"), 1)
+ self.disp(_("no schema found"), 1)
self.host.quit(1)
self.output(schema)
self.host.quit()
@@ -760,7 +755,7 @@ class NodeSchemaGet(base.CommandBase):
callback=self.psSchemaGetCb,
errback=partial(
self.errback,
- msg=_(u"can't get schema: {}"),
+ msg=_("can't get schema: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -771,7 +766,7 @@ class NodeSchema(base.CommandBase):
def __init__(self, host):
super(NodeSchema, self).__init__(
- host, "schema", use_profile=False, help=_(u"data schema manipulation")
+ host, "schema", use_profile=False, help=_("data schema manipulation")
)
@@ -802,24 +797,23 @@ class Set(base.CommandBase):
"set",
use_pubsub=True,
pubsub_flags={C.NODE},
- help=_(u"publish a new item or update an existing one"),
+ help=_("publish a new item or update an existing one"),
)
self.need_loop = True
def add_parser_options(self):
self.parser.add_argument(
"item",
- type=base.unicode_decoder,
nargs="?",
- default=u"",
- help=_(u"id, URL of the item to update, keyword, or nothing for new item"),
+ default="",
+ help=_("id, URL of the item to update, keyword, or nothing for new item"),
)
def psItemsSendCb(self, published_id):
if published_id:
- self.disp(u"Item published at {pub_id}".format(pub_id=published_id))
+ self.disp("Item published at {pub_id}".format(pub_id=published_id))
else:
- self.disp(u"Item published")
+ self.disp("Item published")
self.host.quit(C.EXIT_OK)
def start(self):
@@ -837,7 +831,7 @@ class Set(base.CommandBase):
callback=self.psItemsSendCb,
errback=partial(
self.errback,
- msg=_(u"can't send item: {}"),
+ msg=_("can't send item: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -852,7 +846,7 @@ class Get(base.CommandBase):
use_output=C.OUTPUT_LIST_XML,
use_pubsub=True,
pubsub_flags={C.NODE, C.MULTI_ITEMS},
- help=_(u"get pubsub item(s)"),
+ help=_("get pubsub item(s)"),
)
self.need_loop = True
@@ -860,9 +854,8 @@ class Get(base.CommandBase):
self.parser.add_argument(
"-S",
"--sub-id",
- type=base.unicode_decoder,
- default=u"",
- help=_(u"subscription id"),
+ default="",
+ help=_("subscription id"),
)
# TODO: a key(s) argument to select keys to display
# TODO: add MAM filters
@@ -872,7 +865,7 @@ class Get(base.CommandBase):
self.host.quit(C.EXIT_OK)
def psItemsGetEb(self, failure_):
- self.disp(u"can't get pubsub items: {reason}".format(reason=failure_), error=True)
+ self.disp("can't get pubsub items: {reason}".format(reason=failure_), error=True)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
def start(self):
@@ -897,30 +890,30 @@ class Delete(base.CommandBase):
"delete",
use_pubsub=True,
pubsub_flags={C.NODE, C.ITEM, C.SINGLE_ITEM},
- help=_(u"delete an item"),
+ help=_("delete an item"),
)
self.need_loop = True
def add_parser_options(self):
self.parser.add_argument(
- "-f", "--force", action="store_true", help=_(u"delete without confirmation")
+ "-f", "--force", action="store_true", help=_("delete without confirmation")
)
self.parser.add_argument(
- "-N", "--notify", action="store_true", help=_(u"notify deletion")
+ "-N", "--notify", action="store_true", help=_("notify deletion")
)
def psItemsDeleteCb(self):
- self.disp(_(u"item {item_id} has been deleted").format(item_id=self.args.item))
+ self.disp(_("item {item_id} has been deleted").format(item_id=self.args.item))
self.host.quit(C.EXIT_OK)
def start(self):
if not self.args.item:
- self.parser.error(_(u"You need to specify an item to delete"))
+ self.parser.error(_("You need to specify an item to delete"))
if not self.args.force:
- message = _(u"Are you sure to delete item {item_id} ?").format(
+ message = _("Are you sure to delete item {item_id} ?").format(
item_id=self.args.item
)
- self.host.confirmOrQuit(message, _(u"item deletion cancelled"))
+ self.host.confirmOrQuit(message, _("item deletion cancelled"))
self.host.bridge.psRetractItem(
self.args.service,
self.args.node,
@@ -930,7 +923,7 @@ class Delete(base.CommandBase):
callback=self.psItemsDeleteCb,
errback=partial(
self.errback,
- msg=_(u"can't delete item: {}"),
+ msg=_("can't delete item: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -946,7 +939,7 @@ class Edit(base.CommandBase, common.BaseEdit):
use_pubsub=True,
pubsub_flags={C.NODE, C.SINGLE_ITEM},
use_draft=True,
- help=_(u"edit an existing or new pubsub item"),
+ help=_("edit an existing or new pubsub item"),
)
common.BaseEdit.__init__(self, self.host, PUBSUB_TMP_DIR)
@@ -967,16 +960,16 @@ class Edit(base.CommandBase, common.BaseEdit):
self.profile,
)
if published_id:
- self.disp(u"Item published at {pub_id}".format(pub_id=published_id))
+ self.disp("Item published at {pub_id}".format(pub_id=published_id))
else:
- self.disp(u"Item published")
+ self.disp("Item published")
def getItemData(self, service, node, item):
try:
from lxml import etree
except ImportError:
- self.disp(u'lxml module must be installed to use edit, please install it '
- u'with "pip install lxml"',
+ self.disp('lxml module must be installed to use edit, please install it '
+ 'with "pip install lxml"',
error=True,
)
self.host.quit(1)
@@ -990,8 +983,8 @@ class Edit(base.CommandBase, common.BaseEdit):
try:
payload = item_elt[0]
except IndexError:
- self.disp(_(u"Item has not payload"), 1)
- return u""
+ self.disp(_("Item has not payload"), 1)
+ return ""
return etree.tostring(payload, encoding="unicode", pretty_print=True), item_id
def start(self):
@@ -1010,7 +1003,7 @@ class Subscribe(base.CommandBase):
use_pubsub=True,
pubsub_flags={C.NODE},
use_verbose=True,
- help=_(u"subscribe to a node"),
+ help=_("subscribe to a node"),
)
self.need_loop = True
@@ -1018,9 +1011,9 @@ class Subscribe(base.CommandBase):
pass
def psSubscribeCb(self, sub_id):
- self.disp(_(u"subscription done"), 1)
+ self.disp(_("subscription done"), 1)
if sub_id:
- self.disp(_(u"subscription id: {sub_id}").format(sub_id=sub_id))
+ self.disp(_("subscription id: {sub_id}").format(sub_id=sub_id))
self.host.quit()
def start(self):
@@ -1032,7 +1025,7 @@ class Subscribe(base.CommandBase):
callback=self.psSubscribeCb,
errback=partial(
self.errback,
- msg=_(u"can't subscribe to node: {}"),
+ msg=_("can't subscribe to node: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -1049,7 +1042,7 @@ class Unsubscribe(base.CommandBase):
use_pubsub=True,
pubsub_flags={C.NODE},
use_verbose=True,
- help=_(u"unsubscribe from a node"),
+ help=_("unsubscribe from a node"),
)
self.need_loop = True
@@ -1057,7 +1050,7 @@ class Unsubscribe(base.CommandBase):
pass
def psUnsubscribeCb(self):
- self.disp(_(u"subscription removed"), 1)
+ self.disp(_("subscription removed"), 1)
self.host.quit()
def start(self):
@@ -1068,7 +1061,7 @@ class Unsubscribe(base.CommandBase):
callback=self.psUnsubscribeCb,
errback=partial(
self.errback,
- msg=_(u"can't unsubscribe from node: {}"),
+ msg=_("can't unsubscribe from node: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -1082,7 +1075,7 @@ class Subscriptions(base.CommandBase):
"subscriptions",
use_output=C.OUTPUT_LIST_DICT,
use_pubsub=True,
- help=_(u"retrieve all subscriptions on a service"),
+ help=_("retrieve all subscriptions on a service"),
)
self.need_loop = True
@@ -1101,7 +1094,7 @@ class Subscriptions(base.CommandBase):
callback=self.psSubscriptionsGetCb,
errback=partial(
self.errback,
- msg=_(u"can't retrieve subscriptions: {}"),
+ msg=_("can't retrieve subscriptions: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -1115,7 +1108,7 @@ class Affiliations(base.CommandBase):
"affiliations",
use_output=C.OUTPUT_DICT,
use_pubsub=True,
- help=_(u"retrieve all affiliations on a service"),
+ help=_("retrieve all affiliations on a service"),
)
self.need_loop = True
@@ -1128,7 +1121,7 @@ class Affiliations(base.CommandBase):
def psAffiliationsGetEb(self, failure_):
self.disp(
- u"can't get node affiliations: {reason}".format(reason=failure_), error=True
+ "can't get node affiliations: {reason}".format(reason=failure_), error=True
)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
@@ -1150,7 +1143,7 @@ class Search(base.CommandBase):
"""
RE_FLAGS = re.MULTILINE | re.UNICODE
- EXEC_ACTIONS = (u"exec", u"external")
+ EXEC_ACTIONS = ("exec", "external")
def __init__(self, host):
# FIXME: C.NO_MAX is not needed here, and this can be globally removed from consts
@@ -1164,7 +1157,7 @@ class Search(base.CommandBase):
use_pubsub=True,
pubsub_flags={C.MULTI_ITEMS, C.NO_MAX},
use_verbose=True,
- help=_(u"search items corresponding to filters"),
+ help=_("search items corresponding to filters"),
)
self.need_loop = True
@@ -1178,7 +1171,6 @@ class Search(base.CommandBase):
return self._etree
def filter_opt(self, value, type_):
- value = base.unicode_decoder(value)
return (type_, value)
def filter_flag(self, value, type_):
@@ -1191,16 +1183,16 @@ class Search(base.CommandBase):
"--max-depth",
type=int,
default=0,
- help=_(u"maximum depth of recursion (will search linked nodes if > 0, "
- u"DEFAULT: 0)"),
+ help=_("maximum depth of recursion (will search linked nodes if > 0, "
+ "DEFAULT: 0)"),
)
self.parser.add_argument(
"-M",
"--node-max",
type=int,
default=30,
- help=_(u"maximum number of items to get per node ({} to get all items, "
- u"DEFAULT: 30)".format( C.NO_LIMIT)),
+ help=_("maximum number of items to get per node ({} to get all items, "
+ "DEFAULT: 30)".format( C.NO_LIMIT)),
)
self.parser.add_argument(
"-N",
@@ -1209,17 +1201,17 @@ class Search(base.CommandBase):
nargs=2,
default=[],
metavar="NAME NAMESPACE",
- help=_(u"namespace to use for xpath"),
+ help=_("namespace to use for xpath"),
)
# filters
- filter_text = partial(self.filter_opt, type_=u"text")
- filter_re = partial(self.filter_opt, type_=u"regex")
- filter_xpath = partial(self.filter_opt, type_=u"xpath")
- filter_python = partial(self.filter_opt, type_=u"python")
+ filter_text = partial(self.filter_opt, type_="text")
+ filter_re = partial(self.filter_opt, type_="regex")
+ filter_xpath = partial(self.filter_opt, type_="xpath")
+ filter_python = partial(self.filter_opt, type_="python")
filters = self.parser.add_argument_group(
- _(u"filters"),
- _(u"only items corresponding to following filters will be kept"),
+ _("filters"),
+ _("only items corresponding to following filters will be kept"),
)
filters.add_argument(
"-t",
@@ -1228,7 +1220,7 @@ class Search(base.CommandBase):
dest="filters",
type=filter_text,
metavar="TEXT",
- help=_(u"full text filter, item must contain this string (XML included)"),
+ help=_("full text filter, item must contain this string (XML included)"),
)
filters.add_argument(
"-r",
@@ -1237,7 +1229,7 @@ class Search(base.CommandBase):
dest="filters",
type=filter_re,
metavar="EXPRESSION",
- help=_(u"like --text but using a regular expression"),
+ help=_("like --text but using a regular expression"),
)
filters.add_argument(
"-x",
@@ -1246,7 +1238,7 @@ class Search(base.CommandBase):
dest="filters",
type=filter_xpath,
metavar="XPATH",
- help=_(u"filter items which has elements matching this xpath"),
+ help=_("filter items which has elements matching this xpath"),
)
filters.add_argument(
"-P",
@@ -1255,20 +1247,20 @@ class Search(base.CommandBase):
dest="filters",
type=filter_python,
metavar="PYTHON_CODE",
- help=_(u'Python expression which much return a bool (True to keep item, '
- u'False to reject it). "item" is raw text item, "item_xml" is '
- u'lxml\'s etree.Element'
+ help=_('Python expression which much return a bool (True to keep item, '
+ 'False to reject it). "item" is raw text item, "item_xml" is '
+ 'lxml\'s etree.Element'
),
)
# filters flags
- flag_case = partial(self.filter_flag, type_=u"ignore-case")
- flag_invert = partial(self.filter_flag, type_=u"invert")
- flag_dotall = partial(self.filter_flag, type_=u"dotall")
- flag_matching = partial(self.filter_flag, type_=u"only-matching")
+ flag_case = partial(self.filter_flag, type_="ignore-case")
+ flag_invert = partial(self.filter_flag, type_="invert")
+ flag_dotall = partial(self.filter_flag, type_="dotall")
+ flag_matching = partial(self.filter_flag, type_="only-matching")
flags = self.parser.add_argument_group(
- _(u"filters flags"),
- _(u"filters modifiers (change behaviour of following filters)"),
+ _("filters flags"),
+ _("filters modifiers (change behaviour of following filters)"),
)
flags.add_argument(
"-C",
@@ -1279,7 +1271,7 @@ class Search(base.CommandBase):
const=("ignore-case", True),
nargs="?",
metavar="BOOLEAN",
- help=_(u"(don't) ignore case in following filters (DEFAULT: case sensitive)"),
+ help=_("(don't) ignore case in following filters (DEFAULT: case sensitive)"),
)
flags.add_argument(
"-I",
@@ -1290,7 +1282,7 @@ class Search(base.CommandBase):
const=("invert", True),
nargs="?",
metavar="BOOLEAN",
- help=_(u"(don't) invert effect of following filters (DEFAULT: don't invert)"),
+ help=_("(don't) invert effect of following filters (DEFAULT: don't invert)"),
)
flags.add_argument(
"-A",
@@ -1301,7 +1293,7 @@ class Search(base.CommandBase):
const=("dotall", True),
nargs="?",
metavar="BOOLEAN",
- help=_(u"(don't) use DOTALL option for regex (DEFAULT: don't use)"),
+ help=_("(don't) use DOTALL option for regex (DEFAULT: don't use)"),
)
flags.add_argument(
"-k",
@@ -1312,7 +1304,7 @@ class Search(base.CommandBase):
const=("only-matching", True),
nargs="?",
metavar="BOOLEAN",
- help=_(u"keep only the matching part of the item"),
+ help=_("keep only the matching part of the item"),
)
# action
@@ -1321,13 +1313,13 @@ class Search(base.CommandBase):
default="print",
nargs="?",
choices=("print", "exec", "external"),
- help=_(u"action to do on found items (DEFAULT: print)"),
+ help=_("action to do on found items (DEFAULT: print)"),
)
self.parser.add_argument("command", nargs=argparse.REMAINDER)
def psItemsGetEb(self, failure_, service, node):
self.disp(
- u"can't get pubsub items at {service} (node: {node}): {reason}".format(
+ "can't get pubsub items at {service} (node: {node}): {reason}".format(
service=service, node=node, reason=failure_
),
error=True,
@@ -1357,15 +1349,15 @@ class Search(base.CommandBase):
this list will be filled while xmpp: URIs are discovered
"""
url = match.group(0)
- if url.startswith(u"xmpp"):
+ if url.startswith("xmpp"):
try:
url_data = uri.parseXMPPUri(url)
except ValueError:
return
- if url_data[u"type"] == u"pubsub":
- found_node = {u"service": url_data[u"path"], u"node": url_data[u"node"]}
- if u"item" in url_data:
- found_node[u"item"] = url_data[u"item"]
+ if url_data["type"] == "pubsub":
+ found_node = {"service": url_data["path"], "node": url_data["node"]}
+ if "item" in url_data:
+ found_node["item"] = url_data["item"]
found_nodes.append(found_node)
def getSubNodes(self, item, depth):
@@ -1376,9 +1368,9 @@ class Search(base.CommandBase):
for data in found_nodes:
self.getItems(
depth + 1,
- data[u"service"],
- data[u"node"],
- [data[u"item"]] if u"item" in data else [],
+ data["service"],
+ data["node"],
+ [data["item"]] if "item" in data else [],
)
def parseXml(self, item):
@@ -1386,8 +1378,8 @@ class Search(base.CommandBase):
return self.etree.fromstring(item)
except self.etree.XMLSyntaxError:
self.disp(
- _(u"item doesn't looks like XML, you have probably used --only-matching "
- u"somewhere before and we have no more XML"),
+ _("item doesn't looks like XML, you have probably used --only-matching "
+ "somewhere before and we have no more XML"),
error=True,
)
self.host.quit(C.EXIT_BAD_ARG)
@@ -1410,7 +1402,7 @@ class Search(base.CommandBase):
## filters
- if type_ == u"text":
+ if type_ == "text":
if ignore_case:
if value.lower() not in item.lower():
keep = False
@@ -1422,12 +1414,12 @@ class Search(base.CommandBase):
# so we raise an error
self.host.disp(
_(
- u"--only-matching used with fixed --text string, are you sure?"
+ "--only-matching used with fixed --text string, are you sure?"
),
error=True,
)
self.host.quit(C.EXIT_BAD_ARG)
- elif type_ == u"regex":
+ elif type_ == "regex":
flags = self.RE_FLAGS
if ignore_case:
flags |= re.IGNORECASE
@@ -1438,14 +1430,14 @@ class Search(base.CommandBase):
if keep and only_matching:
item = match.group()
item_xml = None
- elif type_ == u"xpath":
+ elif type_ == "xpath":
if item_xml is None:
item_xml = self.parseXml(item)
try:
elts = item_xml.xpath(value, namespaces=self.args.namespace)
except self.etree.XPathEvalError as e:
self.disp(
- _(u"can't use xpath: {reason}").format(reason=e), error=True
+ _("can't use xpath: {reason}").format(reason=e), error=True
)
self.host.quit(C.EXIT_BAD_ARG)
keep = bool(elts)
@@ -1455,33 +1447,33 @@ class Search(base.CommandBase):
item = self.etree.tostring(item_xml, encoding="unicode")
except TypeError:
# we have a string only, not an element
- item = unicode(item_xml)
+ item = str(item_xml)
item_xml = None
- elif type_ == u"python":
+ elif type_ == "python":
if item_xml is None:
item_xml = self.parseXml(item)
- cmd_ns = {u"item": item, u"item_xml": item_xml}
+ cmd_ns = {"item": item, "item_xml": item_xml}
try:
keep = eval(value, cmd_ns)
except SyntaxError as e:
- self.disp(unicode(e), error=True)
+ self.disp(str(e), error=True)
self.host.quit(C.EXIT_BAD_ARG)
## flags
- elif type_ == u"ignore-case":
+ elif type_ == "ignore-case":
ignore_case = value
- elif type_ == u"invert":
+ elif type_ == "invert":
invert = value
# we need to continue, else loop would end here
continue
- elif type_ == u"dotall":
+ elif type_ == "dotall":
dotall = value
- elif type_ == u"only-matching":
+ elif type_ == "only-matching":
only_matching = value
else:
raise exceptions.InternalError(
- _(u"unknown filter type {type}").format(type=type_)
+ _("unknown filter type {type}").format(type=type_)
)
if invert:
@@ -1497,7 +1489,7 @@ class Search(base.CommandBase):
@param item(unicode): accepted item
"""
action = self.args.action
- if action == u"print" or self.host.verbosity > 0:
+ if action == "print" or self.host.verbosity > 0:
try:
self.output(item)
except self.etree.XMLSyntaxError:
@@ -1506,10 +1498,10 @@ class Search(base.CommandBase):
self.disp(item)
if action in self.EXEC_ACTIONS:
item_elt = self.parseXml(item)
- if action == u"exec":
+ if action == "exec":
use = {
- "service": metadata[u"service"],
- "node": metadata[u"node"],
+ "service": metadata["service"],
+ "node": metadata["node"],
"item": item_elt.get("id"),
"profile": self.profile,
}
@@ -1523,12 +1515,12 @@ class Search(base.CommandBase):
cmd_args = self.args.command
self.disp(
- u"COMMAND: {command}".format(
- command=u" ".join([arg_tools.escape(a) for a in cmd_args])
+ "COMMAND: {command}".format(
+ command=" ".join([arg_tools.escape(a) for a in cmd_args])
),
2,
)
- if action == u"exec":
+ if action == "exec":
ret = subprocess.call(cmd_args)
else:
p = subprocess.Popen(cmd_args, stdin=subprocess.PIPE)
@@ -1538,7 +1530,7 @@ class Search(base.CommandBase):
self.disp(
A.color(
C.A_FAILURE,
- _(u"executed command failed with exit code {code}").format(
+ _("executed command failed with exit code {code}").format(
code=ret
),
)
@@ -1573,16 +1565,16 @@ class Search(base.CommandBase):
if self.args.command:
if self.args.action not in self.EXEC_ACTIONS:
self.parser.error(
- _(u"Command can only be used with {actions} actions").format(
- actions=u", ".join(self.EXEC_ACTIONS)
+ _("Command can only be used with {actions} actions").format(
+ actions=", ".join(self.EXEC_ACTIONS)
)
)
else:
if self.args.action in self.EXEC_ACTIONS:
- self.parser.error(_(u"you need to specify a command to execute"))
+ self.parser.error(_("you need to specify a command to execute"))
if not self.args.node:
# TODO: handle get service affiliations when node is not set
- self.parser.error(_(u"empty node is not handled yet"))
+ self.parser.error(_("empty node is not handled yet"))
# to_get is increased on each get and decreased on each answer
# when it reach 0 again, the command is finished
self.to_get = 0
@@ -1603,7 +1595,7 @@ class Transform(base.CommandBase):
"transform",
use_pubsub=True,
pubsub_flags={C.NODE, C.MULTI_ITEMS},
- help=_(u"modify items of a node using an external command/script"),
+ help=_("modify items of a node using an external command/script"),
)
self.need_loop = True
@@ -1611,39 +1603,39 @@ class Transform(base.CommandBase):
self.parser.add_argument(
"--apply",
action="store_true",
- help=_(u"apply transformation (DEFAULT: do a dry run)"),
+ help=_("apply transformation (DEFAULT: do a dry run)"),
)
self.parser.add_argument(
"--admin",
action="store_true",
- help=_(u"do a pubsub admin request, needed to change publisher"),
+ help=_("do a pubsub admin request, needed to change publisher"),
)
self.parser.add_argument(
"-I",
"--ignore_errors",
action="store_true",
help=_(
- u"if command return a non zero exit code, ignore the item and continue"),
+ "if command return a non zero exit code, ignore the item and continue"),
)
self.parser.add_argument(
"-A",
"--all",
action="store_true",
- help=_(u"get all items by looping over all pages using RSM")
+ help=_("get all items by looping over all pages using RSM")
)
self.parser.add_argument(
"command_path",
- help=_(u"path to the command to use. Will be called repetitivly with an "
- u"item as input. Output (full item XML) will be used as new one. "
- u'Return "DELETE" string to delete the item, and "SKIP" to ignore it'),
+ help=_("path to the command to use. Will be called repetitivly with an "
+ "item as input. Output (full item XML) will be used as new one. "
+ 'Return "DELETE" string to delete the item, and "SKIP" to ignore it'),
)
def psItemsSendCb(self, item_ids, metadata):
if item_ids:
- self.disp(_(u'items published with ids {item_ids}').format(
- item_ids=u', '.join(item_ids)))
+ self.disp(_('items published with ids {item_ids}').format(
+ item_ids=', '.join(item_ids)))
else:
- self.disp(_(u'items published'))
+ self.disp(_('items published'))
if self.args.all:
return self.handleNextPage(metadata)
else:
@@ -1656,30 +1648,30 @@ class Transform(base.CommandBase):
@param metadata(dict): metadata as returned by psItemsGet
"""
try:
- last = metadata[u'rsm_last']
- index = int(metadata[u'rsm_index'])
- count = int(metadata[u'rsm_count'])
+ last = metadata['rsm_last']
+ index = int(metadata['rsm_index'])
+ count = int(metadata['rsm_count'])
except KeyError:
- self.disp(_(u"Can't retrieve all items, RSM metadata not available"),
+ self.disp(_("Can't retrieve all items, RSM metadata not available"),
error=True)
self.host.quit(C.EXIT_MISSING_FEATURE)
except ValueError as e:
- self.disp(_(u"Can't retrieve all items, bad RSM metadata: {msg}")
+ self.disp(_("Can't retrieve all items, bad RSM metadata: {msg}")
.format(msg=e), error=True)
self.host.quit(C.EXIT_ERROR)
if index + self.args.rsm_max >= count:
- self.disp(_(u'All items transformed'))
+ self.disp(_('All items transformed'))
self.host.quit(0)
- self.disp(_(u'Retrieving next page ({page_idx}/{page_total})').format(
+ self.disp(_('Retrieving next page ({page_idx}/{page_total})').format(
page_idx = int(index/self.args.rsm_max) + 1,
page_total = int(count/self.args.rsm_max),
)
)
extra = self.getPubsubExtra()
- extra[u'rsm_after'] = last
+ extra['rsm_after'] = last
self.host.bridge.psItemsGet(
self.args.service,
self.args.node,
@@ -1691,7 +1683,7 @@ class Transform(base.CommandBase):
callback=self.psItemsGetCb,
errback=partial(
self.errback,
- msg=_(u"can't retrieve items: {}"),
+ msg=_("can't retrieve items: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -1708,8 +1700,8 @@ class Transform(base.CommandBase):
item_id = item_elt.get('id')
if item_id in self.items_ids:
self.disp(_(
- u"Duplicate found on item {item_id}, we have probably handled "
- u"all items.").format(item_id=item_id))
+ "Duplicate found on item {item_id}, we have probably handled "
+ "all items.").format(item_id=item_id))
self.host.quit()
self.items_ids.append(item_id)
@@ -1720,13 +1712,13 @@ class Transform(base.CommandBase):
except OSError as e:
exit_code = C.EXIT_CMD_NOT_FOUND if e.errno == 2 else C.EXIT_ERROR
e = str(e).decode('utf-8', errors="ignore")
- self.disp(u"Can't execute the command: {msg}".format(msg=e), error=True)
+ self.disp("Can't execute the command: {msg}".format(msg=e), error=True)
self.host.quit(exit_code)
cmd_std_out, cmd_std_err = p.communicate(item.encode("utf-8"))
ret = p.wait()
if ret != 0:
- self.disp(u"The command returned a non zero status while parsing the "
- u"following item:\n\n{item}".format(item=item), error=True)
+ self.disp("The command returned a non zero status while parsing the "
+ "following item:\n\n{item}".format(item=item), error=True)
if self.args.ignore_errors:
continue
else:
@@ -1738,7 +1730,7 @@ class Transform(base.CommandBase):
if cmd_std_out == "DELETE":
item_elt, __ = xml_tools.etreeParse(self, item)
item_id = item_elt.get('id')
- self.disp(_(u"Deleting item {item_id}").format(item_id=item_id))
+ self.disp(_("Deleting item {item_id}").format(item_id=item_id))
if self.args.apply:
# FIXME: we don't wait for item to be retracted which can cause
# trouble in case of error just before the end of the command
@@ -1753,7 +1745,7 @@ class Transform(base.CommandBase):
self.profile,
errback=partial(
self.errback,
- msg=_(u"can't delete item [%s]: {}" % item_id),
+ msg=_("can't delete item [%s]: {}" % item_id),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -1761,19 +1753,19 @@ class Transform(base.CommandBase):
elif cmd_std_out == "SKIP":
item_elt, __ = xml_tools.etreeParse(self, item)
item_id = item_elt.get('id')
- self.disp(_(u"Skipping item {item_id}").format(item_id=item_id))
+ self.disp(_("Skipping item {item_id}").format(item_id=item_id))
continue
element, etree = xml_tools.etreeParse(self, cmd_std_out)
# at this point command has been run and we have a etree.Element object
if element.tag not in ("item", "{http://jabber.org/protocol/pubsub}item"):
- self.disp(u"your script must return a whole item, this is not:\n{xml}"
+ self.disp("your script must return a whole item, this is not:\n{xml}"
.format(xml=etree.tostring(element, encoding="unicode")), error=True)
self.host.quit(C.EXIT_DATA_ERROR)
if not self.args.apply:
# we have a dry run, we just display filtered items
- serialised = etree.tostring(element, encoding=u'unicode',
+ serialised = etree.tostring(element, encoding='unicode',
pretty_print=True)
self.disp(serialised)
else:
@@ -1790,12 +1782,12 @@ class Transform(base.CommandBase):
self.args.service,
self.args.node,
new_items,
- u"",
+ "",
self.profile,
callback=partial(self.psItemsSendCb, metadata=metadata),
errback=partial(
self.errback,
- msg=_(u"can't send item: {}"),
+ msg=_("can't send item: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -1804,12 +1796,12 @@ class Transform(base.CommandBase):
self.args.service,
self.args.node,
new_items,
- u"",
+ "",
self.profile,
callback=partial(self.psItemsSendCb, metadata=metadata),
errback=partial(
self.errback,
- msg=_(u"can't send item: {}"),
+ msg=_("can't send item: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -1820,11 +1812,11 @@ class Transform(base.CommandBase):
self.items_ids = []
self.disp(A.color(
A.FG_RED, A.BOLD,
- u'/!\\ "--all" should be used with "--order-by creation" /!\\\n',
+ '/!\\ "--all" should be used with "--order-by creation" /!\\\n',
A.RESET,
- u"We'll update items, so order may change during transformation,\n"
- u"we'll try to mitigate that by stopping on first duplicate,\n"
- u"but this method is not safe, and some items may be missed.\n---\n"))
+ "We'll update items, so order may change during transformation,\n"
+ "we'll try to mitigate that by stopping on first duplicate,\n"
+ "but this method is not safe, and some items may be missed.\n---\n"))
else:
self.check_duplicates = False
self.host.bridge.psItemsGet(
@@ -1838,7 +1830,7 @@ class Transform(base.CommandBase):
callback=self.psItemsGetCb,
errback=partial(
self.errback,
- msg=_(u"can't retrieve items: {}"),
+ msg=_("can't retrieve items: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -1853,7 +1845,7 @@ class Uri(base.CommandBase):
use_profile=False,
use_pubsub=True,
pubsub_flags={C.NODE, C.SINGLE_ITEM},
- help=_(u"build URI"),
+ help=_("build URI"),
)
self.need_loop = True
@@ -1861,9 +1853,8 @@ class Uri(base.CommandBase):
self.parser.add_argument(
"-p",
"--profile",
- type=base.unicode_decoder,
default=C.PROF_KEY_DEFAULT,
- help=_(u"profile (used when no server is specified)"),
+ help=_("profile (used when no server is specified)"),
)
def display_uri(self, jid_):
@@ -1877,19 +1868,19 @@ class Uri(base.CommandBase):
key = "path"
if value:
uri_args[key] = value
- self.disp(uri.buildXMPPUri(u"pubsub", **uri_args))
+ self.disp(uri.buildXMPPUri("pubsub", **uri_args))
self.host.quit()
def start(self):
if not self.args.service:
self.host.bridge.asyncGetParamA(
- u"JabberID",
- u"Connection",
+ "JabberID",
+ "Connection",
profile_key=self.args.profile,
callback=self.display_uri,
errback=partial(
self.errback,
- msg=_(u"can't retrieve jid: {}"),
+ msg=_("can't retrieve jid: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -1905,7 +1896,7 @@ class HookCreate(base.CommandBase):
"create",
use_pubsub=True,
pubsub_flags={C.NODE},
- help=_(u"create a Pubsub hook"),
+ help=_("create a Pubsub hook"),
)
self.need_loop = True
@@ -1913,29 +1904,28 @@ class HookCreate(base.CommandBase):
self.parser.add_argument(
"-t",
"--type",
- default=u"python",
+ default="python",
choices=("python", "python_file", "python_code"),
- help=_(u"hook type"),
+ help=_("hook type"),
)
self.parser.add_argument(
"-P",
"--persistent",
action="store_true",
- help=_(u"make hook persistent across restarts"),
+ help=_("make hook persistent across restarts"),
)
self.parser.add_argument(
"hook_arg",
- type=base.unicode_decoder,
- help=_(u"argument of the hook (depend of the type)"),
+ help=_("argument of the hook (depend of the type)"),
)
@staticmethod
def checkArgs(self):
- if self.args.type == u"python_file":
+ if self.args.type == "python_file":
self.args.hook_arg = os.path.abspath(self.args.hook_arg)
if not os.path.isfile(self.args.hook_arg):
self.parser.error(
- _(u"{path} is not a file").format(path=self.args.hook_arg)
+ _("{path} is not a file").format(path=self.args.hook_arg)
)
def start(self):
@@ -1950,7 +1940,7 @@ class HookCreate(base.CommandBase):
callback=self.host.quit,
errback=partial(
self.errback,
- msg=_(u"can't create hook: {}"),
+ msg=_("can't create hook: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -1964,7 +1954,7 @@ class HookDelete(base.CommandBase):
"delete",
use_pubsub=True,
pubsub_flags={C.NODE},
- help=_(u"delete a Pubsub hook"),
+ help=_("delete a Pubsub hook"),
)
self.need_loop = True
@@ -1972,24 +1962,23 @@ class HookDelete(base.CommandBase):
self.parser.add_argument(
"-t",
"--type",
- default=u"",
+ default="",
choices=("", "python", "python_file", "python_code"),
- help=_(u"hook type to remove, empty to remove all (DEFAULT: remove all)"),
+ help=_("hook type to remove, empty to remove all (DEFAULT: remove all)"),
)
self.parser.add_argument(
"-a",
"--arg",
dest="hook_arg",
- type=base.unicode_decoder,
- default=u"",
+ default="",
help=_(
- u"argument of the hook to remove, empty to remove all (DEFAULT: remove all)"
+ "argument of the hook to remove, empty to remove all (DEFAULT: remove all)"
),
)
def psHookRemoveCb(self, nb_deleted):
self.disp(
- _(u"{nb_deleted} hook(s) have been deleted").format(nb_deleted=nb_deleted)
+ _("{nb_deleted} hook(s) have been deleted").format(nb_deleted=nb_deleted)
)
self.host.quit()
@@ -2004,7 +1993,7 @@ class HookDelete(base.CommandBase):
callback=self.psHookRemoveCb,
errback=partial(
self.errback,
- msg=_(u"can't delete hook: {}"),
+ msg=_("can't delete hook: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -2017,7 +2006,7 @@ class HookList(base.CommandBase):
host,
"list",
use_output=C.OUTPUT_LIST_DICT,
- help=_(u"list hooks of a profile"),
+ help=_("list hooks of a profile"),
)
self.need_loop = True
@@ -2026,7 +2015,7 @@ class HookList(base.CommandBase):
def psHookListCb(self, data):
if not data:
- self.disp(_(u"No hook found."))
+ self.disp(_("No hook found."))
self.output(data)
self.host.quit()
@@ -2036,7 +2025,7 @@ class HookList(base.CommandBase):
callback=self.psHookListCb,
errback=partial(
self.errback,
- msg=_(u"can't list hooks: {}"),
+ msg=_("can't list hooks: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
diff --git a/sat_frontends/jp/cmd_roster.py b/sat_frontends/jp/cmd_roster.py
index f31f8979..aa312a55 100644
--- a/sat_frontends/jp/cmd_roster.py
+++ b/sat_frontends/jp/cmd_roster.py
@@ -18,7 +18,7 @@
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see
.
-import base
+from . import base
from collections import OrderedDict
from functools import partial
from sat.core.i18n import _
@@ -43,7 +43,7 @@ class Purge(base.CommandBase):
self.host.bridge.getContacts(profile_key=self.host.profile, callback=self.gotContacts, errback=self.error)
def error(self, failure):
- print (_("Error while retrieving the contacts [%s]") % failure)
+ print((_("Error while retrieving the contacts [%s]") % failure))
self.host.quit(1)
def ask_confirmation(self, no_sub, no_from, no_to):
@@ -55,17 +55,17 @@ class Purge(base.CommandBase):
@return bool
"""
if no_sub:
- print "There's no subscription between profile [%s] and the following contacts:" % self.host.profile
- print " " + "\n ".join(no_sub)
+ print("There's no subscription between profile [%s] and the following contacts:" % self.host.profile)
+ print(" " + "\n ".join(no_sub))
if no_from:
- print "There's no 'from' subscription between profile [%s] and the following contacts:" % self.host.profile
- print " " + "\n ".join(no_from)
+ print("There's no 'from' subscription between profile [%s] and the following contacts:" % self.host.profile)
+ print(" " + "\n ".join(no_from))
if no_to:
- print "There's no 'to' subscription between profile [%s] and the following contacts:" % self.host.profile
- print " " + "\n ".join(no_to)
+ print("There's no 'to' subscription between profile [%s] and the following contacts:" % self.host.profile)
+ print(" " + "\n ".join(no_to))
message = "REMOVE them from profile [%s]'s roster" % self.host.profile
while True:
- res = raw_input("%s (y/N)? " % message)
+ res = input("%s (y/N)? " % message)
if not res or res.lower() == 'n':
return False
if res.lower() == 'y':
@@ -87,7 +87,7 @@ class Purge(base.CommandBase):
elif not to and self.args.no_to:
no_to.append(contact)
if not no_sub and not no_from and not no_to:
- print "Nothing to do - there's a from and/or to subscription(s) between profile [%s] and each of its contacts" % self.host.profile
+ print("Nothing to do - there's a from and/or to subscription(s) between profile [%s] and each of its contacts" % self.host.profile)
elif self.ask_confirmation(no_sub, no_from, no_to):
for contact in no_sub + no_from + no_to:
self.host.bridge.delContact(contact, profile_key=self.host.profile, callback=lambda __: None, errback=lambda failure: None)
@@ -107,7 +107,7 @@ class Stats(base.CommandBase):
self.host.bridge.getContacts(profile_key=self.host.profile, callback=self.gotContacts, errback=self.error)
def error(self, failure):
- print (_("Error while retrieving the contacts [%s]") % failure)
+ print((_("Error while retrieving the contacts [%s]") % failure))
self.host.quit(1)
def gotContacts(self, contacts):
@@ -135,31 +135,31 @@ class Stats(base.CommandBase):
total_group_subscription += len(groups)
if not groups:
no_group += 1
- hosts = OrderedDict(sorted(hosts.items(), key=lambda item:-item[1]))
+ hosts = OrderedDict(sorted(list(hosts.items()), key=lambda item:-item[1]))
- print
- print "Total number of contacts: %d" % len(contacts)
- print "Number of different hosts: %d" % len(hosts)
- print
- for host, count in hosts.iteritems():
- print "Contacts on {host}: {count} ({rate:.1f}%)".format(host=host, count=count, rate=100 * float(count) / len(contacts))
- print
- print "Contacts with no 'from' subscription: %d" % no_from
- print "Contacts with no 'to' subscription: %d" % no_to
- print "Contacts with no subscription at all: %d" % no_sub
- print
- print "Total number of groups: %d" % len(unique_groups)
+ print()
+ print("Total number of contacts: %d" % len(contacts))
+ print("Number of different hosts: %d" % len(hosts))
+ print()
+ for host, count in hosts.items():
+ print("Contacts on {host}: {count} ({rate:.1f}%)".format(host=host, count=count, rate=100 * float(count) / len(contacts)))
+ print()
+ print("Contacts with no 'from' subscription: %d" % no_from)
+ print("Contacts with no 'to' subscription: %d" % no_to)
+ print("Contacts with no subscription at all: %d" % no_sub)
+ print()
+ print("Total number of groups: %d" % len(unique_groups))
try:
contacts_per_group = float(total_group_subscription) / len(unique_groups)
except ZeroDivisionError:
contacts_per_group = 0
- print "Average contacts per group: {:.1f}".format(contacts_per_group)
+ print("Average contacts per group: {:.1f}".format(contacts_per_group))
try:
groups_per_contact = float(total_group_subscription) / len(contacts)
except ZeroDivisionError:
groups_per_contact = 0
- print "Average groups' subscriptions per contact: {:.1f}".format(groups_per_contact)
- print "Contacts not assigned to any group: %d" % no_group
+ print("Average groups' subscriptions per contact: {:.1f}".format(groups_per_contact))
+ print("Contacts not assigned to any group: %d" % no_group)
self.host.quit()
@@ -178,7 +178,7 @@ class Get(base.CommandBase):
self.host.bridge.getContacts(profile_key=self.host.profile, callback=self.gotContacts, errback=self.error)
def error(self, failure):
- print (_("Error while retrieving the contacts [%s]") % failure)
+ print((_("Error while retrieving the contacts [%s]") % failure))
self.host.quit(1)
def gotContacts(self, contacts):
@@ -200,10 +200,10 @@ class Get(base.CommandBase):
args.append("from" if C.bool(attrs["from"]) else "")
args.append("to" if C.bool(attrs["to"]) else "")
if self.args.name:
- args.append(unicode(attrs.get("name", "")))
+ args.append(str(attrs.get("name", "")))
if self.args.groups:
- args.append(u"\t".join(groups) if groups else "")
- print u";".join(["{}"] * field_count).format(*args).encode("utf-8")
+ args.append("\t".join(groups) if groups else "")
+ print(";".join(["{}"] * field_count).format(*args).encode("utf-8"))
self.host.quit()
@@ -211,14 +211,14 @@ class Resync(base.CommandBase):
def __init__(self, host):
super(Resync, self).__init__(
- host, 'resync', help=_(u'do a full resynchronisation of roster with server'))
+ host, 'resync', help=_('do a full resynchronisation of roster with server'))
self.need_loop = True
def add_parser_options(self):
pass
def rosterResyncCb(self):
- self.disp(_(u"Roster resynchronized"))
+ self.disp(_("Roster resynchronized"))
self.host.quit(C.EXIT_OK)
def start(self):
@@ -226,7 +226,7 @@ class Resync(base.CommandBase):
callback=self.rosterResyncCb,
errback=partial(
self.errback,
- msg=_(u"can't resynchronise roster: {}"),
+ msg=_("can't resynchronise roster: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
))
diff --git a/sat_frontends/jp/cmd_shell.py b/sat_frontends/jp/cmd_shell.py
index f2c502d6..9635b5c3 100644
--- a/sat_frontends/jp/cmd_shell.py
+++ b/sat_frontends/jp/cmd_shell.py
@@ -18,7 +18,7 @@
# along with this program. If not, see
.
-import base
+from . import base
import cmd
import sys
from sat.core.i18n import _
@@ -31,7 +31,7 @@ import subprocess
__commands__ = ["Shell"]
INTRO = _(
- u"""Welcome to {app_name} shell, the Salut à Toi shell !
+ """Welcome to {app_name} shell, the Salut à Toi shell !
This enrironment helps you using several {app_name} commands with similar parameters.
@@ -44,7 +44,7 @@ Enter "help" or "?" to know what to do
class Shell(base.CommandBase, cmd.Cmd):
def __init__(self, host):
base.CommandBase.__init__(
- self, host, "shell", help=_(u"launch jp in shell (REPL) mode")
+ self, host, "shell", help=_("launch jp in shell (REPL) mode")
)
cmd.Cmd.__init__(self)
@@ -54,22 +54,22 @@ class Shell(base.CommandBase, cmd.Cmd):
def update_path(self):
self._cur_parser = self.host.parser
- self.help = u""
+ self.help = ""
for idx, path_elt in enumerate(self.path):
try:
self._cur_parser = arg_tools.get_cmd_choices(path_elt, self._cur_parser)
except exceptions.NotFound:
- self.disp(_(u"bad command path"), error=True)
+ self.disp(_("bad command path"), error=True)
self.path = self.path[:idx]
break
else:
self.help = self._cur_parser
- self.prompt = A.color(C.A_PROMPT_PATH, u"/".join(self.path)) + A.color(
- C.A_PROMPT_SUF, u"> "
+ self.prompt = A.color(C.A_PROMPT_PATH, "/".join(self.path)) + A.color(
+ C.A_PROMPT_SUF, "> "
)
try:
- self.actions = arg_tools.get_cmd_choices(parser=self._cur_parser).keys()
+ self.actions = list(arg_tools.get_cmd_choices(parser=self._cur_parser).keys())
except exceptions.NotFound:
self.actions = []
@@ -100,9 +100,9 @@ class Shell(base.CommandBase, cmd.Cmd):
# Situation should be better when we'll move away from python-dbus
if self.verbose:
self.disp(
- _(u"COMMAND {external}=> {args}").format(
- external=_(u"(external) ") if external else u"",
- args=u" ".join(self.format_args(args)),
+ _("COMMAND {external}=> {args}").format(
+ external=_("(external) ") if external else "",
+ args=" ".join(self.format_args(args)),
)
)
if not external:
@@ -124,7 +124,7 @@ class Shell(base.CommandBase, cmd.Cmd):
self.disp(
A.color(
C.A_FAILURE,
- u"command failed with an error code of {err_no}".format(
+ "command failed with an error code of {err_no}".format(
err_no=ret_code
),
),
@@ -145,12 +145,12 @@ class Shell(base.CommandBase, cmd.Cmd):
def do_help(self, args):
"""show help message"""
if not args:
- self.disp(A.color(C.A_HEADER, _(u"Shell commands:")), no_lf=True)
+ self.disp(A.color(C.A_HEADER, _("Shell commands:")), no_lf=True)
super(Shell, self).do_help(args)
if not args:
- self.disp(A.color(C.A_HEADER, _(u"Action commands:")))
+ self.disp(A.color(C.A_HEADER, _("Action commands:")))
help_list = self._cur_parser.format_help().split("\n\n")
- print("\n\n".join(help_list[1 if self.path else 2 :]))
+ print(("\n\n".join(help_list[1 if self.path else 2 :])))
def do_debug(self, args):
"""launch internal debugger"""
@@ -166,8 +166,8 @@ class Shell(base.CommandBase, cmd.Cmd):
if args:
self.verbose = C.bool(args[0])
self.disp(
- _(u"verbose mode is {status}").format(
- status=_(u"ENABLED") if self.verbose else _(u"DISABLED")
+ _("verbose mode is {status}").format(
+ status=_("ENABLED") if self.verbose else _("DISABLED")
)
)
@@ -211,7 +211,7 @@ class Shell(base.CommandBase, cmd.Cmd):
# so we need to add it in arguments to use current user profile
if self.verbose:
self.disp(
- _(u"arg profile={profile} (logged profile)").format(
+ _("arg profile={profile} (logged profile)").format(
profile=self.profile
)
)
@@ -233,25 +233,25 @@ class Shell(base.CommandBase, cmd.Cmd):
args = self.parse_args(args)
if not args:
if not self.use:
- self.disp(_(u"no argument in USE"))
+ self.disp(_("no argument in USE"))
else:
- self.disp(_(u"arguments in USE:"))
- for arg, value in self.use.iteritems():
+ self.disp(_("arguments in USE:"))
+ for arg, value in self.use.items():
self.disp(
_(
A.color(
C.A_SUBHEADER,
arg,
A.RESET,
- u" = ",
+ " = ",
arg_tools.escape(value),
)
)
)
elif len(args) != 2:
- self.disp(u"bad syntax, please use:\nuse [arg] [value]", error=True)
+ self.disp("bad syntax, please use:\nuse [arg] [value]", error=True)
else:
- self.use[args[0]] = u" ".join(args[1:])
+ self.use[args[0]] = " ".join(args[1:])
if self.verbose:
self.disp(
"set {name} = {value}".format(
@@ -271,25 +271,25 @@ class Shell(base.CommandBase, cmd.Cmd):
except KeyError:
self.disp(
A.color(
- C.A_FAILURE, _(u"argument {name} not found").format(name=arg)
+ C.A_FAILURE, _("argument {name} not found").format(name=arg)
),
error=True,
)
else:
if self.verbose:
- self.disp(_(u"argument {name} removed").format(name=arg))
+ self.disp(_("argument {name} removed").format(name=arg))
def do_whoami(self, args):
- u"""print profile currently used"""
+ """print profile currently used"""
self.disp(self.profile)
def do_quit(self, args):
- u"""quit the shell"""
- self.disp(_(u"good bye!"))
+ """quit the shell"""
+ self.disp(_("good bye!"))
self.host.quit()
def do_exit(self, args):
- u"""alias for quit"""
+ """alias for quit"""
self.do_quit(args)
def start(self):
diff --git a/sat_frontends/jp/cmd_ticket.py b/sat_frontends/jp/cmd_ticket.py
index 1022e59d..bb263e22 100644
--- a/sat_frontends/jp/cmd_ticket.py
+++ b/sat_frontends/jp/cmd_ticket.py
@@ -18,7 +18,7 @@
# along with this program. If not, see
.
-import base
+from . import base
from sat.core.i18n import _
from sat_frontends.jp import common
from sat_frontends.jp.constants import Const as C
@@ -28,7 +28,7 @@ import os
__commands__ = ["Ticket"]
-FIELDS_MAP = u"mapping"
+FIELDS_MAP = "mapping"
class Get(base.CommandBase):
@@ -40,9 +40,9 @@ class Get(base.CommandBase):
use_verbose=True,
use_pubsub=True,
pubsub_flags={C.MULTI_ITEMS},
- pubsub_defaults={u"service": _(u"auto"), u"node": _(u"auto")},
+ pubsub_defaults={"service": _("auto"), "node": _("auto")},
use_output=C.OUTPUT_LIST_XMLUI,
- help=_(u"get tickets"),
+ help=_("get tickets"),
)
self.need_loop = True
@@ -59,13 +59,13 @@ class Get(base.CommandBase):
self.args.node,
self.args.max,
self.args.items,
- u"",
+ "",
self.getPubsubExtra(),
self.profile,
callback=self.ticketsGetCb,
errback=partial(
self.errback,
- msg=_(u"can't get tickets: {}"),
+ msg=_("can't get tickets: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -82,16 +82,15 @@ class Import(base.CommandAnswering):
host,
"import",
use_progress=True,
- help=_(u"import tickets from external software/dataset"),
+ help=_("import tickets from external software/dataset"),
)
self.need_loop = True
def add_parser_options(self):
self.parser.add_argument(
"importer",
- type=base.unicode_decoder,
nargs="?",
- help=_(u"importer name, nothing to display importers list"),
+ help=_("importer name, nothing to display importers list"),
)
self.parser.add_argument(
"-o",
@@ -99,8 +98,8 @@ class Import(base.CommandAnswering):
action="append",
nargs=2,
default=[],
- metavar=(u"NAME", u"VALUE"),
- help=_(u"importer specific options (see importer description)"),
+ metavar=("NAME", "VALUE"),
+ help=_("importer specific options (see importer description)"),
)
self.parser.add_argument(
"-m",
@@ -108,46 +107,43 @@ class Import(base.CommandAnswering):
action="append",
nargs=2,
default=[],
- metavar=(u"IMPORTED_FIELD", u"DEST_FIELD"),
+ metavar=("IMPORTED_FIELD", "DEST_FIELD"),
help=_(
- u"specified field in import data will be put in dest field (default: use same field name, or ignore if it doesn't exist)"
+ "specified field in import data will be put in dest field (default: use same field name, or ignore if it doesn't exist)"
),
)
self.parser.add_argument(
"-s",
"--service",
- type=base.unicode_decoder,
- default=u"",
- metavar=u"PUBSUB_SERVICE",
- help=_(u"PubSub service where the items must be uploaded (default: server)"),
+ default="",
+ metavar="PUBSUB_SERVICE",
+ help=_("PubSub service where the items must be uploaded (default: server)"),
)
self.parser.add_argument(
"-n",
"--node",
- type=base.unicode_decoder,
- default=u"",
- metavar=u"PUBSUB_NODE",
+ default="",
+ metavar="PUBSUB_NODE",
help=_(
- u"PubSub node where the items must be uploaded (default: tickets' defaults)"
+ "PubSub node where the items must be uploaded (default: tickets' defaults)"
),
)
self.parser.add_argument(
"location",
- type=base.unicode_decoder,
nargs="?",
help=_(
- u"importer data location (see importer description), nothing to show importer description"
+ "importer data location (see importer description), nothing to show importer description"
),
)
def onProgressStarted(self, metadata):
- self.disp(_(u"Tickets upload started"), 2)
+ self.disp(_("Tickets upload started"), 2)
def onProgressFinished(self, metadata):
- self.disp(_(u"Tickets uploaded successfully"), 2)
+ self.disp(_("Tickets uploaded successfully"), 2)
def onProgressError(self, error_msg):
- self.disp(_(u"Error while uploading tickets: {}").format(error_msg), error=True)
+ self.disp(_("Error while uploading tickets: {}").format(error_msg), error=True)
def error(self, failure):
self.disp(
@@ -162,14 +158,14 @@ class Import(base.CommandAnswering):
if getattr(self.args, name):
self.parser.error(
_(
- u"{name} argument can't be used without location argument"
+ "{name} argument can't be used without location argument"
).format(name=name)
)
if self.args.importer is None:
self.disp(
- u"\n".join(
+ "\n".join(
[
- u"{}: {}".format(name, desc)
+ "{}: {}".format(name, desc)
for name, desc in self.host.bridge.ticketsImportList()
]
)
@@ -180,14 +176,14 @@ class Import(base.CommandAnswering):
self.args.importer
)
except Exception as e:
- msg = [l for l in unicode(e).split("\n") if l][
+ msg = [l for l in str(e).split("\n") if l][
-1
] # we only keep the last line
self.disp(msg)
self.host.quit(1)
else:
self.disp(
- u"{name}: {short_desc}\n\n{long_desc}".format(
+ "{name}: {short_desc}\n\n{long_desc}".format(
name=self.args.importer,
short_desc=short_desc,
long_desc=long_desc,
@@ -202,7 +198,7 @@ class Import(base.CommandAnswering):
if FIELDS_MAP in options:
self.parser.error(
_(
- u"fields_map must be specified either preencoded in --option or using --map, but not both at the same time"
+ "fields_map must be specified either preencoded in --option or using --map, but not both at the same time"
)
)
options[FIELDS_MAP] = json.dumps(fields_map)
diff --git a/sat_frontends/jp/cmd_uri.py b/sat_frontends/jp/cmd_uri.py
index 0fb1e8e1..d274f28e 100644
--- a/sat_frontends/jp/cmd_uri.py
+++ b/sat_frontends/jp/cmd_uri.py
@@ -18,7 +18,7 @@
# along with this program. If not, see
.
-import base
+from . import base
from sat.core.i18n import _
from sat_frontends.jp.constants import Const as C
from sat.tools.common import uri
@@ -34,12 +34,12 @@ class Parse(base.CommandBase):
"parse",
use_profile=False,
use_output=C.OUTPUT_DICT,
- help=_(u"parse URI"),
+ help=_("parse URI"),
)
def add_parser_options(self):
self.parser.add_argument(
- "uri", type=base.unicode_decoder, help=_(u"XMPP URI to parse")
+ "uri", help=_("XMPP URI to parse")
)
def start(self):
@@ -49,21 +49,20 @@ class Parse(base.CommandBase):
class Build(base.CommandBase):
def __init__(self, host):
base.CommandBase.__init__(
- self, host, "build", use_profile=False, help=_(u"build URI")
+ self, host, "build", use_profile=False, help=_("build URI")
)
def add_parser_options(self):
- self.parser.add_argument("type", type=base.unicode_decoder, help=_(u"URI type"))
- self.parser.add_argument("path", type=base.unicode_decoder, help=_(u"URI path"))
+ self.parser.add_argument("type", help=_("URI type"))
+ self.parser.add_argument("path", help=_("URI path"))
self.parser.add_argument(
"-f",
"--field",
- type=base.unicode_decoder,
action="append",
nargs=2,
dest="fields",
- metavar=(u"KEY", u"VALUE"),
- help=_(u"URI fields"),
+ metavar=("KEY", "VALUE"),
+ help=_("URI fields"),
)
def start(self):
diff --git a/sat_frontends/jp/common.py b/sat_frontends/jp/common.py
index 4023ea50..27900618 100644
--- a/sat_frontends/jp/common.py
+++ b/sat_frontends/jp/common.py
@@ -24,7 +24,7 @@ from sat.tools.common import regex
from sat.tools.common.ansi import ANSI as A
from sat.tools.common import uri as xmpp_uri
from sat.tools import config
-from ConfigParser import NoSectionError, NoOptionError
+from configparser import NoSectionError, NoOptionError
from collections import namedtuple
from functools import partial
import json
@@ -55,7 +55,7 @@ METADATA_SUFF = "_metadata.json"
def ansi_ljust(s, width):
"""ljust method handling ANSI escape codes"""
cleaned = regex.ansiRemove(s)
- return s + u" " * (width - len(cleaned))
+ return s + " " * (width - len(cleaned))
def ansi_center(s, width):
@@ -63,13 +63,13 @@ def ansi_center(s, width):
cleaned = regex.ansiRemove(s)
diff = width - len(cleaned)
half = diff / 2
- return half * u" " + s + (half + diff % 2) * u" "
+ return half * " " + s + (half + diff % 2) * " "
def ansi_rjust(s, width):
"""ljust method handling ANSI escape codes"""
cleaned = regex.ansiRemove(s)
- return u" " * (width - len(cleaned)) + s
+ return " " * (width - len(cleaned)) + s
def getTmpDir(sat_conf, cat_dir, sub_dir=None):
@@ -103,13 +103,13 @@ def parse_args(host, cmd_line, **format_kw):
return [a.format(**format_kw) for a in shlex.split(cmd_line)]
except ValueError as e:
host.disp(
- u"Couldn't parse editor cmd [{cmd}]: {reason}".format(cmd=cmd_line, reason=e)
+ "Couldn't parse editor cmd [{cmd}]: {reason}".format(cmd=cmd_line, reason=e)
)
return []
class BaseEdit(object):
- u"""base class for editing commands
+ """base class for editing commands
This class allows to edit file for PubSub or something else.
It works with temporary files in SàT local_dir, in a "cat_dir" subdir
@@ -138,11 +138,11 @@ class BaseEdit(object):
@param path(str): file to unlink
"""
if not os.path.isfile(path):
- raise OSError(u"path must link to a regular file")
+ raise OSError("path must link to a regular file")
if not path.startswith(getTmpDir(self.sat_conf, self.cat_dir_str)):
self.disp(
- u"File {} is not in SàT temporary hierarchy, we do not remove it".format(
- path.decode("utf-8")
+ "File {} is not in SàT temporary hierarchy, we do not remove it".format(
+ path
),
2,
)
@@ -156,8 +156,8 @@ class BaseEdit(object):
backup_path = os.path.join(backup_dir, filename)
# we move file to backup dir
self.host.disp(
- u"Backuping file {src} to {dst}".format(
- src=path.decode("utf-8"), dst=backup_path.decode("utf-8")
+ "Backuping file {src} to {dst}".format(
+ src=path, dst=backup_path
),
1,
)
@@ -167,7 +167,7 @@ class BaseEdit(object):
if len(backup_files) > unlink_max:
backup_files.sort(key=lambda path: os.stat(path).st_mtime)
for path in backup_files[: len(backup_files) - unlink_max]:
- self.host.disp(u"Purging backup file {}".format(path.decode("utf-8")), 2)
+ self.host.disp("Purging backup file {}".format(path), 2)
os.unlink(path)
def runEditor(
@@ -228,7 +228,7 @@ class BaseEdit(object):
# edition will now be checked, and data will be sent if it was a success
if editor_exit != 0:
self.disp(
- u"Editor exited with an error code, so temporary file has not be deleted, and item is not published.\nYou can find temporary file at {path}".format(
+ "Editor exited with an error code, so temporary file has not be deleted, and item is not published.\nYou can find temporary file at {path}".format(
path=content_file_path
),
error=True,
@@ -240,7 +240,7 @@ class BaseEdit(object):
content = f.read()
except (OSError, IOError):
self.disp(
- u"Can read file at {content_path}, have it been deleted?\nCancelling edition".format(
+ "Can read file at {content_path}, have it been deleted?\nCancelling edition".format(
content_path=content_file_path
),
error=True,
@@ -254,7 +254,7 @@ class BaseEdit(object):
metadata = json.load(f)
except (OSError, IOError):
self.disp(
- u"Can read file at {meta_file_path}, have it been deleted?\nCancelling edition".format(
+ "Can read file at {meta_file_path}, have it been deleted?\nCancelling edition".format(
content_path=content_file_path, meta_path=meta_file_path
),
error=True,
@@ -262,7 +262,7 @@ class BaseEdit(object):
self.host.quit(C.EXIT_NOT_FOUND)
except ValueError:
self.disp(
- u"Can't parse metadata, please check it is correct JSON format. Cancelling edition.\n"
+ "Can't parse metadata, please check it is correct JSON format. Cancelling edition.\n"
+ "You can find tmp file at {content_path} and temporary meta file at {meta_path}.".format(
content_path=content_file_path, meta_path=meta_file_path
),
@@ -272,7 +272,7 @@ class BaseEdit(object):
if self.use_metadata and not metadata.get("publish", True):
self.disp(
- u'Publication blocked by "publish" key in metadata, cancelling edition.\n\n'
+ 'Publication blocked by "publish" key in metadata, cancelling edition.\n\n'
+ "temporary file path:\t{content_path}\nmetadata file path:\t{meta_path}".format(
content_path=content_file_path, meta_path=meta_file_path
),
@@ -281,19 +281,19 @@ class BaseEdit(object):
self.host.quit()
if len(content) == 0:
- self.disp(u"Content is empty, cancelling the edition")
+ self.disp("Content is empty, cancelling the edition")
if not content_file_path.startswith(
getTmpDir(self.sat_conf, self.cat_dir_str)
):
self.disp(
- u"File are not in SàT temporary hierarchy, we do not remove them",
+ "File are not in SàT temporary hierarchy, we do not remove them",
2,
)
self.host.quit()
- self.disp(u"Deletion of {}".format(content_file_path.decode("utf-8")), 2)
+ self.disp("Deletion of {}".format(content_file_path), 2)
os.unlink(content_file_path)
if self.use_metadata:
- self.disp(u"Deletion of {}".format(meta_file_path.decode("utf-8")), 2)
+ self.disp("Deletion of {}".format(meta_file_path), 2)
os.unlink(meta_file_path)
self.host.quit()
@@ -301,7 +301,7 @@ class BaseEdit(object):
elif tmp_ori_hash == hashlib.sha1(content).digest() and (
not self.use_metadata or meta_ori == metadata
):
- self.disp(u"The content has not been modified, cancelling the edition")
+ self.disp("The content has not been modified, cancelling the edition")
self.host.quit()
else:
@@ -315,7 +315,7 @@ class BaseEdit(object):
except Exception as e:
if self.use_metadata:
self.disp(
- u"Error while sending your item, the temporary files have been kept at {content_path} and {meta_path}: {reason}".format(
+ "Error while sending your item, the temporary files have been kept at {content_path} and {meta_path}: {reason}".format(
content_path=content_file_path,
meta_path=meta_file_path,
reason=e,
@@ -324,7 +324,7 @@ class BaseEdit(object):
)
else:
self.disp(
- u"Error while sending your item, the temporary file has been kept at {content_path}: {reason}".format(
+ "Error while sending your item, the temporary file has been kept at {content_path}: {reason}".format(
content_path=content_file_path, reason=e
),
error=True,
@@ -353,7 +353,7 @@ class BaseEdit(object):
os.makedirs(tmp_dir)
except OSError as e:
self.disp(
- u"Can't create {path} directory: {reason}".format(
+ "Can't create {path} directory: {reason}".format(
path=tmp_dir, reason=e
),
error=True,
@@ -369,7 +369,7 @@ class BaseEdit(object):
return os.fdopen(fd, "w+b"), path
except OSError as e:
self.disp(
- u"Can't create temporary file: {reason}".format(reason=e), error=True
+ "Can't create temporary file: {reason}".format(reason=e), error=True
)
self.host.quit(1)
@@ -391,7 +391,7 @@ class BaseEdit(object):
]
if not available:
self.disp(
- u"Could not find any content draft in {path}".format(path=tmp_dir),
+ "Could not find any content draft in {path}".format(path=tmp_dir),
error=True,
)
self.host.quit(1)
@@ -403,7 +403,7 @@ class BaseEdit(object):
def getTmpSuff(self):
"""return suffix used for content file"""
- return u"xml"
+ return "xml"
def getItemPath(self):
"""retrieve item path (i.e. service and node) from item argument
@@ -418,7 +418,7 @@ class BaseEdit(object):
if self.args.current:
# user wants to continue current draft
content_file_path = self.getCurrentFile(self.profile)
- self.disp(u"Continuing edition of current draft", 2)
+ self.disp("Continuing edition of current draft", 2)
content_file_obj = open(content_file_path, "r+b")
# we seek at the end of file in case of an item already exist
# this will write content of the existing item at the end of the draft.
@@ -435,7 +435,7 @@ class BaseEdit(object):
content_file_obj, content_file_path = self.getTmpFile()
if item or last_item:
- self.disp(u"Editing requested published item", 2)
+ self.disp("Editing requested published item", 2)
try:
if self.use_metadata:
content, metadata, item = self.getItemData(service, node, item)
@@ -443,21 +443,21 @@ class BaseEdit(object):
content, item = self.getItemData(service, node, item)
except Exception as e:
# FIXME: ugly but we have not good may to check errors in bridge
- if u"item-not-found" in unicode(e):
+ if "item-not-found" in str(e):
# item doesn't exist, we create a new one with requested id
metadata = None
if last_item:
- self.disp(_(u"no item found at all, we create a new one"), 2)
+ self.disp(_("no item found at all, we create a new one"), 2)
else:
self.disp(
_(
- u'item "{item_id}" not found, we create a new item with this id'
+ 'item "{item_id}" not found, we create a new item with this id'
).format(item_id=item),
2,
)
content_file_obj.seek(0)
else:
- self.disp(u"Error while retrieving item: {}".format(e))
+ self.disp("Error while retrieving item: {}".format(e))
self.host.quit(C.EXIT_ERROR)
else:
# item exists, we write content
@@ -468,10 +468,10 @@ class BaseEdit(object):
content_file_obj.write(content.encode("utf-8"))
content_file_obj.seek(0)
self.disp(
- _(u'item "{item_id}" found, we edit it').format(item_id=item), 2
+ _('item "{item_id}" found, we edit it').format(item_id=item), 2
)
else:
- self.disp(u"Editing a new item", 2)
+ self.disp("Editing a new item", 2)
if self.use_metadata:
metadata = None
@@ -520,7 +520,7 @@ class Table(object):
for idx, value in enumerate(row_data_list):
if filters is not None and filters[idx] is not None:
filter_ = filters[idx]
- if isinstance(filter_, basestring):
+ if isinstance(filter_, str):
col_value = filter_.format(value)
else:
try:
@@ -531,7 +531,7 @@ class Table(object):
# when it's mostly style/color changes.
col_size = len(regex.ansiRemove(col_value))
else:
- col_value = unicode(value)
+ col_value = str(value)
col_size = len(col_value)
new_row.append(col_value)
if size is None:
@@ -541,10 +541,10 @@ class Table(object):
if size is None:
size = len(new_row)
if headers is not None and len(headers) != size:
- raise exceptions.DataError(u"headers size is not coherent with rows")
+ raise exceptions.DataError("headers size is not coherent with rows")
else:
if len(new_row) != size:
- raise exceptions.DataError(u"rows size is not coherent")
+ raise exceptions.DataError("rows size is not coherent")
self.rows.append(new_row)
if not data and headers is not None:
@@ -554,8 +554,8 @@ class Table(object):
@property
def string(self):
if self._buffer is None:
- raise exceptions.InternalError(u"buffer must be used to get a string")
- return u"\n".join(self._buffer)
+ raise exceptions.InternalError("buffer must be used to get a string")
+ return "\n".join(self._buffer)
@staticmethod
def readDictValues(data, keys, defaults=None):
@@ -589,9 +589,9 @@ class Table(object):
"""
if keys is None and headers is not None:
# FIXME: keys are not needed with OrderedDict,
- raise exceptions.DataError(u"You must specify keys order to used headers")
+ raise exceptions.DataError("You must specify keys order to used headers")
if keys is None:
- keys = data[0].keys()
+ keys = list(data[0].keys())
if headers is None:
headers = keys
filters = [filters.get(k) for k in keys]
@@ -599,7 +599,7 @@ class Table(object):
host, (cls.readDictValues(d, keys, defaults) for d in data), headers, filters
)
- def _headers(self, head_sep, headers, sizes, alignment=u"left", style=None):
+ def _headers(self, head_sep, headers, sizes, alignment="left", style=None):
"""Render headers
@param head_sep(unicode): sequence to use as separator
@@ -609,18 +609,18 @@ class Table(object):
@param sizes(list[int]): sizes of columns
"""
rendered_headers = []
- if isinstance(style, basestring):
+ if isinstance(style, str):
style = [style]
for idx, header in enumerate(headers):
size = sizes[idx]
- if alignment == u"left":
+ if alignment == "left":
rendered = header[:size].ljust(size)
- elif alignment == u"center":
+ elif alignment == "center":
rendered = header[:size].center(size)
- elif alignment == u"right":
+ elif alignment == "right":
rendered = header[:size].rjust(size)
else:
- raise exceptions.InternalError(u"bad alignment argument")
+ raise exceptions.InternalError("bad alignment argument")
if style:
args = style + [rendered]
rendered = A.color(*args)
@@ -636,28 +636,28 @@ class Table(object):
def display(
self,
- head_alignment=u"left",
- columns_alignment=u"left",
+ head_alignment="left",
+ columns_alignment="left",
head_style=None,
show_header=True,
show_borders=True,
hide_cols=None,
- col_sep=u" │ ",
- top_left=u"┌",
- top=u"─",
- top_sep=u"─┬─",
- top_right=u"┐",
- left=u"│",
+ col_sep=" │ ",
+ top_left="┌",
+ top="─",
+ top_sep="─┬─",
+ top_right="┐",
+ left="│",
right=None,
head_sep=None,
- head_line=u"┄",
- head_line_left=u"├",
- head_line_sep=u"┄┼┄",
- head_line_right=u"┤",
- bottom_left=u"└",
+ head_line="┄",
+ head_line_left="├",
+ head_line_sep="┄┼┄",
+ head_line_right="┤",
+ bottom_left="└",
bottom=None,
- bottom_sep=u"─┴─",
- bottom_right=u"┘",
+ bottom_sep="─┴─",
+ bottom_right="┘",
):
"""Print the table
@@ -700,7 +700,7 @@ class Table(object):
if bottom_sep is None:
bottom_sep = col_sep_size * bottom
if not show_borders:
- left = right = head_line_left = head_line_right = u""
+ left = right = head_line_left = head_line_right = ""
# top border
if show_borders:
self._disp(
@@ -722,14 +722,14 @@ class Table(object):
)
# content
- if columns_alignment == u"left":
+ if columns_alignment == "left":
alignment = lambda idx, s: ansi_ljust(s, sizes[idx])
- elif columns_alignment == u"center":
+ elif columns_alignment == "center":
alignment = lambda idx, s: ansi_center(s, sizes[idx])
- elif columns_alignment == u"right":
+ elif columns_alignment == "right":
alignment = lambda idx, s: ansi_rjust(s, sizes[idx])
else:
- raise exceptions.InternalError(u"bad columns alignment argument")
+ raise exceptions.InternalError("bad columns alignment argument")
for row in self.rows:
if hide_cols:
@@ -752,7 +752,7 @@ class Table(object):
def display_blank(self, **kwargs):
"""Display table without visible borders"""
- kwargs_ = {"col_sep": u" ", "head_line_sep": u" ", "show_borders": False}
+ kwargs_ = {"col_sep": " ", "head_line_sep": " ", "show_borders": False}
kwargs_.update(kwargs)
return self.display(**kwargs_)
@@ -786,7 +786,7 @@ class URIFinder(object):
callback=self.URIFindCb,
errback=partial(
command.errback,
- msg=_(u"can't find " + key + u" URI: {}"),
+ msg=_("can't find " + key + " URI: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@@ -812,7 +812,7 @@ class URIFinder(object):
values = getattr(self.args, key)
except AttributeError:
raise exceptions.InternalError(
- u'there is no "{key}" arguments'.format(key=key)
+ 'there is no "{key}" arguments'.format(key=key)
)
else:
if values is None:
@@ -826,20 +826,20 @@ class URIFinder(object):
except KeyError:
self.host.disp(
_(
- u"No {key} URI specified for this project, please specify service and node"
+ "No {key} URI specified for this project, please specify service and node"
).format(key=self.key),
error=True,
)
self.host.quit(C.EXIT_NOT_FOUND)
else:
- uri = uri_data[u"uri"]
+ uri = uri_data["uri"]
- self.setMetadataList(uri_data, u"labels")
+ self.setMetadataList(uri_data, "labels")
parsed_uri = xmpp_uri.parseXMPPUri(uri)
try:
- self.args.service = parsed_uri[u"path"]
- self.args.node = parsed_uri[u"node"]
+ self.args.service = parsed_uri["path"]
+ self.args.node = parsed_uri["node"]
except KeyError:
- self.host.disp(_(u"Invalid URI found: {uri}").format(uri=uri), error=True)
+ self.host.disp(_("Invalid URI found: {uri}").format(uri=uri), error=True)
self.host.quit(C.EXIT_DATA_ERROR)
self.callback()
diff --git a/sat_frontends/jp/constants.py b/sat_frontends/jp/constants.py
index 9034b9f7..243e8590 100644
--- a/sat_frontends/jp/constants.py
+++ b/sat_frontends/jp/constants.py
@@ -23,20 +23,20 @@ from sat.tools.common.ansi import ANSI as A
class Const(constants.Const):
- APP_NAME = u"jp"
- PLUGIN_CMD = u"commands"
- PLUGIN_OUTPUT = u"outputs"
- OUTPUT_TEXT = u"text" # blob of unicode text
- OUTPUT_DICT = u"dict" # simple key/value dictionary
- OUTPUT_LIST = u"list"
- OUTPUT_LIST_DICT = u"list_dict" # list of dictionaries
- OUTPUT_DICT_DICT = u"dict_dict" # dict of nested dictionaries
- OUTPUT_MESS = u"mess" # messages (chat)
- OUTPUT_COMPLEX = u"complex" # complex data (e.g. multi-level dictionary)
- OUTPUT_XML = u"xml" # XML node (as unicode string)
- OUTPUT_LIST_XML = u"list_xml" # list of XML nodes (as unicode strings)
- OUTPUT_XMLUI = u"xmlui" # XMLUI as unicode string
- OUTPUT_LIST_XMLUI = u"list_xmlui" # list of XMLUI (as unicode strings)
+ APP_NAME = "jp"
+ PLUGIN_CMD = "commands"
+ PLUGIN_OUTPUT = "outputs"
+ OUTPUT_TEXT = "text" # blob of unicode text
+ OUTPUT_DICT = "dict" # simple key/value dictionary
+ OUTPUT_LIST = "list"
+ OUTPUT_LIST_DICT = "list_dict" # list of dictionaries
+ OUTPUT_DICT_DICT = "dict_dict" # dict of nested dictionaries
+ OUTPUT_MESS = "mess" # messages (chat)
+ OUTPUT_COMPLEX = "complex" # complex data (e.g. multi-level dictionary)
+ OUTPUT_XML = "xml" # XML node (as unicode string)
+ OUTPUT_LIST_XML = "list_xml" # list of XML nodes (as unicode strings)
+ OUTPUT_XMLUI = "xmlui" # XMLUI as unicode string
+ OUTPUT_LIST_XMLUI = "list_xmlui" # list of XMLUI (as unicode strings)
OUTPUT_TYPES = (
OUTPUT_TEXT,
OUTPUT_DICT,
@@ -52,12 +52,12 @@ class Const(constants.Const):
)
# Pubsub options flags
- SERVICE = u"service" # service required
- NODE = u"node" # node required
- ITEM = u"item" # item required
- SINGLE_ITEM = u"single_item" # only one item is allowed
- MULTI_ITEMS = u"multi_items" # multiple items are allowed
- NO_MAX = u"no_max" # don't add --max option for multi items
+ SERVICE = "service" # service required
+ NODE = "node" # node required
+ ITEM = "item" # item required
+ SINGLE_ITEM = "single_item" # only one item is allowed
+ MULTI_ITEMS = "multi_items" # multiple items are allowed
+ NO_MAX = "no_max" # don't add --max option for multi items
# ANSI
A_HEADER = A.BOLD + A.FG_YELLOW
diff --git a/sat_frontends/jp/jp b/sat_frontends/jp/jp
index 0d1d85f6..9b014761 100755
--- a/sat_frontends/jp/jp
+++ b/sat_frontends/jp/jp
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# jp: a SAT command line tool
diff --git a/sat_frontends/jp/output_std.py b/sat_frontends/jp/output_std.py
index b977e273..d427feba 100644
--- a/sat_frontends/jp/output_std.py
+++ b/sat_frontends/jp/output_std.py
@@ -26,9 +26,9 @@ from sat.tools.common import date_utils
import json
__outputs__ = ["Simple", "Json"]
-SIMPLE = u"simple"
-JSON = u"json"
-JSON_RAW = u"json_raw"
+SIMPLE = "simple"
+JSON = "json"
+JSON_RAW = "json_raw"
class Simple(object):
@@ -45,25 +45,25 @@ class Simple(object):
host.register_output(C.OUTPUT_COMPLEX, SIMPLE, self.simple_print)
def simple_print(self, data):
- self.host.disp(unicode(data))
+ self.host.disp(str(data))
def list(self, data):
- self.host.disp(u"\n".join(data))
+ self.host.disp("\n".join(data))
def dict(self, data, indent=0, header_color=C.A_HEADER):
options = self.host.parse_output_options()
- self.host.check_output_options({u"no-header"}, options)
- show_header = not u"no-header" in options
- for k, v in data.iteritems():
+ self.host.check_output_options({"no-header"}, options)
+ show_header = not "no-header" in options
+ for k, v in data.items():
if show_header:
- header = A.color(header_color, k) + u": "
+ header = A.color(header_color, k) + ": "
else:
- header = u""
+ header = ""
self.host.disp(
(
- u"{indent}{header}{value}".format(
- indent=indent * u" ", header=header, value=v
+ "{indent}{header}{value}".format(
+ indent=indent * " ", header=header, value=v
)
)
)
@@ -71,11 +71,11 @@ class Simple(object):
def list_dict(self, data):
for idx, datum in enumerate(data):
if idx:
- self.host.disp(u"\n")
+ self.host.disp("\n")
self.dict(datum)
def dict_dict(self, data):
- for key, sub_dict in data.iteritems():
+ for key, sub_dict in data.items():
self.host.disp(A.color(C.A_HEADER, key))
self.dict(sub_dict, indent=4, header_color=C.A_SUBHEADER)
@@ -84,7 +84,7 @@ class Simple(object):
for mess_data in data:
(uid, timestamp, from_jid, to_jid, message, subject, mess_type,
extra) = mess_data
- time_str = date_utils.date_fmt(timestamp, u"auto_day",
+ time_str = date_utils.date_fmt(timestamp, "auto_day",
tz_info=date_utils.TZ_LOCAL)
from_jid = jid.JID(from_jid)
if mess_type == C.MESS_TYPE_GROUPCHAT:
@@ -96,11 +96,11 @@ class Simple(object):
nick_color = A.BOLD + A.FG_BLUE
else:
nick_color = A.BOLD + A.FG_YELLOW
- message = message.values()[0] if message else u""
+ message = list(message.values())[0] if message else ""
self.host.disp(A.color(
- A.FG_CYAN, u'['+time_str+u'] ',
- nick_color, nick, A.RESET, A.BOLD, u'> ',
+ A.FG_CYAN, '['+time_str+'] ',
+ nick_color, nick, A.RESET, A.BOLD, '> ',
A.RESET, message))
diff --git a/sat_frontends/jp/output_template.py b/sat_frontends/jp/output_template.py
index a62e5a9f..f6782b3b 100644
--- a/sat_frontends/jp/output_template.py
+++ b/sat_frontends/jp/output_template.py
@@ -30,8 +30,8 @@ import tempfile
import os.path
__outputs__ = ["Template"]
-TEMPLATE = u"template"
-OPTIONS = {u"template", u"browser", u"inline-css"}
+TEMPLATE = "template"
+OPTIONS = {"template", "browser", "inline-css"}
class Template(object):
@@ -43,14 +43,14 @@ class Template(object):
def _front_url_tmp_dir(self, ctx, relative_url, tmp_dir):
"""Get front URL for temporary directory"""
- template_data = ctx[u'template_data']
- return u"file://" + os.path.join(tmp_dir, template_data.theme, relative_url)
+ template_data = ctx['template_data']
+ return "file://" + os.path.join(tmp_dir, template_data.theme, relative_url)
def _do_render(self, template_path, css_inline, **kwargs):
try:
return self.renderer.render(template_path, css_inline=css_inline, **kwargs)
except template.TemplateNotFound:
- self.host.disp(_(u"Can't find requested template: {template_path}")
+ self.host.disp(_("Can't find requested template: {template_path}")
.format(template_path=template_path), error=True)
self.host.quit(C.EXIT_NOT_FOUND)
@@ -72,8 +72,8 @@ class Template(object):
except AttributeError:
if not "template" in cmd.args.output_opts:
self.host.disp(_(
- u"no default template set for this command, you need to specify a "
- u"template using --oo template=[path/to/template.html]"),
+ "no default template set for this command, you need to specify a "
+ "template using --oo template=[path/to/template.html]"),
error=True,
)
self.host.quit(C.EXIT_BAD_ARG)
@@ -86,7 +86,7 @@ class Template(object):
# template is not specified, we use default one
pass
if template_path is None:
- self.host.disp(_(u"Can't parse template, please check its syntax"),
+ self.host.disp(_("Can't parse template, please check its syntax"),
error=True)
self.host.quit(C.EXIT_BAD_ARG)
@@ -97,7 +97,7 @@ class Template(object):
else:
kwargs = mapping_cb(data)
- css_inline = u"inline-css" in options
+ css_inline = "inline-css" in options
if "browser" in options:
template_name = os.path.basename(template_path)
@@ -107,9 +107,9 @@ class Template(object):
self.host, front_url_filter=front_url_filter, trusted=True)
rendered = self._do_render(template_path, css_inline=css_inline, **kwargs)
self.host.disp(_(
- u"Browser opening requested.\n"
- u"Temporary files are put in the following directory, you'll have to "
- u"delete it yourself once finished viewing: {}").format(tmp_dir))
+ "Browser opening requested.\n"
+ "Temporary files are put in the following directory, you'll have to "
+ "delete it yourself once finished viewing: {}").format(tmp_dir))
tmp_file = os.path.join(tmp_dir, template_name)
with open(tmp_file, "w") as f:
f.write(rendered.encode("utf-8"))
@@ -129,7 +129,7 @@ class Template(object):
else:
# FIXME: Q&D way to disable template logging
# logs are overcomplicated, and need to be reworked
- template_logger = log.getLogger(u"sat.tools.common.template")
+ template_logger = log.getLogger("sat.tools.common.template")
template_logger.log = lambda *args: None
logging.disable(logging.WARNING)
diff --git a/sat_frontends/jp/output_xml.py b/sat_frontends/jp/output_xml.py
index 0c62c183..4264b5b9 100644
--- a/sat_frontends/jp/output_xml.py
+++ b/sat_frontends/jp/output_xml.py
@@ -36,8 +36,8 @@ except ImportError:
__outputs__ = ["XML"]
-RAW = u"xml_raw"
-PRETTY = u"xml_pretty"
+RAW = "xml_raw"
+PRETTY = "xml_pretty"
class XML(object):
@@ -54,7 +54,7 @@ class XML(object):
if pygments is None:
self.host.disp(
_(
- u"Pygments is not available, syntax highlighting is not possible. Please install if from http://pygments.org or with pip install pygments"
+ "Pygments is not available, syntax highlighting is not possible. Please install if from http://pygments.org or with pip install pygments"
),
error=True,
)
@@ -62,7 +62,7 @@ class XML(object):
if not sys.stdout.isatty():
return xml
lexer = XmlLexer(encoding="utf-8")
- formatter = TerminalFormatter(bg=u"dark")
+ formatter = TerminalFormatter(bg="dark")
return pygments.highlight(xml, lexer, formatter)
def format(self, data, pretty=True):
@@ -77,13 +77,13 @@ class XML(object):
def pretty(self, data):
self.host.disp(self.format(data))
- def pretty_list(self, data, separator=u"\n"):
- list_pretty = map(self.format, data)
+ def pretty_list(self, data, separator="\n"):
+ list_pretty = list(map(self.format, data))
self.host.disp(separator.join(list_pretty))
def raw(self, data):
self.host.disp(self.format_no_pretty(data))
- def list_raw(self, data, separator=u"\n"):
- list_no_pretty = map(self.format_no_pretty, data)
+ def list_raw(self, data, separator="\n"):
+ list_no_pretty = list(map(self.format_no_pretty, data))
self.host.disp(separator.join(list_no_pretty))
diff --git a/sat_frontends/jp/output_xmlui.py b/sat_frontends/jp/output_xmlui.py
index a8032f21..978d10f6 100644
--- a/sat_frontends/jp/output_xmlui.py
+++ b/sat_frontends/jp/output_xmlui.py
@@ -34,15 +34,15 @@ class XMLUI(object):
def __init__(self, host):
self.host = host
- host.register_output(C.OUTPUT_XMLUI, u"simple", self.xmlui, default=True)
+ host.register_output(C.OUTPUT_XMLUI, "simple", self.xmlui, default=True)
host.register_output(
- C.OUTPUT_LIST_XMLUI, u"simple", self.xmlui_list, default=True
+ C.OUTPUT_LIST_XMLUI, "simple", self.xmlui_list, default=True
)
def xmlui(self, data):
xmlui = xmlui_manager.create(self.host, data)
xmlui.show(values_only=True, read_only=True)
- self.host.disp(u"")
+ self.host.disp("")
def xmlui_list(self, data):
for d in data:
diff --git a/sat_frontends/jp/xml_tools.py b/sat_frontends/jp/xml_tools.py
index 5834ffde..d2201bfa 100644
--- a/sat_frontends/jp/xml_tools.py
+++ b/sat_frontends/jp/xml_tools.py
@@ -33,12 +33,12 @@ def etreeParse(cmd, raw_xml, reraise=False):
from lxml import etree
except ImportError:
cmd.disp(
- u'lxml module must be installed, please install it with "pip install lxml"',
+ 'lxml module must be installed, please install it with "pip install lxml"',
error=True,
)
cmd.host.quit(C.EXIT_ERROR)
try:
- if isinstance(raw_xml, basestring):
+ if isinstance(raw_xml, str):
parser = etree.XMLParser(remove_blank_text=True)
element = etree.fromstring(raw_xml, parser)
else:
@@ -47,7 +47,7 @@ def etreeParse(cmd, raw_xml, reraise=False):
if reraise:
raise e
cmd.parser.error(
- _(u"Can't parse the payload XML in input: {msg}").format(msg=e)
+ _("Can't parse the payload XML in input: {msg}").format(msg=e)
)
return element, etree
@@ -59,7 +59,7 @@ def getPayload(cmd, element):
"""
if element.tag in ("item", "{http://jabber.org/protocol/pubsub}item"):
if len(element) > 1:
- cmd.disp(_(u"
- can only have one child element (the payload)"),
+ cmd.disp(_("
- can only have one child element (the payload)"),
error=True)
cmd.host.quit(C.EXIT_DATA_ERROR)
element = element[0]
diff --git a/sat_frontends/jp/xmlui_manager.py b/sat_frontends/jp/xmlui_manager.py
index 324c14a9..0a1c6569 100644
--- a/sat_frontends/jp/xmlui_manager.py
+++ b/sat_frontends/jp/xmlui_manager.py
@@ -60,7 +60,7 @@ class Base(object):
class Widget(Base):
- category = u"widget"
+ category = "widget"
enabled = True
@property
@@ -89,8 +89,8 @@ class Widget(Base):
if self.host.verbosity:
to_disp = [
A.FG_MAGENTA,
- u" " if elems else u"",
- u"({})".format(value),
+ " " if elems else "",
+ "({})".format(value),
A.RESET,
]
if elems is None:
@@ -166,11 +166,11 @@ class OptionsWidget(Widget):
@property
def inline(self):
- return u"inline" in self.style
+ return "inline" in self.style
@property
def no_select(self):
- return u"noselect" in self.style
+ return "noselect" in self.style
class EmptyWidget(xmlui_base.EmptyWidget, Widget):
@@ -179,18 +179,18 @@ class EmptyWidget(xmlui_base.EmptyWidget, Widget):
Widget.__init__(self, xmlui_parent)
def show(self):
- self.host.disp(u'')
+ self.host.disp('')
class TextWidget(xmlui_base.TextWidget, ValueWidget):
- type = u"text"
+ type = "text"
def show(self):
self.host.disp(self.value)
class LabelWidget(xmlui_base.LabelWidget, ValueWidget):
- type = u"label"
+ type = "label"
@property
def for_name(self):
@@ -199,7 +199,7 @@ class LabelWidget(xmlui_base.LabelWidget, ValueWidget):
except AttributeError:
return None
- def show(self, no_lf=False, ansi=u""):
+ def show(self, no_lf=False, ansi=""):
"""show label
@param no_lf(bool): same as for [JP.disp]
@@ -209,10 +209,10 @@ class LabelWidget(xmlui_base.LabelWidget, ValueWidget):
class JidWidget(xmlui_base.JidWidget, TextWidget):
- type = u"jid"
+ type = "jid"
class StringWidget(xmlui_base.StringWidget, InputWidget):
- type = u"string"
+ type = "string"
def show(self):
if self.read_only or self.root.read_only:
@@ -221,9 +221,9 @@ class StringWidget(xmlui_base.StringWidget, InputWidget):
elems = []
self.verboseName(elems)
if self.value:
- elems.append(_(u"(enter: {default})").format(default=self.value))
- elems.extend([C.A_HEADER, u"> "])
- value = raw_input(A.color(*elems).encode('utf-8'))
+ elems.append(_("(enter: {default})").format(default=self.value))
+ elems.extend([C.A_HEADER, "> "])
+ value = input(A.color(*elems).encode('utf-8'))
if value:
# TODO: empty value should be possible
# an escape key should be used for default instead of enter with empty value
@@ -231,11 +231,11 @@ class StringWidget(xmlui_base.StringWidget, InputWidget):
class JidInputWidget(xmlui_base.JidInputWidget, StringWidget):
- type = u"jid_input"
+ type = "jid_input"
class TextBoxWidget(xmlui_base.TextWidget, StringWidget):
- type = u"textbox"
+ type = "textbox"
# TODO: use a more advanced input method
def show(self):
@@ -244,25 +244,25 @@ class TextBoxWidget(xmlui_base.TextWidget, StringWidget):
self.disp(self.value)
else:
if self.value:
- self.disp(A.color(C.A_HEADER, u"↓ current value ↓\n", A.FG_CYAN, self.value,
+ self.disp(A.color(C.A_HEADER, "↓ current value ↓\n", A.FG_CYAN, self.value,
""))
values = []
while True:
try:
if not values:
- line = raw_input(A.color(C.A_HEADER, u"[Ctrl-D to finish]> "))
+ line = input(A.color(C.A_HEADER, "[Ctrl-D to finish]> "))
else:
- line = raw_input()
+ line = input()
values.append(line)
except EOFError:
break
- self.value = u'\n'.join(values).rstrip()
+ self.value = '\n'.join(values).rstrip()
class XHTMLBoxWidget(xmlui_base.XHTMLBoxWidget, StringWidget):
- type = u"xhtmlbox"
+ type = "xhtmlbox"
def show(self):
# FIXME: we use bridge in a blocking way as permitted by python-dbus
@@ -274,7 +274,7 @@ class XHTMLBoxWidget(xmlui_base.XHTMLBoxWidget, StringWidget):
class ListWidget(xmlui_base.ListWidget, OptionsWidget):
- type = u"list"
+ type = "list"
# TODO: handle flags, notably multi
def show(self):
@@ -291,7 +291,7 @@ class ListWidget(xmlui_base.ListWidget, OptionsWidget):
for idx, (value, label) in enumerate(self.options):
elems = []
if not self.root.read_only:
- elems.extend([C.A_SUBHEADER, unicode(idx), A.RESET, u": "])
+ elems.extend([C.A_SUBHEADER, str(idx), A.RESET, ": "])
elems.append(label)
self.verboseName(elems, value)
self.disp(A.color(*elems))
@@ -308,8 +308,8 @@ class ListWidget(xmlui_base.ListWidget, OptionsWidget):
choice = None
limit_max = len(self.options) - 1
while choice is None or choice < 0 or choice > limit_max:
- choice = raw_input(
- A.color(C.A_HEADER, _(u"your choice (0-{max}): ").format(max=limit_max))
+ choice = input(
+ A.color(C.A_HEADER, _("your choice (0-{max}): ").format(max=limit_max))
)
try:
choice = int(choice)
@@ -320,25 +320,25 @@ class ListWidget(xmlui_base.ListWidget, OptionsWidget):
class BoolWidget(xmlui_base.BoolWidget, InputWidget):
- type = u"bool"
+ type = "bool"
def show(self):
- disp_true = A.color(A.FG_GREEN, u"TRUE")
- disp_false = A.color(A.FG_RED, u"FALSE")
+ disp_true = A.color(A.FG_GREEN, "TRUE")
+ disp_false = A.color(A.FG_RED, "FALSE")
if self.read_only or self.root.read_only:
self.disp(disp_true if self.value else disp_false)
else:
- self.disp(A.color(C.A_HEADER, u"0: ",
+ self.disp(A.color(C.A_HEADER, "0: ",
disp_false, A.RESET,
- u" *" if not self.value else u""))
- self.disp(A.color(C.A_HEADER, u"1: ",
+ " *" if not self.value else ""))
+ self.disp(A.color(C.A_HEADER, "1: ",
disp_true, A.RESET,
- u" *" if self.value else u""))
+ " *" if self.value else ""))
choice = None
while choice not in ("0", "1"):
- elems = [C.A_HEADER, _(u"your choice (0,1): ")]
+ elems = [C.A_HEADER, _("your choice (0,1): ")]
self.verboseName(elems)
- choice = raw_input(A.color(*elems))
+ choice = input(A.color(*elems))
self.value = bool(int(choice))
self.disp("")
@@ -350,7 +350,7 @@ class BoolWidget(xmlui_base.BoolWidget, InputWidget):
class Container(Base):
- category = u"container"
+ category = "container"
def __init__(self, xmlui_parent):
super(Container, self).__init__(xmlui_parent)
@@ -371,22 +371,22 @@ class Container(Base):
class VerticalContainer(xmlui_base.VerticalContainer, Container):
- type = u"vertical"
+ type = "vertical"
class PairsContainer(xmlui_base.PairsContainer, Container):
- type = u"pairs"
+ type = "pairs"
class LabelContainer(xmlui_base.PairsContainer, Container):
- type = u"label"
+ type = "label"
def show(self):
for child in self.children:
no_lf = False
# we check linked widget type
# to see if we want the label on the same line or not
- if child.type == u"label":
+ if child.type == "label":
for_name = child.for_name
if for_name:
for_widget = self.root.widgets[for_name]
@@ -535,7 +535,7 @@ class XMLUIPanel(xmlui_base.XMLUIPanel):
def _launchActionCb(self, data):
XMLUIPanel._actions -= 1
assert XMLUIPanel._actions >= 0
- if u"xmlui" in data:
+ if "xmlui" in data:
xmlui_raw = data["xmlui"]
xmlui = create(self.host, xmlui_raw)
xmlui.show()
@@ -557,7 +557,7 @@ class XMLUIPanel(xmlui_base.XMLUIPanel):
callback=self._launchActionCb,
errback=partial(
self.command.errback,
- msg=_(u"can't launch XMLUI action: {}"),
+ msg=_("can't launch XMLUI action: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
diff --git a/sat_frontends/primitivus/chat.py b/sat_frontends/primitivus/chat.py
index 337b5629..cfc6ec64 100644
--- a/sat_frontends/primitivus/chat.py
+++ b/sat_frontends/primitivus/chat.py
@@ -35,7 +35,7 @@ from functools import total_ordering
import bisect
-OCCUPANTS_FOOTER = _(u"{} occupants")
+OCCUPANTS_FOOTER = _("{} occupants")
class MessageWidget(urwid.WidgetWrap, quick_chat.MessageWidget):
@@ -113,16 +113,16 @@ class MessageWidget(urwid.WidgetWrap, quick_chat.MessageWidget):
# message status
if d.status is None:
- markup.append(u" ")
+ markup.append(" ")
elif d.status == "delivered":
- markup.append(("msg_status_received", u"✔"))
+ markup.append(("msg_status_received", "✔"))
else:
- log.warning(u"Unknown status: {}".format(d.status))
+ log.warning("Unknown status: {}".format(d.status))
# timestamp
if self.parent.show_timestamp:
attr = "msg_mention" if mention else "date"
- markup.append((attr, u"[{}]".format(d.time_text)))
+ markup.append((attr, "[{}]".format(d.time_text)))
else:
if mention:
markup.append(("msg_mention", "[*]"))
@@ -134,13 +134,13 @@ class MessageWidget(urwid.WidgetWrap, quick_chat.MessageWidget):
)
else:
markup.append(
- ("my_nick" if d.own_mess else "other_nick", u"[{}] ".format(d.nick or ""))
+ ("my_nick" if d.own_mess else "other_nick", "[{}] ".format(d.nick or ""))
)
msg = self.message # needed to generate self.selected_lang
if d.selected_lang:
- markup.append(("msg_lang", u"[{}] ".format(d.selected_lang)))
+ markup.append(("msg_lang", "[{}] ".format(d.selected_lang)))
# message body
markup.append(msg)
@@ -171,6 +171,9 @@ class OccupantWidget(urwid.WidgetWrap):
)
super(OccupantWidget, self).__init__(text)
+ def __hash__(self):
+ return id(self)
+
def __eq__(self, other):
if other is None:
return False
@@ -218,11 +221,11 @@ class OccupantWidget(urwid.WidgetWrap):
o = self.occupant_data
markup = []
markup.append(
- ("info_msg", u"{}{} ".format(o.role[0].upper(), o.affiliation[0].upper()))
+ ("info_msg", "{}{} ".format(o.role[0].upper(), o.affiliation[0].upper()))
)
markup.append(o.nick)
if o.state is not None:
- markup.append(u" {}".format(C.CHAT_STATE_ICON[o.state]))
+ markup.append(" {}".format(C.CHAT_STATE_ICON[o.state]))
return markup
# events
@@ -240,7 +243,7 @@ class OccupantsWidget(urwid.WidgetWrap):
urwid.ListBox(self.occupants_walker), footer=self.occupants_footer
)
super(OccupantsWidget, self).__init__(occupants_widget)
- occupants_list = sorted(self.parent.occupants.keys(), key=lambda o: o.lower())
+ occupants_list = sorted(list(self.parent.occupants.keys()), key=lambda o: o.lower())
for occupant in occupants_list:
occupant_data = self.parent.occupants[occupant]
self.occupants_walker.append(OccupantWidget(occupant_data))
@@ -253,7 +256,7 @@ class OccupantsWidget(urwid.WidgetWrap):
txt = OCCUPANTS_FOOTER.format(len(self.parent.occupants))
self.occupants_footer.set_text(txt)
- def getNicks(self, start=u""):
+ def getNicks(self, start=""):
"""Return nicks of all occupants
@param start(unicode): only return nicknames which start with this text
@@ -281,16 +284,16 @@ class OccupantsWidget(urwid.WidgetWrap):
class Chat(PrimitivusWidget, quick_chat.QuickChat):
def __init__(self, host, target, type_=C.CHAT_ONE2ONE, nick=None, occupants=None,
subject=None, profiles=None):
- quick_chat.QuickChat.__init__(
- self, host, target, type_, nick, occupants, subject, profiles=profiles
- )
self.filters = [] # list of filter callbacks to apply
self.mess_walker = urwid.SimpleListWalker([])
self.mess_widgets = urwid.ListBox(self.mess_walker)
self.chat_widget = urwid.Frame(self.mess_widgets)
self.chat_colums = urwid.Columns([("weight", 8, self.chat_widget)])
self.pile = urwid.Pile([self.chat_colums])
- PrimitivusWidget.__init__(self, self.pile, self.target)
+ PrimitivusWidget.__init__(self, self.pile, target)
+ quick_chat.QuickChat.__init__(
+ self, host, target, type_, nick, occupants, subject, profiles=profiles
+ )
# we must adapt the behaviour with the type
if type_ == C.CHAT_GROUP:
@@ -365,7 +368,7 @@ class Chat(PrimitivusWidget, quick_chat.QuickChat):
if word_idx == len(words):
word_idx = 0
word = completion_data["last_word"] = words[word_idx]
- return u"{}{}{}".format(text[: space + 1], word, ": " if space < 0 else "")
+ return "{}{}{}".format(text[: space + 1], word, ": " if space < 0 else "")
def getMenu(self):
"""Return Menu bar"""
@@ -479,7 +482,7 @@ class Chat(PrimitivusWidget, quick_chat.QuickChat):
if wid.mess_data.mention:
from_jid = wid.mess_data.from_jid
msg = _(
- u"You have been mentioned by {nick} in {room}".format(
+ "You have been mentioned by {nick} in {room}".format(
nick=wid.mess_data.nick, room=self.target
)
)
@@ -490,7 +493,7 @@ class Chat(PrimitivusWidget, quick_chat.QuickChat):
return
elif self.type == C.CHAT_ONE2ONE:
from_jid = wid.mess_data.from_jid
- msg = _(u"{entity} is talking to you".format(entity=from_jid))
+ msg = _("{entity} is talking to you".format(entity=from_jid))
self.host.notify(
C.NOTIFY_MESSAGE, from_jid, msg, widget=self, profile=self.profile
)
@@ -557,7 +560,7 @@ class Chat(PrimitivusWidget, quick_chat.QuickChat):
"""Set title for a group chat"""
quick_chat.QuickChat.setSubject(self, subject)
self.subj_wid = urwid.Text(
- unicode(subject.replace("\n", "|") if wrap == "clip" else subject),
+ str(subject.replace("\n", "|") if wrap == "clip" else subject),
align="left" if wrap == "clip" else "center",
wrap=wrap,
)
@@ -573,7 +576,7 @@ class Chat(PrimitivusWidget, quick_chat.QuickChat):
"""
if clear:
del self.mess_walker[:]
- for message in self.messages.itervalues():
+ for message in self.messages.values():
self.appendMessage(message, minor_notifs=False)
def redraw(self):
@@ -589,13 +592,13 @@ class Chat(PrimitivusWidget, quick_chat.QuickChat):
if filters and "search" in filters:
self.mess_walker.append(
urwid.Text(
- _(u"Results for searching the globbing pattern: {}").format(
+ _("Results for searching the globbing pattern: {}").format(
filters["search"]
)
)
)
self.mess_walker.append(
- urwid.Text(_(u"Type ':history ' to reset the chat history"))
+ urwid.Text(_("Type ':history ' to reset the chat history"))
)
super(Chat, self).updateHistory(size, filters, profile)
@@ -675,8 +678,8 @@ class Chat(PrimitivusWidget, quick_chat.QuickChat):
def onSubjectDialog(self, new_subject=None):
dialog = sat_widgets.InputDialog(
- _(u"Change title"),
- _(u"Enter the new title"),
+ _("Change title"),
+ _("Enter the new title"),
default_txt=new_subject if new_subject is not None else self.subject,
)
dialog.setCallback("ok", self._onSubjectDialogCb, dialog)
diff --git a/sat_frontends/primitivus/config.py b/sat_frontends/primitivus/config.py
index b1b4cba0..2035d469 100644
--- a/sat_frontends/primitivus/config.py
+++ b/sat_frontends/primitivus/config.py
@@ -21,7 +21,7 @@
from sat_frontends.primitivus.constants import Const as C
from sat_frontends.primitivus.keys import action_key_map
-import ConfigParser
+import configparser
def applyConfig(host):
@@ -29,11 +29,11 @@ def applyConfig(host):
raise: can raise various Exceptions if configuration is not good
"""
- config = ConfigParser.SafeConfigParser()
+ config = configparser.SafeConfigParser()
config.read(C.CONFIG_FILES)
try:
options = config.items(C.CONFIG_SECTION)
- except ConfigParser.NoSectionError:
+ except configparser.NoSectionError:
options = []
shortcuts = {}
for name, value in options:
diff --git a/sat_frontends/primitivus/constants.py b/sat_frontends/primitivus/constants.py
index a4bb1417..4799d92a 100644
--- a/sat_frontends/primitivus/constants.py
+++ b/sat_frontends/primitivus/constants.py
@@ -83,12 +83,12 @@ class Const(constants.Const):
("table_selected", "default, bold", "default"),
]
PRESENCE = {
- "unavailable": (u"⨯", "show_disconnected"),
- "": (u"✔", "show_normal"),
- "chat": (u"✆", "show_chat"),
- "away": (u"✈", "show_away"),
- "dnd": (u"✖", "show_dnd"),
- "xa": (u"☄", "show_xa"),
+ "unavailable": ("⨯", "show_disconnected"),
+ "": ("✔", "show_normal"),
+ "chat": ("✆", "show_chat"),
+ "away": ("✈", "show_away"),
+ "dnd": ("✖", "show_dnd"),
+ "xa": ("☄", "show_xa"),
}
LOG_OPT_SECTION = APP_NAME.lower()
LOG_OPT_OUTPUT = (
diff --git a/sat_frontends/primitivus/contact_list.py b/sat_frontends/primitivus/contact_list.py
index 441b81a6..6e3faac1 100644
--- a/sat_frontends/primitivus/contact_list.py
+++ b/sat_frontends/primitivus/contact_list.py
@@ -47,7 +47,7 @@ class ContactList(PrimitivusWidget, QuickContactList):
# we now build the widget
self.status_bar = StatusBar(host)
self.frame = sat_widgets.FocusFrame(self._buildList(), None, self.status_bar)
- PrimitivusWidget.__init__(self, self.frame, _(u"Contacts"))
+ PrimitivusWidget.__init__(self, self.frame, _("Contacts"))
if on_click:
urwid.connect_signal(self, "click", on_click, user_data)
if on_change:
@@ -134,7 +134,7 @@ class ContactList(PrimitivusWidget, QuickContactList):
pass
idx += 1
- log.debug(u"Not element found for {} in setFocus".format(text))
+ log.debug("Not element found for {} in setFocus".format(text))
# events
@@ -159,7 +159,7 @@ class ContactList(PrimitivusWidget, QuickContactList):
def onNotification(self, entity, notif, profile):
notifs = list(self.host.getNotifs(C.ENTITY_ALL, profile=self.profile))
if notifs:
- self.title_dynamic = u"({})".format(len(notifs))
+ self.title_dynamic = "({})".format(len(notifs))
else:
self.title_dynamic = None
self.host.redraw() # FIXME: should not be necessary
@@ -217,7 +217,7 @@ class ContactList(PrimitivusWidget, QuickContactList):
if show is None:
show = C.PRESENCE_UNAVAILABLE
show_icon, entity_attr = C.PRESENCE.get(show, ("", "default"))
- markup.insert(0, u"{} ".format(show_icon))
+ markup.insert(0, "{} ".format(show_icon))
else:
entity_attr = "default"
@@ -229,9 +229,9 @@ class ContactList(PrimitivusWidget, QuickContactList):
)
if notifs or mentions:
attr = 'cl_mention' if mentions else 'cl_notifs'
- header = [(attr, u"({})".format(len(notifs) + len(mentions))), u" "]
+ header = [(attr, "({})".format(len(notifs) + len(mentions))), " "]
else:
- header = u""
+ header = ""
markup.append((entity_attr, entity_txt))
if markup_prepend:
@@ -333,7 +333,7 @@ class ContactList(PrimitivusWidget, QuickContactList):
content.append(urwid.Divider("="))
groups = list(self.contact_list._groups)
- groups.sort(key=lambda x: x.lower() if x else x)
+ groups.sort(key=lambda x: x.lower() if x else '')
for group in groups:
data = self.contact_list.getGroupData(group)
folded = data.get(C.GROUP_DATA_FOLDED, False)
diff --git a/sat_frontends/primitivus/game_tarot.py b/sat_frontends/primitivus/game_tarot.py
index 51582a2b..b3d53682 100644
--- a/sat_frontends/primitivus/game_tarot.py
+++ b/sat_frontends/primitivus/game_tarot.py
@@ -154,20 +154,20 @@ class Card(TarotCard):
suit = "A"
color = "neutral"
elif self.suit == "pique":
- suit = u"♠"
+ suit = "♠"
color = "black"
elif self.suit == "trefle":
- suit = u"♣"
+ suit = "♣"
color = "black"
elif self.suit == "coeur":
- suit = u"♥"
+ suit = "♥"
color = "red"
elif self.suit == "carreau":
- suit = u"♦"
+ suit = "♦"
color = "red"
if self.bout:
color = "special"
- return ("card_%s" % color, u"%s%s" % (value, suit))
+ return ("card_%s" % color, "%s%s" % (value, suit))
def getWidget(self):
"""Return a widget representing the card"""
@@ -256,12 +256,12 @@ class TarotGame(QuickTarotGame, urwid.WidgetWrap):
def loadCards(self):
"""Load all the cards in memory"""
QuickTarotGame.loadCards(self)
- for value in map(str, range(1, 22)) + ["excuse"]:
+ for value in list(map(str, list(range(1, 22)))) + ["excuse"]:
card = Card("atout", value)
self.cards[card.suit, card.value] = card
self.deck.append(card)
for suit in ["pique", "coeur", "carreau", "trefle"]:
- for value in map(str, range(1, 11)) + ["valet", "cavalier", "dame", "roi"]:
+ for value in list(map(str, list(range(1, 11)))) + ["valet", "cavalier", "dame", "roi"]:
card = Card(suit, value)
self.cards[card.suit, card.value] = card
self.deck.append(card)
diff --git a/sat_frontends/primitivus/primitivus b/sat_frontends/primitivus/primitivus
index 6544b9f8..440ea363 100755
--- a/sat_frontends/primitivus/primitivus
+++ b/sat_frontends/primitivus/primitivus
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Primitivus: a SAT frontend
diff --git a/sat_frontends/primitivus/widget.py b/sat_frontends/primitivus/widget.py
index c1b0ac35..fd3c61b7 100644
--- a/sat_frontends/primitivus/widget.py
+++ b/sat_frontends/primitivus/widget.py
@@ -59,8 +59,8 @@ class PrimitivusWidget(urwid.WidgetWrap):
if self._title_dynamic:
title_elts.append(self._title_dynamic)
if len(all_profiles) > 1 and profiles:
- title_elts.append(u"[{}]".format(u", ".join(profiles)))
- return sat_widgets.SurroundedText(u" ".join(title_elts))
+ title_elts.append("[{}]".format(", ".join(profiles)))
+ return sat_widgets.SurroundedText(" ".join(title_elts))
@title.setter
def title(self, value):
diff --git a/sat_frontends/primitivus/xmlui.py b/sat_frontends/primitivus/xmlui.py
index f0946a7d..9e9c7efc 100644
--- a/sat_frontends/primitivus/xmlui.py
+++ b/sat_frontends/primitivus/xmlui.py
@@ -65,18 +65,18 @@ class PrimitivusJidWidget(xmlui.JidWidget, PrimitivusTextWidget):
class PrimitivusDividerWidget(xmlui.DividerWidget, urwid.Divider):
def __init__(self, _xmlui_parent, style="line"):
if style == "line":
- div_char = u"─"
+ div_char = "─"
elif style == "dot":
- div_char = u"·"
+ div_char = "·"
elif style == "dash":
- div_char = u"-"
+ div_char = "-"
elif style == "plain":
- div_char = u"█"
+ div_char = "█"
elif style == "blank":
div_char = " "
else:
log.warning(_("Unknown div_char"))
- div_char = u"─"
+ div_char = "─"
urwid.Divider.__init__(self, div_char)
diff --git a/sat_frontends/quick_frontend/constants.py b/sat_frontends/quick_frontend/constants.py
index 986496d0..ad5ad316 100644
--- a/sat_frontends/quick_frontend/constants.py
+++ b/sat_frontends/quick_frontend/constants.py
@@ -66,12 +66,12 @@ class Const(constants.Const):
# Chats
CHAT_STATE_ICON = {
- "": u" ",
- "active": u"✔",
- "inactive": u"☄",
- "gone": u"✈",
- "composing": u"✎",
- "paused": u"…",
+ "": " ",
+ "active": "✔",
+ "inactive": "☄",
+ "gone": "✈",
+ "composing": "✎",
+ "paused": "…",
}
# Blogs
diff --git a/sat_frontends/quick_frontend/quick_app.py b/sat_frontends/quick_frontend/quick_app.py
index a1f4d152..bb6246b8 100644
--- a/sat_frontends/quick_frontend/quick_app.py
+++ b/sat_frontends/quick_frontend/quick_app.py
@@ -40,12 +40,12 @@ import time
try:
# FIXME: to be removed when an acceptable solution is here
- unicode("") # XXX: unicode doesn't exist in pyjamas
+ str("") # XXX: unicode doesn't exist in pyjamas
except (
TypeError,
AttributeError,
): # Error raised is not the same depending on pyjsbuild options
- unicode = str
+ str = str
class ProfileManager(object):
@@ -139,7 +139,7 @@ class ProfileManager(object):
)
def _plug_profile_getFeaturesEb(self, failure):
- log.error(u"Couldn't get features: {}".format(failure))
+ log.error("Couldn't get features: {}".format(failure))
self._plug_profile_getFeaturesCb({})
def _plug_profile_getFeaturesCb(self, features):
@@ -154,14 +154,14 @@ class ProfileManager(object):
self._plug_profile_gotCachedValues({})
def _plug_profile_failedCachedValues(self, failure):
- log.error(u"Couldn't get cached values: {}".format(failure))
+ log.error("Couldn't get cached values: {}".format(failure))
self._plug_profile_gotCachedValues({})
def _plug_profile_gotCachedValues(self, cached_values):
contact_list = self.host.contact_lists[self.profile]
# add the contact list and its listener
- for entity_s, data in cached_values.iteritems():
- for key, value in data.iteritems():
+ for entity_s, data in cached_values.items():
+ for key, value in data.items():
self.host.entityDataUpdatedHandler(entity_s, key, value, self.profile)
if not self.connected:
@@ -203,7 +203,7 @@ class ProfileManager(object):
for contact in presences:
for res in presences[contact]:
- jabber_id = (u"%s/%s" % (jid.JID(contact).bare, res)) if res else contact
+ jabber_id = ("%s/%s" % (jid.JID(contact).bare, res)) if res else contact
show = presences[contact][res][0]
priority = presences[contact][res][1]
statuses = presences[contact][res][2]
@@ -216,7 +216,7 @@ class ProfileManager(object):
self.profile,
callback=lambda data, contact=contact: gotEntityData(data, contact),
errback=lambda failure, contact=contact: log.debug(
- u"No cache data for {}".format(contact)
+ "No cache data for {}".format(contact)
),
)
@@ -238,7 +238,7 @@ class ProfilesManager(object):
return profile in self._profiles
def __iter__(self):
- return self._profiles.iterkeys()
+ return iter(self._profiles.keys())
def __getitem__(self, profile):
return self._profiles[profile]
@@ -246,11 +246,11 @@ class ProfilesManager(object):
def __len__(self):
return len(self._profiles)
- def iteritems(self):
- return self._profiles.iteritems()
+ def items(self):
+ return self._profiles.items()
- def itervalues(self):
- return self._profiles.itervalues()
+ def values(self):
+ return self._profiles.values()
def plug(self, profile):
if profile in self._profiles:
@@ -271,7 +271,7 @@ class ProfilesManager(object):
del self._profiles[profile]
def chooseOneProfile(self):
- return self._profiles.keys()[0]
+ return list(self._profiles.keys())[0]
class QuickApp(object):
@@ -350,13 +350,13 @@ class QuickApp(object):
self.ns_map = ns_map
def _namespacesGetEb(self, failure_):
- log.error(_(u"Can't get namespaces map: {msg}").format(msg=failure_))
+ log.error(_("Can't get namespaces map: {msg}").format(msg=failure_))
def _encryptionPluginsGetCb(self, plugins):
self.encryption_plugins = plugins
def _encryptionPluginsGetEb(self, failure_):
- log.warning(_(u"Can't retrieve encryption plugins: {msg}").format(msg=failure_))
+ log.warning(_("Can't retrieve encryption plugins: {msg}").format(msg=failure_))
def onBridgeConnected(self):
self.bridge.namespacesGet(
@@ -402,13 +402,13 @@ class QuickApp(object):
def _bridgeEb(self, failure):
if isinstance(failure, exceptions.BridgeExceptionNoService):
- print(_(u"Can't connect to SàT backend, are you sure it's launched ?"))
+ print((_("Can't connect to SàT backend, are you sure it's launched ?")))
sys.exit(1)
elif isinstance(failure, exceptions.BridgeInitError):
- print(_(u"Can't init bridge"))
+ print((_("Can't init bridge")))
sys.exit(1)
else:
- print(_(u"Error while initialising bridge: {}".format(failure)))
+ print((_("Error while initialising bridge: {}".format(failure))))
@property
def current_profile(self):
@@ -459,10 +459,10 @@ class QuickApp(object):
or if connection has been lost and a reconnection is needed
"""
if state:
- log.debug(u"we are synchronised with server")
+ log.debug("we are synchronised with server")
if self.AUTO_RESYNC:
# we are resynchronising all widgets
- log.debug(u"doing a full widgets resynchronisation")
+ log.debug("doing a full widgets resynchronisation")
for w in self.widgets:
try:
resync = w.resync
@@ -474,7 +474,7 @@ class QuickApp(object):
self._sync = state
else:
- log.debug(u"we have lost synchronisation with server")
+ log.debug("we have lost synchronisation with server")
self._sync = state
# we've lost synchronisation, all widgets must be notified
# note: this is always called independently of AUTO_RESYNC
@@ -496,7 +496,7 @@ class QuickApp(object):
@param with_profile (boolean): True if the signal concerns a specific profile,
in that case the profile name has to be passed by the caller
"""
- log.debug(u"registering signal {name}".format(name=function_name))
+ log.debug("registering signal {name}".format(name=function_name))
if handler is None:
handler = getattr(self, "{}{}".format(function_name, "Handler"))
if not with_profile:
@@ -582,7 +582,7 @@ class QuickApp(object):
pass
else:
profile = kwargs.get("profile")
- for listener, profiles_filter in listeners.iteritems():
+ for listener, profiles_filter in listeners.items():
if profile is None or not profiles_filter or profile in profiles_filter:
listener(*args, **kwargs)
@@ -617,7 +617,7 @@ class QuickApp(object):
cached_signals = self.signals_cache.pop(profile, [])
for function_name, handler, args, kwargs in cached_signals:
log.debug(
- u"Calling cached signal [%s] with args %s and kwargs %s"
+ "Calling cached signal [%s] with args %s and kwargs %s"
% (function_name, args, kwargs)
)
handler(*args, **kwargs)
@@ -632,7 +632,7 @@ class QuickApp(object):
if not errback:
def errback(failure):
- log.error(_(u"Can't connect profile [%s]") % failure)
+ log.error(_("Can't connect profile [%s]") % failure)
try:
module = failure.module
except AttributeError:
@@ -790,8 +790,8 @@ class QuickApp(object):
widget.onMessageState(uid, status, profile)
def messageSend(self, to_jid, message, subject=None, mess_type="auto", extra=None, callback=None, errback=None, profile_key=C.PROF_KEY_NONE):
- if not subject and not extra and (not message or message == {u'': u''}):
- log.debug(u"Not sending empty message")
+ if not subject and not extra and (not message or message == {'': ''}):
+ log.debug("Not sending empty message")
return
if subject is None:
@@ -812,7 +812,7 @@ class QuickApp(object):
return
self.bridge.messageSend(
- unicode(to_jid),
+ str(to_jid),
message,
subject,
mess_type,
@@ -857,8 +857,8 @@ class QuickApp(object):
def mucRoomJoinedHandler(self, room_jid_s, occupants, user_nick, subject, profile):
"""Called when a MUC room is joined"""
log.debug(
- u"Room [{room_jid}] joined by {profile}, users presents:{users}".format(
- room_jid=room_jid_s, profile=profile, users=occupants.keys()
+ "Room [{room_jid}] joined by {profile}, users presents:{users}".format(
+ room_jid=room_jid_s, profile=profile, users=list(occupants.keys())
)
)
room_jid = jid.JID(room_jid_s)
@@ -876,7 +876,7 @@ class QuickApp(object):
def mucRoomLeftHandler(self, room_jid_s, profile):
"""Called when a MUC room is left"""
log.debug(
- u"Room [%(room_jid)s] left by %(profile)s"
+ "Room [%(room_jid)s] left by %(profile)s"
% {"room_jid": room_jid_s, "profile": profile}
)
room_jid = jid.JID(room_jid_s)
@@ -893,7 +893,7 @@ class QuickApp(object):
)
chat_widget.changeUserNick(old_nick, new_nick)
log.debug(
- u"user [%(old_nick)s] is now known as [%(new_nick)s] in room [%(room_jid)s]"
+ "user [%(old_nick)s] is now known as [%(new_nick)s] in room [%(room_jid)s]"
% {"old_nick": old_nick, "new_nick": new_nick, "room_jid": room_jid}
)
@@ -905,7 +905,7 @@ class QuickApp(object):
)
chat_widget.setSubject(subject)
log.debug(
- u"new subject for room [%(room_jid)s]: %(subject)s"
+ "new subject for room [%(room_jid)s]: %(subject)s"
% {"room_jid": room_jid, "subject": subject}
)
@@ -974,7 +974,7 @@ class QuickApp(object):
main_notif_dict = self.profiles[profile].notifications
if entity is C.ENTITY_ALL:
- selected_notifs = main_notif_dict.itervalues()
+ selected_notifs = iter(main_notif_dict.values())
exact_jid = False
else:
if entity is None:
@@ -989,7 +989,7 @@ class QuickApp(object):
for notifs_from_select in selected_notifs:
if type_ is None:
- type_notifs = notifs_from_select.itervalues()
+ type_notifs = iter(notifs_from_select.values())
else:
type_notifs = (notifs_from_select.get(type_, []),)
@@ -1080,10 +1080,10 @@ class QuickApp(object):
callbacks.append((callback, errback))
def progressStartedHandler(self, pid, metadata, profile):
- log.info(u"Progress {} started".format(pid))
+ log.info("Progress {} started".format(pid))
def progressFinishedHandler(self, pid, metadata, profile):
- log.info(u"Progress {} finished".format(pid))
+ log.info("Progress {} finished".format(pid))
try:
callbacks = self._progress_ids.pop(pid)
except KeyError:
@@ -1095,7 +1095,7 @@ class QuickApp(object):
self.callListeners("progressFinished", pid, metadata, profile=profile)
def progressErrorHandler(self, pid, err_msg, profile):
- log.warning(u"Progress {pid} error: {err_msg}".format(pid=pid, err_msg=err_msg))
+ log.warning("Progress {pid} error: {err_msg}".format(pid=pid, err_msg=err_msg))
try:
callbacks = self._progress_ids.pop(pid)
except KeyError:
@@ -1109,7 +1109,7 @@ class QuickApp(object):
def _subscribe_cb(self, answer, data):
entity, profile = data
type_ = "subscribed" if answer else "unsubscribed"
- self.bridge.subscription(type_, unicode(entity.bare), profile_key=profile)
+ self.bridge.subscription(type_, str(entity.bare), profile_key=profile)
def subscribeHandler(self, type, raw_jid, profile):
"""Called when a subsciption management signal is received"""
@@ -1118,18 +1118,18 @@ class QuickApp(object):
# this is a subscription confirmation, we just have to inform user
# TODO: call self.getEntityMBlog to add the new contact blogs
self.showDialog(
- _(u"The contact {contact} has accepted your subscription").format(
+ _("The contact {contact} has accepted your subscription").format(
contact=entity.bare
),
- _(u"Subscription confirmation"),
+ _("Subscription confirmation"),
)
elif type == "unsubscribed":
# this is a subscription refusal, we just have to inform user
self.showDialog(
- _(u"The contact {contact} has refused your subscription").format(
+ _("The contact {contact} has refused your subscription").format(
contact=entity.bare
),
- _(u"Subscription refusal"),
+ _("Subscription refusal"),
"error",
)
elif type == "subscribe":
@@ -1137,8 +1137,8 @@ class QuickApp(object):
# TODO: use sat.stdui.ui_contact_list to display the groups selector
self.showDialog(
_(
- u"The contact {contact} wants to subscribe to your presence"
- u".\nDo you accept ?"
+ "The contact {contact} wants to subscribe to your presence"
+ ".\nDo you accept ?"
).format(contact=entity.bare),
_("Subscription confirmation"),
"yes/no",
@@ -1147,11 +1147,11 @@ class QuickApp(object):
)
def _debugHandler(self, action, parameters, profile):
- if action == u"widgets_dump":
+ if action == "widgets_dump":
from pprint import pformat
- log.info(u"Widgets dump:\n{data}".format(data=pformat(self.widgets._widgets)))
+ log.info("Widgets dump:\n{data}".format(data=pformat(self.widgets._widgets)))
else:
- log.warning(u"Unknown debug action: {action}".format(action=action))
+ log.warning("Unknown debug action: {action}".format(action=action))
def showDialog(self, message, title, type="info", answer_cb=None, answer_data=None):
@@ -1178,11 +1178,11 @@ class QuickApp(object):
pass # FIXME
def dialogFailure(self, failure):
- log.warning(u"Failure: {}".format(failure))
+ log.warning("Failure: {}".format(failure))
def progressIdHandler(self, progress_id, profile):
"""Callback used when an action result in a progress id"""
- log.info(u"Progress ID received: {}".format(progress_id))
+ log.info("Progress ID received: {}".format(progress_id))
def isHidden(self):
"""Tells if the frontend window is hidden.
@@ -1193,11 +1193,11 @@ class QuickApp(object):
def paramUpdateHandler(self, name, value, namespace, profile):
log.debug(
- _(u"param update: [%(namespace)s] %(name)s = %(value)s")
+ _("param update: [%(namespace)s] %(name)s = %(value)s")
% {"namespace": namespace, "name": name, "value": value}
)
if (namespace, name) == ("Connection", "JabberID"):
- log.debug(_(u"Changing JID to %s") % value)
+ log.debug(_("Changing JID to %s") % value)
self.profiles[profile].whoami = jid.JID(value)
elif (namespace, name) == ("General", C.SHOW_OFFLINE_CONTACTS):
self.contact_lists[profile].showOfflineContacts(C.bool(value))
@@ -1264,13 +1264,13 @@ class QuickApp(object):
# we ignore metadata
action_data = {
- k: v for k, v in action_data.iteritems() if not k.startswith("meta_")
+ k: v for k, v in action_data.items() if not k.startswith("meta_")
}
if action_data:
raise exceptions.DataError(
- u"Not all keys in action_data are managed ({keys})".format(
- keys=", ".join(action_data.keys())
+ "Not all keys in action_data are managed ({keys})".format(
+ keys=", ".join(list(action_data.keys()))
)
)
@@ -1348,10 +1348,10 @@ class QuickApp(object):
def _avatarGetEb(self, failure_, entity, contact_list):
# FIXME: bridge needs a proper error handling
- if "NotFound" in unicode(failure_):
- log.info(u"No avatar found for {entity}".format(entity=entity))
+ if "NotFound" in str(failure_):
+ log.info("No avatar found for {entity}".format(entity=entity))
else:
- log.warning(u"Can't get avatar: {}".format(failure_))
+ log.warning("Can't get avatar: {}".format(failure_))
contact_list.setCache(entity, "avatar", self.getDefaultAvatar(entity))
def getAvatar(
@@ -1383,7 +1383,7 @@ class QuickApp(object):
avatar = None
if avatar is None:
self.bridge.avatarGet(
- unicode(entity),
+ str(entity),
cache_only,
hash_only,
profile=profile,
@@ -1413,7 +1413,7 @@ class QuickApp(object):
def onExit(self):
"""Must be called when the frontend is terminating"""
to_unplug = []
- for profile, profile_manager in self.profiles.iteritems():
+ for profile, profile_manager in self.profiles.items():
if profile_manager.connected and profile_manager.autodisconnect:
# The user wants autodisconnection
self.disconnect(profile)
diff --git a/sat_frontends/quick_frontend/quick_blog.py b/sat_frontends/quick_frontend/quick_blog.py
index 28c865af..c5a216e2 100644
--- a/sat_frontends/quick_frontend/quick_blog.py
+++ b/sat_frontends/quick_frontend/quick_blog.py
@@ -30,12 +30,12 @@ from sat.tools.common import data_format
try:
# FIXME: to be removed when an acceptable solution is here
- unicode("") # XXX: unicode doesn't exist in pyjamas
+ str("") # XXX: unicode doesn't exist in pyjamas
except (
TypeError,
AttributeError,
): # Error raised is not the same depending on pyjsbuild options
- unicode = str
+ str = str
ENTRY_CLS = None
COMMENTS_CLS = None
@@ -266,7 +266,7 @@ class Entry(EntriesManager):
for key in keys_to_keep:
value = getattr(self.item, key)
if value is not None:
- mb_data[key] = unicode(value)
+ mb_data[key] = str(value)
for prefix in ("content", "title"):
for suffix in ("", "_rich", "_xhtml"):
@@ -287,7 +287,7 @@ class Entry(EntriesManager):
mb_data['groups'] = list(self.blog.targets)
self.blog.host.bridge.mbSend(
- unicode(self.service or ""),
+ str(self.service or ""),
self.node or "",
data_format.serialise(mb_data),
profile=self.blog.profile,
@@ -300,14 +300,14 @@ class Entry(EntriesManager):
all children entries will be recursively removed too
"""
# XXX: named delete and not remove to avoid conflict with pyjamas
- log.debug(u"deleting entry {}".format("EDIT ENTRY" if self.new else self.item.id))
+ log.debug("deleting entry {}".format("EDIT ENTRY" if self.new else self.item.id))
for child in self.entries:
child.delete()
try:
self.manager.entries.remove(self)
except ValueError:
if self != self.manager.edit_entry:
- log.error(u"Internal Error: entry not found in manager")
+ log.error("Internal Error: entry not found in manager")
else:
self.manager.edit_entry = None
if not self.new:
@@ -328,12 +328,12 @@ class Entry(EntriesManager):
# TODO: manage several comments nodes case.
if self.item.comments:
self.blog.host.bridge.psNodeDelete(
- unicode(self.item.comments_service) or "",
+ str(self.item.comments_service) or "",
self.item.comments_node,
profile=self.blog.profile,
)
self.blog.host.bridge.mbRetract(
- unicode(self.service or ""),
+ str(self.service or ""),
self.node or "",
self.item.id,
profile=self.blog.profile,
@@ -358,10 +358,10 @@ class QuickBlog(EntriesManager, quick_widgets.QuickWidget):
quick_widgets.QuickWidget.__init__(self, host, targets, C.PROF_KEY_NONE)
self._targets_type = C.ALL
else:
- assert isinstance(targets[0], basestring)
+ assert isinstance(targets[0], str)
quick_widgets.QuickWidget.__init__(self, host, targets[0], C.PROF_KEY_NONE)
for target in targets[1:]:
- assert isinstance(target, basestring)
+ assert isinstance(target, str)
self.addTarget(target)
self._targets_type = C.GROUP
@@ -375,7 +375,7 @@ class QuickBlog(EntriesManager, quick_widgets.QuickWidget):
raise ValueError("Unkown targets type")
def __str__(self):
- return u"Blog Widget [target: {}, profile: {}]".format(
+ return "Blog Widget [target: {}, profile: {}]".format(
", ".join(self.targets), self.profile
)
@@ -436,7 +436,7 @@ class QuickBlog(EntriesManager, quick_widgets.QuickWidget):
own_pep = self.host.whoami.bare
self.host.bridge.mbGetFromManyWithComments(
C.JID,
- (unicode(own_pep),),
+ (str(own_pep),),
10,
10,
{},
@@ -446,7 +446,7 @@ class QuickBlog(EntriesManager, quick_widgets.QuickWidget):
)
else:
raise NotImplementedError(
- u"{} target type is not managed".format(self._targets_type)
+ "{} target type is not managed".format(self._targets_type)
)
def isJidAccepted(self, jid_):
diff --git a/sat_frontends/quick_frontend/quick_chat.py b/sat_frontends/quick_frontend/quick_chat.py
index 6f8f8732..05d14bb2 100644
--- a/sat_frontends/quick_frontend/quick_chat.py
+++ b/sat_frontends/quick_frontend/quick_chat.py
@@ -43,12 +43,12 @@ ROOM_USER_MOVED = (ROOM_USER_JOINED, ROOM_USER_LEFT)
try:
# FIXME: to be removed when an acceptable solution is here
- unicode("") # XXX: unicode doesn't exist in pyjamas
+ str("") # XXX: unicode doesn't exist in pyjamas
except (
TypeError,
AttributeError,
): # Error raised is not the same depending on pyjsbuild options
- unicode = str
+ str = str
# FIXME: day_format need to be settable (i18n)
@@ -78,23 +78,20 @@ class Message(object):
)
# is user mentioned here ?
if self.parent.type == C.CHAT_GROUP and not self.own_mess:
- for m in msg.itervalues():
+ for m in msg.values():
if self.parent.nick.lower() in m.lower():
self._mention = True
break
self.handleMe()
self.widgets = set() # widgets linked to this message
- def __unicode__(self):
- return u"Message<{mess_type}> [{time}]{nick}> {message}".format(
+ def __str__(self):
+ return "Message<{mess_type}> [{time}]{nick}> {message}".format(
mess_type=self.type,
time=self.time_text,
nick=self.nick,
message=self.main_message)
- def __str__(self):
- return self.__unicode__().encode('utf-8', 'ignore')
-
@property
def host(self):
return self.parent.host
@@ -126,28 +123,28 @@ class Message(object):
return self.message[""]
except KeyError:
try:
- lang, mess = self.message.iteritems().next()
+ lang, mess = next(iter(self.message.items()))
self.selected_lang = lang
return mess
except StopIteration:
- log.error(u"Can't find message for uid {}".format(self.uid))
+ log.error("Can't find message for uid {}".format(self.uid))
return ""
@property
def main_message_xhtml(self):
"""rich message"""
- xhtml = {k: v for k, v in self.extra.iteritems() if "html" in k}
+ xhtml = {k: v for k, v in self.extra.items() if "html" in k}
if xhtml:
# FIXME: we only return first found value for now
- return next(xhtml.itervalues())
+ return next(iter(xhtml.values()))
@property
def time_text(self):
"""Return timestamp in a nicely formatted way"""
# if the message was sent before today, we print the full date
timestamp = time.localtime(self.timestamp)
- time_format = u"%c" if timestamp < self.parent.day_change else u"%H:%M"
- return time.strftime(time_format, timestamp).decode(getlocale()[1] or "utf-8")
+ time_format = "%c" if timestamp < self.parent.day_change else "%H:%M"
+ return time.strftime(time_format, timestamp)
@property
def avatar(self):
@@ -162,7 +159,7 @@ class Message(object):
try:
return self.extra["user_nick"]
except KeyError:
- log.error(u"extra data is missing user nick for uid {}".format(self.uid))
+ log.error("extra data is missing user nick for uid {}".format(self.uid))
return ""
# FIXME: converted getSpecials to list for pyjamas
if self.parent.type == C.CHAT_GROUP or entity in list(
@@ -197,8 +194,8 @@ class Message(object):
# TODO: XHTML-IM /me are not handled
me = False
# we need to check /me for every message
- for m in self.message.itervalues():
- if m.startswith(u"/me "):
+ for m in self.message.values():
+ if m.startswith("/me "):
me = True
else:
me = False
@@ -207,8 +204,8 @@ class Message(object):
self.type = C.MESS_TYPE_INFO
self.extra["info_type"] = "me"
nick = self.nick
- for lang, mess in self.message.iteritems():
- self.message[lang] = u"* " + nick + mess[3:]
+ for lang, mess in self.message.items():
+ self.message[lang] = "* " + nick + mess[3:]
class MessageWidget(object):
@@ -245,7 +242,7 @@ class Occupant(object):
@property
def jid(self):
"""jid in the room"""
- return jid.JID(u"{}/{}".format(self.parent.target.bare, self.nick))
+ return jid.JID("{}/{}".format(self.parent.target.bare, self.nick))
@property
def real_jid(self):
@@ -295,10 +292,10 @@ class QuickChat(quick_widgets.QuickWidget):
if type_ == C.CHAT_GROUP:
if target.resource:
raise exceptions.InternalError(
- u"a group chat entity can't have a resource"
+ "a group chat entity can't have a resource"
)
if nick is None:
- raise exceptions.InternalError(u"nick must not be None for group chat")
+ raise exceptions.InternalError("nick must not be None for group chat")
self.nick = nick
self.occupants = {}
@@ -306,7 +303,7 @@ class QuickChat(quick_widgets.QuickWidget):
else:
if occupants is not None or nick is not None:
raise exceptions.InternalError(
- u"only group chat can have occupants or nick"
+ "only group chat can have occupants or nick"
)
self.messages = OrderedDict() # key: uid, value: Message instance
self.games = {} # key=game name (unicode), value=instance of quick_games.RoomGame
@@ -334,25 +331,25 @@ class QuickChat(quick_widgets.QuickWidget):
# FIXME: we don't use getter/setter here because of pyjamas
# TODO: use proper getter/setter once we get rid of pyjamas
if self._locked:
- log.warning(u"{wid} is already locked!".format(wid=self))
+ log.warning("{wid} is already locked!".format(wid=self))
return
self._locked = True
# messageNew signals are cached when locked
self._cache = OrderedDict()
- log.debug(u"{wid} is now locked".format(wid=self))
+ log.debug("{wid} is now locked".format(wid=self))
def setUnlocked(self):
if not self._locked:
- log.debug(u"{wid} was already unlocked".format(wid=self))
+ log.debug("{wid} was already unlocked".format(wid=self))
return
self._locked = False
- for uid, data in self._cache.iteritems():
+ for uid, data in self._cache.items():
if uid not in self.messages:
self.messageNew(*data)
else:
- log.debug(u"discarding message already in history: {data}, ".format(data=data))
+ log.debug("discarding message already in history: {data}, ".format(data=data))
del self._cache
- log.debug(u"{wid} is now unlocked".format(wid=self))
+ log.debug("{wid} is now unlocked".format(wid=self))
def postInit(self):
"""Method to be called by frontend after widget is initialised
@@ -404,8 +401,8 @@ class QuickChat(quick_widgets.QuickWidget):
if self._resync_lock:
return
self._resync_lock = True
- log.debug(u"resynchronising {self}".format(self=self))
- for mess in reversed(self.messages.values()):
+ log.debug("resynchronising {self}".format(self=self))
+ for mess in reversed(list(self.messages.values())):
if mess.type == C.MESS_TYPE_INFO:
continue
last_message = mess
@@ -417,7 +414,7 @@ class QuickChat(quick_widgets.QuickWidget):
if self.type == C.CHAT_GROUP:
self.occupantsClear()
self.host.bridge.mucOccupantsGet(
- unicode(self.target), self.profile, callback=self.updateOccupants,
+ str(self.target), self.profile, callback=self.updateOccupants,
errback=log.error)
self.historyPrint(
size=C.HISTORY_LIMIT_NONE,
@@ -427,15 +424,15 @@ class QuickChat(quick_widgets.QuickWidget):
## Widget management ##
- def __unicode__(self):
- return u"Chat Widget [target: {}, type: {}, profile: {}]".format(
+ def __str__(self):
+ return "Chat Widget [target: {}, type: {}, profile: {}]".format(
self.target, self.type, self.profile
)
@staticmethod
def getWidgetHash(target, profiles):
profile = list(profiles)[0]
- return profile + "\n" + unicode(target.bare)
+ return profile + "\n" + str(target.bare)
@staticmethod
def getPrivateHash(target, profile):
@@ -443,7 +440,7 @@ class QuickChat(quick_widgets.QuickWidget):
This method should be used with force_hash to get unique widget for private MUC conversations
"""
- return (unicode(profile), target)
+ return (str(profile), target)
def addTarget(self, target):
super(QuickChat, self).addTarget(target)
@@ -456,7 +453,7 @@ class QuickChat(quick_widgets.QuickWidget):
"""copy important attribute for a new widget"""
kwargs["type_"] = self.type
if self.type == C.CHAT_GROUP:
- kwargs["occupants"] = {o.nick: o.data for o in self.occupants.itervalues()}
+ kwargs["occupants"] = {o.nick: o.data for o in self.occupants.values()}
kwargs["subject"] = self.subject
try:
kwargs["nick"] = self.nick
@@ -492,7 +489,7 @@ class QuickChat(quick_widgets.QuickWidget):
def setOccupants(self, occupants):
"""Set the whole list of occupants"""
assert len(self.occupants) == 0
- for nick, data in occupants.iteritems():
+ for nick, data in occupants.items():
# XXX: this log is disabled because it's really too verbose
# but kept commented as it may be useful for debugging
# log.debug(u"adding occupant {nick} to {room}".format(
@@ -510,12 +507,12 @@ class QuickChat(quick_widgets.QuickWidget):
updated_occupants = set(occupants)
left_occupants = local_occupants - updated_occupants
joined_occupants = updated_occupants - local_occupants
- log.debug(u"updating occupants for {room}:\n"
- u"left: {left_occupants}\n"
- u"joined: {joined_occupants}"
+ log.debug("updating occupants for {room}:\n"
+ "left: {left_occupants}\n"
+ "joined: {joined_occupants}"
.format(room=self.target,
- left_occupants=u", ".join(left_occupants),
- joined_occupants=u", ".join(joined_occupants)))
+ left_occupants=", ".join(left_occupants),
+ joined_occupants=", ".join(joined_occupants)))
for nick in left_occupants:
self.removeUser(occupants[nick])
for nick in joined_occupants:
@@ -533,7 +530,7 @@ class QuickChat(quick_widgets.QuickWidget):
try:
occupant = self.occupants.pop(nick)
except KeyError:
- log.warning(u"Trying to remove an unknown occupant: {}".format(nick))
+ log.warning("Trying to remove an unknown occupant: {}".format(nick))
else:
return occupant
@@ -602,12 +599,12 @@ class QuickChat(quick_widgets.QuickWidget):
if filters is None:
filters = {}
if size == 0:
- log.debug(u"Empty history requested, skipping")
+ log.debug("Empty history requested, skipping")
self._onHistoryPrinted()
return
- log_msg = _(u"now we print the history")
+ log_msg = _("now we print the history")
if size != C.HISTORY_LIMIT_DEFAULT:
- log_msg += _(u" ({} messages)".format(size))
+ log_msg += _(" ({} messages)".format(size))
log.debug(log_msg)
if self.type == C.CHAT_ONE2ONE:
@@ -661,17 +658,17 @@ class QuickChat(quick_widgets.QuickWidget):
callback()
def _historyGetEb(err):
- log.error(_(u"Can't get history: {}").format(err))
+ log.error(_("Can't get history: {}").format(err))
self._onHistoryPrinted()
if callback is not None:
callback()
self.host.bridge.historyGet(
- unicode(self.host.profiles[profile].whoami.bare),
- unicode(target),
+ str(self.host.profiles[profile].whoami.bare),
+ str(target),
size,
True,
- {k: unicode(v) for k,v in filters.iteritems()},
+ {k: str(v) for k,v in filters.items()},
profile,
callback=_historyGetCb,
errback=_historyGetEb,
@@ -683,7 +680,7 @@ class QuickChat(quick_widgets.QuickWidget):
self.messageEncryptionStarted(session_data)
def messageEncryptionGetEb(self, failure_):
- log.error(_(u"Can't get encryption state: {reason}").format(reason=failure_))
+ log.error(_("Can't get encryption state: {reason}").format(reason=failure_))
def getEncryptionState(self):
"""Retrieve encryption state with current target.
@@ -693,7 +690,7 @@ class QuickChat(quick_widgets.QuickWidget):
"""
if self.type == C.CHAT_GROUP:
return
- self.host.bridge.messageEncryptionGet(unicode(self.target.bare), self.profile,
+ self.host.bridge.messageEncryptionGet(str(self.target.bare), self.profile,
callback=self.messageEncryptionGetCb,
errback=self.messageEncryptionGetEb)
@@ -715,7 +712,7 @@ class QuickChat(quick_widgets.QuickWidget):
return
if not msg and not subject and type_ != C.MESS_TYPE_INFO:
- log.warning(u"Received an empty message for uid {}".format(uid))
+ log.warning("Received an empty message for uid {}".format(uid))
return
if self.type == C.CHAT_GROUP:
@@ -734,7 +731,7 @@ class QuickChat(quick_widgets.QuickWidget):
pass
else:
user_data = {
- k[5:]: v for k, v in extra.iteritems() if k.startswith("user_")
+ k[5:]: v for k, v in extra.items() if k.startswith("user_")
}
if info_type == ROOM_USER_JOINED:
self.addUser(user_data)
@@ -747,18 +744,18 @@ class QuickChat(quick_widgets.QuickWidget):
self.messages[uid] = message
if "received_timestamp" in extra:
- log.warning(u"Delayed message received after history, this should not happen")
+ log.warning("Delayed message received after history, this should not happen")
self.createMessage(message)
def messageEncryptionStarted(self, session_data):
self.encrypted = True
- log.debug(_(u"message encryption started with {target} using {encryption}").format(
- target=self.target, encryption=session_data[u'name']))
+ log.debug(_("message encryption started with {target} using {encryption}").format(
+ target=self.target, encryption=session_data['name']))
def messageEncryptionStopped(self, session_data):
self.encrypted = False
- log.debug(_(u"message encryption stopped with {target} (was using {encryption})")
- .format(target=self.target, encryption=session_data[u'name']))
+ log.debug(_("message encryption stopped with {target} (was using {encryption})")
+ .format(target=self.target, encryption=session_data['name']))
def createMessage(self, message, append=False):
"""Must be implemented by frontend to create and show a new message widget
@@ -810,12 +807,12 @@ class QuickChat(quick_widgets.QuickWidget):
count = wid.reentered_count = 1
nick = wid.mess_data.nick
if message.info_type == ROOM_USER_LEFT:
- wid.message = _(u"<= {nick} has left the room ({count})").format(
+ wid.message = _("<= {nick} has left the room ({count})").format(
nick=nick, count=count
)
else:
wid.message = _(
- u"<=> {nick} re-entered the room ({count})"
+ "<=> {nick} re-entered the room ({count})"
).format(nick=nick, count=count)
wid.reentered_count += 1
return True
@@ -845,7 +842,7 @@ class QuickChat(quick_widgets.QuickWidget):
This change the subject on the room itself (i.e. via XMPP),
while setSubject change the subject of this widget
"""
- self.host.bridge.mucSubject(unicode(self.target), new_subject, self.profile)
+ self.host.bridge.mucSubject(str(self.target), new_subject, self.profile)
def addGamePanel(self, widget):
"""Insert a game panel to this Chat dialog.
@@ -879,7 +876,7 @@ class QuickChat(quick_widgets.QuickWidget):
self.occupants[nick].state = state
except KeyError:
log.warning(
- u"{nick} not found in {room}, ignoring new chat state".format(
+ "{nick} not found in {room}, ignoring new chat state".format(
nick=nick, room=self.target.bare
)
)
@@ -902,7 +899,7 @@ class QuickChat(quick_widgets.QuickWidget):
# entity is not here anymore
pass
- for m in self.messages.values():
+ for m in list(self.messages.values()):
if m.nick == entity.resource:
for w in m.widgets:
w.update({"avatar": filename})
@@ -911,8 +908,8 @@ class QuickChat(quick_widgets.QuickWidget):
entity.bare == self.target.bare
or entity.bare == self.host.profiles[profile].whoami.bare
):
- log.info(u"avatar updated for {}".format(entity))
- for m in self.messages.values():
+ log.info("avatar updated for {}".format(entity))
+ for m in list(self.messages.values()):
if m.from_jid.bare == entity.bare:
for w in m.widgets:
w.update({"avatar": filename})
diff --git a/sat_frontends/quick_frontend/quick_contact_list.py b/sat_frontends/quick_frontend/quick_contact_list.py
index a011efd8..d8799de6 100644
--- a/sat_frontends/quick_frontend/quick_contact_list.py
+++ b/sat_frontends/quick_frontend/quick_contact_list.py
@@ -32,7 +32,7 @@ log = getLogger(__name__)
try:
# FIXME: to be removed when an acceptable solution is here
- unicode("") # XXX: unicode doesn't exist in pyjamas
+ str("") # XXX: unicode doesn't exist in pyjamas
except (TypeError, AttributeError): # Error raised is not the same depending on
# pyjsbuild options
# XXX: pyjamas' max doesn't support key argument, so we implement it ourself
@@ -46,7 +46,7 @@ except (TypeError, AttributeError): # Error raised is not the same depending on
# next doesn't exist in pyjamas
def next(iterable, *args):
try:
- return iterable.next()
+ return iterable.__next__()
except StopIteration as e:
if args:
return args[0]
@@ -184,7 +184,7 @@ class ProfileContactList(object):
@return (dict[jid.JID, set(unicode)])
"""
result = {}
- for group, data in self._groups.iteritems():
+ for group, data in self._groups.items():
for entity in data["jids"]:
result.setdefault(entity, set()).add(group)
return result
@@ -203,7 +203,7 @@ class ProfileContactList(object):
entities are not sorted
"""
- return self._cache.iteritems()
+ return iter(self._cache.items())
@property
def items(self):
@@ -214,7 +214,7 @@ class ProfileContactList(object):
"""
return {
jid_: cache
- for jid_, cache in self._cache.iteritems()
+ for jid_, cache in self._cache.items()
if self.entityVisible(jid_)
}
@@ -340,9 +340,9 @@ class ProfileContactList(object):
@raise ValueError: the entity is not bare
"""
if entity.resource:
- raise ValueError(u"getFullJid must be used with a bare jid")
+ raise ValueError("getFullJid must be used with a bare jid")
main_resource = self.getCache(entity, C.CONTACT_MAIN_RESOURCE)
- return jid.JID(u"{}/{}".format(entity, main_resource))
+ return jid.JID("{}/{}".format(entity, main_resource))
def setGroupData(self, group, name, value):
"""Register a data for a group
@@ -508,7 +508,7 @@ class ProfileContactList(object):
if entity.resource
else cache
)
- for attribute, value in attributes.iteritems():
+ for attribute, value in attributes.items():
if value is None:
# XXX: pyjamas hack: we need to use pop instead of del
try:
@@ -596,7 +596,7 @@ class ProfileContactList(object):
try:
groups = self._cache[entity_bare].get(C.CONTACT_GROUPS, set())
except KeyError:
- log.error(_(u"Trying to delete an unknow entity [{}]").format(entity))
+ log.error(_("Trying to delete an unknow entity [{}]").format(entity))
try:
self._roster.remove(entity_bare)
except KeyError:
@@ -639,8 +639,8 @@ class ProfileContactList(object):
del cache[C.CONTACT_RESOURCES][entity.resource]
except KeyError:
log.error(
- u"Presence unavailable received "
- u"for an unknown resource [{}]".format(entity)
+ "Presence unavailable received "
+ "for an unknown resource [{}]".format(entity)
)
if not cache[C.CONTACT_RESOURCES]:
cache[C.CONTACT_MAIN_RESOURCE] = None
@@ -648,8 +648,8 @@ class ProfileContactList(object):
if not entity.resource:
log.warning(
_(
- u"received presence from entity "
- u"without resource: {}".format(entity)
+ "received presence from entity "
+ "without resource: {}".format(entity)
)
)
resources_data = cache[C.CONTACT_RESOURCES]
@@ -703,12 +703,12 @@ class ProfileContactList(object):
try:
cache = self._cache[entity.bare]
except:
- log.error(u"Try to unselect an entity not in cache")
+ log.error("Try to unselect an entity not in cache")
else:
try:
cache[C.CONTACT_SELECTED].remove(entity.resource)
except KeyError:
- log.error(u"Try to unselect a not selected entity")
+ log.error("Try to unselect a not selected entity")
else:
self._selected.remove(entity)
self.update([entity], C.UPDATE_SELECTION)
@@ -721,15 +721,15 @@ class ProfileContactList(object):
"""
if entity is None:
self._selected.clear()
- for cache in self._cache.itervalues():
+ for cache in self._cache.values():
cache[C.CONTACT_SELECTED].clear()
self.update(type_=C.UPDATE_SELECTION, profile=self.profile)
else:
- log.debug(u"select %s" % entity)
+ log.debug("select %s" % entity)
try:
cache = self._cache[entity.bare]
except:
- log.error(u"Try to select an entity not in cache")
+ log.error("Try to select an entity not in cache")
else:
cache[C.CONTACT_SELECTED].add(entity.resource)
self._selected.add(entity)
@@ -777,7 +777,7 @@ class QuickContactListHandler(object):
global handler
if handler is not None:
raise exceptions.InternalError(
- u"QuickContactListHandler must be instanciated only once"
+ "QuickContactListHandler must be instanciated only once"
)
handler = self
self._clist = {} # key: profile, value: ProfileContactList
@@ -794,7 +794,7 @@ class QuickContactListHandler(object):
@param entity (jid.JID): jid of the entity (resource is not ignored,
use bare jid if needed)
"""
- for contact_list in self._clist.itervalues():
+ for contact_list in self._clist.values():
if entity in contact_list:
return True
return False
@@ -806,7 +806,7 @@ class QuickContactListHandler(object):
@return (set[jid.JID])
"""
entities = set()
- for contact_list in self._clist.itervalues():
+ for contact_list in self._clist.values():
entities.update(contact_list.roster)
return entities
@@ -817,7 +817,7 @@ class QuickContactListHandler(object):
@return (set[jid.JID])
"""
entities = set()
- for contact_list in self._clist.itervalues():
+ for contact_list in self._clist.values():
entities.update(contact_list.roster_connected)
return entities
@@ -829,7 +829,7 @@ class QuickContactListHandler(object):
@return (dict[unicode,set(jid.JID)])
"""
groups = {}
- for contact_list in self._clist.itervalues():
+ for contact_list in self._clist.values():
groups.update(contact_list.roster_entities_by_group)
return groups
@@ -841,7 +841,7 @@ class QuickContactListHandler(object):
@return (dict[jid.JID, set(unicode)])
"""
entities = {}
- for contact_list in self._clist.itervalues():
+ for contact_list in self._clist.values():
entities.update(contact_list.roster_groups_by_entities)
return entities
@@ -852,7 +852,7 @@ class QuickContactListHandler(object):
@return (set): set of selected entities
"""
entities = set()
- for contact_list in self._clist.itervalues():
+ for contact_list in self._clist.values():
entities.update(contact_list.selected)
return entities
@@ -862,7 +862,7 @@ class QuickContactListHandler(object):
items are unordered
"""
- for profile, contact_list in self._clist.iteritems():
+ for profile, contact_list in self._clist.items():
for bare_jid, cache in contact_list.all_iter:
data = cache.copy()
data[C.CONTACT_PROFILE] = profile
@@ -876,8 +876,8 @@ class QuickContactListHandler(object):
key: bare jid, value: data
"""
items = {}
- for profile, contact_list in self._clist.iteritems():
- for bare_jid, cache in contact_list.items.iteritems():
+ for profile, contact_list in self._clist.items():
+ for bare_jid, cache in contact_list.items.items():
data = cache.copy()
items[bare_jid] = data
data[C.CONTACT_PROFILE] = profile
@@ -953,7 +953,7 @@ class QuickContactListHandler(object):
@return (set[jid.JID])
"""
entities = set()
- for contact_list in self._clist.itervalues():
+ for contact_list in self._clist.values():
entities.update(contact_list.getSpecialExtras(special_type))
return entities
@@ -984,13 +984,13 @@ class QuickContactListHandler(object):
assert profile in self._clist
to_fill.add(profile)
else:
- to_fill.update(self._clist.keys())
+ to_fill.update(list(self._clist.keys()))
remaining = to_fill.difference(filled)
if remaining != to_fill:
log.debug(
- u"Not re-filling already filled contact list(s) for {}".format(
- u", ".join(to_fill.intersection(filled))
+ "Not re-filling already filled contact list(s) for {}".format(
+ ", ".join(to_fill.intersection(filled))
)
)
for profile in remaining:
@@ -1001,17 +1001,17 @@ class QuickContactListHandler(object):
@param keep_cache: if True, don't reset the cache
"""
- for contact_list in self._clist.itervalues():
+ for contact_list in self._clist.values():
contact_list.clearContacts(keep_cache)
# we need a full update
self.update()
def select(self, entity):
- for contact_list in self._clist.itervalues():
+ for contact_list in self._clist.values():
contact_list.select(entity)
def unselect(self, entity):
- for contact_list in self._clist.itervalues():
+ for contact_list in self._clist.values():
contact_list.select(entity)
def lockUpdate(self, locked=True, do_update=True):
@@ -1025,8 +1025,8 @@ class QuickContactListHandler(object):
what youa re doing!
"""
log.debug(
- u"Contact lists updates are now {}".format(
- u"LOCKED" if locked else u"UNLOCKED"
+ "Contact lists updates are now {}".format(
+ "LOCKED" if locked else "UNLOCKED"
)
)
self._update_locked = locked
diff --git a/sat_frontends/quick_frontend/quick_contact_management.py b/sat_frontends/quick_frontend/quick_contact_management.py
index 69371f7f..23876a7b 100644
--- a/sat_frontends/quick_frontend/quick_contact_management.py
+++ b/sat_frontends/quick_frontend/quick_contact_management.py
@@ -41,7 +41,7 @@ class QuickContactManagement(object):
def add(self, entity):
"""Add contact to the list, update resources"""
- if not self.__contactlist.has_key(entity.bare):
+ if entity.bare not in self.__contactlist:
self.__contactlist[entity.bare] = {"resources": []}
if not entity.resource:
return
@@ -53,7 +53,7 @@ class QuickContactManagement(object):
"""Return all contacts which are in given group"""
result = []
for contact in self.__contactlist:
- if self.__contactlist[contact].has_key("groups"):
+ if "groups" in self.__contactlist[contact]:
if group in self.__contactlist[contact]["groups"]:
result.append(JID(contact))
return result
@@ -63,11 +63,11 @@ class QuickContactManagement(object):
@param entity: jid of the contact
@param name: name of the attribute
@return: asked attribute"""
- if self.__contactlist.has_key(entity.bare):
+ if entity.bare in self.__contactlist:
if name == "status": # FIXME: for the moment, we only use the first status
if self.__contactlist[entity.bare]["statuses"]:
- return self.__contactlist[entity.bare]["statuses"].values()[0]
- if self.__contactlist[entity.bare].has_key(name):
+ return list(self.__contactlist[entity.bare]["statuses"].values())[0]
+ if name in self.__contactlist[entity.bare]:
return self.__contactlist[entity.bare][name]
else:
log.debug(_("Trying to get attribute for an unknown contact"))
@@ -75,7 +75,7 @@ class QuickContactManagement(object):
def isConnected(self, entity):
"""Tell if the contact is online"""
- return self.__contactlist.has_key(entity.bare)
+ return entity.bare in self.__contactlist
def remove(self, entity):
"""remove resource. If no more resource is online or is no resource is specified, contact is deleted"""
@@ -95,7 +95,7 @@ class QuickContactManagement(object):
@param key: name of the attribute
@param value: value of the attribute
"""
- if self.__contactlist.has_key(entity.bare):
+ if entity.bare in self.__contactlist:
self.__contactlist[entity.bare][key] = value
else:
log.debug(_("Trying to update an unknown contact: %s") % entity.bare)
diff --git a/sat_frontends/quick_frontend/quick_game_tarot.py b/sat_frontends/quick_frontend/quick_game_tarot.py
index f54d4ccf..6747e563 100644
--- a/sat_frontends/quick_frontend/quick_game_tarot.py
+++ b/sat_frontends/quick_frontend/quick_game_tarot.py
@@ -33,15 +33,15 @@ class QuickTarotGame(object):
for player in players:
self.played[player] = None
self.player_nick = parent.nick
- self.bottom_nick = unicode(self.player_nick)
+ self.bottom_nick = str(self.player_nick)
idx = self.players.index(self.player_nick)
idx = (idx + 1) % len(self.players)
- self.right_nick = unicode(self.players[idx])
+ self.right_nick = str(self.players[idx])
idx = (idx + 1) % len(self.players)
- self.top_nick = unicode(self.players[idx])
+ self.top_nick = str(self.players[idx])
idx = (idx + 1) % len(self.players)
- self.left_nick = unicode(self.players[idx])
- self.bottom_nick = unicode(self.player_nick)
+ self.left_nick = str(self.players[idx])
+ self.bottom_nick = str(self.player_nick)
self.selected = [] # Card choosed by the player (e.g. during ecart)
self.hand_size = 13 # number of cards in a hand
self.hand = []
diff --git a/sat_frontends/quick_frontend/quick_games.py b/sat_frontends/quick_frontend/quick_games.py
index d384562e..485f80b3 100644
--- a/sat_frontends/quick_frontend/quick_games.py
+++ b/sat_frontends/quick_frontend/quick_games.py
@@ -27,7 +27,7 @@ from sat_frontends.tools import jid
from sat_frontends.tools import games
from sat_frontends.quick_frontend.constants import Const as C
-import quick_chat
+from . import quick_chat
class RoomGame(object):
@@ -82,9 +82,9 @@ class RoomGame(object):
if real_class == cls:
host.showDialog(
_(
- u"A {game} activity between {players} has been started, but you couldn't take part because your client doesn't support it."
+ "A {game} activity between {players} has been started, but you couldn't take part because your client doesn't support it."
).format(game=cls._game_name, players=", ".join(players)),
- _(u"{game} Game").format(game=cls._game_name),
+ _("{game} Game").format(game=cls._game_name),
)
return
panel = real_class(chat_widget, referee, players, *args)
diff --git a/sat_frontends/quick_frontend/quick_menus.py b/sat_frontends/quick_frontend/quick_menus.py
index 238ac3fc..a30989f7 100644
--- a/sat_frontends/quick_frontend/quick_menus.py
+++ b/sat_frontends/quick_frontend/quick_menus.py
@@ -19,12 +19,12 @@
try:
# FIXME: to be removed when an acceptable solution is here
- unicode("") # XXX: unicode doesn't exist in pyjamas
+ str("") # XXX: unicode doesn't exist in pyjamas
except (
TypeError,
AttributeError,
): # Error raised is not the same depending on pyjsbuild options
- unicode = str
+ str = str
from sat.core.log import getLogger
from sat.core.i18n import _, languageSwitch
@@ -100,11 +100,11 @@ class MenuItem(MenuBase):
else:
if caller is None:
- log.error(u"Caller can't be None with a dictionary as data_collector")
+ log.error("Caller can't be None with a dictionary as data_collector")
return {}
data = {}
- for data_key, caller_attr in data_collector.iteritems():
- data[data_key] = unicode(getattr(caller, caller_attr))
+ for data_key, caller_attr in data_collector.items():
+ data[data_key] = str(getattr(caller, caller_attr))
return data
def call(self, caller, profile=C.PROF_KEY_NONE):
@@ -189,7 +189,7 @@ class MenuSeparator(MenuItem):
def __init__(self):
MenuSeparator.SEP_IDX += 1
- name = u"___separator_{}".format(MenuSeparator.SEP_IDX)
+ name = "___separator_{}".format(MenuSeparator.SEP_IDX)
MenuItem.__init__(self, name, name)
@@ -208,7 +208,7 @@ class MenuContainer(MenuBase):
return item.canonical in self._items
def __iter__(self):
- return self._items.itervalues()
+ return iter(self._items.values())
def __getitem__(self, item):
try:
@@ -218,8 +218,8 @@ class MenuContainer(MenuBase):
def getOrCreate(self, item):
log.debug(
- u"MenuContainer getOrCreate: item=%s name=%s\nlist=%s"
- % (item, item.canonical, self._items.keys())
+ "MenuContainer getOrCreate: item=%s name=%s\nlist=%s"
+ % (item, item.canonical, list(self._items.keys()))
)
try:
return self[item]
@@ -229,7 +229,7 @@ class MenuContainer(MenuBase):
def getActiveMenus(self):
"""Return an iterator on active children"""
- for child in self._items.itervalues():
+ for child in self._items.values():
if child.ACTIVE:
yield child
@@ -347,7 +347,7 @@ class QuickMenusManager(object):
try:
return QuickMenusManager._data_collectors[type_]
except KeyError:
- log.error(u"No data collector registered for {}".format(type_))
+ log.error("No data collector registered for {}".format(type_))
return None
def addMenuItem(self, type_, path, item, path_i18n=None, top_extra=None):
@@ -375,14 +375,14 @@ class QuickMenusManager(object):
elif isinstance(container_item, MenuHook):
# MenuHook must not be replaced
log.debug(
- u"ignoring menu at path [{}] because a hook is already in place".format(
+ "ignoring menu at path [{}] because a hook is already in place".format(
path
)
)
else:
- log.error(u"Conflicting menus at path [{}]".format(path))
+ log.error("Conflicting menus at path [{}]".format(path))
else:
- log.debug(u"Adding menu [{type_}] {path}".format(type_=type_, path=path))
+ log.debug("Adding menu [{type_}] {path}".format(type_=type_, path=path))
menu_container.append(item)
self.host.callListeners("menu", type_, path, path_i18n, item)
@@ -461,7 +461,7 @@ class QuickMenusManager(object):
type_, path[-1], path_i18n[-1], callback=callback, extra=extra
)
self.addMenuItem(type_, path[:-1], menu_item, path_i18n[:-1], top_extra)
- log.info(u"Menu hook set on {path} ({type_})".format(path=path, type_=type_))
+ log.info("Menu hook set on {path} ({type_})".format(path=path, type_=type_))
def addCategory(self, type_, path, path_i18n=None, extra=None, top_extra=None):
"""Create a category with all parents, and set extra on the last one
diff --git a/sat_frontends/quick_frontend/quick_profile_manager.py b/sat_frontends/quick_frontend/quick_profile_manager.py
index a8573be6..07502727 100644
--- a/sat_frontends/quick_frontend/quick_profile_manager.py
+++ b/sat_frontends/quick_frontend/quick_profile_manager.py
@@ -122,7 +122,7 @@ class QuickProfileManager(object):
)
def getProfileNameEb(failure):
- log.error(u"Can't retrieve profile name: {}".format(failure))
+ log.error("Can't retrieve profile name: {}".format(failure))
for profile_key in profile_keys:
self.host.bridge.profileNameGet(
@@ -130,7 +130,7 @@ class QuickProfileManager(object):
)
def getParamError(self, __):
- self.host.showDialog(_(u"Error"), _("Can't get profile parameter"), "error")
+ self.host.showDialog(_("Error"), _("Can't get profile parameter"), "error")
## Helping methods ##
@@ -215,14 +215,14 @@ class QuickProfileManager(object):
self.host.bridge.setParam(
"JabberID", login, "Connection", profile_key=self.current.profile
)
- log.info(u"login updated for profile [{}]".format(self.current.profile))
+ log.info("login updated for profile [{}]".format(self.current.profile))
if password != self.current.password and self.current.password is not None:
self.current.password = password
self.host.bridge.setParam(
"Password", password, "Connection", profile_key=self.current.profile
)
log.info(
- u"password updated for profile [{}]".format(self.current.profile)
+ "password updated for profile [{}]".format(self.current.profile)
)
## graphic updates (should probably be overriden in frontends) ##
diff --git a/sat_frontends/quick_frontend/quick_utils.py b/sat_frontends/quick_frontend/quick_utils.py
index a61dcc30..2920976e 100644
--- a/sat_frontends/quick_frontend/quick_utils.py
+++ b/sat_frontends/quick_frontend/quick_utils.py
@@ -50,5 +50,5 @@ def check_options():
(options, args) = parser.parse_args()
if options.profile:
- options.profile = options.profile.decode("utf-8")
+ options.profile = options.profile
return options
diff --git a/sat_frontends/quick_frontend/quick_widgets.py b/sat_frontends/quick_frontend/quick_widgets.py
index a2ecb95b..2d04ca1a 100644
--- a/sat_frontends/quick_frontend/quick_widgets.py
+++ b/sat_frontends/quick_frontend/quick_widgets.py
@@ -29,12 +29,12 @@ classes_map = {}
try:
# FIXME: to be removed when an acceptable solution is here
- unicode("") # XXX: unicode doesn't exist in pyjamas
+ str("") # XXX: unicode doesn't exist in pyjamas
except (
TypeError,
AttributeError,
): # Error raised is not the same depending on pyjsbuild options
- unicode = str
+ str = str
def register(base_cls, child_cls=None):
@@ -63,8 +63,8 @@ class QuickWidgetsManager(object):
def __iter__(self):
"""Iterate throught all widgets"""
- for widget_map in self._widgets.itervalues():
- for widget_instances in widget_map.itervalues():
+ for widget_map in self._widgets.values():
+ for widget_instances in widget_map.values():
for widget in widget_instances:
yield widget
@@ -114,14 +114,14 @@ class QuickWidgetsManager(object):
return
else:
if target is not None:
- filter_hash = unicode(class_.getWidgetHash(target, profiles))
+ filter_hash = str(class_.getWidgetHash(target, profiles))
else:
filter_hash = None
if filter_hash is not None:
for widget in widgets_map.get(filter_hash, []):
yield widget
else:
- for widget_instances in widgets_map.itervalues():
+ for widget_instances in widgets_map.values():
for widget in widget_instances:
yield widget
@@ -136,7 +136,7 @@ class QuickWidgetsManager(object):
@return: a class_ instance or None if the widget doesn't exist
"""
assert (target is not None) or (profiles is not None)
- if profiles is not None and isinstance(profiles, unicode):
+ if profiles is not None and isinstance(profiles, str):
profiles = [profiles]
class_ = self.getRealClass(class_)
hash_ = class_.getWidgetHash(target, profiles)
@@ -223,7 +223,7 @@ class QuickWidgetsManager(object):
if widget is None:
# we need to create a new widget
- log.debug(u"Creating new widget for target {} {}".format(target, cls))
+ log.debug("Creating new widget for target {} {}".format(target, cls))
widget = cls(*_args, **_kwargs)
widgets_map[hash_] = [widget]
@@ -248,13 +248,13 @@ class QuickWidgetsManager(object):
recreateArgs(_args, _kwargs)
widget = cls(*_args, **_kwargs)
widgets_map[hash_].append(widget)
- log.debug(u"widget <{wid}> already exists, a new one has been recreated"
+ log.debug("widget <{wid}> already exists, a new one has been recreated"
.format(wid=widget))
elif callable(on_existing_widget):
widget = on_existing_widget(widget)
if widget is None:
raise exceptions.InternalError(
- u"on_existing_widget method must return the widget to use")
+ "on_existing_widget method must return the widget to use")
else:
raise exceptions.InternalError(
"Unexpected on_existing_widget value ({})".format(on_existing_widget))
@@ -295,9 +295,9 @@ class QuickWidgetsManager(object):
try:
widgets_map = self._widgets[class_.__name__]
except KeyError:
- log.error(u"no widgets_map found for class {cls}".format(cls=class_))
+ log.error("no widgets_map found for class {cls}".format(cls=class_))
return
- widget_hash = unicode(class_.getWidgetHash(widget_to_delete.target,
+ widget_hash = str(class_.getWidgetHash(widget_to_delete.target,
widget_to_delete.profiles))
widget_instances = widgets_map[widget_hash]
if all_instances:
@@ -306,16 +306,16 @@ class QuickWidgetsManager(object):
try:
widget_instances.remove(widget_to_delete)
except ValueError:
- log.error(u"widget_to_delete not found in widget instances")
+ log.error("widget_to_delete not found in widget instances")
return
- log.debug(u"widget {} deleted".format(widget_to_delete))
+ log.debug("widget {} deleted".format(widget_to_delete))
if not widget_instances:
# all instances with this hash have been deleted
# we remove the hash itself
del widgets_map[widget_hash]
- log.debug(u"All instances of {cls} with hash {widget_hash} have been deleted"
+ log.debug("All instances of {cls} with hash {widget_hash} have been deleted"
.format(cls=class_, widget_hash=widget_hash))
@@ -345,7 +345,7 @@ class QuickWidget(object):
self.addTarget(target)
self.profiles = set()
self._sync = True
- if isinstance(profiles, basestring):
+ if isinstance(profiles, str):
self.addProfile(profiles)
elif profiles is None:
if not self.PROFILES_ALLOW_NONE:
@@ -430,7 +430,7 @@ class QuickWidget(object):
@param profiles: profile(s) associated to target, see __init__ docstring
@return: a hash (can correspond to one or many targets or profiles, depending of widget class)
"""
- return unicode(target) # by defaut, there is one hash for one target
+ return str(target) # by defaut, there is one hash for one target
# widget life events
diff --git a/sat_frontends/tools/css_color.py b/sat_frontends/tools/css_color.py
index bf515ebd..74c4b065 100644
--- a/sat_frontends/tools/css_color.py
+++ b/sat_frontends/tools/css_color.py
@@ -23,154 +23,154 @@ log = getLogger(__name__)
CSS_COLORS = {
- u"black": u"000000",
- u"silver": u"c0c0c0",
- u"gray": u"808080",
- u"white": u"ffffff",
- u"maroon": u"800000",
- u"red": u"ff0000",
- u"purple": u"800080",
- u"fuchsia": u"ff00ff",
- u"green": u"008000",
- u"lime": u"00ff00",
- u"olive": u"808000",
- u"yellow": u"ffff00",
- u"navy": u"000080",
- u"blue": u"0000ff",
- u"teal": u"008080",
- u"aqua": u"00ffff",
- u"orange": u"ffa500",
- u"aliceblue": u"f0f8ff",
- u"antiquewhite": u"faebd7",
- u"aquamarine": u"7fffd4",
- u"azure": u"f0ffff",
- u"beige": u"f5f5dc",
- u"bisque": u"ffe4c4",
- u"blanchedalmond": u"ffebcd",
- u"blueviolet": u"8a2be2",
- u"brown": u"a52a2a",
- u"burlywood": u"deb887",
- u"cadetblue": u"5f9ea0",
- u"chartreuse": u"7fff00",
- u"chocolate": u"d2691e",
- u"coral": u"ff7f50",
- u"cornflowerblue": u"6495ed",
- u"cornsilk": u"fff8dc",
- u"crimson": u"dc143c",
- u"darkblue": u"00008b",
- u"darkcyan": u"008b8b",
- u"darkgoldenrod": u"b8860b",
- u"darkgray": u"a9a9a9",
- u"darkgreen": u"006400",
- u"darkgrey": u"a9a9a9",
- u"darkkhaki": u"bdb76b",
- u"darkmagenta": u"8b008b",
- u"darkolivegreen": u"556b2f",
- u"darkorange": u"ff8c00",
- u"darkorchid": u"9932cc",
- u"darkred": u"8b0000",
- u"darksalmon": u"e9967a",
- u"darkseagreen": u"8fbc8f",
- u"darkslateblue": u"483d8b",
- u"darkslategray": u"2f4f4f",
- u"darkslategrey": u"2f4f4f",
- u"darkturquoise": u"00ced1",
- u"darkviolet": u"9400d3",
- u"deeppink": u"ff1493",
- u"deepskyblue": u"00bfff",
- u"dimgray": u"696969",
- u"dimgrey": u"696969",
- u"dodgerblue": u"1e90ff",
- u"firebrick": u"b22222",
- u"floralwhite": u"fffaf0",
- u"forestgreen": u"228b22",
- u"gainsboro": u"dcdcdc",
- u"ghostwhite": u"f8f8ff",
- u"gold": u"ffd700",
- u"goldenrod": u"daa520",
- u"greenyellow": u"adff2f",
- u"grey": u"808080",
- u"honeydew": u"f0fff0",
- u"hotpink": u"ff69b4",
- u"indianred": u"cd5c5c",
- u"indigo": u"4b0082",
- u"ivory": u"fffff0",
- u"khaki": u"f0e68c",
- u"lavender": u"e6e6fa",
- u"lavenderblush": u"fff0f5",
- u"lawngreen": u"7cfc00",
- u"lemonchiffon": u"fffacd",
- u"lightblue": u"add8e6",
- u"lightcoral": u"f08080",
- u"lightcyan": u"e0ffff",
- u"lightgoldenrodyellow": u"fafad2",
- u"lightgray": u"d3d3d3",
- u"lightgreen": u"90ee90",
- u"lightgrey": u"d3d3d3",
- u"lightpink": u"ffb6c1",
- u"lightsalmon": u"ffa07a",
- u"lightseagreen": u"20b2aa",
- u"lightskyblue": u"87cefa",
- u"lightslategray": u"778899",
- u"lightslategrey": u"778899",
- u"lightsteelblue": u"b0c4de",
- u"lightyellow": u"ffffe0",
- u"limegreen": u"32cd32",
- u"linen": u"faf0e6",
- u"mediumaquamarine": u"66cdaa",
- u"mediumblue": u"0000cd",
- u"mediumorchid": u"ba55d3",
- u"mediumpurple": u"9370db",
- u"mediumseagreen": u"3cb371",
- u"mediumslateblue": u"7b68ee",
- u"mediumspringgreen": u"00fa9a",
- u"mediumturquoise": u"48d1cc",
- u"mediumvioletred": u"c71585",
- u"midnightblue": u"191970",
- u"mintcream": u"f5fffa",
- u"mistyrose": u"ffe4e1",
- u"moccasin": u"ffe4b5",
- u"navajowhite": u"ffdead",
- u"oldlace": u"fdf5e6",
- u"olivedrab": u"6b8e23",
- u"orangered": u"ff4500",
- u"orchid": u"da70d6",
- u"palegoldenrod": u"eee8aa",
- u"palegreen": u"98fb98",
- u"paleturquoise": u"afeeee",
- u"palevioletred": u"db7093",
- u"papayawhip": u"ffefd5",
- u"peachpuff": u"ffdab9",
- u"peru": u"cd853f",
- u"pink": u"ffc0cb",
- u"plum": u"dda0dd",
- u"powderblue": u"b0e0e6",
- u"rosybrown": u"bc8f8f",
- u"royalblue": u"4169e1",
- u"saddlebrown": u"8b4513",
- u"salmon": u"fa8072",
- u"sandybrown": u"f4a460",
- u"seagreen": u"2e8b57",
- u"seashell": u"fff5ee",
- u"sienna": u"a0522d",
- u"skyblue": u"87ceeb",
- u"slateblue": u"6a5acd",
- u"slategray": u"708090",
- u"slategrey": u"708090",
- u"snow": u"fffafa",
- u"springgreen": u"00ff7f",
- u"steelblue": u"4682b4",
- u"tan": u"d2b48c",
- u"thistle": u"d8bfd8",
- u"tomato": u"ff6347",
- u"turquoise": u"40e0d0",
- u"violet": u"ee82ee",
- u"wheat": u"f5deb3",
- u"whitesmoke": u"f5f5f5",
- u"yellowgreen": u"9acd32",
- u"rebeccapurple": u"663399",
+ "black": "000000",
+ "silver": "c0c0c0",
+ "gray": "808080",
+ "white": "ffffff",
+ "maroon": "800000",
+ "red": "ff0000",
+ "purple": "800080",
+ "fuchsia": "ff00ff",
+ "green": "008000",
+ "lime": "00ff00",
+ "olive": "808000",
+ "yellow": "ffff00",
+ "navy": "000080",
+ "blue": "0000ff",
+ "teal": "008080",
+ "aqua": "00ffff",
+ "orange": "ffa500",
+ "aliceblue": "f0f8ff",
+ "antiquewhite": "faebd7",
+ "aquamarine": "7fffd4",
+ "azure": "f0ffff",
+ "beige": "f5f5dc",
+ "bisque": "ffe4c4",
+ "blanchedalmond": "ffebcd",
+ "blueviolet": "8a2be2",
+ "brown": "a52a2a",
+ "burlywood": "deb887",
+ "cadetblue": "5f9ea0",
+ "chartreuse": "7fff00",
+ "chocolate": "d2691e",
+ "coral": "ff7f50",
+ "cornflowerblue": "6495ed",
+ "cornsilk": "fff8dc",
+ "crimson": "dc143c",
+ "darkblue": "00008b",
+ "darkcyan": "008b8b",
+ "darkgoldenrod": "b8860b",
+ "darkgray": "a9a9a9",
+ "darkgreen": "006400",
+ "darkgrey": "a9a9a9",
+ "darkkhaki": "bdb76b",
+ "darkmagenta": "8b008b",
+ "darkolivegreen": "556b2f",
+ "darkorange": "ff8c00",
+ "darkorchid": "9932cc",
+ "darkred": "8b0000",
+ "darksalmon": "e9967a",
+ "darkseagreen": "8fbc8f",
+ "darkslateblue": "483d8b",
+ "darkslategray": "2f4f4f",
+ "darkslategrey": "2f4f4f",
+ "darkturquoise": "00ced1",
+ "darkviolet": "9400d3",
+ "deeppink": "ff1493",
+ "deepskyblue": "00bfff",
+ "dimgray": "696969",
+ "dimgrey": "696969",
+ "dodgerblue": "1e90ff",
+ "firebrick": "b22222",
+ "floralwhite": "fffaf0",
+ "forestgreen": "228b22",
+ "gainsboro": "dcdcdc",
+ "ghostwhite": "f8f8ff",
+ "gold": "ffd700",
+ "goldenrod": "daa520",
+ "greenyellow": "adff2f",
+ "grey": "808080",
+ "honeydew": "f0fff0",
+ "hotpink": "ff69b4",
+ "indianred": "cd5c5c",
+ "indigo": "4b0082",
+ "ivory": "fffff0",
+ "khaki": "f0e68c",
+ "lavender": "e6e6fa",
+ "lavenderblush": "fff0f5",
+ "lawngreen": "7cfc00",
+ "lemonchiffon": "fffacd",
+ "lightblue": "add8e6",
+ "lightcoral": "f08080",
+ "lightcyan": "e0ffff",
+ "lightgoldenrodyellow": "fafad2",
+ "lightgray": "d3d3d3",
+ "lightgreen": "90ee90",
+ "lightgrey": "d3d3d3",
+ "lightpink": "ffb6c1",
+ "lightsalmon": "ffa07a",
+ "lightseagreen": "20b2aa",
+ "lightskyblue": "87cefa",
+ "lightslategray": "778899",
+ "lightslategrey": "778899",
+ "lightsteelblue": "b0c4de",
+ "lightyellow": "ffffe0",
+ "limegreen": "32cd32",
+ "linen": "faf0e6",
+ "mediumaquamarine": "66cdaa",
+ "mediumblue": "0000cd",
+ "mediumorchid": "ba55d3",
+ "mediumpurple": "9370db",
+ "mediumseagreen": "3cb371",
+ "mediumslateblue": "7b68ee",
+ "mediumspringgreen": "00fa9a",
+ "mediumturquoise": "48d1cc",
+ "mediumvioletred": "c71585",
+ "midnightblue": "191970",
+ "mintcream": "f5fffa",
+ "mistyrose": "ffe4e1",
+ "moccasin": "ffe4b5",
+ "navajowhite": "ffdead",
+ "oldlace": "fdf5e6",
+ "olivedrab": "6b8e23",
+ "orangered": "ff4500",
+ "orchid": "da70d6",
+ "palegoldenrod": "eee8aa",
+ "palegreen": "98fb98",
+ "paleturquoise": "afeeee",
+ "palevioletred": "db7093",
+ "papayawhip": "ffefd5",
+ "peachpuff": "ffdab9",
+ "peru": "cd853f",
+ "pink": "ffc0cb",
+ "plum": "dda0dd",
+ "powderblue": "b0e0e6",
+ "rosybrown": "bc8f8f",
+ "royalblue": "4169e1",
+ "saddlebrown": "8b4513",
+ "salmon": "fa8072",
+ "sandybrown": "f4a460",
+ "seagreen": "2e8b57",
+ "seashell": "fff5ee",
+ "sienna": "a0522d",
+ "skyblue": "87ceeb",
+ "slateblue": "6a5acd",
+ "slategray": "708090",
+ "slategrey": "708090",
+ "snow": "fffafa",
+ "springgreen": "00ff7f",
+ "steelblue": "4682b4",
+ "tan": "d2b48c",
+ "thistle": "d8bfd8",
+ "tomato": "ff6347",
+ "turquoise": "40e0d0",
+ "violet": "ee82ee",
+ "wheat": "f5deb3",
+ "whitesmoke": "f5f5f5",
+ "yellowgreen": "9acd32",
+ "rebeccapurple": "663399",
}
-DEFAULT = u"000000"
+DEFAULT = "000000"
def parse(raw_value, as_string=True):
@@ -186,52 +186,52 @@ def parse(raw_value, as_string=True):
If value can't be parsed, a warning message is logged, and DEFAULT is returned
"""
raw_value = raw_value.strip().lower()
- if raw_value.startswith(u"#"):
+ if raw_value.startswith("#"):
# we have a hexadecimal value
str_value = raw_value[1:]
if len(raw_value) in (3, 4):
- str_value = u"".join([2 * v for v in str_value])
- elif raw_value.startswith(u"rgb"):
- left_p = raw_value.find(u"(")
- right_p = raw_value.find(u")")
+ str_value = "".join([2 * v for v in str_value])
+ elif raw_value.startswith("rgb"):
+ left_p = raw_value.find("(")
+ right_p = raw_value.find(")")
rgb_values = [v.strip() for v in raw_value[left_p + 1 : right_p].split(",")]
- expected_len = 4 if raw_value.startswith(u"rgba") else 3
+ expected_len = 4 if raw_value.startswith("rgba") else 3
if len(rgb_values) != expected_len:
- log.warning(u"incorrect value: {}".format(raw_value))
+ log.warning("incorrect value: {}".format(raw_value))
str_value = DEFAULT
else:
int_values = []
for rgb_v in rgb_values:
- p_idx = rgb_v.find(u"%")
+ p_idx = rgb_v.find("%")
if p_idx == -1:
# base 10 value
try:
int_v = int(rgb_v)
if int_v > 255:
- raise ValueError(u"value exceed 255")
+ raise ValueError("value exceed 255")
int_values.append(int_v)
except ValueError:
- log.warning(u"invalid int: {}".format(rgb_v))
+ log.warning("invalid int: {}".format(rgb_v))
int_values.append(0)
else:
# percentage
try:
int_v = int(int(rgb_v[:p_idx]) / 100.0 * 255)
if int_v > 255:
- raise ValueError(u"value exceed 255")
+ raise ValueError("value exceed 255")
int_values.append(int_v)
except ValueError:
- log.warning(u"invalid percent value: {}".format(rgb_v))
+ log.warning("invalid percent value: {}".format(rgb_v))
int_values.append(0)
- str_value = u"".join([u"{:02x}".format(v) for v in int_values])
- elif raw_value.startswith(u"hsl"):
- log.warning(u"hue-saturation-lightness not handled yet") # TODO
+ str_value = "".join(["{:02x}".format(v) for v in int_values])
+ elif raw_value.startswith("hsl"):
+ log.warning("hue-saturation-lightness not handled yet") # TODO
str_value = DEFAULT
else:
try:
str_value = CSS_COLORS[raw_value]
except KeyError:
- log.warning(u"unrecognised format: {}".format(raw_value))
+ log.warning("unrecognised format: {}".format(raw_value))
str_value = DEFAULT
if as_string:
@@ -240,6 +240,6 @@ def parse(raw_value, as_string=True):
return tuple(
[
int(str_value[i] + str_value[i + 1], 16)
- for i in xrange(0, len(str_value), 2)
+ for i in range(0, len(str_value), 2)
]
)
diff --git a/sat_frontends/tools/games.py b/sat_frontends/tools/games.py
index 89f8075b..0fd56680 100644
--- a/sat_frontends/tools/games.py
+++ b/sat_frontends/tools/games.py
@@ -26,7 +26,7 @@ SUITS_ORDER = [
"carreau",
"atout",
] # I have switched the usual order 'trefle' and 'carreau' because card are more easy to see if suit colour change (black, red, black, red)
-VALUES_ORDER = [str(i) for i in xrange(1, 11)] + ["valet", "cavalier", "dame", "roi"]
+VALUES_ORDER = [str(i) for i in range(1, 11)] + ["valet", "cavalier", "dame", "roi"]
class TarotCard(object):
@@ -82,4 +82,4 @@ class TarotCard(object):
# These symbols are diplayed by Libervia next to the player's nicknames
-SYMBOLS = {"Radiocol": [u"♬"], "Tarot": [u"♠", u"♣", u"♥", u"♦"]}
+SYMBOLS = {"Radiocol": ["♬"], "Tarot": ["♠", "♣", "♥", "♦"]}
diff --git a/sat_frontends/tools/jid.py b/sat_frontends/tools/jid.py
index b74c4732..b35e644d 100644
--- a/sat_frontends/tools/jid.py
+++ b/sat_frontends/tools/jid.py
@@ -20,12 +20,12 @@
# hack to use this module with pyjamas
try:
- unicode("") # XXX: unicode doesn't exist in pyjamas
+ str("") # XXX: unicode doesn't exist in pyjamas
# normal version
- class BaseJID(unicode):
+ class BaseJID(str):
def __new__(cls, jid_str):
- self = unicode.__new__(cls, cls._normalize(jid_str))
+ self = str.__new__(cls, cls._normalize(jid_str))
return self
def __init__(self, jid_str):
@@ -114,7 +114,7 @@ class JID(BaseJID):
def bare(self):
if not self.node:
return JID(self.domain)
- return JID(u"{}@{}".format(self.node, self.domain))
+ return JID("{}@{}".format(self.node, self.domain))
def is_valid(self):
"""
@@ -131,4 +131,4 @@ def newResource(entity, resource):
@param resource (unicode): new resource
@return: a new JID instance
"""
- return JID(u"%s/%s" % (entity.bare, resource))
+ return JID("%s/%s" % (entity.bare, resource))
diff --git a/sat_frontends/tools/xmlui.py b/sat_frontends/tools/xmlui.py
index 179d580e..5ac74727 100644
--- a/sat_frontends/tools/xmlui.py
+++ b/sat_frontends/tools/xmlui.py
@@ -51,7 +51,7 @@ def getText(node):
for child in node.childNodes:
if child.nodeType == child.TEXT_NODE:
data.append(child.wholeText)
- return u"".join(data)
+ return "".join(data)
class Widget(object):
@@ -295,7 +295,7 @@ class XMLUIBase(object):
top = parsed_dom.documentElement
self.session_id = top.getAttribute("session_id") or None
self.submit_id = top.getAttribute("submit") or None
- self.xmlui_title = title or top.getAttribute("title") or u""
+ self.xmlui_title = title or top.getAttribute("title") or ""
self.hidden = {}
if flags is None:
flags = []
@@ -342,8 +342,8 @@ class XMLUIBase(object):
raise ValueError("Can't submit is self.submit_id is not set")
if "session_id" in data:
raise ValueError(
- u"session_id must no be used in data, it is automaticaly filled with "
- u"self.session_id if present"
+ "session_id must no be used in data, it is automaticaly filled with "
+ "self.session_id if present"
)
if self.session_id is not None:
data["session_id"] = self.session_id
@@ -376,7 +376,7 @@ class ValueGetter(object):
return self.__getitem__(name)
def keys(self):
- return self.widgets.keys()
+ return list(self.widgets.keys())
class XMLUIPanel(XMLUIBase):
@@ -420,7 +420,7 @@ class XMLUIPanel(XMLUIBase):
@staticmethod
def escape(name):
"""Return escaped name for forms"""
- return u"%s%s" % (C.SAT_FORM_PREFIX, name)
+ return "%s%s" % (C.SAT_FORM_PREFIX, name)
@property
def main_cont(self):
@@ -556,7 +556,7 @@ class XMLUIPanel(XMLUIBase):
value = getText(value_elt)
else:
value = (
- node.getAttribute("value") if node.hasAttribute("value") else u""
+ node.getAttribute("value") if node.hasAttribute("value") else ""
)
if type_ == "empty":
ctrl = self.widget_factory.createEmptyWidget(_xmlui_parent)
@@ -569,8 +569,8 @@ class XMLUIPanel(XMLUIBase):
data[CURRENT_LABEL] = ctrl
elif type_ == "hidden":
if name in self.hidden:
- raise exceptions.ConflictError(u"Conflict on hidden value with "
- u"name {name}".format(name=name))
+ raise exceptions.ConflictError("Conflict on hidden value with "
+ "name {name}".format(name=name))
self.hidden[name] = value
continue
elif type_ == "jid":
@@ -617,7 +617,7 @@ class XMLUIPanel(XMLUIBase):
self.ctrl_list[name] = {"type": type_, "control": ctrl}
elif type_ == "list":
style = [] if node.getAttribute("multi") == "yes" else ["single"]
- for attr in (u"noselect", u"extensible", u"reducible", u"inline"):
+ for attr in ("noselect", "extensible", "reducible", "inline"):
if node.getAttribute(attr) == "yes":
style.append(attr)
_options = [
@@ -778,7 +778,7 @@ class XMLUIPanel(XMLUIBase):
escaped = self.escape(field)
ctrl = self.ctrl_list[field]
if isinstance(ctrl["control"], ListWidget):
- data[escaped] = u"\t".join(ctrl["control"]._xmluiGetSelectedValues())
+ data[escaped] = "\t".join(ctrl["control"]._xmluiGetSelectedValues())
else:
data[escaped] = ctrl["control"]._xmluiGetValue()
self._xmluiLaunchAction(callback_id, data)
@@ -810,7 +810,7 @@ class XMLUIPanel(XMLUIBase):
target._xmluiAddValues(values, select=True)
else:
if isinstance(source, ListWidget):
- value = u", ".join(source._xmluiGetSelectedValues())
+ value = ", ".join(source._xmluiGetSelectedValues())
else:
value = source._xmluiGetValue()
if action == "move":
@@ -877,12 +877,12 @@ class XMLUIPanel(XMLUIBase):
ctrl = self.ctrl_list[ctrl_name]
if isinstance(ctrl["control"], ListWidget):
selected_values.append(
- (escaped, u"\t".join(ctrl["control"]._xmluiGetSelectedValues()))
+ (escaped, "\t".join(ctrl["control"]._xmluiGetSelectedValues()))
)
else:
selected_values.append((escaped, ctrl["control"]._xmluiGetValue()))
data = dict(selected_values)
- for key, value in self.hidden.iteritems():
+ for key, value in self.hidden.items():
data[self.escape(key)] = value
if self.submit_id is not None:
@@ -913,7 +913,7 @@ class XMLUIPanel(XMLUIBase):
assert self.type == "param"
for ctrl in self.param_changed:
if isinstance(ctrl, ListWidget):
- value = u"\t".join(ctrl._xmluiGetSelectedValues())
+ value = "\t".join(ctrl._xmluiGetSelectedValues())
else:
value = ctrl._xmluiGetValue()
param_name = ctrl._xmlui_name.split(C.SAT_PARAM_SEPARATOR)[1]
@@ -1012,10 +1012,10 @@ def registerClass(type_, class_):
# TODO: remove this method, as there are seme use cases where different XMLUI
# classes can be used in the same frontend, so a global value is not good
assert type_ in (CLASS_PANEL, CLASS_DIALOG)
- log.warning(u"registerClass for XMLUI is deprecated, please use partial with "
- u"xmlui.create and class_map instead")
+ log.warning("registerClass for XMLUI is deprecated, please use partial with "
+ "xmlui.create and class_map instead")
if type_ in _class_map:
- log.debug(_(u"XMLUI class already registered for {type_}, ignoring").format(
+ log.debug(_("XMLUI class already registered for {type_}, ignoring").format(
type_=type_))
return
diff --git a/setup.py b/setup.py
index b30a8aef..2cf0d683 100644
--- a/setup.py
+++ b/setup.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# SAT: an XMPP client
@@ -76,11 +76,11 @@ def sat_dev_version():
setup(name=NAME,
version=VERSION,
- description=u'Salut à Toi multipurpose and multi frontend XMPP client',
- long_description=u'Salut à Toi (SàT) is a XMPP client based on a daemon/frontend '
- u'architecture. Its multi frontend (desktop, web, console '
- u'interface, CLI, etc) and multipurpose (instant messaging, '
- u'microblogging, games, file sharing, etc).',
+ description='Salut à Toi multipurpose and multi frontend XMPP client',
+ long_description='Salut à Toi (SàT) is a XMPP client based on a daemon/frontend '
+ 'architecture. Its multi frontend (desktop, web, console '
+ 'interface, CLI, etc) and multipurpose (instant messaging, '
+ 'microblogging, games, file sharing, etc).',
author='Association « Salut à Toi »',
author_email='contact@goffi.org',
url='https://salut-a-toi.org',
diff --git a/twisted/plugins/sat_plugin.py b/twisted/plugins/sat_plugin.py
index 979708a1..7e79e342 100644
--- a/twisted/plugins/sat_plugin.py
+++ b/twisted/plugins/sat_plugin.py
@@ -28,7 +28,7 @@ if defer.Deferred.debug:
except ImportError:
pass
-from zope.interface import implements
+from zope.interface import implementer
from twisted.python import usage
from twisted.plugin import IPlugin
from twisted.application.service import IServiceMaker
@@ -49,11 +49,11 @@ class Options(usage.Options):
optParameters = []
-class SatMaker(object):
- implements(IServiceMaker, IPlugin)
+@implementer(IPlugin, IServiceMaker)
+class SatMaker:
tapname = C.APP_NAME_FILE
- description = _(u"%s XMPP client backend") % C.APP_NAME_FULL
+ description = _("%s XMPP client backend") % C.APP_NAME_FULL
options = Options
def makeService(self, options):