Skip to content

Commit

Permalink
Survive without validators & improve errors
Browse files Browse the repository at this point in the history
Improve the errors that are shown if an import fails;
also handle the case where the validators module is missing.
Other parts of the code are necessary for full functionality,
but validators is, at least currently, just nice to have.

Signed-off-by: David Weinehall <[email protected]>
  • Loading branch information
taotriad committed Jul 25, 2023
1 parent 439a11e commit 81dd2a0
Show file tree
Hide file tree
Showing 14 changed files with 40 additions and 27 deletions.
4 changes: 2 additions & 2 deletions ansible_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
try:
import yaml
except ModuleNotFoundError:
sys.exit("ModuleNotFoundError: You probably need to install python3-yaml; did you forget to run cmt-install?")
sys.exit("ModuleNotFoundError: Could not import yaml; you may need to (re-)run `cmt-install` or `pip3 install PyYAML`; aborting.")

import cmtlib
from cmtio import check_path, join_securitystatus_set, secure_mkdir, secure_rm, secure_rmdir
Expand All @@ -39,7 +39,7 @@
try:
import ansible_runner # type: ignore
except ModuleNotFoundError:
sys.exit("ModuleNotFoundError: You probably need to install ansible_runner; did you forget to run cmt-install?")
sys.exit("ModuleNotFoundError: Could not import ansible_runner; you may need to (re-)run `cmt-install` or `pip3 install ansible-runner`; aborting.")

# Exit if the ansible directory does not exist
if not Path(ANSIBLE_DIR).exists():
Expand Down
4 changes: 2 additions & 2 deletions cmt
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,15 @@ from typing import Any, cast, Dict, List, Optional, Sequence, Tuple
try:
import yaml
except ModuleNotFoundError:
sys.exit("ModuleNotFoundError: You probably need to install python3-yaml; did you forget to run cmt-install?")
sys.exit("ModuleNotFoundError: Could not import yaml; you may need to (re-)run `cmt-install` or `pip3 install PyYAML`; aborting.")

from cryptography import x509
from cryptography.hazmat.primitives import serialization

try:
from natsort import natsorted
except ModuleNotFoundError:
sys.exit("ModuleNotFoundError: You probably need to install python3-natsort; did you forget to run cmt-install?")
sys.exit("ModuleNotFoundError: Could not import natsort; you may need to (re-)run `cmt-install` or `pip3 install natsort`; aborting.")

from cmttypes import deep_get, DictPath, FilePath, FilePathAuditError, HostNameStatus
from cmtpaths import CMT_CONFIG_FILE, CMT_CONFIG_FILENAME, DEFAULT_THEME_FILE, KUBE_CONFIG_FILE, VIEW_DIR
Expand Down
2 changes: 1 addition & 1 deletion cmtinv
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ from typing import cast, Dict, List, Optional, Tuple
try:
from natsort import natsorted
except ModuleNotFoundError:
sys.exit("ModuleNotFoundError: You probably need to install python3-natsort; did you forget to run cmt-install?")
sys.exit("ModuleNotFoundError: Could not import natsort; you may need to (re-)run `cmt-install` or `pip3 install natsort`; aborting.")

from cmttypes import deep_get, DictPath, FilePath, ProgrammingError, UnknownError
from cmtpaths import HOMEDIR, SSH_DIR
Expand Down
2 changes: 1 addition & 1 deletion cmtio_yaml.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
try:
import yaml
except ModuleNotFoundError:
sys.exit("ModuleNotFoundError: You probably need to install python3-yaml; did you forget to run cmt-install?")
sys.exit("ModuleNotFoundError: Could not import yaml; you may need to (re-)run `cmt-install` or `pip3 install PyYAML`; aborting.")

import cmtio
from cmttypes import FilePath, SecurityChecks
Expand Down
6 changes: 3 additions & 3 deletions cmtlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ def read_cmtconfig() -> Dict:
# pylint: disable-next=import-outside-toplevel
from natsort import natsorted
except ModuleNotFoundError:
sys.exit("ModuleNotFoundError: You probably need to install python3-natsort; did you forget to run cmt-install?")
sys.exit("ModuleNotFoundError: Could not import natsort; you may need to (re-)run `cmt-install` or `pip3 install natsort`; aborting.")

global cmtconfig # pylint: disable=global-statement

