add black

This commit is contained in:
Ben V. Brown
2021-04-05 19:15:02 +10:00
parent e463cf2fd2
commit d9100d1625
3 changed files with 54 additions and 26 deletions

View File

@@ -84,3 +84,6 @@ jobs:
- name: Check formatting with clang-format - name: Check formatting with clang-format
run: cd source && make clean && make check-style run: cd source && make clean && make check-style
- name: Check python formatting with black
run: black --check Translations

View File

@@ -65,11 +65,15 @@ def validate_langcode_matches_content(filename: str, content: dict) -> None:
# ...cause they should be the same! # ...cause they should be the same!
if lang_code != lang_code_from_json: if lang_code != lang_code_from_json:
raise ValueError(f"Invalid languageCode {lang_code_from_json} in file {filename}") raise ValueError(
f"Invalid languageCode {lang_code_from_json} in file {filename}"
)
def write_start(f: TextIO): def write_start(f: TextIO):
f.write("// WARNING: THIS FILE WAS AUTO GENERATED BY make_translation.py. PLEASE DO NOT EDIT.\n") f.write(
"// WARNING: THIS FILE WAS AUTO GENERATED BY make_translation.py. PLEASE DO NOT EDIT.\n"
)
f.write("\n") f.write("\n")
f.write('#include "Translation.h"\n') f.write('#include "Translation.h"\n')
@@ -89,7 +93,7 @@ def get_constants() -> List[str]:
("SymbolVolts", "V"), ("SymbolVolts", "V"),
("SymbolDC", "DC"), ("SymbolDC", "DC"),
("SymbolCellCount", "S"), ("SymbolCellCount", "S"),
("SymbolVersionNumber", buildVersion) ("SymbolVersionNumber", buildVersion),
] ]
@@ -107,7 +111,7 @@ def get_debug_menu() -> List[str]:
"Vin ", "Vin ",
"PCB ", "PCB ",
"PWR ", "PWR ",
"Max " "Max ",
] ]
@@ -240,7 +244,7 @@ def get_chars_from_font_index(index: int) -> str:
# the chars take 2 bytes. To do this, we use \xF1 to \xFF as lead bytes # the chars take 2 bytes. To do this, we use \xF1 to \xFF as lead bytes
# to designate double-byte chars, and leave the remaining as single-byte # to designate double-byte chars, and leave the remaining as single-byte
# chars. # chars.
# #
# For the sake of sanity, \x00 always means the end of string, so we skip # For the sake of sanity, \x00 always means the end of string, so we skip
# \xF1\x00 and others in the mapping. # \xF1\x00 and others in the mapping.
# #
@@ -296,15 +300,21 @@ def get_font_map_and_table(text_list: List[str]) -> Tuple[str, Dict[str, str]]:
# do not need to be in the small font table to save space. # do not need to be in the small font table to save space.
# We assume all symbols not in the font table to be a CJK char. # We assume all symbols not in the font table to be a CJK char.
# We also enforce that numbers are first. # We also enforce that numbers are first.
ordered_normal_sym_list: List[str] = forced_first_symbols + [x for x in text_list if x not in forced_first_symbols and x in font_table] ordered_normal_sym_list: List[str] = forced_first_symbols + [
ordered_cjk_sym_list: List[str] = [x for x in text_list if x not in forced_first_symbols and x not in font_table] x for x in text_list if x not in forced_first_symbols and x in font_table
]
ordered_cjk_sym_list: List[str] = [
x for x in text_list if x not in forced_first_symbols and x not in font_table
]
total_symbol_count = len(ordered_normal_sym_list) + len(ordered_cjk_sym_list) total_symbol_count = len(ordered_normal_sym_list) + len(ordered_cjk_sym_list)
# \x00 is for NULL termination and \x01 is for newline, so the maximum # \x00 is for NULL termination and \x01 is for newline, so the maximum
# number of symbols allowed is as follow (see also the comments in # number of symbols allowed is as follow (see also the comments in
# `get_chars_from_font_index`): # `get_chars_from_font_index`):
if total_symbol_count > (0x10 * 0xFF - 15) - 2: # 4063 if total_symbol_count > (0x10 * 0xFF - 15) - 2: # 4063
logging.error(f"Error, too many used symbols for this version (total {total_symbol_count})") logging.error(
f"Error, too many used symbols for this version (total {total_symbol_count})"
)
sys.exit(1) sys.exit(1)
logging.info(f"Generating fonts for {total_symbol_count} symbols") logging.info(f"Generating fonts for {total_symbol_count} symbols")
@@ -338,7 +348,9 @@ def get_font_map_and_table(text_list: List[str]) -> Tuple[str, Dict[str, str]]:
sys.exit(1) sys.exit(1)
font_table_strings.append(f"{font_line}//{symbol_map[sym]} -> {sym}") font_table_strings.append(f"{font_line}//{symbol_map[sym]} -> {sym}")
# No data to add to the small font table # No data to add to the small font table
font_small_table_strings.append(f"// {symbol_map[sym]} -> {sym}") font_small_table_strings.append(
f"// {symbol_map[sym]} -> {sym}"
)
output_table = "const uint8_t USER_FONT_12[] = {\n" output_table = "const uint8_t USER_FONT_12[] = {\n"
for line in font_table_strings: for line in font_table_strings:
@@ -393,7 +405,9 @@ def write_language(lang: dict, defs: dict, f: TextIO) -> None:
if "feature" in mod: if "feature" in mod:
f.write(f"#ifdef {mod['feature']}\n") f.write(f"#ifdef {mod['feature']}\n")
f.write(f" /* [{index:02d}] {eid.ljust(max_len)[:max_len]} */ ") f.write(f" /* [{index:02d}] {eid.ljust(max_len)[:max_len]} */ ")
f.write(f"\"{convert_string(symbol_conversion_table, obj[eid]['desc'])}\",//{obj[eid]['desc']} \n") f.write(
f"\"{convert_string(symbol_conversion_table, obj[eid]['desc'])}\",//{obj[eid]['desc']} \n"
)
if "feature" in mod: if "feature" in mod:
f.write("#endif\n") f.write("#endif\n")
@@ -441,13 +455,17 @@ def write_language(lang: dict, defs: dict, f: TextIO) -> None:
for mod in defs["characters"]: for mod in defs["characters"]:
eid: str = mod["id"] eid: str = mod["id"]
f.write(f'const char* {eid} = "{convert_string(symbol_conversion_table, obj[eid])}";//{obj[eid]} \n') f.write(
f'const char* {eid} = "{convert_string(symbol_conversion_table, obj[eid])}";//{obj[eid]} \n'
)
f.write("\n") f.write("\n")
# Write out firmware constant options # Write out firmware constant options
constants = get_constants() constants = get_constants()
for x in constants: for x in constants:
f.write(f'const char* {x[0]} = "{convert_string(symbol_conversion_table, x[1])}";//{x[1]} \n') f.write(
f'const char* {x[0]} = "{convert_string(symbol_conversion_table, x[1])}";//{x[1]} \n'
)
f.write("\n") f.write("\n")
# Debug Menu # Debug Menu
@@ -475,7 +493,9 @@ def write_language(lang: dict, defs: dict, f: TextIO) -> None:
if "feature" in mod: if "feature" in mod:
f.write(f"#ifdef {mod['feature']}\n") f.write(f"#ifdef {mod['feature']}\n")
f.write(f" /* [{index:02d}] {eid.ljust(max_len)[:max_len]} */ ") f.write(f" /* [{index:02d}] {eid.ljust(max_len)[:max_len]} */ ")
f.write(f'{{ "{convert_string(symbol_conversion_table, source_text)}" }},//{obj[eid]["text2"]} \n') f.write(
f'{{ "{convert_string(symbol_conversion_table, source_text)}" }},//{obj[eid]["text2"]} \n'
)
if "feature" in mod: if "feature" in mod:
f.write("#endif\n") f.write("#endif\n")
@@ -498,7 +518,9 @@ def write_language(lang: dict, defs: dict, f: TextIO) -> None:
else: else:
source_text = "\n" + obj[eid]["text2"] source_text = "\n" + obj[eid]["text2"]
f.write(f" /* {eid.ljust(max_len)[:max_len]} */ ") f.write(f" /* {eid.ljust(max_len)[:max_len]} */ ")
f.write(f'"{convert_string(symbol_conversion_table, source_text)}",//{obj[eid]["text2"]} \n') f.write(
f'"{convert_string(symbol_conversion_table, source_text)}",//{obj[eid]["text2"]} \n'
)
f.write("};\n\n") f.write("};\n\n")
@@ -510,19 +532,25 @@ def write_language(lang: dict, defs: dict, f: TextIO) -> None:
for mod in defs["menuGroups"]: for mod in defs["menuGroups"]:
eid = mod["id"] eid = mod["id"]
f.write(f" /* {eid.ljust(max_len)[:max_len]} */ ") f.write(f" /* {eid.ljust(max_len)[:max_len]} */ ")
f.write(f"\"{convert_string(symbol_conversion_table, (obj[eid]['desc']))}\",//{obj[eid]['desc']} \n") f.write(
f"\"{convert_string(symbol_conversion_table, (obj[eid]['desc']))}\",//{obj[eid]['desc']} \n"
)
f.write("};\n\n") f.write("};\n\n")
f.write(f"const bool HasFahrenheit = {('true' if lang.get('tempUnitFahrenheit', True) else 'false')};\n") f.write(
f"const bool HasFahrenheit = {('true' if lang.get('tempUnitFahrenheit', True) else 'false')};\n"
)
f.write("\n// Verify SettingsItemIndex values:\n") f.write("\n// Verify SettingsItemIndex values:\n")
for i, mod in enumerate(defs["menuOptions"]): for i, mod in enumerate(defs["menuOptions"]):
eid = mod["id"] eid = mod["id"]
f.write(f"static_assert(static_cast<uint8_t>(SettingsItemIndex::{eid}) == {i});\n") f.write(
f"static_assert(static_cast<uint8_t>(SettingsItemIndex::{eid}) == {i});\n"
)
def read_version() -> str: def read_version() -> str:
with open(HERE.parent / 'source' / 'version.h') as version_file: with open(HERE.parent / "source" / "version.h") as version_file:
for line in version_file: for line in version_file:
if re.findall(r"^.*(?<=(#define)).*(?<=(BUILD_VERSION))", line): if re.findall(r"^.*(?<=(#define)).*(?<=(BUILD_VERSION))", line):
line = re.findall(r"\"(.+?)\"", line) line = re.findall(r"\"(.+?)\"", line)
@@ -538,13 +566,10 @@ def read_version() -> str:
def parse_args() -> argparse.Namespace: def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument("--output", "-o", parser.add_argument(
help="Target file", "--output", "-o", help="Target file", type=argparse.FileType("w"), required=True
type=argparse.FileType("w"), )
required=True parser.add_argument("languageCode", help="Language to generate")
)
parser.add_argument("languageCode",
help="Language to generate")
return parser.parse_args() return parser.parse_args()

View File

@@ -2,7 +2,7 @@
set -e set -e
# Setup shell file to setup the environment on an ubuntu machine # Setup shell file to setup the environment on an ubuntu machine
sudo apt-get update && sudo apt-get install -y make bzip2 git python3 python3-pip wget sudo apt-get update && sudo apt-get install -y make bzip2 git python3 python3-pip wget
python3 -m pip install bdflib python3 -m pip install bdflib black
sudo mkdir -p /build sudo mkdir -p /build
cd /build cd /build