Search in sources :

Example 46 with Optional

use of java.util.Optional in project buck by facebook.

the class ZipStep method execute.

@Override
public StepExecutionResult execute(ExecutionContext context) {
    if (filesystem.exists(pathToZipFile)) {
        context.postEvent(ConsoleEvent.severe("Attempting to overwrite an existing zip: %s", pathToZipFile));
        return StepExecutionResult.ERROR;
    }
    // Since filesystem traversals can be non-deterministic, sort the entries we find into
    // a tree map before writing them out.
    final Map<String, Pair<CustomZipEntry, Optional<Path>>> entries = Maps.newTreeMap();
    FileVisitor<Path> pathFileVisitor = new SimpleFileVisitor<Path>() {

        private boolean isSkipFile(Path file) {
            return !paths.isEmpty() && !paths.contains(file);
        }

        private String getEntryName(Path path) {
            Path relativePath = junkPaths ? path.getFileName() : baseDir.relativize(path);
            return MorePaths.pathWithUnixSeparators(relativePath);
        }

        private CustomZipEntry getZipEntry(String entryName, final Path path, BasicFileAttributes attr) throws IOException {
            boolean isDirectory = filesystem.isDirectory(path);
            if (isDirectory) {
                entryName += "/";
            }
            CustomZipEntry entry = new CustomZipEntry(entryName);
            // We want deterministic ZIPs, so avoid mtimes.
            entry.setFakeTime();
            entry.setCompressionLevel(isDirectory ? ZipCompressionLevel.MIN_COMPRESSION_LEVEL.getValue() : compressionLevel.getValue());
            // If we're using STORED files, we must manually set the CRC, size, and compressed size.
            if (entry.getMethod() == ZipEntry.STORED && !isDirectory) {
                entry.setSize(attr.size());
                entry.setCompressedSize(attr.size());
                entry.setCrc(new ByteSource() {

                    @Override
                    public InputStream openStream() throws IOException {
                        return filesystem.newFileInputStream(path);
                    }
                }.hash(Hashing.crc32()).padToLong());
            }
            long externalAttributes = filesystem.getFileAttributesForZipEntry(path);
            LOG.verbose("Setting mode for entry %s path %s to 0x%08X", entryName, path, externalAttributes);
            entry.setExternalAttributes(externalAttributes);
            return entry;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (!isSkipFile(file)) {
                CustomZipEntry entry = getZipEntry(getEntryName(file), file, attrs);
                entries.put(entry.getName(), new Pair<>(entry, Optional.of(file)));
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            if (!dir.equals(baseDir) && !isSkipFile(dir)) {
                CustomZipEntry entry = getZipEntry(getEntryName(dir), dir, attrs);
                entries.put(entry.getName(), new Pair<>(entry, Optional.empty()));
            }
            return FileVisitResult.CONTINUE;
        }
    };
    try (BufferedOutputStream baseOut = new BufferedOutputStream(filesystem.newFileOutputStream(pathToZipFile));
        CustomZipOutputStream out = ZipOutputStreams.newOutputStream(baseOut, THROW_EXCEPTION)) {
        filesystem.walkRelativeFileTree(baseDir, pathFileVisitor);
        // Write the entries out using the iteration order of the tree map above.
        for (Pair<CustomZipEntry, Optional<Path>> entry : entries.values()) {
            out.putNextEntry(entry.getFirst());
            if (entry.getSecond().isPresent()) {
                try (InputStream input = filesystem.newFileInputStream(entry.getSecond().get())) {
                    ByteStreams.copy(input, out);
                }
            }
            out.closeEntry();
        }
    } catch (IOException e) {
        context.logError(e, "Error creating zip file %s", pathToZipFile);
        return StepExecutionResult.ERROR;
    }
    return StepExecutionResult.SUCCESS;
}
Also used : Path(java.nio.file.Path) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) Optional(java.util.Optional) InputStream(java.io.InputStream) IOException(java.io.IOException) ByteSource(com.google.common.io.ByteSource) BufferedOutputStream(java.io.BufferedOutputStream) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) Pair(com.facebook.buck.model.Pair)

Example 47 with Optional

