blob: 7b50dcdb2bfbec10feeb0e7d52e810c0cc7e83db [file] [log] [blame]
Andrew Lambeceaec02020-02-11 14:16:41 -07001# Copyright 2020 The Chromium OS Authors. All rights reserved.
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
Andrew Lamb5d132052020-05-29 14:49:06 -06006import json
7import pathlib
Andrew Lambeceaec02020-02-11 14:16:41 -07008
Sean McAllister576d80c2020-05-29 13:00:19 -06009from typing import Any, Dict
10
Prathmesh Prabhu72f8a002020-04-10 09:57:53 -070011from chromiumos.config.payload import config_bundle_pb2
Andrew Lambeceaec02020-02-11 14:16:41 -070012
David Burger54f704e2020-04-30 13:33:47 -060013from google.protobuf import json_format
Sean McAllister576d80c2020-05-29 13:00:19 -060014from google.protobuf.message import Message
15
16
17def write_message_json(message: Message, path: pathlib.Path, \
18 default_fields=False):
19 """Take a Message and write it to a file as json.
20
21 Args:
22 message: protobuf message to write to file
23 path: output file write json to
24 default_fields: If true, include default values for fields
25 """
26 # ow this is a long parameter
27 opts = {'including_default_value_fields': default_fields, 'sort_keys': True}
28
29 with open(path, 'w') as outfile:
30 outfile.write(json_format.MessageToJson(message, **opts))
David Burger54f704e2020-04-30 13:33:47 -060031
Andrew Lambeceaec02020-02-11 14:16:41 -070032
Andrew Lamb9328c402020-03-05 12:57:59 -070033def read_config(path: str) -> config_bundle_pb2.ConfigBundle:
Sean McAllister576d80c2020-05-29 13:00:19 -060034 """Reads a ConfigBundle mesage from a jsonpb file.
Andrew Lamb9328c402020-03-05 12:57:59 -070035
Sean McAllister576d80c2020-05-29 13:00:19 -060036 Args:
37 path: Path to the json proto. See note above about deprecated repo
38 root behavior.
39
40 Returns:
41 ConfigBundle parsed from file.
42 """
David Burger54f704e2020-04-30 13:33:47 -060043 project_config = config_bundle_pb2.ConfigBundle()
44 with open(path, 'r') as f:
45 json_format.Parse(f.read(), project_config)
46 return project_config
Andrew Lamb5d132052020-05-29 14:49:06 -060047
48
Sean McAllister576d80c2020-05-29 13:00:19 -060049def read_model_sku_json(factory_dir: pathlib.Path) -> Dict[str, Any]:
Andrew Lamb5d132052020-05-29 14:49:06 -060050 """Reads and parses the model_sku.json file.
51
52 Args:
Sean McAllister576d80c2020-05-29 13:00:19 -060053 factory_dir: Path to a project's factory dir.
54
55 Returns:
56 Parsed model_sku.json as a dict
Andrew Lamb5d132052020-05-29 14:49:06 -060057 """
58 with open(factory_dir.joinpath('generated', 'model_sku.json')) as f:
59 return json.load(f)