Refactoring
- Flatten plugin module into Plugin class - Move logger to its own class and rework it slightly - Rename source and name to get_source and get_name since name() now clashes with the plugin name
This commit is contained in:
parent
00f3321230
commit
a9fa15d643
7 changed files with 82 additions and 68 deletions
2
examples
2
examples
|
@ -1 +1 @@
|
||||||
Subproject commit 49bd55b9951270f233683f7bd51f70f8eab43985
|
Subproject commit f8b077f3764c16935462ffb818bdb5aeda75222b
|
43
src/sshare/logger.py
Normal file
43
src/sshare/logger.py
Normal file
|
@ -0,0 +1,43 @@
|
||||||
|
# This file is part of SSHare.
|
||||||
|
#
|
||||||
|
# SSHare is free software: you can redistribute it and/or modify it under the terms of
|
||||||
|
# the GNU General Public License as published by the Free Software Foundation,
|
||||||
|
# either version 3 of the License, or (at your option) any later version.
|
||||||
|
#
|
||||||
|
# SSHare is distributed in the hope that it will be useful, but WITHOUT ANY
|
||||||
|
# WARRANTY; without even the implied warranty of MERCHANTABILITY
|
||||||
|
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||||
|
# more details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU General Public License along with
|
||||||
|
# SSHare. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
from sshare.plugin import Plugin
|
||||||
|
|
||||||
|
class Logger:
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
if kwargs.get("preload_command_line") == True:
|
||||||
|
self.loggers = [ Plugin.internal("command_line") ]
|
||||||
|
else:
|
||||||
|
self.loggers = []
|
||||||
|
self.add(*args)
|
||||||
|
|
||||||
|
def add(self, *args, **kwargs):
|
||||||
|
for logger in args:
|
||||||
|
self.loggers.append()
|
||||||
|
|
||||||
|
def info(self, message):
|
||||||
|
for logger in self.loggers:
|
||||||
|
logger.info(message)
|
||||||
|
|
||||||
|
def warn(self, message):
|
||||||
|
for logger in self.loggers:
|
||||||
|
logger.warn(message)
|
||||||
|
|
||||||
|
def error(self, message):
|
||||||
|
for logger in self.loggers:
|
||||||
|
logger.error(message)
|
||||||
|
|
||||||
|
def fatal(self, message, error_code=1):
|
||||||
|
self.error(message)
|
||||||
|
sys.exit(error_code)
|
|
@ -22,39 +22,13 @@ import subprocess
|
||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
from sshare.logger import Logger
|
||||||
from sshare.plugin import Plugin
|
from sshare.plugin import Plugin
|
||||||
from sshare.plugins.config import Flag
|
from sshare.plugins.config import Flag
|
||||||
from sshare.plugins.config import NoArgument
|
from sshare.plugins.config import NoArgument
|
||||||
from sshare.plugins.config import NoDefault
|
from sshare.plugins.config import NoDefault
|
||||||
|
|
||||||
from sshare.version import version
|
from sshare.version import version
|
||||||
|
|
||||||
class Congloggerate:
|
|
||||||
def __init__(self, loggers):
|
|
||||||
def info(message):
|
|
||||||
for logger in loggers:
|
|
||||||
logger.info(message)
|
|
||||||
|
|
||||||
def warn(message):
|
|
||||||
for logger in loggers:
|
|
||||||
logger.warn(message)
|
|
||||||
|
|
||||||
def error(message):
|
|
||||||
for logger in loggers:
|
|
||||||
logger.error(message)
|
|
||||||
|
|
||||||
self.info = info
|
|
||||||
self.warn = warn
|
|
||||||
self.error = error
|
|
||||||
|
|
||||||
fatalicize(self)
|
|
||||||
|
|
||||||
def fatalicize(logger):
|
|
||||||
def fatal(message):
|
|
||||||
logger.error(message)
|
|
||||||
sys.exit(1)
|
|
||||||
setattr(logger, "fatal", fatal)
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
config_directory = Path(os.environ.get("XDG_CONFIG_DIR") or f"{os.environ["HOME"]}/.config") / "sshare"
|
config_directory = Path(os.environ.get("XDG_CONFIG_DIR") or f"{os.environ["HOME"]}/.config") / "sshare"
|
||||||
|
@ -65,13 +39,10 @@ def main():
|
||||||
# so that it can be used to report errors while loading and
|
# so that it can be used to report errors while loading and
|
||||||
# configuring plugins
|
# configuring plugins
|
||||||
# i.e. before other logging plugins have had a chance to be initialised
|
# i.e. before other logging plugins have had a chance to be initialised
|
||||||
command_line = Plugin.internal("command_line")
|
logger = Logger(preload_command_line=True)
|
||||||
logger = command_line.module
|
|
||||||
fatalicize(logger)
|
|
||||||
|
|
||||||
# Load inbuilt plugins
|
# Load inbuilt plugins
|
||||||
plugins_flat = [
|
plugins_flat = [
|
||||||
command_line,
|
|
||||||
Plugin.internal("file"),
|
Plugin.internal("file"),
|
||||||
Plugin.internal("current_time"),
|
Plugin.internal("current_time"),
|
||||||
Plugin.internal("append_type"),
|
Plugin.internal("append_type"),
|
||||||
|
@ -107,15 +78,15 @@ def main():
|
||||||
if config.get("plugins") == None:
|
if config.get("plugins") == None:
|
||||||
config["plugins"] = {}
|
config["plugins"] = {}
|
||||||
for plugin in plugins_flat:
|
for plugin in plugins_flat:
|
||||||
if hasattr(plugin.module, "config"):
|
if hasattr(plugin, "config"):
|
||||||
plugin_config = config["plugins"].get(plugin.name)
|
plugin_config = config["plugins"].get(plugin.name)
|
||||||
if plugin_config != None:
|
if plugin_config != None:
|
||||||
for config_entry in plugin_config.items():
|
for config_entry in plugin_config.items():
|
||||||
plugin.module.config[config_entry[0]] = config_entry[1]
|
plugin.config[config_entry[0]] = config_entry[1]
|
||||||
else:
|
else:
|
||||||
setattr(plugin.module, "config", {})
|
setattr(plugin, "config", {})
|
||||||
if hasattr(plugin.module, "args"):
|
if hasattr(plugin, "args"):
|
||||||
for arg_name, arg in plugin.module.args.items():
|
for arg_name, arg in plugin.args.items():
|
||||||
if arg.is_valid():
|
if arg.is_valid():
|
||||||
arg.bind(plugin, arg_name)
|
arg.bind(plugin, arg_name)
|
||||||
def check_flag(flag):
|
def check_flag(flag):
|
||||||
|
@ -137,33 +108,33 @@ def main():
|
||||||
value = getattr(arguments, arg)
|
value = getattr(arguments, arg)
|
||||||
if value != NoArgument:
|
if value != NoArgument:
|
||||||
if value != Flag:
|
if value != Flag:
|
||||||
plugin.module.config[config] = value
|
plugin.config[config] = value
|
||||||
del argument_map[arg]
|
del argument_map[arg]
|
||||||
|
|
||||||
# Sort plugins by type and check activation criteria
|
# Sort plugins by type and check activation criteria
|
||||||
error = False
|
error = False
|
||||||
for plugin in plugins_flat:
|
for plugin in plugins_flat:
|
||||||
if isinstance(plugin.module.plugin_type, str):
|
if isinstance(plugin.plugin_type, str):
|
||||||
plugin.module.plugin_type = [ plugin.module.plugin_type ]
|
plugin.plugin_type = [ plugin.plugin_type ]
|
||||||
for plugin_type in plugin.module.plugin_type:
|
for plugin_type in plugin.plugin_type:
|
||||||
plugins_of_type = plugins.get(plugin_type)
|
plugins_of_type = plugins.get(plugin_type)
|
||||||
if plugins_of_type == None:
|
if plugins_of_type == None:
|
||||||
logger.error(f"Error: Plugin '{plugin.name}' has an invalid plugin type '{plugin_type}'")
|
logger.error(f"Error: Plugin '{plugin.name}' has an invalid plugin type '{plugin_type}'")
|
||||||
error = True
|
error = True
|
||||||
else:
|
else:
|
||||||
active = True
|
active = True
|
||||||
if hasattr(plugin.module, "activate"):
|
if hasattr(plugin, "activate"):
|
||||||
criteria = plugin.module.activate
|
criteria = plugin.activate
|
||||||
if isinstance(plugin.module.activate, dict):
|
if isinstance(plugin.activate, dict):
|
||||||
criteria = plugin.module.activate.get(plugin_type)
|
criteria = plugin.activate.get(plugin_type)
|
||||||
if criteria != None:
|
if criteria != None:
|
||||||
for criterion in criteria:
|
for criterion in criteria:
|
||||||
active = not plugin.module.args[criterion].dest in argument_map
|
active = not plugin.args[criterion].dest in argument_map
|
||||||
if not active:
|
if not active:
|
||||||
break
|
break
|
||||||
plugins_of_type["active" if active else "inactive"].append(plugin)
|
plugins_of_type["active" if active else "inactive"].append(plugin)
|
||||||
if active:
|
if active:
|
||||||
for config_entry in plugin.module.config.items():
|
for config_entry in plugin.config.items():
|
||||||
if config_entry[1] == NoDefault:
|
if config_entry[1] == NoDefault:
|
||||||
logger.error(f"Error: Value 'plugins.{plugin.name}.{config_entry[0]}' has no default value and must be specified explicitly")
|
logger.error(f"Error: Value 'plugins.{plugin.name}.{config_entry[0]}' has no default value and must be specified explicitly")
|
||||||
error = True
|
error = True
|
||||||
|
@ -175,11 +146,11 @@ def main():
|
||||||
logger.error(f"No '{plugin_type}' plugins activated. Activate at least one of:")
|
logger.error(f"No '{plugin_type}' plugins activated. Activate at least one of:")
|
||||||
for plugin in plugins_of_type["inactive"]:
|
for plugin in plugins_of_type["inactive"]:
|
||||||
logger.error(f"{plugin.name}:")
|
logger.error(f"{plugin.name}:")
|
||||||
criteria = plugin.module.activate
|
criteria = plugin.activate
|
||||||
if isinstance(plugin.module.activate, dict):
|
if isinstance(plugin.activate, dict):
|
||||||
criteria = plugin.module.activate[plugin_type]
|
criteria = plugin.activate[plugin_type]
|
||||||
for criterion in criteria:
|
for criterion in criteria:
|
||||||
logger.error(f" {plugin.module.args[criterion].pretty()}")
|
logger.error(f" {plugin.args[criterion].pretty()}")
|
||||||
error = True
|
error = True
|
||||||
if error:
|
if error:
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
@ -188,24 +159,24 @@ def main():
|
||||||
error = False
|
error = False
|
||||||
class PluginConfig: pass
|
class PluginConfig: pass
|
||||||
for plugin in plugins_flat:
|
for plugin in plugins_flat:
|
||||||
config = plugin.module.config
|
config = plugin.config
|
||||||
plugin.module.config = PluginConfig()
|
plugin.config = PluginConfig()
|
||||||
for config_entry in config.items():
|
for config_entry in config.items():
|
||||||
setattr(plugin.module.config, config_entry[0], config_entry[1])
|
setattr(plugin.config, config_entry[0], config_entry[1])
|
||||||
if error:
|
if error:
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
# Initialise plugins
|
# Initialise plugins
|
||||||
for plugin in plugins_flat:
|
for plugin in plugins_flat:
|
||||||
setattr(plugin.module, "logger", logger)
|
setattr(plugin, "logger", logger)
|
||||||
if hasattr(plugin.module, "init"):
|
if hasattr(plugin, "init"):
|
||||||
error = error or plugin.module.init()
|
error = error or plugin.init()
|
||||||
|
|
||||||
logger = Congloggerate([ logger.module for logger in plugins["logger"]["active"] ])
|
logger.add(*plugins["logger"]["active"])
|
||||||
|
|
||||||
sources = []
|
sources = []
|
||||||
for plugin in plugins["source"]["active"]:
|
for plugin in plugins["source"]["active"]:
|
||||||
sources.append(plugin.module.source())
|
sources.append(plugin.get_source())
|
||||||
if len(sources) == 0:
|
if len(sources) == 0:
|
||||||
logger.error("Error: No sources provided. Must activate at least one source plugin")
|
logger.error("Error: No sources provided. Must activate at least one source plugin")
|
||||||
log_activations(logger, plugins["source"])
|
log_activations(logger, plugins["source"])
|
||||||
|
@ -213,15 +184,15 @@ def main():
|
||||||
for index, source in enumerate(sources):
|
for index, source in enumerate(sources):
|
||||||
name = ""
|
name = ""
|
||||||
for plugin in plugins["name"]["active"]:
|
for plugin in plugins["name"]["active"]:
|
||||||
name = plugin.module.name(name, source)
|
name = plugin.get_name(name, source)
|
||||||
sources[index] = name, source
|
sources[index] = name, source
|
||||||
|
|
||||||
for name, source in sources:
|
for name, source in sources:
|
||||||
for plugin in plugins["upload"]["active"]:
|
for plugin in plugins["upload"]["active"]:
|
||||||
plugin.module.upload(name, source)
|
plugin.upload(name, source)
|
||||||
|
|
||||||
for name, _ in sources:
|
for name, _ in sources:
|
||||||
for plugin in plugins["result"]["active"]:
|
for plugin in plugins["result"]["active"]:
|
||||||
plugin.module.result(name)
|
plugin.result(name)
|
||||||
|
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
|
|
|
@ -17,8 +17,8 @@ import importlib.util
|
||||||
|
|
||||||
class Plugin:
|
class Plugin:
|
||||||
def __init__(self, name, module):
|
def __init__(self, name, module):
|
||||||
|
self.__dict__ = module.__dict__
|
||||||
self.name = name
|
self.name = name
|
||||||
self.module = module
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def internal(name):
|
def internal(name):
|
||||||
|
|
|
@ -17,7 +17,7 @@ from ..source import Raw
|
||||||
|
|
||||||
plugin_type = "name"
|
plugin_type = "name"
|
||||||
|
|
||||||
def name(name, source):
|
def get_name(name, source):
|
||||||
if isinstance(source, File):
|
if isinstance(source, File):
|
||||||
if source.path.is_dir():
|
if source.path.is_dir():
|
||||||
return name
|
return name
|
||||||
|
|
|
@ -38,7 +38,7 @@ def init():
|
||||||
elif config.base > 62:
|
elif config.base > 62:
|
||||||
logger.fatal("Error: 'base' cannot be greater than 62")
|
logger.fatal("Error: 'base' cannot be greater than 62")
|
||||||
|
|
||||||
def name(name, source):
|
def get_name(name, source):
|
||||||
return name + _rebase(config.base, time.time_ns())
|
return name + _rebase(config.base, time.time_ns())
|
||||||
|
|
||||||
def _rebase(base, number):
|
def _rebase(base, number):
|
||||||
|
|
|
@ -27,7 +27,7 @@ args = {
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
def source():
|
def get_source():
|
||||||
file = File(config.file)
|
file = File(config.file)
|
||||||
if file.path.is_dir():
|
if file.path.is_dir():
|
||||||
logger.info(f"Uploading directory '{config.file}'")
|
logger.info(f"Uploading directory '{config.file}'")
|
||||||
|
|
Loading…
Reference in a new issue