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;
}
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)));
}
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());
}
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());
}
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"));
}
Aggregations