blob: e12e7d24cb469e7bb1774764c7b3f07ef4d3a57d [file] [log] [blame]
Cole Faust5c503d12023-01-24 11:48:08 -08001#!/usr/bin/env python3
2# Copyright 2023 Google Inc. All rights reserved.
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
16import argparse
17import py_compile
18import os
19import shutil
20import tempfile
21import zipfile
22
23# This file needs to support both python 2 and 3.
24
25
26def process_one_file(name, inf, outzip):
27 if not name.endswith('.py'):
28 outzip.writestr(name, inf.read())
29 return
30
31 # Unfortunately py_compile requires the input/output files to be written
32 # out to disk.
33 with tempfile.NamedTemporaryFile(prefix="Soong_precompile_", delete=False) as tmp:
34 shutil.copyfileobj(inf, tmp)
35 in_name = tmp.name
36 with tempfile.NamedTemporaryFile(prefix="Soong_precompile_", delete=False) as tmp:
37 out_name = tmp.name
38 try:
39 py_compile.compile(in_name, out_name, name, doraise=True)
40 with open(out_name, 'rb') as f:
41 outzip.writestr(name + 'c', f.read())
42 finally:
43 os.remove(in_name)
44 os.remove(out_name)
45
46
47def main():
48 parser = argparse.ArgumentParser()
49 parser.add_argument('src_zip')
50 parser.add_argument('dst_zip')
51 args = parser.parse_args()
52
53 with open(args.dst_zip, 'wb') as outf, open(args.src_zip, 'rb') as inf:
54 with zipfile.ZipFile(outf, mode='w') as outzip, zipfile.ZipFile(inf, mode='r') as inzip:
55 for name in inzip.namelist():
56 with inzip.open(name, mode='r') as inzipf:
57 process_one_file(name, inzipf, outzip)
58
59
60if __name__ == "__main__":
61 main()