Java Code Examples for org.gradle.api.file.RelativePath

The following examples show how to use org.gradle.api.file.RelativePath. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public WorkResult execute(final CopyActionProcessingStream stream) {
    final Set<RelativePath> visited = new HashSet<RelativePath>();

    WorkResult didWork = delegate.execute(new CopyActionProcessingStream() {
        public void process(final CopyActionProcessingStreamAction action) {
            stream.process(new CopyActionProcessingStreamAction() {
                public void processFile(FileCopyDetailsInternal details) {
                    visited.add(details.getRelativePath());
                    action.processFile(details);
                }
            });
        }
    });

    SyncCopyActionDecoratorFileVisitor fileVisitor = new SyncCopyActionDecoratorFileVisitor(visited);

    MinimalFileTree walker = new DirectoryFileTree(baseDestDir).postfix();
    walker.visit(fileVisitor);
    visited.clear();

    return new SimpleWorkResult(didWork.getDidWork() || fileVisitor.didWork);
}
 
Example 2
Source Project: javaide   Source File: LibraryCache.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void unzipAar(final File bundle, final File folderOut, final Project project) throws IOException {
    FileUtils.deleteFolder(folderOut);
    folderOut.mkdirs();
    project.copy(new Action<CopySpec>() {
        @Override
        public void execute(CopySpec copySpec) {
            copySpec.from(project.zipTree(bundle));
            copySpec.into(new Object[]{folderOut});
            copySpec.filesMatching("**/*.jar", new Action<FileCopyDetails>() {
                @Override
                public void execute(FileCopyDetails details) {
                    setRelativePath(details, new RelativePath(false, FD_JARS).plus(details.getRelativePath()));
                }
            });
        }
    });
}
 
Example 3
public WorkResult execute(final CopyActionProcessingStream stream) {
    final Set<RelativePath> visited = new HashSet<RelativePath>();

    WorkResult didWork = delegate.execute(new CopyActionProcessingStream() {
        public void process(final CopyActionProcessingStreamAction action) {
            stream.process(new CopyActionProcessingStreamAction() {
                public void processFile(FileCopyDetailsInternal details) {
                    visited.add(details.getRelativePath());
                    action.processFile(details);
                }
            });
        }
    });

    SyncCopyActionDecoratorFileVisitor fileVisitor = new SyncCopyActionDecoratorFileVisitor(visited);

    MinimalFileTree walker = new DirectoryFileTree(baseDestDir).postfix();
    walker.visit(fileVisitor);
    visited.clear();

    return new SimpleWorkResult(didWork.getDidWork() || fileVisitor.didWork);
}
 
Example 4
Source Project: javaccPlugin   Source File: JavaccSourceFileVisitorTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenAJavaccSourceFileWhenVisitFileThenDelegatesToTaskCompile() {
    FileVisitDetails fileDetails = mock(FileVisitDetails.class);
    when(fileDetails.getFile()).thenReturn(new File(JAVACC_SOURCE_FILE));
    when(fileDetails.getName()).thenReturn(JAVACC_SOURCE_FILE);
    when(fileDetails.getPath()).thenReturn(JAVACC_SOURCE_FILE);

    sourceVisitor.visitFile(fileDetails);

    verify(compiler).compile(any(File.class), any(RelativePath.class));
}
 
Example 5
public File transform(RelativePath relativePath) {
    String sourceFileName = relativePath.getLastName();
    
    String destinationFileNameBase = sourceFileName;
    if (sourceFileName.endsWith(".coffee")) {
        destinationFileNameBase = sourceFileName.substring(0, sourceFileName.length() - 7);
    }
    
    String destinationFileName = String.format("%s.js", destinationFileNameBase);
    RelativePath destinationRelativePath = relativePath.replaceLastName(destinationFileName);
    return new File(destination, destinationRelativePath.getPathString());
}
 
Example 6
public Spec<FileTreeElement> getAsIncludeSpec() {
    List<Spec<FileTreeElement>> matchers = Lists.newArrayList();
    for (String include : includes) {
        Spec<RelativePath> patternMatcher = PatternMatcherFactory.getPatternMatcher(true, caseSensitive, include);
        matchers.add(new RelativePathSpec(patternMatcher));
    }

    matchers.addAll(includeSpecs);
    return new OrSpec<FileTreeElement>(matchers);
}
 
