aboutsummaryrefslogtreecommitdiff
path: root/python/scripts/precompile_python.py
diff options
context:
space:
mode:
authorGeorge Zacharia <george.zcharia@gmail.com>2024-06-30 21:31:39 +0530
committerGeorge Zacharia <george.zcharia@gmail.com>2024-06-30 21:31:39 +0530
commit5cf52b53bd3c1ffdf1f0b505b08cd9765ad1cc0d (patch)
tree612a855b839f086862ec76805da2547c94eef94c /python/scripts/precompile_python.py
parente867a64ffb8fc36f0e39c3a4fe5b98104bffda2f (diff)
parent8bf89894cce3b5387e548a325febf7029828875c (diff)
Merge tag 'android-14.0.0_r50' of https://android.googlesource.com/platform/build/soong into u14.0
Android 14.0.0 Release 50 (AP2A.240605.024)
Diffstat (limited to 'python/scripts/precompile_python.py')
-rw-r--r--python/scripts/precompile_python.py25
1 files changed, 19 insertions, 6 deletions
diff --git a/python/scripts/precompile_python.py b/python/scripts/precompile_python.py
index e12e7d24c..aa1a5df53 100644
--- a/python/scripts/precompile_python.py
+++ b/python/scripts/precompile_python.py
@@ -16,6 +16,7 @@
import argparse
import py_compile
import os
+import sys
import shutil
import tempfile
import zipfile
@@ -23,22 +24,34 @@ import zipfile
# This file needs to support both python 2 and 3.
-def process_one_file(name, inf, outzip):
- if not name.endswith('.py'):
- outzip.writestr(name, inf.read())
+def process_one_file(name, infile, outzip):
+ # Create a ZipInfo instance with a fixed date to ensure a deterministic output.
+ # Date was chosen to be the same as
+ # https://cs.android.com/android/platform/superproject/main/+/main:build/soong/jar/jar.go;l=36;drc=2863e4535eb65e15f955dc8ed48fa99b1d2a1db5
+ info = zipfile.ZipInfo(filename=name, date_time=(2008, 1, 1, 0, 0, 0))
+
+ if not info.filename.endswith('.py'):
+ outzip.writestr(info, infile.read())
return
# Unfortunately py_compile requires the input/output files to be written
# out to disk.
with tempfile.NamedTemporaryFile(prefix="Soong_precompile_", delete=False) as tmp:
- shutil.copyfileobj(inf, tmp)
+ shutil.copyfileobj(infile, tmp)
in_name = tmp.name
with tempfile.NamedTemporaryFile(prefix="Soong_precompile_", delete=False) as tmp:
out_name = tmp.name
try:
- py_compile.compile(in_name, out_name, name, doraise=True)
+ # Ensure a deterministic .pyc output by using the hash rather than the timestamp.
+ # Only works on Python 3.7+
+ # See https://docs.python.org/3/library/py_compile.html#py_compile.PycInvalidationMode
+ if sys.version_info >= (3, 7):
+ py_compile.compile(in_name, out_name, info.filename, doraise=True, invalidation_mode=py_compile.PycInvalidationMode.CHECKED_HASH)
+ else:
+ py_compile.compile(in_name, out_name, info.filename, doraise=True)
with open(out_name, 'rb') as f:
- outzip.writestr(name + 'c', f.read())
+ info.filename = info.filename + 'c'
+ outzip.writestr(info, f.read())
finally:
os.remove(in_name)
os.remove(out_name)