1 /*
2  * Copyright (C) 2017 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 com.android.loganalysis.parser;
17 
18 import com.android.loganalysis.item.AppVersionItem;
19 import com.android.loganalysis.item.DumpsysPackageStatsItem;
20 
21 import java.util.List;
22 import java.util.regex.Matcher;
23 import java.util.regex.Pattern;
24 
25 /** A {@link IParser} to parse package stats and create a mapping table of packages and versions */
26 public class DumpsysPackageStatsParser implements IParser {
27 
28     /** Matches: Package [com.google.android.googlequicksearchbox] (607929e): */
29     private static final Pattern PACKAGE_NAME = Pattern.compile("^\\s*Package \\[(.*)\\].*");
30 
31     /** Matches: versionCode=300734793 minSdk=10000 targetSdk=10000 */
32     private static final Pattern VERSION_CODE = Pattern.compile("^\\s*versionCode=(\\d+).*");
33 
34     /** Matches: versionName=6.16.35.26.arm64 */
35     private static final Pattern VERSION_NAME = Pattern.compile("^\\s*versionName=(.*)$");
36 
37     /**
38      * {@inheritDoc}
39      *
40      * @return The {@link DumpsysPackageStatsItem}.
41      */
42     @Override
parse(List<String> lines)43     public DumpsysPackageStatsItem parse(List<String> lines) {
44         DumpsysPackageStatsItem item = new DumpsysPackageStatsItem();
45         String packageName = null;
46         String versionCode = null;
47         String versionName = null;
48 
49         for (String line : lines) {
50             Matcher m = PACKAGE_NAME.matcher(line);
51             if (m.matches()) {
52                 packageName = m.group(1);
53                 versionCode = null;
54                 versionName = null;
55                 continue;
56             }
57             m = VERSION_CODE.matcher(line);
58             if (m.matches()) {
59                 versionCode = m.group(1);
60                 continue;
61             }
62             m = VERSION_NAME.matcher(line);
63             if (m.matches()) {
64                 versionName = m.group(1).trim();
65                 if (packageName != null && versionCode != null) {
66                     item.put(
67                             packageName,
68                             new AppVersionItem(Integer.parseInt(versionCode), versionName));
69                 }
70                 packageName = null;
71             }
72         }
73         return item;
74     }
75 }
76