Search in sources :

Example 6 with SimpleFileVisitor

use of java.nio.file.SimpleFileVisitor in project intellij-community by JetBrains.

the class LocalFileSystemTest method doTestInterruptedRefresh.

public static void doTestInterruptedRefresh(@NotNull File top) throws Exception {
    for (int i = 1; i <= 3; i++) {
        File sub = IoTestUtil.createTestDir(top, "sub_" + i);
        for (int j = 1; j <= 3; j++) {
            IoTestUtil.createTestDir(sub, "sub_" + j);
        }
    }
    Files.walkFileTree(top.toPath(), new SimpleFileVisitor<Path>() {

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            for (int k = 1; k <= 3; k++) {
                IoTestUtil.createTestFile(dir.toFile(), "file_" + k, ".");
            }
            return FileVisitResult.CONTINUE;
        }
    });
    VirtualFile topDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(top);
    assertNotNull(topDir);
    Set<VirtualFile> files = ContainerUtil.newHashSet();
    VfsUtilCore.processFilesRecursively(topDir, file -> {
        if (!file.isDirectory())
            files.add(file);
        return true;
    });
    // 13 dirs of 3 files
    assertEquals(39, files.size());
    topDir.refresh(false, true);
    Set<VirtualFile> processed = ContainerUtil.newHashSet();
    MessageBusConnection connection = ApplicationManager.getApplication().getMessageBus().connect();
    connection.subscribe(VirtualFileManager.VFS_CHANGES, new BulkFileListener() {

        @Override
        public void after(@NotNull List<? extends VFileEvent> events) {
            events.forEach(e -> processed.add(e.getFile()));
        }
    });
    try {
        files.forEach(f -> IoTestUtil.updateFile(new File(f.getPath()), "+++"));
        ((NewVirtualFile) topDir).markDirtyRecursively();
        RefreshWorker.setCancellingCondition(file -> file.getPath().endsWith(top.getName() + "/sub_2/file_2"));
        topDir.refresh(false, true);
        assertThat(processed.size()).isGreaterThan(0).isLessThan(files.size());
        RefreshWorker.setCancellingCondition(null);
        topDir.refresh(false, true);
        assertThat(processed).isEqualTo(files);
    } finally {
        connection.disconnect();
        RefreshWorker.setCancellingCondition(null);
    }
}
Also used : Path(java.nio.file.Path) VfsRootAccess(com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess) java.util(java.util) WriteAction(com.intellij.openapi.application.WriteAction) ArrayUtil(com.intellij.util.ArrayUtil) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) FileAttributes(com.intellij.openapi.util.io.FileAttributes) ContainerUtil(com.intellij.util.containers.ContainerUtil) FileSystemUtil(com.intellij.openapi.util.io.FileSystemUtil) MessageBusConnection(com.intellij.util.messages.MessageBusConnection) com.intellij.openapi.vfs.newvfs(com.intellij.openapi.vfs.newvfs) PersistentFSImpl(com.intellij.openapi.vfs.newvfs.persistent.PersistentFSImpl) VFileCreateEvent(com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent) FileUtil(com.intellij.openapi.util.io.FileUtil) VFileDeleteEvent(com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent) Path(java.nio.file.Path) VFileEvent(com.intellij.openapi.vfs.newvfs.events.VFileEvent) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) RefreshWorker(com.intellij.openapi.vfs.newvfs.persistent.RefreshWorker) PlatformTestUtil(com.intellij.testFramework.PlatformTestUtil) Files(java.nio.file.Files) StringUtil(com.intellij.openapi.util.text.StringUtil) PlatformTestCase(com.intellij.testFramework.PlatformTestCase) PersistentFS(com.intellij.openapi.vfs.newvfs.persistent.PersistentFS) IOException(java.io.IOException) VirtualDirectoryImpl(com.intellij.openapi.vfs.newvfs.impl.VirtualDirectoryImpl) VFileContentChangeEvent(com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent) SystemInfo(com.intellij.openapi.util.SystemInfo) File(java.io.File) FileVisitResult(java.nio.file.FileVisitResult) ApplicationManager(com.intellij.openapi.application.ApplicationManager) IoTestUtil(com.intellij.openapi.util.io.IoTestUtil) com.intellij.openapi.vfs(com.intellij.openapi.vfs) GeneralSettings(com.intellij.ide.GeneralSettings) VirtualFileSystemEntry(com.intellij.openapi.vfs.newvfs.impl.VirtualFileSystemEntry) ObjectUtils(com.intellij.util.ObjectUtils) NotNull(org.jetbrains.annotations.NotNull) MessageBusConnection(com.intellij.util.messages.MessageBusConnection) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) File(java.io.File)

