Skip to content

Commit

Permalink
refractor
Browse files Browse the repository at this point in the history
  • Loading branch information
bitranox committed Jul 15, 2020
1 parent 4e3856a commit 69f20a4
Show file tree
Hide file tree
Showing 10 changed files with 124 additions and 24 deletions.
5 changes: 3 additions & 2 deletions .docs/commandline_help.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
commandline tool to resolve RST File includes
Options:
--version Show the version and exit.
-h, --help Show this message and exit.
--version Show the version and exit.
--traceback / --no-traceback return traceback information on cli
-h, --help Show this message and exit.
Commands:
include include the include files, use "-" for stdin as SOURCE and "-"...
Expand Down
7 changes: 7 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ Changelog
- new MINOR version for added functionality in a backwards compatible manner
- new PATCH version for backwards compatible bug fixes

2.0.2
-----
2020-07-16: Patch release
- fix cli test
- enable traceback option on cli errors


2.0.1
-----
2020-07-05 : patch release
Expand Down
12 changes: 10 additions & 2 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -442,8 +442,9 @@ Usage from Commandline
commandline tool to resolve RST File includes
Options:
--version Show the version and exit.
-h, --help Show this message and exit.
--version Show the version and exit.
--traceback / --no-traceback return traceback information on cli
-h, --help Show this message and exit.
Commands:
include include the include files, use "-" for stdin as SOURCE and "-"...
Expand Down Expand Up @@ -488,6 +489,13 @@ Changelog
- new MINOR version for added functionality in a backwards compatible manner
- new PATCH version for backwards compatible bug fixes

2.0.2
-----
2020-07-16: Patch release
- fix cli test
- enable traceback option on cli errors


