1/*
2 * Copyright (C) 2018 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
17package com.android.sdkparcelables
18
19import org.objectweb.asm.ClassReader
20import org.objectweb.asm.Opcodes
21import java.io.File
22import java.io.IOException
23import java.util.zip.ZipFile
24
25fun main(args: Array<String>) {
26    if (args.size != 2) {
27        usage()
28    }
29
30    val zipFileName = args[0]
31    val aidlFileName = args[1]
32
33    val zipFile: ZipFile
34
35    try {
36        zipFile = ZipFile(zipFileName)
37    } catch (e: IOException) {
38        System.err.println("error reading input jar: ${e.message}")
39        kotlin.system.exitProcess(2)
40    }
41
42    val ancestorCollector = AncestorCollector(Opcodes.ASM6, null)
43
44    for (entry in zipFile.entries()) {
45        if (entry.name.endsWith(".class")) {
46            val reader = ClassReader(zipFile.getInputStream(entry))
47            reader.accept(ancestorCollector,
48                    ClassReader.SKIP_CODE or ClassReader.SKIP_DEBUG or ClassReader.SKIP_FRAMES)
49        }
50    }
51
52    val parcelables = ParcelableDetector.ancestorsToParcelables(ancestorCollector.ancestors)
53
54    try {
55        val outFile = File(aidlFileName)
56        val outWriter = outFile.bufferedWriter()
57        for (parcelable in parcelables) {
58            outWriter.write("parcelable ")
59            outWriter.write(parcelable.replace('/', '.').replace('$', '.'))
60            outWriter.write(";\n")
61        }
62        outWriter.flush()
63    } catch (e: IOException) {
64        System.err.println("error writing output aidl: ${e.message}")
65        kotlin.system.exitProcess(2)
66    }
67}
68
69fun usage() {
70    System.err.println("Usage: <input jar> <output aidl>")
71    kotlin.system.exitProcess(1)
72}
73