Example 7 with SimpleFileVisitor

use of java.nio.file.SimpleFileVisitor in project buck by facebook.

the class ProjectWorkspace method assertPathsEqual.

/**
   * For every file in the template directory whose name ends in {@code .expected}, checks that an
   * equivalent file has been written in the same place under the destination directory.
   *
   * @param templateSubdirectory An optional subdirectory to check. Only files in this directory
   *                     will be compared.
   */
private void assertPathsEqual(final Path templateSubdirectory, final Path destinationSubdirectory) throws IOException {
    SimpleFileVisitor<Path> copyDirVisitor = new SimpleFileVisitor<Path>() {

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            String fileName = file.getFileName().toString();
            if (fileName.endsWith(EXPECTED_SUFFIX)) {
                // Get File for the file that should be written, but without the ".expected" suffix.
                Path generatedFileWithSuffix = destinationSubdirectory.resolve(templateSubdirectory.relativize(file));
                Path directory = generatedFileWithSuffix.getParent();
                Path observedFile = directory.resolve(MorePaths.getNameWithoutExtension(file));
                assertFilesEqual(file, observedFile);
            }
            return FileVisitResult.CONTINUE;
        }
    };
    Files.walkFileTree(templateSubdirectory, copyDirVisitor);
}
Also used : Path(java.nio.file.Path) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 8 with SimpleFileVisitor

use of java.nio.file.SimpleFileVisitor in project buck by facebook.

the class ProjectWorkspace method setUp.

/**
   * This will copy the template directory, renaming files named {@code foo.fixture} to {@code foo}
   * in the process. Files whose names end in {@code .expected} will not be copied.
   */
@SuppressWarnings("PMD.EmptyCatchBlock")
public ProjectWorkspace setUp() throws IOException {
    MoreFiles.copyRecursively(templatePath, destPath, BUILD_FILE_RENAME);
    // Stamp the buck-out directory if it exists and isn't stamped already
    try (OutputStream outputStream = new BufferedOutputStream(Channels.newOutputStream(Files.newByteChannel(destPath.resolve(BuckConstant.getBuckOutputPath().resolve(".currentversion")), ImmutableSet.<OpenOption>of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE))))) {
        outputStream.write(BuckVersion.getVersion().getBytes(Charsets.UTF_8));
    } catch (FileAlreadyExistsException | NoSuchFileException e) {
    // If the current version file already exists we don't need to create it
    // If buck-out doesn't exist we don't need to stamp it
    }
    if (Platform.detect() == Platform.WINDOWS) {
        // Hack for symlinks on Windows.
        SimpleFileVisitor<Path> copyDirVisitor = new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
                // On NTFS length of path must be greater than 0 and less than 4096.
                if (attrs.size() > 0 && attrs.size() <= 4096) {
                    String linkTo = new String(Files.readAllBytes(path), UTF_8);
                    Path linkToFile;
                    try {
                        linkToFile = templatePath.resolve(linkTo);
                    } catch (InvalidPathException e) {
                        // link.
                        return FileVisitResult.CONTINUE;
                    }
                    if (Files.isRegularFile(linkToFile)) {
                        Files.copy(linkToFile, path, StandardCopyOption.REPLACE_EXISTING);
                    } else if (Files.isDirectory(linkToFile)) {
                        Files.delete(path);
                        MoreFiles.copyRecursively(linkToFile, path);
                    }
                }
                return FileVisitResult.CONTINUE;
            }
        };
        Files.walkFileTree(destPath, copyDirVisitor);
    }
    if (!Files.exists(getPath(".buckconfig.local"))) {
        manageLocalConfigs = true;
        // Disable the directory cache by default.  Tests that want to enable it can call
        // `enableDirCache` on this object.  Only do this if a .buckconfig.local file does not already
        // exist, however (we assume the test knows what it is doing at that point).
        addBuckConfigLocalOption("cache", "mode", "");
        // Limit the number of threads by default to prevent multiple integration tests running at the
        // same time from creating a quadratic number of threads. Tests can disable this using
        // `disableThreadLimitOverride`.
        addBuckConfigLocalOption("build", "threads", "2");
    }
    isSetUp = true;
    return this;
}
Also used : Path(java.nio.file.Path) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) NoSuchFileException(java.nio.file.NoSuchFileException) BufferedOutputStream(java.io.BufferedOutputStream) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) InvalidPathException(java.nio.file.InvalidPathException)