Example 7
public Spec<FileTreeElement> getAsExcludeSpec() {
    Collection<String> allExcludes = Sets.newLinkedHashSet(excludes);
    Collections.addAll(allExcludes, DirectoryScanner.getDefaultExcludes());

    List<Spec<FileTreeElement>> matchers = Lists.newArrayList();
    for (String exclude : allExcludes) {
        Spec<RelativePath> patternMatcher = PatternMatcherFactory.getPatternMatcher(false, caseSensitive, exclude);
        matchers.add(new RelativePathSpec(patternMatcher));
    }

    matchers.addAll(excludeSpecs);
    return new OrSpec<FileTreeElement>(matchers);
}
 
Example 8
public boolean isSatisfiedBy(RelativePath element) {
    if (element.isFile() || !partialMatchDirs) {
        return pathMatcher.matches(element.getSegments(), 0);
    } else {
        return pathMatcher.isPrefix(element.getSegments(), 0);
    }
}
 
Example 9
private void visitDirs(RelativePath path, FileVisitor visitor) {
    if (path == null || path.getParent() == null || !visitedDirs.add(path)) {
        return;
    }

    visitDirs(path.getParent(), visitor);
    visitor.visitDir(new FileVisitDetailsImpl(path, null, stopFlag, chmod));
}
 
Example 10
private void doVisit(FileVisitor visitor, File file, LinkedList<String> relativePath, int segmentIndex, AtomicBoolean stopFlag) {
    if (stopFlag.get()) {
        return;
    }

    String segment = patternSegments.get(segmentIndex);

    if (segment.contains("**")) {
        PatternSet patternSet = new PatternSet();
        patternSet.include(includePattern);
        patternSet.exclude(excludeSpec);
        DirectoryFileTree fileTree = new DirectoryFileTree(baseDir, patternSet);
        fileTree.visitFrom(visitor, file, new RelativePath(file.isFile(), relativePath.toArray(new String[relativePath.size()])));
    } else if (segment.contains("*") || segment.contains("?")) {
        PatternStep step = PatternStepFactory.getStep(segment, false);
        File[] children = file.listFiles();
        if (children == null) {
            if (!file.canRead()) {
                throw new GradleException(String.format("Could not list contents of directory '%s' as it is not readable.", file));
            }
            // else, might be a link which points to nothing, or has been removed while we're visiting, or ...
            throw new GradleException(String.format("Could not list contents of '%s'.", file));
        }
        for (File child : children) {
            if (stopFlag.get()) { break; }
            if (step.matches(child.getName())) {
                relativePath.addLast(child.getName());
                doVisitDirOrFile(visitor, child, relativePath, segmentIndex + 1, stopFlag);
                relativePath.removeLast();
            }
        }
    } else {
        relativePath.addLast(segment);
        doVisitDirOrFile(visitor, new File(file, segment), relativePath, segmentIndex + 1, stopFlag);
        relativePath.removeLast();
    }
}
 
Example 11
public RelativePath getRelativePath() {
    if (relativePath == null) {
        RelativePath path = fileDetails.getRelativePath();
        relativePath = specResolver.getDestPath().append(path.isFile(), path.getSegments());
    }
    return relativePath;
}
 
Example 12
public boolean isSatisfiedBy(RelativePath element) {
    if (element.isFile() || !partialMatchDirs) {
        return pathMatcher.matches(element.getSegments(), 0);
    } else {
        return pathMatcher.isPrefix(element.getSegments(), 0);
    }
}
 
