def _AddExtraJarFiles(jar_path, provider_configurations=None, file_tuples=None): with zipfile.ZipFile(jar_path, 'a') as z: for config in provider_configurations or []: zip_path = 'META-INF/services/' + os.path.basename(config) build_utils.AddToZipHermetic(z, zip_path, src_path=config) for src_path, zip_path in file_tuples or []: build_utils.AddToZipHermetic(z, zip_path, src_path=src_path)
def main(args): args = build_utils.ExpandFileArgs(args) parser = argparse.ArgumentParser() build_utils.AddDepfileOption(parser) parser.add_argument('--output', required=True, help='Path to output aar.') parser.add_argument('--jars', required=True, help='GN list of jar inputs.') parser.add_argument('--dependencies-res-zips', required=True, help='GN list of resource zips') parser.add_argument('--r-text-files', required=True, help='GN list of R.txt files to merge') parser.add_argument('--proguard-configs', required=True, help='GN list of ProGuard flag files to merge.') parser.add_argument( '--android-manifest', help='Path to AndroidManifest.xml to include.', default=os.path.join(_ANDROID_BUILD_DIR, 'AndroidManifest.xml')) options = parser.parse_args(args) options.jars = build_utils.ParseGnList(options.jars) options.dependencies_res_zips = build_utils.ParseGnList( options.dependencies_res_zips) options.r_text_files = build_utils.ParseGnList(options.r_text_files) options.proguard_configs = build_utils.ParseGnList(options.proguard_configs) with tempfile.NamedTemporaryFile(delete=False) as staging_file: try: with zipfile.ZipFile(staging_file.name, 'w') as z: build_utils.AddToZipHermetic( z, 'AndroidManifest.xml', src_path=options.android_manifest) with tempfile.NamedTemporaryFile() as jar_file: build_utils.MergeZips(jar_file.name, options.jars) build_utils.AddToZipHermetic(z, 'classes.jar', src_path=jar_file.name) build_utils.AddToZipHermetic( z, 'R.txt', data=_MergeRTxt(options.r_text_files)) build_utils.AddToZipHermetic(z, 'public.txt', data='') if options.proguard_configs: build_utils.AddToZipHermetic( z, 'proguard.txt', data=_MergeProguardConfigs(options.proguard_configs)) _AddResources(z, options.dependencies_res_zips) except: os.unlink(staging_file.name) raise shutil.move(staging_file.name, options.output) if options.depfile: all_inputs = (options.jars + options.dependencies_res_zips + options.r_text_files + options.proguard_configs) build_utils.WriteDepfile(options.depfile, options.output, all_inputs)
def _CreateJarFile(jar_path, provider_configurations, additional_jar_files, classes_dir): logging.info('Start creating jar file: %s', jar_path) with build_utils.AtomicOutput(jar_path) as f: with zipfile.ZipFile(f.name, 'w') as z: build_utils.ZipDir(z, classes_dir) if provider_configurations: for config in provider_configurations: zip_path = 'META-INF/services/' + os.path.basename(config) build_utils.AddToZipHermetic(z, zip_path, src_path=config) if additional_jar_files: for src_path, zip_path in additional_jar_files: build_utils.AddToZipHermetic(z, zip_path, src_path=src_path) logging.info('Completed jar file: %s', jar_path)
def DoMain(argv): global COWBOY usage = 'usage: %prog [options] [output_dir] input_file(s)...' parser = optparse.OptionParser(usage=usage) build_utils.AddDepfileOption(parser) parser.add_option('--cowboy', help="Whether building for Cowboy and Terrace") parser.add_option('--srcjar', help='When specified, a .srcjar at the given path is ' 'created instead of individual .java files.') options, args = parser.parse_args(argv) COWBOY = options.cowboy == '1' if not args: parser.error('Need to specify at least one input file') input_paths = args with zipfile.ZipFile(options.srcjar, 'w', zipfile.ZIP_STORED) as srcjar: for output_path, data in DoGenerate(input_paths): if COWBOY: full_path = os.path.join(os.getcwd(), 'gen/enums', output_path) build_utils.MakeDirectory(os.path.dirname(full_path)) with open(full_path, 'w') as out_file: out_file.write(data) build_utils.AddToZipHermetic(srcjar, output_path, data=data) if options.depfile: build_utils.WriteDepfile(options.depfile, options.srcjar)
def copy_resource(zipinfo, out_dir=''): compress = zipinfo.compress_type != zipfile.ZIP_STORED build_utils.AddToZipHermetic(out_apk, out_dir + zipinfo.filename, data=resource_apk.read( zipinfo.filename), compress=compress)
def main(argv): option_parser = optparse.OptionParser() option_parser.add_option('--aidl-path', help='Path to the aidl binary.') option_parser.add_option('--imports', help='Files to import.') option_parser.add_option('--includes', help='Directories to add as import search paths.') option_parser.add_option('--srcjar', help='Path for srcjar output.') options, args = option_parser.parse_args(argv[1:]) with build_utils.TempDir() as temp_dir: for f in args: classname = os.path.splitext(os.path.basename(f))[0] output = os.path.join(temp_dir, classname + '.java') aidl_cmd = [options.aidl_path] aidl_cmd += [ '-p' + s for s in build_utils.ParseGnList(options.imports) ] if options.includes is not None: aidl_cmd += [ '-I' + s for s in build_utils.ParseGnList(options.includes) ] aidl_cmd += [f, output] build_utils.CheckOutput(aidl_cmd) with build_utils.AtomicOutput(options.srcjar) as f: with zipfile.ZipFile(f, 'w') as srcjar: for path in build_utils.FindInDirectory(temp_dir, '*.java'): with open(path) as fileobj: data = fileobj.read() pkg_name = re.search(r'^\s*package\s+(.*?)\s*;', data, re.M).group(1) arcname = '%s/%s' % (pkg_name.replace( '.', '/'), os.path.basename(path)) build_utils.AddToZipHermetic(srcjar, arcname, data=data)
def main(): parser = argparse.ArgumentParser() parser.add_argument('--module', required=True, help='The module name.') parser.add_argument('--libraries', required=True, help='GN list of native library paths.') parser.add_argument('--output', required=True, help='Path to the generated srcjar file.') options = parser.parse_args(build_utils.ExpandFileArgs(sys.argv[1:])) options.libraries = build_utils.ParseGnList(options.libraries) libraries = [] for path in options.libraries: path = path.strip() filename = os.path.split(path)[1] assert filename.startswith('lib') assert filename.endswith('.so') # Remove lib prefix and .so suffix. libraries += [filename[3:-3]] format_dict = { 'MODULE': options.module, 'LIBRARIES': ','.join(['"%s"' % l for l in libraries]), } with build_utils.AtomicOutput(options.output) as f: with zipfile.ZipFile(f.name, 'w') as srcjar_file: build_utils.AddToZipHermetic( srcjar_file, 'org/chromium/components/module_installer/builder/' 'ModuleDescriptor_%s.java' % options.module, data=_TEMPLATE.format(**format_dict))
def _AddNativeLibraries(out_apk, native_libs, android_abi, uncompress): """Add native libraries to APK.""" has_crazy_linker = any('android_linker' in os.path.basename(p) for p in native_libs) has_monochrome = any('monochrome' in os.path.basename(p) for p in native_libs) for path in native_libs: basename = os.path.basename(path) compress = None if uncompress and os.path.splitext(basename)[1] == '.so': # Trichrome if has_crazy_linker and has_monochrome: compress = False elif ( 'android_linker' not in basename and (not has_crazy_linker or 'clang_rt' not in basename) and (not has_crazy_linker or 'crashpad_handler' not in basename)): compress = False if has_crazy_linker and not has_monochrome: basename = 'crazy.' + basename apk_path = 'lib/%s/%s' % (android_abi, basename) build_utils.AddToZipHermetic(out_apk, apk_path, src_path=path, compress=compress)
def _AddAssets(apk, path_tuples, disable_compression=False): """Adds the given paths to the apk. Args: apk: ZipFile to write to. paths: List of paths (with optional :zipPath suffix) to add. disable_compression: Whether to disable compression. """ # Group all uncompressed assets together in the hope that it will increase # locality of mmap'ed files. for target_compress in (False, True): for src_path, dest_path in path_tuples: compress = not disable_compression and ( os.path.splitext(src_path)[1] not in _NO_COMPRESS_EXTENSIONS) if target_compress == compress: apk_path = 'assets/' + dest_path try: apk.getinfo(apk_path) # Should never happen since write_build_config.py handles merging. raise Exception( 'Multiple targets specified the asset path: %s' % apk_path) except KeyError: build_utils.AddToZipHermetic(apk, apk_path, src_path=src_path, compress=compress)
def AddDiffFiles(diff_files, tmp_dir_32, out_zip, uncompress_shared_libraries): """ Insert files only present in 32-bit APK into 64-bit APK (tmp_apk). """ for diff_file in diff_files: compress = not uncompress_shared_libraries and diff_file.endswith('.so') build_utils.AddToZipHermetic(out_zip, diff_file, os.path.join(tmp_dir_32, diff_file), compress=compress)
def _AddLocaleResourceFileToZip(out_zip, android_locale, locale): locale_data = _GenerateLocaleStringsXml(locale) if android_locale: zip_path = 'values-%s/strings.xml' % android_locale else: zip_path = 'values/strings.xml' build_utils.AddToZipHermetic(out_zip, zip_path, data=locale_data, compress=False)
def _DoWriteJarOutput(output_path, constant_definition): folder = os.path.dirname(output_path) if folder and not os.path.exists(folder): os.makedirs(folder) with zipfile.ZipFile(output_path, 'w') as srcjar: path = '%s/%s' % (PACKAGE.replace('.', '/'), CLASSNAME + '.java') data = GenerateOutput(constant_definition) build_utils.AddToZipHermetic(srcjar, path, data=data)
def _CreateJarFile(jar_path, service_provider_configuration_dir, additional_jar_files, classes_dir): logging.info('Start creating jar file: %s', jar_path) with build_utils.AtomicOutput(jar_path) as f: with zipfile.ZipFile(f.name, 'w') as z: build_utils.ZipDir(z, classes_dir) if service_provider_configuration_dir: config_files = build_utils.FindInDirectory( service_provider_configuration_dir) for config_file in config_files: zip_path = os.path.relpath(config_file, service_provider_configuration_dir) build_utils.AddToZipHermetic(z, zip_path, src_path=config_file) if additional_jar_files: for src_path, zip_path in additional_jar_files: build_utils.AddToZipHermetic(z, zip_path, src_path=src_path) logging.info('Completed jar file: %s', jar_path)
def DoZip(inputs, link_inputs, zip_inputs, output, base_dir): files = [] with zipfile.ZipFile(output, 'w', zipfile.ZIP_DEFLATED) as outfile: for f in inputs: file_name = os.path.relpath(f, base_dir) files.append(file_name) build_utils.AddToZipHermetic(outfile, file_name, f) for f in link_inputs: realf = os.path.realpath(f) # Resolve symlinks. file_name = os.path.relpath(realf, base_dir) files.append(file_name) build_utils.AddToZipHermetic(outfile, file_name, realf) for zf_name in zip_inputs: with zipfile.ZipFile(zf_name, 'r') as zf: for f in zf.namelist(): if f not in files: files.append(f) build_utils.AddToZipHermetic(outfile, f, data=zf.read(f))
def _Generate(java_file_paths, srcjar_path, proxy_opts, header_path=None, namespace=''): """Generates files required to perform JNI registration. Generates a srcjar containing a single class, GEN_JNI, that contains all native method declarations. Optionally generates a header file that provides functions (RegisterMainDexNatives and RegisterNonMainDexNatives) to perform JNI registration. Args: java_file_paths: A list of java file paths. srcjar_path: Path to the GEN_JNI srcjar. header_path: If specified, generates a header file in this location. namespace: If specified, sets the namespace for the generated header file. """ # Without multiprocessing, script takes ~13 seconds for chrome_public_apk # on a z620. With multiprocessing, takes ~2 seconds. pool = multiprocessing.Pool() results = [] for d in pool.imap_unordered( functools.partial(_DictForPath, use_proxy_hash=proxy_opts.use_hash), java_file_paths): if d: results.append(d) pool.close() # Sort to make output deterministic. results.sort(key=lambda d: d['FULL_CLASS_NAME']) combined_dict = {} for key in MERGEABLE_KEYS: combined_dict[key] = ''.join(d.get(key, '') for d in results) if header_path: combined_dict['HEADER_GUARD'] = \ os.path.splitext(header_path)[0].replace('/', '_').upper() + '_' combined_dict['NAMESPACE'] = namespace header_content = CreateFromDict(combined_dict, proxy_opts.use_hash) with build_utils.AtomicOutput(header_path, mode='w') as f: f.write(header_content) with build_utils.AtomicOutput(srcjar_path) as f: with zipfile.ZipFile(f, 'w') as srcjar: build_utils.AddToZipHermetic( srcjar, '%s.java' % jni_generator.ProxyHelpers.GetQualifiedClass( proxy_opts.use_hash), data=CreateProxyJavaFromDict(combined_dict, proxy_opts))
def main(): parser = argparse.ArgumentParser() build_utils.AddDepfileOption(parser) parser.add_argument('--module', required=True, help='The module name.') parser.add_argument('--libraries-file', required=True, help='Path to file with GN list of library paths') parser.add_argument('--paks', help='GN list of PAK file paths') parser.add_argument('--output', required=True, help='Path to the generated srcjar file.') parser.add_argument( '--load-native-on-get-impl', action='store_true', default=False, help='Load module automatically on calling Module.getImpl().') options = parser.parse_args() options.paks = build_utils.ParseGnList(options.paks) with open(options.libraries_file) as f: libraries_list = build_utils.ParseGnList(f.read()) libraries = [] for path in libraries_list: path = path.strip() filename = os.path.split(path)[1] assert filename.startswith('lib') assert filename.endswith('.so') # Remove lib prefix and .so suffix. libraries += [filename[3:-3]] paks = options.paks if options.paks else [] format_dict = { 'MODULE': options.module, 'LIBRARIES': ','.join(['"%s"' % l for l in libraries]), 'PAKS': ','.join(['"%s"' % os.path.basename(p) for p in paks]), 'LOAD_NATIVE_ON_GET_IMPL': ('true' if options.load_native_on_get_impl else 'false'), } with build_utils.AtomicOutput(options.output) as f: with zipfile.ZipFile(f.name, 'w') as srcjar_file: build_utils.AddToZipHermetic( srcjar_file, 'org/chromium/components/module_installer/builder/' 'ModuleDescriptor_%s.java' % options.module, data=_TEMPLATE.format(**format_dict)) if options.depfile: build_utils.WriteDepfile(options.depfile, options.output, inputs=[options.libraries_file])
def AddDiffFiles(diff_files, tmp_dir_32, out_zip, expected_files, component_build, uncompress_shared_libraries): """ Insert files only present in 32-bit APK into 64-bit APK (tmp_apk). """ for diff_file in diff_files: if component_build and diff_file.endswith('.so'): compress = not uncompress_shared_libraries else: compress = expected_files[os.path.basename(diff_file)] build_utils.AddToZipHermetic(out_zip, diff_file, os.path.join(tmp_dir_32, diff_file), compress=compress)
def MergeBinaries(apk, out_apk, secondary_abi_out_dir, shared_library): shutil.copyfile(apk, out_apk) with zipfile.ZipFile(out_apk, 'a') as apk_zip: secondary_abi = GetSecondaryAbi(apk_zip, shared_library) build_utils.AddToZipHermetic( apk_zip, 'lib/%s/%s' % (secondary_abi, shared_library), src_path=os.path.join(secondary_abi_out_dir, shared_library), compress=False) build_utils.AddToZipHermetic(apk_zip, 'assets/%s' % 'snapshot_blob_64.bin', src_path=os.path.join( secondary_abi_out_dir, 'snapshot_blob.bin'), compress=False) build_utils.AddToZipHermetic(apk_zip, 'assets/%s' % 'natives_blob_64.bin', src_path=os.path.join( secondary_abi_out_dir, 'natives_blob.bin'), compress=False)
def MergeBinaries(apk, out_apk, secondary_abi_out_dir, shared_library): shutil.copyfile(apk, out_apk) # Remove existing signatures subprocess.check_call(['zip', '-d', out_apk, 'META-INF/*.SF', 'META-INF/*.RSA']) with zipfile.ZipFile(out_apk, 'a') as apk_zip: secondary_abi = GetSecondaryAbi(apk_zip, shared_library) build_utils.AddToZipHermetic( apk_zip, 'lib/%s/%s' % (secondary_abi, shared_library), src_path = os.path.join(secondary_abi_out_dir, shared_library), compress = False) build_utils.AddToZipHermetic( apk_zip, 'assets/%s' % 'snapshot_blob_64.bin', src_path = os.path.join(secondary_abi_out_dir, 'snapshot_blob.bin'), compress = False) build_utils.AddToZipHermetic( apk_zip, 'assets/%s' % 'natives_blob_64.bin', src_path = os.path.join(secondary_abi_out_dir, 'natives_blob.bin'), compress = False)
def main(argv): global COWBOY option_parser = optparse.OptionParser() build_utils.AddDepfileOption(option_parser) option_parser.add_option('--aidl-path', help='Path to the aidl binary.') option_parser.add_option('--cowboy', help="Whether building for Cowboy and Terrace") option_parser.add_option('--imports', help='Files to import.') option_parser.add_option('--includes', help='Directories to add as import search paths.') option_parser.add_option('--srcjar', help='Path for srcjar output.') options, args = option_parser.parse_args(argv[1:]) COWBOY = options.cowboy == '1' with build_utils.TempDir() as temp_dir: for f in args: classname = os.path.splitext(os.path.basename(f))[0] output = os.path.join(temp_dir, classname + '.java') aidl_cmd = [options.aidl_path] aidl_cmd += [ '-p' + s for s in build_utils.ParseGnList(options.imports) ] if options.includes is not None: aidl_cmd += [ '-I' + s for s in build_utils.ParseGnList(options.includes) ] aidl_cmd += [ f, output ] build_utils.CheckOutput(aidl_cmd) with zipfile.ZipFile(options.srcjar, 'w') as srcjar: for path in build_utils.FindInDirectory(temp_dir, '*.java'): with open(path) as fileobj: data = fileobj.read() pkg_name = re.search(r'^\s*package\s+(.*?)\s*;', data, re.M).group(1) arcname = '%s/%s' % (pkg_name.replace('.', '/'), os.path.basename(path)) build_utils.AddToZipHermetic(srcjar, arcname, data=data) if COWBOY: full_path = os.path.join( os.getcwd(), 'gen/aidl', arcname) build_utils.MakeDirectory(os.path.dirname(full_path)) with open(full_path, 'w') as out_file: out_file.write(data) if options.depfile: build_utils.WriteDepfile(options.depfile, options.srcjar)
def _AddNativeLibraries(out_apk, native_libs, android_abi, uncompress): """Add native libraries to APK.""" for path in native_libs: basename = os.path.basename(path) apk_path = 'lib/%s/%s' % (android_abi, basename) compress = None if (uncompress and os.path.splitext(basename)[1] == '.so'): compress = False build_utils.AddToZipHermetic(out_apk, apk_path, src_path=path, compress=compress)
def _SplitModuleForAssetTargeting(src_module_zip, tmp_dir, split_dimensions): """Splits assets in a module if needed. Args: src_module_zip: input zip module path. tmp_dir: Path to temporary directory, where the new output module might be written to. split_dimensions: list of split dimensions. Returns: If the module doesn't need asset targeting, doesn't do anything and returns src_module_zip. Otherwise, create a new module zip archive under tmp_dir with the same file name, but which contains assets paths targeting the proper dimensions. """ split_language = 'LANGUAGE' in split_dimensions if not split_language: # Nothing to target, so return original module path. return src_module_zip with zipfile.ZipFile(src_module_zip, 'r') as src_zip: language_files = [ f for f in src_zip.namelist() if f.startswith(_LOCALES_SUBDIR)] if not language_files: # Not language-based assets to split in this module. return src_module_zip tmp_zip = os.path.join(tmp_dir, os.path.basename(src_module_zip)) with zipfile.ZipFile(tmp_zip, 'w') as dst_zip: for info in src_zip.infolist(): src_path = info.filename is_compressed = info.compress_type != zipfile.ZIP_STORED dst_paths = [src_path] if src_path in language_files: dst_paths = _RewriteLanguageAssetPath(src_path) for dst_path in dst_paths: build_utils.AddToZipHermetic( dst_zip, dst_path, data=src_zip.read(src_path), compress=is_compressed) return tmp_zip
def DoMain(argv): usage = 'usage: %prog [options] [output_dir] input_file(s)...' parser = optparse.OptionParser(usage=usage) parser.add_option('--srcjar', help='When specified, a .srcjar at the given path is ' 'created instead of individual .java files.') options, args = parser.parse_args(argv) if not args: parser.error('Need to specify at least one input file') input_paths = args with build_utils.AtomicOutput(options.srcjar) as f: with zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED) as srcjar: for output_path, data in DoGenerate(input_paths): build_utils.AddToZipHermetic(srcjar, output_path, data=data)
def DoMain(argv): usage = 'usage: %prog [number] [output]' parser = optparse.OptionParser(usage=usage) options, args = parser.parse_args(argv) if len(args) != 2: parser.error('Need to specify number and output_dir') number, output = args number = int(number) path_template = "org/chromium/content/app/SandboxedProcessService{0}.java" with build_utils.AtomicOutput(output) as f: with zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED) as srcjar: for i in xrange(number): build_utils.AddToZipHermetic(srcjar, path_template.format(i), data=GenerateService(i))
def AddToZipHermetic(zip_file, zip_path, src_path=None, data=None, compress=None, alignment=None): """Same as build_utils.AddToZipHermetic(), but with alignment. Args: alignment: If set, align the data of the entry to this many bytes. """ zipinfo = build_utils.HermeticZipInfo(filename=zip_path) if alignment: _SetAlignment(zip_file, zipinfo, alignment) build_utils.AddToZipHermetic(zip_file, zipinfo, src_path=src_path, data=data, compress=compress)
def _AddNativeLibraries(out_apk, native_libs, android_abi, uncompress): """Add native libraries to APK.""" has_crazy_linker = any('android_linker' in os.path.basename(p) for p in native_libs) for path in native_libs: basename = os.path.basename(path) compress = None if (uncompress and os.path.splitext(basename)[1] == '.so' and 'android_linker' not in basename): compress = False # Add prefix to prevent android install from extracting upon install. if has_crazy_linker: basename = 'crazy.' + basename apk_path = 'lib/%s/%s' % (android_abi, basename) build_utils.AddToZipHermetic(out_apk, apk_path, src_path=path, compress=compress)
def main(args): args = build_utils.ExpandFileArgs(args) parser = argparse.ArgumentParser() parser.add_argument('--include-dirs', help='GN list of include directories.') parser.add_argument('--output', help='Path for .srcjar.') parser.add_argument('--define', action='append', dest='defines', help='List of -D args') parser.add_argument('templates', nargs='+', help='Template files.') options = parser.parse_args(args) options.defines = build_utils.ParseGnList(options.defines) options.include_dirs = build_utils.ParseGnList(options.include_dirs) gcc_cmd = [ 'gcc', '-E', # stop after preprocessing. '-DANDROID', # Specify ANDROID define for pre-processor. '-x', 'c-header', # treat sources as C header files '-P', # disable line markers, i.e. '#line 309' ] gcc_cmd.extend('-D' + x for x in options.defines) gcc_cmd.extend('-I' + x for x in options.include_dirs) with build_utils.AtomicOutput(options.output) as f: with zipfile.ZipFile(f, 'w') as z: for template in options.templates: data = build_utils.CheckOutput(gcc_cmd + [template]) package_name = _ParsePackageName(data) if not package_name: raise Exception('Could not find java package of ' + template) zip_path = posixpath.join( package_name.replace('.', '/'), os.path.splitext(os.path.basename(template))[0]) + '.java' build_utils.AddToZipHermetic(z, zip_path, data=data)
def _Main(argv): parser = argparse.ArgumentParser() parser.add_argument('--srcjar', required=True, help='The path at which to generate the .srcjar file') parser.add_argument('--template', required=True, help='The template file with which to generate the Java ' 'class. Must have "{NATIVE_FEATURES}" somewhere in ' 'the template.') parser.add_argument('inputs', nargs='+', help='Input file(s)', metavar='INPUTFILE') args = parser.parse_args(argv) with build_utils.AtomicOutput(args.srcjar) as f: with zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED) as srcjar: data, path = _Generate(args.inputs, args.template) build_utils.AddToZipHermetic(srcjar, path, data=data)
def _Main(argv): parser = argparse.ArgumentParser() parser.add_argument('--srcjar', required=True, help='When specified, a .srcjar at the given path is ' 'created instead of individual .java files.') parser.add_argument('--template', required=True, help='Can be used to provide a context into which the' 'new string constants will be inserted.') parser.add_argument('inputs', nargs='+', help='Input file(s)', metavar='INPUTFILE') args = parser.parse_args(argv) with build_utils.AtomicOutput(args.srcjar) as f: with zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED) as srcjar: data, path = _Generate(args.inputs, args.template) build_utils.AddToZipHermetic(srcjar, path, data=data)
def on_stale_md5(): with tempfile.NamedTemporaryFile() as tmp_apk: tmp_file = tmp_apk.name with zipfile.ZipFile(options.resource_apk) as resource_apk, \ zipfile.ZipFile(tmp_file, 'w', zipfile.ZIP_DEFLATED) as out_apk: def copy_resource(zipinfo, out_dir=''): compress = zipinfo.compress_type != zipfile.ZIP_STORED build_utils.AddToZipHermetic(out_apk, out_dir + zipinfo.filename, data=resource_apk.read( zipinfo.filename), compress=compress) # Make assets come before resources in order to maintain the same file # ordering as GYP / aapt. http://crbug.com/561862 resource_infos = resource_apk.infolist() # 1. AndroidManifest.xml assert resource_infos[0].filename == 'AndroidManifest.xml' copy_resource(resource_infos[0], out_dir=apk_manifest_dir) # 2. Assets if options.write_asset_list: data = _CreateAssetsList( itertools.chain(assets, uncompressed_assets)) build_utils.AddToZipHermetic(out_apk, 'assets/assets_list', data=data) _AddAssets(out_apk, assets, disable_compression=False) _AddAssets(out_apk, uncompressed_assets, disable_compression=True) # 3. Dex files if options.dex_file and options.dex_file.endswith('.zip'): with zipfile.ZipFile(options.dex_file, 'r') as dex_zip: for dex in (d for d in dex_zip.namelist() if d.endswith('.dex')): build_utils.AddToZipHermetic( out_apk, apk_dex_dir + dex, data=dex_zip.read(dex)) elif options.dex_file: build_utils.AddToZipHermetic(out_apk, apk_dex_dir + 'classes.dex', src_path=options.dex_file) # 4. Native libraries. _AddNativeLibraries(out_apk, native_libs, options.android_abi, options.uncompress_shared_libraries) if options.secondary_android_abi: _AddNativeLibraries(out_apk, secondary_native_libs, options.secondary_android_abi, options.uncompress_shared_libraries) for name in sorted(options.native_lib_placeholders): # Note: Empty libs files are ignored by md5check (can cause issues # with stale builds when the only change is adding/removing # placeholders). apk_path = 'lib/%s/%s' % (options.android_abi, name) build_utils.AddToZipHermetic(out_apk, apk_path, data='') for name in sorted(options.secondary_native_lib_placeholders): # Note: Empty libs files are ignored by md5check (can cause issues # with stale builds when the only change is adding/removing # placeholders). apk_path = 'lib/%s/%s' % (options.secondary_android_abi, name) build_utils.AddToZipHermetic(out_apk, apk_path, data='') # 5. Resources for info in resource_infos[1:]: copy_resource(info) # 6. Java resources that should be accessible via # Class.getResourceAsStream(), in particular parts of Emma jar. # Prebuilt jars may contain class files which we shouldn't include. for java_resource in options.java_resources: with zipfile.ZipFile(java_resource, 'r') as java_resource_jar: for apk_path in java_resource_jar.namelist(): apk_path_lower = apk_path.lower() if apk_path_lower.startswith('meta-inf/'): continue if apk_path_lower.endswith('/'): continue if apk_path_lower.endswith('.class'): continue build_utils.AddToZipHermetic( out_apk, apk_root_dir + apk_path, data=java_resource_jar.read(apk_path)) if options.apk_pak_info_path: _MergePakInfoFiles(options.apk_pak_info_path, pak_infos) if options.apk_res_info_path: _MergeResInfoFiles(options.apk_res_info_path, options.resource_apk) if options.format == 'apk': finalize_apk.FinalizeApk(options.apksigner_path, options.zipalign_path, tmp_file, options.output_apk, options.key_path, options.key_passwd, options.key_name) else: shutil.move(tmp_file, options.output_apk) tmp_apk.delete = False