Skip to content

Commit

Permalink
Merge pull request #23 from bbglab/dev/21-add-env-variable-for-plugins
Browse files Browse the repository at this point in the history
Add environment variable `OPENVAR_PLUGIN`
  • Loading branch information
FedericaBrando authored Mar 13, 2024
2 parents 20acac5 + 51689e5 commit 6b3796b
Show file tree
Hide file tree
Showing 6 changed files with 30 additions and 9 deletions.
6 changes: 3 additions & 3 deletions openvariant/annotation/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,9 +249,9 @@ def _plugin_builder(x: dict, base_path: str = None) -> PluginBuilder:
ctxt = _get_plugin_context(mod)
except ModuleNotFoundError:
try:
files = list(glob.iglob(f"{os.getcwd()}/**/{x[AnnotationTypes.PLUGIN.value]}", recursive=True))
files = list(glob.iglob(f"{os.environ['OPENVAR_PLUGIN']}/**/{x[AnnotationTypes.PLUGIN.value]}", recursive=True))
if len(files) == 0:
raise FileNotFoundError(f"Unable to find '{x[AnnotationTypes.PLUGIN.value]}' plugin in '{os.getcwd()}'")
raise FileNotFoundError(f"Unable to find '{x[AnnotationTypes.PLUGIN.value]}' plugin in '{os.environ['OPENVAR_PLUGIN']}'")
else:
try:
for package in files:
Expand All @@ -263,7 +263,7 @@ def _plugin_builder(x: dict, base_path: str = None) -> PluginBuilder:
func = _get_plugin_function(mod)
ctxt = _get_plugin_context(mod)
except (ImportError, AttributeError):
raise ImportError(f"Unable to import 'run' on the plugin.")
raise ImportError("Unable to import 'run' on the plugin.")
except ModuleNotFoundError:
raise ModuleNotFoundError(f"Unable to found '{x[AnnotationTypes.PLUGIN.value]}' plugin.")
except (ImportError, AttributeError) as e:
Expand Down
7 changes: 4 additions & 3 deletions openvariant/commands/openvar.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@
from openvariant.tasks.count import count as count_task
from openvariant.tasks.groupby import group_by as group_by_task
from openvariant.tasks.plugin import PluginActions
from openvariant.utils.utils import loadEnvironmentVariables


@click.group(context_settings={'help_option_names': ['-h', '--help']})
@click.version_option(openvariant.__version__)
def openvar():
"""'openvar' is the command-line interface of OpenVariant.
Parsing and data transformation of multiple input formats."""
loadEnvironmentVariables()
pass


Expand Down Expand Up @@ -106,10 +108,9 @@ def groupby(input_path: str, script: str, where: str, group_by: str, cores: int,
@openvar.command(name="plugin", short_help='Actions to execute for a plugin: create.')
@click.argument('action', type=click.Choice(['create']))
@click.option('--name', '-n', type=click.STRING, help="Name of the plugin.")
@click.option('--directory', '-d', type=click.STRING, help="Directory to reach the plugin.")
def plugin(action, name: str or None, directory: str or None):
def plugin(action, name: str or None):
"""Actions to apply on the plugin system."""
PluginActions[action.upper()].value(name, directory)
PluginActions[action.upper()].value(name)


if __name__ == "__main__":
Expand Down
4 changes: 2 additions & 2 deletions openvariant/tasks/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from functools import partial


def _add_action(name: str, directory: str = None) -> None:
def _add_action(name: str) -> None:
"""Create a new plugin
It will generate all the required structure for a new plugin (files and folders).
Expand All @@ -20,7 +20,7 @@ def _add_action(name: str, directory: str = None) -> None:
directory : str
The path to create the plugin.
"""
path = directory if directory is not None else os.getcwd()
path = os.environ['OPENVAR_PLUGIN']
if os.path.exists(f"{path}/{name}"):
raise FileExistsError(f"Directory {path}/{name} already exists.")
os.mkdir(f"{path}/{name}")
Expand Down
17 changes: 17 additions & 0 deletions openvariant/utils/utils.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,25 @@
import re
import os
from appdirs import user_data_dir
from fnmatch import fnmatch
from os.path import basename


ENV_VAR = {
'OPENVAR_PLUGIN': user_data_dir('openvariant', 'bbglab')
}

def loadEnvironmentVariables() -> None:
"""Load environment variable into the environment."""

missing_vars = set(ENV_VAR.keys()).difference(set(os.environ))

for env_var in missing_vars:
os.environ[env_var] = ENV_VAR[env_var]
os.makedirs(ENV_VAR[env_var], exist_ok=True)

return

def check_extension(ext: str, path: str) -> bool:
"""Check if file matches with the annotation pattern"""
return fnmatch(basename(path), ext) if ext[0] == '*' else re.match(ext, basename(path)) is not None
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
keywords='bioinformatics,openvariant,openvar,bbglab',
packages=find_packages(exclude=["tests.*", "tests"]),
include_package_data=True,
install_requires=['pyyaml', 'tqdm', 'click', 'pyliftover'],
install_requires=['pyyaml', 'tqdm', 'click', 'pyliftover', 'appdirs'],
entry_points={
'console_scripts': [
'openvar = openvariant.commands.openvar:openvar',
Expand Down
3 changes: 3 additions & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from openvariant.utils.utils import loadEnvironmentVariables

loadEnvironmentVariables()

0 comments on commit 6b3796b

Please sign in to comment.