Search in sources :

Example 91 with PathMatcher

use of java.nio.file.PathMatcher in project configuration-as-code-plugin by jenkinsci.

the class ConfigurationAsCode method getBundledCasCURIs.

@Restricted(NoExternalUse.class)
public List<String> getBundledCasCURIs() {
    final String cascFile = "/WEB-INF/" + DEFAULT_JENKINS_YAML_PATH;
    final String cascDirectory = "/WEB-INF/" + DEFAULT_JENKINS_YAML_PATH + ".d/";
    List<String> res = new ArrayList<>();
    final ServletContext servletContext = Jenkins.get().servletContext;
    try {
        URL bundled = servletContext.getResource(cascFile);
        if (bundled != null) {
            res.add(bundled.toString());
        }
    } catch (IOException e) {
        LOGGER.log(Level.WARNING, "Failed to load " + cascFile, e);
    }
    PathMatcher matcher = FileSystems.getDefault().getPathMatcher(YAML_FILES_PATTERN);
    Set<String> resources = servletContext.getResourcePaths(cascDirectory);
    if (resources != null) {
        // sort to execute them in a deterministic order
        for (String cascItem : new TreeSet<>(resources)) {
            try {
                URL bundled = servletContext.getResource(cascItem);
                if (bundled != null && matcher.matches(new File(bundled.getPath()).toPath())) {
                    res.add(bundled.toString());
                }
            // TODO: else do some handling?
            } catch (IOException e) {
                LOGGER.log(Level.WARNING, "Failed to execute " + res, e);
            }
        }
    }
    return res;
}
Also used : PathMatcher(java.nio.file.PathMatcher) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) ServletContext(javax.servlet.ServletContext) IOException(java.io.IOException) File(java.io.File) URL(java.net.URL) Restricted(org.kohsuke.accmod.Restricted)

Example 92 with PathMatcher

use of java.nio.file.PathMatcher in project configuration-as-code-plugin by jenkinsci.

the class ConfigurationAsCode method configs.

/**
 * Recursive search for all {@link #YAML_FILES_PATTERN} in provided base path
 *
 * @param path base path to start (can be file or directory)
 * @return list of all paths matching pattern. Only base file itself if it is a file matching pattern
 */
@Restricted(NoExternalUse.class)
public List<Path> configs(String path) throws ConfiguratorException {
    final Path root = Paths.get(path);
    if (!Files.exists(root)) {
        throw new ConfiguratorException("Invalid configuration: '" + path + "' isn't a valid path.");
    }
    if (Files.isRegularFile(root) && Files.isReadable(root)) {
        return Collections.singletonList(root);
    }
    final PathMatcher matcher = FileSystems.getDefault().getPathMatcher(YAML_FILES_PATTERN);
    try (Stream<Path> stream = Files.find(Paths.get(path), Integer.MAX_VALUE, (next, attrs) -> !attrs.isDirectory() && !isHidden(next) && matcher.matches(next), FileVisitOption.FOLLOW_LINKS)) {
        return stream.sorted().collect(toList());
    } catch (IOException e) {
        throw new IllegalStateException("failed config scan for " + path, e);
    }
}
Also used : Path(java.nio.file.Path) PathMatcher(java.nio.file.PathMatcher) IOException(java.io.IOException) Restricted(org.kohsuke.accmod.Restricted)

Example 93 with PathMatcher

use of java.nio.file.PathMatcher in project copybara by google.

the class BuildifierFormat method transform.

@Override
public TransformationStatus transform(TransformWork work) throws IOException, ValidationException {
    PathMatcher pathMatcher = glob.relativeTo(work.getCheckoutDir());
    ImmutableList.Builder<String> paths = ImmutableList.builder();
    Files.walkFileTree(work.getCheckoutDir(), new SimpleFileVisitor<Path>() {

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (pathMatcher.matches(file)) {
                paths.add(file.toAbsolutePath().toString());
            }
            return FileVisitResult.CONTINUE;
        }
    });
    ImmutableList<String> builtPaths = paths.build();
    if (builtPaths.isEmpty()) {
        return TransformationStatus.noop(glob + " didn't match any build file to format");
    }
    for (List<String> sublist : Iterables.partition(builtPaths, buildifierOptions.batchSize)) {
        run(work.getConsole(), work.getCheckoutDir(), sublist);
    }
    return TransformationStatus.success();
}
Also used : Path(java.nio.file.Path) PathMatcher(java.nio.file.PathMatcher) ImmutableList(com.google.common.collect.ImmutableList) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 94 with PathMatcher

use of java.nio.file.PathMatcher in project copybara by google.

the class GerritOrigin method newReader.

