1 /* 2 * Copyright (C) 2024 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package android.aconfig; 17 18 import android.aconfig.nano.Aconfig.parsed_flag; 19 import android.aconfig.nano.Aconfig.parsed_flags; 20 21 import java.io.File; 22 import java.io.FileInputStream; 23 import java.io.IOException; 24 import java.util.ArrayList; 25 import java.util.Arrays; 26 import java.util.List; 27 28 /** @hide */ 29 public class DeviceProtosTestUtil { 30 public static final String[] PATHS = { 31 TEMPLATE 32 }; 33 34 private static final String APEX_DIR = "/apex/"; 35 private static final String APEX_ACONFIG_PATH_SUFFIX = "/etc/aconfig_flags.pb"; 36 private static final String SYSTEM_APEX_DIR = "/system/apex"; 37 38 /** 39 * Returns a list of all on-device aconfig protos. 40 * 41 * <p>May throw an exception if the protos can't be read at the call site. For example, some of 42 * the protos are in the apex/ partition, which is mounted somewhat late in the boot process. 43 * 44 * @throws IOException if we can't read one of the protos yet 45 * @return a list of all on-device aconfig protos 46 */ loadAndParseFlagProtos()47 public static List<parsed_flag> loadAndParseFlagProtos() throws IOException { 48 ArrayList<parsed_flag> result = new ArrayList(); 49 50 for (String path : parsedFlagsProtoPaths()) { 51 try (FileInputStream inputStream = new FileInputStream(path)) { 52 parsed_flags parsedFlags = parsed_flags.parseFrom(inputStream.readAllBytes()); 53 for (parsed_flag flag : parsedFlags.parsedFlag) { 54 result.add(flag); 55 } 56 } 57 } 58 59 return result; 60 } 61 62 /** 63 * Returns the list of all on-device aconfig protos paths. 64 * 65 * @hide 66 */ parsedFlagsProtoPaths()67 public static List<String> parsedFlagsProtoPaths() { 68 ArrayList<String> paths = new ArrayList(Arrays.asList(PATHS)); 69 70 File apexDirectory = new File(SYSTEM_APEX_DIR); 71 if (!apexDirectory.isDirectory()) { 72 return paths; 73 } 74 75 File[] subdirs = apexDirectory.listFiles(); 76 if (subdirs == null) { 77 return paths; 78 } 79 80 for (File prefix : subdirs) { 81 String apexName = prefix.getName().replace("com.google", "com"); 82 apexName = apexName.substring(0, apexName.lastIndexOf('.')); 83 84 File protoPath = new File(APEX_DIR + apexName + APEX_ACONFIG_PATH_SUFFIX); 85 if (!protoPath.exists()) { 86 continue; 87 } 88 89 paths.add(protoPath.getAbsolutePath()); 90 } 91 return paths; 92 } 93 } 94