Search in sources :

Example 1 with HumanReadableException

use of com.facebook.buck.util.HumanReadableException in project buck by facebook.

the class DefaultAndroidDirectoryResolver method findBuildTools.

private Optional<Path> findBuildTools() {
    if (!sdk.isPresent()) {
        buildToolsErrorMessage = Optional.of(TOOLS_NEED_SDK_MESSAGE);
        return Optional.empty();
    }
    final Path sdkDir = sdk.get();
    final Path toolsDir = sdkDir.resolve("build-tools");
    if (toolsDir.toFile().isDirectory()) {
        // In older versions of the ADT that have been upgraded via the SDK manager, the build-tools
        // directory appears to contain subfolders of the form "17.0.0". However, newer versions of
        // the ADT that are downloaded directly from http://developer.android.com/ appear to have
        // subfolders of the form android-4.2.2. There also appear to be cases where subfolders
        // are named build-tools-18.0.0. We need to support all of these scenarios.
        File[] directories;
        try {
            directories = toolsDir.toFile().listFiles(pathname -> {
                if (!pathname.isDirectory()) {
                    return false;
                }
                String version = stripBuildToolsPrefix(pathname.getName());
                if (!VersionStringComparator.isValidVersionString(version)) {
                    throw new HumanReadableException("%s in %s is not a valid build tools directory.%n" + "Build tools directories should be follow the naming scheme: " + "android-<VERSION>, build-tools-<VERSION>, or <VERSION>. Please remove " + "directory %s.", pathname.getName(), buildTools, pathname.getName());
                }
                if (targetBuildToolsVersion.isPresent()) {
                    return targetBuildToolsVersion.get().equals(pathname.getName());
                }
                return true;
            });
        } catch (HumanReadableException e) {
            buildToolsErrorMessage = Optional.of(e.getHumanReadableErrorMessage());
            return Optional.empty();
        }
        if (targetBuildToolsVersion.isPresent()) {
            if (directories.length == 0) {
                buildToolsErrorMessage = unableToFindTargetBuildTools();
                return Optional.empty();
            } else {
                return Optional.of(directories[0].toPath());
            }
        }
        // We aren't looking for a specific version, so we pick the newest version
        final VersionStringComparator comparator = new VersionStringComparator();
        File newestBuildDir = null;
        String newestBuildDirVersion = null;
        for (File directory : directories) {
            String currentDirVersion = stripBuildToolsPrefix(directory.getName());
            if (newestBuildDir == null || newestBuildDirVersion == null || comparator.compare(newestBuildDirVersion, currentDirVersion) < 0) {
                newestBuildDir = directory;
                newestBuildDirVersion = currentDirVersion;
            }
        }
        if (newestBuildDir == null) {
            buildToolsErrorMessage = Optional.of(buildTools + " was empty, but should have " + "contained a subdirectory with build tools. Install them using the Android " + "SDK Manager (" + toolsDir.getParent().resolve("tools").resolve("android") + ").");
            return Optional.empty();
        }
        return Optional.of(newestBuildDir.toPath());
    }
    if (targetBuildToolsVersion.isPresent()) {
        // We were looking for a specific version, but we aren't going to find it at this point since
        // nothing under platform-tools was versioned.
        buildToolsErrorMessage = unableToFindTargetBuildTools();
        return Optional.empty();
    }
    // Build tools used to exist inside of platform-tools, so fallback to that.
    return Optional.of(sdkDir.resolve("platform-tools"));
}
Also used : Path(java.nio.file.Path) Charsets(com.google.common.base.Charsets) ImmutableSet(com.google.common.collect.ImmutableSet) Properties(java.util.Properties) ImmutableMap(com.google.common.collect.ImmutableMap) Files(java.nio.file.Files) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) HumanReadableException(com.facebook.buck.util.HumanReadableException) FileSystem(java.nio.file.FileSystem) Collectors(java.util.stream.Collectors) File(java.io.File) Objects(java.util.Objects) Strings(com.google.common.base.Strings) DirectoryStream(java.nio.file.DirectoryStream) List(java.util.List) Escaper(com.facebook.buck.util.Escaper) Optional(java.util.Optional) Pair(com.facebook.buck.model.Pair) VisibleForTesting(com.google.common.annotations.VisibleForTesting) BufferedReader(java.io.BufferedReader) VersionStringComparator(com.facebook.buck.util.VersionStringComparator) Path(java.nio.file.Path) HumanReadableException(com.facebook.buck.util.HumanReadableException) VersionStringComparator(com.facebook.buck.util.VersionStringComparator) File(java.io.File)

