blob: ee43989d683eb497e014def5a5fe9b3de4546435 [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
David Burger54f704e2020-04-30 13:33:47 -060011from google.protobuf import json_format
Sean McAllister576d80c2020-05-29 13:00:19 -060012from google.protobuf.message import Message
13
Andrew Lamb0ed1b902020-06-08 17:03:47 -060014from chromiumos.config.payload import config_bundle_pb2
15
16
Sean McAllister576d80c2020-05-29 13:00:19 -060017
18def write_message_json(message: Message, path: pathlib.Path, \
19 default_fields=False):
20 """Take a Message and write it to a file as json.
21
22 Args:
23 message: protobuf message to write to file
24 path: output file write json to
25 default_fields: If true, include default values for fields
26 """
27 # ow this is a long parameter
28 opts = {'including_default_value_fields': default_fields, 'sort_keys': True}
29
30 with open(path, 'w') as outfile:
31 outfile.write(json_format.MessageToJson(message, **opts))
David Burger54f704e2020-04-30 13:33:47 -060032
Andrew Lambeceaec02020-02-11 14:16:41 -070033
Andrew Lamb9328c402020-03-05 12:57:59 -070034def read_config(path: str) -> config_bundle_pb2.ConfigBundle:
Sean McAllister576d80c2020-05-29 13:00:19 -060035 """Reads a ConfigBundle mesage from a jsonpb file.
Andrew Lamb9328c402020-03-05 12:57:59 -070036
Sean McAllister576d80c2020-05-29 13:00:19 -060037 Args:
38 path: Path to the json proto. See note above about deprecated repo
39 root behavior.
40
41 Returns:
42 ConfigBundle parsed from file.
43 """
David Burger54f704e2020-04-30 13:33:47 -060044 project_config = config_bundle_pb2.ConfigBundle()
45 with open(path, 'r') as f:
46 json_format.Parse(f.read(), project_config)
47 return project_config
Andrew Lamb5d132052020-05-29 14:49:06 -060048
49
Sean McAllister576d80c2020-05-29 13:00:19 -060050def read_model_sku_json(factory_dir: pathlib.Path) -> Dict[str, Any]:
Andrew Lamb5d132052020-05-29 14:49:06 -060051 """Reads and parses the model_sku.json file.
52
53 Args:
Sean McAllister576d80c2020-05-29 13:00:19 -060054 factory_dir: Path to a project's factory dir.
55
56 Returns:
57 Parsed model_sku.json as a dict
Andrew Lamb5d132052020-05-29 14:49:06 -060058 """
59 with open(factory_dir.joinpath('generated', 'model_sku.json')) as f:
60 return json.load(f)