Example 13
Source Project: crate   Source File: JdkDownloadPlugin.java    License: Apache License 2.0 5 votes vote down vote up
private static TaskProvider<?> createExtractTask(
    String taskName,
    Project rootProject,
    boolean isWindows,
    Provider<Directory> extractPath,
    Supplier<File> jdkBundle) {
    if (isWindows) {
        Action<CopySpec> removeRootDir = copy -> {
            // remove extra unnecessary directory levels
            copy.eachFile(details -> {
                Path newPathSegments = trimArchiveExtractPath(details.getRelativePath().getPathString());
                String[] segments = StreamSupport.stream(newPathSegments.spliterator(), false)
                    .map(Path::toString)
                    .toArray(String[]::new);
                details.setRelativePath(new RelativePath(true, segments));
            });
            copy.setIncludeEmptyDirs(false);
        };

        return rootProject.getTasks().register(taskName, Copy.class, copyTask -> {
            copyTask.doFirst(t -> rootProject.delete(extractPath));
            copyTask.into(extractPath);
            Callable<FileTree> fileGetter = () -> rootProject.zipTree(jdkBundle.get());
            copyTask.from(fileGetter, removeRootDir);
        });
    } else {
        /*
         * Gradle TarFileTree does not resolve symlinks, so we have to manually
         * extract and preserve the symlinks. cf. https://github.com/gradle/gradle/issues/3982
         * and https://discuss.gradle.org/t/tar-and-untar-losing-symbolic-links/2039
         */
        return rootProject.getTasks().register(taskName, SymbolicLinkPreservingUntarTask.class, task -> {
            task.getTarFile().fileProvider(rootProject.provider(jdkBundle::get));
            task.getExtractPath().set(extractPath);
            task.setTransform(JdkDownloadPlugin::trimArchiveExtractPath);
        });
    }
}
 
Example 14
public RelativePath getRelativePath() {
    if (relativePath == null) {
        RelativePath path = fileDetails.getRelativePath();
        relativePath = spec.getDestPath().append(path.isFile(), path.getSegments());
    }
    return relativePath;
}
 
Example 15
private void maybeDelete(FileVisitDetails fileDetails, boolean isDir) {
    RelativePath path = fileDetails.getRelativePath();
    if (!visited.contains(path)) {
        if (isDir) {
            GFileUtils.deleteDirectory(fileDetails.getFile());
        } else {
            GFileUtils.deleteQuietly(fileDetails.getFile());
        }
        didWork = true;
    }
}
 
Example 16
public WorkResult execute(final CopyActionProcessingStream stream) {
    final Set<RelativePath> visitedFiles = new HashSet<RelativePath>();

    return delegate.execute(new CopyActionProcessingStream() {
        public void process(final CopyActionProcessingStreamAction action) {
            stream.process(new CopyActionProcessingStreamAction() {
                public void processFile(FileCopyDetailsInternal details) {
                    if (!details.isDirectory()) {
                        DuplicatesStrategy strategy = details.getDuplicatesStrategy();

                        if (!visitedFiles.add(details.getRelativePath())) {
                            if (strategy == DuplicatesStrategy.EXCLUDE) {
                                return;
                            } else if (strategy == DuplicatesStrategy.FAIL) {
                                throw new DuplicateFileCopyingException(String.format("Encountered duplicate path \"%s\" during copy operation configured with DuplicatesStrategy.FAIL", details.getRelativePath()));
                            } else if (strategy == DuplicatesStrategy.WARN) {
                                LOGGER.warn("Encountered duplicate path \"{}\" during copy operation configured with DuplicatesStrategy.WARN", details.getRelativePath());
                            }
                        }
                    }

                    action.processFile(details);
                }
            });
        }
    });
}
 
Example 17
private void doVisit(FileVisitor visitor, File file, LinkedList<String> relativePath, int segmentIndex, AtomicBoolean stopFlag) {
    if (stopFlag.get()) {
        return;
    }

    String segment = patternSegments.get(segmentIndex);

    if (segment.contains("**")) {
        PatternSet patternSet = new PatternSet();
        patternSet.include(includePattern);
        patternSet.exclude(excludeSpec);
        DirectoryFileTree fileTree = new DirectoryFileTree(baseDir, patternSet);
        fileTree.visitFrom(visitor, file, new RelativePath(file.isFile(), relativePath.toArray(new String[relativePath.size()])));
    } else if (segment.contains("*") || segment.contains("?")) {
        PatternStep step = PatternStepFactory.getStep(segment, false);
        File[] children = file.listFiles();
        if (children == null) {
            if (!file.canRead()) {
                throw new GradleException(String.format("Could not list contents of directory '%s' as it is not readable.", file));
            }
            // else, might be a link which points to nothing, or has been removed while we're visiting, or ...
            throw new GradleException(String.format("Could not list contents of '%s'.", file));
        }
        for (File child : children) {
            if (stopFlag.get()) { break; }
            if (step.matches(child.getName())) {
                relativePath.addLast(child.getName());
                doVisitDirOrFile(visitor, child, relativePath, segmentIndex + 1, stopFlag);
                relativePath.removeLast();
            }
        }
    } else {
        relativePath.addLast(segment);
        doVisitDirOrFile(visitor, new File(file, segment), relativePath, segmentIndex + 1, stopFlag);
        relativePath.removeLast();
    }
}
 
