Andrew Lamb | eceaec0 | 2020-02-11 14:16:41 -0700 | [diff] [blame] | 1 | # 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 | |
| 6 | import os |
| 7 | |
Prathmesh Prabhu | 72f8a00 | 2020-04-10 09:57:53 -0700 | [diff] [blame] | 8 | from chromiumos.config.payload import config_bundle_pb2 |
Andrew Lamb | eceaec0 | 2020-02-11 14:16:41 -0700 | [diff] [blame] | 9 | |
David Burger | 54f704e | 2020-04-30 13:33:47 -0600 | [diff] [blame^] | 10 | from google.protobuf import json_format |
| 11 | |
Andrew Lamb | eceaec0 | 2020-02-11 14:16:41 -0700 | [diff] [blame] | 12 | |
Andrew Lamb | 9328c40 | 2020-03-05 12:57:59 -0700 | [diff] [blame] | 13 | def read_config(path: str) -> config_bundle_pb2.ConfigBundle: |
David Burger | 54f704e | 2020-04-30 13:33:47 -0600 | [diff] [blame^] | 14 | """Reads a json proto from a file. |
Andrew Lamb | 9328c40 | 2020-03-05 12:57:59 -0700 | [diff] [blame] | 15 | |
Andrew Lamb | eceaec0 | 2020-02-11 14:16:41 -0700 | [diff] [blame] | 16 | Args: |
David Burger | 54f704e | 2020-04-30 13:33:47 -0600 | [diff] [blame^] | 17 | path: Path to the json proto. See note above about deprecated repo |
Andrew Lamb | 9328c40 | 2020-03-05 12:57:59 -0700 | [diff] [blame] | 18 | root behavior. |
Andrew Lamb | eceaec0 | 2020-02-11 14:16:41 -0700 | [diff] [blame] | 19 | """ |
David Burger | 54f704e | 2020-04-30 13:33:47 -0600 | [diff] [blame^] | 20 | 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 | |
| 28 | def _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 | |
| 35 | def _read_binary_config(path: str) -> config_bundle_pb2.ConfigBundle: |
Andrew Lamb | eceaec0 | 2020-02-11 14:16:41 -0700 | [diff] [blame] | 36 | project_config = config_bundle_pb2.ConfigBundle() |
Andrew Lamb | 9328c40 | 2020-03-05 12:57:59 -0700 | [diff] [blame] | 37 | with open(os.path.join(path), 'rb') as f: |
Andrew Lamb | eceaec0 | 2020-02-11 14:16:41 -0700 | [diff] [blame] | 38 | project_config.ParseFromString(f.read()) |
| 39 | return project_config |