Skip to content

Commit

Permalink
updating code again based on PR recommendations
Browse files Browse the repository at this point in the history
fixing linter issue

more changes based on PR
  • Loading branch information
travishathaway committed May 9, 2022
1 parent 7366643 commit d78f075
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 70 deletions.
33 changes: 13 additions & 20 deletions conda_build/cli/main_debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
# Consult LICENSE.txt or http://opensource.org/licenses/BSD-3-Clause.
import logging
import sys
from argparse import ArgumentParser, Namespace
from argparse import ArgumentParser

from conda_build import api
from conda_build.utils import on_win
Expand All @@ -31,6 +31,7 @@ def get_parser() -> ArgumentParser:
help=("Path to recipe directory or package file to use for dependency and source information. "
"If you use a recipe, you get the build/host env and source work directory. If you use "
"a package file, you get the test environments and the test_tmp folder."),
type=valid.validate_is_conda_pkg_or_recipe_dir
)
p.add_argument("-p", "--path",
help=("root path in which to place envs, source and activation script. Defaults to a "
Expand All @@ -49,18 +50,12 @@ def get_parser() -> ArgumentParser:
p._handle_conflict_resolve(None, [('--bootstrap', [_ for _ in p._actions if _.option_strings == ['--bootstrap']][0])])
p._handle_conflict_resolve(None, [('--old-build-string', [_ for _ in p._actions if
_.option_strings == ['--old-build-string']][0])])

return p


ARG_VALIDATORS = (
('recipe_or_package_file_path', valid.validate_is_conda_pkg_or_recipe_dir),
)


@valid.validate_args(ARG_VALIDATORS, get_parser())
def execute(args: Namespace):
test = True
def execute():
parser = get_parser()
args = parser.parse_args()

try:
activation_string = api.debug(
Expand All @@ -71,18 +66,16 @@ def execute(args: Namespace):

if not args.activate_string_only:
print("#" * 80)
if test:
print("Test environment created for debugging. To enter a debugging environment:\n")
else:
print("Build and/or host environments created for debugging. To enter a debugging environment:\n")
print(
"Build and/or host environments created for debugging. To enter a debugging environment:\n"
)

print(activation_string)
if not args.activate_string_only:
if test:
test_file = "conda_test_runner.bat" if on_win else "conda_test_runner.sh"
print(f"To run your tests, you might want to start with running the {test_file} file.")
else:
build_file = "conda_build.bat" if on_win else "conda_build.sh"
print(f"To run your build, you might want to start with running the {build_file} file.")
build_file = "conda_build.bat" if on_win else "conda_build.sh"
print(
f"To run your build, you might want to start with running the {build_file} file."
)
print("#" * 80)

except ValueError as e:
Expand Down
49 changes: 8 additions & 41 deletions conda_build/cli/validators.py
Original file line number Diff line number Diff line change
@@ -1,51 +1,19 @@
from __future__ import annotations

import os
import sys
from argparse import ArgumentParser, Namespace
from functools import wraps
from typing import Sequence, Callable, Tuple
from argparse import ArgumentError

from conda_build.utils import CONDA_PACKAGE_EXTENSIONS
from conda_build import utils

ParserFunction = Callable[..., Tuple[ArgumentParser, Namespace]]
ValidatorFunction = Callable[[str, Namespace], str]
CONDA_PKG_OR_RECIPE_ERROR_MESSAGE = (
"\nUnable to parse provided recipe directory or package file.\n\n"
f"Please make sure this argument is either a valid package \n"
f'file ({" or ".join(CONDA_PACKAGE_EXTENSIONS)}) or points to a directory containing recipe.'
)


def validate_args(
validators: Sequence[tuple[str, ValidatorFunction]],
parser: ArgumentParser,
):
"""
Runs a set of validation rules for a command. We assume that the first positional
argument is and
"""
def outer_wrap(func):
@wraps(func)
def wrapper(*args, **kwargs):
parsed_args = parser.parse_args()

for arg, validator in validators:
parsed_value = getattr(parsed_args, arg)
setattr(parsed_args, arg, validator(parsed_value, parsed_args))

return func(parsed_args, *args, **kwargs)
return wrapper
return outer_wrap


def get_is_conda_pkg_or_recipe_error_message() -> str:
"""Return the error displayed on the `validate_is_conda_pkg_or_recipe_dir` validator"""
valid_ext_str = ' or '.join(CONDA_PACKAGE_EXTENSIONS)
return (
'Error: Unable to parse provided recipe directory or package file.\n\n'
f'Please make sure this argument is either a valid package \n'
f'file ({valid_ext_str}) or points to a directory containing recipe.'
)


def validate_is_conda_pkg_or_recipe_dir(arg_val: str, _: Namespace) -> str:
def validate_is_conda_pkg_or_recipe_dir(arg_val: str) -> str:
"""
Makes sure the argument is either a conda pkg file or a recipe directory.
"""
Expand All @@ -54,5 +22,4 @@ def validate_is_conda_pkg_or_recipe_dir(arg_val: str, _: Namespace) -> str:
elif utils.is_conda_pkg(arg_val):
return arg_val
else:
print(get_is_conda_pkg_or_recipe_error_message(), file=sys.stderr)
sys.exit(1)
raise ArgumentError(None, CONDA_PKG_OR_RECIPE_ERROR_MESSAGE)
11 changes: 6 additions & 5 deletions tests/cli/test_main_debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,21 @@
from conda_build.cli import main_debug as debug, validators as valid


@pytest.fixture(scope='session')
@pytest.fixture(scope='module')
def main_debug_help() -> str:
"""Read what the current help message should be and return it as a fixture"""
sys.argv = ['conda-debug']
parser = debug.get_parser()

with io.StringIO() as fp:
parser.print_usage(file=fp)
fp.seek(0)
return fp.read()
yield fp.read()

sys.argv = []

def test_main_debug_help_message(capsys: CaptureFixture, main_debug_help: str):
sys.argv = ['conda-debug']

def test_main_debug_help_message(capsys: CaptureFixture, main_debug_help: str):
with pytest.raises(SystemExit):
debug.main()

Expand All @@ -37,7 +38,7 @@ def test_main_debug_file_does_not_exist(capsys: CaptureFixture):
debug.main()

captured = capsys.readouterr()
assert valid.get_is_conda_pkg_or_recipe_error_message() in captured.err
assert valid.CONDA_PKG_OR_RECIPE_ERROR_MESSAGE in captured.err


def test_main_debug_happy_path(fs: FakeFilesystem, capsys: CaptureFixture):
Expand Down
7 changes: 3 additions & 4 deletions tests/cli/test_validators.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from argparse import Namespace
from argparse import ArgumentError
from typing import Union

import pytest
Expand Down Expand Up @@ -26,11 +26,10 @@ def test_validate_is_conda_pkg_or_recipe_dir(
fs.create_dir(file_or_folder)
else:
fs.create_file(file_or_folder)
name_space = Namespace() # intentionally left empty because our validator doesn't need it

try:
received = valid.validate_is_conda_pkg_or_recipe_dir(file_or_folder, name_space)
except SystemExit: # if we get this error, we know it's not valid
received = valid.validate_is_conda_pkg_or_recipe_dir(file_or_folder)
except (ArgumentError, SystemExit): # if we get these errors, we know it's not valid
received = False

assert received == expected

0 comments on commit d78f075

Please sign in to comment.