Expand Down Expand Up @@ -548,7 +548,7 @@ def check_deb_versions(deb_packages: List[str]) -> List[Tuple[str, str, str, Lis
# pylint: disable-next=import-outside-toplevel
from natsort import natsorted
except ModuleNotFoundError:
sys.exit("ModuleNotFoundError: You probably need to install python3-natsort; did you forget to run cmt-install?")
sys.exit("ModuleNotFoundError: Could not import natsort; you may need to (re-)run `cmt-install` or `pip3 install natsort`; aborting.")

deb_versions = []

Expand Down Expand Up @@ -614,7 +614,7 @@ def check_rpm_versions(rpm_packages: List[str]) -> List[Tuple[str, str, str, Lis
# pylint: disable-next=import-outside-toplevel
from natsort import natsorted
except ModuleNotFoundError:
sys.exit("ModuleNotFoundError: You probably need to install python3-natsort; did you forget to run cmt-install?")
sys.exit("ModuleNotFoundError: Could not import natsort; you may need to (re-)run `cmt-install` or `pip3 install natsort`; aborting.")

rpm_versions = []
rpm_versions_dict = {}
Expand Down
4 changes: 2 additions & 2 deletions cmu
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,12 @@ from typing import Any, Callable, cast, Dict, List, Optional, Sequence, Tuple, T
try:
import yaml
except ModuleNotFoundError:
sys.exit("ModuleNotFoundError: You probably need to install python3-yaml; did you forget to run cmt-install?")
sys.exit("ModuleNotFoundError: Could not import yaml; you may need to (re-)run `cmt-install` or `pip3 install PyYAML`; aborting.")

try:
from natsort import natsorted
except ModuleNotFoundError:
sys.exit("ModuleNotFoundError: You probably need to install python3-natsort; did you forget to run cmt-install?")
sys.exit("ModuleNotFoundError: Could not import natsort; you may need to (re-)run `cmt-install` or `pip3 install natsort`; aborting.")

from cmttypes import deep_get, deep_get_list, deep_get_with_fallback, deep_set, DictPath, FilePath, Retval, SecurityPolicy, StatusGroup
from cmtpaths import BINDIR, HOMEDIR, DEPLOYMENT_DIR, CMT_CONFIG_FILE_DIR, THEME_DIR, VIEW_DIR
Expand Down
19 changes: 14 additions & 5 deletions commandparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
try:
import validators # type: ignore
except ModuleNotFoundError:
print("ModuleNotFoundError: Could not import validators; you may need to (re-)run `cmt-install` or `pip3 install validators`; disabling IP-address validation.\n", file = sys.stderr)
validators = None

import about
Expand Down Expand Up @@ -158,8 +159,12 @@ def validate_argument(arg: str, arg_string: List[ANSIThemeString], options: Dict
valid = False
if "/" in subarg:
ip, netmask = subarg.split("/")
valid_ipv4_address = validators.ipv4(ip)
valid_ipv6_address = validators.ipv6(ip)
if validators is not None:
valid_ipv4_address = validators.ipv4(ip)
valid_ipv6_address = validators.ipv6(ip)
else:
valid_ipv4_address = True
valid_ipv6_address = True
try:
if valid_ipv4_address and 0 < int(netmask) <= 32:
valid = True
Expand All @@ -183,8 +188,12 @@ def validate_argument(arg: str, arg_string: List[ANSIThemeString], options: Dict
sys.exit(errno.EINVAL)
elif validator in ("hostname", "hostname_or_path", "hostname_or_ip", "ip"):
valid_dns_label = cmtlib.validate_name("dns-label", subarg)
valid_ipv4_address = validators.ipv4(subarg)
valid_ipv6_address = validators.ipv6(subarg)
if validators is not None:
valid_ipv4_address = validators.ipv4(subarg)
valid_ipv6_address = validators.ipv6(subarg)
else:
valid_ipv4_address = True
valid_ipv6_address = True

if validator in ("hostname", "hostname_or_path") and not valid_dns_label:
# If validation failed as subname we check if it's a valid path;
Expand Down Expand Up @@ -286,7 +295,7 @@ def validate_argument(arg: str, arg_string: List[ANSIThemeString], options: Dict
tmp_arg = f"https://{arg}"

# Workaround; it seems validators.url accepts usernames that start with "-"
if arg.startswith("-") or not validators.url(tmp_arg):
if arg.startswith("-") or validators is not None and not validators.url(tmp_arg):
ansithemeprint([ANSIThemeString(f"{programname}", "programname"),
ANSIThemeString(": “", "default"),
ANSIThemeString(f"{subarg}", "option"),
Expand Down
2 changes: 1 addition & 1 deletion curses_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
try:
from natsort import natsorted
except ModuleNotFoundError:
sys.exit("ModuleNotFoundError: You probably need to install python3-natsort; did you forget to run cmt-install?")
sys.exit("ModuleNotFoundError: Could not import natsort; you may need to (re-)run `cmt-install` or `pip3 install natsort`; aborting.")

from cmtio import check_path, join_securitystatus_set
from cmtio_yaml import secure_read_yaml
Expand Down
2 changes: 1 addition & 1 deletion formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
try:
import yaml
except ModuleNotFoundError:
sys.exit("ModuleNotFoundError: You probably need to install python3-yaml; did you forget to run cmt-install?")
sys.exit("ModuleNotFoundError: Could not import yaml; you may need to (re-)run `cmt-install` or `pip3 install PyYAML`; aborting.")

from cmttypes import deep_get, DictPath

Expand Down
2 changes: 1 addition & 1 deletion itemgetter.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
try:
from natsort import natsorted
except ModuleNotFoundError:
sys.exit("ModuleNotFoundError: You probably need to install python3-natsort; did you forget to run cmt-install?")
sys.exit("ModuleNotFoundError: Could not import natsort; you may need to (re-)run `cmt-install` or `pip3 install natsort`; aborting.")

from curses_helper import ThemeAttr, ThemeString, WidgetLineAttrs

Expand Down
4 changes: 2 additions & 2 deletions kubernetes_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,15 @@
try:
import yaml
except ModuleNotFoundError:
sys.exit("ModuleNotFoundError: You probably need to install python3-yaml; did you forget to run cmt-install?")
sys.exit("ModuleNotFoundError: Could not import yaml; you may need to (re-)run `cmt-install` or `pip3 install PyYAML`; aborting.")

from cryptography import x509
from cryptography.hazmat.primitives import serialization

try:
import urllib3
except ModuleNotFoundError:
sys.exit("ModuleNotFoundError: You probably need to install python3-urllib3; did you forget to run cmt-install?")
sys.exit("ModuleNotFoundError: Could not import urllib3; you may need to (re-)run `cmt-install` or `pip3 install urllib3`; aborting.")

from cmtpaths import KUBE_CONFIG_FILE, KUBE_CREDENTIALS_FILE
import cmtlib
Expand Down
12 changes: 8 additions & 4 deletions logparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,17 +46,18 @@
try:
import yaml
except ModuleNotFoundError:
sys.exit("ModuleNotFoundError: You probably need to install python3-yaml; did you forget to run cmt-install?")
sys.exit("ModuleNotFoundError: Could not import yaml; you may need to (re-)run `cmt-install` or `pip3 install PyYAML`; aborting.")

try:
from natsort import natsorted
except ModuleNotFoundError:
sys.exit("ModuleNotFoundError: You probably need to install python3-natsort; did you forget to run cmt-install?")
sys.exit("ModuleNotFoundError: Could not import natsort; you may need to (re-)run `cmt-install` or `pip3 install natsort`; aborting.")

try:
import validators # type: ignore
except ModuleNotFoundError:
sys.exit("ModuleNotFoundError: You probably need to install python3-validators; did you forget to run cmt-install?")
print("ModuleNotFoundError: Could not import validators; you may need to (re-)run `cmt-install` or `pip3 install validators`; disabling IP-address validation.\n", file = sys.stderr)
validators = None

from cmtpaths import HOMEDIR, PARSER_DIR

Expand Down Expand Up @@ -573,7 +574,10 @@ def http(message: str, severity: Optional[LogLevel] = LogLevel.INFO, facility: s
# Safe
tmp = re.match(r"^([a-f0-9:][a-f0-9:.]+[a-f0-9])( - - .*)", message)
if tmp is not None:
if validators.ipv4(tmp[1]) or validators.ipv6(tmp[1]):
# Just pass-through if validators isn't installed;
# this might lead to false positives, but it's better than
# not working at all
if validators is None or validators.ipv4(tmp[1]) or validators.ipv6(tmp[1]):
ipaddress = tmp[1]
message = tmp[2]

Expand Down
2 changes: 1 addition & 1 deletion networkio.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
try:
import urllib3
except ModuleNotFoundError:
sys.exit("ModuleNotFoundError: You probably need to install python3-urllib3; did you forget to run cmt-install?")
sys.exit("ModuleNotFoundError: Could not import urllib3; you may need to (re-)run `cmt-install` or `pip3 install urllib3`; aborting.")

def scan_and_add_ssh_keys(hosts: List[str]) -> None:
"""
Expand Down
2 changes: 1 addition & 1 deletion objgetter.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
try:
from natsort import natsorted
except ModuleNotFoundError:
sys.exit("ModuleNotFoundError: You probably need to install python3-natsort; did you forget to run cmt-install?")
sys.exit("ModuleNotFoundError: Could not import natsort; you may need to (re-)run `cmt-install` or `pip3 install natsort`; aborting.")

from cmttypes import deep_get, DictPath, FilePath, FilePathAuditError, SecurityChecks, SecurityStatus
from ansible_helper import ansible_run_playbook_on_selection, get_playbook_path
Expand Down

0 comments on commit 81dd2a0

Please sign in to comment.