Skip to content

Commit 67cb369

Browse files
committed
Colored logging
1 parent cc61295 commit 67cb369

9 files changed

Lines changed: 93 additions & 33 deletions

File tree

remove-json-keys/pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ authors = [{name = "Adam Lui", email = "adam@kudoai.com"}]
1010
readme = "README.md"
1111
license = "MIT"
1212
license-files = ["LICENSE.md"]
13+
dependencies = ["colorama>=0.4.6,<1.0.0"]
1314
requires-python = ">=3.6,<4.0"
1415
keywords = ["json", "data"]
1516
classifiers = [

remove-json-keys/src/remove_json_keys/__main__.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,26 @@ def main():
66

77
if not cli.config.no_wizard:
88
while True: # prompt user for keys to remove
9-
if getattr(cli.config, 'keys', '') : print('Key(s) to remove:', cli.config.keys)
10-
input_key = input("Enter key to remove (or ENTER if done): ")
9+
if getattr(cli.config, 'keys', '') : print('\nKey(s) to remove:', cli.config.keys)
10+
input_key = input(f'\n{log.colors.bw}Enter key to remove (or ENTER if done): {log.colors.nc}')
1111
if not input_key : break
1212
cli.config.keys.append(input_key)
1313

14-
log.trunc(f'\nSearching for {cli.config.json_dir}...')
14+
log.info(f'Searching for {cli.config.json_dir}...')
1515
cli.config.json_dir = init.json_dir(cli.config.json_dir)
16-
if cli.config.json_dir : log.trunc(f'JSON directory found!\n\n>> {cli.config.json_dir}\n')
17-
else : log.trunc(f'Unable to locate a {cli.config.json_dir} directory.') ; sys.exit(1)
16+
if cli.config.json_dir:
17+
log.success('Directory found!')
18+
print(f'\n>> {cli.config.json_dir}')
19+
else:
20+
log.warn('Unable to locate directory.')
21+
sys.exit(1)
1822

19-
keys_removed, keys_skipped, files_processed_cnt = data.json.keys(cli)
23+
keys_removed, keys_skipped, files_processed_cnt = data.json.remove_keys(cli)
2024

2125
log.final_summary({
2226
'removed': [f'{key} ({file_path})' for key, file_path in keys_removed],
2327
'skipped': [f'{key} ({file_path})' for key, file_path in keys_skipped],
2428
})
25-
log.trunc(f'Total JSON files processed: {files_processed_cnt}\n')
29+
log.data(f'Total JSON files processed: {files_processed_cnt}')
2630

2731
if __name__ == '__main__' : main()

remove-json-keys/src/remove_json_keys/lib/data/json.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ def remove_keys(cli):
1616

1717
# Remove keys
1818
modified = False
19-
for key in cli.config.remove_keys:
19+
for key in cli.config.keys:
2020
re_key = fr'"{re.escape(key)}"\s*:\s*(?:\{{[^}}]*\}}|"[^"]*"|\d+|true|false|null)\s*,?\s*'
2121
data, cnt = re.subn(re_key, '', data)
2222
if cnt > 0:
Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,45 @@
11
import os
2+
from sys import stdout
3+
from types import SimpleNamespace as sns
4+
import colorama
25

36
try:
47
terminal_width = os.get_terminal_size()[0]
58
except OSError:
69
terminal_width = 80
710

11+
colorama.init() # enable compatibility w/ Windows
12+
colors = sns(
13+
nc='\x1b[0m', # no color
14+
br='\x1b[1;91m', # bright red
15+
by='\x1b[1;33m', # bright yellow
16+
bo='\x1b[38;5;214m', # bright orange
17+
bg='\x1b[1;92m', # bright green
18+
bw='\x1b[1;97m', # bright white
19+
dg='\x1b[32m', # dark green
20+
dy='\x1b[33m', # dark yellow
21+
gry='\x1b[90m' # gray
22+
)
23+
24+
def data(msg) : print(f'\n{colors.bw}{msg}{colors.nc}')
25+
def dim(msg) : print(f'\n{colors.gry}{msg}{colors.nc}')
26+
def error(msg) : print(f'\n{colors.br}ERROR: {msg}{colors.nc}')
27+
def info(msg, end='') : print(f'\n{colors.by}{msg}{colors.nc}', end=end)
28+
def overwrite_print(msg) : stdout.write('\r' + msg.ljust(terminal_width)[:terminal_width])
29+
def tip(msg) : print(f'\n{colors.by}TIP: {msg}{colors.nc}')
30+
def success(msg) : print(f'\n{colors.bg}{msg}{colors.nc}')
31+
def warn(msg) : print(f'\n{colors.bo}WARNING: {msg}{colors.nc}')
32+
833
def final_summary(summary_dict):
9-
trunc('\nAll JSON files updated successfully!\n')
34+
success('All JSON files processed!')
1035
for name, file_set in summary_dict.items():
1136
if file_set:
1237
status = name.replace('_', ' ')
13-
print(f'\nKeys {status}: {len(file_set)}')
14-
print('[\n' + '\n'.join(file_set) + '\n]')
38+
status_color = colors.by if status == 'removed' else colors.gry
39+
data(f'Keys {status}: {len(file_set)}')
40+
print(f'{status_color}[\n ' + '\n '.join(file_set) + f'\n]{colors.nc}')
1541

1642
def trunc(msg, end='\n'):
1743
truncated_lines = [
18-
line if len(line) < terminal_width else line[:terminal_width -4] + '...' for line in msg.splitlines() ]
44+
line if len(line) < terminal_width else line[:terminal_width -4] + '...' for line in msg.splitlines()]
1945
print('\n'.join(truncated_lines), end=end)

