All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.heroku.sdk.deploy.util.PathUtils Maven / Gradle / Ivy

There is a newer version: 3.0.7
Show newest version
package com.heroku.sdk.deploy.util;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class PathUtils {

    public static List normalizeAll(Path basePath, List paths) {
        List normalizedPaths = new ArrayList<>();
        for (Path path : paths) {
            normalize(basePath, path).ifPresent(normalizedPaths::add);
        }

        return normalizedPaths;
    }

    public static Optional normalize(Path basePath, Path path) {
        Path absoluteBasePath = basePath.toAbsolutePath();
        Path normalizedAbsolutePath = absoluteBasePath.resolve(path).normalize();

        if (normalizedAbsolutePath.startsWith(absoluteBasePath)) {
            return Optional.of(absoluteBasePath.relativize(normalizedAbsolutePath));
        }

        return Optional.empty();
    }

    public static boolean isValidPath(Path basePath, Path path) {
        return normalize(basePath, path).isPresent();
    }

    public static List expandDirectories(Path basePath, List paths) throws IOException {
        ArrayList result = new ArrayList<>();
        for (Path path : paths) {
            result.addAll(expandDirectory(basePath, path));
        }

        return result;
    }

    public static List expandDirectory(Path basePath, Path path) throws IOException {
        return Files
                .walk(basePath.resolve(path).normalize())
                .filter(subPath -> !Files.isDirectory(subPath))
                .map(subPath -> normalize(basePath, subPath))
                .filter(Optional::isPresent)
                .map(Optional::get)
                .collect(Collectors.toList());
    }

    public static String separatorsToUnix(Path path) {
        // Path will normalize separators back to Windows when run on Windows. We have to fall back to a String here.
        return path.toString().replace('\\', '/');
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy