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

@ -46,7 +46,7 @@ from sat.tools.common import data_format
from sat.tools.common.ansi import ANSI as A
from sat.core import exceptions
import sat_frontends.jp
from sat_frontends.jp.loops import QuitException, getJPLoop
from sat_frontends.jp.loops import QuitException, get_jp_loop
from sat_frontends.jp.constants import Const as C
from sat_frontends.bridge.bridge_frontend import BridgeException
from sat_frontends.tools import misc
@ -55,9 +55,9 @@ from collections import OrderedDict
## bridge handling
# we get bridge name from conf and initialise the right class accordingly
main_config = config.parseMainConf()
bridge_name = config.getConfig(main_config, '', 'bridge', 'dbus')
JPLoop = getJPLoop(bridge_name)
main_config = config.parse_main_conf()
bridge_name = config.config_get(main_config, '', 'bridge', 'dbus')
JPLoop = get_jp_loop(bridge_name)
try:
@ -118,7 +118,7 @@ class LiberviaCli:
def get_config(self, name, section=C.CONFIG_SECTION, default=None):
"""Retrieve a setting value from sat.conf"""
return config.getConfig(self.sat_conf, section, name, default=default)
return config.config_get(self.sat_conf, section, name, default=default)
def guess_background(self):
# cf. https://unix.stackexchange.com/a/245568 (thanks!)
@ -204,7 +204,7 @@ class LiberviaCli:
C.A_DIRECTORY = A.BOLD + A.FG_MAGENTA
C.A_FILE = A.FG_BLACK
def _bridgeConnected(self):
def _bridge_connected(self):
self.parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter, description=DESCRIPTION)
self._make_parents()
@ -231,7 +231,7 @@ class LiberviaCli:
async def set_progress_id(self, progress_id):
# because we use async, we need an explicit setter
self._progress_id = progress_id
await self.replayCache('progress_ids_cache')
await self.replay_cache('progress_ids_cache')
@property
def watch_progress(self):
@ -254,7 +254,7 @@ class LiberviaCli:
except AttributeError:
return 0
async def replayCache(self, cache_attribute):
async def replay_cache(self, cache_attribute):
"""Replay cached signals
@param cache_attribute(str): name of the attribute containing the cache
@ -294,14 +294,14 @@ class LiberviaCli:
if inspect.isawaitable(ret):
await ret
def addOnQuitCallback(self, callback, *args, **kwargs):
def add_on_quit_callback(self, callback, *args, **kwargs):
"""Add a callback which will be called on quit command
@param callback(callback): method to call
"""
self._onQuitCallbacks.append((callback, args, kwargs))
def getOutputChoices(self, output_type):
def get_output_choices(self, output_type):
"""Return valid output filters for output_type
@param output_type: True for default,
@ -612,7 +612,7 @@ class LiberviaCli:
url = self.get_xmpp_uri_from_http(url)
try:
uri_data = uri.parseXMPPUri(url)
uri_data = uri.parse_xmpp_uri(url)
except ValueError:
self.parser.error(_('invalid XMPP URL: {url}').format(url=url))
else:
@ -694,7 +694,7 @@ class LiberviaCli:
async def main(self, args, namespace):
try:
await self.bridge.bridgeConnect()
await self.bridge.bridge_connect()
except Exception as e:
if isinstance(e, exceptions.BridgeExceptionNoService):
print(
@ -711,9 +711,9 @@ class LiberviaCli:
)
self.quit(C.EXIT_BRIDGE_ERROR, raise_exc=False)
return
await self.bridge.getReady()
self.version = await self.bridge.getVersion()
self._bridgeConnected()
await self.bridge.ready_get()
self.version = await self.bridge.version_get()
self._bridge_connected()
self.import_plugins()
try:
self.args = self.parser.parse_args(args, namespace=None)
@ -756,14 +756,14 @@ class LiberviaCli:
res = await self.ainput(f"{message} (y/N)? ")
return res in ("y", "Y")
async def confirmOrQuit(self, message, cancel_message=_("action cancelled by user")):
async def confirm_or_quit(self, message, cancel_message=_("action cancelled by user")):
"""Request user to confirm action, and quit if he doesn't"""
confirmed = await self.confirm(message)
if not confirmed:
self.disp(cancel_message)
self.quit(C.EXIT_USER_CANCELLED)
def quitFromSignal(self, exit_code=0):
def quit_from_signal(self, exit_code=0):
r"""Same as self.quit, but from a signal handler
/!\: return must be used after calling this method !
@ -805,7 +805,7 @@ class LiberviaCli:
nodes2jid = {}
try:
contacts = await self.bridge.getContacts(self.profile)
contacts = await self.bridge.contacts_get(self.profile)
except BridgeException as e:
if e.classname == "AttributeError":
# we may get an AttributeError if we use a component profile
@ -872,7 +872,7 @@ class LiberviaCli:
self.disp('')
return pwd
async def connectOrPrompt(self, method, err_msg=None):
async def connect_or_prompt(self, method, err_msg=None):
"""Try to connect/start profile session and prompt for password if needed
@param method(callable): bridge method to either connect or start profile session
@ -907,7 +907,7 @@ class LiberviaCli:
"""
# FIXME: need better exit codes
self.profile = await self.bridge.profileNameGet(self.args.profile)
self.profile = await self.bridge.profile_name_get(self.args.profile)
if not self.profile:
log.error(
@ -922,12 +922,12 @@ class LiberviaCli:
pass
else:
if start_session:
await self.connectOrPrompt(
lambda pwd: self.bridge.profileStartSession(pwd, self.profile),
await self.connect_or_prompt(
lambda pwd: self.bridge.profile_start_session(pwd, self.profile),
err_msg="Can't start {profile}'s session: {e}"
)
return
elif not await self.bridge.profileIsSessionStarted(self.profile):
elif not await self.bridge.profile_is_session_started(self.profile):
if not self.args.connect:
self.disp(_(
"Session for [{profile}] is not started, please start it "
@ -945,13 +945,13 @@ class LiberviaCli:
# creation/deletion)
return
elif self.args.connect is True: # if connection is asked, we connect the profile
await self.connectOrPrompt(
await self.connect_or_prompt(
lambda pwd: self.bridge.connect(self.profile, pwd, {}),
err_msg = 'Can\'t connect profile "{profile!s}": {e}'
)
return
else:
if not await self.bridge.isConnected(self.profile):
if not await self.bridge.is_connected(self.profile):
log.error(
_("Profile [{profile}] is not connected, please connect it "
"before using jp, or use --connect option")
@ -966,14 +966,14 @@ class LiberviaCli:
_jid = JID(param_jid)
if not _jid.resource:
#if the resource is not given, we try to add the main resource
main_resource = await self.bridge.getMainResource(param_jid, self.profile)
main_resource = await self.bridge.main_resource_get(param_jid, self.profile)
if main_resource:
return f"{_jid.bare}/{main_resource}"
return param_jid
async def get_profile_jid(self):
"""Retrieve current profile bare JID if possible"""
full_jid = await self.bridge.asyncGetParamA(
full_jid = await self.bridge.param_get_a_async(
"JabberID", "Connection", profile_key=self.profile
)
return full_jid.rsplit("/", 1)[0]
@ -1054,7 +1054,7 @@ class CommandBase:
assert use_output in C.OUTPUT_TYPES
self._output_type = use_output
output_parent = argparse.ArgumentParser(add_help=False)
choices = set(self.host.getOutputChoices(use_output))
choices = set(self.host.get_output_choices(use_output))
choices.update(extra_outputs)
if not choices:
raise exceptions.InternalError(
@ -1125,14 +1125,14 @@ class CommandBase:
async def set_progress_id(self, progress_id):
return await self.host.set_progress_id(progress_id)
async def progressStartedHandler(self, uid, metadata, profile):
async def progress_started_handler(self, uid, metadata, profile):
if profile != self.profile:
return
if self.progress_id is None:
# the progress started message can be received before the id
# so we keep progressStarted signals in cache to replay they
# so we keep progress_started signals in cache to replay they
# when the progress_id is received
cache_data = (self.progressStartedHandler, uid, metadata, profile)
cache_data = (self.progress_started_handler, uid, metadata, profile)
try:
cache = self.host.progress_ids_cache
except AttributeError:
@ -1140,14 +1140,14 @@ class CommandBase:
cache.append(cache_data)
else:
if self.host.watch_progress and uid == self.progress_id:
await self.onProgressStarted(metadata)
await self.on_progress_started(metadata)
while True:
await asyncio.sleep(PROGRESS_DELAY)
cont = await self.progressUpdate()
cont = await self.progress_update()
if not cont:
break
async def progressFinishedHandler(self, uid, metadata, profile):
async def progress_finished_handler(self, uid, metadata, profile):
if profile != self.profile:
return
if uid == self.progress_id:
@ -1155,26 +1155,26 @@ class CommandBase:
self.host.pbar.finish()
except AttributeError:
pass
await self.onProgressFinished(metadata)
await self.on_progress_finished(metadata)
if self.host.quit_on_progress_end:
self.host.quitFromSignal()
self.host.quit_from_signal()
async def progressErrorHandler(self, uid, message, profile):
async def progress_error_handler(self, uid, message, profile):
if profile != self.profile:
return
if uid == self.progress_id:
if self.args.progress:
self.disp('') # progress is not finished, so we skip a line
if self.host.quit_on_progress_end:
await self.onProgressError(message)
self.host.quitFromSignal(C.EXIT_ERROR)
await self.on_progress_error(message)
self.host.quit_from_signal(C.EXIT_ERROR)
async def progressUpdate(self):
async def progress_update(self):
"""This method is continualy called to update the progress bar
@return (bool): False to stop being called
"""
data = await self.host.bridge.progressGet(self.progress_id, self.profile)
data = await self.host.bridge.progress_get(self.progress_id, self.profile)
if data:
try:
size = data['size']
@ -1214,38 +1214,38 @@ class CommandBase:
elif self.host.pbar is not None:
return False
await self.onProgressUpdate(data)
await self.on_progress_update(data)
return True
async def onProgressStarted(self, metadata):
async def on_progress_started(self, metadata):
"""Called when progress has just started
can be overidden by a command
@param metadata(dict): metadata as sent by bridge.progressStarted
@param metadata(dict): metadata as sent by bridge.progress_started
"""
self.disp(_("Operation started"), 2)
async def onProgressUpdate(self, metadata):
async def on_progress_update(self, metadata):
"""Method called on each progress updata
can be overidden by a command to handle progress metadata
@para metadata(dict): metadata as returned by bridge.progressGet
@para metadata(dict): metadata as returned by bridge.progress_get
"""
pass
async def onProgressFinished(self, metadata):
async def on_progress_finished(self, metadata):
"""Called when progress has just finished
can be overidden by a command
@param metadata(dict): metadata as sent by bridge.progressFinished
@param metadata(dict): metadata as sent by bridge.progress_finished
"""
self.disp(_("Operation successfully finished"), 2)
async def onProgressError(self, e):
async def on_progress_error(self, e):
"""Called when a progress failed
@param error_msg(unicode): error message as sent by bridge.progressError
@param error_msg(unicode): error message as sent by bridge.progress_error
"""
self.disp(_("Error while doing operation: {e}").format(e=e), error=True)
@ -1260,7 +1260,7 @@ class CommandBase:
_('trying to use output when use_output has not been set'))
return self.host.output(output_type, self.args.output, self.extra_outputs, data)
def getPubsubExtra(self, extra: Optional[dict] = None) -> str:
def get_pubsub_extra(self, extra: Optional[dict] = None) -> str:
"""Helper method to compute extra data from pubsub arguments
@param extra: base extra dict, or None to generate a new one
@ -1328,7 +1328,7 @@ class CommandBase:
for cls in subcommands:
cls(self)
def overridePubsubFlags(self, new_flags: Set[str]) -> None:
def override_pubsub_flags(self, new_flags: Set[str]) -> None:
"""Replace pubsub_flags given in __init__
useful when a command is extending an other command (e.g. blog command which does
@ -1356,11 +1356,11 @@ class CommandBase:
# we need to register the following signal even if we don't display the
# progress bar
self.host.bridge.register_signal(
"progressStarted", self.progressStartedHandler)
"progress_started", self.progress_started_handler)
self.host.bridge.register_signal(
"progressFinished", self.progressFinishedHandler)
"progress_finished", self.progress_finished_handler)
self.host.bridge.register_signal(
"progressError", self.progressErrorHandler)
"progress_error", self.progress_error_handler)
if self.need_connect is not None:
await self.host.connect_profile()
@ -1387,7 +1387,7 @@ class CommandAnswering(CommandBase):
def __init__(self, *args, **kwargs):
super(CommandAnswering, self).__init__(*args, **kwargs)
async def onActionNew(self, action_data, action_id, security_limit, profile):
async def on_action_new(self, action_data, action_id, security_limit, profile):
if profile != self.profile:
return
try:
@ -1398,7 +1398,7 @@ class CommandAnswering(CommandBase):
except KeyError:
pass
else:
self.onXMLUI(xml_ui)
self.on_xmlui(xml_ui)
else:
try:
callback = self.action_callbacks[action_type]
@ -1407,7 +1407,7 @@ class CommandAnswering(CommandBase):
else:
await callback(action_data, action_id, security_limit, profile)
def onXMLUI(self, xml_ui):
def on_xmlui(self, xml_ui):
"""Display a dialog received from the backend.
@param xml_ui (unicode): dialog XML representation
@ -1422,7 +1422,7 @@ class CommandAnswering(CommandBase):
async def start_answering(self):
"""Auto reply to confirmation requests"""
self.host.bridge.register_signal("actionNew", self.onActionNew)
actions = await self.host.bridge.actionsGet(self.profile)
self.host.bridge.register_signal("action_new", self.on_action_new)
actions = await self.host.bridge.actions_get(self.profile)
for action_data, action_id, security_limit in actions:
await self.onActionNew(action_data, action_id, security_limit, self.profile)
await self.on_action_new(action_data, action_id, security_limit, self.profile)