Debian Codegraph @

common/src/main/java/com/android/utils/FileUtils.java

raw
1 /*
2 * Copyright (C) 2015 The Android Open Source Project
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
17 package com.android.utils;
18
19 import static com.google.common.base.Preconditions.checkArgument;
20
21 import com.android.SdkConstants;
22 import com.android.annotations.NonNull;
23 import com.google.common.base.Charsets;
24 import com.google.common.base.Joiner;
25 import com.google.common.base.Optional;
26 import com.google.common.base.Preconditions;
27 import com.google.common.base.Predicates;
28 import com.google.common.collect.FluentIterable;
29 import com.google.common.collect.Iterables;
30 import com.google.common.hash.HashCode;
31 import com.google.common.hash.HashFunction;
32 import com.google.common.hash.Hashing;
33 import com.google.common.io.Files;
34
35 import java.io.EOFException;
36 import java.io.File;
37 import java.io.IOException;
38 import java.io.RandomAccessFile;
39 import java.nio.charset.StandardCharsets;
40 import java.nio.file.StandardCopyOption;
41 import java.util.List;
42 import java.util.regex.Pattern;
43
44 @SuppressWarnings("WeakerAccess") // These are utility methods, meant to be public.
45 public final class FileUtils {
46
47 private FileUtils() {}
48
49 private static final Joiner PATH_JOINER = Joiner.on(File.separatorChar);
50 private static final Joiner COMMA_SEPARATED_JOINER = Joiner.on(", ");
51 private static final Joiner UNIX_NEW_LINE_JOINER = Joiner.on('\n');
52
53 /**
54 * Recursively deletes a path.
55 *
56 * @param path the path delete, may exist or not
57 * @throws IOException failed to delete the file / directory
58 */
59 public static void deletePath(@NonNull final File path) throws IOException {
60 if (!path.exists()) {
61 return;
62 }
63
64 if (path.isDirectory()) {
65 deleteDirectoryContents(path);
66 }
67
68 if (!path.delete()) {
69 throw new IOException(String.format("Could not delete path '%s'.", path));
70 }
71 }
72
73 /**
74 * Recursively deletes a directory or file.
75 *
76 * @param directory the directory, that must exist and be a valid directory
77 * @throws IOException failed to delete the file / directory
78 */
79 public static void deleteDirectoryContents(@NonNull final File directory) throws IOException {
80 Preconditions.checkArgument(directory.isDirectory(), "!directory.isDirectory");
81
82 File[] files = directory.listFiles();
83 Preconditions.checkNotNull(files);
84 for (File file : files) {
85 deletePath(file);
86 }
87 }
88
89 /**
90 * Makes sure {@code path} is an empty directory. If {@code path} is a directory, its contents
91 * are removed recursively, leaving an empty directory. If {@code path} is not a directory,
92 * it is removed and a directory created with the given path. If {@code path} does not
93 * exist, a directory is created with the given path.
94 *
95 * @param path the path, that may exist or not and may be a file or directory
96 * @throws IOException failed to delete directory contents, failed to delete {@code path} or
97 * failed to create a directory at {@code path}
98 */
99 public static void cleanOutputDir(@NonNull File path) throws IOException {
100 if (!path.isDirectory()) {
101 if (path.exists()) {
102 deletePath(path);
103 }
104
105 if (!path.mkdirs()) {
106 throw new IOException(String.format("Could not create empty folder %s", path));
107 }
108
109 return;
110 }
111
112 deleteDirectoryContents(path);
113 }
114
115 /**
116 * Copies a regular file from one path to another, preserving file attributes. If the
117 * destination file exists, it gets overwritten.
118 */
119 public static void copyFile(@NonNull File from, @NonNull File to) throws IOException {
120 java.nio.file.Files.copy(
121 from.toPath(),
122 to.toPath(),
123 StandardCopyOption.COPY_ATTRIBUTES,
124 StandardCopyOption.REPLACE_EXISTING);
125 }
126
127 /**
128 * Copies a directory from one path to another. If the destination directory exists, the file
129 * contents are merged and files from the source directory overwrite files in the destination.
130 */
131 public static void copyDirectory(@NonNull File from, @NonNull File to) throws IOException {
132 Preconditions.checkArgument(from.isDirectory(), "Source path is not a directory.");
133 Preconditions.checkArgument(
134 !to.exists() || to.isDirectory(),
135 "Destination path exists and is not a directory.");
136
137 mkdirs(to);
138 File[] children = from.listFiles();
139 if (children != null) {
140 for (File child : children) {
141 if (child.isFile()) {
142 copyFileToDirectory(child, to);
143 } else if (child.isDirectory()) {
144 copyDirectoryToDirectory(child, to);
145 } else {
146 throw new IllegalArgumentException(
147 "Don't know how to copy file " + child.getAbsolutePath());
148 }
149 }
150 }
151 }
152
153 /**
154 * Makes a copy of the given file in the specified directory, preserving the name and file
155 * attributes.
156 */
157 public static void copyFileToDirectory(@NonNull final File from, @NonNull final File to)
158 throws IOException {
159 copyFile(from, new File(to, from.getName()));
160 }
161
162 /**
163 * Makes a copy of the given directory in the specified destination directory.
164 *
165 * @see #copyDirectory(File, File)
166 */
167 public static void copyDirectoryToDirectory(@NonNull final File from, @NonNull final File to)
168 throws IOException {
169 copyDirectory(from, new File(to, from.getName()));
170 }
171
172 /**
173 * Makes a copy of the directory's content, in the specified location, while maintaining the
174 * directory structure. So the entire directory tree from the source will be copied.
175 *
176 * @param from directory from which the content is copied
177 * @param to destination directory, will be created if does not exist
178 */
179 public static void copyDirectoryContentToDirectory(
180 @NonNull final File from, @NonNull final File to) throws IOException {
181 Preconditions.checkArgument(from.isDirectory(), "Source path is not a directory.");
182
183 File[] children = from.listFiles();
184 if (children != null) {
185 for (File f : children) {
186 if (f.isDirectory()) {
187 File destination = new File(to, relativePath(f, from));
188 Files.createParentDirs(destination);
189 mkdirs(destination);
190
191 copyDirectoryContentToDirectory(f, destination);
192 } else if (f.isFile()) {
193 File destination = new File(to, relativePath(f.getParentFile(), from));
194 Files.createParentDirs(destination);
195 mkdirs(destination);
196
197 copyFileToDirectory(f, destination);
198 }
199 }
200 }
201 }
202
203 /**
204 * Creates a directory, if it doesn't exist.
205 *
206 * @param folder the directory to create, may already exist
207 * @return {@code folder}
208 */
209 @NonNull
210 public static File mkdirs(@NonNull File folder) {
211 // attempt to create first.
212 // if failure only throw if folder does not exist.
213 // This makes this method able to create the same folder(s) from different thread
214 if (!folder.mkdirs() && !folder.exists()) {
215 throw new RuntimeException("Cannot create directory " + folder);
216 }
217
218 return folder;
219 }
220
221 /**
222 * Deletes a file.
223 *
224 * @param file the file to delete; the file must exist
225 * @throws IOException failed to delete the file
226 */
227 public static void delete(@NonNull File file) throws IOException {
228 boolean result = file.delete();
229 if (!result) {
230 throw new IOException("Failed to delete " + file.getAbsolutePath());
231 }
232 }
233
234 public static void deleteIfExists(@NonNull File file) throws IOException {
235 boolean result = file.delete();
236 if (!result && file.exists()) {
237 throw new IOException("Failed to delete " + file.getAbsolutePath());
238 }
239 }
240
241 public static void renameTo(@NonNull File file, @NonNull File to) throws IOException {
242 boolean result = file.renameTo(to);
243 if (!result) {
244 throw new IOException("Failed to rename " + file.getAbsolutePath() + " to " + to);
245 }
246 }
247
248 /**
249 * Joins a list of path segments to a given File object.
250 *
251 * @param dir the file object.
252 * @param paths the segments.
253 * @return a new File object.
254 */
255 @NonNull
256 public static File join(@NonNull File dir, @NonNull String... paths) {
257 if (paths.length == 0) {
258 return dir;
259 }
260
261 return new File(dir, PATH_JOINER.join(paths));
262 }
263
264 /**
265 * Joins a list of path segments to a given File object.
266 *
267 * @param dir the file object.
268 * @param paths the segments.
269 * @return a new File object.
270 */
271 @NonNull
272 public static File join(@NonNull File dir, @NonNull Iterable<String> paths) {
273 return new File(dir, PATH_JOINER.join(paths));
274 }
275
276 /**
277 * Joins a set of segment into a string, separating each segments with a host-specific
278 * path separator.
279 *
280 * @param paths the segments.
281 * @return a string with the segments.
282 */
283 @NonNull
284 public static String join(@NonNull String... paths) {
285 return PATH_JOINER.join(paths);
286 }
287
288 /**
289 * Joins a set of segment into a string, separating each segments with a host-specific
290 * path separator.
291 *
292 * @param paths the segments.
293 * @return a string with the segments.
294 */
295 @NonNull
296 public static String join(@NonNull Iterable<String> paths) {
297 return PATH_JOINER.join(paths);
298 }
299
300 /**
301 * Loads a text file forcing the line separator to be of Unix style '\n' rather than being
302 * Windows style '\r\n'.
303 */
304 @NonNull
305 public static String loadFileWithUnixLineSeparators(@NonNull File file) throws IOException {
306 return UNIX_NEW_LINE_JOINER.join(Files.readLines(file, Charsets.UTF_8));
307 }
308
309 /**
310 * Computes the relative of a file or directory with respect to a directory.
311 *
312 * @param file the file or directory, which must exist in the filesystem
313 * @param dir the directory to compute the path relative to
314 * @return the relative path from {@code dir} to {@code file}; if {@code file} is a directory
315 * the path comes appended with the file separator (see documentation on {@code relativize}
316 * on java's {@code URI} class)
317 */
318 @NonNull
319 public static String relativePath(@NonNull File file, @NonNull File dir) {
320 checkArgument(file.isFile() || file.isDirectory(), "%s is not a file nor a directory.",
321 file.getPath());
322 checkArgument(dir.isDirectory(), "%s is not a directory.", dir.getPath());
323 return relativePossiblyNonExistingPath(file, dir);
324 }
325
326 /**
327 * Computes the relative of a file or directory with respect to a directory.
328 * For example, if the file's absolute path is {@code /a/b/c} and the directory
329 * is {@code /a}, this method returns {@code b/c}.
330 *
331 * @param file the path that may not correspond to any existing path in the filesystem
332 * @param dir the directory to compute the path relative to
333 * @return the relative path from {@code dir} to {@code file}; if {@code file} is a directory
334 * the path comes appended with the file separator (see documentation on {@code relativize}
335 * on java's {@code URI} class)
336 */
337 @NonNull
338 public static String relativePossiblyNonExistingPath(@NonNull File file, @NonNull File dir) {
339 String path = dir.toURI().relativize(file.toURI()).getPath();
340 return toSystemDependentPath(path);
341 }
342
343 /**
344 * Converts a /-based path into a path using the system dependent separator.
345 * @param path the system independent path to convert
346 * @return the system dependent path
347 */
348 @NonNull
349 public static String toSystemDependentPath(@NonNull String path) {
350 if (File.separatorChar != '/') {
351 path = path.replace('/', File.separatorChar);
352 }
353 return path;
354 }
355
356 /**
357 * Converts a system-dependent path into a /-based path.
358 * @param path the system dependent path
359 * @return the system independent path
360 */
361 @NonNull
362 public static String toSystemIndependentPath(@NonNull String path) {
363 if (File.separatorChar != '/') {
364 path = path.replace(File.separatorChar, '/');
365 }
366 return path;
367 }
368
369 @NonNull
370 public static String sha1(@NonNull File file) throws IOException {
371 return Hashing.sha1().hashBytes(Files.toByteArray(file)).toString();
372 }
373
374 @NonNull
375 public static FluentIterable<File> getAllFiles(@NonNull File dir) {
376 return Files.fileTreeTraverser().preOrderTraversal(dir).filter(Files.isFile());
377 }
378
379 @NonNull
380 public static String getNamesAsCommaSeparatedList(@NonNull Iterable<File> files) {
381 return COMMA_SEPARATED_JOINER.join(Iterables.transform(files, File::getName));
382 }
383
384 /**
385 * Chooses a directory name, based on a JAR file name, considering exploded-aar and classes.jar.
386 */
387 @NonNull
388 public static String getDirectoryNameForJar(@NonNull File inputFile) {
389 // add a hash of the original file path.
390 HashFunction hashFunction = Hashing.sha1();
391 HashCode hashCode = hashFunction.hashString(inputFile.getAbsolutePath(), Charsets.UTF_16LE);
392
393 String name = Files.getNameWithoutExtension(inputFile.getName());
394 if (name.equals("classes") && inputFile.getAbsolutePath().contains("exploded-aar")) {
395 // This naming scheme is coming from DependencyManager#computeArtifactPath.
396 File versionDir = inputFile.getParentFile().getParentFile();
397 File artifactDir = versionDir.getParentFile();
398 File groupDir = artifactDir.getParentFile();
399
400 name = Joiner.on('-').join(
401 groupDir.getName(), artifactDir.getName(), versionDir.getName());
402 }
403 name = name + "_" + hashCode.toString();
404 return name;
405 }
406
407 public static void createFile(@NonNull File file, @NonNull String content) throws IOException {
408 checkArgument(!file.exists(), "%s exists already.", file);
409
410 Files.createParentDirs(file);
411 Files.write(content, file, Charsets.UTF_8);
412 }
413
414 /**
415 * Find a list of files in a directory, using a specified path pattern.
416 */
417 public static List<File> find(@NonNull File base, @NonNull final Pattern pattern) {
418 checkArgument(base.isDirectory(), "'%s' must be a directory.", base.getAbsolutePath());
419 return Files.fileTreeTraverser()
420 .preOrderTraversal(base)
421 .filter(Predicates.compose(Predicates.contains(pattern), File::getPath))
422 .toList();
423 }
424
425 /**
426 * Find a file with the specified name in a given directory .
427 */
428 public static Optional<File> find(@NonNull File base, @NonNull final String name) {
429 checkArgument(base.isDirectory(), "'%s' must be a directory.", base.getAbsolutePath());
430 return Files.fileTreeTraverser()
431 .preOrderTraversal(base)
432 .filter(Predicates.compose(Predicates.equalTo(name), File::getName))
433 .last();
434 }
435
436 /**
437 * Reads a portion of a file to memory.
438 *
439 * @param file the file to read data from
440 * @param start the offset in the file to start reading
441 * @param length the number of bytes to read
442 * @return the bytes read
443 * @throws Exception failed to read the file
444 */
445 @NonNull
446 public static byte[] readSegment(@NonNull File file, long start, int length) throws Exception {
447 Preconditions.checkArgument(start >= 0, "start < 0");
448 Preconditions.checkArgument(length >= 0, "length < 0");
449
450 byte data[];
451 try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
452 raf.seek(start);
453
454 data = new byte[length];
455 int tot = 0;
456 while (tot < length) {
457 int r = raf.read(data, tot, length - tot);
458 if (r < 0) {
459 throw new EOFException();
460 }
461
462 tot += r;
463 }
464 }
465
466 return data;
467 }
468
469 /**
470 * Join multiple file paths as String.
471 */
472 @NonNull
473 public static String joinFilePaths(@NonNull Iterable<File> files) {
474 return Joiner.on(File.pathSeparatorChar)
475 .join(Iterables.transform(files, File::getAbsolutePath));
476 }
477
478 /**
479 * Returns a valid file name modified from the requested file name. This method guarantees that
480 * there is a one-to-one mapping between the requested file names and the returned file names
481 * (i.e., if the input file names are different, the returned file names will also be
482 * different). The file name consists of a base name and an extension (which is an empty string
483 * if there is no extension). A directory where the file is located is also provided to check
484 * the length of the file path and keep both the file name and file path's lengths within limit.
485 *
486 * @param baseName the base name of the requested file name
487 * @param extension the extension of the requested file name (empty string if not available)
488 * @param directory the directory where the file will be located
489 * @throws IOException if the requested file name or file path is too long
490 */
491 @NonNull
492 public static String getValidFileName(
493 @NonNull String baseName, @NonNull String extension, @NonNull File directory)
494 throws IOException {
495 String fileName = (extension.isEmpty() ? baseName : (baseName + "." + extension));
496
497 String validBaseName = baseName.replaceAll("[^a-zA-Z0-9]", "_");
498 String validExtension = extension.replaceAll("[^a-zA-Z0-9]", "_");
499 String validExtensionWithDot = (validExtension.isEmpty() ? "" : ("." + validExtension));
500 String validFileName = validBaseName + validExtensionWithDot;
501
502 // Add a hash code to the returned file name to avoid accidental collision (when two
503 // different requested file names produce the same returned file name)
504 String fileHash = Hashing.sha1().hashString(fileName, StandardCharsets.UTF_8).toString();
505 if (!validFileName.equals(fileName)) {
506 validFileName = validBaseName + "_" + fileHash + validExtensionWithDot;
507 }
508
509 // If the file name/file path is too long, retain the hash code only and also keep the
510 // extension
511 if (isFilePathTooLong(validFileName, directory)) {
512 validFileName = fileHash + validExtensionWithDot;
513
514 // If the file name/file path is still too long, throw a RuntimeException
515 if (isFilePathTooLong(validFileName, directory)) {
516 throw new IOException("File name or file path is too long: "
517 + new File(directory, validFileName).getAbsolutePath());
518 }
519 }
520
521 return validFileName;
522 }
523
524 /**
525 * Returns <code>true</code> if the file name is too long.
526 *
527 * @param fileName the file name
528 */
529 public static boolean isFileNameTooLong(@NonNull String fileName) {
530 return fileName.length() > 255;
531 }
532
533 /**
534 * Returns <code>true</code> if the file name or file path is too long.
535 *
536 * @param fileName the file name
537 * @param directory the directory where the file will be located
538 */
539 public static boolean isFilePathTooLong(@NonNull String fileName, @NonNull File directory) {
540 if (isFileNameTooLong(fileName)) {
541 return true;
542 }
543
544 int filePathLength = new File(directory, fileName).getAbsolutePath().length();
545 if (SdkConstants.currentPlatform() == SdkConstants.PLATFORM_WINDOWS) {
546 return filePathLength > 260;
547 } else {
548 return filePathLength > 4096;
549 }
550 }
551 }