blob: 12252a3e97a4c70321a8bb85ca9684d2b7370f6d [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
6import os
7
Prathmesh Prabhu72f8a002020-04-10 09:57:53 -07008from chromiumos.config.payload import config_bundle_pb2
Andrew Lambeceaec02020-02-11 14:16:41 -07009
David Burger54f704e2020-04-30 13:33:47 -060010from google.protobuf import json_format
11
Andrew Lambeceaec02020-02-11 14:16:41 -070012
Andrew Lamb9328c402020-03-05 12:57:59 -070013def read_config(path: str) -> config_bundle_pb2.ConfigBundle:
David Burger54f704e2020-04-30 13:33:47 -060014 """Reads a json proto from a file.
Andrew Lamb9328c402020-03-05 12:57:59 -070015
Andrew Lambeceaec02020-02-11 14:16:41 -070016 Args:
David Burger54f704e2020-04-30 13:33:47 -060017 path: Path to the json proto. See note above about deprecated repo
Andrew Lamb9328c402020-03-05 12:57:59 -070018 root behavior.
Andrew Lambeceaec02020-02-11 14:16:41 -070019 """
David Burger54f704e2020-04-30 13:33:47 -060020 try:
21 return _read_json_config(path)
22 except:
23 # TODO(crbug.com/1073530): remove binary pb fallback when transition to
24 # json pb is complete.
25 return _read_binary_config(path)
26
27
28def _read_json_config(path: str) -> config_bundle_pb2.ConfigBundle:
29 project_config = config_bundle_pb2.ConfigBundle()
30 with open(path, 'r') as f:
31 json_format.Parse(f.read(), project_config)
32 return project_config
33
34
35def _read_binary_config(path: str) -> config_bundle_pb2.ConfigBundle:
Andrew Lambeceaec02020-02-11 14:16:41 -070036 project_config = config_bundle_pb2.ConfigBundle()
Andrew Lamb9328c402020-03-05 12:57:59 -070037 with open(os.path.join(path), 'rb') as f:
Andrew Lambeceaec02020-02-11 14:16:41 -070038 project_config.ParseFromString(f.read())
39 return project_config