blob: 7a24809a1c9b9ebbf6cc297a98f2b2a4a08f8f7a [file] [log] [blame]
Greg Edelston9cd16f52020-11-12 10:50:28 -07001#!/usr/bin/env python3
2# Copyright 2020 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Print one platform's full config data to stdout.
7
8This script takes one platform name (and optionally a model name) as inputs,
9calculates the full config for that platform, and prints the results as
10plaintext JSON.
11
12The full config is calculated based on the fw-testing-configs inheritance
13model. Each platform config has an optional "parent" attribute. For each
14config field, if the platform does not explicitly set a value for that field,
15then the value is instead inherited from the parent config. This inheritance
16can be recursive: the parent may have a parent, and so on. At the top of the
17inheritance tree (when parent is None), any remaining fields inherit their
18values from DEFAULTS. Also, if the platform has a "models" attribute matching
19the passed-in model name, then its field-value pairs override everything else.
20"""
21
22import argparse
23import collections
24import json
25import os
26import re
27import sys
28
29
30# Regexes matching fields which describe config metadata: that is, they do not
31# contain actual config information. When calculating the final config, fields
32# matching any of these regexes will be ignored.
33META_FIELD_REGEXES = (
34 re.compile(r'^models$'),
35 re.compile(r'\.DOC$')
36)
37
38
39class PlatformNotFoundError(AttributeError):
40 """Error class for when the requested platform name is not found."""
41 pass
42
43
44def parse_args(argv):
45 """Determine input dir and output file from command-line args.
46
47 Args:
48 argv: List of command-line args, excluding the invoked script.
49 Typically, this should be set to sys.argv[1:].
50
51 Returns:
52 An argparse.Namespace with the following attributes:
53 condense_output: A bool determining whether to remove pretty
54 whitespace from the script's final output.
55 consolidated: The filepath to CONSOLIDATED.json
56 platform: The name of the board whose config should be calculated
57 model: The name of the model for the board
58
59 Raises:
60 ValueError: If the passed-in platform name ends in '.json'
61 """
62 parser = argparse.ArgumentParser()
63 parser.add_argument('platform',
64 help='The platform name to calculate a config for. '
65 'Should not include ".json" suffix.')
66 parser.add_argument('-m', '--model', default=None,
67 help='The model name of the board. If not specified, '
68 'then no model overrides will be used.')
69 parser.add_argument('-c', '--consolidated', default='CONSOLIDATED.json',
70 help='The filepath to CONSOLIDATED.json')
71 parser.add_argument('--condense-output', action='store_true',
72 help='Print the output without pretty whitespace.')
73 args = parser.parse_args(argv)
74 return args
75
76
77def calculate_field_value(consolidated_json, field, platform, model=None):
78 """Calculate a platform's ultimate value for a single field.
79
80 Args:
81 consolidated_json: The key-value contents of CONSOLIDATED.json.
82 field: The name of the JSON field to calculate.
83 platform: The name of the platform to calculate for. If the
84 platform does not define the field, then recursively check its
85 parent's config (or DEFAULTS).
86 model: The name of the model to check overrides for.
87
88 Raises:
89 PlatformNotFoundError: If platform is not in consolidated_json.
90 """
91 if platform not in consolidated_json:
92 raise PlatformNotFoundError(platform)
93
94 # Model overrides are most important.
95 # Not all models have config overrides, so it's OK for the model name not
96 # to be present in models_json.
97 models_json = consolidated_json[platform].get('models', {})
98 if field in models_json.get(model, {}):
99 return models_json[model][field]
100
101 # Then check if the platform explicitly defines the value.
102 if field in consolidated_json[platform]:
103 return consolidated_json[platform][field]
104
105 # Finally, inherit from the parent (or DEFAULTS).
106 # The DEFAULTS config contains every field name, so this will terminate the
107 # recursion.
108 parent = consolidated_json[platform].get('parent', 'DEFAULTS')
109 return calculate_field_value(consolidated_json, field, parent, model)
110
111
112def calculate_platform_json(platform, model, consolidated_fp):
113 """Calculate a platform's ultimate config values for all fields.
114
115 Args:
116 platform: The name of the platform to calculate values for.
117 model: The name of the model to check for overrides.
118 """
119 if not os.path.isfile(consolidated_fp):
120 raise FileNotFoundError(consolidated_fp)
121 with open(consolidated_fp) as consolidated_file:
122 consolidated_json = json.load(consolidated_file)
123 final_json = collections.OrderedDict()
124 for field in consolidated_json['DEFAULTS']:
125 if any(regex.search(field) for regex in META_FIELD_REGEXES):
126 continue
127 value = calculate_field_value(consolidated_json, field, platform, model)
128 final_json[field] = value
129 return final_json
130
131
132def main(argv):
133 """
134 Parse command-line args and print a JSON config to stdout.
135
136 Args:
137 argv: List of command-line args, excluding the invoked script.
138 Typically, this should be set to sys.argv[1:].
139 """
140 args = parse_args(argv)
141 j = calculate_platform_json(args.platform, args.model, args.consolidated)
142 if args.condense_output:
143 print(json.dumps(j), end='')
144 else:
145 print(json.dumps(j, indent=4))
146
147
148if __name__ == '__main__':
149 main(sys.argv[1:])