@Override
public Reader<GitRevision> newReader(Glob originFiles, Authoring authoring) {
    return new GitOrigin.ReaderImpl(repoUrl, originFiles, authoring, gitOptions, gitOriginOptions, generalOptions, includeBranchCommitLogs, submoduleStrategy, firstParent, partialFetch, patchTransformation, describeVersion, /*configPath=*/
    null, /*workflowName=*/
    null) {

        @Override
        public ImmutableList<GitRevision> findBaselinesWithoutLabel(GitRevision startRevision, int limit) throws RepoException, ValidationException {
            // Skip the first change as it is the Gerrit review change
            BaselinesWithoutLabelVisitor<GitRevision> visitor = new BaselinesWithoutLabelVisitor<>(originFiles, limit, /*skipFirst=*/
            true);
            visitChanges(startRevision, visitor);
            return visitor.getResult();
        }

        @Override
        public Endpoint getFeedbackEndPoint(Console console) throws ValidationException {
            gerritOptions.validateEndpointChecker(endpointChecker, repoUrl);
            return new GerritEndpoint(gerritOptions.newGerritApiSupplier(repoUrl, endpointChecker), repoUrl, console);
        }

        @Override
        public ChangesResponse<GitRevision> changes(@Nullable GitRevision fromRef, GitRevision toRef) throws RepoException, ValidationException {
            ChangesResponse<GitRevision> result = super.changes(fromRef, toRef);
            Change<GitRevision> change = change(toRef);
            if (!ignoreGerritNoop || change.getChangeFiles() == null || !toRef.associatedLabels().containsKey(GerritChange.GERRIT_COMPLETE_CHANGE_ID_LABEL)) {
                return result;
            }
            PathMatcher pathMatcher = originFiles.relativeTo(Paths.get("/"));
            if (change.getChangeFiles().stream().noneMatch(x -> pathMatcher.matches(Paths.get("/", x)))) {
                logger.atInfo().log("Skipping a Gerrit noop change with ref: %s", toRef.getSha1());
                return ChangesResponse.noChanges(EmptyReason.NO_CHANGES);
            }
            return result;
        }
    };
}
Also used : PathMatcher(java.nio.file.PathMatcher) Console(com.google.copybara.util.console.Console) BaselinesWithoutLabelVisitor(com.google.copybara.BaselinesWithoutLabelVisitor) Nullable(javax.annotation.Nullable)

Example 95 with PathMatcher

use of java.nio.file.PathMatcher in project copybara by google.

the class GitDestinationReader method copyDestinationFiles.

@Override
public void copyDestinationFiles(Glob glob) throws RepoException {
    ImmutableList<TreeElement> treeElements = repository.lsTree(baseline, null, true, true);
    PathMatcher pathMatcher = glob.relativeTo(workDir);
    for (TreeElement file : treeElements) {
        Path path = workDir.resolve(file.getPath());
        if (pathMatcher.matches(path)) {
            try {
                Files.createDirectories(path.getParent());
            } catch (IOException e) {
                throw new RepoException(String.format("Cannot create parent directory for %s", path), e);
            }
        }
    }
    repository.checkout(glob, workDir, baseline);
}
Also used : Path(java.nio.file.Path) PathMatcher(java.nio.file.PathMatcher) IOException(java.io.IOException) RepoException(com.google.copybara.exception.RepoException) TreeElement(com.google.copybara.git.GitRepository.TreeElement)

Aggregations

PathMatcher (java.nio.file.PathMatcher)107 Path (java.nio.file.Path)47 Test (org.junit.Test)30 IOException (java.io.IOException)28 File (java.io.File)18 ArrayList (java.util.ArrayList)13 FileSystem (java.nio.file.FileSystem)11 BasicFileAttributes (java.nio.file.attribute.BasicFileAttributes)11 FileVisitResult (java.nio.file.FileVisitResult)10 Glob.createGlob (com.google.copybara.util.Glob.createGlob)8 Files (java.nio.file.Files)6 Paths (java.nio.file.Paths)6 List (java.util.List)6 FileSystems (java.nio.file.FileSystems)5 HashSet (java.util.HashSet)5 ProjectHandlerRegistry (org.eclipse.che.api.project.server.handlers.ProjectHandlerRegistry)5 ProjectImporterRegistry (org.eclipse.che.api.project.server.importer.ProjectImporterRegistry)5 ProjectTypeRegistry (org.eclipse.che.api.project.server.type.ProjectTypeRegistry)5 DefaultFileWatcherNotificationHandler (org.eclipse.che.api.vfs.impl.file.DefaultFileWatcherNotificationHandler)5 FileTreeWatcher (org.eclipse.che.api.vfs.impl.file.FileTreeWatcher)5