Skip to content

Commit b765bd6

Browse files
committed
Overhauled settings.load() to enforce narg vals, added --config [path] to docs + --help screen
1 parent f865aad commit b765bd6

8 files changed

Lines changed: 80 additions & 65 deletions

File tree

remove-json-keys/docs/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ Options can be set by using command-line arguments:
4343
| ---------------------- | ------------------------------------------------------------------------------- | -----------------------------
4444
| `-d`, `--json-dir` | Name of the folder containing JSON files (default: `_locales`) | `--json-dir=data`
4545
| `-k`, `--keys` | Comma-separated list of keys to remove | `--keys=app_DESC,err_NOT_FOUND`
46+
| `config` | Use custom config file | `--config=path/to/file`
4647
| `init`, `-i`, `--init` | Create .remove-json.config.json5 in project root to store default settings |
4748
| `-n`, `--no-wizard` | Skip interactive prompts during start-up |
4849
| `-h`, `--help` | Show help screen |

remove-json-keys/src/remove_json_keys/assets/data/messages.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
"err_UNRECOGNIZED_ARGS": { "message": "Unrecognized argument(s)" },
2828
"help_JSON_DIR": { "message": "Name of the folder containing JSON files (default: \"_locales\")" },
2929
"help_KEYS": { "message": "Keys to remove (e.g. \"app_NAME,author\")" },
30+
"help_CONFIG": { "message": "Use custom config file (e.g. \"path/to/file\")" },
3031
"help_INIT": { "message": "Create .remove-json.config.json5 file to store default options" },
3132
"help_FORCE": { "message": "Force overwrite existing config file when using init" },
3233
"help_NO_WIZARD": { "message": "Skip interactive prompts during start-up" },

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

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
from pathlib import Path
2-
import sys
32

43
from . import data, language, log, settings, url
54

@@ -42,11 +41,13 @@ def config_file(cli):
4241
def config_filepath(cli): # for settings.load()
4342

4443
# Check --config <path>
45-
for idx, arg in enumerate(sys.argv):
46-
if arg == '--config' and idx +1 < len(sys.argv):
47-
cli.config_filepath = Path(sys.argv[idx + 1]).resolve()
48-
if cli.config_filepath.exists(): return
49-
else : log.warn(f'{cli.msgs.warn_SPECIFIED_CONFIG} {cli.config_filepath} {cli.msgs.warn_NOT_FOUND.lower()}')
44+
if getattr(cli.config, 'config', ''):
45+
cli.config_filepath = Path(cli.config.config).resolve()
46+
if cli.config_filepath.exists():
47+
log.debug(f'Config file found: {cli.config_filepath}')
48+
return
49+
else:
50+
log.warn(f'{cli.msgs.warn_SPECIFIED_CONFIG} {cli.config_filepath} not found')
5051

5152
# Search upwards
5253
possible_config_filenames = [
@@ -61,6 +62,8 @@ def config_filepath(cli): # for settings.load()
6162
cli.config_filepath = possible_config_filepath
6263
return
6364

65+
cli.config_filepath = None
66+
6467
def json_path(cli):
6568
for path in Path.cwd().rglob(cli.config.json_dir):
6669
if path.is_dir():

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

Lines changed: 29 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
args=['-d', '--json-dir', '--json-folder'], type=str, default_val='_locales'),
99
keys=sn(
1010
args=['-k', '--keys', '--remove-keys', '--delete-keys'], type=str, parser='csv'),
11+
config=sn(
12+
args=['--config'], type=str),
1113
init=sn(
1214
args=['-i', '--init'],
1315
action='store_true', subcmd='true', exit=True, handler=lambda cli: init.config_file(cli)
@@ -27,51 +29,51 @@
2729
)
2830

2931
def load(cli):
32+
cli.config = sn()
3033

3134
# Assign help tips from cli.msgs
3235
for ctrl_key, ctrl in vars(controls).items():
3336
if not hasattr(ctrl, 'help') : ctrl.help = getattr(cli.msgs, f'help_{ctrl_key.upper()}')
3437

