Skip to content

Commit

Permalink
Merge pull request #3 from epam/develop
Browse files Browse the repository at this point in the history
Release 2.0.5 (3.112)
  • Loading branch information
oleksandr-onsha authored Jun 17, 2024
2 parents b6469bb + 27a1015 commit 5a063f0
Show file tree
Hide file tree
Showing 17 changed files with 320 additions and 394 deletions.
20 changes: 19 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,24 @@
CHANGELOG
=========

# [2.0.5] - 2024-04-19
* Enhance readability by using the `modular setup` command if an invalid link is
provided by the user.

# [2.0.4] - 2024-03-05
* hide error logs when executing cli commands on MacOS

# [2.0.3] - 2024-02-07
* Update the `README.md` file:
* Add the `Open Source Code` link
* Change the `Support` email

# [2.0.2] - 2024-02-07
* Update python version in the `README.md` file

# [2.0.1] - 2023-10-30
* Implemented proper bool type command option processing

# [2.0.0] - 2023-09-25
* Update libraries to support Python 3.10:
* `prettytable` from 3.2.0 to 3.9.0
Expand Down Expand Up @@ -126,4 +144,4 @@ information in logs [SFTGMSTR-5931]
# [1.0.0] - 2022-04-15
* Fix an error associated with command freeze in case to `setup` command
passed invalid link
* Added logging to the tool
* Added logging to the tool
11 changes: 5 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ via HTTP requests.
<a name="install"></a>
## 2. Installation

The installation of Modular-CLI assumed that you have Python3.9 and pip installed.
The installation of Modular-CLI assumed that you have Python3.10 and pip installed.
Use the following links to install the tools in case they are not installed.</br>

