From e68d165f09c76f55024d53ff34651c66ddc5aa99 Mon Sep 17 00:00:00 2001 From: Sebastian Ohlmann <sebastian.ohlmann@mpcdf.mpg.de> Date: Tue, 7 Mar 2023 18:51:51 +0100 Subject: [PATCH] Improve handling of formats Restrict choice of parameter to available formats. --- mmd_tools/mmdCreate.py | 4 ++-- mmd_tools/mmdFormats.py | 20 +++++++++++++++++++- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/mmd_tools/mmdCreate.py b/mmd_tools/mmdCreate.py index a8847ff..086d035 100755 --- a/mmd_tools/mmdCreate.py +++ b/mmd_tools/mmdCreate.py @@ -137,6 +137,7 @@ def main(): "--format", help="specify metadata format", default="mmd", + choices=mmdFormats.get_list_of_formats(), ) parser.add_argument( "-t", "--template", help="A JSON file with some pre-filled key value pairs" @@ -160,8 +161,7 @@ def main(): # Was there a metadataformat specified. If not, use MmdSimple: print("Metadata format: ", args.format) - format_file = str(pathlib.Path(__file__).parent.resolve()) + f"/formats/{args.format}.json" - metadata = mmdFormats.MmdFormat(format_file) + metadata = mmdFormats.MmdFormat.from_format(args.format) # Was there a template with JSON encoded key value pairs specified: if args.template: diff --git a/mmd_tools/mmdFormats.py b/mmd_tools/mmdFormats.py index cabd393..d591d2d 100755 --- a/mmd_tools/mmdFormats.py +++ b/mmd_tools/mmdFormats.py @@ -3,6 +3,7 @@ import json from datetime import date import os +import pathlib def convertJson2MetadataDict(mfile): with open(mfile, 'r') as f: @@ -82,7 +83,17 @@ class MmdFormat: for property in metadata['properties']: self.data.append(MmdEntry(*property.values())) - + + @classmethod + def from_format(cls, format): + """Alternative constructor, takes format string + + Instantiates class with a path to the internal data files. + """ + metadata_file = str(pathlib.Path(__file__).parent.resolve() / "formats" + / f"{format}.json") + return cls(metadata_file) + def toJson(self): data={} data['id']=self.id @@ -96,3 +107,10 @@ class MmdFormat: dataJson=json.dumps(data, indent=4, ensure_ascii=False) return dataJson + +def get_list_of_formats(): + """Return list of formats that can be chosen + + The list is generated from the json files in the formats folder""" + format_dir = pathlib.Path(__file__).parent / "formats" + return [file.name[:-5] for file in format_dir.glob("*.json")] -- GitLab