Search in sources :

Example 1 with TempDirectory

use of com.android.tools.build.bundletool.io.TempDirectory in project bundletool by google.

the class BuildApksCommand method execute.

public Path execute() {
    validateInput();
    Path outputDirectory = getOutputFormat().equals(APK_SET) ? getOutputFile().getParent() : getOutputFile();
    if (outputDirectory != null && Files.notExists(outputDirectory)) {
        logger.info("Output directory '" + outputDirectory + "' does not exist, creating it.");
        FileUtils.createDirectories(outputDirectory);
    }
    try (TempDirectory tempDir = new TempDirectory(getClass().getSimpleName())) {
        Path bundlePath;
        // The old APK serializer relies on the compression of entries in the App Bundle.
        // Unfortunately, we don't know the compression level that was used when the bundle was built,
        // so we re-compress all entries with our desired compression level.
        // Exception is made when the device spec is specified, we only need a fraction of the
        // entries, so re-compressing all entries would be a waste of CPU.
        boolean recompressAppBundle = !getDeviceSpec().isPresent() && !getEnableApkSerializerWithoutBundleRecompression();
        if (recompressAppBundle) {
            bundlePath = tempDir.getPath().resolve("recompressed.aab");
            new AppBundleRecompressor(getExecutorService()).recompressAppBundle(getBundlePath().toFile(), bundlePath.toFile());
        } else {
            bundlePath = getBundlePath();
        }
        try (ZipFile bundleZip = new ZipFile(bundlePath.toFile());
            ZipReader zipReader = ZipReader.createFromFile(bundlePath);
            Closer closer = Closer.create()) {
            AppBundleValidator bundleValidator = AppBundleValidator.create(getExtraValidators());
            bundleValidator.validateFile(bundleZip);
            AppBundle appBundle = AppBundle.buildFromZip(bundleZip);
            bundleValidator.validate(appBundle);
            validateSdkBundles(closer);
            AppBundlePreprocessorManager appBundlePreprocessorManager = DaggerAppBundlePreprocessorComponent.builder().setBuildApksCommand(this).build().create();
            AppBundle preprocessedAppBundle = appBundlePreprocessorManager.processAppBundle(appBundle);
            BuildApksManager buildApksManager = DaggerBuildApksManagerComponent.builder().setBuildApksCommand(this).setTempDirectory(tempDir).setAppBundle(preprocessedAppBundle).setZipReader(zipReader).setUseBundleCompression(recompressAppBundle).build().create();
            buildApksManager.execute();
        } catch (ZipException e) {
            throw InvalidBundleException.builder().withCause(e).withUserMessage("The App Bundle is not a valid zip file.").build();
        } finally {
            if (isExecutorServiceCreatedByBundleTool()) {
                getExecutorService().shutdown();
            }
        }
    } catch (IOException e) {
        throw new UncheckedIOException("An error occurred when processing the App Bundle.", e);
    }
    return getOutputFile();
}
Also used : Path(java.nio.file.Path) Closer(com.google.common.io.Closer) AppBundleValidator(com.android.tools.build.bundletool.validation.AppBundleValidator) AppBundle(com.android.tools.build.bundletool.model.AppBundle) ZipReader(com.android.tools.build.bundletool.io.ZipReader) ZipException(java.util.zip.ZipException) UncheckedIOException(java.io.UncheckedIOException) AppBundlePreprocessorManager(com.android.tools.build.bundletool.preprocessors.AppBundlePreprocessorManager) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) TempDirectory(com.android.tools.build.bundletool.io.TempDirectory) AppBundleRecompressor(com.android.tools.build.bundletool.preprocessors.AppBundleRecompressor) ZipFile(java.util.zip.ZipFile)

Example 2 with TempDirectory

use of com.android.tools.build.bundletool.io.TempDirectory in project bundletool by google.

the class BuildSdkApksCommand method execute.