[Python download page](https://www.python.org/downloads/)
Expand Down Expand Up @@ -161,8 +161,7 @@ To deactivate:
<a name="project_info"></a>
## 6. Project information

**Source Code**: https://git.epam.com/epmc-eoos/m3-modular-cli
**Documentation**: https://git.epam.com/epmc-eoos/m3-modular-cli/-/blob/develop/README.md
**Changelog**: https://git.epam.com/epmc-eoos/m3-modular-cli/-/blob/develop/CHANGELOG.md
**Supported Python Version**: 3.9
**Support**: [email protected]`
**Open Source Code**: https://github.com/epam/modular-cli
**Documentation**: https://github.com/epam/modular-cli/blob/develop/README.md
**Changelog**: https://github.com/epam/modular-cli/blob/develop/CHANGELOG.md
**Supported Python Version**: 3.10
22 changes: 12 additions & 10 deletions modular_cli/modular_cli.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
from json import JSONDecodeError

from http import HTTPStatus
import click

from modular_cli.service.decorators import dynamic_dispatcher, CommandResponse, \
ResponseDecorator
from modular_cli.service.help_client import retrieve_commands_meta_content, \
HelpProcessor, LoginCommandHandler
from modular_cli.service.decorators import (
dynamic_dispatcher, CommandResponse, ResponseDecorator,
)
from modular_cli.service.help_client import (
retrieve_commands_meta_content, HelpProcessor, LoginCommandHandler,
)
from modular_cli.service.initializer import init_configuration
from modular_cli.service.request_processor import prepare_request
from modular_cli.service.utils import find_token_meta
from modular_cli.utils.exceptions import ModularCliInternalException
from modular_cli.utils.variables import RESPONSE_NO_CONTENT, NO_CONTENT_RESPONSE_MESSAGE
from modular_cli.utils.variables import NO_CONTENT_RESPONSE_MESSAGE

CONTEXT_SETTINGS = dict(allow_extra_args=True,
ignore_unknown_options=True)
Expand Down Expand Up @@ -62,7 +64,7 @@ def modular_cli(help, command=None, parameters=None, view_type=None):
resource=resource, parameters=parameters,
method=method, params_to_log=params_to_log)
# ===========================================================================
if response.status_code == RESPONSE_NO_CONTENT:
if response.status_code == HTTPStatus.NO_CONTENT.value:
return CommandResponse(message=NO_CONTENT_RESPONSE_MESSAGE)
try:
response_body = response.json()
Expand All @@ -82,7 +84,7 @@ def __is_help_required(token_meta, specified_parameters, help_flag):
return help_flag
if not token_meta.get('route'):
return True
required_parameters = [param
for param in token_meta.get('parameters')
if param.get('required')]
required_parameters = [
param for param in token_meta.get('parameters') if param.get('required')
]
return required_parameters and not specified_parameters
2 changes: 1 addition & 1 deletion modular_cli/modular_cli_autocomplete/complete_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
PROFILE_BASH_COMPLETE_SCRIPT, COMPLETE_PROCESS_FILE
from modular_cli.utils.logger import get_logger

_LOG = get_logger('complete_handler')
_LOG = get_logger(__name__)
PYTHON_SYMLINK = 'PYTHON_SYMLINK'
SCRIPT_PATH = 'SCRIPT_PATH'
HELP_FILE = 'HELP_FILE'
Expand Down
44 changes: 13 additions & 31 deletions modular_cli/service/adapter_client.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import os

import requests

from modular_cli.service.config import ConfigurationProvider
from modular_cli.utils.logger import get_logger, get_user_logger
from modular_cli.utils.exceptions import ModularCliConfigurationException, \
ModularCliTimeoutException
from modular_cli.utils.exceptions import (
ModularCliConfigurationException, ModularCliTimeoutException,
)
from modular_cli.utils.logger import get_logger
from modular_cli.version import __version__

SYSTEM_LOG = get_logger('service.adapter_client')
USER_LOG = get_user_logger('user')
SYSTEM_LOG = get_logger(__name__)

CONF = ConfigurationProvider()

Expand All @@ -17,8 +16,6 @@
HTTP_PATCH = 'PATCH'
HTTP_DELETE = 'DELETE'

ALLOWED_METHODS = [HTTP_GET, HTTP_POST, HTTP_PATCH, HTTP_DELETE]


class AdapterClient:

Expand All @@ -35,26 +32,10 @@ def __init__(self, adapter_api, username, secret, token):
}
SYSTEM_LOG.info('Adapter SDK has been initialized')

@staticmethod
def get_tool_version():
from pathlib import Path

version = {}
ver_path = os.path.join(Path(__file__).parent.parent.parent, "version.py")

with open(ver_path) as fp:
exec(fp.read(), version)

return version['__version__']

def __make_request(self, resource: str, method: str, payload: dict = None,
params_to_log: dict = None) -> requests.Response:
if method not in ALLOWED_METHODS:
SYSTEM_LOG.error(f'Requested method {method} in not allowed. '
f'Allowed methods: {ALLOWED_METHODS}')
USER_LOG.error('Sorry, error happened. '
'Please contact the tool support team.')
method_func = self.__method_to_function.get(method)
assert method in self.__method_to_function # todo allow all methods
method_func = self.__method_to_function[method]
parameters = dict(url=f'{self.__api_link}{resource}')
if method == HTTP_GET:
parameters.update(params=payload)
Expand All @@ -65,15 +46,16 @@ def __make_request(self, resource: str, method: str, payload: dict = None,
f'Parameters: {params_to_log if params_to_log else {}}; '
f'Method: {method}.')
if self.__token and resource != '/login':
parameters.update(headers=
{'authorization': f'Bearer {self.__token}'})
parameters.update(
headers={'authorization': f'Bearer {self.__token}'}
)
else:
parameters.update(auth=(self.__username, self.__secret))

if parameters.get('headers'):
parameters['headers'].update({'Cli-Version': self.get_tool_version()})
parameters['headers'].update({'Cli-Version': __version__})
else:
parameters['headers'] = {'Cli-Version': self.get_tool_version()}
parameters['headers'] = {'Cli-Version': __version__}

try:
response = method_func(**parameters)
Expand Down
46 changes: 26 additions & 20 deletions modular_cli/service/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,34 +6,30 @@
import yaml

from modular_cli import ENTRY_POINT
from modular_cli.utils.exceptions import ModularCliConfigurationException, \
ModularCliBadRequestException
from modular_cli.utils.logger import get_logger, get_user_logger
from modular_cli.utils.variables import (TOOL_FOLDER_NAME, TOOL_CONFIGURATION_FOLDER,
CREDENTIALS_FILE_NAME,
TEMPORARY_CREDS_FILENAME,
COMMANDS_META, DEFAULT_CONNECTION_TIMEOUT)
from modular_cli.utils.exceptions import (
ModularCliConfigurationException, ModularCliBadRequestException,
)
from modular_cli.utils.logger import get_logger
from modular_cli.utils.variables import (
TOOL_FOLDER_NAME, TOOL_CONFIGURATION_FOLDER, CREDENTIALS_FILE_NAME,
TEMPORARY_CREDS_FILENAME, COMMANDS_META, DEFAULT_CONNECTION_TIMEOUT,
)

SYSTEM_LOG = get_logger(__name__)
USER_LOG = get_user_logger('user')


def save_configuration(api_link: str, username: str, password: str):
valid_link = __api_link_validation(link=api_link)
if not valid_link:
raise ModularCliBadRequestException(f'Invalid API link: {api_link}')
def save_configuration(api_link: str, username: str, password: str) -> str:
if api_link.endswith('/'):
api_link = api_link[:-1]
valid_link = __api_link_validation(link=api_link)
folder_path = get_credentials_folder()
try:
folder_path.mkdir(exist_ok=True)
except OSError:
SYSTEM_LOG.exception(f'Creation of the directory {folder_path} failed')
USER_LOG.info(f'Unable to create configuration folder {folder_path}')
return 'Error occurred while configurating tool. Please contact ' \
'support team for assistance.'
return f'Could not create configuration folder {folder_path}'

config_data = dict(api_link=api_link,
config_data = dict(api_link=valid_link,
username=username,
password=password)
with open(folder_path / CREDENTIALS_FILE_NAME, 'w') as config_file:
Expand All @@ -54,14 +50,24 @@ def get_credentials_folder() -> Path:
return (Path.home() / TOOL_CONFIGURATION_FOLDER).resolve()


def __api_link_validation(link):
def __api_link_validation(link: str) -> str:
try:
requests.get(link, timeout=DEFAULT_CONNECTION_TIMEOUT)
resp = requests.get(
link + '/health_check',
timeout=DEFAULT_CONNECTION_TIMEOUT,
)
if resp.status_code != 200:
raise ModularCliBadRequestException(
f'API link failed: {link}. '
f'Health check was not successful.'
)
except (requests.exceptions.RequestException,
requests.exceptions.MissingSchema, requests.exceptions.InvalidURL,
requests.exceptions.ConnectionError,
requests.exceptions.InvalidSchema):
return
requests.exceptions.InvalidSchema) as e:
raise ModularCliBadRequestException(
f'API link error: {link}. An exception occurred during the request.'
) from e
return link


Expand Down
Loading

0 comments on commit 5a063f0

Please sign in to comment.