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:
Goffi 2023-04-08 13:54:42 +02:00
commit 6a6f15707a
10 changed files with 9945 additions and 9945 deletions

View file

@ -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

View file

@ -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

View file

@ -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)

View file

@ -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")

View file

@ -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

View file

@ -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.

View file

@ -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)

View file

@ -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:

View file

@ -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_))

View file

@ -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}"