2.0.1
-----
2020-07-05 : patch release
Expand Down
2 changes: 1 addition & 1 deletion mypy.ini
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ warn_unused_configs = True
ignore_missing_imports = True
no_implicit_optional = True
no_strict_optional = True
warn-unused-ignores = False
show_error_context = True
4 changes: 2 additions & 2 deletions rst_include/__init__conf__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name = 'rst_include'
title = 'commandline tool to resolve RST File includes'
version = '2.0.1'
version = '2.0.2'
url = 'https://github.com/bitranox/rst_include'
author = 'Robert Nowotny'
author_email = '[email protected]'
Expand All @@ -14,7 +14,7 @@ def print_info() -> None:
commandline tool to resolve RST File includes
Version : 2.0.1
Version : 2.0.2
Url : https://github.com/bitranox/rst_include
Author : Robert Nowotny
Email : [email protected]""")
72 changes: 72 additions & 0 deletions rst_include/cli_exit_tools.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import sys
import traceback
from typing import TextIO


class _Config(object):
traceback: bool = False


config = _Config()


def get_system_exit_code(exc: BaseException) -> int:
"""
Return the exit code for linux or windows, based on the exception.
If, on windows, the winerror is set on the Exception, we return that winerror code.
>>> try:
... raise FileNotFoundError()
... except FileNotFoundError as exc:
... assert get_system_exit_code(exc) == 2
... setattr(exc, 'winerror', 42)
... assert get_system_exit_code(exc) == 42
"""

# from https://www.thegeekstuff.com/2010/10/linux-error-codes
# dict key sorted from most specific to unspecific
posix_exceptions = {FileNotFoundError: 2, PermissionError: 13, FileExistsError: 17, TypeError: 22,
ValueError: 22, RuntimeError: 1, BaseException: 1}
windows_exceptions = {FileNotFoundError: 2, PermissionError: 5, ValueError: 13, FileExistsError: 80, TypeError: 87,
RuntimeError: 1, BaseException: 1}

if hasattr(exc, 'winerror'):
try:
exit_code = int(exc.winerror) # type: ignore
return exit_code
except (AttributeError, TypeError):
pass

if 'posix' in sys.builtin_module_names:
exceptions = posix_exceptions
else:
exceptions = windows_exceptions

for exception in exceptions:
if isinstance(exc, exception):
return exceptions[exception]
return 1


def print_exception_message(trace_back: bool = config.traceback, stream: TextIO = sys.stderr) -> None:
"""
Prints the Exception Message to stderr
if trace_back is True, it also prints the traceback information
>>> try:
... raise FileNotFoundError('test')
... except Exception: # noqa
... print_exception_message(False)
... print_exception_message(True)
"""
exc_info = sys.exc_info()[1]
if exc_info is not None:
exc_info_type = type(exc_info).__name__
exc_info_msg = ''.join([exc_info_type, ': ', exc_info.args[0]])
if trace_back:
exc_info_msg = ''.join(['Traceback Information : \n', traceback.format_exc()]).rstrip('\n')
print(exc_info_msg, file=stream)
20 changes: 16 additions & 4 deletions rst_include/rst_include_cli.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# STDLIB
import sys
from typing import Optional

# EXT
import click

Expand All @@ -6,11 +10,13 @@

try:
from . import __init__conf__
from . import cli_exit_tools
from . import rst_include
except (ImportError, ModuleNotFoundError): # pragma: no cover
# imports for doctest
import __init__conf__ # type: ignore # pragma: no cover
import rst_include # type: ignore # pragma: no cover
import cli_exit_tools # type: ignore # pragma: no cover
import rst_include # type: ignore # pragma: no cover


def info() -> None:
Expand All @@ -26,8 +32,10 @@ def info() -> None:
@click.version_option(version=__init__conf__.version,
prog_name=__init__conf__.shell_command,
message='{} version %(version)s'.format(__init__conf__.shell_command))
def cli_main() -> None: # pragma: no cover
pass # pragma: no cover
@click.option('--traceback/--no-traceback', is_flag=True, type=bool, default=None, help='return traceback information on cli')
def cli_main(traceback: Optional[bool] = None) -> None:
if traceback is not None:
cli_exit_tools.config.traceback = traceback


@cli_main.command('info', context_settings=CLICK_CONTEXT_SETTINGS)
Expand Down Expand Up @@ -71,4 +79,8 @@ def cli_replace(source: str, target: str, str_pattern: str, str_replace: str, co

# entry point if main
if __name__ == '__main__':
cli_main()
try:
cli_main()
except Exception as exc:
cli_exit_tools.print_exception_message()
sys.exit(cli_exit_tools.get_system_exit_code(exc))
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def get_line_data(line: str) -> str:

setup_kwargs: Dict[str, Any] = dict()
setup_kwargs['name'] = 'rst_include'
setup_kwargs['version'] = '2.0.1'
setup_kwargs['version'] = '2.0.2'
setup_kwargs['url'] = 'https://github.com/bitranox/rst_include'
setup_kwargs['packages'] = find_packages()
setup_kwargs['package_data'] = {'rst_include': ['py.typed', '*.pyi', '__init__.pyi']}
Expand Down
1 change: 1 addition & 0 deletions tests/local_testscripts/lib_bash_functions.sh
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ function clean_caches() {
sudo find "${project_root_dir}" -name "build" -type d -exec rm -rf {} \; 2>/dev/null
sudo find "${project_root_dir}" -name "dist" -type d -exec rm -rf {} \; 2>/dev/null
sudo find "${project_root_dir}" -name "*.egg-info" -type d -exec rm -rf {} \; 2>/dev/null
sudo find "${project_root_dir}" -name "__pycache__" -type d -exec rm -rf {} \; 2>/dev/null
sudo rm -rf "$HOME/.eggs/*"
sudo rm -rf "$HOME/.mypy_cache"
}
Expand Down
23 changes: 11 additions & 12 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,18 @@

def call_cli_command(commandline_args: str = '', log: bool = True) -> bool:
command = ' '.join([sys.executable, str(path_cli_command), commandline_args])
result = subprocess.run(command, shell=True, capture_output=True)
if result.returncode == 0:
return True
else:
if log:
# You need to enable --log-cli-level=CRITICAL to see that output in pytest
logger.critical('\n'.join(['STDOUT for {}:'.format(command), result.stdout.decode()]))
logger.critical('\n'.join(['STDOUT for {}:'.format(command), result.stderr.decode()]))
try:
subprocess.run(command, shell=True, check=True)
except subprocess.CalledProcessError as exc:
return False
return True


def test_cli_commands():
assert not call_cli_command('--unknown_option', log=False)
assert call_cli_command('--version')
assert call_cli_command('-h')
assert call_cli_command('info')
# due to a bug in python 3.8.1 with setup.py test on travis we need to cancel the click tests there !
if sys.version_info < (3, 8, 1) or sys.version_info >= (3, 8, 2):
assert not call_cli_command('--unknown_option')
assert call_cli_command('--version')
assert call_cli_command('-h')
assert call_cli_command('info')
assert call_cli_command('--traceback info')

0 comments on commit 69f20a4

Please sign in to comment.