1# Copyright 2020 The ChromiumOS Authors 2# Use of this source code is governed by a BSD-style license that can be 3# found in the LICENSE file. 4"""IO-related helper functions.""" 5 6import json 7import pathlib 8 9from typing import Any, Dict 10 11from google.protobuf import json_format 12from google.protobuf.message import Message 13 14from chromiumos.config.payload import config_bundle_pb2 15from chromiumos.config.payload import flat_config_pb2 16 17 18def write_message_json( 19 message: Message, 20 path: pathlib.Path, 21 default_fields=False, 22 use_integers_for_enums=False, 23): 24 """Take a Message and write it to a file as json. 25 26 Args: 27 message: protobuf message to write to file 28 path: output file write json to 29 default_fields: If true, include default values for fields 30 use_integers_for_enums: If true, print integers instead of enum names. 31 """ 32 with open(path, 'w', encoding='utf-8') as outfile: 33 outfile.write( 34 json_format.MessageToJson( 35 message, 36 including_default_value_fields=default_fields, 37 sort_keys=True, 38 use_integers_for_enums=use_integers_for_enums, 39 )) 40 41 42def write_message_binary(message: Message, path: pathlib.Path): 43 """Write a Message to a file as binary wire format. 44 45 Args: 46 message: protobuf message to write to file 47 path: output file write to 48 """ 49 with open(path, 'wb') as outfile: 50 outfile.write(message.SerializeToString()) 51 52 53def read_json_proto(message, path): 54 """Read a jsonproto encoded message from a file. 55 56 Args: 57 message: an instance of the protobuffer message to read into 58 path (str): path to the json encoded message on disk. 59 60 Returns: 61 reference to message 62 """ 63 64 with open(path, 'r', encoding='utf-8') as f: 65 json_format.Parse(f.read(), message) 66 return message 67 68 69def read_config(path: str) -> config_bundle_pb2.ConfigBundle: 70 """Reads a ConfigBundle message from a jsonpb file. 71 72 Args: 73 path: Path to the json proto. 74 75 Returns: 76 ConfigBundle parsed from file. 77 """ 78 return read_json_proto( 79 config_bundle_pb2.ConfigBundle(), 80 path, 81 ) 82 83 84def read_flat_config(path: str) -> flat_config_pb2.FlatConfigList: 85 """Reads a FlatConfigList message from a jsonpb file. 86 87 Args: 88 path: Path to the json proto. 89 90 Returns: 91 FlatConfigList parsed from file. 92 """ 93 return read_json_proto( 94 flat_config_pb2.FlatConfigList(), 95 path, 96 ) 97 98 99def read_model_sku_json(factory_dir: pathlib.Path) -> Dict[str, Any]: 100 """Reads and parses the model_sku.json file. 101 102 Args: 103 factory_dir: Path to a project's factory dir. 104 105 Returns: 106 Parsed model_sku.json as a dict 107 """ 108 with open( 109 factory_dir.joinpath('generated', 'model_sku.json'), 110 encoding='utf-8') as f: 111 return json.load(f) 112