35-
# Load from config file
36-
cli.config = sn()
37-
init.config_filepath(cli)
38-
if getattr(cli, 'config_filepath', None):
39-
cli.config = data.sns.from_dict(data.json.read(cli.config_filepath))
40-
log.debug('Config file loaded!', cli)
41-
else:
42-
log.debug('No config file found.')
43-
4438
# Parse CLI args
4539
argp = argparse.ArgumentParser(description=cli.description, add_help=False)
46-
sys.argv = [arg.replace('_', '-') if arg.startswith('--') and '_' in arg else arg for arg in sys.argv]
47-
for attr_name in vars(controls): # add args to argp
48-
kwargs = getattr(controls, attr_name).__dict__.copy()
40+
for ctrl_key in vars(controls): # add args to argp
41+
kwargs = getattr(controls, ctrl_key).__dict__.copy()
4942
args = kwargs.pop('args')
50-
valid_argparse_params = {
43+
valid_argparse_kwargs = {
5144
'action', 'choices', 'const', 'default', 'dest', 'help', 'metavar', 'nargs', 'required', 'type', 'version' }
52-
argparse_kwargs = { key:val for key,val in kwargs.items() if key in valid_argparse_params}
45+
argparse_kwargs = { key:val for key,val in kwargs.items() if key in valid_argparse_kwargs}
5346
argp.add_argument(*args, **argparse_kwargs)
54-
parsed_args, unrecognized_args = argp.parse_known_args()
47+
parsed_args, unknown_args = argp.parse_known_args()
5548
subcmd_flags = [] # exempt dashless args from validation
5649
for ctrl in vars(controls).values():
5750
if getattr(ctrl, 'subcmd', False):
5851
for arg in ctrl.args : subcmd_flags.append(arg)
59-
if unrecognized_args and not all(f'--{arg}' in subcmd_flags for arg in unrecognized_args):
60-
log.error(f"{cli.msgs.err_UNRECOGNIZED_ARGS}: {' '.join(unrecognized_args)}")
52+
if unknown_args and not all(f'--{arg}' in subcmd_flags for arg in unknown_args):
53+
log.error(f"{cli.msgs.err_UNRECOGNIZED_ARGS}: {' '.join(unknown_args)}")
6154
log.help_cmd_docs_url_exit(cli)
62-
for attr_name, ctrl in vars(controls).items(): # process subcmds
55+
for ctrl_key, ctrl in vars(controls).items(): # process subcmds
6356
if getattr(ctrl, 'subcmd', False) and next(arg for arg in ctrl.args if arg.startswith('--'))[2:] in sys.argv:
64-
setattr(parsed_args, attr_name, True)
57+
setattr(parsed_args, ctrl_key, True)
6558
for key, val in vars(parsed_args).items(): # apply parsed_args to cli.config
66-
if val : setattr(cli.config, key, val)
59+
setattr(cli.config, key, val)
6760
log.debug('Args parsed!', cli)
6861

69-
# Init all cli.config vals
70-
for name, ctrl in vars(controls).items():
71-
val = getattr(cli.config, name, '')
72-
if getattr(ctrl, 'parser', '') == 'csv':
73-
val = data.csv.parse(val)
62+
# Load from config file (w/o overriding args)
63+
init.config_filepath(cli)
64+
if getattr(cli, 'config_filepath', None):
65+
for key, val in data.json.read(cli.config_filepath).items():
66+
if not getattr(cli.config, key): setattr(cli.config, key, val)
67+
log.debug('Config file loaded!', cli)
68+
else:
69+
log.debug('No config file found.')
70+
71+
# Apply parsers/default_vals
72+
for ctrl_key, ctrl in vars(controls).items():
73+
val = getattr(cli.config, ctrl_key, '')
7474
if not val and hasattr(ctrl, 'default_val'):
75-
val = ctrl.default_val
76-
setattr(cli.config, name, val)
75+
setattr(cli.config, ctrl_key, ctrl.default_val)
76+
if getattr(ctrl, 'parser', '') == 'csv':
77+
setattr(cli.config, ctrl_key, data.csv.parse(val))
78+
7779
log.debug('All cli.config vals set!', cli)

translate-messages/docs/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ Options can be set by using command-line arguments:
4747
| `--exclude-langs` | Comma-separated list of languages to exclude | `--exclude-langs=es,zh`
4848
| `--exclude-keys` | Comma-separated list of keys to ignore | `--exclude-keys=app_NAME,author`
4949
| `--only-stable` | Only use stable locales (skip auto-discovery) |
50+
| `config` | Use custom config file | `--config=path/to/file`
5051
| `init`, `-i`, `--init` | Create `.translate-msgs.config.json5` in project root to store default options |
5152
| `-f`, `--force` | Force overwrite of existing config file when using `init` |
5253
| `-n`, `--no-wizard` | Skip interactive prompts during start-up |

translate-messages/src/translate_messages/assets/data/messages.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
"help_EXCLUDE_LANGS": { "message": "Languages to exclude (e.g. \"es,zh\")" },
3939
"help_EXCLUDE_KEYS": { "message": "Keys to ignore (e.g. \"app_NAME,author\")" },
4040
"help_ONLY_STABLE": { "message": "Only use stable locales (skip auto-discovery)" },
41+
"help_CONFIG": { "message": "Use custom config file (e.g. \"path/to/file\")" },
4142
"help_INIT": { "message": "Create .translate-msgs.config.json5 file to store default options" },
4243
"help_FORCE": { "message": "Force overwrite existing config file when using init" },
4344
"help_NO_WIZARD": { "message": "Skip interactive prompts during start-up" },

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

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -42,11 +42,13 @@ def config_file(cli):
4242
def config_filepath(cli): # for settings.load()
4343

4444
# Check --config <path>
45-
for idx, arg in enumerate(sys.argv):
46-
if arg == '--config' and idx +1 < len(sys.argv):
47-
cli.config_filepath = Path(sys.argv[idx + 1]).resolve()
48-
if cli.config_filepath.exists(): return
49-
else : log.warn(f'{cli.msgs.warn_SPECIFIED_CONFIG} {cli.config_filepath} {cli.msgs.warn_NOT_FOUND.lower()}')
45+
if getattr(cli.config, 'config', ''):
46+
cli.config_filepath = Path(cli.config.config).resolve()
47+
if cli.config_filepath.exists():
48+
log.debug(f'Config file found: {cli.config_filepath}')
49+
return
50+
else:
51+
log.warn(f'{cli.msgs.warn_SPECIFIED_CONFIG} {cli.config_filepath} not found')
5052

5153
# Search upwards
5254
possible_config_filenames = [
@@ -61,6 +63,8 @@ def config_filepath(cli): # for settings.load()
6163
cli.config_filepath = possible_config_filepath
6264
return
6365

66+
cli.config_filepath = None
67+
6468
def locales_path(cli):
6569
for path in Path.cwd().rglob(cli.config.locales_dir):
6670
if path.is_dir():

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

Lines changed: 29 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
args=['--exclude-keys', '--ignore-keys'], type=str, parser='csv'),
1919
only_stable=sn(
2020
args=['-s', '--only-stable', '--no-discovery'], action='store_true'),
21+
config=sn(
22+
args=['--config'], type=str),
2123
init=sn(
2224
args=['-i', '--init'],
2325
action='store_true', subcmd='true', exit=True, handler=lambda cli: init.config_file(cli)
@@ -37,51 +39,51 @@
3739
)
3840

3941
def load(cli):
42+
cli.config = sn()
4043

4144
# Assign help tips from cli.msgs
4245
for ctrl_key, ctrl in vars(controls).items():
4346
if not hasattr(ctrl, 'help') : ctrl.help = getattr(cli.msgs, f'help_{ctrl_key.upper()}')
4447

45-
# Load from config file
46-
cli.config = sn()
47-
init.config_filepath(cli)
48-
if getattr(cli, 'config_filepath', None):
49-
cli.config = data.sns.from_dict(data.json.read(cli.config_filepath))
50-
log.debug('Config file loaded!', cli)
51-
else:
52-
log.debug('No config file found.')
53-
5448
# Parse CLI args
5549
argp = argparse.ArgumentParser(description=cli.description, add_help=False)
56-
sys.argv = [arg.replace('_', '-') if arg.startswith('--') and '_' in arg else arg for arg in sys.argv]
57-
for attr_name in vars(controls): # add args to argp
58-
kwargs = getattr(controls, attr_name).__dict__.copy()
50+
for ctrl_key in vars(controls): # add args to argp
51+
kwargs = getattr(controls, ctrl_key).__dict__.copy()
5952
args = kwargs.pop('args')
60-
valid_argparse_params = {
53+
valid_argparse_kwargs = {
6154
'action', 'choices', 'const', 'default', 'dest', 'help', 'metavar', 'nargs', 'required', 'type', 'version' }
62-
argparse_kwargs = { key:val for key,val in kwargs.items() if key in valid_argparse_params}
55+
argparse_kwargs = { key:val for key,val in kwargs.items() if key in valid_argparse_kwargs}
6356
argp.add_argument(*args, **argparse_kwargs)
64-
parsed_args, unrecognized_args = argp.parse_known_args()
57+
parsed_args, unknown_args = argp.parse_known_args()
6558
subcmd_flags = [] # exempt dashless args from validation
6659
for ctrl in vars(controls).values():
6760
if getattr(ctrl, 'subcmd', False):
6861
for arg in ctrl.args : subcmd_flags.append(arg)
69-
if unrecognized_args and not all(f'--{arg}' in subcmd_flags for arg in unrecognized_args):
70-
log.error(f"{cli.msgs.err_UNRECOGNIZED_ARGS}: {' '.join(unrecognized_args)}")
62+
if unknown_args and not all(f'--{arg}' in subcmd_flags for arg in unknown_args):
63+
log.error(f"{cli.msgs.err_UNRECOGNIZED_ARGS}: {' '.join(unknown_args)}")
7164
log.help_cmd_docs_url_exit(cli)
72-
for attr_name, ctrl in vars(controls).items(): # process subcmds
65+
for ctrl_key, ctrl in vars(controls).items(): # process subcmds
7366
if getattr(ctrl, 'subcmd', False) and next(arg for arg in ctrl.args if arg.startswith('--'))[2:] in sys.argv:
74-
setattr(parsed_args, attr_name, True)
67+
setattr(parsed_args, ctrl_key, True)
7568
for key, val in vars(parsed_args).items(): # apply parsed_args to cli.config
76-
if val : setattr(cli.config, key, val)
69+
setattr(cli.config, key, val)
7770
log.debug('Args parsed!', cli)
7871

79-
# Init all cli.config vals
80-
for name, ctrl in vars(controls).items():
81-
val = getattr(cli.config, name, '')
82-
if getattr(ctrl, 'parser', '') == 'csv':
83-
val = data.csv.parse(val)
72+
# Load from config file (w/o overriding args)
73+
init.config_filepath(cli)
74+
if getattr(cli, 'config_filepath', None):
75+
for key, val in data.json.read(cli.config_filepath).items():
76+
if not getattr(cli.config, key): setattr(cli.config, key, val)
77+
log.debug('Config file loaded!', cli)
78+
else:
79+
log.debug('No config file found.')
80+
81+
# Apply parsers/default_vals
82+
for ctrl_key, ctrl in vars(controls).items():
83+
val = getattr(cli.config, ctrl_key, '')
8484
if not val and hasattr(ctrl, 'default_val'):
85-
val = ctrl.default_val
86-
setattr(cli.config, name, val)
85+
setattr(cli.config, ctrl_key, ctrl.default_val)
86+
if getattr(ctrl, 'parser', '') == 'csv':
87+
setattr(cli.config, ctrl_key, data.csv.parse(val))
88+
8789
log.debug('All cli.config vals set!', cli)

0 commit comments

Comments
 (0)