public void execute() {
    validateInput();
    try (ZipFile bundleZip = new ZipFile(getSdkBundlePath().toFile());
        ZipReader zipReader = ZipReader.createFromFile(getSdkBundlePath());
        TempDirectory tempDir = new TempDirectory(getClass().getSimpleName())) {
        SdkBundleValidator bundleValidator = SdkBundleValidator.create();
        bundleValidator.validateFile(bundleZip);
        SdkBundle sdkBundle = SdkBundle.buildFromZip(bundleZip, getVersionCode());
        bundleValidator.validate(sdkBundle);
        DaggerBuildSdkApksManagerComponent.builder().setBuildSdkApksCommand(this).setTempDirectory(tempDir).setSdkBundle(sdkBundle).setZipReader(zipReader).setUseBundleCompression(false).build().create().execute();
    } catch (ZipException e) {
        throw InvalidBundleException.builder().withCause(e).withUserMessage("The SDK Bundle is not a valid zip file.").build();
    } catch (IOException e) {
        throw new UncheckedIOException("An error occurred when validating the Sdk Bundle.", e);
    } finally {
        if (isExecutorServiceCreatedByBundleTool()) {
            getExecutorService().shutdown();
        }
    }
}
Also used : TempDirectory(com.android.tools.build.bundletool.io.TempDirectory) ZipFile(java.util.zip.ZipFile) SdkBundle(com.android.tools.build.bundletool.model.SdkBundle) SdkBundleValidator(com.android.tools.build.bundletool.validation.SdkBundleValidator) ZipReader(com.android.tools.build.bundletool.io.ZipReader) ZipException(java.util.zip.ZipException) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException)

Example 3 with TempDirectory

use of com.android.tools.build.bundletool.io.TempDirectory in project bundletool by google.

the class InstallApksCommand method execute.

public void execute() {
    BuildApksResult toc = readBuildApksResult();
    validateInput(toc);
    AdbServer adbServer = getAdbServer();
    adbServer.init(getAdbPath());
    try (TempDirectory tempDirectory = new TempDirectory()) {
        DeviceSpec deviceSpec = new DeviceAnalyzer(adbServer).getDeviceSpec(getDeviceId());
        if (getDeviceTier().isPresent()) {
            deviceSpec = deviceSpec.toBuilder().setDeviceTier(Int32Value.of(getDeviceTier().get())).build();
        }
        if (getDeviceGroups().isPresent()) {
            deviceSpec = deviceSpec.toBuilder().addAllDeviceGroups(getDeviceGroups().get()).build();
        }
        final ImmutableList<Path> apksToInstall = getApksToInstall(toc, deviceSpec, tempDirectory.getPath());
        final ImmutableList<Path> filesToPush = ImmutableList.<Path>builder().addAll(getApksToPushToStorage(toc, deviceSpec, tempDirectory.getPath())).addAll(getAdditionalLocalTestingFiles().orElse(ImmutableList.of())).build();
        AdbRunner adbRunner = new AdbRunner(adbServer);
        InstallOptions installOptions = InstallOptions.builder().setAllowDowngrade(getAllowDowngrade()).setAllowTestOnly(getAllowTestOnly()).setTimeout(getTimeout()).build();
        if (getDeviceId().isPresent()) {
            adbRunner.run(device -> device.installApks(apksToInstall, installOptions), getDeviceId().get());
        } else {
            adbRunner.run(device -> device.installApks(apksToInstall, installOptions));
        }
        if (!filesToPush.isEmpty()) {
            pushFiles(filesToPush, toc, adbRunner);
        }
        if (toc.getLocalTestingInfo().getEnabled()) {
            cleanUpEmulatedSplits(adbRunner, toc);
        }
    }
}
Also used : DeviceSpec(com.android.bundle.Devices.DeviceSpec) Path(java.nio.file.Path) TempDirectory(com.android.tools.build.bundletool.io.TempDirectory) BuildApksResult(com.android.bundle.Commands.BuildApksResult) AdbRunner(com.android.tools.build.bundletool.device.AdbRunner) DeviceAnalyzer(com.android.tools.build.bundletool.device.DeviceAnalyzer) InstallOptions(com.android.tools.build.bundletool.device.Device.InstallOptions) AdbServer(com.android.tools.build.bundletool.device.AdbServer)

Example 4 with TempDirectory

use of com.android.tools.build.bundletool.io.TempDirectory in project bundletool by google.

the class InstallMultiApksCommand method extractApkListFromApks.

/**
 * Extracts the apk/apex files that will be installed from a given .apks.
 */