Example 9 with SimpleFileVisitor

use of java.nio.file.SimpleFileVisitor in project buck by facebook.

the class ProvisioningProfileStore method fromSearchPath.

public static ProvisioningProfileStore fromSearchPath(final ProcessExecutor executor, final ImmutableList<String> readCommand, final Path searchPath) {
    LOG.debug("Provisioning profile search path: " + searchPath);
    return new ProvisioningProfileStore(Suppliers.memoize(() -> {
        final ImmutableList.Builder<ProvisioningProfileMetadata> profilesBuilder = ImmutableList.builder();
        try {
            Files.walkFileTree(searchPath.toAbsolutePath(), new SimpleFileVisitor<Path>() {

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (file.toString().endsWith(".mobileprovision")) {
                        try {
                            ProvisioningProfileMetadata profile = ProvisioningProfileMetadata.fromProvisioningProfilePath(executor, readCommand, file);
                            profilesBuilder.add(profile);
                        } catch (IOException | IllegalArgumentException e) {
                            LOG.error(e, "Ignoring invalid or malformed .mobileprovision file");
                        } catch (InterruptedException e) {
                            throw new IOException(e);
                        }
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            if (e.getCause() instanceof InterruptedException) {
                LOG.error(e, "Interrupted while searching for mobileprovision files");
            } else {
                LOG.error(e, "Error while searching for mobileprovision files");
            }
        }
        return profilesBuilder.build();
    }));
}
Also used : Path(java.nio.file.Path) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 10 with SimpleFileVisitor

use of java.nio.file.SimpleFileVisitor in project buck by facebook.

the class MoreFiles method copyRecursively.

public static void copyRecursively(final Path fromPath, final Path toPath, final Function<Path, Path> transform, final Function<Path, Boolean> filter) throws IOException {
    // Adapted from http://codingjunkie.net/java-7-copy-move/.
    SimpleFileVisitor<Path> copyDirVisitor = new SimpleFileVisitor<Path>() {

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            Path targetPath = toPath.resolve(fromPath.relativize(dir));
            if (!Files.exists(targetPath)) {
                Files.createDirectory(targetPath);
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (!filter.apply(file)) {
                return FileVisitResult.CONTINUE;
            }
            Path destPath = toPath.resolve(fromPath.relativize(file));
            Path transformedDestPath = transform.apply(destPath);
            if (transformedDestPath != null) {
                if (Files.isSymbolicLink(file)) {
                    Files.deleteIfExists(transformedDestPath);
                    Files.createSymbolicLink(transformedDestPath, Files.readSymbolicLink(file));
                } else {
                    Files.copy(file, transformedDestPath, StandardCopyOption.REPLACE_EXISTING);
                }
            }
            return FileVisitResult.CONTINUE;
        }
    };
    Files.walkFileTree(fromPath, copyDirVisitor);
}
Also used : Path(java.nio.file.Path) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Aggregations

Path (java.nio.file.Path)11 SimpleFileVisitor (java.nio.file.SimpleFileVisitor)11 BasicFileAttributes (java.nio.file.attribute.BasicFileAttributes)10 IOException (java.io.IOException)8 SourcePath (com.facebook.buck.rules.SourcePath)3 AbstractExecutionStep (com.facebook.buck.step.AbstractExecutionStep)2 ExecutionContext (com.facebook.buck.step.ExecutionContext)2 StepExecutionResult (com.facebook.buck.step.StepExecutionResult)2 MakeCleanDirectoryStep (com.facebook.buck.step.fs.MakeCleanDirectoryStep)2 InputStream (java.io.InputStream)2 FileVisitResult (java.nio.file.FileVisitResult)2 TargetCpuType (com.facebook.buck.android.NdkCxxPlatforms.TargetCpuType)1 ProjectFilesystem (com.facebook.buck.io.ProjectFilesystem)1 Pair (com.facebook.buck.model.Pair)1 ExplicitBuildTargetSourcePath (com.facebook.buck.rules.ExplicitBuildTargetSourcePath)1 PathSourcePath (com.facebook.buck.rules.PathSourcePath)1 Step (com.facebook.buck.step.Step)1 CopyStep (com.facebook.buck.step.fs.CopyStep)1 MkdirStep (com.facebook.buck.step.fs.MkdirStep)1 XzStep (com.facebook.buck.step.fs.XzStep)1