1# Copyright (C) 2024 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#      http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import json
16import os
17import pathlib
18import sys
19
20
21def OpenModuleInfoFile():
22    product_out = os.getenv("ANDROID_PRODUCT_OUT")
23    if not product_out:
24        if os.getenv("QUIET_VERIFYMODINFO") != "true":
25            sys.stderr.write("No ANDROID_PRODUCT_OUT. Try running 'lunch' first.\n")
26        sys.exit(1)
27    try:
28        return open(pathlib.Path(product_out) / "module-info.json")
29    except (FileNotFoundError, PermissionError):
30        if os.getenv("QUIET_VERIFYMODINFO") != "true":
31            sys.stderr.write("Could not find module-info.json. Please run 'refreshmod' first.\n")
32        sys.exit(1)
33
34
35def ReadModuleInfo():
36    with OpenModuleInfoFile() as f:
37        return json.load(f)
38
39def GetModule(modules, module_name):
40    if module_name not in modules:
41        sys.stderr.write(f"Could not find module '{module_name}' (try 'refreshmod' if there have been build changes?)\n")
42        sys.exit(1)
43    return modules[module_name]
44
45