private static ImmutableList<PackagePathVersion> extractApkListFromApks(DeviceSpec deviceSpec, PackagePathVersion apksArchive, Optional<InstalledPackageInfo> installedPackage, TempDirectory tempDirectory) {
    logger.info(String.format("Extracting package '%s'", apksArchive.getPackageName()));
    try {
        Path output = tempDirectory.getPath().resolve(apksArchive.getPackageName());
        Files.createDirectory(output);
        ExtractApksCommand.Builder extractApksCommand = ExtractApksCommand.builder().setApksArchivePath(apksArchive.getPath()).setDeviceSpec(deviceSpec).setOutputDirectory(output);
        ImmutableList<Path> extractedPaths = fixExtension(extractApksCommand.build().execute(), installedPackage.map(InstalledPackageInfo::isApex).orElse(false));
        return extractedPaths.stream().map(path -> PackagePathVersion.create(path, apksArchive.getPackageName(), apksArchive.getVersionCode())).collect(toImmutableList());
    } catch (IncompatibleDeviceException e) {
        logger.warning(String.format("Package '%s' is not supported by the attached device (SDK version %d). Skipping.", apksArchive.getPackageName(), deviceSpec.getSdkVersion()));
        return ImmutableList.of();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
Also used : Path(java.nio.file.Path) ZipPath(com.android.tools.build.bundletool.model.ZipPath) TimeoutException(java.util.concurrent.TimeoutException) SYSTEM_PATH_VARIABLE(com.android.tools.build.bundletool.model.utils.SdkToolsLocator.SYSTEM_PATH_VARIABLE) DeviceSpec(com.android.bundle.Devices.DeviceSpec) DeviceAnalyzer(com.android.tools.build.bundletool.device.DeviceAnalyzer) TempDirectory(com.android.tools.build.bundletool.io.TempDirectory) ImmutableListMultimap.toImmutableListMultimap(com.google.common.collect.ImmutableListMultimap.toImmutableListMultimap) Locale(java.util.Locale) Flag(com.android.tools.build.bundletool.flags.Flag) Duration(java.time.Duration) AdbShellCommandTask(com.android.tools.build.bundletool.device.AdbShellCommandTask) ZipFile(java.util.zip.ZipFile) FilePreconditions.checkFileHasExtension(com.android.tools.build.bundletool.model.utils.files.FilePreconditions.checkFileHasExtension) Path(java.nio.file.Path) ZipEntry(java.util.zip.ZipEntry) InstalledPackageInfo(com.android.tools.build.bundletool.device.PackagesParser.InstalledPackageInfo) ImmutableSet(com.google.common.collect.ImmutableSet) BadgingInfo(com.android.tools.build.bundletool.device.BadgingInfoParser.BadgingInfo) ImmutableMap(com.google.common.collect.ImmutableMap) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Aapt2Command(com.android.tools.build.bundletool.androidtools.Aapt2Command) Device(com.android.tools.build.bundletool.device.Device) ParsedFlags(com.android.tools.build.bundletool.flags.ParsedFlags) CanIgnoreReturnValue(com.google.errorprone.annotations.CanIgnoreReturnValue) Streams(com.google.common.collect.Streams) Logger(java.util.logging.Logger) UncheckedIOException(java.io.UncheckedIOException) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) SystemEnvironmentProvider(com.android.tools.build.bundletool.model.utils.SystemEnvironmentProvider) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap) AutoValue(com.google.auto.value.AutoValue) ByteStreams(com.google.common.io.ByteStreams) Optional(java.util.Optional) FilePreconditions.checkFileExistsAndReadable(com.android.tools.build.bundletool.model.utils.files.FilePreconditions.checkFileExistsAndReadable) ZipPath(com.android.tools.build.bundletool.model.ZipPath) Collectors.groupingBy(java.util.stream.Collectors.groupingBy) Supplier(java.util.function.Supplier) ImmutableList(com.google.common.collect.ImmutableList) DefaultSystemEnvironmentProvider(com.android.tools.build.bundletool.model.utils.DefaultSystemEnvironmentProvider) BadgingInfoParser(com.android.tools.build.bundletool.device.BadgingInfoParser) Suppliers(com.google.common.base.Suppliers) Comparator.comparing(java.util.Comparator.comparing) AdbServer(com.android.tools.build.bundletool.device.AdbServer) OutputStream(java.io.OutputStream) ANDROID_HOME_VARIABLE(com.android.tools.build.bundletool.model.utils.SdkToolsLocator.ANDROID_HOME_VARIABLE) FilePreconditions.checkFileExistsAndExecutable(com.android.tools.build.bundletool.model.utils.files.FilePreconditions.checkFileExistsAndExecutable) AdbCommand(com.android.tools.build.bundletool.androidtools.AdbCommand) Files(java.nio.file.Files) ANDROID_SERIAL_VARIABLE(com.android.tools.build.bundletool.commands.CommandUtils.ANDROID_SERIAL_VARIABLE) Collectors.maxBy(java.util.stream.Collectors.maxBy) IOException(java.io.IOException) PackagesParser(com.android.tools.build.bundletool.device.PackagesParser) Streams.stream(com.google.common.collect.Streams.stream) IncompatibleDeviceException(com.android.tools.build.bundletool.model.exceptions.IncompatibleDeviceException) InvalidCommandException(com.android.tools.build.bundletool.model.exceptions.InvalidCommandException) FlagDescription(com.android.tools.build.bundletool.commands.CommandHelp.FlagDescription) Versions(com.android.tools.build.bundletool.model.utils.Versions) CommandDescription(com.android.tools.build.bundletool.commands.CommandHelp.CommandDescription) InputStream(java.io.InputStream) InstalledPackageInfo(com.android.tools.build.bundletool.device.PackagesParser.InstalledPackageInfo) UncheckedIOException(java.io.UncheckedIOException) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) IncompatibleDeviceException(com.android.tools.build.bundletool.model.exceptions.IncompatibleDeviceException)

