Skip to content

Commit

Permalink
Add .util.click.exec_cb for --nodes, --regions CLI options
Browse files Browse the repository at this point in the history
  • Loading branch information
khaeru committed Oct 30, 2023
1 parent dc3e339 commit 0cacda5
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion message_ix_models/util/click.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import logging
from datetime import datetime
from pathlib import Path
from typing import List, Optional, Union
from typing import Callable, List, Optional, Union

import click
from click import Argument, Choice, Option
Expand Down Expand Up @@ -59,6 +59,32 @@ def _callback(context, param, value):
return _callback


def exec_cb(expression: str) -> Callable:
"""Return a callback that :func:`exec`-utes an `expression`.
The `expression` is executed in a limited context that has only two names available:
- :py:`context`: the :class:`.Context` instance.
- :py:`value`: the value passed to the :mod:`click.Parameter`.
Example
-------
>>> @click.command
... @click.option(
... "--myopt", callback=exec_cb("context.my_mod.my_opt = value + 3")
... )
... def cmd(...):
... ...
"""

def _cb(context: Union[click.Context, Context], param, value):
ctx = context.obj if isinstance(context, click.Context) else context
exec(expression, {}, {"context": ctx, "value": value})
return value

return _cb


def format_sys_argv() -> str:
"""Format :data:`sys.argv` in a readable manner."""
import sys
Expand Down Expand Up @@ -159,6 +185,7 @@ def unique_id() -> str:
"nodes": Option(
["--nodes"],
help="Code list to use for 'node' dimension.",
callback=exec_cb("context.model.regions = value"),
type=Choice(codelists("node")),
),
"output_model": Option(
Expand All @@ -178,6 +205,7 @@ def unique_id() -> str:
"regions": Option(
["--regions"],
help="Code list to use for 'node' dimension.",
callback=exec_cb("context.model.regions = value"),
type=Choice(codelists("node")),
),
"rep_out_path": Option(
Expand Down

0 comments on commit 0cacda5

Please sign in to comment.