blob: 4ee18700b302bd2189cc0245fab03eb25985dafe [file] [log] [blame]
Dario Freniadbee5d2018-12-27 12:44:01 +00001#!/usr/bin/env python
2#
3# Copyright (C) 2018 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
Abhijeet Kaura9716132019-01-04 09:02:31 +000017import apex_manifest_pb2
Jooyung Hancd4d81e2019-11-02 02:47:22 +090018from google.protobuf import message
Jooyung Han4ebf2192019-12-03 19:28:12 +090019from google.protobuf.json_format import MessageToJson
20import zipfile
Jiyong Park34c821c2019-06-03 21:36:53 +090021
Dario Freniadbee5d2018-12-27 12:44:01 +000022class ApexManifestError(Exception):
Jiyong Park34c821c2019-06-03 21:36:53 +090023
24 def __init__(self, errmessage):
25 # Apex Manifest parse error (extra fields) or if required fields not present
26 self.errmessage = errmessage
27
Dario Freniadbee5d2018-12-27 12:44:01 +000028
Jooyung Hancd4d81e2019-11-02 02:47:22 +090029def ValidateApexManifest(file):
Jiyong Park34c821c2019-06-03 21:36:53 +090030 try:
Jooyung Hancd4d81e2019-11-02 02:47:22 +090031 with open(file, "rb") as f:
32 manifest_pb = apex_manifest_pb2.ApexManifest()
33 manifest_pb.ParseFromString(f.read())
34 except message.DecodeError as err:
Jiyong Park34c821c2019-06-03 21:36:53 +090035 raise ApexManifestError(err)
36 # Checking required fields
37 if manifest_pb.name == "":
38 raise ApexManifestError("'name' field is required.")
39 if manifest_pb.version == 0:
40 raise ApexManifestError("'version' field is required.")
41 if manifest_pb.noCode and (manifest_pb.preInstallHook or
42 manifest_pb.postInstallHook):
43 raise ApexManifestError(
44 "'noCode' can't be true when either preInstallHook or postInstallHook is set"
45 )
46 return manifest_pb
Jooyung Han4ebf2192019-12-03 19:28:12 +090047
48def fromApex(apexFilePath):
49 with zipfile.ZipFile(apexFilePath, 'r') as apexFile:
50 with apexFile.open('apex_manifest.pb') as manifestFile:
51 manifest = apex_manifest_pb2.ApexManifest()
52 manifest.ParseFromString(manifestFile.read())
53 return manifest
54
55def toJsonString(manifest):
56 return MessageToJson(manifest, indent=2)