Search in sources :

Example 26 with DirectoryWalker

use of com.google.cloud.tools.jib.filesystem.DirectoryWalker in project jib by google.

the class TarExtractor method preserveModificationTimes.

/**
 * Preserve modification timestamps of files and directories in a tar file. If a directory is not
 * an entry in the tar file and reproducible timestamps are enabled then its modification
 * timestamp is set to a constant value. Note that the modification timestamps of symbolic links
 * are not preserved even with reproducible timestamps enabled.
 *
 * @param destination target root for unzipping
 * @param entries list of entries in tar file
 * @param enableReproducibleTimestamps whether or not reproducible timestamps should be used
 * @throws IOException when I/O error occurs
 */
private static void preserveModificationTimes(Path destination, List<TarArchiveEntry> entries, boolean enableReproducibleTimestamps) throws IOException {
    if (enableReproducibleTimestamps) {
        FileTime epochPlusOne = FileTime.fromMillis(1000L);
        new DirectoryWalker(destination).filter(Files::isDirectory).walk(path -> Files.setLastModifiedTime(path, epochPlusOne));
    }
    for (TarArchiveEntry entry : entries) {
        // the target to change
        if (!entry.isSymbolicLink()) {
            Files.setLastModifiedTime(destination.resolve(entry.getName()), FileTime.from(entry.getModTime().toInstant()));
        }
    }
}
Also used : DirectoryWalker(com.google.cloud.tools.jib.filesystem.DirectoryWalker) FileTime(java.nio.file.attribute.FileTime) TarArchiveEntry(org.apache.commons.compress.archivers.tar.TarArchiveEntry)

Example 27 with DirectoryWalker

use of com.google.cloud.tools.jib.filesystem.DirectoryWalker in project jib by google.

the class GradleProjectProperties method getClassFiles.

@Override
public List<Path> getClassFiles() throws IOException {
    // TODO: Consolidate with createJibContainerBuilder
    FileCollection classesOutputDirectories = getMainSourceSet().getOutput().getClassesDirs().filter(File::exists);
    List<Path> classFiles = new ArrayList<>();
    for (File classesOutputDirectory : classesOutputDirectories) {
        classFiles.addAll(new DirectoryWalker(classesOutputDirectory.toPath()).walk());
    }
    return classFiles;
}
Also used : Path(java.nio.file.Path) ArrayList(java.util.ArrayList) DirectoryWalker(com.google.cloud.tools.jib.filesystem.DirectoryWalker) FileCollection(org.gradle.api.file.FileCollection) File(java.io.File)

Example 28 with DirectoryWalker

use of com.google.cloud.tools.jib.filesystem.DirectoryWalker in project jib by google.

the class LayerBuilderTest method testBuild.

