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

View file

@ -65,13 +65,13 @@ def format_time(timestamp):
def ansi_ljust(s, width):
"""ljust method handling ANSI escape codes"""
cleaned = regex.ansiRemove(s)
cleaned = regex.ansi_remove(s)
return s + " " * (width - len(cleaned))
def ansi_center(s, width):
"""ljust method handling ANSI escape codes"""
cleaned = regex.ansiRemove(s)
cleaned = regex.ansi_remove(s)
diff = width - len(cleaned)
half = diff / 2
return half * " " + s + (half + diff % 2) * " "
@ -79,25 +79,25 @@ def ansi_center(s, width):
def ansi_rjust(s, width):
"""ljust method handling ANSI escape codes"""
cleaned = regex.ansiRemove(s)
cleaned = regex.ansi_remove(s)
return " " * (width - len(cleaned)) + s
def getTmpDir(sat_conf, cat_dir, sub_dir=None):
def get_tmp_dir(sat_conf, cat_dir, sub_dir=None):
"""Return directory used to store temporary files
@param sat_conf(ConfigParser.ConfigParser): instance opened on sat configuration
@param cat_dir(str): directory of the category (e.g. "blog")
@param sub_dir(str): sub directory where data need to be put
profile can be used here, or special directory name
sub_dir will be escaped to be usable in path (use regex.pathUnescape to find
sub_dir will be escaped to be usable in path (use regex.path_unescape to find
initial str)
@return (Path): path to the dir
"""
local_dir = config.getConfig(sat_conf, "", "local_dir", Exception)
local_dir = config.config_get(sat_conf, "", "local_dir", Exception)
path_elts = [local_dir, cat_dir]
if sub_dir is not None:
path_elts.append(regex.pathEscape(sub_dir))
path_elts.append(regex.path_escape(sub_dir))
return Path(*path_elts)
@ -141,7 +141,7 @@ class BaseEdit(object):
self.cat_dir = cat_dir
self.use_metadata = use_metadata
def secureUnlink(self, path):
def secure_unlink(self, path):
"""Unlink given path after keeping it for a while
This method is used to prevent accidental deletion of a draft
@ -152,7 +152,7 @@ class BaseEdit(object):
path = Path(path).resolve()
if not path.is_file:
raise OSError("path must link to a regular file")
if path.parent != getTmpDir(self.sat_conf, self.cat_dir):
if path.parent != get_tmp_dir(self.sat_conf, self.cat_dir):
self.disp(
f"File {path} is not in SàT temporary hierarchy, we do not remove " f"it",
2,
@ -160,7 +160,7 @@ class BaseEdit(object):
return
# we have 2 files per draft with use_metadata, so we double max
unlink_max = SECURE_UNLINK_MAX * 2 if self.use_metadata else SECURE_UNLINK_MAX
backup_dir = getTmpDir(self.sat_conf, self.cat_dir, SECURE_UNLINK_DIR)
backup_dir = get_tmp_dir(self.sat_conf, self.cat_dir, SECURE_UNLINK_DIR)
if not os.path.exists(backup_dir):
os.makedirs(backup_dir)
filename = os.path.basename(path)
@ -179,7 +179,7 @@ class BaseEdit(object):
self.host.disp("Purging backup file {}".format(path), 2)
os.unlink(path)
async def runEditor(
async def run_editor(
self,
editor_args_opt,
content_file_path,
@ -210,12 +210,12 @@ class BaseEdit(object):
content_file_obj.close()
# we prepare arguments
editor = config.getConfig(self.sat_conf, C.CONFIG_SECTION, "editor") or os.getenv(
editor = config.config_get(self.sat_conf, C.CONFIG_SECTION, "editor") or os.getenv(
"EDITOR", "vi"
)
try:
# is there custom arguments in sat.conf ?
editor_args = config.getConfig(
editor_args = config.config_get(
self.sat_conf, C.CONFIG_SECTION, editor_args_opt, Exception
)
except (NoOptionError, NoSectionError):
@ -291,7 +291,7 @@ class BaseEdit(object):
if len(content) == 0:
self.disp("Content is empty, cancelling the edition")
if content_file_path.parent != getTmpDir(self.sat_conf, self.cat_dir):
if content_file_path.parent != get_tmp_dir(self.sat_conf, self.cat_dir):
self.disp(
"File are not in SàT temporary hierarchy, we do not remove them",
2,
@ -335,22 +335,22 @@ class BaseEdit(object):
)
self.host.quit(1)
self.secureUnlink(content_file_path)
self.secure_unlink(content_file_path)
if self.use_metadata:
self.secureUnlink(meta_file_path)
self.secure_unlink(meta_file_path)
async def publish(self, content):
# if metadata is needed, publish will be called with it last argument
raise NotImplementedError
def getTmpFile(self):
def get_tmp_file(self):
"""Create a temporary file
@return (tuple(file, Path)): opened (w+b) file object and file path
"""
suff = "." + self.getTmpSuff()
suff = "." + self.get_tmp_suff()
cat_dir_str = self.cat_dir
tmp_dir = getTmpDir(self.sat_conf, self.cat_dir, self.profile)
tmp_dir = get_tmp_dir(self.sat_conf, self.cat_dir, self.profile)
if not tmp_dir.exists():
try:
tmp_dir.mkdir(parents=True)
@ -372,7 +372,7 @@ class BaseEdit(object):
self.disp(f"Can't create temporary file: {e}", error=True)
self.host.quit(1)
def getCurrentFile(self, profile):
def get_current_file(self, profile):
"""Get most recently edited file
@param profile(unicode): profile linked to the draft
@ -381,7 +381,7 @@ class BaseEdit(object):
# we guess the item currently edited by choosing
# the most recent file corresponding to temp file pattern
# in tmp_dir, excluding metadata files
tmp_dir = getTmpDir(self.sat_conf, self.cat_dir, profile)
tmp_dir = get_tmp_dir(self.sat_conf, self.cat_dir, profile)
available = [
p
for p in tmp_dir.glob(f"{self.cat_dir}_*")
@ -395,15 +395,15 @@ class BaseEdit(object):
self.host.quit(1)
return max(available, key=lambda p: p.stat().st_mtime)
async def getItemData(self, service, node, item):
async def get_item_data(self, service, node, item):
"""return formatted content, metadata (or not if use_metadata is false), and item id"""
raise NotImplementedError
def getTmpSuff(self):
def get_tmp_suff(self):
"""return suffix used for content file"""
return "xml"
async def getItemPath(self):
async def get_item_path(self):
"""Retrieve item path (i.e. service and node) from item argument
This method is obviously only useful for edition of PubSub based features
@ -415,7 +415,7 @@ class BaseEdit(object):
if self.args.current:
# user wants to continue current draft
content_file_path = self.getCurrentFile(self.profile)
content_file_path = self.get_current_file(self.profile)
self.disp("Continuing edition of current draft", 2)
content_file_obj = content_file_path.open("r+b")
# we seek at the end of file in case of an item already exist
@ -430,15 +430,15 @@ class BaseEdit(object):
content_file_obj.seek(0, os.SEEK_END)
else:
# we need a temporary file
content_file_obj, content_file_path = self.getTmpFile()
content_file_obj, content_file_path = self.get_tmp_file()
if item or last_item:
self.disp("Editing requested published item", 2)
try:
if self.use_metadata:
content, metadata, item = await self.getItemData(service, node, item)
content, metadata, item = await self.get_item_data(service, node, item)
else:
content, item = await self.getItemData(service, node, item)
content, item = await self.get_item_data(service, node, item)
except Exception as e:
# FIXME: ugly but we have not good may to check errors in bridge
if "item-not-found" in str(e):
@ -529,7 +529,7 @@ class Table(object):
col_value = filter_(value)
# we count size without ANSI code as they will change length of the
# string when it's mostly style/color changes.
col_size = len(regex.ansiRemove(col_value))
col_size = len(regex.ansi_remove(col_value))
else:
col_value = str(value)
col_size = len(col_value)
@ -558,7 +558,7 @@ class Table(object):
return "\n".join(self._buffer)
@staticmethod
def readDictValues(data, keys, defaults=None):
def read_dict_values(data, keys, defaults=None):
if defaults is None:
defaults = {}
for key in keys:
@ -572,7 +572,7 @@ class Table(object):
raise e
@classmethod
def fromListDict(
def from_list_dict(
cls, host, data, keys=None, headers=None, filters=None, defaults=None
):
"""Create a table from a list of dictionaries
@ -600,7 +600,7 @@ class Table(object):
filters = {}
filters = [filters.get(k) for k in keys]
return cls(
host, (cls.readDictValues(d, keys, defaults) for d in data), headers, filters
host, (cls.read_dict_values(d, keys, defaults) for d in data), headers, filters
)
def _headers(self, head_sep, headers, sizes, alignment="left", style=None):
@ -679,7 +679,7 @@ class Table(object):
if not self.sizes:
# the table is empty
return
col_sep_size = len(regex.ansiRemove(col_sep))
col_sep_size = len(regex.ansi_remove(col_sep))
# if we have columns to hide, we remove them from headers and size
if not hide_cols:
@ -784,7 +784,7 @@ async def fill_well_known_uri(command, path, key, meta_map=None):
host = command.host
try:
uris_data = await host.bridge.URIFind(path, [key])
uris_data = await host.bridge.uri_find(path, [key])
except Exception as e:
host.disp(f"can't find {key} URI: {e}", error=True)
host.quit(C.EXIT_BRIDGE_ERRBACK)
@ -824,7 +824,7 @@ async def fill_well_known_uri(command, path, key, meta_map=None):
values.extend(json.loads(new_values_json))
setattr(args, dest, values)
parsed_uri = xmpp_uri.parseXMPPUri(uri)
parsed_uri = xmpp_uri.parse_xmpp_uri(uri)
try:
args.service = parsed_uri["path"]
args.node = parsed_uri["node"]