From 23923f04f3cff14239262989125f252940498497 Mon Sep 17 00:00:00 2001 From: Mikkel Pedersen Date: Fri, 14 Jul 2023 10:47:23 +0200 Subject: [PATCH] fix(postprocess): Allow input as file, string, or list --- pollination_handlers/inputs/postprocess.py | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/pollination_handlers/inputs/postprocess.py b/pollination_handlers/inputs/postprocess.py index d5e7bd4..fb94bdd 100644 --- a/pollination_handlers/inputs/postprocess.py +++ b/pollination_handlers/inputs/postprocess.py @@ -1,15 +1,17 @@ """Handlers for post-processing options.""" +import os import json from jsonschema import validate from .helper import get_tempfile -def grid_metrics(json_file): +def grid_metrics(gm_obj): """Validate the file for custom grid metrics. Args: - json_file: A JSON file with custom grid metrics. + gm_obj: An object with custom grid metrics. This can be either a + JSON file, a string, or a list of grid metrics. Returns: str -- Path to a the custom grid metrics file. @@ -42,8 +44,20 @@ def grid_metrics(json_file): } } - with open(json_file) as file: - grid_metrics = json.load(file) + if isinstance(gm_obj, str): + if os.path.isfile(gm_obj): + with open(gm_obj) as file: + grid_metrics = json.load(file) + else: + grid_metrics = json.loads(gm_obj) + elif isinstance(gm_obj, list): + grid_metrics = [_gm for _gm in gm_obj] + else: + raise TypeError( + 'Unexpected type of input gm_obj. Valid types are str and list. ' + 'Type of input is: %s.' % type(gm_obj) + ) + validate(grid_metrics, schema) file_path = get_tempfile('json', 'grid_metrics')