use of java.util.Optional in project buck by facebook.

the class TargetNodeTranslator method translateNode.

/**
   * @return a copy of the given {@link TargetNode} with all found {@link BuildTarget}s translated,
   *         or {@link Optional#empty()} if the node requires no translation.
   */
public <A> Optional<TargetNode<A, ?>> translateNode(TargetNode<A, ?> node) {
    CellPathResolver cellPathResolver = node.getCellNames();
    BuildTargetPatternParser<BuildTargetPattern> pattern = BuildTargetPatternParser.forBaseName(node.getBuildTarget().getBaseName());
    Optional<BuildTarget> target = translateBuildTarget(node.getBuildTarget());
    Optional<A> constructorArg = translateConstructorArg(cellPathResolver, pattern, node);
    Optional<ImmutableSet<BuildTarget>> declaredDeps = translateSet(cellPathResolver, pattern, node.getDeclaredDeps());
    Optional<ImmutableSet<BuildTarget>> extraDeps = translateSet(cellPathResolver, pattern, node.getExtraDeps());
    Optional<ImmutableMap<BuildTarget, Version>> newSelectedVersions = getSelectedVersions(node.getBuildTarget());
    Optional<ImmutableMap<BuildTarget, Version>> oldSelectedVersions = node.getSelectedVersions();
    Optional<Optional<ImmutableMap<BuildTarget, Version>>> selectedVersions = oldSelectedVersions.equals(newSelectedVersions) ? Optional.empty() : Optional.of(newSelectedVersions);
    // If nothing has changed, don't generate a new node.
    if (!target.isPresent() && !constructorArg.isPresent() && !declaredDeps.isPresent() && !extraDeps.isPresent() && !selectedVersions.isPresent()) {
        return Optional.empty();
    }
    return Optional.of(node.withTargetConstructorArgDepsAndSelectedVerisons(target.orElse(node.getBuildTarget()), constructorArg.orElse(node.getConstructorArg()), declaredDeps.orElse(node.getDeclaredDeps()), extraDeps.orElse(node.getExtraDeps()), selectedVersions.orElse(oldSelectedVersions)));
}
Also used : BuildTargetPattern(com.facebook.buck.model.BuildTargetPattern) Optional(java.util.Optional) ImmutableMap(com.google.common.collect.ImmutableMap) ImmutableSet(com.google.common.collect.ImmutableSet) BuildTarget(com.facebook.buck.model.BuildTarget) CellPathResolver(com.facebook.buck.rules.CellPathResolver)

Example 48 with Optional

use of java.util.Optional in project buck by facebook.

the class AppleConfigTest method getXcodeSelectDetectedAppleDeveloperDirectorySupplier.

@Test
public void getXcodeSelectDetectedAppleDeveloperDirectorySupplier() {
    BuckConfig buckConfig = FakeBuckConfig.builder().build();
    AppleConfig config = new AppleConfig(buckConfig);
    ProcessExecutorParams xcodeSelectParams = ProcessExecutorParams.builder().setCommand(ImmutableList.of("xcode-select", "--print-path")).build();
    FakeProcess fakeXcodeSelect = new FakeProcess(0, "/path/to/another/place", "");
    FakeProcessExecutor processExecutor = new FakeProcessExecutor(ImmutableMap.of(xcodeSelectParams, fakeXcodeSelect));
    Supplier<Optional<Path>> supplier = config.getAppleDeveloperDirectorySupplier(processExecutor);
    assertNotNull(supplier);
    assertEquals(Optional.of(Paths.get("/path/to/another/place")), supplier.get());
}
Also used : ProcessExecutorParams(com.facebook.buck.util.ProcessExecutorParams) FakeBuckConfig(com.facebook.buck.cli.FakeBuckConfig) BuckConfig(com.facebook.buck.cli.BuckConfig) Optional(java.util.Optional) FakeProcessExecutor(com.facebook.buck.util.FakeProcessExecutor) FakeProcess(com.facebook.buck.util.FakeProcess) Test(org.junit.Test)

Example 49 with Optional

use of java.util.Optional in project buck by facebook.

the class AppleConfigTest method getSpecifiedAppleDeveloperDirectorySupplier.

