massive refactoring to switch from camelCase to snake_case:
historically, Libervia (SàT before) was using camelCase as allowed by PEP8 when using a pre-PEP8 code, to use the same coding style as in Twisted. However, snake_case is more readable and it's better to follow PEP8 best practices, so it has been decided to move on full snake_case. Because Libervia has a huge codebase, this ended with a ugly mix of camelCase and snake_case. To fix that, this patch does a big refactoring by renaming every function and method (including bridge) that are not coming from Twisted or Wokkel, to use fully snake_case. This is a massive change, and may result in some bugs.
This commit is contained in:
parent
d50412c7f7
commit
6a6f15707a
19 changed files with 9945 additions and 9945 deletions
|
|
@ -25,10 +25,10 @@ from . import utils
|
|||
from twisted.internet import defer
|
||||
|
||||
class TriggerManager(sync_trigger.TriggerManager):
|
||||
"""This is a TriggerManager with an new asyncPoint method"""
|
||||
"""This is a TriggerManager with an new async_point method"""
|
||||
|
||||
@defer.inlineCallbacks
|
||||
def asyncPoint(self, point_name, *args, **kwargs):
|
||||
def async_point(self, point_name, *args, **kwargs):
|
||||
"""This put a trigger point with potentially async Deferred
|
||||
|
||||
All the triggers for that point will be run
|
||||
|
|
@ -47,25 +47,25 @@ class TriggerManager(sync_trigger.TriggerManager):
|
|||
|
||||
for priority, trigger in self.__triggers[point_name]:
|
||||
try:
|
||||
cont = yield utils.asDeferred(trigger, *args, **kwargs)
|
||||
cont = yield utils.as_deferred(trigger, *args, **kwargs)
|
||||
if can_cancel and not cont:
|
||||
defer.returnValue(False)
|
||||
except sync_trigger.SkipOtherTriggers:
|
||||
break
|
||||
defer.returnValue(True)
|
||||
|
||||
async def asyncReturnPoint(
|
||||
async def async_return_point(
|
||||
self,
|
||||
point_name: str,
|
||||
*args, **kwargs
|
||||
) -> Tuple[bool, Any]:
|
||||
"""Async version of returnPoint"""
|
||||
"""Async version of return_point"""
|
||||
if point_name not in self.__triggers:
|
||||
return True, None
|
||||
|
||||
for priority, trigger in self.__triggers[point_name]:
|
||||
try:
|
||||
cont, ret_value = await utils.asDeferred(trigger, *args, **kwargs)
|
||||
cont, ret_value = await utils.as_deferred(trigger, *args, **kwargs)
|
||||
if not cont:
|
||||
return False, ret_value
|
||||
except sync_trigger.SkipOtherTriggers:
|
||||
|
|
|
|||
|
|
@ -107,7 +107,7 @@ def iter2dict(name, iter_, dict_=None, check_conflict=True):
|
|||
return dict
|
||||
|
||||
|
||||
def getSubDict(name, dict_, sep="_"):
|
||||
def get_sub_dict(name, dict_, sep="_"):
|
||||
"""get a sub dictionary from a serialised dictionary
|
||||
|
||||
look for keys starting with name, and create a dict with it
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@ class Message(object):
|
|||
self._subject_data = msg_data[5]
|
||||
self._type = msg_data[6]
|
||||
self._extra = data_format.deserialise(msg_data[7])
|
||||
self._html = dict(data_format.getSubDict("xhtml", self._extra))
|
||||
self._html = dict(data_format.get_sub_dict("xhtml", self._extra))
|
||||
|
||||
@property
|
||||
def id(self):
|
||||
|
|
@ -203,7 +203,7 @@ class OnClick(object):
|
|||
def __init__(self, url=None):
|
||||
self.url = url
|
||||
|
||||
def formatUrl(self, *args, **kwargs):
|
||||
def format_url(self, *args, **kwargs):
|
||||
"""format URL using Python formatting
|
||||
|
||||
values will be quoted before being used
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ log = getLogger(__name__)
|
|||
|
||||
|
||||
def bridge(name, module_path="sat.bridge"):
|
||||
"""Import bridge module
|
||||
"""import bridge module
|
||||
|
||||
@param module_path(str): path of the module to import
|
||||
@param name(str): name of the bridge to import (e.g.: dbus)
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@ from sat.core.log import getLogger
|
|||
log = getLogger(__name__)
|
||||
|
||||
|
||||
def sendEmail(config, to_emails, subject="", body="", from_email=None):
|
||||
def send_email(config, to_emails, subject="", body="", from_email=None):
|
||||
"""Send an email using SàT configuration
|
||||
|
||||
@param config (SafeConfigParser): the configuration instance
|
||||
|
|
@ -42,11 +42,11 @@ def sendEmail(config, to_emails, subject="", body="", from_email=None):
|
|||
"""
|
||||
if isinstance(to_emails, str):
|
||||
to_emails = to_emails.split()
|
||||
email_host = tools_config.getConfig(config, None, "email_server") or "localhost"
|
||||
email_from = from_email or tools_config.getConfig(config, None, "email_from")
|
||||
email_host = tools_config.config_get(config, None, "email_server") or "localhost"
|
||||
email_from = from_email or tools_config.config_get(config, None, "email_from")
|
||||
|
||||
# we suppose that email domain and XMPP domain are identical
|
||||
domain = tools_config.getConfig(config, None, "xmpp_domain")
|
||||
domain = tools_config.config_get(config, None, "xmpp_domain")
|
||||
if domain is None:
|
||||
if email_from is not None:
|
||||
domain = email_from.split("@", 1)[-1]
|
||||
|
|
@ -55,14 +55,14 @@ def sendEmail(config, to_emails, subject="", body="", from_email=None):
|
|||
|
||||
if email_from is None:
|
||||
email_from = "no_reply@" + domain
|
||||
email_sender_domain = tools_config.getConfig(
|
||||
email_sender_domain = tools_config.config_get(
|
||||
config, None, "email_sender_domain", domain
|
||||
)
|
||||
email_port = int(tools_config.getConfig(config, None, "email_port", 25))
|
||||
email_username = tools_config.getConfig(config, None, "email_username")
|
||||
email_password = tools_config.getConfig(config, None, "email_password")
|
||||
email_auth = C.bool(tools_config.getConfig(config, None, "email_auth", C.BOOL_FALSE))
|
||||
email_starttls = C.bool(tools_config.getConfig(config, None, "email_starttls",
|
||||
email_port = int(tools_config.config_get(config, None, "email_port", 25))
|
||||
email_username = tools_config.config_get(config, None, "email_username")
|
||||
email_password = tools_config.config_get(config, None, "email_password")
|
||||
email_auth = C.bool(tools_config.config_get(config, None, "email_auth", C.BOOL_FALSE))
|
||||
email_starttls = C.bool(tools_config.config_get(config, None, "email_starttls",
|
||||
C.BOOL_FALSE))
|
||||
|
||||
msg = MIMEText(body, "plain", "UTF-8")
|
||||
|
|
|
|||
|
|
@ -33,12 +33,12 @@ TEXT_MAX_LEN = 60
|
|||
TEXT_WORD_MIN_LENGHT = 0
|
||||
|
||||
|
||||
def reJoin(exps):
|
||||
def re_join(exps):
|
||||
"""Join (OR) various regexes"""
|
||||
return re.compile("|".join(exps))
|
||||
|
||||
|
||||
def reSubDict(pattern, repl_dict, string):
|
||||
def re_sub_dict(pattern, repl_dict, string):
|
||||
"""Replace key, value found in dict according to pattern
|
||||
|
||||
@param pattern(basestr): pattern using keys found in repl_dict
|
||||
|
|
@ -49,29 +49,29 @@ def reSubDict(pattern, repl_dict, string):
|
|||
return pattern.sub(lambda m: repl_dict[re.escape(m.group(0))], string)
|
||||
|
||||
|
||||
path_escape_re = reJoin(list(path_escape.keys()))
|
||||
path_escape_rev_re = reJoin(list(path_escape_rev.keys()))
|
||||
path_escape_re = re_join(list(path_escape.keys()))
|
||||
path_escape_rev_re = re_join(list(path_escape_rev.keys()))
|
||||
|
||||
|
||||
def pathEscape(string):
|
||||
def path_escape(string):
|
||||
"""Escape string so it can be use in a file path
|
||||
|
||||
@param string(basestr): string to escape
|
||||
@return (str, unicode): escaped string, usable in a file path
|
||||
"""
|
||||
return reSubDict(path_escape_re, path_escape, string)
|
||||
return re_sub_dict(path_escape_re, path_escape, string)
|
||||
|
||||
|
||||
def pathUnescape(string):
|
||||
def path_unescape(string):
|
||||
"""Unescape string from value found in file path
|
||||
|
||||
@param string(basestr): string found in file path
|
||||
@return (str, unicode): unescaped string
|
||||
"""
|
||||
return reSubDict(path_escape_rev_re, path_escape_rev, string)
|
||||
return re_sub_dict(path_escape_rev_re, path_escape_rev, string)
|
||||
|
||||
|
||||
def ansiRemove(string):
|
||||
def ansi_remove(string):
|
||||
"""Remove ANSI escape codes from string
|
||||
|
||||
@param string(basestr): string to filter
|
||||
|
|
@ -80,7 +80,7 @@ def ansiRemove(string):
|
|||
return RE_ANSI_REMOVE.sub("", string)
|
||||
|
||||
|
||||
def urlFriendlyText(text):
|
||||
def url_friendly_text(text):
|
||||
"""Convert text to url-friendly one"""
|
||||
# we change special chars to ascii one,
|
||||
# trick found at https://stackoverflow.com/a/3194567
|
||||
|
|
|
|||
|
|
@ -162,7 +162,7 @@ class TemplateLoader(jinja2.BaseLoader):
|
|||
return TemplateData(site, theme, template_path)
|
||||
|
||||
@staticmethod
|
||||
def getSitesAndThemes(
|
||||
def get_sites_and_themes(
|
||||
site: str,
|
||||
theme: str,
|
||||
settings: Optional[dict] = None,
|
||||
|
|
@ -205,7 +205,7 @@ class TemplateLoader(jinja2.BaseLoader):
|
|||
raise exceptions.InternalError(
|
||||
"_get_template_f must not be used with absolute path")
|
||||
settings = self.sites_themes[site][theme]['settings']
|
||||
for site_to_check, theme_to_check in self.getSitesAndThemes(
|
||||
for site_to_check, theme_to_check in self.get_sites_and_themes(
|
||||
site, theme, settings):
|
||||
try:
|
||||
base_path = self.sites_paths[site_to_check]
|
||||
|
|
@ -328,12 +328,12 @@ class ScriptsHandler(object):
|
|||
scripts = []
|
||||
tpl = "<script src={src} {attribute}></script>"
|
||||
for library, attribute in self.scripts:
|
||||
library_path = self.renderer.getStaticPath(self.template_data, library)
|
||||
library_path = self.renderer.get_static_path(self.template_data, library)
|
||||
if library_path is None:
|
||||
log.warning(_("Can't find {libary} javascript library").format(
|
||||
library=library))
|
||||
continue
|
||||
path = self.renderer.getFrontURL(library_path)
|
||||
path = self.renderer.get_front_url(library_path)
|
||||
scripts.append(tpl.format(src=quoteattr(path), attribute=attribute))
|
||||
return safe("\n".join(scripts))
|
||||
|
||||
|
|
@ -377,11 +377,11 @@ class Renderer(object):
|
|||
}
|
||||
self.sites_themes = {
|
||||
}
|
||||
conf = config.parseMainConf()
|
||||
public_sites = config.getConfig(conf, None, "sites_path_public_dict", {})
|
||||
conf = config.parse_main_conf()
|
||||
public_sites = config.config_get(conf, None, "sites_path_public_dict", {})
|
||||
sites_data = [public_sites]
|
||||
if private:
|
||||
private_sites = config.getConfig(conf, None, "sites_path_private_dict", {})
|
||||
private_sites = config.config_get(conf, None, "sites_path_private_dict", {})
|
||||
sites_data.append(private_sites)
|
||||
for sites in sites_data:
|
||||
normalised = {}
|
||||
|
|
@ -459,7 +459,7 @@ class Renderer(object):
|
|||
self.env._template_data = None
|
||||
self._locale_str = C.DEFAULT_LOCALE
|
||||
self._locale = Locale.parse(self._locale_str)
|
||||
self.installTranslations()
|
||||
self.install_translations()
|
||||
|
||||
# we want to have access to SàT constants in templates
|
||||
self.env.globals["C"] = C
|
||||
|
|
@ -490,7 +490,7 @@ class Renderer(object):
|
|||
"default": lambda o: o.to_json() if hasattr(o, "to_json") else None
|
||||
}
|
||||
|
||||
def getFrontURL(self, template_data, path=None):
|
||||
def get_front_url(self, template_data, path=None):
|
||||
"""Give front URL (i.e. URL seen by end-user) of a path
|
||||
|
||||
@param template_data[TemplateData]: data of current template
|
||||
|
|
@ -500,7 +500,7 @@ class Renderer(object):
|
|||
return self.env.filters["front_url"]({"template_data": template_data},
|
||||
path or template_data.path)
|
||||
|
||||
def installTranslations(self):
|
||||
def install_translations(self):
|
||||
# TODO: support multi translation
|
||||
# for now, only translations in sat_templates are handled
|
||||
self.translations = {}
|
||||
|
|
@ -546,7 +546,7 @@ class Renderer(object):
|
|||
key=lambda l: l.language_name.lower()))
|
||||
|
||||
|
||||
def setLocale(self, locale_str):
|
||||
def set_locale(self, locale_str):
|
||||
"""set current locale
|
||||
|
||||
change current translation locale and self self._locale and self._locale_str
|
||||
|
|
@ -582,7 +582,7 @@ class Renderer(object):
|
|||
self._locale = locale
|
||||
self._locale_str = locale_str
|
||||
|
||||
def getThemeAndRoot(self, template):
|
||||
def get_theme_and_root(self, template):
|
||||
"""retrieve theme and root dir of a given template
|
||||
|
||||
@param template(unicode): template to parse
|
||||
|
|
@ -600,13 +600,13 @@ class Renderer(object):
|
|||
raise exceptions.NotFound
|
||||
return theme, os.path.join(site_root_dir, C.TEMPLATE_TPL_DIR, theme)
|
||||
|
||||
def getThemesData(self, site_name):
|
||||
def get_themes_data(self, site_name):
|
||||
try:
|
||||
return self.sites_themes[site_name]
|
||||
except KeyError:
|
||||
raise exceptions.NotFound(f"no theme found for {site_name}")
|
||||
|
||||
def getStaticPath(
|
||||
def get_static_path(
|
||||
self,
|
||||
template_data: TemplateData,
|
||||
filename: str,
|
||||
|
|
@ -640,7 +640,7 @@ class Renderer(object):
|
|||
else:
|
||||
return None
|
||||
|
||||
sites_and_themes = TemplateLoader.getSitesAndThemes(template_data.site,
|
||||
sites_and_themes = TemplateLoader.get_sites_and_themes(template_data.site,
|
||||
template_data.theme,
|
||||
settings)
|
||||
for site, theme in sites_and_themes:
|
||||
|
|
@ -653,7 +653,7 @@ class Renderer(object):
|
|||
|
||||
return None
|
||||
|
||||
def _appendCSSPaths(
|
||||
def _append_css_paths(
|
||||
self,
|
||||
template_data: TemplateData,
|
||||
css_files: list,
|
||||
|
|
@ -669,16 +669,16 @@ class Renderer(object):
|
|||
with "_noscript" suffix
|
||||
"""
|
||||
name = name_root + ".css"
|
||||
css_path = self.getStaticPath(template_data, name, settings)
|
||||
css_path = self.get_static_path(template_data, name, settings)
|
||||
if css_path is not None:
|
||||
css_files.append(self.getFrontURL(css_path))
|
||||
css_files.append(self.get_front_url(css_path))
|
||||
noscript_name = name_root + "_noscript.css"
|
||||
noscript_path = self.getStaticPath(
|
||||
noscript_path = self.get_static_path(
|
||||
template_data, noscript_name, settings)
|
||||
if noscript_path is not None:
|
||||
css_files_noscript.append(self.getFrontURL(noscript_path))
|
||||
css_files_noscript.append(self.get_front_url(noscript_path))
|
||||
|
||||
def getCSSFiles(self, template_data):
|
||||
def get_css_files(self, template_data):
|
||||
"""Retrieve CSS files to use according template_data
|
||||
|
||||
For each element of the path, a .css file is looked for in /static, and returned
|
||||
|
|
@ -719,17 +719,17 @@ class Renderer(object):
|
|||
else:
|
||||
settings = self.sites_themes[site][template_data.theme]['settings']
|
||||
|
||||
css_path = self.getStaticPath(template_data, 'fonts.css', settings)
|
||||
css_path = self.get_static_path(template_data, 'fonts.css', settings)
|
||||
if css_path is not None:
|
||||
css_files.append(self.getFrontURL(css_path))
|
||||
css_files.append(self.get_front_url(css_path))
|
||||
|
||||
for name_root in ('styles', 'styles_extra', 'highlight'):
|
||||
self._appendCSSPaths(
|
||||
self._append_css_paths(
|
||||
template_data, css_files, css_files_noscript, name_root, settings)
|
||||
|
||||
for idx in range(len(path_elems)):
|
||||
name_root = "_".join(path_elems[:idx+1])
|
||||
self._appendCSSPaths(
|
||||
self._append_css_paths(
|
||||
template_data, css_files, css_files_noscript, name_root, settings)
|
||||
|
||||
return css_files, css_files_noscript
|
||||
|
|
@ -1024,7 +1024,7 @@ class Renderer(object):
|
|||
template_source = self.env.get_template(template)
|
||||
|
||||
if css_files is None:
|
||||
css_files, css_files_noscript = self.getCSSFiles(template_data)
|
||||
css_files, css_files_noscript = self.get_css_files(template_data)
|
||||
else:
|
||||
css_files_noscript = []
|
||||
|
||||
|
|
@ -1045,7 +1045,7 @@ class Renderer(object):
|
|||
kwargs["css_content" + suffix] = "\n".join(css_contents)
|
||||
|
||||
scripts_handler = ScriptsHandler(self, template_data)
|
||||
self.setLocale(locale)
|
||||
self.set_locale(locale)
|
||||
|
||||
# XXX: theme used in template arguments is the requested theme, which may differ
|
||||
# from actual theme if the template doesn't exist in the requested theme.
|
||||
|
|
|
|||
|
|
@ -191,10 +191,10 @@ class Container(object):
|
|||
def __iter__(self):
|
||||
return iter(self.children)
|
||||
|
||||
def _xmluiAppend(self, widget):
|
||||
def _xmlui_append(self, widget):
|
||||
self.children.append(widget)
|
||||
|
||||
def _xmluiRemove(self, widget):
|
||||
def _xmlui_remove(self, widget):
|
||||
self.children.remove(widget)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -33,14 +33,14 @@ except ImportError:
|
|||
log = getLogger(__name__)
|
||||
|
||||
|
||||
def getOptionsFromConfig(config, section=""):
|
||||
def get_options_from_config(config, section=""):
|
||||
options = {}
|
||||
for option in ('tls_certificate', 'tls_private_key', 'tls_chain'):
|
||||
options[option] = tools_config.getConfig(config, section, option)
|
||||
options[option] = tools_config.config_get(config, section, option)
|
||||
return options
|
||||
|
||||
|
||||
def TLSOptionsCheck(options):
|
||||
def tls_options_check(options):
|
||||
"""Check options coherence if TLS is activated, and update missing values
|
||||
|
||||
Must be called only if TLS is activated
|
||||
|
|
@ -52,7 +52,7 @@ def TLSOptionsCheck(options):
|
|||
options["tls_private_key"] = options["tls_certificate"]
|
||||
|
||||
|
||||
def loadCertificates(f):
|
||||
def load_certificates(f):
|
||||
"""Read a .pem file with a list of certificates
|
||||
|
||||
@param f (file): file obj (opened .pem file)
|
||||
|
|
@ -78,7 +78,7 @@ def loadCertificates(f):
|
|||
return certificates
|
||||
|
||||
|
||||
def loadPKey(f):
|
||||
def load_p_key(f):
|
||||
"""Read a private key from a .pem file
|
||||
|
||||
@param f (file): file obj (opened .pem file)
|
||||
|
|
@ -88,7 +88,7 @@ def loadPKey(f):
|
|||
return OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, f.read())
|
||||
|
||||
|
||||
def loadCertificate(f):
|
||||
def load_certificate(f):
|
||||
"""Read a public certificate from a .pem file
|
||||
|
||||
@param f (file): file obj (opened .pem file)
|
||||
|
|
@ -98,7 +98,7 @@ def loadCertificate(f):
|
|||
return OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, f.read())
|
||||
|
||||
|
||||
def getTLSContextFactory(options):
|
||||
def get_tls_context_factory(options):
|
||||
"""Load TLS certificate and build the context factory needed for listenSSL"""
|
||||
if ssl is None:
|
||||
raise ImportError("Python module pyOpenSSL is not installed!")
|
||||
|
|
@ -106,9 +106,9 @@ def getTLSContextFactory(options):
|
|||
cert_options = {}
|
||||
|
||||
for name, option, method in [
|
||||
("privateKey", "tls_private_key", loadPKey),
|
||||
("certificate", "tls_certificate", loadCertificate),
|
||||
("extraCertChain", "tls_chain", loadCertificates),
|
||||
("privateKey", "tls_private_key", load_p_key),
|
||||
("certificate", "tls_certificate", load_certificate),
|
||||
("extraCertChain", "tls_chain", load_certificates),
|
||||
]:
|
||||
path = options[option]
|
||||
if not path:
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ import urllib.request, urllib.parse, urllib.error
|
|||
# FIXME: basic implementation, need to follow RFC 5122
|
||||
|
||||
|
||||
def parseXMPPUri(uri):
|
||||
def parse_xmpp_uri(uri):
|
||||
"""Parse an XMPP uri and return a dict with various information
|
||||
|
||||
@param uri(unicode): uri to parse
|
||||
|
|
@ -87,7 +87,7 @@ def parseXMPPUri(uri):
|
|||
return data
|
||||
|
||||
|
||||
def addPairs(uri, pairs):
|
||||
def add_pairs(uri, pairs):
|
||||
for k, v in pairs.items():
|
||||
uri.append(
|
||||
";"
|
||||
|
|
@ -97,7 +97,7 @@ def addPairs(uri, pairs):
|
|||
)
|
||||
|
||||
|
||||
def buildXMPPUri(type_: Optional[str] = None, **kwargs: str) -> str:
|
||||
def build_xmpp_uri(type_: Optional[str] = None, **kwargs: str) -> str:
|
||||
uri = ["xmpp:"]
|
||||
subtype = kwargs.pop("subtype", None)
|
||||
path = kwargs.pop("path")
|
||||
|
|
@ -114,7 +114,7 @@ def buildXMPPUri(type_: Optional[str] = None, **kwargs: str) -> str:
|
|||
kwargs["node"] = "urn:xmpp:microblog:0"
|
||||
if kwargs:
|
||||
uri.append("?")
|
||||
addPairs(uri, kwargs)
|
||||
add_pairs(uri, kwargs)
|
||||
else:
|
||||
raise NotImplementedError("{type_} URI are not handled yet".format(type_=type_))
|
||||
|
||||
|
|
|
|||
|
|
@ -111,7 +111,7 @@ class OrderedSet(collections.abc.MutableSet):
|
|||
self._dict.update({i: None for i in items})
|
||||
|
||||
|
||||
def parseSize(size):
|
||||
def parse_size(size):
|
||||
"""Parse a file size with optional multiple symbole"""
|
||||
try:
|
||||
return int(size)
|
||||
|
|
@ -143,7 +143,7 @@ def parseSize(size):
|
|||
raise ValueError(f"invalid size: {e}")
|
||||
|
||||
|
||||
def getSizeMultiplier(size, suffix="o"):
|
||||
def get_size_multiplier(size, suffix="o"):
|
||||
"""Get multiplier of a file size"""
|
||||
size = int(size)
|
||||
# cf. https://stackoverflow.com/a/1094933 (thanks)
|
||||
|
|
@ -154,6 +154,6 @@ def getSizeMultiplier(size, suffix="o"):
|
|||
return size, f"Yi{suffix}"
|
||||
|
||||
|
||||
def getHumanSize(size, suffix="o", sep=" "):
|
||||
size, symbol = getSizeMultiplier(size, suffix)
|
||||
def get_human_size(size, suffix="o", sep=" "):
|
||||
size, symbol = get_size_multiplier(size, suffix)
|
||||
return f"{size:.2f}{sep}{symbol}"
|
||||
|
|
|
|||
|
|
@ -34,7 +34,7 @@ from sat.core import exceptions
|
|||
log = getLogger(__name__)
|
||||
|
||||
|
||||
def fixConfigOption(section, option, value, silent=True):
|
||||
def fix_config_option(section, option, value, silent=True):
|
||||
"""Force a configuration option value
|
||||
|
||||
the option will be written in the first found user config file, a new user
|
||||
|
|
@ -75,7 +75,7 @@ def fixConfigOption(section, option, value, silent=True):
|
|||
config_file=target_file))
|
||||
|
||||
|
||||
def parseMainConf(log_filenames=False):
|
||||
def parse_main_conf(log_filenames=False):
|
||||
"""Look for main .ini configuration file, and parse it
|
||||
|
||||
@param log_filenames(bool): if True, log filenames of read config files
|
||||
|
|
@ -99,7 +99,7 @@ def parseMainConf(log_filenames=False):
|
|||
return config
|
||||
|
||||
|
||||
def getConfig(config, section, name, default=None):
|
||||
def config_get(config, section, name, default=None):
|
||||
"""Get a configuration option
|
||||
|
||||
@param config (ConfigParser): the configuration instance
|
||||
|
|
@ -145,7 +145,7 @@ def getConfig(config, section, name, default=None):
|
|||
return value
|
||||
|
||||
|
||||
def getConf(
|
||||
def get_conf(
|
||||
conf: ConfigParser,
|
||||
prefix: str,
|
||||
section: str,
|
||||
|
|
@ -168,4 +168,4 @@ def getConf(
|
|||
"""
|
||||
# XXX: This is a temporary method until parameters are refactored
|
||||
value = os.getenv(f"LIBERVIA_{prefix}_{name}".upper())
|
||||
return value or getConfig(conf, section, f"{prefix}_{name}", default)
|
||||
return value or config_get(conf, section, f"{prefix}_{name}", default)
|
||||
|
|
|
|||
|
|
@ -53,7 +53,7 @@ def check(host, path, max_size=None):
|
|||
report = {}
|
||||
image = Image.open(path)
|
||||
if max_size is None:
|
||||
max_size = tuple(host.memory.getConfig(None, "image_max", (1200, 720)))
|
||||
max_size = tuple(host.memory.config_get(None, "image_max", (1200, 720)))
|
||||
if image.size > max_size:
|
||||
report['too_large'] = True
|
||||
if image.size[0] > max_size[0]:
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ KEY_DEFERREDS = "deferreds"
|
|||
KEY_NEXT = "next_defer"
|
||||
|
||||
|
||||
def stanza2NotFound(failure_):
|
||||
def stanza_2_not_found(failure_):
|
||||
"""Convert item-not-found StanzaError to exceptions.NotFound"""
|
||||
failure_.trap(jabber_error.StanzaError)
|
||||
if failure_.value.condition == 'item-not-found':
|
||||
|
|
@ -95,7 +95,7 @@ class RTDeferredSessions(memory.Sessions):
|
|||
timeout=timeout, resettable_timeout=False
|
||||
)
|
||||
|
||||
def newSession(self, deferreds, profile):
|
||||
def new_session(self, deferreds, profile):
|
||||
"""Launch a new session with a list of deferreds
|
||||
|
||||
@param deferreds(list[defer.Deferred]): list of deferred to call
|
||||
|
|
@ -103,7 +103,7 @@ class RTDeferredSessions(memory.Sessions):
|
|||
@param return (tupe[str, defer.Deferred]): tuple with session id and a deferred wich fire *WITHOUT RESULT* when all results are received
|
||||
"""
|
||||
data = {KEY_NEXT: defer.Deferred()}
|
||||
session_id, session_data = super(RTDeferredSessions, self).newSession(
|
||||
session_id, session_data = super(RTDeferredSessions, self).new_session(
|
||||
data, profile=profile
|
||||
)
|
||||
if isinstance(deferreds, dict):
|
||||
|
|
@ -120,7 +120,7 @@ class RTDeferredSessions(memory.Sessions):
|
|||
d.addErrback(self._errback, d, session_id, profile)
|
||||
return session_id
|
||||
|
||||
def _purgeSession(
|
||||
def _purge_session(
|
||||
self, session_id, reason="timeout", no_warning=False, got_result=False
|
||||
):
|
||||
"""Purge the session
|
||||
|
|
@ -155,14 +155,14 @@ class RTDeferredSessions(memory.Sessions):
|
|||
"RTDeferredList cancelled: {} (profile {})".format(reason, profile)
|
||||
)
|
||||
|
||||
super(RTDeferredSessions, self)._purgeSession(session_id)
|
||||
super(RTDeferredSessions, self)._purge_session(session_id)
|
||||
|
||||
def _gotResult(self, session_id, profile):
|
||||
"""Method called after each callback or errback
|
||||
|
||||
manage the next_defer deferred
|
||||
"""
|
||||
session_data = self.profileGet(session_id, profile)
|
||||
session_data = self.profile_get(session_id, profile)
|
||||
defer_next = session_data[KEY_NEXT]
|
||||
if not defer_next.called:
|
||||
defer_next.callback(None)
|
||||
|
|
@ -182,9 +182,9 @@ class RTDeferredSessions(memory.Sessions):
|
|||
@param reason (unicode): reason of the cancellation
|
||||
@param no_log(bool): if True, don't log the cancellation
|
||||
"""
|
||||
self._purgeSession(session_id, reason=reason, no_warning=no_log)
|
||||
self._purge_session(session_id, reason=reason, no_warning=no_log)
|
||||
|
||||
def getResults(
|
||||
def get_results(
|
||||
self, session_id, on_success=None, on_error=None, profile=C.PROF_KEY_NONE
|
||||
):
|
||||
"""Get current results of a real-time deferred session
|
||||
|
|
@ -212,7 +212,7 @@ class RTDeferredSessions(memory.Sessions):
|
|||
"""
|
||||
if profile == C.PROF_KEY_NONE:
|
||||
raise exceptions.ProfileNotSetError
|
||||
session_data = self.profileGet(session_id, profile)
|
||||
session_data = self.profile_get(session_id, profile)
|
||||
|
||||
@defer.inlineCallbacks
|
||||
def next_cb(__):
|
||||
|
|
@ -261,7 +261,7 @@ class RTDeferredSessions(memory.Sessions):
|
|||
else:
|
||||
# no more data to get, the result have been gotten,
|
||||
# we can cleanly finish the session
|
||||
self._purgeSession(session_id, got_result=True)
|
||||
self._purge_session(session_id, got_result=True)
|
||||
|
||||
defer.returnValue((len(filtered_data), results))
|
||||
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ log = getLogger(__name__)
|
|||
|
||||
|
||||
class IStreamProducer(interface.Interface):
|
||||
def startStream(consumer):
|
||||
def start_stream(consumer):
|
||||
"""start producing the stream
|
||||
|
||||
@return (D): deferred fired when stream is finished
|
||||
|
|
@ -68,18 +68,18 @@ class SatFile:
|
|||
@param path(Path, str): path to the file to get or write to
|
||||
@param mode(str): same as for built-in "open" function
|
||||
@param uid(unicode, None): unique id identifing this progressing element
|
||||
This uid will be used with self.host.progressGet
|
||||
This uid will be used with self.host.progress_get
|
||||
will be automaticaly generated if None
|
||||
@param size(None, int): size of the file (when known in advance)
|
||||
@param data_cb(None, callable): method to call on each data read/write
|
||||
can be used to do processing like calculating hash.
|
||||
if data_cb return a non None value, it will be used instead of the
|
||||
data read/to write
|
||||
@param auto_end_signals(bool): if True, progressFinished and progressError signals
|
||||
@param auto_end_signals(bool): if True, progress_finished and progress_error signals
|
||||
are automatically sent.
|
||||
if False, you'll have to call self.progressFinished and self.progressError
|
||||
if False, you'll have to call self.progress_finished and self.progress_error
|
||||
yourself.
|
||||
progressStarted signal is always sent automatically
|
||||
progress_started signal is always sent automatically
|
||||
@param check_size_with_read(bool): if True, size will be checked using number of
|
||||
bytes read or written. This is useful when data_cb modifiy len of file.
|
||||
@param pre_close_cb:
|
||||
|
|
@ -92,11 +92,11 @@ class SatFile:
|
|||
self.data_cb = data_cb
|
||||
self.auto_end_signals = auto_end_signals
|
||||
self.pre_close_cb = pre_close_cb
|
||||
metadata = self.getProgressMetadata()
|
||||
self.host.registerProgressCb(
|
||||
self.uid, self.getProgress, metadata, profile=client.profile
|
||||
metadata = self.get_progress_metadata()
|
||||
self.host.register_progress_cb(
|
||||
self.uid, self.get_progress, metadata, profile=client.profile
|
||||
)
|
||||
self.host.bridge.progressStarted(self.uid, metadata, client.profile)
|
||||
self.host.bridge.progress_started(self.uid, metadata, client.profile)
|
||||
|
||||
self._transfer_count = 0 if check_size_with_read else None
|
||||
|
||||
|
|
@ -111,7 +111,7 @@ class SatFile:
|
|||
else:
|
||||
self._transfer_count = None
|
||||
|
||||
def checkSize(self):
|
||||
def check_size(self):
|
||||
"""Check that current size correspond to given size
|
||||
|
||||
must be used when the transfer is supposed to be finished
|
||||
|
|
@ -142,7 +142,7 @@ class SatFile:
|
|||
self.pre_close_cb()
|
||||
if error is None:
|
||||
try:
|
||||
size_ok = self.checkSize()
|
||||
size_ok = self.check_size()
|
||||
except exceptions.NotFound:
|
||||
size_ok = True
|
||||
if not size_ok:
|
||||
|
|
@ -154,12 +154,12 @@ class SatFile:
|
|||
|
||||
if self.auto_end_signals:
|
||||
if error is None:
|
||||
self.progressFinished(progress_metadata)
|
||||
self.progress_finished(progress_metadata)
|
||||
else:
|
||||
assert progress_metadata is None
|
||||
self.progressError(error)
|
||||
self.progress_error(error)
|
||||
|
||||
self.host.removeProgressCb(self.uid, self.profile)
|
||||
self.host.remove_progress_cb(self.uid, self.profile)
|
||||
if error is not None:
|
||||
log.error(f"file {self._file} closed with an error: {error}")
|
||||
|
||||
|
|
@ -167,13 +167,13 @@ class SatFile:
|
|||
def closed(self):
|
||||
return self._file.closed
|
||||
|
||||
def progressFinished(self, metadata=None):
|
||||
def progress_finished(self, metadata=None):
|
||||
if metadata is None:
|
||||
metadata = {}
|
||||
self.host.bridge.progressFinished(self.uid, metadata, self.profile)
|
||||
self.host.bridge.progress_finished(self.uid, metadata, self.profile)
|
||||
|
||||
def progressError(self, error):
|
||||
self.host.bridge.progressError(self.uid, error, self.profile)
|
||||
def progress_error(self, error):
|
||||
self.host.bridge.progress_error(self.uid, error, self.profile)
|
||||
|
||||
def flush(self):
|
||||
self._file.flush()
|
||||
|
|
@ -207,8 +207,8 @@ class SatFile:
|
|||
def mode(self):
|
||||
return self._file.mode
|
||||
|
||||
def getProgressMetadata(self):
|
||||
"""Return progression metadata as given to progressStarted
|
||||
def get_progress_metadata(self):
|
||||
"""Return progression metadata as given to progress_started
|
||||
|
||||
@return (dict): metadata (check bridge for documentation)
|
||||
"""
|
||||
|
|
@ -230,7 +230,7 @@ class SatFile:
|
|||
|
||||
return metadata
|
||||
|
||||
def getProgress(self, progress_id, profile):
|
||||
def get_progress(self, progress_id, profile):
|
||||
ret = {"position": self._file.tell()}
|
||||
if self.size:
|
||||
ret["size"] = self.size
|
||||
|
|
@ -252,7 +252,7 @@ class FileStreamObject(basic.FileSender):
|
|||
def registerProducer(self, producer, streaming):
|
||||
pass
|
||||
|
||||
def startStream(self, consumer):
|
||||
def start_stream(self, consumer):
|
||||
return self.beginFileTransfer(self.file_obj, consumer)
|
||||
|
||||
def write(self, data):
|
||||
|
|
|
|||
|
|
@ -111,7 +111,7 @@ class TriggerManager(object):
|
|||
break
|
||||
return True
|
||||
|
||||
def returnPoint(self, point_name, *args, **kwargs):
|
||||
def return_point(self, point_name, *args, **kwargs):
|
||||
"""Like point but trigger must return (continue, return_value)
|
||||
|
||||
All triggers for that point must return a tuple with 2 values:
|
||||
|
|
|
|||
|
|
@ -67,7 +67,7 @@ def logError(failure_):
|
|||
|
||||
def partial(func, *fixed_args, **fixed_kwargs):
|
||||
# FIXME: temporary hack to workaround the fact that inspect.getargspec is not working with functools.partial
|
||||
# making partial unusable with current D-bus module (in addMethod).
|
||||
# making partial unusable with current D-bus module (in add_method).
|
||||
# Should not be needed anywore once moved to Python 3
|
||||
|
||||
ori_args = inspect.getargspec(func).args
|
||||
|
|
@ -93,7 +93,7 @@ def partial(func, *fixed_args, **fixed_kwargs):
|
|||
return method
|
||||
|
||||
|
||||
def asDeferred(func, *args, **kwargs):
|
||||
def as_deferred(func, *args, **kwargs):
|
||||
"""Call a method and return a Deferred
|
||||
|
||||
the method can be a simple callable, a Deferred or a coroutine.
|
||||
|
|
@ -184,7 +184,7 @@ def parse_xmpp_date(
|
|||
return dt.timestamp()
|
||||
|
||||
|
||||
def generatePassword(vocabulary=None, size=20):
|
||||
def generate_password(vocabulary=None, size=20):
|
||||
"""Generate a password with random characters.
|
||||
|
||||
@param vocabulary(iterable): characters to use to create password
|
||||
|
|
@ -199,7 +199,7 @@ def generatePassword(vocabulary=None, size=20):
|
|||
return "".join([random.choice(vocabulary) for i in range(15)])
|
||||
|
||||
|
||||
def getRepositoryData(module, as_string=True, is_path=False):
|
||||
def get_repository_data(module, as_string=True, is_path=False):
|
||||
"""Retrieve info on current mecurial repository
|
||||
|
||||
Data is gotten by using the following methods, in order:
|
||||
|
|
|
|||
|
|
@ -74,7 +74,7 @@ class NoCheckContextFactory:
|
|||
treq_client_no_ssl = HTTPClient(http_client.Agent(reactor, NoCheckContextFactory()))
|
||||
|
||||
|
||||
async def downloadFile(
|
||||
async def download_file(
|
||||
url: str,
|
||||
dest: Union[str, Path, BufferedIOBase],
|
||||
max_size: Optional[int] = None
|
||||
|
|
|
|||
|
|
@ -47,7 +47,7 @@ XML_ENTITIES = ("quot", "amp", "apos", "lt", "gt")
|
|||
|
||||
# method to clean XHTML, receive raw unsecure XML or HTML, must return cleaned raw XHTML
|
||||
# this method must be set during runtime
|
||||
cleanXHTML = None
|
||||
clean_xhtml = None
|
||||
|
||||
# TODO: move XMLUI stuff in a separate module
|
||||
# TODO: rewrite this with lxml or ElementTree or domish.Element: it's complicated and difficult to maintain with current minidom implementation
|
||||
|
|
@ -55,7 +55,7 @@ cleanXHTML = None
|
|||
# Helper functions
|
||||
|
||||
|
||||
def _dataFormField2XMLUIData(field, read_only=False):
|
||||
def _data_form_field_2_xmlui_data(field, read_only=False):
|
||||
"""Get data needed to create an XMLUI's Widget from Wokkel's data_form's Field.
|
||||
|
||||
The attribute field can be modified (if it's fixed and it has no value).
|
||||
|
|
@ -144,14 +144,14 @@ def _dataFormField2XMLUIData(field, read_only=False):
|
|||
|
||||
return widget_type, widget_args, widget_kwargs
|
||||
|
||||
def dataForm2Widgets(form_ui, form, read_only=False, prepend=None, filters=None):
|
||||
def data_form_2_widgets(form_ui, form, read_only=False, prepend=None, filters=None):
|
||||
"""Complete an existing XMLUI with widget converted from XEP-0004 data forms.
|
||||
|
||||
@param form_ui (XMLUI): XMLUI instance
|
||||
@param form (data_form.Form): Wokkel's implementation of data form
|
||||
@param read_only (bool): if True and it makes sense, create a read only input widget
|
||||
@param prepend(iterable, None): widgets to prepend to main LabelContainer
|
||||
if not None, must be an iterable of *args for addWidget. Those widgets will
|
||||
if not None, must be an iterable of *args for add_widget. Those widgets will
|
||||
be added first to the container.
|
||||
@param filters(dict, None): if not None, a dictionary of callable:
|
||||
key is the name of the widget to filter
|
||||
|
|
@ -165,14 +165,14 @@ def dataForm2Widgets(form_ui, form, read_only=False, prepend=None, filters=None)
|
|||
if form.instructions:
|
||||
form_ui.addText("\n".join(form.instructions), "instructions")
|
||||
|
||||
form_ui.changeContainer("label")
|
||||
form_ui.change_container("label")
|
||||
|
||||
if prepend is not None:
|
||||
for widget_args in prepend:
|
||||
form_ui.addWidget(*widget_args)
|
||||
form_ui.add_widget(*widget_args)
|
||||
|
||||
for field in form.fieldList:
|
||||
widget_type, widget_args, widget_kwargs = _dataFormField2XMLUIData(
|
||||
widget_type, widget_args, widget_kwargs = _data_form_field_2_xmlui_data(
|
||||
field, read_only
|
||||
)
|
||||
try:
|
||||
|
|
@ -190,12 +190,12 @@ def dataForm2Widgets(form_ui, form, read_only=False, prepend=None, filters=None)
|
|||
else:
|
||||
form_ui.addEmpty()
|
||||
|
||||
form_ui.addWidget(widget_type, *widget_args, **widget_kwargs)
|
||||
form_ui.add_widget(widget_type, *widget_args, **widget_kwargs)
|
||||
|
||||
return form_ui
|
||||
|
||||
|
||||
def dataForm2XMLUI(form, submit_id, session_id=None, read_only=False):
|
||||
def data_form_2_xmlui(form, submit_id, session_id=None, read_only=False):
|
||||
"""Take a data form (Wokkel's XEP-0004 implementation) and convert it to a SàT XMLUI.
|
||||
|
||||
@param form (data_form.Form): a Form instance
|
||||
|
|
@ -205,13 +205,13 @@ def dataForm2XMLUI(form, submit_id, session_id=None, read_only=False):
|
|||
@return: XMLUI instance
|
||||
"""
|
||||
form_ui = XMLUI("form", "vertical", submit_id=submit_id, session_id=session_id)
|
||||
return dataForm2Widgets(form_ui, form, read_only=read_only)
|
||||
return data_form_2_widgets(form_ui, form, read_only=read_only)
|
||||
|
||||
|
||||
def dataForm2dataDict(form: data_form.Form) -> dict:
|
||||
def data_form_2_data_dict(form: data_form.Form) -> dict:
|
||||
"""Convert data form to a simple dict, easily serialisable
|
||||
|
||||
see dataDict2dataForm for a description of the format
|
||||
see data_dict_2_data_form for a description of the format
|
||||
"""
|
||||
fields = []
|
||||
data_dict = {
|
||||
|
|
@ -253,7 +253,7 @@ def dataForm2dataDict(form: data_form.Form) -> dict:
|
|||
return data_dict
|
||||
|
||||
|
||||
def dataDict2dataForm(data_dict):
|
||||
def data_dict_2_data_form(data_dict):
|
||||
"""Convert serialisable dict of data to a data form
|
||||
|
||||
The format of the dict is as follow:
|
||||
|
|
@ -299,7 +299,7 @@ def dataDict2dataForm(data_dict):
|
|||
)
|
||||
|
||||
|
||||
def dataFormEltResult2XMLUIData(form_xml):
|
||||
def data_form_elt_result_2_xmlui_data(form_xml):
|
||||
"""Parse a data form result (not parsed by Wokkel's XEP-0004 implementation).
|
||||
|
||||
The raw data form is used because Wokkel doesn't manage result items parsing yet.
|
||||
|
|
@ -337,12 +337,12 @@ def dataFormEltResult2XMLUIData(form_xml):
|
|||
continue
|
||||
field = data_form.Field.fromElement(elt)
|
||||
|
||||
xmlui_data.append(_dataFormField2XMLUIData(field))
|
||||
xmlui_data.append(_data_form_field_2_xmlui_data(field))
|
||||
|
||||
return headers, xmlui_data
|
||||
|
||||
|
||||
def XMLUIData2AdvancedList(xmlui, headers, xmlui_data):
|
||||
def xmlui_data_2_advanced_list(xmlui, headers, xmlui_data):
|
||||
"""Take a raw data form result (not parsed by Wokkel's XEP-0004 implementation) and convert it to an advanced list.
|
||||
|
||||
The raw data form is used because Wokkel doesn't manage result items parsing yet.
|
||||
|
|
@ -354,15 +354,15 @@ def XMLUIData2AdvancedList(xmlui, headers, xmlui_data):
|
|||
adv_list = AdvancedListContainer(
|
||||
xmlui, headers=headers, columns=len(headers), parent=xmlui.current_container
|
||||
)
|
||||
xmlui.changeContainer(adv_list)
|
||||
xmlui.change_container(adv_list)
|
||||
|
||||
for widget_type, widget_args, widget_kwargs in xmlui_data:
|
||||
xmlui.addWidget(widget_type, *widget_args, **widget_kwargs)
|
||||
xmlui.add_widget(widget_type, *widget_args, **widget_kwargs)
|
||||
|
||||
return xmlui
|
||||
|
||||
|
||||
def dataFormResult2AdvancedList(xmlui, form_xml):
|
||||
def data_form_result_2_advanced_list(xmlui, form_xml):
|
||||
"""Take a raw data form result (not parsed by Wokkel's XEP-0004 implementation) and convert it to an advanced list.
|
||||
|
||||
The raw data form is used because Wokkel doesn't manage result items parsing yet.
|
||||
|
|
@ -370,11 +370,11 @@ def dataFormResult2AdvancedList(xmlui, form_xml):
|
|||
@param form_xml (domish.Element): element of the data form
|
||||
@return: the completed XMLUI instance
|
||||
"""
|
||||
headers, xmlui_data = dataFormEltResult2XMLUIData(form_xml)
|
||||
XMLUIData2AdvancedList(xmlui, headers, xmlui_data)
|
||||
headers, xmlui_data = data_form_elt_result_2_xmlui_data(form_xml)
|
||||
xmlui_data_2_advanced_list(xmlui, headers, xmlui_data)
|
||||
|
||||
|
||||
def dataFormEltResult2XMLUI(form_elt, session_id=None):
|
||||
def data_form_elt_result_2_xmlui(form_elt, session_id=None):
|
||||
"""Take a raw data form (not parsed by XEP-0004) and convert it to a SàT XMLUI.
|
||||
|
||||
The raw data form is used because Wokkel doesn't manage result items parsing yet.
|
||||
|
|
@ -384,14 +384,14 @@ def dataFormEltResult2XMLUI(form_elt, session_id=None):
|
|||
"""
|
||||
xml_ui = XMLUI("window", "vertical", session_id=session_id)
|
||||
try:
|
||||
dataFormResult2AdvancedList(xml_ui, form_elt)
|
||||
data_form_result_2_advanced_list(xml_ui, form_elt)
|
||||
except exceptions.DataError:
|
||||
parsed_form = data_form.Form.fromElement(form_elt)
|
||||
dataForm2Widgets(xml_ui, parsed_form, read_only=True)
|
||||
data_form_2_widgets(xml_ui, parsed_form, read_only=True)
|
||||
return xml_ui
|
||||
|
||||
|
||||
def dataFormResult2XMLUI(result_form, base_form, session_id=None, prepend=None,
|
||||
def data_form_result_2_xmlui(result_form, base_form, session_id=None, prepend=None,
|
||||
filters=None, read_only=True):
|
||||
"""Convert data form result to SàT XMLUI.
|
||||
|
||||
|
|
@ -399,12 +399,12 @@ def dataFormResult2XMLUI(result_form, base_form, session_id=None, prepend=None,
|
|||
@param base_form (data_form.Form): initial form (i.e. of form type "form")
|
||||
this one is necessary to reconstruct options when needed (e.g. list elements)
|
||||
@param session_id (unicode): session id to return with the data
|
||||
@param prepend: same as for [dataForm2Widgets]
|
||||
@param filters: same as for [dataForm2Widgets]
|
||||
@param read_only: same as for [dataForm2Widgets]
|
||||
@param prepend: same as for [data_form_2_widgets]
|
||||
@param filters: same as for [data_form_2_widgets]
|
||||
@param read_only: same as for [data_form_2_widgets]
|
||||
@return: XMLUI instance
|
||||
"""
|
||||
# we deepcopy the form because _dataFormField2XMLUIData can modify the value
|
||||
# we deepcopy the form because _data_form_field_2_xmlui_data can modify the value
|
||||
# FIXME: check if it's really important, the only modified value seems to be
|
||||
# the replacement of None by "" on fixed fields
|
||||
# form = deepcopy(result_form)
|
||||
|
|
@ -416,11 +416,11 @@ def dataFormResult2XMLUI(result_form, base_form, session_id=None, prepend=None,
|
|||
continue
|
||||
field.options = base_field.options[:]
|
||||
xml_ui = XMLUI("window", "vertical", session_id=session_id)
|
||||
dataForm2Widgets(xml_ui, form, read_only=read_only, prepend=prepend, filters=filters)
|
||||
data_form_2_widgets(xml_ui, form, read_only=read_only, prepend=prepend, filters=filters)
|
||||
return xml_ui
|
||||
|
||||
|
||||
def _cleanValue(value):
|
||||
def _clean_value(value):
|
||||
"""Workaround method to avoid DBus types with D-Bus bridge.
|
||||
|
||||
@param value: value to clean
|
||||
|
|
@ -433,7 +433,7 @@ def _cleanValue(value):
|
|||
return value
|
||||
|
||||
|
||||
def XMLUIResult2DataFormResult(xmlui_data):
|
||||
def xmlui_result_2_data_form_result(xmlui_data):
|
||||
""" Extract form data from a XMLUI return.
|
||||
|
||||
@param xmlui_data (dict): data returned by frontends for XMLUI form
|
||||
|
|
@ -451,11 +451,11 @@ def XMLUIResult2DataFormResult(xmlui_data):
|
|||
# FIXME: workaround to handle multiple values. Proper serialisation must
|
||||
# be done in XMLUI
|
||||
value = value.split("\t")
|
||||
ret[key[len(SAT_FORM_PREFIX) :]] = _cleanValue(value)
|
||||
ret[key[len(SAT_FORM_PREFIX) :]] = _clean_value(value)
|
||||
return ret
|
||||
|
||||
|
||||
def formEscape(name):
|
||||
def form_escape(name):
|
||||
"""Return escaped name for forms.
|
||||
|
||||
@param name (unicode): form name
|
||||
|
|
@ -464,23 +464,23 @@ def formEscape(name):
|
|||
return "%s%s" % (SAT_FORM_PREFIX, name)
|
||||
|
||||
|
||||
def isXMLUICancelled(raw_xmlui):
|
||||
def is_xmlui_cancelled(raw_xmlui):
|
||||
"""Tell if an XMLUI has been cancelled by checking raw XML"""
|
||||
return C.bool(raw_xmlui.get('cancelled', C.BOOL_FALSE))
|
||||
|
||||
|
||||
def XMLUIResultToElt(xmlui_data):
|
||||
def xmlui_result_to_elt(xmlui_data):
|
||||
"""Construct result domish.Element from XMLUI result.
|
||||
|
||||
@param xmlui_data (dict): data returned by frontends for XMLUI form
|
||||
@return: domish.Element
|
||||
"""
|
||||
form = data_form.Form("submit")
|
||||
form.makeFields(XMLUIResult2DataFormResult(xmlui_data))
|
||||
form.makeFields(xmlui_result_2_data_form_result(xmlui_data))
|
||||
return form.toElement()
|
||||
|
||||
|
||||
def tupleList2dataForm(values):
|
||||
def tuple_list_2_data_form(values):
|
||||
"""Convert a list of tuples (name, value) to a wokkel submit data form.
|
||||
|
||||
@param values (list): list of tuples
|
||||
|
|
@ -494,7 +494,7 @@ def tupleList2dataForm(values):
|
|||
return form
|
||||
|
||||
|
||||
def paramsXML2XMLUI(xml):
|
||||
def params_xml_2_xmlui(xml):
|
||||
"""Convert the XML for parameter to a SàT XML User Interface.
|
||||
|
||||
@param xml (unicode)
|
||||
|
|
@ -516,7 +516,7 @@ def paramsXML2XMLUI(xml):
|
|||
raise exceptions.DataError(
|
||||
_("INTERNAL ERROR: params categories must have a name")
|
||||
)
|
||||
tabs_cont.addTab(category_name, label=label, container=LabelContainer)
|
||||
tabs_cont.add_tab(category_name, label=label, container=LabelContainer)
|
||||
for param in category.getElementsByTagName("param"):
|
||||
widget_kwargs = {}
|
||||
|
||||
|
|
@ -530,12 +530,12 @@ def paramsXML2XMLUI(xml):
|
|||
callback_id = param.getAttribute("callback_id") or None
|
||||
|
||||
if type_ == "list":
|
||||
options, selected = _paramsGetListOptions(param)
|
||||
options, selected = _params_get_list_options(param)
|
||||
widget_kwargs["options"] = options
|
||||
widget_kwargs["selected"] = selected
|
||||
widget_kwargs["styles"] = ["extensible"]
|
||||
elif type_ == "jids_list":
|
||||
widget_kwargs["jids"] = _paramsGetListJids(param)
|
||||
widget_kwargs["jids"] = _params_get_list_jids(param)
|
||||
|
||||
if type_ in ("button", "text"):
|
||||
param_ui.addEmpty()
|
||||
|
|
@ -562,12 +562,12 @@ def paramsXML2XMLUI(xml):
|
|||
param_name,
|
||||
)
|
||||
|
||||
param_ui.addWidget(type_, **widget_kwargs)
|
||||
param_ui.add_widget(type_, **widget_kwargs)
|
||||
|
||||
return param_ui.toXml()
|
||||
|
||||
|
||||
def _paramsGetListOptions(param):
|
||||
def _params_get_list_options(param):
|
||||
"""Retrieve the options for list element.
|
||||
|
||||
The <option/> tags must be direct children of <param/>.
|
||||
|
|
@ -599,7 +599,7 @@ def _paramsGetListOptions(param):
|
|||
return (options, selected)
|
||||
|
||||
|
||||
def _paramsGetListJids(param):
|
||||
def _params_get_list_jids(param):
|
||||
"""Retrive jids from a jids_list element.
|
||||
|
||||
the <jid/> tags must be direct children of <param/>
|
||||
|
|
@ -679,9 +679,9 @@ class TabElement(Element):
|
|||
self.elem.setAttribute("name", name)
|
||||
self.elem.setAttribute("label", label)
|
||||
if selected:
|
||||
self.setSelected(selected)
|
||||
self.set_selected(selected)
|
||||
|
||||
def setSelected(self, selected=False):
|
||||
def set_selected(self, selected=False):
|
||||
"""Set the tab selected.
|
||||
|
||||
@param selected (bool): set to True to select this tab
|
||||
|
|
@ -824,7 +824,7 @@ class Container(Element):
|
|||
super(Container, self).__init__(xmlui, parent)
|
||||
self.elem.setAttribute("type", self.type)
|
||||
|
||||
def getParentContainer(self):
|
||||
def get_parent_container(self):
|
||||
""" Return first parent container
|
||||
|
||||
@return: parent container or None
|
||||
|
|
@ -856,7 +856,7 @@ class LabelContainer(Container):
|
|||
class TabsContainer(Container):
|
||||
type = "tabs"
|
||||
|
||||
def addTab(self, name, label=None, selected=None, container=VerticalContainer):
|
||||
def add_tab(self, name, label=None, selected=None, container=VerticalContainer):
|
||||
"""Add a tab.
|
||||
|
||||
@param name (unicode): tab name
|
||||
|
|
@ -869,15 +869,15 @@ class TabsContainer(Container):
|
|||
label = name
|
||||
tab_elt = TabElement(self, name, label, selected)
|
||||
new_container = container(self.xmlui, tab_elt)
|
||||
return self.xmlui.changeContainer(new_container)
|
||||
return self.xmlui.change_container(new_container)
|
||||
|
||||
def end(self):
|
||||
""" Called when we have finished tabs
|
||||
|
||||
change current container to first container parent
|
||||
"""
|
||||
parent_container = self.getParentContainer()
|
||||
self.xmlui.changeContainer(parent_container)
|
||||
parent_container = self.get_parent_container()
|
||||
self.xmlui.change_container(parent_container)
|
||||
|
||||
|
||||
class AdvancedListContainer(Container):
|
||||
|
|
@ -928,9 +928,9 @@ class AdvancedListContainer(Container):
|
|||
raise exceptions.DataError(
|
||||
_("Headers lenght doesn't correspond to columns")
|
||||
)
|
||||
self.addHeaders(headers)
|
||||
self.add_headers(headers)
|
||||
if items:
|
||||
self.addItems(items)
|
||||
self.add_items(items)
|
||||
self.elem.setAttribute("columns", str(self._columns))
|
||||
if callback_id is not None:
|
||||
self.elem.setAttribute("callback", callback_id)
|
||||
|
|
@ -940,18 +940,18 @@ class AdvancedListContainer(Container):
|
|||
self.elem.setAttribute("auto_index", "true")
|
||||
self.next_row_idx = None
|
||||
|
||||
def addHeaders(self, headers):
|
||||
def add_headers(self, headers):
|
||||
for header in headers:
|
||||
self.addHeader(header)
|
||||
|
||||
def addHeader(self, header):
|
||||
pass # TODO
|
||||
|
||||
def addItems(self, items):
|
||||
def add_items(self, items):
|
||||
for item in items:
|
||||
self.append(item)
|
||||
|
||||
def setRowIndex(self, idx):
|
||||
def set_row_index(self, idx):
|
||||
""" Set index for next row
|
||||
|
||||
index are returned when a row is selected, in data's "index" key
|
||||
|
|
@ -974,8 +974,8 @@ class AdvancedListContainer(Container):
|
|||
"""
|
||||
if self._item_idx % self._columns != 0:
|
||||
raise exceptions.DataError(_("Incorrect number of items in list"))
|
||||
parent_container = self.getParentContainer()
|
||||
self.xmlui.changeContainer(parent_container)
|
||||
parent_container = self.get_parent_container()
|
||||
self.xmlui.change_container(parent_container)
|
||||
|
||||
|
||||
## Widgets ##
|
||||
|
|
@ -1004,7 +1004,7 @@ class Widget(Element):
|
|||
xmlui.named_widgets[name] = self
|
||||
self.elem.setAttribute("type", self.type)
|
||||
|
||||
def setInternalCallback(self, callback, fields, data_elts=None):
|
||||
def set_internal_callback(self, callback, fields, data_elts=None):
|
||||
"""Set an internal UI callback when the widget value is changed.
|
||||
|
||||
The internal callbacks are NO callback ids, they are strings from
|
||||
|
|
@ -1169,10 +1169,10 @@ class XHTMLBoxWidget(StringWidget):
|
|||
word, set to False only if you made the XHTML yourself)
|
||||
"""
|
||||
if clean:
|
||||
if cleanXHTML is None:
|
||||
if clean_xhtml is None:
|
||||
raise exceptions.NotFound(
|
||||
"No cleaning method set, can't clean the XHTML")
|
||||
value = cleanXHTML(value)
|
||||
value = clean_xhtml(value)
|
||||
|
||||
super(XHTMLBoxWidget, self).__init__(
|
||||
xmlui, value=value, name=name, parent=parent, read_only=read_only)
|
||||
|
|
@ -1279,10 +1279,10 @@ class ListWidget(InputWidget):
|
|||
# because we would not have the labels
|
||||
log.warning(_('empty "options" list'))
|
||||
super(ListWidget, self).__init__(xmlui, name, parent)
|
||||
self.addOptions(options, selected)
|
||||
self.setStyles(styles)
|
||||
self.add_options(options, selected)
|
||||
self.set_styles(styles)
|
||||
|
||||
def addOptions(self, options, selected=None):
|
||||
def add_options(self, options, selected=None):
|
||||
"""Add options to a multi-values element (e.g. list) """
|
||||
if selected:
|
||||
if isinstance(selected, str):
|
||||
|
|
@ -1294,7 +1294,7 @@ class ListWidget(InputWidget):
|
|||
value = option if isinstance(option, str) else option[0]
|
||||
OptionElement(self, option, value in selected)
|
||||
|
||||
def setStyles(self, styles):
|
||||
def set_styles(self, styles):
|
||||
if not styles.issubset(self.STYLES):
|
||||
raise exceptions.DataError(_("invalid styles"))
|
||||
for style in styles:
|
||||
|
|
@ -1302,7 +1302,7 @@ class ListWidget(InputWidget):
|
|||
# TODO: check flags incompatibily (noselect and multi) like in __init__
|
||||
|
||||
def setStyle(self, style):
|
||||
self.setStyles([style])
|
||||
self.set_styles([style])
|
||||
|
||||
@property
|
||||
def value(self):
|
||||
|
|
@ -1336,9 +1336,9 @@ class JidsListWidget(InputWidget):
|
|||
if not jids:
|
||||
log.debug("empty jids list")
|
||||
else:
|
||||
self.addJids(jids)
|
||||
self.add_jids(jids)
|
||||
|
||||
def addJids(self, jids):
|
||||
def add_jids(self, jids):
|
||||
for jid_ in jids:
|
||||
JidElement(self, jid_)
|
||||
|
||||
|
|
@ -1499,20 +1499,20 @@ class XMLUI(object):
|
|||
if panel_type == C.XMLUI_DIALOG:
|
||||
if dialog_opt is None:
|
||||
dialog_opt = {}
|
||||
self._createDialog(dialog_opt)
|
||||
self._create_dialog(dialog_opt)
|
||||
return
|
||||
self.main_container = self._createContainer(container, TopElement(self))
|
||||
self.main_container = self._create_container(container, TopElement(self))
|
||||
self.current_container = self.main_container
|
||||
self.named_widgets = {}
|
||||
|
||||
@staticmethod
|
||||
def creatorWrapper(widget_cls, is_input):
|
||||
def creator_wrapper(widget_cls, is_input):
|
||||
# TODO: once moved to Python 3, use functools.partialmethod and
|
||||
# remove the creatorWrapper
|
||||
def createWidget(self, *args, **kwargs):
|
||||
# remove the creator_wrapper
|
||||
def create_widget(self, *args, **kwargs):
|
||||
if self.type == C.XMLUI_DIALOG:
|
||||
raise exceptions.InternalError(_(
|
||||
"createWidget can't be used with dialogs"))
|
||||
"create_widget can't be used with dialogs"))
|
||||
if "parent" not in kwargs:
|
||||
kwargs["parent"] = self.current_container
|
||||
if "name" not in kwargs and is_input:
|
||||
|
|
@ -1521,7 +1521,7 @@ class XMLUI(object):
|
|||
args = list(args)
|
||||
kwargs["name"] = args.pop(0)
|
||||
return widget_cls(self, *args, **kwargs)
|
||||
return createWidget
|
||||
return create_widget
|
||||
|
||||
@classmethod
|
||||
def _introspect(cls):
|
||||
|
|
@ -1547,10 +1547,10 @@ class XMLUI(object):
|
|||
# .format(creator_name=creator_name, is_input=is_input))
|
||||
|
||||
assert not hasattr(cls, creator_name)
|
||||
# XXX: we need to use creatorWrapper because we are in a loop
|
||||
# XXX: we need to use creator_wrapper because we are in a loop
|
||||
# and Python 2 doesn't support default values in kwargs
|
||||
# when using *args, **kwargs
|
||||
setattr(cls, creator_name, cls.creatorWrapper(obj, is_input))
|
||||
setattr(cls, creator_name, cls.creator_wrapper(obj, is_input))
|
||||
|
||||
elif issubclass(obj, Container):
|
||||
if obj.__name__ == "Container":
|
||||
|
|
@ -1602,7 +1602,7 @@ class XMLUI(object):
|
|||
else:
|
||||
raise exceptions.DataError("session_id can't be empty")
|
||||
|
||||
def _createDialog(self, dialog_opt):
|
||||
def _create_dialog(self, dialog_opt):
|
||||
dialog_type = dialog_opt.setdefault(C.XMLUI_DATA_TYPE, C.XMLUI_DIALOG_MESSAGE)
|
||||
if (
|
||||
dialog_type in [C.XMLUI_DIALOG_CONFIRM, C.XMLUI_DIALOG_FILE]
|
||||
|
|
@ -1630,7 +1630,7 @@ class XMLUI(object):
|
|||
except KeyError:
|
||||
pass
|
||||
|
||||
def _createContainer(self, container, parent=None, **kwargs):
|
||||
def _create_container(self, container, parent=None, **kwargs):
|
||||
"""Create a container element
|
||||
|
||||
@param type: container type (cf init doc)
|
||||
|
|
@ -1642,15 +1642,15 @@ class XMLUI(object):
|
|||
new_container = cls(self, parent=parent, **kwargs)
|
||||
return new_container
|
||||
|
||||
def changeContainer(self, container, **kwargs):
|
||||
def change_container(self, container, **kwargs):
|
||||
"""Change the current container
|
||||
|
||||
@param container: either container type (container it then created),
|
||||
or an Container instance"""
|
||||
if isinstance(container, str):
|
||||
self.current_container = self._createContainer(
|
||||
self.current_container = self._create_container(
|
||||
container,
|
||||
self.current_container.getParentContainer() or self.main_container,
|
||||
self.current_container.get_parent_container() or self.main_container,
|
||||
**kwargs
|
||||
)
|
||||
else:
|
||||
|
|
@ -1660,7 +1660,7 @@ class XMLUI(object):
|
|||
assert isinstance(self.current_container, Container)
|
||||
return self.current_container
|
||||
|
||||
def addWidget(self, type_, *args, **kwargs):
|
||||
def add_widget(self, type_, *args, **kwargs):
|
||||
"""Convenience method to add an element"""
|
||||
if "parent" not in kwargs:
|
||||
kwargs["parent"] = self.current_container
|
||||
|
|
@ -1702,13 +1702,13 @@ def note(message, title="", level=C.XMLUI_DATA_LVL_INFO):
|
|||
return note_xmlui
|
||||
|
||||
|
||||
def quickNote(host, client, message, title="", level=C.XMLUI_DATA_LVL_INFO):
|
||||
def quick_note(host, client, message, title="", level=C.XMLUI_DATA_LVL_INFO):
|
||||
"""more sugar to do the whole note process"""
|
||||
note_ui = note(message, title, level)
|
||||
host.actionNew({"xmlui": note_ui.toXml()}, profile=client.profile)
|
||||
host.action_new({"xmlui": note_ui.toXml()}, profile=client.profile)
|
||||
|
||||
|
||||
def deferredUI(host, xmlui, chained=False):
|
||||
def deferred_ui(host, xmlui, chained=False):
|
||||
"""create a deferred linked to XMLUI
|
||||
|
||||
@param xmlui(XMLUI): instance of the XMLUI
|
||||
|
|
@ -1720,15 +1720,15 @@ def deferredUI(host, xmlui, chained=False):
|
|||
assert xmlui.submit_id == ""
|
||||
xmlui_d = defer.Deferred()
|
||||
|
||||
def onSubmit(data, profile):
|
||||
def on_submit(data, profile):
|
||||
xmlui_d.callback(data)
|
||||
return xmlui_d if chained else {}
|
||||
|
||||
xmlui.submit_id = host.registerCallback(onSubmit, with_data=True, one_shot=True)
|
||||
xmlui.submit_id = host.register_callback(on_submit, with_data=True, one_shot=True)
|
||||
return xmlui_d
|
||||
|
||||
|
||||
def deferXMLUI(host, xmlui, action_extra=None, security_limit=C.NO_SECURITY_LIMIT,
|
||||
def defer_xmlui(host, xmlui, action_extra=None, security_limit=C.NO_SECURITY_LIMIT,
|
||||
chained=False, profile=C.PROF_KEY_NONE):
|
||||
"""Create a deferred linked to XMLUI
|
||||
|
||||
|
|
@ -1736,17 +1736,17 @@ def deferXMLUI(host, xmlui, action_extra=None, security_limit=C.NO_SECURITY_LIMI
|
|||
Must be an XMLUI that you can submit, with submit_id set to ''
|
||||
@param profile: %(doc_profile)s
|
||||
@param action_extra(None, dict): extra action to merge with xmlui
|
||||
mainly used to add meta informations (see actionNew doc)
|
||||
mainly used to add meta informations (see action_new doc)
|
||||
@param security_limit: %(doc_security_limit)s
|
||||
@param chained(bool): True if the Deferred result must be returned to the frontend
|
||||
useful when backend is in a series of dialogs with an ui
|
||||
@return (data): a deferred which fire the data
|
||||
"""
|
||||
xmlui_d = deferredUI(host, xmlui, chained)
|
||||
xmlui_d = deferred_ui(host, xmlui, chained)
|
||||
action_data = {"xmlui": xmlui.toXml()}
|
||||
if action_extra is not None:
|
||||
action_data.update(action_extra)
|
||||
host.actionNew(
|
||||
host.action_new(
|
||||
action_data,
|
||||
security_limit=security_limit,
|
||||
keep_id=xmlui.submit_id,
|
||||
|
|
@ -1755,7 +1755,7 @@ def deferXMLUI(host, xmlui, action_extra=None, security_limit=C.NO_SECURITY_LIMI
|
|||
return xmlui_d
|
||||
|
||||
|
||||
def deferDialog(host, message, title="Please confirm", type_=C.XMLUI_DIALOG_CONFIRM,
|
||||
def defer_dialog(host, message, title="Please confirm", type_=C.XMLUI_DIALOG_CONFIRM,
|
||||
options=None, action_extra=None, security_limit=C.NO_SECURITY_LIMIT, chained=False,
|
||||
profile=C.PROF_KEY_NONE):
|
||||
"""Create a submitable dialog and manage it with a deferred
|
||||
|
|
@ -1766,7 +1766,7 @@ def deferDialog(host, message, title="Please confirm", type_=C.XMLUI_DIALOG_CONF
|
|||
@param options(None, dict): if not None, will be used to update (extend) dialog_opt
|
||||
arguments of XMLUI
|
||||
@param action_extra(None, dict): extra action to merge with xmlui
|
||||
mainly used to add meta informations (see actionNew doc)
|
||||
mainly used to add meta informations (see action_new doc)
|
||||
@param security_limit: %(doc_security_limit)s
|
||||
@param chained(bool): True if the Deferred result must be returned to the frontend
|
||||
useful when backend is in a series of dialogs with an ui
|
||||
|
|
@ -1778,19 +1778,19 @@ def deferDialog(host, message, title="Please confirm", type_=C.XMLUI_DIALOG_CONF
|
|||
if options is not None:
|
||||
dialog_opt.update(options)
|
||||
dialog = XMLUI(C.XMLUI_DIALOG, title=title, dialog_opt=dialog_opt, submit_id="")
|
||||
return deferXMLUI(host, dialog, action_extra, security_limit, chained, profile)
|
||||
return defer_xmlui(host, dialog, action_extra, security_limit, chained, profile)
|
||||
|
||||
|
||||
def deferConfirm(*args, **kwargs):
|
||||
"""call deferDialog and return a boolean instead of the whole data dict"""
|
||||
d = deferDialog(*args, **kwargs)
|
||||
def defer_confirm(*args, **kwargs):
|
||||
"""call defer_dialog and return a boolean instead of the whole data dict"""
|
||||
d = defer_dialog(*args, **kwargs)
|
||||
d.addCallback(lambda data: C.bool(data["answer"]))
|
||||
return d
|
||||
|
||||
|
||||
# Misc other funtions
|
||||
|
||||
def elementCopy(
|
||||
def element_copy(
|
||||
element: domish.Element,
|
||||
with_parent: bool = True,
|
||||
with_children: bool = True
|
||||
|
|
@ -1815,7 +1815,7 @@ def elementCopy(
|
|||
return new_elt
|
||||
|
||||
|
||||
def isXHTMLField(field):
|
||||
def is_xhtml_field(field):
|
||||
"""Check if a data_form.Field is an XHTML one"""
|
||||
return (field.fieldType is None and field.ext_type == "xml" and
|
||||
field.value.uri == C.NS_XHTML)
|
||||
|
|
@ -1826,7 +1826,7 @@ class ElementParser:
|
|||
|
||||
# XXX: Found at http://stackoverflow.com/questions/2093400/how-to-create-twisted-words-xish-domish-element-entirely-from-raw-xml/2095942#2095942
|
||||
|
||||
def _escapeHTML(self, matchobj):
|
||||
def _escape_html(self, matchobj):
|
||||
entity = matchobj.group(1)
|
||||
if entity in XML_ENTITIES:
|
||||
# we don't escape XML entities
|
||||
|
|
@ -1854,23 +1854,23 @@ class ElementParser:
|
|||
raw_xml = "<div>{}</div>".format(raw_xml)
|
||||
|
||||
# avoid ParserError on HTML escaped chars
|
||||
raw_xml = html_entity_re.sub(self._escapeHTML, raw_xml)
|
||||
raw_xml = html_entity_re.sub(self._escape_html, raw_xml)
|
||||
|
||||
self.result = None
|
||||
|
||||
def onStart(elem):
|
||||
def on_start(elem):
|
||||
self.result = elem
|
||||
|
||||
def onEnd():
|
||||
def on_end():
|
||||
pass
|
||||
|
||||
def onElement(elem):
|
||||
self.result.addChild(elem)
|
||||
|
||||
parser = domish.elementStream()
|
||||
parser.DocumentStartEvent = onStart
|
||||
parser.DocumentStartEvent = on_start
|
||||
parser.ElementEvent = onElement
|
||||
parser.DocumentEndEvent = onEnd
|
||||
parser.DocumentEndEvent = on_end
|
||||
tmp = domish.Element((None, "s"))
|
||||
if force_spaces:
|
||||
raw_xml = raw_xml.replace("\n", " ").replace("\t", " ")
|
||||
|
|
@ -1888,8 +1888,8 @@ class ElementParser:
|
|||
parse = ElementParser()
|
||||
|
||||
|
||||
# FIXME: this method is duplicated from frontends.tools.xmlui.getText
|
||||
def getText(node):
|
||||
# FIXME: this method is duplicated from frontends.tools.xmlui.get_text
|
||||
def get_text(node):
|
||||
"""Get child text nodes of a domish.Element.
|
||||
|
||||
@param node (domish.Element)
|
||||
|
|
@ -1902,7 +1902,7 @@ def getText(node):
|
|||
return "".join(data)
|
||||
|
||||
|
||||
def findAll(elt, namespaces=None, names=None):
|
||||
def find_all(elt, namespaces=None, names=None):
|
||||
"""Find child element at any depth matching criteria
|
||||
|
||||
@param elt(domish.Element): top parent of the elements to find
|
||||
|
|
@ -1924,11 +1924,11 @@ def findAll(elt, namespaces=None, names=None):
|
|||
and (not namespaces or child.uri in namespaces)
|
||||
):
|
||||
yield child
|
||||
for found in findAll(child, namespaces, names):
|
||||
for found in find_all(child, namespaces, names):
|
||||
yield found
|
||||
|
||||
|
||||
def findAncestor(
|
||||
def find_ancestor(
|
||||
elt,
|
||||
name: str,
|
||||
namespace: Optional[Union[str, Iterable[str]]] = None
|
||||
|
|
@ -1958,12 +1958,12 @@ def findAncestor(
|
|||
current = current.parent
|
||||
|
||||
|
||||
def pFmtElt(elt, indent=0, defaultUri=""):
|
||||
def p_fmt_elt(elt, indent=0, defaultUri=""):
|
||||
"""Pretty format a domish.Element"""
|
||||
strings = []
|
||||
for child in elt.children:
|
||||
if domish.IElement.providedBy(child):
|
||||
strings.append(pFmtElt(child, indent+2, defaultUri=elt.defaultUri))
|
||||
strings.append(p_fmt_elt(child, indent+2, defaultUri=elt.defaultUri))
|
||||
else:
|
||||
strings.append(f"{(indent+2)*' '}{child!s}")
|
||||
if elt.children:
|
||||
|
|
@ -1977,9 +1977,9 @@ def pFmtElt(elt, indent=0, defaultUri=""):
|
|||
return '\n'.join(strings)
|
||||
|
||||
|
||||
def ppElt(elt):
|
||||
def pp_elt(elt):
|
||||
"""Pretty print a domish.Element"""
|
||||
print(pFmtElt(elt))
|
||||
print(p_fmt_elt(elt))
|
||||
|
||||
|
||||
# ElementTree
|
||||
|
|
|
|||
Loading…
Reference in a new issue