Example 5 with TempDirectory

use of com.android.tools.build.bundletool.io.TempDirectory in project bundletool by google.

the class InstallMultiApksCommand method apksWithPackageName.

private static Optional<PackagePathVersion> apksWithPackageName(Path apksArchivePath, DeviceSpec deviceSpec, Supplier<Aapt2Command> aapt2CommandSupplier) {
    try (TempDirectory tempDirectory = new TempDirectory()) {
        // Any of the extracted .apk/.apex files will work.
        Path extractedFile = ExtractApksCommand.builder().setApksArchivePath(apksArchivePath).setDeviceSpec(deviceSpec).setOutputDirectory(tempDirectory.getPath()).build().execute().get(0);
        BadgingInfo badgingInfo = BadgingInfoParser.parse(aapt2CommandSupplier.get().dumpBadging(extractedFile));
        return Optional.of(PackagePathVersion.create(apksArchivePath, badgingInfo.getPackageName(), badgingInfo.getVersionCode()));
    } catch (IncompatibleDeviceException e) {
        logger.warning(String.format("Unable to determine package name of %s, as it is not compatible with the attached" + " device. Skipping.", apksArchivePath));
        return Optional.empty();
    }
}
Also used : Path(java.nio.file.Path) ZipPath(com.android.tools.build.bundletool.model.ZipPath) TempDirectory(com.android.tools.build.bundletool.io.TempDirectory) IncompatibleDeviceException(com.android.tools.build.bundletool.model.exceptions.IncompatibleDeviceException) BadgingInfo(com.android.tools.build.bundletool.device.BadgingInfoParser.BadgingInfo)

Aggregations

TempDirectory (com.android.tools.build.bundletool.io.TempDirectory)10 IOException (java.io.IOException)8 UncheckedIOException (java.io.UncheckedIOException)8 Path (java.nio.file.Path)8 ZipFile (java.util.zip.ZipFile)6 AdbServer (com.android.tools.build.bundletool.device.AdbServer)5 DeviceAnalyzer (com.android.tools.build.bundletool.device.DeviceAnalyzer)5 ZipPath (com.android.tools.build.bundletool.model.ZipPath)5 DeviceSpec (com.android.bundle.Devices.DeviceSpec)4 AdbShellCommandTask (com.android.tools.build.bundletool.device.AdbShellCommandTask)4 BadgingInfo (com.android.tools.build.bundletool.device.BadgingInfoParser.BadgingInfo)4 Device (com.android.tools.build.bundletool.device.Device)4 IncompatibleDeviceException (com.android.tools.build.bundletool.model.exceptions.IncompatibleDeviceException)4 InvalidCommandException (com.android.tools.build.bundletool.model.exceptions.InvalidCommandException)4 ImmutableList (com.google.common.collect.ImmutableList)4 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)4 Files (java.nio.file.Files)4 Aapt2Command (com.android.tools.build.bundletool.androidtools.Aapt2Command)3 AdbCommand (com.android.tools.build.bundletool.androidtools.AdbCommand)3 CommandDescription (com.android.tools.build.bundletool.commands.CommandHelp.CommandDescription)3