Example 18
public File transform(RelativePath relativePath) {
    String sourceFileName = relativePath.getLastName();
    
    String destinationFileNameBase = sourceFileName;
    if (sourceFileName.endsWith(".coffee")) {
        destinationFileNameBase = sourceFileName.substring(0, sourceFileName.length() - 7);
    }
    
    String destinationFileName = String.format("%s.js", destinationFileNameBase);
    RelativePath destinationRelativePath = relativePath.replaceLastName(destinationFileName);
    return new File(destination, destinationRelativePath.getPathString());
}
 
Example 19
public Spec<FileTreeElement> getAsExcludeSpec() {
    Collection<String> allExcludes = Sets.newLinkedHashSet(excludes);
    Collections.addAll(allExcludes, DirectoryScanner.getDefaultExcludes());

    List<Spec<FileTreeElement>> matchers = Lists.newArrayList();
    for (String exclude : allExcludes) {
        Spec<RelativePath> patternMatcher = PatternMatcherFactory.getPatternMatcher(false, caseSensitive, exclude);
        matchers.add(new RelativePathSpec(patternMatcher));
    }

    matchers.addAll(excludeSpecs);
    return new OrSpec<FileTreeElement>(matchers);
}
 
Example 20
Source Project: javaccPlugin   Source File: JjdocProgramInvokerTest.java    License: MIT License 5 votes vote down vote up
private void givenArgumentsWhenAugmentArgumentsThenExpectOutputFileWithExtension(ProgramArguments arguments, String extension) throws IOException {
    File inputDirectory = testFolder.newFolder("input");
    RelativePath fileToCompile = new RelativePath(true, "MyClass.jj");

    ProgramArguments augmentedArguments = programInvoker.augmentArguments(inputDirectory, fileToCompile, arguments);

    String expectedOutputFileArgument = String.format("-OUTPUT_FILE=%s" + File.separator + "%s.%s", tempOutputDirectory.getAbsolutePath(), "MyClass", extension);
    assertThat(augmentedArguments.get(augmentedArguments.size() - 1), is(equalTo(expectedOutputFileArgument)));
}
 
Example 21
public boolean isSatisfiedBy(RelativePath element) {
    if (element.isFile() || !partialMatchDirs) {
        return pathMatcher.matches(element.getSegments(), 0);
    } else {
        return pathMatcher.isPrefix(element.getSegments(), 0);
    }
}
 
Example 22
private void visitDirs(RelativePath path, FileVisitor visitor) {
    if (path == null || path.getParent() == null || !visitedDirs.add(path)) {
        return;
    }

    visitDirs(path.getParent(), visitor);
    visitor.visitDir(new FileVisitDetailsImpl(path, null, stopFlag, chmod));
}
 
Example 23
private void doVisit(FileVisitor visitor, File file, LinkedList<String> relativePath, int segmentIndex, AtomicBoolean stopFlag) {
    if (stopFlag.get()) {
        return;
    }

    String segment = patternSegments.get(segmentIndex);

    if (segment.contains("**")) {
        PatternSet patternSet = new PatternSet();
        patternSet.include(includePattern);
        patternSet.exclude(excludeSpec);
        DirectoryFileTree fileTree = new DirectoryFileTree(baseDir, patternSet);
        fileTree.visitFrom(visitor, file, new RelativePath(file.isFile(), relativePath.toArray(new String[relativePath.size()])));
    } else if (segment.contains("*") || segment.contains("?")) {
        PatternStep step = PatternStepFactory.getStep(segment, false);
        File[] children = file.listFiles();
        if (children == null) {
            if (!file.canRead()) {
                throw new GradleException(String.format("Could not list contents of directory '%s' as it is not readable.", file));
            }
            // else, might be a link which points to nothing, or has been removed while we're visiting, or ...
            throw new GradleException(String.format("Could not list contents of '%s'.", file));
        }
        for (File child : children) {
            if (stopFlag.get()) { break; }
            if (step.matches(child.getName())) {
                relativePath.addLast(child.getName());
                doVisitDirOrFile(visitor, child, relativePath, segmentIndex + 1, stopFlag);
                relativePath.removeLast();
            }
        }
    } else {
        relativePath.addLast(segment);
        doVisitDirOrFile(visitor, new File(file, segment), relativePath, segmentIndex + 1, stopFlag);
        relativePath.removeLast();
    }
}
 
