Source code for schrodinger.utils.featureflags.write

"""
Utility functions to read and write features.json files. No
dependencies on schrodinger.
"""

import argparse
import json
import logging
import os
import sys

logger = logging.getLogger()


[docs]def format_json(json_data): """ Convert json data into a formatted string. :type json_data: list[dict] :param json_data: List of features to write to the file. :returntype: str :return: String of formatted json, ready for writing to disk """ sorted_flags = sorted(json_data, key=lambda x: x['Feature']) return json.dumps(sorted_flags, ensure_ascii=False, indent=2, sort_keys=True)
[docs]def write_features_json(json_data, filename): """ Write the json data to the user state file in UTF-8 encoding. :type json_data: list[dict] :param json_data: List of features to write to the file. :type filename: str :param filename: File to write the features to. :raise IOError: if json data cannot be written to the file. """ formatted_json = format_json(json_data) d = os.path.dirname(filename) os.makedirs(os.path.dirname(filename), exist_ok=True) with open(filename, "w", encoding="utf-8", newline="\n") as json_fp: json_fp.write(formatted_json) json_fp.write("\n")
[docs]def read_json_data(json_data_file): """ Read feature flags data from json document. :type json_data_file: str :param json_data_file: File name to decode feature flags json document. :returntype: dict :return: Dictionary of feature name and its corresponding json item. :raise ValueError: if json document cannot be parsed. """ try: with open(json_data_file, encoding="utf-8", newline="\n") as json_fp: json_data = json_fp.read() except OSError: return {} if not json_data: return {} featureflags = json.loads(json_data) fflags = {} ignore_items = [] for pos, item in enumerate(featureflags): if not all(key in item for key in ("Feature", "Enabled")): ignore_items.append((pos, item)) continue fflags[item['Feature']] = item if ignore_items: logger.warning("WARNING: Ignoring bad feature flags format for the " "following item(s) in '%s' - " % json_data_file) for (pos, item) in ignore_items: logger.warning("%-10sIndex %d - %s" % ('', pos, item)) logger.warning('') return fflags
[docs]def main(): desc = "Read featureflags json file and print formatted version to stdout." parser = argparse.ArgumentParser(description=desc) parser.add_argument('input', type=str, metavar='featureflags.json', help='input featureflags json file') parser.add_argument('--in-place', action='store_true', help='overwrite input file with formated json') opts = parser.parse_args() json_data = read_json_data(opts.input).values() if opts.in_place: write_features_json(json_data, opts.input) else: print(format_json(json_data), file=sys.stdout)
if __name__ == '__main__': main()