@Test
public void testBuild() throws URISyntaxException, IOException {
    Path layerDirectory = Paths.get(Resources.getResource("layer").toURI());
    Path blobA = Paths.get(Resources.getResource("blobA").toURI());
    String extractionPathBase = "extract/here";
    LayerBuilder layerBuilder = new LayerBuilder(new ArrayList<>(Arrays.asList(layerDirectory, blobA)), extractionPathBase, false);
    // Writes the layer tar to a temporary file.
    UnwrittenLayer unwrittenLayer = layerBuilder.build();
    Path temporaryFile = temporaryFolder.newFile().toPath();
    try (OutputStream temporaryFileOutputStream = new BufferedOutputStream(Files.newOutputStream(temporaryFile))) {
        unwrittenLayer.getBlob().writeTo(temporaryFileOutputStream);
    }
    // Reads the file back.
    try (TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(Files.newInputStream(temporaryFile))) {
        // Verifies that all the files have been added to the tarball stream.
        new DirectoryWalker(layerDirectory).filter(path -> !path.equals(layerDirectory)).walk(path -> {
            TarArchiveEntry header = tarArchiveInputStream.getNextTarEntry();
            StringBuilder expectedExtractionPath = new StringBuilder("extract/here");
            for (Path pathComponent : layerDirectory.getParent().relativize(path)) {
                expectedExtractionPath.append("/").append(pathComponent);
            }
            // Check path-equality because there might be an appended backslash in the header
            // filename.
            Assert.assertEquals(Paths.get(expectedExtractionPath.toString()), Paths.get(header.getName()));
            // If is a normal file, checks that the file contents match.
            if (Files.isRegularFile(path)) {
                String expectedFileString = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
                String extractedFileString = CharStreams.toString(new InputStreamReader(tarArchiveInputStream, StandardCharsets.UTF_8));
                Assert.assertEquals(expectedFileString, extractedFileString);
            }
        });
        // Verifies that blobA was added.
        TarArchiveEntry header = tarArchiveInputStream.getNextTarEntry();
        String expectedExtractionPath = "extract/here/blobA";
        Assert.assertEquals(expectedExtractionPath, header.getName());
        String expectedFileString = new String(Files.readAllBytes(blobA), StandardCharsets.UTF_8);
        String extractedFileString = CharStreams.toString(new InputStreamReader(tarArchiveInputStream, StandardCharsets.UTF_8));
        Assert.assertEquals(expectedFileString, extractedFileString);
    }
}
Also used : Path(java.nio.file.Path) CoreMatchers(org.hamcrest.CoreMatchers) Arrays(java.util.Arrays) TarArchiveInputStream(org.apache.commons.compress.archivers.tar.TarArchiveInputStream) URISyntaxException(java.net.URISyntaxException) RunWith(org.junit.runner.RunWith) FileTime(java.nio.file.attribute.FileTime) BufferedOutputStream(java.io.BufferedOutputStream) ArrayList(java.util.ArrayList) TarArchiveEntry(org.apache.commons.compress.archivers.tar.TarArchiveEntry) CharStreams(com.google.common.io.CharStreams) Path(java.nio.file.Path) OutputStream(java.io.OutputStream) Blob(com.google.cloud.tools.jib.blob.Blob) Resources(com.google.common.io.Resources) Files(java.nio.file.Files) StandardOpenOption(java.nio.file.StandardOpenOption) DirectoryWalker(com.google.cloud.tools.jib.filesystem.DirectoryWalker) IOException(java.io.IOException) Test(org.junit.Test) InputStreamReader(java.io.InputStreamReader) StandardCharsets(java.nio.charset.StandardCharsets) Rule(org.junit.Rule) Paths(java.nio.file.Paths) Blobs(com.google.cloud.tools.jib.blob.Blobs) Assert(org.junit.Assert) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) TemporaryFolder(org.junit.rules.TemporaryFolder) InputStreamReader(java.io.InputStreamReader) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) DirectoryWalker(com.google.cloud.tools.jib.filesystem.DirectoryWalker) TarArchiveEntry(org.apache.commons.compress.archivers.tar.TarArchiveEntry) TarArchiveInputStream(org.apache.commons.compress.archivers.tar.TarArchiveInputStream) BufferedOutputStream(java.io.BufferedOutputStream) Test(org.junit.Test)

Example 29 with DirectoryWalker

use of com.google.cloud.tools.jib.filesystem.DirectoryWalker in project jib by google.

the class CacheReader method getLastModifiedTime.

/**
 * @return the last modified time for the file at {@code path}. Recursively finds the most recent
 *     last modified time for all subfiles if the file is a directory.
 */
private static FileTime getLastModifiedTime(Path path) throws IOException {
    if (Files.isDirectory(path)) {
        List<Path> subFiles = new DirectoryWalker(path).walk();
        FileTime maxLastModifiedTime = FileTime.from(Instant.MIN);
        // Finds the max last modified time for the subfiles.
        for (Path subFilePath : subFiles) {
            FileTime subFileLastModifiedTime = Files.getLastModifiedTime(subFilePath);
            if (subFileLastModifiedTime.compareTo(maxLastModifiedTime) > 0) {
                maxLastModifiedTime = subFileLastModifiedTime;
            }
        }
        return maxLastModifiedTime;
    }
    return Files.getLastModifiedTime(path);
}
Also used : Path(java.nio.file.Path) DirectoryWalker(com.google.cloud.tools.jib.filesystem.DirectoryWalker) FileTime(java.nio.file.attribute.FileTime)

