Skip to content

Commit

Permalink
Maybe exit?
Browse files Browse the repository at this point in the history
  • Loading branch information
tzarc committed Jun 13, 2024
1 parent e69d30a commit 5025dc4
Show file tree
Hide file tree
Showing 6 changed files with 31 additions and 12 deletions.
12 changes: 6 additions & 6 deletions lib/python/qmk/cli/generate/autocorrect_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
For full documentation, see QMK Docs
"""

import sys
import textwrap
from typing import Any, Dict, Iterator, List, Tuple

Expand All @@ -38,6 +37,7 @@
from qmk.keyboard import keyboard_completer, keyboard_folder
from qmk.keymap import keymap_completer, locate_keymap
from qmk.path import normpath
from qmk.util import maybe_exit

KC_A = 4
KC_SPC = 0x2c
Expand Down Expand Up @@ -88,16 +88,16 @@ def parse_file(file_name: str) -> List[Tuple[str, str]]:
# Check that `typo` is valid.
if not (all([c in TYPO_CHARS for c in typo])):
cli.log.error('{fg_red}Error:%d:{fg_reset} Typo "{fg_cyan}%s{fg_reset}" has characters other than a-z, \' and :.', line_number, typo)
sys.exit(1)
maybe_exit(1)
for other_typo in typos:
if typo in other_typo or other_typo in typo:
cli.log.error('{fg_red}Error:%d:{fg_reset} Typos may not be substrings of one another, otherwise the longer typo would never trigger: "{fg_cyan}%s{fg_reset}" vs. "{fg_cyan}%s{fg_reset}".', line_number, typo, other_typo)
sys.exit(1)
maybe_exit(1)
if len(typo) < 5:
cli.log.warning('{fg_yellow}Warning:%d:{fg_reset} It is suggested that typos are at least 5 characters long to avoid false triggers: "{fg_cyan}%s{fg_reset}"', line_number, typo)
if len(typo) > 127:
cli.log.error('{fg_red}Error:%d:{fg_reset} Typo exceeds 127 chars: "{fg_cyan}%s{fg_reset}"', line_number, typo)
sys.exit(1)
maybe_exit(1)

check_typo_against_dictionary(typo, line_number, correct_words)

Expand Down Expand Up @@ -136,7 +136,7 @@ def parse_file_lines(file_name: str) -> Iterator[Tuple[int, str, str]]:
tokens = [token.strip() for token in line.split('->', 1)]
if len(tokens) != 2 or not tokens[0]:
print(f'Error:{line_number}: Invalid syntax: "{line}"')
sys.exit(1)
maybe_exit(1)

typo, correction = tokens
typo = typo.lower() # Force typos to lowercase.
Expand Down Expand Up @@ -237,7 +237,7 @@ def encode_link(link: Dict[str, Any]) -> List[int]:
byte_offset = link['byte_offset']
if not (0 <= byte_offset <= 0xffff):
cli.log.error('{fg_red}Error:{fg_reset} The autocorrection table is too large, a node link exceeds 64KB limit. Try reducing the autocorrection dict to fewer entries.')
sys.exit(1)
maybe_exit(1)
return [byte_offset & 255, byte_offset >> 8]


Expand Down
5 changes: 3 additions & 2 deletions lib/python/qmk/cli/via2json.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from qmk.json_encoders import KeymapJSONEncoder
from qmk.commands import parse_configurator_json, dump_lines
from qmk.keymap import generate_json, list_keymaps, locate_keymap, parse_keymap_c
from qmk.util import maybe_exit


def _find_via_layout_macro(keyboard):
Expand Down Expand Up @@ -69,7 +70,7 @@ def _via_to_keymap(via_backup, keyboard_data, keymap_layout):
layout_data = keyboard_data['layouts'].get(keymap_layout)
if not layout_data:
cli.log.error(f'LAYOUT macro {keymap_layout} is not a valid one for keyboard {cli.args.keyboard}!')
exit(1)
maybe_exit(1)

layout_data = layout_data['layout']
sorting_hat = list()
Expand Down Expand Up @@ -118,7 +119,7 @@ def via2json(cli):
keymap_layout = cli.args.layout if cli.args.layout else _find_via_layout_macro(cli.args.keyboard)
if not keymap_layout:
cli.log.error(f"Couldn't find LAYOUT macro for keyboard {cli.args.keyboard}. Please specify it with the '-l' argument.")
exit(1)
maybe_exit(1)

# Load the VIA backup json
with cli.args.filename.open('r') as fd:
Expand Down
3 changes: 2 additions & 1 deletion lib/python/qmk/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from qmk.constants import QMK_USERSPACE, HAS_QMK_USERSPACE
from qmk.json_schema import json_load, validate
from qmk.keyboard import keyboard_alias_definitions
from qmk.util import maybe_exit


def find_make():
Expand Down Expand Up @@ -52,7 +53,7 @@ def parse_configurator_json(configurator_file):

except jsonschema.ValidationError as e:
cli.log.error(f'Invalid JSON keymap: {configurator_file} : {e.message}')
exit(1)
maybe_exit(1)

keyboard = user_keymap['keyboard']
aliases = keyboard_alias_definitions()
Expand Down
3 changes: 2 additions & 1 deletion lib/python/qmk/info.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from qmk.commands import parse_configurator_json
from qmk.makefile import parse_rules_mk_file
from qmk.math import compute
from qmk.util import maybe_exit

true_values = ['1', 'on', 'yes']
false_values = ['0', 'off', 'no']
Expand Down Expand Up @@ -208,7 +209,7 @@ def _validate(keyboard, info_data):
except jsonschema.ValidationError as e:
json_path = '.'.join([str(p) for p in e.absolute_path])
cli.log.error('Invalid API data: %s: %s: %s', keyboard, json_path, e.message)
exit(1)
maybe_exit(1)


def info_json(keyboard):
Expand Down
6 changes: 4 additions & 2 deletions lib/python/qmk/json_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

from milc import cli

from qmk.util import maybe_exit


def _dict_raise_on_duplicates(ordered_pairs):
"""Reject duplicate keys."""
Expand Down Expand Up @@ -38,10 +40,10 @@ def _json_load_impl(json_file, strict=True):

except (json.decoder.JSONDecodeError, hjson.HjsonDecodeError) as e:
cli.log.error('Invalid JSON encountered attempting to load {fg_cyan}%s{fg_reset}:\n\t{fg_red}%s', json_file, e)
exit(1)
maybe_exit(1)
except Exception as e:
cli.log.error('Unknown error attempting to load {fg_cyan}%s{fg_reset}:\n\t{fg_red}%s', json_file, e)
exit(1)
maybe_exit(1)


def json_load(json_file, strict=True):
Expand Down
14 changes: 14 additions & 0 deletions lib/python/qmk/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,23 @@
"""
import contextlib
import multiprocessing
import sys

from milc import cli

maybe_exit_should_exit = True
maybe_exit_reraise = False


# Controls whether or not early `exit()` calls should be made
def maybe_exit(rc):
if maybe_exit_should_exit:
sys.exit(rc)
if maybe_exit_reraise:
e = sys.exception()
if e:
raise e


@contextlib.contextmanager
def parallelize():
Expand Down

0 comments on commit 5025dc4

Please sign in to comment.