Example 24
public WorkResult execute(final CopyActionProcessingStream stream) {
    final Set<RelativePath> visitedFiles = new HashSet<RelativePath>();

    return delegate.execute(new CopyActionProcessingStream() {
        public void process(final CopyActionProcessingStreamAction action) {
            stream.process(new CopyActionProcessingStreamAction() {
                public void processFile(FileCopyDetailsInternal details) {
                    if (!details.isDirectory()) {
                        DuplicatesStrategy strategy = details.getDuplicatesStrategy();

                        if (!visitedFiles.add(details.getRelativePath())) {
                            if (strategy == DuplicatesStrategy.EXCLUDE) {
                                return;
                            } else if (strategy == DuplicatesStrategy.FAIL) {
                                throw new DuplicateFileCopyingException(String.format("Encountered duplicate path \"%s\" during copy operation configured with DuplicatesStrategy.FAIL", details.getRelativePath()));
                            } else if (strategy == DuplicatesStrategy.WARN) {
                                LOGGER.warn("Encountered duplicate path \"{}\" during copy operation configured with DuplicatesStrategy.WARN", details.getRelativePath());
                            }
                        }
                    }

                    action.processFile(details);
                }
            });
        }
    });
}
 
Example 25
private void maybeDelete(FileVisitDetails fileDetails, boolean isDir) {
    RelativePath path = fileDetails.getRelativePath();
    if (!visited.contains(path)) {
        if (isDir) {
            GFileUtils.deleteDirectory(fileDetails.getFile());
        } else {
            GFileUtils.deleteQuietly(fileDetails.getFile());
        }
        didWork = true;
    }
}
 
Example 26
Source Project: javaccPlugin   Source File: JavaccSourceFileCompilerTest.java    License: MIT License 5 votes vote down vote up
@Test
public void compileThrowsExceptionWhenUnderlyingProgramInvokerFails() throws Exception {
    Exception programFailure = new RuntimeException();
    doThrow(programFailure).when(programInvoker).invokeCompiler(programArguments);

    RelativePath fileToCompile = givenFileToCompile();

    thrown.expect(JavaccTaskException.class);
    thrown.expectCause(is(programFailure));

    compiler.compile(inputFolder, fileToCompile);
}
 
Example 27
private void visitDirs(RelativePath path, FileVisitor visitor) {
    if (path == null || path.getParent() == null || !visitedDirs.add(path)) {
        return;
    }

    visitDirs(path.getParent(), visitor);
    visitor.visitDir(new FileVisitDetailsImpl(path, null, stopFlag, chmod));
}
 
Example 28
public File transform(RelativePath relativePath) {
    String sourceFileName = relativePath.getLastName();
    
    String destinationFileNameBase = sourceFileName;
    if (sourceFileName.endsWith(".coffee")) {
        destinationFileNameBase = sourceFileName.substring(0, sourceFileName.length() - 7);
    }
    
    String destinationFileName = String.format("%s.js", destinationFileNameBase);
    RelativePath destinationRelativePath = relativePath.replaceLastName(destinationFileName);
    return new File(destination, destinationRelativePath.getPathString());
}
 
Example 29
public static Transformer<Transformer<File, RelativePath>, File> asFactory() {
    return new Transformer<Transformer<File, RelativePath>, File>() {
        public Transformer<File, RelativePath> transform(File original) {
            return new CoffeeScriptCompileDestinationCalculator(original);
        }
    };
}
 
Example 30
Source Project: Pushjet-Android   Source File: PatternSet.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public Spec<FileTreeElement> getAsIncludeSpec() {
    List<Spec<FileTreeElement>> matchers = Lists.newArrayList();
    for (String include : includes) {
        Spec<RelativePath> patternMatcher = PatternMatcherFactory.getPatternMatcher(true, caseSensitive, include);
        matchers.add(new RelativePathSpec(patternMatcher));
    }

    matchers.addAll(includeSpecs);
    return new OrSpec<FileTreeElement>(matchers);
}