Example 2 with HumanReadableException

use of com.facebook.buck.util.HumanReadableException in project buck by facebook.

the class DefaultAndroidDirectoryResolver method findNdkVersionFromDirectory.

/**
   * The method returns the NDK version of a path.
   * @param ndkDirectory Path to the folder that contains the NDK.
   * @return A string containing the NDK version or absent.
   */
public static Optional<String> findNdkVersionFromDirectory(Path ndkDirectory) {
    Path newNdk = ndkDirectory.resolve(NDK_POST_R11_VERSION_FILENAME);
    Path oldNdk = ndkDirectory.resolve(NDK_PRE_R11_VERSION_FILENAME);
    boolean newNdkPathFound = Files.exists(newNdk);
    boolean oldNdkPathFound = Files.exists(oldNdk);
    if (newNdkPathFound && oldNdkPathFound) {
        throw new HumanReadableException("Android NDK directory " + ndkDirectory + " can not " + "contain both properties files. Remove source.properties or RELEASE.TXT.");
    } else if (newNdkPathFound) {
        Properties sourceProperties = new Properties();
        try (FileInputStream fileStream = new FileInputStream(newNdk.toFile())) {
            sourceProperties.load(fileStream);
            return Optional.ofNullable(sourceProperties.getProperty("Pkg.Revision"));
        } catch (IOException e) {
            throw new HumanReadableException("Failed to read NDK version from " + newNdk + ".");
        }
    } else if (oldNdkPathFound) {
        try (BufferedReader reader = Files.newBufferedReader(oldNdk, Charsets.UTF_8)) {
            // around since we should consider them equivalent.
            return Optional.ofNullable(reader.readLine().split("\\s+")[0].replace("r10e-rc4", "r10e"));
        } catch (IOException e) {
            throw new HumanReadableException("Failed to read NDK version from " + oldNdk + ".");
        }
    } else {
        throw new HumanReadableException(ndkDirectory + " does not contain a valid properties " + "file for Android NDK.");
    }
}
Also used : Path(java.nio.file.Path) HumanReadableException(com.facebook.buck.util.HumanReadableException) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) Properties(java.util.Properties) FileInputStream(java.io.FileInputStream)

Example 3 with HumanReadableException

use of com.facebook.buck.util.HumanReadableException in project buck by facebook.

the class AndroidResourceDescription method collectInputFiles.

@VisibleForTesting
ImmutableSortedMap<Path, SourcePath> collectInputFiles(final ProjectFilesystem filesystem, Path inputDir) {
    final ImmutableSortedMap.Builder<Path, SourcePath> paths = ImmutableSortedMap.naturalOrder();
    // We ignore the same files that mini-aapt and aapt ignore.
    FileVisitor<Path> fileVisitor = new SimpleFileVisitor<Path>() {

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attr) throws IOException {
            String dirName = dir.getFileName().toString();
            // Special case: directory starting with '_' as per aapt.
            if (dirName.charAt(0) == '_' || !isPossibleResourceName(dirName)) {
                return FileVisitResult.SKIP_SUBTREE;
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attr) throws IOException {
            String filename = file.getFileName().toString();
            if (isPossibleResourceName(filename)) {
                paths.put(MorePaths.relativize(inputDir, file), new PathSourcePath(filesystem, file));
            }
            return FileVisitResult.CONTINUE;
        }
    };
    try {
        filesystem.walkRelativeFileTree(inputDir, fileVisitor);
    } catch (IOException e) {
        throw new HumanReadableException(e, "Error while searching for android resources in directory %s.", inputDir);
    }
    return paths.build();
}
Also used : SourcePath(com.facebook.buck.rules.SourcePath) Path(java.nio.file.Path) PathSourcePath(com.facebook.buck.rules.PathSourcePath) SourcePath(com.facebook.buck.rules.SourcePath) PathSourcePath(com.facebook.buck.rules.PathSourcePath) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) HumanReadableException(com.facebook.buck.util.HumanReadableException) ImmutableSortedMap(com.google.common.collect.ImmutableSortedMap) PathSourcePath(com.facebook.buck.rules.PathSourcePath) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 4 with HumanReadableException

use of com.facebook.buck.util.HumanReadableException in project buck by facebook.

the class ApkBuilderStep method createKeystoreProperties.

