1#!/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
17import apex_manifest_pb2
18from google.protobuf import message
19from google.protobuf.json_format import MessageToJson
20import zipfile
21
22class ApexManifestError(Exception):
23
24  def __init__(self, errmessage):
25    # Apex Manifest parse error (extra fields) or if required fields not present
26    self.errmessage = errmessage
27
28
29def ValidateApexManifest(file):
30  try:
31    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:
35    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
47
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)