@Test
public void getSpecifiedAppleDeveloperDirectorySupplier() {
    BuckConfig buckConfig = FakeBuckConfig.builder().setSections(ImmutableMap.of("apple", ImmutableMap.of("xcode_developer_dir", "/path/to/somewhere"))).build();
    AppleConfig config = new AppleConfig(buckConfig);
    Supplier<Optional<Path>> supplier = config.getAppleDeveloperDirectorySupplier(new FakeProcessExecutor());
    assertNotNull(supplier);
    assertEquals(Optional.of(Paths.get("/path/to/somewhere")), supplier.get());
    // Developer directory for tests should fall back to developer dir if not separately specified.
    Supplier<Optional<Path>> supplierForTests = config.getAppleDeveloperDirectorySupplierForTests(new FakeProcessExecutor());
    assertNotNull(supplierForTests);
    assertEquals(Optional.of(Paths.get("/path/to/somewhere")), supplierForTests.get());
}
Also used : FakeBuckConfig(com.facebook.buck.cli.FakeBuckConfig) BuckConfig(com.facebook.buck.cli.BuckConfig) Optional(java.util.Optional) FakeProcessExecutor(com.facebook.buck.util.FakeProcessExecutor) Test(org.junit.Test)

Example 50 with Optional

use of java.util.Optional in project buck by facebook.

the class ProvisioningProfileCopyStepTest method testDoesNotFailInDryRunMode.

@Test
public void testDoesNotFailInDryRunMode() throws Exception {
    assumeTrue(Platform.detect() == Platform.MACOS);
    Path emptyDir = TestDataHelper.getTestDataDirectory(this).resolve("provisioning_profiles_empty");
    ProvisioningProfileCopyStep step = new ProvisioningProfileCopyStep(projectFilesystem, testdataDir.resolve("Info.plist"), ApplePlatform.IPHONEOS, Optional.empty(), Optional.empty(), ProvisioningProfileStore.fromSearchPath(new DefaultProcessExecutor(new TestConsole()), ProvisioningProfileStore.DEFAULT_READ_COMMAND, emptyDir), outputFile, xcentFile, codeSignIdentityStore, Optional.of(dryRunResultFile));
    Future<Optional<ProvisioningProfileMetadata>> profileFuture = step.getSelectedProvisioningProfileFuture();
    step.execute(executionContext);
    assertTrue(profileFuture.isDone());
    assertNotNull(profileFuture.get());
    assertFalse(profileFuture.get().isPresent());
    Optional<String> resultContents = projectFilesystem.readFileIfItExists(dryRunResultFile);
    assertTrue(resultContents.isPresent());
    NSDictionary resultPlist = (NSDictionary) PropertyListParser.parse(resultContents.get().getBytes(Charsets.UTF_8));
    assertEquals(new NSString("com.example.TestApp"), resultPlist.get("bundle-id"));
}
Also used : Path(java.nio.file.Path) DefaultProcessExecutor(com.facebook.buck.util.DefaultProcessExecutor) Optional(java.util.Optional) NSDictionary(com.dd.plist.NSDictionary) NSString(com.dd.plist.NSString) TestConsole(com.facebook.buck.testutil.TestConsole) NSString(com.dd.plist.NSString) Test(org.junit.Test)

Aggregations

Optional (java.util.Optional)414 List (java.util.List)208 Map (java.util.Map)138 ArrayList (java.util.ArrayList)107 Set (java.util.Set)95 Collectors (java.util.stream.Collectors)92 IOException (java.io.IOException)85 ImmutableList (com.google.common.collect.ImmutableList)82 ImmutableMap (com.google.common.collect.ImmutableMap)75 Test (org.junit.Test)69 ImmutableSet (com.google.common.collect.ImmutableSet)65 HashMap (java.util.HashMap)65 Path (java.nio.file.Path)55 Logger (org.slf4j.Logger)54 LoggerFactory (org.slf4j.LoggerFactory)53 Collections (java.util.Collections)51 Collection (java.util.Collection)48 Arrays (java.util.Arrays)42 BuildTarget (com.facebook.buck.model.BuildTarget)40 HashSet (java.util.HashSet)37