View Javadoc
1   /*
2    * Copyright 2001-2005 The Apache Software Foundation.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.codehaus.plexus.archiver.dir;
17  
18  import javax.inject.Named;
19  
20  import java.io.File;
21  import java.io.IOException;
22  import java.io.InputStream;
23  import java.nio.file.Files;
24  import java.nio.file.Path;
25  import java.nio.file.attribute.FileTime;
26  import java.util.ArrayList;
27  import java.util.List;
28  
29  import org.codehaus.plexus.archiver.AbstractArchiver;
30  import org.codehaus.plexus.archiver.ArchiveEntry;
31  import org.codehaus.plexus.archiver.ArchiverException;
32  import org.codehaus.plexus.archiver.ResourceIterator;
33  import org.codehaus.plexus.archiver.SymlinkFailureMode;
34  import org.codehaus.plexus.archiver.exceptions.EmptyArchiveException;
35  import org.codehaus.plexus.archiver.util.ArchiveEntryUtils;
36  import org.codehaus.plexus.archiver.util.DeferredSymlinks;
37  import org.codehaus.plexus.archiver.util.ResourceUtils;
38  import org.codehaus.plexus.components.io.attributes.SymlinkUtils;
39  import org.codehaus.plexus.components.io.functions.SymlinkDestinationSupplier;
40  import org.codehaus.plexus.components.io.resources.PlexusIoResource;
41  
42  /**
43   * A plexus archiver implementation that stores the files to archive in a directory.
44   */
45  @Named("dir")
46  public class DirectoryArchiver extends AbstractArchiver {
47  
48      private final List<Runnable> directoryChmods = new ArrayList<>();
49      private long filesCopied;
50  
51      private SymlinkFailureMode symlinkFailureMode = SymlinkFailureMode.COPY_TARGET;
52  
53      /**
54       * Returns what happens to a symbolic link that the file system refuses to create.
55       *
56       * @return the failure mode, {@link SymlinkFailureMode#COPY_TARGET} by default
57       * @since 4.15.0
58       */
59      public SymlinkFailureMode getSymlinkFailureMode() {
60          return symlinkFailureMode;
61      }
62  
63      /**
64       * Sets what happens to a symbolic link that the file system refuses to create, for example on Windows without
65       * the "Create symbolic links" right or Developer Mode.
66       *
67       * @param symlinkFailureMode the failure mode
68       * @since 4.15.0
69       */
70      public void setSymlinkFailureMode(SymlinkFailureMode symlinkFailureMode) {
71          if (symlinkFailureMode == null) {
72              throw new IllegalArgumentException("symlinkFailureMode must not be null");
73          }
74          this.symlinkFailureMode = symlinkFailureMode;
75      }
76  
77      /**
78       * Creates a symbolic link. Visible for testing, so a test can simulate a file system that refuses links.
79       *
80       * @param link the link to create
81       * @param target the link target
82       * @throws IOException if the link cannot be created
83       * @since 4.15.0
84       */
85      protected void createSymbolicLink(File link, File target) throws IOException {
86          SymlinkUtils.createSymbolicLink(link, target);
87      }
88  
89      /**
90       * Default constructor.
91       */
92      public DirectoryArchiver() {
93          // preserver default behavior
94          setForced(false);
95      }
96  
97      public void resetArchiver() throws IOException {
98          cleanUp();
99      }
100 
101     @Override
102     public void execute() throws ArchiverException, IOException {
103         // Most of this method was copied from org.codehaus.plexus.archiver.tar.TarArchiver
104         // and modified to store files in a directory, not a tar archive.
105         final ResourceIterator iter = getResources();
106         if (!iter.hasNext()) {
107             throw new EmptyArchiveException("archive cannot be empty");
108         }
109 
110         final File destDirectory = getDestFile();
111         if (destDirectory == null) {
112             throw new ArchiverException("You must set the destination directory.");
113         }
114         if (destDirectory.exists() && !destDirectory.isDirectory()) {
115             throw new ArchiverException(destDirectory + " is not a directory.");
116         }
117         if (destDirectory.exists() && !destDirectory.canWrite()) {
118             throw new ArchiverException(destDirectory + " is not writable.");
119         }
120 
121         getLogger().info("Copying files to {}", destDirectory.getAbsolutePath());
122 
123         DeferredSymlinks deferredSymlinks = new DeferredSymlinks(getLogger());
124         try {
125             final Path root = destDirectory.getCanonicalFile().toPath();
126             while (iter.hasNext()) {
127                 final ArchiveEntry f = iter.next();
128                 // Check if we don't add directory file in itself
129                 if (ResourceUtils.isSame(f.getResource(), destDirectory)) {
130                     throw new ArchiverException("The destination directory cannot include itself.");
131                 }
132                 String fileName = f.getName();
133                 final String destDir = destDirectory.getCanonicalPath();
134                 fileName = destDir + File.separator + fileName;
135                 PlexusIoResource resource = f.getResource();
136                 if (resource instanceof SymlinkDestinationSupplier) {
137                     String dest = ((SymlinkDestinationSupplier) resource).getSymlinkDestination();
138                     File target = new File(dest);
139                     File symlink = new File(fileName);
140                     makeParentDirectories(symlink);
141                     try {
142                         createSymbolicLink(symlink, target);
143                     } catch (IOException | UnsupportedOperationException e) {
144                         if (symlinkFailureMode == SymlinkFailureMode.FAIL) {
145                             if (e instanceof IOException) {
146                                 throw (IOException) e;
147                             }
148                             throw new IOException("Cannot create symbolic link " + symlink, e);
149                         }
150                         boolean copy = symlinkFailureMode == SymlinkFailureMode.COPY_TARGET;
151                         getLogger()
152                                 .warn(
153                                         "Cannot create symbolic link {} -> {} ({}). On Windows this needs the"
154                                                 + " 'Create symbolic links' right or Developer Mode; {}.",
155                                         f.getName(),
156                                         dest,
157                                         e.getMessage(),
158                                         copy ? "the link target will be copied instead" : "the entry is skipped");
159                         if (copy) {
160                             deferredSymlinks.add(root, symlink, dest, f.getName());
161                         }
162                     }
163                 } else {
164                     copyFile(f, fileName);
165                 }
166             }
167 
168             deferredSymlinks.resolve();
169 
170             directoryChmods.forEach(Runnable::run);
171             directoryChmods.clear();
172 
173             if (filesCopied > 0) {
174                 getLogger()
175                         .info(
176                                 "{} file{} copied to {}",
177                                 filesCopied,
178                                 filesCopied > 0 ? "s" : "",
179                                 destDirectory.getAbsolutePath());
180             } else {
181                 getLogger().info("All files are uptodate in {}", destDirectory.getAbsolutePath());
182             }
183 
184             filesCopied = 0;
185 
186         } catch (final IOException ioe) {
187             final String message = "Problem copying files : " + ioe.getMessage();
188             throw new ArchiverException(message, ioe);
189         }
190     }
191 
192     /**
193      * Copies the specified file to the specified path, creating any ancestor directory structure as necessary.
194      *
195      * @param entry The file to copy (IOException will be thrown if this does not exist)
196      * @param vPath The fully qualified path to copy the file to.
197      *
198      * @throws ArchiverException If there is a problem creating the directory structure
199      * @throws IOException If there is a problem copying the file
200      */
201     protected void copyFile(final ArchiveEntry entry, final String vPath) throws ArchiverException, IOException {
202         // don't add "" to the archive
203         if (vPath.length() <= 0) {
204             return;
205         }
206 
207         final PlexusIoResource in = entry.getResource();
208         final File outFile = new File(vPath);
209 
210         final long inLastModified = in.getLastModified();
211 
212         if (!isForced()) {
213             final long outLastModified = outFile.lastModified();
214             if (ResourceUtils.isUptodate(inLastModified, outLastModified)) {
215                 return;
216             }
217         }
218 
219         if (!in.isDirectory()) {
220             makeParentDirectories(outFile);
221             try (InputStream input = entry.getInputStream()) {
222                 ResourceUtils.copyFile(input, outFile);
223             }
224             filesCopied++;
225             setFileModes(entry, outFile, inLastModified);
226         } else { // file is a directory
227             if (outFile.exists()) {
228                 if (!outFile.isDirectory()) {
229                     // should we just delete the file and replace it with a directory?
230                     // throw an exception, let the user delete the file manually.
231                     throw new ArchiverException("Expected directory and found file at copy destination of "
232                             + in.getName() + " to " + outFile);
233                 }
234             } else if (!outFile.mkdirs()) {
235                 // Failure, unable to create specified directory for some unknown reason.
236                 throw new ArchiverException("Unable to create directory or parent directory of " + outFile);
237             }
238 
239             directoryChmods.add(() -> {
240                 try {
241                     setFileModes(entry, outFile, inLastModified);
242                 } catch (IOException e) {
243                     throw new ArchiverException("Failed setting file attributes", e);
244                 }
245             });
246         }
247     }
248 
249     private static void makeParentDirectories(File file) {
250         if (!file.getParentFile().exists()) {
251             // create the parent directory...
252             if (!file.getParentFile().mkdirs()) {
253                 // Failure, unable to create specified directory for some unknown reason.
254                 throw new ArchiverException("Unable to create directory or parent directory of " + file);
255             }
256         }
257     }
258 
259     private void setFileModes(ArchiveEntry entry, File outFile, long inLastModified) throws IOException {
260         if (!isIgnorePermissions()) {
261             ArchiveEntryUtils.chmod(outFile, entry.getMode());
262         }
263 
264         if (getLastModifiedTime() == null) {
265             FileTime fromMillis = FileTime.fromMillis(
266                     inLastModified == PlexusIoResource.UNKNOWN_MODIFICATION_DATE
267                             ? System.currentTimeMillis()
268                             : inLastModified);
269             Files.setLastModifiedTime(outFile.toPath(), fromMillis);
270         } else {
271             Files.setLastModifiedTime(outFile.toPath(), getLastModifiedTime());
272         }
273     }
274 
275     @Override
276     protected void cleanUp() throws IOException {
277         super.cleanUp();
278         setIncludeEmptyDirs(false);
279         setIncludeEmptyDirs(true);
280     }
281 
282     @Override
283     protected void close() throws IOException {}
284 
285     @Override
286     protected String getArchiveType() {
287         return "directory";
288     }
289 
290     @Override
291     public boolean isSupportingForced() {
292         return true;
293     }
294 }