|
| 1 | +package io.miret.etienne.gradle.sass; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.io.InputStream; |
| 5 | +import java.nio.file.Files; |
| 6 | +import java.nio.file.Path; |
| 7 | +import java.nio.file.Paths; |
| 8 | +import java.util.Collection; |
| 9 | +import java.util.Objects; |
| 10 | + |
| 11 | +public class Utils { |
| 12 | + |
| 13 | + /** |
| 14 | + * Copies classpath resources to a directory. |
| 15 | + * <p> |
| 16 | + * Each resource will be searched in the classpath from {@code base} and |
| 17 | + * copied to {@code destination}. That is, for {@code base = "/io/miret/"}, |
| 18 | + * {@code destination = "/var/tmp"} and a {@code foo/bar.txt} resource, |
| 19 | + * the {@code /io/miret/foo/bar.txt} classpath resource will be copied |
| 20 | + * to {@code /var/tmp/foo/bar.txt}. |
| 21 | + * <p> |
| 22 | + * Intermediate directories will be created as needed. |
| 23 | + * |
| 24 | + * @param base base name for the resources, must include the starting '/'. |
| 25 | + * @param resources the set of file resources to copy, relative to base. |
| 26 | + * @param destination a path that points to an existing directory. |
| 27 | + */ |
| 28 | + public static void copy( |
| 29 | + String base, |
| 30 | + Collection<String> resources, |
| 31 | + Path destination |
| 32 | + ) throws IOException { |
| 33 | + if (!base.startsWith("/")) { |
| 34 | + throw new IllegalArgumentException("Base resource name must start with a '/'"); |
| 35 | + } |
| 36 | + for (String resourceStr : resources) { |
| 37 | + Path resourcePath = Paths.get(resourceStr); |
| 38 | + if (resourcePath.isAbsolute()) { |
| 39 | + throw new IllegalArgumentException("Absolute path provided: " + resourceStr); |
| 40 | + } |
| 41 | + Path target = destination.resolve(resourcePath); |
| 42 | + Files.createDirectories(target.getParent()); |
| 43 | + try (InputStream input = Utils.class.getResourceAsStream(base + "/" + resourceStr)) { |
| 44 | + Objects.requireNonNull(input, "No such resource: " + resourceStr); |
| 45 | + Files.copy(input, target); |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | +} |
0 commit comments