translate-messages/pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ authors = [{name = "Adam Lui", email = "adam@kudoai.com"}]
1010
readme = "README.md"
1111
license = "MIT"
1212
license-files = ["LICENSE.md"]
13-
dependencies = ["requests>=2.32.0,<3.0.0", "translate>=3.8.0,<4.0.0"]
13+
dependencies = ["requests>=2.32.0,<3.0.0", "translate>=3.8.0,<4.0.0", "colorama>=0.4.6,<1.0.0"]
1414
requires-python = ">=3.6,<4.0"
1515
keywords = ["translate", "translation", "messages", "i18n", "chrome", "mymemory"]
1616
classifiers = [

translate-messages/src/translate_messages/__main__.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,19 @@ def main():
77

88
if not cli.config.no_wizard:
99
while True: # prompt user for keys to ignore
10-
if getattr(cli.config, 'exclude_keys', '') : print('Ignored key(s):', cli.config.exclude_keys)
11-
input_key = input('Enter key to ignore (or ENTER if done): ')
10+
if getattr(cli.config, 'exclude_keys', '') : print('\nIgnored key(s):', cli.config.exclude_keys)
11+
input_key = input(f'\n{log.colors.bw}Enter key to ignore (or ENTER if done): {log.colors.nc}')
1212
if not input_key : break
1313
cli.config.exclude_keys.append(input_key)
1414

15-
log.trunc(f'\nSearching for {cli.config.locales_dir}...')
15+
log.info(f'Searching for {cli.config.locales_dir}...')
1616
cli.config.locales_dir = init.locales_dir(cli.config.locales_dir)
17-
if cli.config.locales_dir : log.trunc(f'_locales directory found!\n\n>> {cli.config.locales_dir}\n')
18-
else : log.trunc('Unable to locate directory.') ; sys.exit(1)
17+
if cli.config.locales_dir:
18+
log.success('Directory found!')
19+
print(f'\n>> {cli.config.locales_dir}')
20+
else:
21+
log.warn('Unable to locate directory.')
22+
sys.exit(1)
1923

2024
cli.config.msgs_filename = 'messages.json'
2125
cli.config.en_msgs = data.json.read(os.path.join(cli.config.locales_dir, 'en', cli.config.msgs_filename))

translate-messages/src/translate_messages/lib/init.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import argparse, os, requests
22
from types import SimpleNamespace as sns
3-
from . import data
3+
from . import data, log
44

55
def cli(caller_file):
66

@@ -58,10 +58,10 @@ def cli(caller_file):
5858
def config_file(cli):
5959
if os.path.exists(cli.config_path):
6060
if cli.config.force:
61-
print(f'Overwriting existing config at {cli.config_path}...')
61+
log.info(f'Overwriting existing config at {cli.config_path}...')
6262
else:
63-
print(f'Config already exists at {cli.config_path}.Skipping --init.')
64-
print('\nTIP: Pass --force to overwrite.')
63+
log.warn(f'Config already exists at {cli.config_path}.Skipping --init.')
64+
log.tip('TIP: Pass --force to overwrite.')
6565
return
6666
cli.config_filename = '.translate-msgs.config.json'
6767
cli.config_path = os.path.join(cli.project_root, cli.config_filename)
@@ -73,7 +73,7 @@ def config_file(cli):
7373
except (requests.RequestException, ValueError) as err:
7474
raise RuntimeError(f"Failed to fetch default config from {jsd_url}: {err}")
7575
data.json.write(cli.file_config, cli.config_path)
76-
print(f'Default config created at {cli.config_path}')
76+
log.success(f'Default config created at {cli.config_path}')
7777

7878
def locales_dir(target_dir):
7979
for root, dirs, _ in os.walk(os.getcwd()):

translate-messages/src/translate_messages/lib/language.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,17 +51,19 @@ def write_translations(cli):
5151
msgs_path = os.path.join(lang_folder_path, cli.config.msgs_filename)
5252
msgs = data.json.read(msgs_path)
5353

54-
log.trunc(f"{ 'Adding' if not msgs else 'Updating' } {lang_folder}/{cli.config.msgs_filename}...", end='')
54+
log.info(f"{ 'Adding' if not msgs else 'Updating' } {lang_folder}/{cli.config.msgs_filename}...", end='')
5555
sys.stdout.flush()
5656
translated_msgs = create_translations(cli, msgs, lang_code)
5757
data.json.write(translated_msgs, msgs_path)
5858

5959
if translated_msgs == msgs : langs_skipped.append(lang_code) ; lang_skipped = True
6060
elif translated_msgs != msgs : langs_translated.append(lang_code) ; lang_translated = True
6161
if not lang_translated : langs_not_translated.append(lang_code)
62-
log.overwrite_print(
63-
f"{'Added' if lang_added else 'Skipped' if lang_skipped else 'Updated'} "
64-
f"{lang_folder}/{cli.config.msgs_filename}"
62+
status = (
63+
f"{log.colors.dg}Added" if lang_added else
64+
f"{log.colors.gry}Skipped" if lang_skipped else
65+
f"{log.colors.dy}Updated"
6566
)
67+
log.overwrite_print(f"{status} {lang_folder}/{cli.config.msgs_filename}{log.colors.nc}")
6668

6769
return langs_translated, langs_skipped, langs_added, langs_not_translated
Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,45 @@
11
import os
22
from sys import stdout
3+
from types import SimpleNamespace as sns
4+
import colorama
35

46
try:
57
terminal_width = os.get_terminal_size()[0]
68
except OSError:
79
terminal_width = 80
810

11+
colorama.init() # enable compatibility w/ Windows
12+
colors = sns(
13+
nc='\x1b[0m', # no color
14+
br='\x1b[1;91m', # bright red
15+
by='\x1b[1;33m', # bright yellow
16+
bo='\x1b[38;5;214m', # bright orange
17+
bg='\x1b[1;92m', # bright green
18+
bw='\x1b[1;97m', # bright white
19+
dg='\x1b[32m', # dark green
20+
dy='\x1b[33m', # dark yellow
21+
gry='\x1b[90m' # gray
22+
)
23+
24+
def data(msg) : print(f'\n{colors.bw}{msg}{colors.nc}')
25+
def dim(msg) : print(f'\n{colors.gry}{msg}{colors.nc}')
26+
def error(msg) : print(f'\n{colors.br}ERROR: {msg}{colors.nc}')
27+
def info(msg, end='') : print(f'\n{colors.by}{msg}{colors.nc}', end=end)
28+
def overwrite_print(msg) : stdout.write('\r' + msg.ljust(terminal_width)[:terminal_width])
29+
def tip(msg) : print(f'\n{colors.by}TIP: {msg}{colors.nc}')
30+
def success(msg) : print(f'\n{colors.bg}{msg}{colors.nc}')
31+
def warn(msg) : print(f'\n{colors.bo}WARNING: {msg}{colors.nc}')
32+
933
def final_summary(summary_dict):
10-
trunc('\nAll JSON files updated successfully!\n')
34+
success('\nAll JSON files updated successfully!')
1135
for name, lang_set in summary_dict.items():
1236
if lang_set:
1337
status = name.replace('_', ' ')
14-
print(f'\nLanguages {status}: {len(lang_set)}')
15-
print(f"[ {', '.join(lang_set)} ]")
16-
17-
def overwrite_print(msg) : stdout.write('\r' + msg.ljust(terminal_width)[:terminal_width])
38+
status_color = colors.by if status == 'translated' else colors.bg if status == 'added' else colors.gry
39+
data(f'Languages {status}: {len(lang_set)}')
40+
print(f"{status_color}[ {', '.join(lang_set)} ]{colors.nc}")
1841

1942
def trunc(msg, end='\n'):
2043
truncated_lines = [
21-
line if len(line) < terminal_width else line[:terminal_width -4] + '...' for line in msg.splitlines() ]
44+
line if len(line) < terminal_width else line[:terminal_width -4] + '...' for line in msg.splitlines()]
2245
print('\n'.join(truncated_lines), end=end)

0 commit comments

Comments
 (0)