Example 30 with DirectoryWalker

use of com.google.cloud.tools.jib.filesystem.DirectoryWalker in project jib by google.

the class LayerBuilder method build.

/**
 * Builds and returns the layer.
 */
public UnwrittenLayer build() throws IOException {
    List<TarArchiveEntry> filesystemEntries = new ArrayList<>();
    for (Path sourceFile : sourceFiles) {
        if (Files.isDirectory(sourceFile)) {
            new DirectoryWalker(sourceFile).filter(path -> !path.equals(sourceFile)).walk(path -> {
                /*
                   * Builds the same file path as in the source file for extraction. The iteration
                   * is necessary because the path needs to be in Unix-style.
                   */
                StringBuilder subExtractionPath = new StringBuilder(extractionPath);
                Path sourceFileRelativePath = sourceFile.getParent().relativize(path);
                for (Path sourceFileRelativePathComponent : sourceFileRelativePath) {
                    subExtractionPath.append('/').append(sourceFileRelativePathComponent);
                }
                filesystemEntries.add(new TarArchiveEntry(path.toFile(), subExtractionPath.toString()));
            });
        } else {
            TarArchiveEntry tarArchiveEntry = new TarArchiveEntry(sourceFile.toFile(), extractionPath + "/" + sourceFile.getFileName());
            filesystemEntries.add(tarArchiveEntry);
        }
    }
    if (enableReproducibleBuilds) {
        makeListReproducible(filesystemEntries);
    }
    // Adds all the files to a tar stream.
    TarStreamBuilder tarStreamBuilder = new TarStreamBuilder();
    for (TarArchiveEntry entry : filesystemEntries) {
        tarStreamBuilder.addEntry(entry);
    }
    return new UnwrittenLayer(tarStreamBuilder.toBlob());
}
Also used : Path(java.nio.file.Path) List(java.util.List) TarArchiveEntry(org.apache.commons.compress.archivers.tar.TarArchiveEntry) Files(java.nio.file.Files) TarStreamBuilder(com.google.cloud.tools.jib.tar.TarStreamBuilder) DirectoryWalker(com.google.cloud.tools.jib.filesystem.DirectoryWalker) IOException(java.io.IOException) Comparator(java.util.Comparator) Path(java.nio.file.Path) Collections(java.util.Collections) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) DirectoryWalker(com.google.cloud.tools.jib.filesystem.DirectoryWalker) TarArchiveEntry(org.apache.commons.compress.archivers.tar.TarArchiveEntry) TarStreamBuilder(com.google.cloud.tools.jib.tar.TarStreamBuilder)

Aggregations

DirectoryWalker (com.google.cloud.tools.jib.filesystem.DirectoryWalker)52 Path (java.nio.file.Path)48 Test (org.junit.Test)23 Result (com.google.cloud.tools.jib.api.MainClassFinder.Result)20 AbsoluteUnixPath (com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath)15 IOException (java.io.IOException)11 FileEntriesLayer (com.google.cloud.tools.jib.api.buildplan.FileEntriesLayer)9 Files (java.nio.file.Files)9 FileTime (java.nio.file.attribute.FileTime)8 List (java.util.List)8 Predicate (java.util.function.Predicate)8 Instant (java.time.Instant)7 Map (java.util.Map)7 ModificationTimeProvider (com.google.cloud.tools.jib.api.buildplan.ModificationTimeProvider)6 RelativeUnixPath (com.google.cloud.tools.jib.api.buildplan.RelativeUnixPath)6 InputStream (java.io.InputStream)6 Paths (java.nio.file.Paths)6 ArrayList (java.util.ArrayList)6 StringJoiner (java.util.StringJoiner)6 FilePermissions (com.google.cloud.tools.jib.api.buildplan.FilePermissions)5