From ed35c3a94ae3fc134d2718c4507738072a2c06fd Mon Sep 17 00:00:00 2001 From: Frantisek Hrbata Date: Thu, 27 Jul 2023 13:55:09 +0200 Subject: [PATCH] feat(tools): add global build context Introduces get_build_context() helper, which allows to get build context, e.g. project description, at places where this info is not available. The build context is set within ensure_build_directory. Signed-off-by: Frantisek Hrbata --- tools/idf_py_actions/tools.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/tools/idf_py_actions/tools.py b/tools/idf_py_actions/tools.py index 183cf0c39bf1..e823303390ed 100644 --- a/tools/idf_py_actions/tools.py +++ b/tools/idf_py_actions/tools.py @@ -30,6 +30,37 @@ SHELL_COMPLETE_RUN = SHELL_COMPLETE_VAR in os.environ +# The ctx dict "abuses" how python evaluates default parameter values. +# https://docs.python.org/3/reference/compound_stmts.html#function-definitions +# Default parameter values are evaluated from left to right +# when the function definition is executed +def get_build_context(ctx: Dict={}) -> Dict: + """ + The build context is set in the ensure_build_directory function. It can be used + in modules or other code, which don't have direct access to such information. + It returns dictionary with the following keys: + + 'proj_desc' - loaded project_description.json file + + Please make sure that ensure_build_directory was called otherwise the build + context dictionary will be empty. Also note that it might not be thread-safe to + modify the returned dictionary. It should be considered read-only. + """ + return ctx + + +def _set_build_context(args: 'PropertyDict') -> None: + # private helper to set global build context from ensure_build_directory + ctx = get_build_context() + + proj_desc_fn = f'{args.build_dir}/project_description.json' + try: + with open(proj_desc_fn, 'r') as f: + ctx['proj_desc'] = json.load(f) + except (OSError, ValueError) as e: + raise FatalError(f'Cannot load {proj_desc_fn}: {e}') + + def executable_exists(args: List) -> bool: try: subprocess.check_output(args) @@ -567,6 +598,9 @@ def ensure_build_directory(args: 'PropertyDict', prog_name: str, always_run_cmak except KeyError: pass + # set global build context + _set_build_context(args) + def merge_action_lists(*action_lists: Dict) -> Dict: merged_actions: Dict = {