Skip to content

Commit

Permalink
Allow running the yacfg scripts directly; use absolute imports, add s…
Browse files Browse the repository at this point in the history
…hebang, and fixup `sys.path` if needed (#308)

* Allow running the yacfg scripts directly; use absolute imports, add shebang, and fixup `sys.path` if needed

Shebang has been added at the beginning of yacfg_batch_cli.py and yacfg_cli.py to allow script execution. The import statements have been updated to avoid 'ImportError'. Unnecessary sys.path entries are removed to guard against import misdirection. Also, a script entry point check has been added at the end of yacfg_cli.py.
  • Loading branch information
jiridanek authored Apr 10, 2024
1 parent bb004ac commit 2e6f50f
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 20 deletions.
6 changes: 4 additions & 2 deletions src/yacfg/cli/cli_arguments.py
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
#! /usr/bin/env -S python3 -sP

from __future__ import annotations

import argparse
import json
import re
from typing import Dict, List, Tuple, Union

from .. import DESCRIPTION, NAME, __version__
from yacfg import DESCRIPTION, NAME, __version__

REX_BOOL_TRUE = re.compile(r"^(true|yes|1|on)$", re.IGNORECASE)
REX_BOOL_FALSE = re.compile(r"^(false|no|0|off)$", re.IGNORECASE)
Expand Down Expand Up @@ -210,5 +212,5 @@ def parse_key_value_list(items: list[str]) -> dict[str, str]:
"--version", help="Display version information", action="store_true"
)

if __name__ == '__main__':
if __name__ == "__main__":
args = parser.parse_args()
18 changes: 12 additions & 6 deletions src/yacfg/cli/yacfg_cli.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
#! /usr/bin/env -S python3 -sP

import logging
import os
import sys

from .. import NAME, __version__, logger_settings
from yacfg import NAME, __version__, logger_settings
from yacfg.cli.cli_arguments import boolize, parse_key_value_list, parser
from ..config_data import RenderOptions
from ..exceptions import GenerationError, ProfileError, TemplateError
from ..output import (
from yacfg.config_data import RenderOptions
from yacfg.exceptions import GenerationError, ProfileError, TemplateError
from yacfg.output import (
export_tuning_variables,
new_profile,
new_profile_rendered,
new_template,
)
from ..query import list_profiles, list_templates
from ..yacfg import generate
from yacfg.query import list_profiles, list_templates
from yacfg.yacfg import generate

logger_settings.config_console_logger()

Expand Down Expand Up @@ -148,3 +150,7 @@ def error(msg: str, ecode: int = 2) -> None:
def main():
app = CommandLineApp()
app.run()


if __name__ == "__main__":
main()
17 changes: 9 additions & 8 deletions src/yacfg/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,13 +108,17 @@ def select_profile_file(profile_name: str) -> Tuple[str, str]:
# User-defined profile in the ./profiles/ directory
LOG.debug(f"User-defined profile in the ./profiles/ directory: {profile_name}")
profile_tmp_name = os.path.abspath(user_extra_path)
selected_profile_name, selected_profile_path = os.path.basename(profile_tmp_name), os.path.dirname(profile_tmp_name)
selected_profile_name, selected_profile_path = os.path.basename(
profile_tmp_name
), os.path.dirname(profile_tmp_name)

if os.path.isfile(profile_name):
# User directly specified the profile file
LOG.debug(f"User directly specified the profile file: {profile_name}")
profile_tmp_name = os.path.abspath(profile_name)
selected_profile_name, selected_profile_path = os.path.basename(profile_tmp_name), os.path.dirname(profile_tmp_name)
selected_profile_name, selected_profile_path = os.path.basename(
profile_tmp_name
), os.path.dirname(profile_tmp_name)

profiles_paths = get_profiles_paths()
LOG.debug(f"Profiles paths: {profiles_paths}")
Expand Down Expand Up @@ -150,17 +154,15 @@ def select_template_dir(template_name: str) -> str:

if os.path.isdir(user_extra_path):
selected_template_path = user_extra_path
LOG.debug(f'Using user defined template path {template_name}')
LOG.debug(f"Using user defined template path {template_name}")

# user direct path
if os.path.isdir(template_name):
selected_template_path = template_name
LOG.debug(f'Using user defined template path {template_name}')
LOG.debug(f"Using user defined template path {template_name}")

if not os.path.isdir(selected_template_path):
raise TemplateError(
f'Unable to load requested template set "{template_name}"'
)
raise TemplateError(f'Unable to load requested template set "{template_name}"')

if not os.path.isfile(os.path.join(selected_template_path, "_template")):
raise TemplateError(
Expand All @@ -172,7 +174,6 @@ def select_template_dir(template_name: str) -> str:
return selected_template_path



def ensure_output_path(output_path: str) -> None:
"""
Ensure that the output path is an existing directory
Expand Down
2 changes: 1 addition & 1 deletion src/yacfg/yacfg.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ def generate_outputs(
generate_exception: Optional[GenerationError] = None

# TODO: volkswagen mode on
if 'PYTEST_CURRENT_TEST' not in os.environ:
if "PYTEST_CURRENT_TEST" not in os.environ:
if output_path and not os.path.exists(output_path):
raise GenerationError(f"Output path '{output_path}' does not exist.")

Expand Down
17 changes: 14 additions & 3 deletions src/yacfg_batch/yacfg_batch_cli.py
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,13 +1,24 @@
#! /usr/bin/env -S python3 -sP

from __future__ import print_function

import logging
import pathlib
import sys

# `from yacfg_batch import ...` may target both src/yacfg/yacfg_batch/__init__.py
# and src/yacfg/yacfg_batch/yacfg_batch.py (which is on sys.path when running
# this file directly). Remove the undesirable sys.path entry to prevent `ImportError`s.
try:
sys.path.remove(str(pathlib.Path(__file__).resolve().parent))
except ValueError:
pass

from yacfg import NAME, logger_settings

from . import __version__
from .cli_arguments import parser
from .yacfg_batch import generate
from yacfg_batch import __version__
from yacfg_batch.cli_arguments import parser
from yacfg_batch.yacfg_batch import generate

logger_settings.config_console_logger()

Expand Down

0 comments on commit 2e6f50f

Please sign in to comment.