private PrivateKeyAndCertificate createKeystoreProperties() throws IOException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
    KeyStore keystore = KeyStore.getInstance(JARSIGNER_KEY_STORE_TYPE);
    KeystoreProperties keystoreProperties = keystorePropertiesSupplier.get();
    InputStream inputStream = filesystem.getInputStreamForRelativePath(pathToKeystore);
    char[] keystorePassword = keystoreProperties.getStorepass().toCharArray();
    try {
        keystore.load(inputStream, keystorePassword);
    } catch (IOException | NoSuchAlgorithmException | CertificateException e) {
        throw new HumanReadableException(e, "%s is an invalid keystore.", pathToKeystore);
    }
    String alias = keystoreProperties.getAlias();
    char[] keyPassword = keystoreProperties.getKeypass().toCharArray();
    Key key = keystore.getKey(alias, keyPassword);
    // key can be null if alias/password is incorrect.
    if (key == null) {
        throw new HumanReadableException("The keystore [%s] key.alias [%s] does not exist or does not identify a key-related " + "entry", pathToKeystore, alias);
    }
    Certificate certificate = keystore.getCertificate(alias);
    return new PrivateKeyAndCertificate((PrivateKey) key, (X509Certificate) certificate);
}
Also used : InputStream(java.io.InputStream) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStore(java.security.KeyStore) HumanReadableException(com.facebook.buck.util.HumanReadableException) Key(java.security.Key) PrivateKey(java.security.PrivateKey) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 5 with HumanReadableException

use of com.facebook.buck.util.HumanReadableException in project buck by facebook.

the class ApkGenruleDescription method createBuildRule.

@Override
protected <A extends ApkGenruleDescription.Arg> BuildRule createBuildRule(BuildRuleParams params, BuildRuleResolver resolver, A args, Optional<com.facebook.buck.rules.args.Arg> cmd, Optional<com.facebook.buck.rules.args.Arg> bash, Optional<com.facebook.buck.rules.args.Arg> cmdExe) {
    final BuildRule apk = resolver.getRule(args.apk);
    if (!(apk instanceof HasInstallableApk)) {
        throw new HumanReadableException("The 'apk' argument of %s, %s, must correspond to an " + "installable rule, such as android_binary() or apk_genrule().", params.getBuildTarget(), args.apk.getFullyQualifiedName());
    }
    HasInstallableApk installableApk = (HasInstallableApk) apk;
    final Supplier<ImmutableSortedSet<BuildRule>> originalExtraDeps = params.getExtraDeps();
    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
    return new ApkGenrule(params.copyReplacingExtraDeps(Suppliers.memoize(() -> ImmutableSortedSet.<BuildRule>naturalOrder().addAll(originalExtraDeps.get()).add(installableApk).build())), ruleFinder, args.srcs, cmd, bash, cmdExe, args.type.isPresent() ? args.type : Optional.of("apk"), installableApk.getSourcePathToOutput());
}
Also used : HumanReadableException(com.facebook.buck.util.HumanReadableException) ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) BuildRule(com.facebook.buck.rules.BuildRule) SourcePathRuleFinder(com.facebook.buck.rules.SourcePathRuleFinder)

Aggregations

HumanReadableException (com.facebook.buck.util.HumanReadableException)195 Path (java.nio.file.Path)79 SourcePath (com.facebook.buck.rules.SourcePath)50 BuildTarget (com.facebook.buck.model.BuildTarget)49 Test (org.junit.Test)46 IOException (java.io.IOException)45 ImmutableList (com.google.common.collect.ImmutableList)39 BuildRule (com.facebook.buck.rules.BuildRule)31 ImmutableSet (com.google.common.collect.ImmutableSet)30 SourcePathRuleFinder (com.facebook.buck.rules.SourcePathRuleFinder)29 ImmutableMap (com.google.common.collect.ImmutableMap)26 SourcePathResolver (com.facebook.buck.rules.SourcePathResolver)22 Optional (java.util.Optional)21 PathSourcePath (com.facebook.buck.rules.PathSourcePath)20 VisibleForTesting (com.google.common.annotations.VisibleForTesting)18 Map (java.util.Map)18 BuildRuleResolver (com.facebook.buck.rules.BuildRuleResolver)17 ImmutableSortedSet (com.google.common.collect.ImmutableSortedSet)16 UnflavoredBuildTarget (com.facebook.buck.model.UnflavoredBuildTarget)15 ProjectWorkspace (com.facebook.buck.testutil.integration.ProjectWorkspace)15