Skip to content

Commit 5a30fdf

Browse files
authored
Merge pull request #446 from biothings/codacy-fixes
fix: refactor code for codacy
2 parents c3e40d9 + 8460eb4 commit 5a30fdf

13 files changed

Lines changed: 80 additions & 105 deletions

File tree

biothings/cli/commands/dataplugin.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ def listing(
137137

138138

139139
@dataplugin_application.command(name="inspect")
140-
def inspect_source(
140+
def inspect_source( # pylint: disable=too-many-arguments,too-many-positional-arguments
141141
plugin_name: Annotated[Optional[str], typer.Option("--name", "-n", help=PLUGIN_NAME_HELP)] = None,
142142
sub_source_name: Annotated[
143143
Optional[str], typer.Option("--sub-source-name", "-s", help="Your sub source name")

biothings/cli/commands/decorators.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,16 @@
1616

1717
from biothings.cli.exceptions import MissingPluginName
1818

19-
2019
logger = logging.getLogger(name="biothings-cli")
2120

2221

22+
def get_biothings_config():
23+
try:
24+
return sys.modules["biothings.config"]
25+
except KeyError as exc:
26+
raise RuntimeError("BioThings CLI configuration has not been loaded") from exc
27+
28+
2329
def operation_mode(operation: Callable):
2430
"""
2531
Based off the directory structure for where the biothings-cli
@@ -86,8 +92,7 @@ async def handle_corountine(*args, **kwargs):
8692

8793
if inspect.iscoroutinefunction(operation):
8894
return handle_corountine(*args, **kwargs)
89-
else:
90-
return handle_function(*args, **kwargs)
95+
return handle_function(*args, **kwargs)
9196

9297
return determine_operation_mode
9398

@@ -103,8 +108,7 @@ def cli_system_path(operation: Callable): # pylint: disable=unused-argument
103108
def update_system_path(*args, **kwargs):
104109

105110
def update_system_path_from_file():
106-
from biothings import config
107-
111+
config = get_biothings_config()
108112
discovery_path = pathlib.Path(config.BIOTHINGS_CLI_PATH).resolve().absolute()
109113
path_file = discovery_path.joinpath("biothings_cli.pth")
110114

@@ -130,7 +134,6 @@ async def handle_corountine(*args, **kwargs):
130134

131135
if inspect.iscoroutinefunction(operation):
132136
return handle_corountine(*args, **kwargs)
133-
else:
134-
return handle_function(*args, **kwargs)
137+
return handle_function(*args, **kwargs)
135138

136139
return update_system_path

biothings/cli/commands/operations.py

Lines changed: 25 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@
5656
import shutil
5757
import sys
5858
import uuid
59+
from importlib import import_module
5960
from typing import Optional, Union
6061

6162
import jsonschema
@@ -66,9 +67,9 @@
6667
from rich.console import Console
6768
from rich.panel import Panel
6869

69-
from biothings.cli.commands.decorators import cli_system_path, operation_mode
70-
from biothings.cli.structure import TEMPLATE_DIRECTORY
70+
from biothings.cli.commands.decorators import cli_system_path, get_biothings_config, operation_mode
7171
from biothings.cli.exceptions import UnknownUploaderSource
72+
from biothings.cli.structure import TEMPLATE_DIRECTORY
7273
from biothings.cli.utils import (
7374
clean_dumped_files,
7475
clean_uploaded_sources,
@@ -87,6 +88,10 @@
8788
logger = logging.getLogger(name="biothings-cli")
8889

8990

91+
def _load_attr(module_path: str, attr_name: str):
92+
return getattr(import_module(module_path), attr_name)
93+
94+
9095
# do not apply operation_mode decorator since this operation means to create a new plugin
9196
# regardless what the current working directory has
9297
def do_create(plugin_name: str, multi_uploaders: bool = False, parallelizer: bool = False):
@@ -127,9 +132,9 @@ async def do_dump(plugin_name: Optional[str] = None, show_dumped: bool = True, m
127132
"""
128133
Perform dump for the given plugin
129134
"""
130-
from biothings import config
131-
from biothings.cli.assistant import CLIAssistant
132-
from biothings.utils import hub_db
135+
config = get_biothings_config()
136+
CLIAssistant = _load_attr("biothings.cli.assistant", "CLIAssistant")
137+
hub_db = import_module("biothings.utils.hub_db")
133138

134139
hub_db.setup(config)
135140
assistant_instance = CLIAssistant(plugin_name)
@@ -184,8 +189,7 @@ async def do_upload(plugin_name: Optional[str] = None, batch_limit: int = 10000,
184189
>>> self.commands["upload_all"] = self.managers["upload_manager"].upload_all
185190
>>> self.commands["update_source_meta"] = self.managers["upload_manager"].update_source_meta
186191
"""
187-
from biothings.cli.assistant import CLIAssistant
188-
192+
CLIAssistant = _load_attr("biothings.cli.assistant", "CLIAssistant")
189193
assistant_instance = CLIAssistant(plugin_name)
190194
uploader_classes = assistant_instance.get_uploader_class()
191195
for uploader_class in uploader_classes:
@@ -243,8 +247,7 @@ async def do_parallel_upload(
243247
244248
This is a modified version of the ParallelUploader `update_data` source call
245249
"""
246-
from biothings.cli.assistant import CLIAssistant
247-
250+
CLIAssistant = _load_attr("biothings.cli.assistant", "CLIAssistant")
248251
assistant_instance = CLIAssistant(plugin_name)
249252
uploader_classes = assistant_instance.get_uploader_class()
250253
for uploader_class in uploader_classes:
@@ -368,10 +371,10 @@ async def do_index(plugin_name: Optional[str] = None, sub_source_name: Optional[
368371
The default location is localhost:9200. If successful a couple frames detailing the build and
369372
index information will be displayed to the enduser
370373
"""
371-
from biothings import config
372-
from biothings.cli.assistant import CLIAssistant
373-
from biothings.hub.databuild.builder import BuilderException
374-
from biothings.utils.manager import JobManager
374+
config = get_biothings_config()
375+
CLIAssistant = _load_attr("biothings.cli.assistant", "CLIAssistant")
376+
BuilderException = _load_attr("biothings.hub.databuild.builder", "BuilderException")
377+
JobManager = _load_attr("biothings.utils.manager", "JobManager")
375378

376379
if platform.system() == "Windows":
377380
logger.warning("The `biothings-cli dataplugin index` command isn't supported on windows")
@@ -500,8 +503,7 @@ async def do_list(
500503
"""
501504
List the dumped files, uploaded sources, or hubdb content.
502505
"""
503-
from biothings.cli.assistant import CLIAssistant
504-
506+
CLIAssistant = _load_attr("biothings.cli.assistant", "CLIAssistant")
505507
assistant_instance = CLIAssistant(plugin_name)
506508
if dump:
507509
dumper_instance = assistant_instance.get_dumper_class()
@@ -524,7 +526,7 @@ async def do_list(
524526

525527
@cli_system_path
526528
@operation_mode
527-
async def do_inspect(
529+
async def do_inspect( # pylint: disable=too-many-arguments,too-many-positional-arguments
528530
plugin_name: Optional[str] = None,
529531
sub_source_name: Optional[str] = None,
530532
mode: str = "type,stats",
@@ -535,8 +537,7 @@ async def do_inspect(
535537
"""
536538
Perform inspection on a data plugin.
537539
"""
538-
from biothings.cli.assistant import CLIAssistant
539-
540+
CLIAssistant = _load_attr("biothings.cli.assistant", "CLIAssistant")
540541
assistant_instance = CLIAssistant(plugin_name)
541542
uploader_classes = assistant_instance.get_uploader_class()
542543

@@ -593,9 +594,9 @@ async def do_serve(plugin_name: Optional[str] = None, host: str = "localhost", p
593594
"""
594595
Handles creation of a basic web server for hosting files using for a dataplugin
595596
"""
596-
from biothings.cli.assistant import CLIAssistant
597-
from biothings.cli.web_app import main
598-
from biothings.utils import hub_db
597+
CLIAssistant = _load_attr("biothings.cli.assistant", "CLIAssistant")
598+
main = _load_attr("biothings.cli.web_app", "main")
599+
hub_db = import_module("biothings.utils.hub_db")
599600

600601
assistant_instance = CLIAssistant(plugin_name)
601602
uploader_classes = assistant_instance.get_uploader_class()
@@ -614,8 +615,7 @@ async def do_clean(
614615
"""
615616
Clean the dumped files, uploaded sources, or both.
616617
"""
617-
from biothings.cli.assistant import CLIAssistant
618-
618+
CLIAssistant = _load_attr("biothings.cli.assistant", "CLIAssistant")
619619
if clean_all:
620620
dump = True
621621
upload = True
@@ -644,8 +644,7 @@ async def display_schema():
644644
Loads the jsonschema definition file and displays it to the
645645
console
646646
"""
647-
from biothings.hub.dataplugin.loaders.schema import load_manifest_schema
648-
647+
load_manifest_schema = _load_attr("biothings.hub.dataplugin.loaders.schema", "load_manifest_schema")
649648
manifest_schema = load_manifest_schema()
650649
schema_validator = jsonschema.validators.validator_for(manifest_schema)
651650
valid_schema = False
@@ -677,8 +676,7 @@ async def validate_manifest(plugin_name: Optional[str] = None):
677676
Loads the manifest file and validates it against the schema file
678677
If an error exists it will display the error to the enduser
679678
"""
680-
from biothings.hub.dataplugin.loaders.loader import ManifestBasedPluginLoader
681-
679+
ManifestBasedPluginLoader = _load_attr("biothings.hub.dataplugin.loaders.loader", "ManifestBasedPluginLoader")
682680
if plugin_name is None:
683681
plugin_directory = pathlib.Path.cwd().resolve().absolute()
684682
plugin_name = plugin_directory.name

biothings/cli/commands/pathing.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,7 @@
1010
from rich.console import Console
1111
from rich.table import Table
1212

13-
from biothings.cli.commands.decorators import cli_system_path, operation_mode
14-
13+
from biothings.cli.commands.decorators import cli_system_path, get_biothings_config, operation_mode
1514

1615
SHORT_HELP = (
1716
"[green]CLI tool for viewing the python system path and adding external directories to the system path[/green]"
@@ -96,8 +95,7 @@ def display_system_paths() -> None:
9695
@cli_system_path
9796
@operation_mode
9897
def update_system_paths() -> None:
99-
from biothings import config
100-
98+
config = get_biothings_config()
10199
discovery_path = pathlib.Path(config.BIOTHINGS_CLI_PATH).resolve().absolute()
102100
discovery_path.mkdir(parents=True, exist_ok=True)
103101

@@ -116,8 +114,7 @@ def update_system_paths() -> None:
116114
@cli_system_path
117115
@operation_mode
118116
def remove_system_paths() -> None:
119-
from biothings import config
120-
117+
config = get_biothings_config()
121118
discovery_path = pathlib.Path(config.BIOTHINGS_CLI_PATH).resolve().absolute()
122119
path_file = discovery_path.joinpath("biothings_cli.pth")
123120
path_file.unlink(missing_ok=True)

biothings/hub/dataindex/mongo_build_cleanup.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
1+
from datetime import datetime
12
from functools import partial
23

4+
from config import logger as logging
5+
36
from biothings import config as btconfig
47
from biothings.hub.manager import BaseManager
8+
from biothings.utils import mongo
59
from biothings.utils.hub_db import get_src_build
6-
from config import logger as logging
710

811

912
class MongoBuildCleaner:
@@ -19,8 +22,6 @@ def list_builds(self, build_config=None, build_name=None, year=None):
1922
if build_name:
2023
filters["_id"] = build_name
2124
if year:
22-
from datetime import datetime
23-
2425
year = int(year)
2526
filters["started_at"] = {
2627
"$gte": datetime(year, 1, 1),
@@ -51,8 +52,6 @@ async def delete_builds(self, build_ids):
5152
"target_collections_deleted": [],
5253
}
5354

54-
from biothings.utils import mongo
55-
5655
conn = mongo.get_hub_db_async_conn()
5756
try:
5857
src_build = mongo.get_src_build_async(conn)
@@ -99,8 +98,6 @@ async def validate_builds(self):
9998
10099
Returns a dict with ``builds_removed`` (count) and ``builds_removed_names``.
101100
"""
102-
from biothings.utils import mongo
103-
104101
logging.info("Starting validation of MongoDB builds...")
105102
conn = mongo.get_hub_db_async_conn()
106103
try:

0 commit comments

Comments
 (0)